开发者

CakePHP form $options['options']

Hey! Total CakePHP noob here.

Updated at bottom /

This is sort of a two fold question. In a view that is used for adding user objects I would like to use a drop down (selection) field in the form.

Each user belongs to a group so when I add a user I want a drop down that contains all of the groups that the user could possibly join. Currently the group_id field is a textfield. I know how to force it to be a selection field, but I don't know how to populate the selection with the names of the groups programmatically.

The Current method:

echo $form->input('group_id', array(
    '1' => 'NameOfGroup1',
    '2' => 'NameOfGroup2',
    '3' => 'NameOfGroup3')
    );

I want to generate the options array programmatically though.

echo $form->input('group_id', $this->Group->find('list'));

This doesn't work though. 开发者_运维知识库I get an error:

Undefined property: View::$Group [APP/views/users/add.ctp, line 8]

To me this means that I don't have access to the Group object from inside my user view.

How can I accomplish this? Again, I want to do it programmatically so that it updates as I add groups or remove them.

EDIT: Why doesn't this work?

// In views/users/someaction.ctp
echo $form->input('group_id',
                  array('options' => $this->formOptionsGroups)
                  );

// In controllers/users_controller.php
function someaction() {
    // Any other logic
    $this->set('formOptionsGroups', $this->Group->find('list'));
}

Error is that Group is an undefined object.


I think it's not necessary to use the requestAction function in your situation.Because you can get the grouplist in your users controller easily then assign it to your user-add page where you need it.That would be more graceful.

BTW,about requestAction from the cookbook: requestAction is best used in conjunction with (cached) elements – as a way to fetch data for an element before rendering.

E.g

/*code In the your user-add action of the users controller*/
function useradd()
{
    ......
    //your ownstuff skipped

    $grouplist = $this->User->Group->find('list');
    $this->set("grouplist",$grouplist);   
}

Then in your view of the useradd action :

echo $form->input('group_id', $grouplist);


The problem was with how I was requesting the action in the controller.

A correct implementation is:

echo $form->input('group_id', 
                  array('options' => $this->requestAction(array('controller' => 'groups', 'action' => 'formSelectOptions')))
                  );

And then in the groups controller:

// formSelectOptions() returns array for use with a form $options['options']
function formSelectOptions() {
    return $this->Group->find('list');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜