Zend Framework 2 FormElementManager factories not working - zend-framework2

Please help me with Zend framework 2:)
I want to create a form with collection of fieldsets using Form Element Manager (absolutely like in official documentation).
My FormElementManager configuration:
'form_elements' => array(
'factories' => array(
'Admin\Form\TaskForm' => function($sm) {
$form = new TaskForm();
$doctrimeEntityManager = $sm->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$form -> setEntityManager($doctrimeEntityManager);
$form -> init();
return $form;
},
'Admin\Form\TaskbrandFieldset' => function($sm) {
$doctrimeEntityManager = $sm->get('Doctrine\ORM\EntityManager');
$form = new TaskbrandFieldset();
$form->setEntityManager($doctrimeEntityManager);
return $form;
},
)
),
Admin\Form\TaskForm (only problem part):
namespace Admin\Form;
use Doctrine\ORM\EntityManager;
use Zend\Form\Form;
class TaskForm extends Form {
protected $entityManager;
public function init() {
$this->setAttribute('method', 'post');
// Id
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
// My fieldset
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'taskbrands',
'options' => array(
'label' => 'Brand of the product',
'count' => 0,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type'=>'Admin\Form\TaskbrandFieldset'
),
),
'attributes' => array(
'id' => 'addressFieldset'
)
));
}
}
Admin\Form\TaskbrandFieldset:
namespace Admin\Form;
use Admin\Entity\Taskbrand;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class TaskbrandFieldset extends Fieldset implements InputFilterProviderInterface, ServiceLocatorAwareInterface {
protected $entityManager;
protected $serviceLocator;
public function init() {
$this->setName('TaskbrandFieldset');
$this->setHydrator(new ClassMethodsHydrator(false))
->setObject(new Taskbrand());
$this->setLabel('Taskbrand');
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'brand',
'options' => array(
'object_manager' => $this->getEntityManager(),
'target_class' => 'Module\Entity\Brand',
'property' => 'name',
),
));
}
}
And, finally, my controller:
$Task = $this->getServiceLocator()->get('Admin\Model\Task')->findByPk($id);
$formManager = $this->getServiceLocator()->get('FormElementManager');
$form = $formManager->create('Admin\Form\TaskForm');
$form->bind($Task);
The problem is that form Admin\Form\TaskForm instantiates in factory described in form_elements configuration section, but Admin\Form\TaskbrandFieldset does not. It just invokes.
Trying to understand this problem I found that Admin\Form\TaskForm and Admin\Form\TaskbrandFieldset instantiates with different instances of FormElementManager, first one have my config inside (including factories description), but second has nothing.
Please help me :)

The problem is in your controller. Use
$form = $formManager->get('Admin\Form\TaskForm');
instead of
$form = $formManager->create('Admin\Form\TaskForm');
Remember that you don't have to use $form->init(). It's automatically called, same like in zf1. There is a good tutorial on zf2 site

Related

ZF2 An Invalid Factory Was Registered

I've the following classes and my module config in ZF2 application and it is giving the below error:
While attempting to create applicationformuserform(alias: Application\Form
\UserForm) an invalid factory was registered for this instance type.
UserFormFactory.php
<?php
namespace Application\Factory\Form;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Application\Form\UserForm;
class UserFormFactory implements FactoryInterface {
public function createService(ServiceLocatorInterface $serviceLocator) {
$services = $serviceLocator->getServiceLocator();
$entityManager = $services->get('Doctrine\ORM\EntityManager');
$form = new UserForm($entityManager);
return $form;
}
}
?>
UserForm.php
<?php
namespace Application\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
use Doctrine\ORM\EntityManager;
class UserForm extends Form implements InputFilterProviderInterface {
protected $entityManager;
public function __construct(EntityManager $entityManager) {
parent::__construct();
$this->entityManager = $entityManager;
}
public function init() {
$this->add(array(
'name' => 'username',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'User Name',
),
));
$this->add(array(
'name' => 'first_name',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'First Name',
),
));
$this->add(array(
'name' => 'last_name',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Last Name',
),
));
$this->add(array(
'name' => 'role_id',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
'object_manager' => $this->entityManager,
'target_class' => 'Application\Entity\Role',
'property' => 'id',
'is_method' => true,
'find_method' => array(
'name' => 'getRoles',
),
'label' => 'User Role',
),
));
}
public function getInputFilterSpecification() {
return array(); // filter and validation here
}
}
?>
Module.config.php
'form_elements' => array(
'factories' => array(
'Application\Form\UserForm' => 'Application\Factory\Form\UserFormFactory',
),
),
And I'm using this form factory in another controller factory
UserControllerFactory.php
<?php
namespace Member\Factory\Controller;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Member\Controller\UserController;
use Application\Form\UserForm;
class UserControllerFactory implements FactoryInterface {
public function createService(ServiceLocatorInterface $serviceLocator) {
$services = $serviceLocator->getServiceLocator();
$userForm = $services->get('FormElementManager')->get('Application\Form\UserForm');
$controller = new UserController($userForm);
return $controller;
}
}
?>
Could anybody tell me that what may be the issue?
Your Factory is not being found.
Check if you using PSR-4 or PSR-0 in your controller among the other answers
Briefly
did you name the Factory correctly (no misspellings)?
Is your composer.json updated with PSR-0, or PSR-4 namespaces for your modules?
did you run composer dump-autoload?
Does your autoload_classmap.php contain an outdated entry & confuses autoloader?
Check your folder structure and names
make sure your Factory implements FactoryInterface
Ask yourself "Why is my Factory class not being found when I have placed it right there" where it obviously without a doubt must be found? That will help you guide your way into finding out what's wrong.
I got my answer at my own after looking at the code again and again. Actually my Factory and Form folders were outside of src folder that's why Zend could not found all the classes of both folders.
I moved both Factory and Form folder in src and now it's working fine.
I had a similar problem. I had made some changes to my factory classes (refactoring + minor class name changes). Turns out that because I was using the Classmap Autoloader ... and forgot to re-run php vendor/bin/classmap_generator.php in the module structure ... the newly renamed classes were not found. Too bad a "class not found" error wasn't generated.

How to add dynamically validators and filters to elements in fieldsets in ZF2?

I use fieldsets in ZF2 forms. I can add validators and filters to elements:
$form->getInputFilter()->add(array(
'name' => 'element_name',
'required' => true,
'filters' => array(
array('name' => 'Zend\Filter\StringTrim'),
),
));
But how can I do this if element is in fieldset?
I tried to do so:
$form->getInputFilter()->add(array(
'fieldset_name' => array(
'name' => 'element_name',
'required' => true,
'filters' => array(
array('name' => 'Zend\Filter\StringTrim'),
),
),
));
But it doesn't work
The method of #Fouad Fodail should be preferred. The InputSpecification should be declared at the FieldsetClass itself. However if you need to do this like you asked it's just as simple:
$form->getInputFilter()
->get('fieldset_name')
->get('element_name')
->add($additionalFilter);
You should implement getInputFilterSpecification() method in your Fieldset Class and make the
required configurations there. This is necessary because the fleldset’s form receives all of its “InputFilter” specifications from the getInputFilterSpecification() methods of the referenced fleldsets.
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class MyFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct()
{
//...
}
public function getInputFilterSpecification()
{
return array(
'element_name' => array(
'filters' => array(),
'validators' => array(),
'properties' => array(),
'required' => true
)
);
}
}
Just add the validators directly in the fieldsets, not in the form.

How to get data from different model for select?

I have form with some attributes:
class ToraForm extends Form
{
public function __construct($name = null)
{
parent::__construct('tora');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'name',
'attributes' => array(
'type' => 'text',
'required' => true,
),
'options' => array(
'label' => 'name',
),
));
}
but I want add drop-down list with data taken from another model. How to do it?
There are several different approaches you can take. Ultimately your Form has a dependency, which needs to be injected. I have written an in-depth blog-post about the three most common use-cases for Form-Dependencies for a Select-List.
Zend\Form\Element\Select and Database-Values
My BlogPost covers the following scenarios:
Zend\Form\Element\Select via DbAdapter
Zend\Form\Element\Select via TableGateway
DoctrineModule\Form\Element\DoctrineObject via Doctrine2
Here i will demonstrate only the DbAdapter approach without much explanation. Please refer to my blogpost for the in-depth explanations.
public function formDbAdapterAction()
{
$vm = new ViewModel();
$vm->setTemplate('form-dependencies/form/form-db-adapter.phtml');
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$form = new DbAdapterForm($dbAdapter);
return $vm->setVariables(array(
'form' => $form
));
}
Then the respective Form Class:
class DbAdapterForm extends Form
{
protected $dbAdapter;
public function __construct(AdapterInterface $dbAdapter)
{
$this->setDbAdapter($dbAdapter);
parent::__construct('db-adapter-form');
$this->add(array(
'name' => 'db-select',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Dynamic DbAdapter Select',
'value_options' => $this->getOptionsForSelect(),
'empty_option' => '--- please choose ---'
)
));
}
// more later...
// Also: create SETTER and GETTER for $dbAdapter!
}
And last but not least the DataProvider function:
public function getOptionsForSelect()
{
$dbAdapter = $this->getDbAdapter();
$sql = 'SELECT t0.id, t0.title FROM selectoptions t0 ORDER BY t0.title ASC';
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[$res['id']] = $res['title'];
}
return $selectData;
}
My use is like that:
Class Useful{
/**
* All languages
* #return array
*/
public static function getLanguages(){
return array(
'fr_DZ'=>'Algeria - Français',
'es_AR'=>'Argentina - Español',
'en_AU'=>'Australia - English',
'nl_BE'=>'België - Nederlands',
'fr_BE'=>'Belgique - Français',
'es_BO'=>'Bolivia - Español',
'bs_BA'=>'Bosna i Hercegovina - Hrvatski',
...
);
}
}
After I use like that:
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'languages',
'attributes'=>array(
'multiple'=>"multiple",
),
'options' => array(
'label' => 'My languages I speak',
'description' => '',
'value_options' => Useful::getLanguages()
),
));

dynamic dropdown get in zf2?

I want to put a dropdown in my project which is made in zf2... I wasted all day but I only got a static dropdown, not dynamic. Can anyone help me with this problem??
UserForm.php
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
'options' => array('1=>php','2'=>'java'),
),
'options' => array(
'label' => '',
),
));
Thanks in advance for your valuabe answer.
Try this:
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
),
'options' => array(
'label' => '',
'value_options' => array(
'1' => 'php',
'2' => 'java'
),
),
));
This is what i did:
In my constructor for my form
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'color',
'options' => array(
'empty_option' => 'Select a Color',
'value_options' => self::getColors(),
'label' => 'Color',
),
));
In the form class yet, i created this method:
public static function getColors() {
// access database here
//example return
return array(
'blue' => 'Blue',
'red' => 'Red',
);
}
In my view script:
<div class="form_element">
<?php $element = $form->get('color'); ?>
<label>
<?php echo $element->getOption('label'); ?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
Think about it from a abstract level.
You have one Form
The Form needs Data from the outside
So ultimately your Form has a Dependency. Since we've learned from the official docs, there's two types of Dependency-Injection aka DI. Setter-Injection and Constructor-Injection. Personally(!) i use one or the other in those cases:
Constructor-Injection if the dependency is an absolute requirement for the functionality to work
Setter-Injection if the dependencies are more or less optional to extend already working stuff
In the case of your Form, it is a required dependency (because without it there is no populated Select-Element) hence i'll be giving you an example for Constructor-Injection.
Some action of your controller:
$sl = $this->getServiceLocator();
$dbA = $sl->get('Zend\Db\Adapter\Adapter');
$form = new SomeForm($dbA);
That's all for the form. The population now happens inside your Form. This is only an example and may need some fine-tuning, but you'll get the idea:
class SomeForm extends \Zend\Form
{
public function __construct(\Zend\Db\Adapter\Adapter $dbA)
{
parent::__construct('my-form-name');
// Create all the form elements and stuff
// Get Population data
$popData = array();
$result = $dbA->query('SELECT id, title FROM Categories', $dbA::QUERY_MODE_EXECUTE)->toArray();
foreach ($result as $cat) {
$popData[$cat['id'] = $cat['title'];
}
$selectElement = $this->getElement('select-element-name');
$selectElement->setValueOptions($popData);
}
}
Important: I HAVE NO CLUE ABOUT Zend\Db the above code is only for how i think it would work going by the docs! This is the part that would need some optimization probably. But all in all you'll get the idea of how it's done.
In your controller you can do something like below;
On my first example assuming that you have a Group Table. Then we're going to fetchAll the data in group table;
We need the id and name to be display in select options;
public function indexAction()
{
$groupTable = new GroupTable();
$groupList = $groupTable->fetchAll();
$groups = array();
foreach ($groupList as $list) {
$groups[$list->getId()] = $list->getName();
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
OR
in this example the grouplist is hardcoded;
public function indexAction()
{
$groupList = array('1' => 'PHP', '2' => 'JAVA', '3' => 'C#');
$groups = array();
foreach ($groupList as $id => $list) {
$groups[$id] = $list;
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
Then in your view script;
<?php
$form = $this->form;
echo $this->formRow($form->get('group_name'));
?>
Or you can right a controller helper, you may check this link http://www.resourcemode.com/me/?p=327
Just came across the same problem and had to take a look into zf2 source.
Here's a more OOP solution:
Inside the form constructor:
$this->add(array(
'name' => 'customer',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => array(
0 => 'Kunde',
)
),
'options' => array(
'label' => 'Kunde'
)));
inside the controller:
$view->form = new SearchForm();
$customers = $view->form->get('customer')->getValueOptions();
$customers[] = 'Kunde1';
$customers[] = 'Kunde2';
$customers[] = 'Kunde3';
$customers[] = 'Kunde4';
$view->form->get('customer')->setValueOptions($customers);

ZFCUser extend form

I am using Zendframework 2 with ZfcUser and ZfcUserDoctrineORM.
I extended the normal user with some additional information.
Now i want to adapt the registerForm. Therefor i created this form in the ZfcUser\Form folder:
class UserRegister extends ZfcUser\Form\Register {
public function init(){
$this->add(array(
'name' => 'firstName',
'options' => array(
'label' => 'First Name',
),
'attributes' => array(
'type' => 'text'
),
));
$this->add(array(
'name' => 'name',
'options' => array(
'label' => 'Last Name',
),
'attributes' => array(
'type' => 'text'
),
));
}
}
In the Next step I changed adapted the getServiceConfig() function in the Module.php in the ZfcUser folder:
'zfcuser_register_form' => function ($sm) {
$options = $sm->get('zfcuser_module_options');
$form = new Form\UserRegister(null, $options);
//$form->setCaptchaElement($sm->get('zfcuser_captcha_element'));
$form->setInputFilter(new Form\RegisterFilter(
new Validator\NoRecordExists(array(
'mapper' => $sm->get('zfcuser_user_mapper'),
'key' => 'email'
)),
new Validator\NoRecordExists(array(
'mapper' => $sm->get('zfcuser_user_mapper'),
'key' => 'username'
)),
$options
));
return $form;
},
When calling the register url this error message is shown:
Fatal error: Cannot redeclare class UserRegister in C:\xampp\htdocs\THWDiver\vendor\zf-commons\zfc-user\src\ZfcUser\Form\UserRegister.php on line 24
What am I making wrong?
Realize this is an old question, but just stumbled onto it. You need to edit your Entity module's bootstrap and attach to 'ZfcUser\Form\Register' at 'init'.
I've got a blog article here that details the solution in depth:
http://circlical.com/blog/2013/4/1/l5wftnf3p7oks5561bohmb9vkpasp6
Hope it helps you!
I think that the answer is to override the service factory "zfcuser_register_form" and inside of it declare your own RegisterForm.

Resources