SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

How to display validation messages with multiple models in one form

CakePHP has built in data validation rules for its models. It will validate data when doing save(). By combining with its Form helper, it will display validation error messages automatically. In this tutorial, we will look at how to save multiple models using inside one form, and let form helper to display validation messages for us automatically.

Models' relationship

Let us assume we are building a user registration form and for each user, we will have one profile. So the relationship between User model and Profile model is one to one.

<?php
class User extends AppModel {
    var $name = 'User';
    var $validate = array(
        'name' => array(
            'notempty' => array(
                'rule' => array('notempty')
            ),
        ),
    );
     
    var $hasOne = array(
        'Profile' => array(
            'className' => 'Profile',
            'foreignKey' => 'user_id',
            'dependent' => false
        )
    );
 
}
?

<?php
class Profile extends AppModel {
    var $name = 'Profile';
    var $validate = array(
        'first_name' => array(
            'notempty' => array(
                'rule' => array('notempty')
            ),
        ),
        'user_id' => array(
            'numeric' => array(
                'rule' => array('numeric')
            ),
        ),
    );
 
    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        )
    );
}

For demo purpose, we create two simple database tables (users and profiles).You will need to create these two tables in your database if you wish to run this demo.

Create form

New what we need to do is to create a form to save the profile.

<?php echo $this->Form->create('Profile');?>
    <fieldset>
        <legend><?php __('Add Profile'); ?></legend>
    <?php
        echo $this->Form->input('User.name');
        echo $this->Form->input('first_name');     
    ?>
    </fieldset>
<?php echo $this->Form->end(__('Submit', true));?>

This form will be submitted to ProfilesControllers's add function. Note how we name the field "name" for User model.

Modify save() function

When working with one model, we will call model's save() function to save data. When working with associated multiple models. We will use saveAll(). But before calling saveAll(), we will need to unset the foreign key (user_id in our case) to prevent unexpected validation failure:

function add() {
        if (!empty($this->data)) {
            $this->Profile->create();
             
            unset($this->Profile->validate['user_id']);
            if ($this->Profile->saveAll($this->data)) {
                $this->Session->setFlash(__('The profile has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The profile could not be saved. Please, try again.', true));
            }
        }      
    }

That is all. Now when you try to create profile with empty data, the form should automatically show your error messages for both User and Profile's fields.

The end

Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.