蛋糕填充模型的下拉列表

时间:2013-05-30 12:51:08

标签: cakephp

我正在尝试使用一些选项填充dropdpwn。我正在尝试为我的输入表单下载名称标题和国家/地区列表。

例如:

标题我需要'先生','太太','小姐'

我试过方法:

模型

// Built a list of search options (unless you have this list somewhere else)
public function __construct($id = false, $table = null, $ds = null) {
$this->titles = array(
             0 => __('Mr', true),
             1 => __('Mrs', true),
            2 => __('Miss', true));
 parent::__construct($id, $table, $ds);
 }

控制器

public function add() {
    if ($this->request->is('post')) {
        $this->Member->create();
        if ($this->Member->save($this->request->data)) {
            $this->Session->setFlash(__('The member has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The member could not be saved. Please, try again.'));
        }
    }
}

查看

<?php echo $this->Form->input('title',array('class' => 'span10', 'options' => $titles   )); ?>

我收到错误Undefined variable:titles

我也试过模型

public $validate = array(
    'member_no' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'title' => array(
        'titlesValid' => array(
            'rule' => array('multiple', array(
                'in'  => array('Mr', 'Mrs', 'Miss'),
                'min' => 1
            )),

我缺少的是什么,对于更长的列表(例如国家/地区)最好的解决方案,它只是在表单上,​​所以我认为我不需要标题和国家/地区表和链接ID?

1 个答案:

答案 0 :(得分:3)

我觉得很奇怪你必须在下拉列表的模型构造中创建一个变量。特别是如果你只打算使用一次。

但首先要做的事情。您收到该错误是因为您尚未将变量设置为视图。在你的控制器中,需要有这样的东西:

public function add() {
    $this->set('titles', $your_titles_array);
    if ($this->request->is('post')) {

    //etc

现在,请从那里获取下拉阵列。有两个可能更好的地方。我不会挑剔地说你需要将这些值作为数据库中的表格。如果你说这只是一个地方而你想要硬编码,那就这样吧。

一种选择是将其放在一个模型中,例如

class YourModel extends AppModel {
    //all your other definitions

    public function getTitles() {
        return array(
         0 => __('Mr', true),
         1 => __('Mrs', true),
        2 => __('Miss', true));
    }
}

在控制器中执行

    public function add() {
    $this->set('titles', $this->YourModel->getTitles());
    if ($this->request->is('post')) {

    //etc

但是,我认为您没有合适的模型来添加该功能。您打算在哪里添加它?用户模型可能吗?例如,它不能像Post模型那样没有任何意义......所以,给它一个想法,如果模型中有逻辑位置你可以放置该函数,那么继续。

否则,如果只是一次只在一个地方使用一个表单,为什么不将它硬编码到视图或控制器?

对于较大的列表,我的建议是在我所展示的模型中进行(但我坚持认为,把它放在模型中,这是合乎逻辑的)。好吧,我宁愿有一个表并引用这些值,但它不是强制性的(虽然给它一个想法,实际上没那么多工作,是吗?对于更大的列表,我的意思)。

相关问题