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

Select tag option use other field in Model

Hi, I want to build select tag option using field that is a combination of two fields in resultsets. I know if this can be code using "concatenate" when querying and get the resultset, but I want to achieve it by using Model only. I already created new setter/getter, but I cannot show it in Views. Below is my code:

Lets say we have Countries table: Countries have: Id, Code, and Name.

Model

    class Countries extends Model{
        public $Id;
        public $Code;
        public $Name;
        public $CodeName;

        public function setCodeName()
        {
            $this->CodeName = $this->Code . " - " . $this->Name;
        }

        public function getCodeName()
        {
            return $this->CodeName;
        }
    }

Controller

    $countries = Countries::find();

    /*I also use this but its still not work

    foreach($countries as $country){
        $country->setCodeName();
    }
    */

View

    echo $this->tag->select(
        array(
            "Country",
            $countries,
            "using" => array('Id', 'CodeName'),
            "useEmpty" => true,
            "emptyText" => 'Please choose...',
            "emptyValue" => '0',
            "class" => "test",
        )
    ) 

And the result, it return empty in option selection. Please help.

Thank you.



58.4k

Hi I am assuming that you have form:

    $results = Teacher::find(
        array(
            'columns' => 'Id, ' . new  RawValue('CONCAT (LastName, " ", FirstName) as typeName')
        )
    );

    $teacherParams = array(
        'useEmpty'  => true,
        'emptyText' => '-----',
        'using'     => array('Id', 'typeName')
    );

    $TeacherId = new Select('TeacherId', $results, $teacherParams);

    $TeacherId->setLabel(_('Teacher Name'));
    $TeacherId->addValidators(array(
        new PresenceOf(array(
            'message' => (_('Teacher is required'))
        ))
    ));
    $this->add($TeacherId);

And in view you can use following

                            <td>    {{form.label('TeacherId')}}     </td>
                            <td>    {{form.render('TeacherId')}}    </td>