[英]Can Laminas Dependency Plugin be removed after the migration from ZF3 to Laminas?
[英]Laminas / ZF3: Add manually Error to a field
是否可以在字段驗證和輸入過濾器之后手動向字段添加錯誤消息?
如果用戶名和密碼錯誤,我需要它來標記這些字段/顯示錯誤消息。
顯然在 ZF/ZF2 中可以使用$form->getElement('password')->addErrorMessage('The Entered Password is not Correct');
- 但這在 ZF3/Laminas 中不再起作用
在不知道如何進行驗證的情況下(實際上有幾種方法),最干凈的解決方案是在創建 inputFilter 時設置錯誤消息(而不是在元素添加到表單后將其設置為元素)。
請記住,表單配置(元素、水合器、過濾器、驗證器、消息)應在表單創建時設置,而不是在使用時設置。
此處表單被擴展(使用其輸入過濾器),如文檔中所示:
use Laminas\Form\Form;
use Laminas\Form\Element;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\NotEmpty;
class Password extends Form implements InputFilterProviderInterface {
public function __construct($name = null, $options = []) {
parent::__construct($name, $options);
}
public function init() {
parent::init();
$this->add([
'name' => 'password',
'type' => Element\Password::class,
'options' => [
'label' => 'Password',
]
]);
}
public function getInputFilterSpecification() {
$inputFilter[] = [
'name' => 'password',
'required' => true,
'validators' => [
[
'name' => NotEmpty::class,
'options' => [
// Here you define your custom messages
'messages' => [
// You must specify which validator error messageyou are overriding
NotEmpty::IS_EMPTY => 'Hey, you forgot to type your password!'
]
]
]
]
];
return $inputFilter;
}
}
還有其他方法可以創建表單,但解決方案是相同的。
我還建議你看看laminas-validator 的文檔,你會發現很多有用的信息
Laminas Laminas\Form\Element
class 有一個名為setMessages()的方法,它需要一個數組作為參數,例如
$form->get('password')
->setMessages(['The Entered Password is not Correct']);
請注意,這將清除您的元素可能已有的所有錯誤消息。 如果你想像舊的addErrorMessage()
方法一樣添加你的消息,你可以這樣做:
$myMessages = [
'The Entered Password is not Correct',
'..maybe a 2nd custom message'
];
$allMessages = array_merge(
$form->get('password')->getMessages(),
$myMessages);
$form
->get('password')
->setMessages($allMessages);
您還可以使用錯誤模板名稱 Laminas 用於其錯誤消息作為消息數組中的鍵來覆蓋特定的錯誤消息:
$myMessages = [
'notSame' => 'The Entered Password is not Correct'
];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.