How to Unvalidate Some Fields in Yii2

How to Unvalidate Some Fields in Yii2

Validation can be disabled both on the client side (for yiiActiveForm) and on the server side.

Using a scenario will indicate that server-side validation should be skipped for certain fields.

On the client side, validation for specific fields will be dynamically removed depending on the selected action (in our case — delete).

Our controller:

$NewsletterMailForm = new NewsletterMailForm();

if(Yii::$app -> request -> post($NewsletterMailForm -> formName())['event'] != NewsletterMailForm::EVENT_DELETE)
{
	$NewsletterMailForm -> scenario = NewsletterMailForm::EVENT_SEND;
}

If the "event" field is not equal to "delete", it means we are going to send emails (no other actions are handled at this point).

Our view:

$this -> registerJs("
	$('.btnEmailDelete').click(function(e){
		e.preventDefault();
		
		if(confirm('".Yii::t('app', 'Delete selected emails?')."'))
		{
			$('#".Html::getInputId($NewsletterMailForm, 'event')."').val('".NewsletterMailForm::EVENT_DELETE."');
			$('#form-news-letter-mail').yiiActiveForm('remove', '".Html::getInputId($NewsletterMailForm, 'subject')."');
			$('#form-news-letter-mail').yiiActiveForm('remove', '".Html::getInputId($NewsletterMailForm, 'body')."');
				
			$('#form-news-letter-mail').submit();
		}
	});
");

A quick explanation. By default, form submission triggers validation. If everything is fine, the form is sent to the server. However, if we click the "delete selected" link (in this case, email addresses), we need to somehow bypass validation and submit the form directly.

I couldn't find a more elegant way to do it, so I used the approach shown above.

In the model, it's implemented like this:

if($this -> validate() == true)
{
if($this -> event == NewsletterMailForm::EVENT_DELETE)
{
/* Delete subscribers */
}
elseif($this -> event == NewsletterMailForm::EVENT_SEND)
{
/* Send list of emails */
}

return true;
}
return false;

Instead of using $this -> event, I could have used a scenario — but I’m not going to refactor it for now.

Good luck!

Are you having problems with your Yii2 framework website? Do you need additional functionality?
>Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *