-3

If condition is true it should show an error message "already exits" or else a message "successful" should be displayed.

Is it possible to add a validation like this to the model part:

$name = $_POST["name"];
$validation_sql = "SELECT COUNT(*) > 0 FROM college WHERE status='2' AND name='$name'"; 
DIDoS
  • 812
  • 9
  • 23
user12342
  • 107
  • 2
  • 12
  • 2
    Please read the manual section on [Validation](http://book.cakephp.org/2.0/en/models/data-validation.html). The rule you need is [isUnique](http://book.cakephp.org/2.0/en/models/data-validation.html#Model::Validation::isUnique). – Inigo Flores Jan 04 '16 at 11:16
  • 1
    How can you use three two CakePHP versions at the same time? Tag your stuff properly! – floriank Jan 04 '16 at 13:52

3 Answers3

0

You can use hasAny() as the solution:

$conditions = array(
    'status'=>'2',
    'name'=>$name
);
if ($this->XXXXXXX->hasAny($conditions)){
    //do something
}

hasAny will return true if found else false.

NOTE: hasAny is not available in version 3.x

AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57
0

You can add server validation in model like:

public $validate = array(
    'name' => array(
        'rule' => array('isUnique', array('name'), false),
        'message' => 'This name has already been used.'
    )
);
Er.KT
  • 2,852
  • 1
  • 36
  • 70
0

It is not recommended to use $_POST in CakePHP at all, rather use the Request Object in the controller to access the data given by a POST request:

$this->request->data['College']['name'];

This information can then be passed to the model where it is validated.

If the post request has been created by the CakePHP form helper you don't need to access it - you can directly pass the data to the save method of the model instance (see CakePHP Handbook - Saving your data).

if ($this->College->save($this->request->data)) {
// handle the success (Normally success flash)
}
debug($this->College->validationErrors); //Normally error flash - if FormHelper is used the error messages are automatically shown beside the input elements

The validations can be added with the Bake Console or manually by adding validation rules to the College Model code:

public $validate = array(
    'name' => array(
        'rule' => 'isUnique',
        'message' => 'This username has already been taken.'
    )
);
DIDoS
  • 812
  • 9
  • 23