cakephp - belongsTo模型的表单

时间:2012-12-04 11:02:38

标签: database forms cakephp model

我创建了以下模型来链接2个关系表:

    class Ficha extends AppModel {

    //public $useTable = 'ficha_seg';

    var $primaryKey = 'id_ficha';

    var $name = 'Ficha';
    var $belongsTo = array(
        'Perigo' => array(
            'className'    => 'Perigo',
            'foreignKey'   => false,
            'conditions' => 'Perigo.id_fichas = Ficha.id_ficha'
        )
    );
}

现在,我有一个需要来自Ficha类的数据的表单,然后被重定向到另一个ctp页面,在那里我将输入表“Perigos”的数据。然而,因为我仍然是cakephp的新手,我有困难的建筑,第二种形式将数据插入“Perigos”表。这里是我与第二种形式相关的代码:

FichasController.php(它应该将数据保存在表“Perigos”上的方法:

public function preencher_ficha(){

if ($this->request->is('ficha')) {
        $this->Ficha->create();

    if ($this->Ficha->Perigo->save($this->request->data)) {
        $last_id=$this->Ficha->getLastInsertID();
        $this->Session->setFlash('Your post has been updated '.$last_id.'.');
        //$this->redirect(array('action' => 'preencher_ficha'));
    } else {
        $this->Session->setFlash('Unable to qualquer coisa your post.');
    }
}   
}

preencher_ficha.ctp文件,格式为:

echo $this->Form->create('Ficha->Perigo', array('action' => 'index'));
echo $this->Form->input('class_subst', array('label' => 'Classificação:'));
echo $this->Form->input('simbolos_perigo', array('label' => 'Símbolos:'));
echo $this->Form->input('frases_r', array('label' => 'Frases:'));
echo $this->Form->end('Finalizar Ficha'); 

这里我猜创建部分是错误的,但我认为控制器部分也有错误。

1 个答案:

答案 0 :(得分:1)

我建议您以其他方式构建视图。 如果要在Perigos表中保存数据,请使用save的{​​{1}}方法,并使用Perigos视图中的PerigosController文件显示您要使用的表单

无论如何,如果您想以自己的方式进行,您的表单应指向save.ctp函数来提交数据:

preencher_ficha

另外,你必须改变这个:

echo $this->Form->create('Ficha->Perigo', array('action' => 'preencher_ficha'));

到此

if ($this->request->is('ficha')) {

这只是一种检查数据是来自POST方法还是来自GET方法的方法。

而且,只是一个建议:不要使用控制器或模型的西班牙名称。如果你使用英文版,那么遵循CakePHP命名约定会更简单,它会更有意义,它可以节省你一些时间。