from表单中,如果有个字段是不希望保存的,需要在form->ignore中设置对应的字段。ignore的目的应该只是限制字段的保存,不限制字段的处理。
比如密码的修改,需要校验新密码new_password和旧密码password。但是如果设置了忽略new_password字段,则在saving回调中取不到new_password的值。如果不设置忽略new_password,则sql报错。
参考controller中form方法,其中一部分代码为:
$form->saving(function (Form $form) {
// 此处取不到new_password的值。
$newPassword = trim($form->new_password);
if (strlen($newPassword) > 0) {
$salt = $form->salt;
$form->password = sha1($salt . $newPassword);
}
});
$form->ignore(['new_password']);
修改vendor/encore/laravel-admin/src/Form.php文件,prepare方法:
$this->inputs = $this->removeIgnoredFields($this->inputs); 逻辑后移。
修改前:
protected function prepare($data = [])
{
if (($response = $this->callSubmitted()) instanceof Response) {
return $response;
}
$this->inputs = $this->removeIgnoredFields($data);
if (($response = $this->callSaving()) instanceof Response) {
return $response;
}
$this->relations = $this->getRelationInputs($this->inputs);
$this->updates = array_except($this->inputs, array_keys($this->relations));
}
修改后的方法:
protected function prepare($data = [])
{
if (($response = $this->callSubmitted()) instanceof Response) {
return $response;
}
$this->inputs = $data;
if (($response = $this->callSaving()) instanceof Response) {
return $response;
}
$this->inputs = $this->removeIgnoredFields($this->inputs);
$this->relations = $this->getRelationInputs($this->inputs);
$this->updates = array_except($this->inputs, array_keys($this->relations));
}
所有提交的参数都可以通过Laravel内置的request()方法取到
request('new_password');
如果我需要根据某些字段的值,判断是否忽略其他字段,l逻辑后移是不是更好一点?
需求是在 saving 通过判断 password 字段是否为空,为空则不保存,不为空则 Hash::make 后保存
Most helpful comment
所有提交的参数都可以通过Laravel内置的
request()方法取到