Hi all!
I'm having a particularly annoying problem pre-filling form elements with data from the DB. Now, I should say upfront that for most of the forms I've built so far, I've had no issues, but because I want to make use of a <select multiple>...</select>
element I'm having issues. In addition, and this will become relevant when I talk about my 2nd attempt, I have one table that stores the base information for the "item". I then have a number of linked tables that store an indeterminant number of additional "properties" for the "item", as such I have to build the form programmatically, and do not know up-front the number of fields, their names, or the possible values etc.
My first attempt to solve the problem involved using the tag helper functions in the volt template file to build the form manually. Then in the controller i would use $this->tag->setDefault("elementName", $val-from-db);
. This would generally work for most elements, except when I wanted to set the default values of a select with the 'multiple' attribute, as I was trying to pass and array. I tried combining all the defaults into an array and then using the $this->tag->setDefaults($defaults);
but the best I could do was get it to select the very first option in my multi-select, regardless of whether this was set in the DB tables.
My 2nd approach saw me move to a \Phalcon\Forms\Form
method. I created a separate form file that stored the base field elements. Now, because I have the "variable" number of elements to display, I have a function in the controller that builds additional fields and adds them to the form. The volt file gets passed a variable with the "additional" field names, and itterates through the base elements and the "additional' fields and then prints the field to the volt template. I have used the entity of the "base" item to aid the pre-population of the base form, and this works, for the base elements. For the additional elements, I am using something like this:
$field = new Select ($name, $values, ['class' => 'select2 form-control', 'multiple' => 'mutiple'])
$field->setDefault(array(3,2,5,));
$form->add($field);
This does nothing. It doesn't work for simple text inputs or any other type of input field, let alone my select-multiple elements.
Can someone help put me out of my misery? I think I should "prefer" the 2nd approach generally, and for most instances I should be able to pass entities tot he base forms to make it use that to populate the default values. But it's not clear how to:
- Set the default values of the "linked" tables that might be associated with the base entity i.e. $entity->SomeOtherTable->name.
- How to set manual default values from within the controller, if i need to "override" them.
If someone could provide some information on how to acheive what I'm looking to do, I would really apprecaite it.
Any questions, please do not hesitate to contact me.
Many thanks in advance.