简体   繁体   中英

Phalcon validation messages on related (aliased) models

Assuming I try to save the following data and the Songs model's name attribute has a Phalcon\\Mvc\\Model\\Validator\\PresenceOf validator set on it

// Get an existing artist
$artist = Artists::findFirst('name = "Shinichi Osawa"');

// Create an album
$album          = new Albums();
$album->name    = 'The One';
$album->artist  = $artist;

$songs = array();

// Create a first song
$songs[0]           = new Songs();
$songs[0]->name     = 'Star Guitar';
$songs[0]->duration = '5:54';

// Create a second song
$songs[1]           = new Songs();
$songs[1]->name     = '';
$songs[1]->duration = '4:29';

// Assign the songs array
$album->songs = $songs;

// Save the album + its songs
if (!$album->save()) {
    foreach ($album->getMessages() as $message) {
        $message->getModel(); // this returns null since model is new
    }
}

I will get an error message saying that 'name' is required.

Question: is there a built in way of getting the related model on which the error occurred (in this case $songs[1] ), or at least the alias/index of the error model (in this case songs/1)?

Didn't find a built-in solution but came up with this.

Base model

public function beforeValidation()
{
    $session = $this->getService('session');

    if (!$session->has('model:validation')) {
        $validation = $indexes = [];
    } else {
        $modelName = get_called_class();
        $validation = $session->get('model:validation');
        if (!isset($validation[$modelName])) {
            $validation[$modelName] = 0;
            $indexes = $session->get('model:validation:relationIndex');
            $indexes[] = $modelName;
        } else {
            $validation[$modelName]++;
            // reset child indexes
            $indexes = $session->get('model:validation:relationIndex'); 
            $modelIndex = array_search($modelName, $indexes);
            for ($i = $modelIndex + 1; $i < count($indexes); $i++) {
                $modelName = $indexes[$i];
                unset($validation[$modelName]);
                unset($indexes[$i]);
            }
            $indexes = array_values($indexes);
        }
    }

    $session->set('model:validation:relationIndex', $indexes);
    $session->set('model:validation', $validation);
}

Controller

$session = $this->getDI()->get('session');
$session->remove('model:validation');
$session->remove('model:validation:relationIndex');

if (!$this->save()) {
    var_dump($session->get('model:validation:relationIndex'));
    var_dump($session->get('model:validation'));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM