Пожалуйста, помогите мне с Zend Framework 2 :)Zend Framework 2 FormElementManager заводы не работают
Я хочу, чтобы создать форму с коллекцией fieldsets с помощью формы Element Manager (абсолютно как in official documentation). Конфигурация
Мои FormElementManager:
'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 (только часть проблемы):
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 \ Форма \ 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',
),
));
}
}
И, наконец, мой контроллер:
$Task = $this->getServiceLocator()->get('Admin\Model\Task')->findByPk($id);
$formManager = $this->getServiceLocator()->get('FormElementManager');
$form = $formManager->create('Admin\Form\TaskForm');
$form->bind($Task);
Проблема заключается в том, что форма Admin \ Form \ TaskForm создается на фабрике, описанной в разделе конфигурации form_elements, но Admin \ Form \ TaskbrandFieldset этого не делает. Он просто вызывает.
Попытка понять эту проблему Я обнаружил, что Admin \ Form \ TaskForm и Admin \ Form \ TaskbrandFieldset создаются с помощью разных экземпляров FormElementManager, сначала у меня есть моя конфигурация внутри (включая описание фабрик), но вторая ничего не имеет.
Пожалуйста, помогите мне :)
Форма ** Элемент ** Менеджер должен создать Form ** Elements **;) Используйте обычную фабрику сервисов для создания ваших форм (service_manager => фабрик) – Sam
Я пробовал. Если используется обычная фабрика услуг (в контроллере $ this-> getServiceLocator() -> get ('Admin \ Form \ TaskForm')) TaskForm создает правильные настройки, но Admin \ Form \ TaskbrandFieldset все еще создает экземпляр с FormElementManager без конфигурации. В [официальной документации] (http://framework.zend.com/manual/2.2/en/modules/zend.form.advanced-use-of-forms.html#handling-dependencies) они используют FormElementManager. – user2582502
Хм, лично я делаю это, как указано в [DoctrineDocs] (https://github.com/doctrine/DoctrineModule/blob/master/docs/hydrator.md#a-complete-example-using-zendform) и просто создать экземпляр Fieldset в моей форме, который уже знает об EntityManager, поэтому его легко передать. – Sam