Can Cake Php Validation clear input field value - cakephp

Can Cake Php Validation clear input field value
var $validate = array(
'name' => array(
'isUnique' => array (
'rule' => 'isUnique',
'message' => 'This Person name already exists.'
)
)
);
If error persist in validation, I want to clear name field value. Is it possible to do so with cake php validation itself ?

You can do it with a custom validation rule if you wanted.
var $validate = array(
'name' => array(
'isUnique' => array (
'rule' => 'ifNotUniqueClear', // use custom rule defined below
'message' => 'This Person name already exists.'
)
)
);
function ifNotUniqueClear(&$data) {
$field = key($data);
// see if the record exists
$user = $this->find('first', array(
'conditions' => array(
$field => $data[$field]
),
'recursive' => -1
));
if ($user) {
// unset or empty it, your choice
unset($this->data[$this->alias][$field]);
return false;
}
return true;
}

Related

Cake php modal validation error

I have a simple registration form and complete model validation.
public function add() {
// Has any form data been POSTed?
if ($this->request->is('post')) {
$this->User->set($this->request->data); //echo '<pre>'; print_r($this->data);exit;
if($this->User->validates()){
if ($this->User->save($this->request->data)) {
// Set a session flash message and redirect.
$this->Session->setFlash('User Saved!');
return $this->redirect('/users');
}
}
}
}
Modal validation code is below
class User extends AppModel {
public $validate = array(
'username' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
),
'email' => 'email',
'born' => array(
'rule' => 'date',
'message' => 'Enter a valid date',
'allowEmpty' => true
)
);
}
The problem is that when i delete html fields using firebug and submit form it save data with blank entries . i think its a big problem i am facing because it not good practice to save blank entry and i want to stop it by the hacker or any one.
please help.
Add the validation rule 'notEmpty' for all fields which shouldn't be blank entries in the database.
Reference: cookbook
I am agree with semmelbroesel13
please use notEmpty rules as:
'rule' => array('notempty')
Updated:
Please try below code and check whats the query exactly
public function add() {
// Has any form data been POSTed?
if ($this->request->is('post')) {
$this->User->set($this->request->data); //echo '<pre>'; print_r($this->data);exit;
if($this->User->validates()){
if ($this->User->save($this->request->data)) {
$log=$this->User->getDataSource()->getLog(false, false);
echo "<pre>";print_r($log);exit;
// Set a session flash message and redirect.
$this->Session->setFlash('User Saved!');
return $this->redirect('/users');
}
}
}
}

Simple CakePHP search action

I want a simple search feature that can search the current selected results on the model's index page. I have created a model Search which has no actual table:
class Search extends AppModel {
protected $_schema = array(
'search_term' => array('type' => 'string' , 'null' => true, 'default' => '', 'length' => '255'),
'model' => array('type' => 'string' , 'null' => true, 'default' => '', 'length' => '255'),
);
public $useTable = false;
public $validate = array(
'search_term' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter a search term'
),
'between' => array(
'rule' => array('between',3,30),
'message' => 'Please enter a search term greater than 3 characters.'
)
)
);
}
In any index.ctp view I have this with a hidden input field with the model's name:
echo $this->Form->create('Search, array('action' => 'search'));
echo $this->Form->input('search_term', array('label'=> 'Search'));
echo $this->Form->input('model', array('type'=> 'hidden', 'value'=>$this->params['controller']));
echo $this->Form->end(__('Submit'));
In the SearchesController:
public function search() {
$conditions = null;
if( $this->request->is('post') ) {
$searchModel = $this->request->data[$this->modelClass]['model'];
...
$this->{$this->modelClass}->useTable = Inflector::tableize($searchModel);
...
$this->paginate = array('conditions'=>array($groups,'OR' => $conditions));
$this->set($searchModel, $this->paginate());
$this->render("/$searchModel/index");
}
Problem is paginate is returning an array with the model labelled as 'Search' (understandably because of the useTable call) and not say Groups or Users, the model's being searched. Any way to relabel the array returned from paginate to the model being searched ? The alternative is to modify all the index.ctp files or create a results.ctp for each model.
I wouldn’t create another model merely for searching; it’s a hack and not extendable.
In the past, I’ve just used parameters (usually in the query string) to alter the conditions array (whether it’s a normal find operation of a paginate operation). An example:
<?php
class ItemsController extends AppController {
public function index() {
$conditions = array();
if (isset($this->request->query['search'])) {
$conditions['Item.title'] = $this->request->query['search'];
}
$items = $this->Item->find('all', array(
'conditions' => $conditions
));
$this->set(compact('items'));
}
}
Hopefully the above demonstrates this approach.

CakePHP: Keep the same checkboxes checked after submit

How can I keep the same checkboxes checked after submit? All the other input fields on the form automatically keeps the values. I thought this would also go for checkboxes, but nope.
echo $this->Form->input('type_id', array(
'multiple' => 'checkbox',
'options' => array(
'1' => 'Til salgs',
'2' => 'Ønskes kjøpt',
'3' => 'Gis bort'
),
'div' => false,
'label' => false
));
I believe this can be done in the controller, but how?
Edit:
Since I posted this question I've changed to CakeDcs Search plugin, because I've gotten this to work with that before. Still... I can't get it to work this time.
Adding model and controller code:
AppController
public $components = array('DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginAction' => '/',
'loginRedirect' => '/login',
'logoutRedirect' => '/',
'authError' => 'Du må logge inn for å vise denne siden.',
'authorize' => array('Controller'),
),
'Search.Prg'
);
public $presetVars = true; //Same as in model filterArgs(). For Search-plugin.
AdsController
public function view() {
$this->set('title_for_layout', 'Localtrade Norway');
$this->set('show_searchbar', true); //Shows searchbar div in view
$this->log($this->request->data, 'debug');
//Setting users home commune as default filter when the form is not submitted.
$default_filter = array(
'Ad.commune_id' => $this->Auth->user('User.commune_id')
);
$this->Prg->commonProcess(); //Search-plugin
$this->paginate = array(
'conditions' => array_merge($default_filter, $this->Ad->parseCriteria($this->passedArgs)), //If Ad.commune_id is empty in second array, then the first will be used.
'fields' => $this->Ad->setFields(),
'limit' => 3
);
$this->set('res', $this->paginate());
}
Model
public $actsAs = array('Search.Searchable');
public $filterArgs = array(
'search_field' => array('type' => 'query', 'method' => 'filterSearchField'),
'commune_id' => array('type' => 'value'),
'type_id' => array('type' => 'int')
);
public function filterSearchField($data) {
if (empty($data['search_field'])) {
return array();
}
$str_filter = '%' . $data['search_field'] . '%';
return array(
'OR' => array(
$this->alias . '.title LIKE' => $str_filter,
$this->alias . '.description LIKE' => $str_filter,
)
);
}
/**
* Sets the fields which will be returned by the search.
*
* #access public
* #return array Database table fields
* #author Morten Flydahl
*
*/
public function setFields() {
return array(
'Ad.id',
'Ad.title',
'Ad.description',
'Ad.price',
'Ad.modified',
'User.id',
'User.first_name',
'User.middle_name',
'User.last_name',
'User.link',
'User.picture_url',
'Commune.name',
'Type.id',
'Type.name'
);
}
You have to set manually the selected option of the input, as an array with "keys = values = intval(checkbox id)"
I cannot explain why this format, but this is the only way I get it to work.
Here is my code:
echo $this->Form->create('User');
// Read the submitted value
$selected = $this->Form->value('User.Albums');
// Formats the value
if (empty($selected)) {
$selected = array(); // avoid mess
} else {
$selected = array_map('intval', $selected);
$selected = array_combine ($selected, $selected);
}
// Renders the checkboxes
echo $this->Form->input('Albums',array(
'type' => 'select',
'multiple' => 'checkbox',
'options' => $albums, // array ( (int)id => string(label), ... )
'selected' => $selected, // array ( (int)id => (int)id, ... )
));
Hope this helps.
++

Validation defined in model - CakePHP

Using CakePHP 1.3 I developed engine for blog with posts and comments tables and recently I have noticed that in database I've got records with null values in content column despite of the fact that Comment model has defined proper validation:
<?php
class Comment extends AppModel {
var $name = 'Comment';
var $sequence = 'comments_seq';
var $belongsTo = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'post_id'
)
);
var $validate = array(
'content' => array(
'required' => array (
'rule' => 'notEmpty',
'message' => 'Content can't be empty.'
)
),
'post_id' => array(
'rule' => 'notEmpty'
),
'created' => array(
'rule' => 'notEmpty'
)
);
?>
Is there a bug in CakePHP framework or validation defined above is not correct or insufficient?
In your validation rules, you're not actually requiring the field. Requiring means that the key must exist when it comes time to validate. The notEmpty rule requires only that the key is not empty but not that it exists.
To require that the field exists, use the required option in your validation rules:
var $validate = array(
'content' => array(
'required' => array ( // here, 'required' is the name of the validation rule
'rule' => 'notEmpty',
'message' => 'Content can\'t be empty.',
'required' => true // here, we say that the field 'content' must
// exist when validating
)
),
'post_id' => array(
'rule' => 'notEmpty'
),
'created' => array(
'rule' => 'notEmpty'
)
);
Without the required key, you could potentially save completely empty records by simply not including the 'content' key when saving. Now that it is required, validation will fail if 'content' is not in the data that you're saving.

CakePHP 2.1 - testing a simple admin_add() controller action

New to unit testing... testing an articles controller and I am getting a fail on the $this->assertNotEmpty();
Shouldn't this be displaying an array full of validation errors? Instead I am getting an empty array.
It seems my validation rules are not being picked up... as further inspection show that Article::save() is returning true on data that should fail....
/**
* Admin Add
* #see controllers/MastersController::_admin_add()
* #return void
*/
public function admin_add(){
//parent::_admin_add();
if(!empty($this->request->data){
$this->Article->save($this->request->data);
}
}
/**
* Test Admin Add
*
* #return void
*/
public function testAdminAdd() {
#define sample passing data
$sampleDataPass = array(
'Article'=>array(
'title'=>'Test Article Add Will Pass',
'body'=>'Test Article Add Body',
'status_id'=>1,
'category_id'=>1,
)
);
#test action
$this->testAction('admin/articles/add', array('data'=>$sampleDataPass));
$this->assertEmpty($this->Articles->Article->validationErrors); #####PASSES#####
#define sample failing data
$sampleDataFail = array(
'Article'=>array(
'title'=>'Test Article Add Will Fail',
)
);
$this->testAction('admin/articles/add', array('data'=>$sampleDataFail));
$this->assertNotEmpty($this->Articles->Article->validationErrors); #####FAILS#####
}
class Article extends AppModel {
/*
* Name
*/
public $name = 'Article';
/*
* Validation Rules
*/
public $validate = array(
'title' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'You must supply an article title in order to save.',
),
),
'body' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'You must supply an article title in order to save.',
),
),
'status_id' => array(
'numeric' => array(
'rule' => array('numeric'),
'message' => 'You must choose a status.',
'allowEmpty' => false,
),
),
'category_id' => array(
'numeric' => array(
'rule' => array('numeric'),
'message' => 'You must choose a category.',
'allowEmpty' => false,
),
)
);
}
CakePHP will ignore validation rules if the field is not present in the data.
By setting the option 'required' to true the validation rule will always be checked.
For example:
'title' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'You must supply an article title in order to save.',
'required' => true
),
),
Documention on validation in CakePHP can be found here: http://book.cakephp.org/2.0/en/models/data-validation.html#one-rule-per-field

Resources