Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Setting the default option in a new Select()

Hello,

Update: This only happens when the name of the field is an array... ie phone_numbers[] , it works as intended otherwise.

I am able to set default of all my text fields and what not with "setDefault" in my form creator. However when I am trying to select a default option in a select I can not seem to get to take. I have a form class that is doing something like this.

$form_item = new Select($fields['name']);
$form_item->setOptions($fields['options']);
$form_item->setDefault($fields['default']); 
$form_item->add($form_item);

I have only been able to set a default by using the tag->setDefault right before rendering in my view.

$this->tag->setDefault($fields['name'],$fields['default']);
$this->render($fields['name']);

Any thoughts?

btw this is Phalcon 1.3.x



18.5k

Show declaration of $fields["options"].

I noticed it is happening when it the new Select("field_name[]") is an array

Show declaration of $fields["options"].



18.5k

I noticed it is happening when it the new Select("field_name[]") is an array

Show declaration of $fields["options"].

The select is a multiple one? Then the default value must be an array if I remember well.

Yeah it looks to be something along that lines. I also noticed that when the form is submitted, those are the only fields it doesn't retain the information at this time.

So I have 3 phone number fields and a select to choose the type for each

phonenumbertype[]

phonenumbertype[]

phonenumbertype[]

as the name of the fields (but they would have option to add more actually) so it I am trying to not to do any hardcoding on this and making it all dynamic.

I noticed it is happening when it the new Select("field_name[]") is an array

Show declaration of $fields["options"].

The select is a multiple one? Then the default value must be an array if I remember well.



18.5k

Then you must get all selects and all values, and do something like:

for ($i = 0; $i < count($values); $i++)
{
    $selects[$i]->setDefault($values[$i]);
}

Well one step back, how do I get the "$selects" or form fields that are already added to loop through them? The getElements() on the form seems to return the entire object of the app

Then you must get all selects and all values, and do something like:

``` for ($i = 0; $i < count($values); $i++) { $selects[$i]->setDefault($values[$i]); } ```



18.5k
Accepted
answer
edited Jan '15
foreach($this->request->getPost('phoneNumberType') as $select)
{
    // Create the SELECT as you know.
}
foreach($this->request->getPost('phoneNumberValue') as $value)
{
    // Create the INPUT as you know.
}
for ($i = 0; $i < count($selects); $i++)
{
    // Append the SELECT and the INPUT to a container... or whatever. This pass may be optional.
}