我想从表单中的特定模型更新两个字段,并且仅更新两个字段。同一模型上还有许多其他字段,将在其他地方进行验证,但这两个字段采用不同的形式。
我需要它们匹配并且都存在。 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);
最初创建记录时似乎可以正常工作...但是仅更新这两个字段时,验证似乎不适用。
示例:
命名“蓬松兔子”,并确认并查看在数据库中创建的记录。验证会按预期进行-在确认输入中放入其他内容将返回设置的错误。
转到书名更新页面。
输入不匹配的书名并提交,保存新书名。没有引发错误。可以在数据库中看到显示的新值。如果尝试将浏览器留空,则抛出浏览器“一定不能为空”错误。
表格本身:
<?= $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'));
我想我可以在控制器中进行一些手动验证,但这似乎违反了设置整个验证模型的目的。我想念什么?
答案 0 :(得分:1)
直接设置值时,不执行验证;它假设您知道自己在做出这些价值观时在做什么。而是使用patchEntity
函数:
$book = $this->Books->patchEntity($book, $this->request->getData());