我是带有版本2.0的cakePHP框架的新手,我的问题是当我保存数据或插入新记录时,字段为空或没有数据要保存我该如何解决这个问题。
我的模特
class Post extends AppModel{
public $name = 'posts';
}
我的控制器
public function add(){
if($this->request->is('post')){
$this->Post->create();
if($this->Post->save($this->request->data)){
$this->Session->setFlash('The posts was saved');
$this->redirect('index');
}
}
}
我的观点
echo $this->Form->create('Create Posts');
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Save Posts');
答案 0 :(得分:1)
您需要将验证规则放在Post
模型中,然后您可以在save
之前在控制器操作中检查验证数据到模型中。请参阅以下Model
和controller
在模型中
class Post extends AppModel{
public $name = 'posts';
public $validate = array(
'title' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'This is can'\t blank'
),
),
'body' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'This is can'\t blank'
),
),
);
}
在控制器中
public function add(){
if($this->request->is('post')){
$this->Post->create();
$this->Post->set($this->request->data);
if ($this->Post->validates()) {
// it validated logic
if($this->Post->save($this->request->data)){
$this->Session->setFlash('The posts was saved');
$this->redirect('index');
}
} else {
// didn't validate logic
$errors = $this->Post->validationErrors;
}
}
}