Thursday, July 14, 2011

Validation Tips and Tricks

When using validation, as mentioned previously, there are some tricks to automatically adding the class required to your form fields. Any validation rule that has minlength works. So a short, simple rule to just ensure the required class is added to the field label could look something like this:
    var $validate = array(
        'field_name' => array(
            'rule' => array('minlength', 1)
        )
    );
If you want to require user input but don't care about the required class for your labels, you can actually use something as simple as this:
    var $validate = array(
        'field_name' => 'notEmpty'
    );
If you expand that to the following code, however, you will also get the required class for your field label.
    var $validate = array(
        'field_name' => array(
            'rule' => 'notEmpty'
        )
    );
This is very useful when you want the required class for select fields.

Wednesday, July 13, 2011

Model: User: Display Name

When adding a record that has a relationship of "belongs to" with another table as mentioned previously, CakePHP automatically lists the records of the other table using the display name of that model. By default that display name field is "name". However, if your field doesn't have a "name" field, such as the Users table, you can specify the display name manually in the model.

Edit app/models/user.php and add the following line:
    var $displayField = 'username';
This does not support multiple fields, for example if you wanted to combine first_name and last_name. In order to do this you need to use virtualFields in your model. Virtual fields allow you to access a created field, but you cannot save it.

Edit app/models/user.php and add the following line:
    var $virtualFields = array( 'full_name' => "CONCAT(User.first_name, ' ', User.last_name)");
then change the display field from username to full_name.