php - Validation for form
Get the solution ↓↓↓Please help with setting rules (). The thing is, I have a form. Where 2 fields are present. If all fields are empty, the form cannot be submitted, but if at least ONE is not empty, then the form can be submitted. Can you help me please, I'm new at it?
Here's my form
<?php $form = ActiveForm::begin() ?>
$form->field($model, 'field1')->textInput();
$form->field($model, 'field2')->textInput();
<?php $form = ActiveForm::end() ?>
And this's my model, but this rule does not quite suit me. Because the rules require you to fill in all the fields. And the main thing for me is that at least one, but was filled, so i could send the form. If ALL fields are empty, then validation fails.
public function rules()
{
return [
[['field1', 'field1'], 'require'] ]}
Should I add something in controller maybe?
Answer
Solution:
You haveTYPO
in rules: userequired
public function rules()
{
return [
[['field1', 'field1'], 'required']
];
}
Answer
Solution:
You can use property to decide whether the rule should or shouldn't be applied.
public function rules()
{
return [
[['field1'], 'required', 'when' => function ($model) {
return empty($model->field2);
}]
[['field2'], 'required', 'when' => function ($model) {
return empty($model->field1);
}]
];
}
The when property is expecting a callable that returnstrue
if the rule should be applied. If you are using a client side validation you might also need to set up the property.
Answer
Solution:
You can use standalone validation:
public function rules()
{
return [
[['field1', 'field2'], MyValidator::className()],
];
}
And create a new class like follows:
namespace app\components;
use yii\validators\Validator;
class MyValidator extends Validator
{
public function validateAttribute($model, $attribute)
{
if (empty($model->filed1) and empty($model->field2)) {
$this->addError($model, $attribute, 'some message');
}
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function update() on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.