zend-framework,zend-framework2 , How to use helper classes in zf2?

How to use helper classes in zf2?


Tag: zend-framework,zend-framework2

I'm using Zend Framework 2 for web apps. In a controller Action I would create some PDF Documents. I'd like to use a helper class for developing the methods creating the PDF. What is the best place to store the class? inside the controller directory? Or does the framework provide some better place in its architecture for doing this? Or even better methods or concepts?

Thank you!


You can create a directory called Plugin under the Controller directory. A good name for your plugin will have the 'Plugin' termination.

If your plugin will only have one method you can put your logic in the __invoke method:

public function __invoke($data)
    // [ process $data ]

If not and you need more methods, then your invoke method will have to return your plugin instance:

public function __invoke()
    return $this;

public function otherMethod($data)
    // [ process $data ]

Then you have to register your plugin in the module.config.php creating a new key called 'controller_plugins':

'controller_plugins' => array(
    'invokables' => array(
        'myPdf' => 'MyModule\Controller\Plugin\MyPdfPlugin',

You can use there the same methods that are used for every kind of service in the module.config.php: invokables, factories, abstract_factories, aliases, ...

And now you are ready to use it in your controller:


In the case you have more than one methods:



CORS POST request in ZF2 becomes OPTIONS request instead

Is there anyway in Zend Framework 2 to allow CORS on my API? I have already allowed all origins header("Access-Control-Allow-Origin: *"); Every time I send a POST request with headers the server responds with 405. On my access log I see the the request is actually OPTIONS...

ZF2 DB Adapter - Column not found: 1054 Unknown column

I'm using ZF2 DB Adapter and get following error on my query: Column not found: 1054 Unknown column '"product"' But "product" is no column, it's a value, so how come? This is how I build the query: $select = $this->getGateway()->getSql()->select(); $select->join('keywordlink', 'keywordlink_ref_type = "product" AND keywordlink_ref_id = product_id', ['keyword_count' =>...

How to make Zf2 Apigilty accept client request with no Accept set in header

Recently I have upgraded my rest server to Zf2 Apigility, which the content negotiation settings are as follows, 'zf-content-negotiation' => array( 'controllers' => array( 'CloudSchoolBusFileApi\\V1\\Rest\\FileReceiver\\Controller' => 'Json', ), 'accept_whitelist' => array( 'CloudSchoolBusFileApi\\V1\\Rest\\FileReceiver\\Controller' => array( 0 => 'application/vnd.cloud-school-bus-file-api.v1+json', 1 => 'application/json', ), ), 'content_type_whitelist' => array(...

Bootstrap of Zend Module is not loading

I am new in working with zend so I am facing this problem from the past two days. I have searched a lot but still can not find any solution. Possible duplicate of Zend Module Bootstrap does not load but it still can not solve my problem. In my User...

Socialengine addon Advanced Events Plugin v4.8.8p2 throwing errror on create

I've got a site set up with the base Socialengine setup going. I've installed most of the SocialEngineAddon suite of plugins, and for some reason, the Advanced Events plugin throws this error when I try and create one ie: example.com/appeals/create I've tried renaming back to the default site-event, but the...

ZF 2 - Fatal Error: Call to a member function getPosts() on null

I am creating a website using Zend Framework 2, and I'm using as an example the exercise from the official course of Zend Technology, Zend Framework 2: Fundamentals. I have a table called posts and I want to show the table content in my home page, ordered by id. These...

ZF2 Bulk insert using INSERT INTO … SELECT from a table to same table

I am trying to do a bulk copy of some records from a table into the same table with one field changed. But I am not able to find the correct method in ZF2 for it. My existing table looks like this : CoID -- CatCode -- CategoryName PP --...

Composer + Rocketeer + ZF2- Cannot install Rocketeer due to requirements conflict

Can somebody can tell me how to fix this? Rocketeer installs just fine in empty dir, but not along with my existing project, don't know w why. What is requiering that installation? - Installation request for symfony/console == -> satisfiable by symfony/console[v2.6.6]. composer.json { "name": "zendframework/skeleton-application", "description": "Skeleton Application...

zend2 forms and action attribute

in my EditController I have indexAction : public function indexAction() { $delete = new DeleteForm(); $view = new ViewModel(array('delete' => $delete )); return $view; } and the view <?php $formDelete = $this->delete; $formDelete->prepare(); $formDelete->setAttribute('action', $this->url(NULL, array('controller'=>'Register', 'action' => 'process'))); ?> <?php echo $this->form()->openTag($formDelete);?> <div class="form-group"> <?=$this->formLabel($formDelete->get('reason')); ?>...

Pass array on url using zend framework 2 routes

I have a web app that lets user make multiple searches and show the results of that searches all on the same page. Here's a basic structure: Search 1 - Attribute 1 = X - Attribute 3 = Y Search 2 -Attribute 2 = Z All these results are loaded...

BETWEEN with range including '1' also returns '10'

I'm getting some unexpected behaviour using a BETWEEN predicate in ZF2. Consider the following code: $ranges = array( array( 'min' => 2, 'max' => 4 ), array( 'min' => 7, 'max' => 9 ) ); $predicates = array(); foreach($ranges as $range){ // create a new 'Between' predicate and add it...

Zend Framework 2 routing error: resolves to invalid controller class or alias

I'm trying to learn Zend Framework 2 and I have their skeleton application up and running. In order to access it I visit http://localhost:8080/. When visiting that link it displays their generic Zend page. What I want to be able to do is visit http://localhost:8080/application/test and have it bring me...

Zend Framwork 2 - Tablegateway - Updating only one column of a row in DB

I have a table called users. It has the following columns: id name username email User can not edit any data from this table except the username column. The question is that when user wants to edit his username, what would the query be in ZF2 Tablegateway? In my controller...

zend2 adding another controller to application

I'm working on a ZendFramework2.4-project. I just got started an filled the IndexController of a standard skeleton application with some code and thought of another controller in the same application. No new modul, just a second Controller to keep code seperated. Of course I read the documentation at Zend2: Routing...

Zend Framework 2 - Sending form using Zend\Mail

So i'm making a contact page. Of course it will have a form, which needs to be sent. I made the class to send email: <?php namespace Site\Mail; use Zend\Mail\Message; use Zend\Mail\Transport\Sendmail; class SendEMail { public function SendEMail($to, $from, $subject, $body) { $message = new Message(); $message->addTo($to) ->addFrom($from) ->setSubject($subject) ->setBody($body);...

how retrieve array returned by config in zend framework 2

How I can get the array returned by config/autoload in zend framework 2? #config/autoload/myconfig.local.php return array('foo' => 'bar'); I noticed if the file have not "return array()" an exception will throw...

Uninstalling php 5.3 in ubuntu 14.04

I have installed php 5.3 manually by executing commands like make & make install. But I need to upgrade it to v5.5 therefore I deleted all the directories related to php5 using sudo command. But when I run php -v Still I am getting PHP 5.3.29 (cli) (built: Jun 8...

Best way to configure a Table in Module.php - Zend 2

I am setting up my tables in module.php using the default example in zend2 tutorial, but in my project I have so much tables, so my module.php is too large. Here is my default config EXAMPLE 1: 'UsersTableGateway' => function ($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new...

Zend 2 Navigation add before label name

I have the following navigation array, but now i want a before my label. How and where can i add this? The output must be: <ul class="sidebar-nav"> <li class="active"> <a href="/admin/users"><i class="gi gi-user sidebar-nav-icon"></i> Users</a> </li> </ul> Array module config: 'navigation' => array( 'default' => array( array( 'label' => 'Users',...

Zend Skeleton Application album tutorial 404

As far as I can see I've followed the Zend skeleton application tutorial to the letter (I actually went through it twice with the same result) but when I try to access zf2-tutorial.localhost/album I get the following error: A 404 error occurred Page not found. The requested URL could not...

Expecting Zend to fail to find an action, but instead it finds it and tries to render a view

With an action such as public function checkImagesAction() I can request that route in my browser with /checkImages and the page is displayed using the check-images.phtml view as I'd expect. However, requesting /checkImageS or another crazy spelling causes Zend to throw a RuntimeException because it is unable to render template...

Wrong datatype for referenced entity on Doctrine ObjectSelect

I have a form which uses Doctrine's ObjectSelect to make a dropdown $this->add(array( 'name' => 'category', 'type' => 'DoctrineModule\Form\Element\ObjectSelect', 'options' => array( 'label' => 'Category', 'object_manager' => $em, 'target_class' => 'Blog\Entity\Category', 'property' => 'name' ), 'attributes' => array( 'required' => true ) )); the issue I have, is that this...

zend framework 2 nested module structrue in one main module

I am trying to create a app using zend framework 2. Have used structure as follow. Getting error class not found. Trying to created nested sub module login inside a main module called album. I have following structure: Album - src - Album - Controller - AlbumController.php - Form -...

zf2 call a method from a Model in another Model

I have a couple of modules in ZF2 project. Each module has different model classes performing different required functions. Now I have method in a model class of first module which I want to call in the model class of second module. Is it possible to do so? if yes,...

Zend 2 Translation global

The following code works fine in a controller,how global? XXXController.php $lang = 'nl'; $loc = $this->getServiceLocator(); $translator = $this->get('translator'); $translator->addTranslationFile("phparray",'./module/admin/language/lang.array.'.$lang.'.php'); $loc->get('ViewHelperManager')->get('translate')->setTranslator($translator); View.phtml echo $this->translate('homepage'); The awnser: module.config.php 'translator' => array( 'locale' => 'it_IT', 'translation_files' => array( array( 'type' =>...

Get Google Plus Images Using Zend Framework 1 Gdata

I've been searching for an answer for this for quite some time now. I've looked into the other questions here but couldn't find a relevant one to my situation. Googling the question wasn't helpful as well. Basically, I am using ZF1's Gdata class to access the photos api. This was...

Validator EmailAddress can validate an array of email

I have a select2 field (tags) wich need to be validated with EmailAddress validator from Zend framework 2. the post from select2 field is like this : '[email protected], [email protected]' From here, my form has an input filter wich looks like this : public function getInputFilterSpecification() { return array( 'name' =>...

ZF2 & Apigility - Correct way to setup GET and POST RPC services

What is the correct way to setup GET and POST services in ApiGility? Currently, if I am setting up a GET service, I will include the variable I require in my route: /api/verify/merchant[/:merchant_code] And if I wish to setup a POST service, my route becomes: /api/verify/merchant And I add a...

Zend Framework 2 - Accessing 2 different tables from same controller file

I have succesfully completed the the album table tutorial in Zend Framework 2 manual. I have implemented using tablegateway. I can see that he used only one table named "album" and hence he implemented according to that one table. Lets say I have another table called "artist" that holds the...

Zend Framework 2: Create Search Widget for Layout

I have a small private Project to learn ZF2. I have integrated Zend Lucene as a Search Function. This works well, but I now want to integrate a Search Field in my Layout, so that it is available on all pages. I am really not sure how to achieve this....

How can I make PHPUnit ignore a file pattern?

I'm doing Code Coverage reports for a project and there's a ton of files that are included or required while tests are running that are not actually required to be tested or added to coverage reports (I'm using Zend Framework 2; config + Module files are the culprit here). Is...

D2l first time signature is matched but next time, it displays authenticated signature?

I am trying to integrate the Desire2Learn (D2L) sandbox with my app. I created an API for a D2L request. The first time, the signature is matched, but after logging out of D2L and trying once again, it then displays an authenticated signature. But when I quit and restart my...

Zend Framework 2 - Showing the content of a database

I'm making some kind of market site with Zend Framework 2. The home got a slider showing all the products (realized with CSS3 keyframes) and some text. Both the sliding pictures and the text are read from a MySQL database. But as result, i get no output but also no...

Create a subquery using ALL and ANY statements

I'm trying to make this query SELECT * FROM district WHERE id = ANY (SELECT districtId FROM address WHERE id = ANY (SELECT addressId FROM schedule WHERE workshopId = '1')) My real problem is inserting the ANY statement. Does anyone know how to apply ANY or ALL to the query...

integrate login to my sites with OpenId or OAuth

i have a few site developed with zend framework 1 and zend framework 2,i wanna users register in main site and in other sites i want to have a login button ,if user click on login: 1- if user logged in in main site ago , user login without enter...

zend framework 2 controller's action arguments

I had this public function in ApplicationController public function indexAction($bar) { echo $bar; return new ViewModel(); } How I can pass this argument? I've tried http://localhost/zf2/public/application/index/index?bar=foo but this not works...

Failed installation of zend-escaper with Composer

I'm trying to install zend-escaper but I'm getting this error: This is strange as my PHP version (from phpinfo()) is 5.5.19, the message claims it is 5.3.5(!) which should satisfy the requirement anyway. My ZF version is 1.12.13 I'm using PHP Storm Can anyone help please? Thanks Tomasz...

How to send field name for required true validation in zend

Here is what my form field, $this->addElement( 'text', 'title', array( 'placeholder' => 'Title', 'class' => 'form-control', 'required' => true, 'filters' => array( 'StringTrim' ), 'autocomplete' => 'off', ) ); I Simply need the error string like: Title is required and can't be empty....

Zend_Pdf how to reduce the loading time of images?

I built an pdf document which is based on database records of 2 related tables. The mastertable contains shopdata with logos. In the records I of course don't save the image itself, but only the pathinfo. The detailtable just contains meeting dates, no problems with this one. If I start...

PHPUnit: Testing RestFul API with die response

I am trying to PHPUnit test an action in my ZF2 project. The APIs return a JSON string using die($jsonObject). This causes the PHPUnit test to stop processing and just die a JSON response. public function testStartupAction() { $this->dispatch('/api/v3/startup', "POST", array()); $this->assertJson('{"status":false,"message":"Please enter the UID","data":null}'); } assetJson method is never...

PHP/Zend Framework 2 - Unable to display table field values within dynamically generated table

Problem I am trying to display field values into a table using Zend Framework 2 and PHP/MySQL. Given the following table which is dynamically generated, I am trying to get the values shown below. Unfortunately, I only get empty values for the cell locations. Question How can I solve this...

Transfert a Zend Project to Symfony

I have a project made using Zend. My boss asked me to change the technology to Symfony 2.7. Is there a way to transfer the project ? Or to take some files into Symfony ? Or should I begin all the project from scratch using Symfony ? Thanks !...

Zend And YouTube Not Deleting Videos

Until yesterday I could delete YouTube videos using Zend framework. I was using this code: $httpClient = Zend_Gdata_ClientLogin::getHttpClient( $username, $password, 'youtube', null, 'MySite', null, null, 'https://www.google.com/accounts/ClientLogin'); $yt = new Zend_Gdata_YouTube($httpClient, '', '', $myDevKey); $vid = $yt->getVideoEntry($myVidID, null, true); $yt->delete($vid); Now I am getting this error: Expected response code 200, got...

The class 'Doctrine\ORM\EntityManager' was not found in the chain configured namespaces XXX

I have read the the other questions concerning this issue but have not come across a solution as of yet. I get the following error message: The class 'Doctrine\ORM\EntityManager' was not found in the chain configured >namespaces ZfcUser\Entity, Common\Entity, Employment\Entity, Intern\Entity, >Team\Entity, PurchaseRequest\Entity. I have a HolidayEntity, HolidayController, HolidayService. Adding...

Zend paginator with AJAX

I have multiple albums listed on a page, next to each album are listed reviews about the album. Essentially this means there are many reviews about many albums on a single page. What would be the best approach to paginate each review section for each album? For example so each...

PHP Frameworks and Project Repositories

I'm starting a new in PHP and for the first time I'm going to use a framework as the basis of the project. I've decided to use Zend Framework 2 for it. I'm going to be version controlling the project via Github. Is it normal to include all the framework...