I have a database with a simple one-to-many relationship that looks like this:
Tables Company Category
Rows ID ID
Name Name
Category_ID
I have a forms where I can add, edit and delete the company’s or category’s name, which works fine. Entering the category by ID also works, but is obviously terrible to use. What I want is a simple select element in the form to pick from an existing category.
The code I have to generate the <select> is:
$this->add(array(
'name' => 'Categorie',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => $categories,
),
'options' => array(
'label' => 'Categorie',
),
));
From what I could find in the (extremely sparse) ZF2 documentation, I should be using a Hydrator to fetch data into the $categories variable, but I’m not sure where to go from there.
Any sort of example or tips would be well appreciated!
Here‘s a very good article about forms.
My solution is based on this tutorial and it is (almost) working well. I don’t know if you use Doctrine for your project or not, but I think it would be a very good idea!
I also heavily use select elements. In the given fieldset, I generate value options for a select with this piece of code:
If you (plan to) use Doctrine, you should read about repositories very carefully in the Doctrine documentation. If you use collections in the form, the topic about associations is also a must read.