1

I'm trying to sanitize form input values in my plugin. Yii2 framework provides the following validation method: https://www.yiiframework.com/doc/guide/2.0/en/tutorial-core-validators#filter

It says that it applies a filter on the input value and assigns it back to the attribute being validated.

However when the entry is saved, I still can see unescaped characters. Maybe someone knows why it's not working?

My code looks like this:
Plugin.php

 Event::on(
        SaveController::class,
        SaveController::EVENT_BEFORE_SAVE_ENTRY,
        function(SaveEvent $event) {
           ...
           $response = Plugin::getInstance()->formValidator->validate($event->entry);
           if(!$response['success']){
             $event->isValid = false;
             $event->entry>addErrors($response['errors']);
           }
        }

FormValidator.php

public function validate(Entry $entry)
{
    $model = new DynamicModel(
        [
            'firstName' => $entry->firstName,
            'lastName' => $entry->lastName,
            'companyName' => $entry->companyName,
            'email' => $entry->emailAddress,
            'phone' => $entry->phoneNumber,
            'comment' => $entry->comment
        ]
    );

    if(!$model
       ...
        ->addRule(['firstName', 'lastName', 'companyName', 'email', 'phone', 'comment'], 'filter', ['filter' => [$this, 'sanitizeInput']])
      ...
        ->validate()) {

        return [
            'success' => false,
            'errors' => $model->getErrors(),
        ];
    }

    return [
        'success' => true,
        'errors' => [],
    ];
}

public function sanitizeInput($value) {
    $value = trim($value);
    $value = stripslashes($value);
    $value = htmlspecialchars($value);
    return $value;
}
1
  • Never used the filter validation method before, but looking at the docs, should it be ..., 'filter', 'filter' => [$this, 'sanitizeInput']) ?
    – Brad Bell
    Commented Nov 23, 2019 at 0:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.