We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Recommended way to populate options for Phalcon\Forms\Element\Select with Phalcon\Mvc\Model?

What's the recommended way to populate the options for a Phalcon\Forms\Element\Select object with data from Phalcon\Mvc\Model?

For example, say I have 2 models, User and Email and they're related like so:

class User extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->hasMany("user_id", "Email", "user_id", array('alias'=>'emails'));
    }
}
....
class Email extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->hasOne("user_id", "User", "user_id", array('alias'=>'user'));
    }
}

And I want to make a select form element with all the user's emails as options. If you use Phalcon\Forms\Element\Select, you can pass it an assoc array to populate all the options, but in the manual I didn't see a way to pull an assoc array out of the model. So do I have to do something like this every time I want to fill them in?

class SomeForm extends Phalcon\Forms\Form {
    public function initialize() {
        $user = User::find(25); 
        $emails = $user->getEmails(array(
            'columns' => array('email_id', 'email')
        ));

        $assoc_emails = array();
        foreach($emails as $e) {
            $assoc_emails[$e['email_id']] = $e['email'];
        }

        $this->add(new Phalcon\Forms\Element\Select('email', $assoc_emails));
    }

I'm sure I'm doing something wrong here. Is it the way I'm pulling from the model? Or is there an easier way to set the select options? Is there something like Symfony's Entity field type that I should be using instead?

Following the documentation wouldn't you use:

$this->add(new Phalcon\Forms\Element\Select('email', Emails::find(), array('using' => array('email_id', 'email')));

Thanks, that's exactly what I'm looking for.

BTW, where is that in the documention? I looked all over but didn't see it. Is there a list of all available options you can pass for that 3rd param somewhere?



13.4k
Accepted
answer

Here it is in the documentation:

https://docs.phalcon.io/en/latest/reference/forms.html#initializing-forms

As far as I can see, there's nothing documenting ALL options for the third parameter - the "using" param is specific to the Select box when using a Model for the values. All the other values passed will be attributes set on the element for example:

$this->add(new Phalcon\Forms\Element\Select('email', Emails::find(), array('class' => 'form-input', 'using' => array('email_id', 'email')));

WIll render the select element with the values from the database and a class of "form-input"