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.

Define a html attribute in select for each option

Hi everyone,

I'm trying to set an html attribute in a tag option from a select element.

Here the definition of my form:

public function initialize($null, $image)
{
  $this->add(new Select('image', $image, array(
    'class' => 'form-control'
  )));
}

$image is an array. I want to set a new html attribute: data-image with the content from my array $image. But I didn't find how to do it. I'm using volt so I'd like to avoid .phtml

Thanks for your time



84.1k
edited Jul '14

The second parameter of initialize is an array of options:

public function initialize($entity=null, $option=null)
{
  $this->add(new Select('image', $option['data-image'], array(
    'class' => 'form-control'
  )));
}

Creating the form:

$this->view->form = new MyForm(null, array('data-image' => $data));

Rending the form:

{{ form.render() }}
edited Jul '14

Hi thanks for answering me !

But I think I wasn't really clear.

Here the code I already have:

    // forms/ArticlesForm
    $this->add(new Select('image', $image['value'], array(
    'class' => 'form-control'
    )));
    // controllers/AdminController
    $image = array('image0.jpg', 'image1.jpg', 'image2.jpg', 'image3.jpg');
    $form = new ArticlesForm(null, array('value' => $image));

Here the result:

<select id="image" name="image" class="form-control">
    <option selected="selected" value="0">image0.jpg</option>
    <option value="1">image1.jpg</option>
    <option value="2">image2.jpg</option>
    <option value="3">image3.jpg</option>
</select>

and I'm trying to have that kind of result:

<select id="image" name="image" class="form-control">
    <option selected="selected" value="image0.jpg" data-image="image0.jpg">image0.jpg</option>
    <option value="image1.jpg" data-image="image1.jpg">image1.jpg</option>
    <option value="image2.jpg" data-image="image2.jpg">image2.jpg</option>
    <option value="image3.jpg" data-image="image3.jpg">image3.jpg</option>
</select>

Thanks again



4.5k
Accepted
answer
edited Jul '14

Finally I used javascript for adding the HTML attribute to my options tag ... I'll change it to native phalcon function when I'll find it !



12.4k

You have the "array('class' => 'form-control')", I tried to add another name-value pair and it becomes the arbitrary attribute in the output.