Add validation filters before saving in Solar
Posted in PHP, Solar, Uncategorized on October 22nd, 2010 by Jon – Be the first to commentI have preached about how Solar makes my web development life so much easier, and here is another example of why.
Every once in a while, I have to add or modify my record validation before it is saved in the database. For example, I am working on a publication database where a publication has several availability “flags”, such as
- available as pdf,
- available in print,
- available as pdf by email
In this scenario, all three can be “unchecked”, however; available as pdf and available as pdf by email can NOT both be checked. So, to validate that, I use a pre-save hook in the publication record class and set a filter.
<?php class Bookstore_Model_Publications_Record extends Bookstore_Sql_Model_Record { protected function _preSave() { parent::_preSave(); // Check to make sure that email_pdf and pdf are not both checked if ($this->_data['available_pdf'] == '1' && $this->_data['available_pdf_email'] == '1') { $this->addFilter( 'available_pdf_email', 'validateNotEquals', 'available_pdf' ); } } } } ?>
So, basically, before the record is saved, I look to see if available_pdf == 1 AND available_pdf_email == 1 and if so, add a new validation filter on available_pdf_email. The new filter is called “validateNotEquals” and you pass the name of a field you don’t want to allow it to be the same as. In this case available_pdf.
With this filter added, the record won’t save and will display an error message under available_pdf_email.
Simple.