我想从表单中的特定模型更新两个字段,并且只更新两个字段。同一模型上还有许多其他字段将在其他地方得到验证,但这两个字段是在一个单独的表单上。
我需要他们匹配,两者都存在。 book_name_confirm
未保存在数据库中。
$validator
->scalar('book_name')
->maxLength('book_name', 255)
->requirePresence('book_name')
->sameAs('book_name_confirm', 'book_name', 'Book names must match')
->allowEmptyString('book_name', false);
这在最初创建记录时似乎工作正常......但是当更新这两个字段时,验证似乎不适用。
例:
名书“蓬松的兔子”,确认,看在数据库中创建的记录。验证按预期发生 - 在确认输入中放入任何其他内容将返回设置错误。
转到图书名称更新页面。
输入不匹配的书名并提交,保存新书名。没有错误抛出。可以在DB中看到显示的新值。如果您尝试将其留空,则抛出浏览器“一定不能为空”错误。
表格本身:
<?= $this->Form->create($book) ?>
<fieldset>
<?php
echo $this->Form->control('book_name');
echo $this->Form->control('book_name_confirm', array('label' => 'Confirm book name'));
?>
</fieldset>
<?= $this->Form->button(__('Set new book name')) ?>
<?= $this->Form->end() ?>
和控制器:
if ($this->request->is(['patch', 'post', 'put'])){
//bookTracking is passed through URL, is a UUID
$bookQuery = $this->Books->find('all')
->where(["tracking =" => $bookTracking]);
$book = $bookQuery->first();
//stuff here to handle missing books
$book->book_name = $this->request->getData("book_name");
$book->book_name_confirm = $this->request->getData("book_name_confirm");
$this->Books->save($book);
//redirect
}
$book = $this->Books->newEntity();
$this->set(compact('book'));
我想我可以在控制器中做一些手动验证,但这似乎打败了设置整个验证模型的目的。我错过了什么?
直接设置值时,不执行验证;它假设你在制作这些价值时知道自己在做什么。相反,使用patchEntity
函数:
$book = $this->Books->patchEntity($book, $this->request->getData());