Kevin Tabada
Kevin Tabada

Reputation: 25

Inserting with empty string in cakePHP

i am new in cakePHP framework with version 2.0 my problem is when i save the data or insert the new record the field is empty or no data to be save how can i fix this. .

My Model

class Post extends AppModel{
    public $name = 'posts';
} 

My Controller

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');
        }       
    }
}

My View

echo $this->Form->create('Create Posts');
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Save Posts');

Upvotes: 0

Views: 283

Answers (1)

Supravat Mondal
Supravat Mondal

Reputation: 2584

You need to put the validation rules in the Post model, Then you can check validate data or not in the controller action before save into model. See the following Model and controller

In Model

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'
            ),            
        ),
    );
} 

In Controller

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;
        }       
    }
}

Upvotes: 1

Related Questions