How to add attributes to options in select?

hi all. maybe somebody know how to add an attribute to options in select element?

edited Jul '16

When generating the element:

$options = [
    'disabled' => 'disabled',
    'style' => 'border: 1px solid red;',
    'class' => 'input-sm'
];
new \Phalcon\Forms\Element\Select('input-name', $values, $options);

In volt you can add array with options to .render() method.

{{ field.render([
    'disabled' => 'disabled',
    'style' => 'border: 1px solid red;',
    'class' => 'input-sm'
]) }}

UPDATE: Oh, wait a sec! You are asking if you could add attribute to the <option> not to the <select> element? If so please confirm so i can remove above answer :)



1.3k
edited Jul '16

When generating the element:

```php $options = [ 'disabled' => 'disabled', 'style' => 'border: 1px solid red;', 'class' => 'input-sm' ]; new \Phalcon\Forms\Element\Select('input-name', $values, $options); ```

In volt you can add array with options to .render() method.

thx, i know about this, but i need method to add different attributes to optinons. somethink like this:

$element->addOption(array('id'=>'1', 'name'=>'One', 'class'=>'test', 'img'=>'../img/test.jpg')); $element->addOption(array('id'=>'2', 'name'=>'Two', 'class'=>'test2', 'img'=>'../img/test2.jpg'));

edited Jul '16

Yes, yes ! After i read your question 3 times i realised what you are asking. Sorry!

I think your best option is to create your own select class like MySelect which extends Phalcon's Select and overwrite it's render() method.

You can check class methods here docs.phalconphp.com/en/latest/api/PhalconFormsElement_Select.html and also how to extend and create your own element.

Here is example where I created a custom form element with similar problem to yours:

class Recaptcha extends \Phalcon\Forms\Element
{
    public function render($attributes = null)
    {
        $config = loadConfig();
        $language = \Phalcon\DI::getDefault()->getSession()->language;
        $html = '<script src="https://www.google.com/recaptcha/api.js?hl='. $language .'"></script>';
        $html.= '<script>function recaptchaCallback() { document.getElementById("recaptchaTemp").setAttribute("value", "checked") }</script>';
        $html.= '<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="'. $config->sensitive->recaptcha->publicKey .'"></div>';
        $html.= '<input type="hidden" name="recaptchaTemp" id="recaptchaTemp" value=""/>';
        return $html;
    }
}

Lets hope someone else has a better suggestions then this :)



4.3k

There is a bug for that:

https://github.com/phalcon/cphalcon/issues/899

Let's hope it will be fixed soon. I also need to disable certain options.