Hello! How can you pass an object or an array (in particular, a <select> element) from a database (Zend Expressive + Doctrine) into a form?

The form:

 public function __construct($name = null) { $name = isset($name) ? $name : 'categories-form'; parent::__construct($name); $this->setAttribute('enctype', 'multipart/form-data'); $this->setHydrator(new ClassMethodsHydrator())->setAttribute('method', 'post'); $this->add([ 'name' => 'parent', 'type' => 'Zend\Form\Element\Select', 'options' => [ 'label' => 'Принадлежность', 'empty_option' => 'Выберите категорию...', 'value_options' => [], ], ]); $this->add([ 'name' => 'submit', 'type' => 'Submit', 'attributes' => [ 'value' => 'Сохранить', ], ]); } 

Factory:

 use App\Panel\Form\CategoriesForm; use Interop\Container\ContainerInterface; class CategoriesFormFactory { /** * @param ContainerInterface $container * @return CategoriesForm */ public function __invoke(ContainerInterface $container) { return new CategoriesForm('categories-form'); } } 

Act:

 $form = new CategoriesForm(); if ($request->getMethod() === 'POST') { $form->setData($request->getParsedBody()); } 

HTML (twig):

  <div class="form-group select"> <label for="{{ form.get('parent').name }}">{{ form.get('parent').label }}</label> <select class="form-control" type="{{ form.get('parent').attributes.type }}" name="{{ form.get('parent').name }}"> {% for option in form.get('parent').options.value_options %} <option>{{ option }}</option> {% endfor %} </select> </div> 

    1 answer 1

     class CategoryForm extends Form implements ObjectManagerAwareInterface private $objectManager; public function __construct(ObjectManager $objectManager) { $this->setObjectManager($objectManager); } $this->add([ 'type' => ObjectSelect::class, 'name' => 'parent', 'attributes' => [ 'id' => 'parent', 'class' => 'select' ], 'options' => [ 'label' => 'Категория', 'object_manager' => $this->getObjectManager(), 'target_class' => Category::class, 'property' => 'name', 'empty_option' => '== Категория ==', 'is_method' => true, 'find_method' => [ 'name' => 'findParentCategories', 'params' => [ //'criteria' => ['status' => 1], 'orderBy' => ['name' => 'ASC'], ], ], ], ]);