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.

Models -> Combining columns from result set into key => value array

In my action controller I have:

$user_groups = UserGroup::find(array('columns' => 'id,label'));
$form = new ProductReviewForm($user_groups);

In the form initialize I have:

public function initialize($user_groups) {

    $user_groups_array = $user_groups->toArray();
    $user_groups_name = array_column($user_groups_array,'id');
    $user_groups_label = array_column($user_groups_array, 'label'); 
    $user_group_options = array_combine($user_groups_name, $user_groups_label);

    $user_group_element = new \Phalcon\Forms\Element\Select("User Group", $user_group_options);
    $user_group_element->setLabel("<label for='User Group' >User Group: </label>");
}

My question? Is there a way to do transform a resultset into an \Phalcon\Forms\Element\Select in less lines?



24.1k
Accepted
answer
edited Jan '15

Maybe:

$form = new ProductReviewForm(UserGroup::find(array('columns' => 'id,label')));

...

public function initialize($user_groups)
{
    $user_group_options = [];

    foreach($user_groups as $userGroup)
    {
        $user_group_options[$userGroup->id] = $userGroup->label;
    }

    $user_group_element = new \Phalcon\Forms\Element\Select("User Group", $user_group_options);
    $user_group_element->setLabel("<label for='User Group' >User Group: </label>");
}


32.5k
edited Jan '15

RompePC - This looks less expensive to me. The way to go. Thanks.



24.1k

Also I think

$user_group_element = new \Phalcon\Forms\Element\Select(
    'User Group',
    UserGroup::find(['columns' => 'id, label']),
    'using' => ['id', 'label']
);

should do the trick.