我有一个与表UserDetail相关的用户表。User(#id, name, password) UserDetail(#id, address, city, user_id)
UserDetail.user_id是链接到User.id的外键。
如果我想添加一个新的地址,这是我把我的地址放在那里的表格:
<?php echo $this->Form->create('UserDetail');?>
<?php echo $this->Form->hidden('id'); ?>
<?php echo $this->Form->input('address', array('class' => 'form-control')); ?>
<?php echo $this->Form->input('city', array('class' => 'form-control')); ?>
<?php echo $this->Form->hidden('user_id'); ?>
<?php echo $this->Form->button('Modifier', array('class' => 'btn btn-primary')); ?>
<?php echo $this->Form->end(); ?>我的控制器:
public function customer_edit($id = null){
if (!$this->User->exists($id)) {
throw new NotFoundException('Invalid user details');
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->request->data['UserDetail']['user_id'] = $id;
if ($this->User->UserDetail->save($this->request->data)) {
$this->Flash->success('Done!');
return $this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash('Error.');
}
}
}我总有一个闪光灯“错误”。if ($this->User->UserDetail->save($this->request->data))不工作。如果我看一下$request->data和DebugKit,我就有了所有的输入数据。
添加一张新唱片行不通..。问题出在哪里?
谢谢。
编辑:这是我的UserDetail类:
class UserDetail extends AppModel {
public $validate = array(
'id' => array(
'numeric' => array(
'rule' => array('numeric')
),
),
'address' => array(
'notempty' => array(
'rule' => array('notempty'),
'allowEmpty' => false,
),
),
'city' => array(
'notempty' => array(
'rule' => array('notempty'),
'allowEmpty' => false,
),
),
'user_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => '',
'counterCache' => true,
'counterScope' => array(),
)
);
}以及UserDetail发布的数据内容:
>UserDetail
id
地址测试
市试验
user_id 19
发布于 2015-12-03 09:37:06
通常,您不希望为主键模型::id设置验证规则。但是,如果这样做,则必须只在更新记录时强制执行,而不是在创建记录时强制执行(在这种情况下,它是空的)。
尝试重写验证数组,如下所示:
public $validate = array(
'id' => array(
'numeric' => array(
'rule' => array('numeric'),
'on' => 'update' //don't enforce rule on create
),
),
'address' => array(
'notempty' => array(
'rule' => array('notEmpty'),
'allowEmpty' => false,
),
),
'city' => array(
'notempty' => array(
'rule' => array('notEmpty'),
'allowEmpty' => false,
),
),
'user_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);顺便说一句,将'rule' => array('notEmpty')和'allowEmpty' => false放在相同的规则中是多余的。你可以删除后者。
说了这些之后,我建议你重新考虑你的观点和行动,因为它们似乎并没有像我想的那样表现出来。
https://stackoverflow.com/questions/34047031
复制相似问题