Showing posts with label cakephp. Show all posts
Showing posts with label cakephp. Show all posts

Monday, December 17, 2012

Modificating validation rules in the CakePHP Models

There are many cases in which you need to add, modify or remove some validation rules that has already been set in the model. I was looking around how to do it and I found a good way to do it using the beforeValidate() callback form the model.

In my case I needed to save mora than one type of user, in one of them I didn't need to save the email address, but in the other case I did need it. This was the validation rule:

 'email' => array(  
  'rule'  => array('email', true),  
  'message' => 'Please supply a valid email address.'  
 )  

So what I did was to set this in the model:

 public function beforeValidate($options = array()) {  
  parent::beforeValidate($options);  
  if (($this->data['User']['group_id'] == STUDENT) && empty($this->data['User']['email'])){  
   $this->validator()->remove('email');  
  }  
 }  

With this I got to tell what type of user was being saved and if it was a "STUDENT" type of user and the email field was empty the rule for email was removed.

I hope you can use this.

Tuesday, June 1, 2010

Using ajax or another layout

Sometimes we want to render a view with the ajax layout, but only when it is been showed because an ajax request. I used to make two different views, and some times two different actions. But I realized that there is a component that help us tell when the call comes from an ajax request.

The component is the RequestHandler, to use it you have to set it on the controller, like this:
class ExamplesController extends AppController{
   var $components = array('RequestHandler');
and in the action we want to tell if it is an ajax call we have to set:
function myaction(){
   $this->layout = $this->RequestHandler->isAjax()?'ajax':'default';
so if it is an AJAX call the layaout that will be used is the ajax layout. By the way, this is a layout that comes with CakePHP, you don't need to create it. And you also can use any other layout you create.