Unbind Model Validation in CakePHP Unbind Model Validation in CakePHP

Have you found yourself wanting to remove validation on a specific field in a specific form?� Yes?� Excellent, you found the right place.

If you haven't had the need for this, a great example of where you would want to accomplish this would be in a users edit form.� Normally in CakePHP we would encrypt the password, especially if you are using the AuthComponent, so we wouldn't want the password prefilled on our form.� Instead, we'll make it blank and place a note underneath that says "Only enter a password if you wish to change it".

The above shouldn't be difficult, however, when you go to use the form, you will get some unexpected results.� I keep getting a message saying that I must enter a password, because I had setup validation on that field for the registration process.� Below is a simple solution to this problem.


The solution is really quite simple.� By default the password field will be in the $this->data when you submit the form.� To remove validation, you need to unset() the value from the variable you pass to the save() function.� Below is an example of how to accomplish this:

if (empty($this->data['User']['password'])) {
�� unset($this->data['User']['password']);
}

As long as we unset() the field, CakePHP will not validate our field.� This one was a bit tricky for me at first and I was looking for more complicated solutions, until I found this easy answer.� Hopefully, I have saved you some time with this.

If you find yourself utilizing this quite frequently and potentially multiple times inside your controller (or beforeValidate() callback function) I would suggest creating a function that performs this for you.� Perhaps a function that accepts a single value or an array of values as well as your $this->data and then have the function loop through each array item and unset() the values that you told it to, if they are empty.

I invite anyone to share a function similar to this, if you have one.

Published on Mar 28, 2009

Tags: CakePHP Tutorial | validation

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.