[英]Not able to Validation data in Yii2 model
我無法驗證 model 中的值。我是新手,任何人都可以建議我做錯了什么。 我正在處理 REST API 和 excel 文件上傳並一次驗證單行
這是我在 model 中的數據和負載數據
$data = array(
'firstName' => 'asdjqkw',
'lastName' => '',
'email' => 'ansm@',
'companyName' => 'ddq',
'address_1' => '',
'address_2' => 'aas',
'country' => '',
'state' => 'New Brunswick',
'city' => '87875',
'zip' => '484527',
);
$model->load($data);
if (!$model->validate()) {
$validation = $model->errors;
}
這是我定義的 model 規則和屬性標簽,其中包含 email 和最大長度驗證,但仍有一些值可用,但它仍在為該字段發送必需的驗證錯誤
public function rules() {
return [
[['firstName', 'lastName', 'email', 'companyName', 'address_1', 'country', 'state', 'city', 'zip'], 'required'],
['email', 'email'],
[['firstName', 'lastName', 'email', 'companyName', 'address_1', 'country', 'state', 'city', 'zip'], 'string', 'max' => 250],
];
}
public function attributeLabels() {
return [
'firstName' => 'First Name',
'lastName' => 'Last Name',
'email' => 'Email',
'companyName' => 'Company Name',
'address_1' => 'Address 1',
'country' => 'Country',
'state' => 'State',
'city' => 'City',
'zip' => 'Zip',
];
}
加載此數據后出現驗證錯誤
"firstName": [
"First Name cannot be blank."
],
"lastName": [
"Last Name cannot be blank."
],
"email": [
"Email cannot be blank."
],
"companyName": [
"Company Name cannot be blank."
],
"address_1": [
"Address 1 cannot be blank."
],
"country": [
"Country cannot be blank."
],
"state": [
"State cannot be blank."
],
"city": [
"City cannot be blank."
],
"zip": [
"Zip cannot be blank."
]
所以這里發生的事情是您正在調用 model 的加載方法。它有 2 個 arguments,第一個是您的數據,第二個是 formName。 當沒有聲明 formName 參數時,Yii2 會將其設置為等於您的 model。因此在這種情況下,它會嘗試像這樣加載數據:$data['modelName']。 因此,您可以更改數據數組以遵循以下格式:
$data = array(
'yourModel' => [
'yourData => 'yourValue'
]
)
但是有一個更簡單的方法,不需要我們經常記住如何構造我們的數據 arrays:將 'load' 方法的 'formName' 參數設置為空字符串。 這樣做的原因是它允許以下代碼在“加載”方法中運行:
if ($scope === '' && !empty($data)) {
$this->setAttributes($data);
return true;
}
這樣我們就可以繼續在一個更少的維度上編寫我們的 arrays,這是一種讓我們的 arrays 保持整潔的小而好的方法:)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.