[英]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 假设我尝试保存以下数据,并且Songs模型的name属性上设置了Phalcon \\ Mvc \\ Model \\ Validator \\ PresenceOf验证器
// 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)? 问题:是否有内置的方式来获取发生错误的相关模型(在本例中$songs[1]
),或者至少获取错误模型的别名/索引(在本例中为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'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.