populating zend form's fieldsets with objects within object - php

I am using PHP Zendframework to build forms. I have service object that i need want to use to populate my ServiceEditForm.php. But in this service form i have Object of "Billing", "Subscription" and array of object "Commands". Below is my implementation of Service class.
class Service{
public $service_id;
public $ServiceName;
public $TelecomOperator;
public $SubMethod;
public $Provider;
public $active;
public $billingType;
public $subscriptionPlan;
public $commands;
function exchangeArray(array $data);}
I want to bind the object of Service class to my Edit form which used subscription, billing and commands related data as fieldsets. I am able to populate service values in form using bind but not other objects. here is my form implementation
class ServiceEditForm extends Form{
public function __construct($name = null)
{
parent::__construct('Edit Service');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/form-data');
//here i have other fields that belongs to service object
$this->add( array(
'name' => 'billingType',
'type' => 'Services\Form\BillingTypeFieldset',
'options' => array(
'label' => 'Billing Type',
),
));
$this->add( array(
'name' => 'subscriptionPlan',
'type' => 'Services\Form\SubscriptionPlanFieldset',
'options' => array(
'label' => 'Subscription Plan',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'commands',
'options' => array(
'label' => 'commands',
'count' => 2,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type' => 'Services\Form\CommandFieldset',
),
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Save'
),
));
}
}
As I said I am not able to populate fieldsets with bind within form with this implementation. Any suggestion will be appreciated.

Although I have already answer the question after looking up for possible solutions but Hydrator Implementations given in this link is also useful in explaining the very basics that one should read before using it. My bad i didn't went for full-throttled study before implementing fieldsets.
http://framework.zend.com/manual/current/en/modules/zend.stdlib.hydrator.html
This url explain possible implementation of hydrators that can deliver you very easy binding solution for your class.

Related

How to call a controller function inside the form in zend 2

i am new in zend framework
i need to add dynamic values inside the form selection elements
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'SECTOR_ID',
'attributes' => array(
'class' => 'form-control select2drop',
'id' => 'Sector_ID'
),
'options' => array(
'value_options' => $this->getOptionsForSectorSelect(),
),
'disable_inarray_validator' => true
));
above code help me to get dynamic values
but i need to call a controller function for getting value , now i wrote getOptionsForSectorSelect inside the form
Please help me
You could make the method inside your Controller static
class IndexController extends AbstractActionController {
public static function getOptionsForSectorSelect() {
// Building dynamic array ...
return $dynamicArray;
}
// More code ...
}
Or you could pass the array with your form when creating it in your action like so:
public function indexAction() {
$dynamicArray = $this->getOptionsForSectorSelect();
$myForm = new YourForm($dynamicArray);
// more action code...
}
And then in your form:
class YourForm extends Form {
private $dynamicArray;
public function __construct(array $dynamicArray) {
$this->dynamicArray = $dynamicArray;
}
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'SECTOR_ID',
'attributes' => array(
'class' => 'form-control select2drop',
'id' => 'Sector_ID'
),
'options' => array(
'value_options' => $this->dynamicArray,
),
'disable_inarray_validator' => true,
));
}
Hope it helps! :)

How to use collections in a fieldset factory in ZF2

I am developing a project with ZF2 and Doctrine. I am attempting to use Doctrine Hydrator in the form creation as shown in this tutorial. In this method, an ObjectManager object is created in the controller and passed to the new form when it is instantiated. Passing the ObjectManager object from the controller to the form creates a problem when I want to use ZF2's FormElementManager because ZF2 requires that I get an instance of the form class through the Zend\Form\FormElementManager instead of directly instantiating it. To work around this requirement, I have created form and fieldset factories based upon the answer to the question How to pass a Doctrine ObjectManager to a form through ZF2 FormElementManager. The method presented in the answer to the question works for typical fieldset elements, but I need to determine how to include a collection element. The tutorial uses the ObjectManager object in the collection element in the parent fieldset, and I need to figure out how to add the collection using a factory.
TagFieldset from the tutorial that I am trying to emulate:
namespace Application\Form;
use Application\Entity\Tag;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class TagFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('tag');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new Tag());
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'name',
'options' => array(
'label' => 'Tag'
)
));
}
public function getInputFilterSpecification()
{
return array(
'id' => array(
'required' => false
),
'name' => array(
'required' => true
)
);
}
}
new TagFieldsetFactory:
namespace Application\Form;
use Zend\Form\Fieldset;
use Application\Entity\Tag;
class TagFieldsetFactory
{
public function __invoke($formElementManager, $name, $requestedName)
{
$serviceManager = $formElementManager->getServiceLocator();
$hydrator = $serviceManager->get('HydratorManager')->get('DoctrineEntityHydrator');
$fieldset = new Fieldset('tags');
$fieldset->setHydrator($hydrator);
$fieldset->setObject(new Tag);
//... add fieldset elements.
$fieldset->add(['...']);
//...
return $fieldset;
}
}
BlogPostFieldset from the tutorial that I am trying to emulate:
namespace Application\Form;
use Application\Entity\BlogPost;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class BlogPostFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('blog-post');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new BlogPost());
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
$tagFieldset = new TagFieldset($objectManager);
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));
}
public function getInputFilterSpecification()
{
return array(
'title' => array(
'required' => true
),
);
}
}
new BlogPostFieldsetFactory:
namespace Application\Form;
use Zend\Form\Fieldset;
use Application\Entity\BlogPost;
class BlogPostFieldsetFactory
{
public function __invoke($formElementManager, $name, $requestedName)
{
$serviceManager = $formElementManager->getServiceLocator();
$hydrator = $serviceManager->get('HydratorManager')->get('DoctrineEntityHydrator');
$fieldset = new Fieldset('blog_post');
$fieldset->setHydrator($hydrator);
$fieldset->setObject(new BlogPost);
//... add fieldset elements.
$fieldset->add(['...']);
//...
return $fieldset;
}
}
in module.config.php:
'form_elements' => [
'factories' => [
'UpdateBlogPostForm' => 'Application\Form\UpdateBlogPostFormFactory',
'BlogPostFieldset' => 'Application\Form\BlogPostFieldsetFactory',
'TagFieldset' => 'Application\Form\TagFieldsetFactory',
],
],
When I add the fieldset elements In my new BlogPostFieldsetFactory I replace this code from the original fieldset:
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
with this:
$fieldset->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
How do I replace the collection element from the original fieldset:
$tagFieldset = new TagFieldset($objectManager);
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));
maybe i'm getting your question wrong.... but if you replaced this
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
whith this:
$fieldset->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
then you probably can replace this:
$tagFieldset = new TagFieldset($objectManager);
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));
with this:
$tagFieldset = new TagFieldset($objectManager);
$fieldset->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));
now, if you cant pass the $objectManger to the form... well if you look at the code you have this thing available $serviceManager, that thing looks like a DI container, im sure you can get the $objectManager instance from there, and if is not available, you can probably put an instance of it inside.
So de final code probably ending looks like this:
$objectManager = $serviceManager->get('DoctrineObjectManager') //or something like this
$tagFieldset = new TagFieldset($objectManager);
$fieldset->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));

Nested Fieldset with dependency injection in zend framework 2

I followed zend Advanced use of forms to solve my problem.
Scenario:
I have two fieldset. JudgesFieldset and JudgesCareerFieldset (one judge has multiple career so i need to use collection in judge fieldset). JudgesCareerFieldset has doctrine 2 object manager dependency for creating select element and create service of JudgesCareerFieldset in module.php as described in the Advanced use of forms. Everything is fine and working and create form successfully. The code and example shown below.
class JudgesCareerFieldset extends Fieldset implements InputFilterProviderInterface {
private $entityManager;
public function __construct(ObjectManager $entityManager) {
parent::__construct('judges-career');
$this->entityManager = $entityManager;
$this->setHydrator(new DoctrineHydrator($entityManager))
->setObject(new Judges());
//fields of the entity
}
and
class JudgesFieldset extends Fieldset implements InputFilterProviderInterface {
private $entityManager;
public function __construct(ObjectManager $entityManager) {
parent::__construct('judges');
$this->entityManager = $entityManager;
$this->setHydrator(new DoctrineHydrator($entityManager))
->setObject(new Judges());
//Remaining Fields of the Judge entities
}
public function init() {
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'judgeCareer',
'options' => array(
'label' => 'Please Judge Career',
'count' => 2,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type' => 'CaseLaw\Judges\Form\JudgesCareerFieldset'
),
),
));
}}
and form code
class JudgesFieldsetForm extends Form {
public function __construct(ObjectManager $entityManager) {
parent::__construct('Judges');
$this->setAttribute('method', 'post')
->setHydrator(new DoctrineHydrator($entityManager));
$judgesFieldset = new \Caselaw\Judges\Form\JudgesFieldset($entityManager);
$judgesFieldset->setUseAsBaseFieldset(true);
$this->add($judgesFieldset);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Add Judge',
'id' => 'submit',
'class' => 'btn btn-primary'
),
));
}}
Problem:
In the view script when I tried to display collection it will display this error "No element by the name of [judgeCareer] found in form". How can i get judgeCareer collection ?
Error:
I solved my problem by changing in collection code in JudgesFieldset class.
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'judgeCareer',
'options' => array(
'label' => 'Please Judge Career',
'count' => 2,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type' => 'CaseLaw\Judges\Form\JudgesCareerFieldset'
),
),
));
Change to
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'judgeCareer',
'options' => array(
'label' => 'Please choose categories for this product',
'count' => 2,
'should_create_template' => true,
'allow_add' => true,
'target_element' => new \Caselaw\Judges\Form\JudgesCareerFieldset($this->entityManager)
),
));
You are trying to add a collection named judgeCareer, but your JudgesCareerFieldset object has the name judges-career. Change the name and the Zend\Form\Fieldset should find your fieldset.

ZF2 Form Collections - filtering empty records

I'm trying to work out how to filter empty records from a form collection. With my application I have 2 entities, Competition and League. A competition may have zero or more Leagues.
So I create a Competition form (CompetitionForm), a Competition fieldset (CompetitionFieldset) and a League fieldset (LeagueFieldset).
The CompetitionFieldset is added to the CompetitionForm, and the CompetitionFieldset uses Zend\Form\Element\Collection to allow the user to add 1 or more Leagues. I've added the current code for each class below.
By default, I want to display input fields for 3 leagues within a competition, so within the CompetitionFieldset, when I add the Zend\Form\Element\Collection item, I set the count option to 3.
But if a user doesn't supply any data for the leagues, I want to ignore them. At present, three empty associated leagues are created within my database.
If I set an InputFilter on the LeagueFieldset to make the name field required for example, then the form won't validate.
I should maybe also mention that I'm using Doctrine2 to model my entities and hydrate my forms etc.
I'm sure I could make it work with some additional code on my models, or even in my Controller where I process the form, but I'm sure there is a neater solution maybe using Filters.
If anyone could point me in the right direction it would be much appreciated.
Many thanks in advance for any help you can provide.
:wq
familymangreg
My CompetitionForm
use Kickoff\Form\AbstractAdminForm;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Stdlib\Hydrator\ClassMethods;
class CompetitionForm extends AbstractAdminForm
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct($objectManager, 'competition-form');
$fieldset = new CompetitionFieldset($objectManager);
$fieldset->setUseAsBaseFieldset(true);
$this->add($fieldset);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Submit',
'id' => 'submitbutton',
),
));
}
}
My CompetitionFieldset
use Kickoff\Form\AbstractFieldset;
use Kickoff\Model\Entities\Competition;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
class CompetitionFieldset extends AbstractFieldset
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct($objectManager,'Competition');
$this->setHydrator(new DoctrineHydrator($this->objectManager,'Kickoff\Model\Entities\Competition'))
->setObject(new Competition());
$this->setLabel('Competition');
$this->add(array(
'name' => 'name',
'options' => array(
'label' => 'Competition name (e.g. Premier League)',
),
'attirbutes' => array(
'type' => 'text',
),
));
$this->add(array(
'name' => 'long_name',
'options' => array(
'label' => 'Competition long name (e.g. Barclays Premier League)',
),
'attirbutes' => array(
'type' => 'text',
),
));
$leagueFieldset = new LeagueFieldset($objectManager);
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'leagues',
'options' => array(
'label' => 'Leagues',
'count' => 3,
'should_create_template' => true,
'allow_add' => true,
'target_element' => $leagueFieldset,
),
));
}
}
My LeagueFieldset
use Kickoff\Form\AbstractFieldset;
use Kickoff\Model\Entities\League;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\InputFilter\InputFilterProviderInterface;
class LeagueFieldset extends AbstractFieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct($objectManager,'League');
$this->setHydrator(new DoctrineHydrator($this->objectManager,'Kickoff\Model\Entities\League'))
->setObject(new League());
$this->setLabel('League');
$this->add(array(
'name' => 'name',
'options' => array(
'label' => 'League name (e.g. First Qualifying Round)',
),
'attirbutes' => array(
'type' => 'text',
),
));
$this->add(array(
'name' => 'long_name',
'options' => array(
'label' => 'League long name (e.g. UEFA Champions League First Qualifying Round)',
),
'attirbutes' => array(
'type' => 'text',
),
));
}
public function getInputFilterSpecification()
{
return array(
'name' => array(
'required' => true,
)
);
}
}
You need to get data from request before you pass it to EntityManager, that's for sure. Just add your own validation to filter empty records. You can also provide javascript filters that will catch submit form event and delete empty fields before submitting it.

Create a drop down list in Zend Framework 2

I know this sounds much more basic, still I want to post my question as it is related to Zend Framework 2. I know this form from the Zend example module
namespace Album\Form;
use Zend\Form\Form;
class AlbumForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('album');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'artist',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Artist',
),
));
$this->add(array(
'name' => 'title',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Title',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
And this is called in this fashion
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('album', array('action' => 'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('title'));
echo $this->formRow($form->get('artist'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
How can I add a drop down list for the artist field where the list is stored in an associative array. Since Im getting into Zend Framework 2, I wanted the suggestions from the experts. I have followed this previous post but it was somewhat unclear to me.
This is one way to do it for static options.
....
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'number'
'options' array(
'options' => array( '1' => 'one', '2', 'two' )
)
));
Be warned....
Because you are creating the form within a constructor you will not have access the ServiceManger. This could cause a problem if you want to populate from a database.
Lets try something like...
class AlbumForm extends Form implements ServiceManagerAwareInterface
{
public function __construct()
{
....
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'number'
));
....
}
....
public function initFormOptions()
{
$this->get('number')->setAttribute('options', $this->getNumberOptions());
}
protected function getNumberOptions()
{
// or however you want to load the data in
$mapper = $this->getServiceManager()->get('NumberMapper');
return $mapper->getList();
}
public function getServiceManager()
{
if ( is_null($this->serviceManager) ) {
throw new Exception('The ServiceManager has not been set.');
}
return $this->serviceManager;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
}
But that's not great, rethink...
Extending the Form so that you can create a form isn't quite right. We are not creating a new type of form, we are just setting up a form. This calls for a factory. Also, the advantages of using a factory here are that we can set it up in a way in which we can use the service manager to serve it up, that way the service manager can inject itself instead of us doing in manually from the controller. Another advantage is that we can invoke this form whenever we have the service manager.
Another point worth making is that where it makes sense, I think it's better to take code out of the controller. The controller is not a script dump so it's nice to have objects look after themselves. What I'm trying to say is that it's good to inject an object with objects it needs, but it's not okay to just hand it the data from the controller because it creates too much of a dependency. Don't spoon feed objects from the controller, inject the spoon.
Anyway, too much rant more code...
class MySpankingFormService implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceManager )
{
$mySpankingNewForm = new Form;
// build that form baby,
// you have a service manager,
// inject it if you need to,
// otherwise just use it.
return $mySpankingNewForm;
}
}
controller
<?php
class FooController
{
...
protected function getForm()
{
if ( is_null($this->form) ) {
$this->form =
$this->getServiceManager()->get('MySpankingFormService');
}
return $this->form;
}
...
}
module.config.php
...
'service_manager' => array (
'factories' => array (
...
'MySpankingFormService'
=> 'MyNameSpacing\Foo\MySpankingFormService',
...

Categories