Skip to content
Grav 2.1 is out: every page speaks Markdown. Read the announcement →

Custom form handling fault?

Started by Muut Archive 11 years ago · 2 replies · 564 views
11 years ago

Hi, I'm new to grav and i created a simple plugin for additional form validation.
This works fine so far, but when a validation error occurs and $event->stopPropagation() is called
only the next form action in the series will be stopped instead of all.

This means in my example below, the Email won't be sent but the page will be redirected.

Is this the right behavior or is something wrong within the plugin?

Form frontmatter:

YAML
process:
        -   validate: validate
        -   email:
                from: "{{ form.value.email }}"
                to: "{{ config.plugins.email.to }}"
                subject: "Contact"
                body: "{% include 'forms/mail.html.twig' %}"
        -   redirect: contact/thankyou

Plugin code:

PHP

<?php 
namespace Grav\Plugin;

use Grav\Common\Plugin;
use RocketTheme\Toolbox\Event\Event;

class ValidationPlugin extends Plugin{
    public static function getSubscribedEvents()    {
        return [
            'onFormProcessed' => ['onFormProcessed', 0]
        ];
    }

    public function onFormProcessed(Event $event){
        $form = $event['form'];
        $action = $event['action'];
        $params = $event['params'];
        switch ($action) {
            case 'validate':
                $arrPost = $form->value()->toArray();
                $errCount = 0;
                if ($arrPost['json'] != "an" || !empty($arrPost['website']) || !empty($arrPost['mail']) || $arrPost['form-id']!=$form->name){
                    $errCount++;
                    $errMsg[] = $this->grav['language']->translate('FORM.VALIDATION_FAIL', null, true) .  $this->grav['language']->translate('PLUGIN_VALIDATION.ERROR_BOT');
                }
                if (isset($arrPost['schash'])  && $arrPost['schash'] != md5($arrPost[$arrPost['scfield']])){
                    $errCount++;
                    $errMsg[] = $this->grav['language']->translate('FORM.VALIDATION_FAIL', null, true) .  $this->grav['language']->translate('PLUGIN_VALIDATION.ERROR_SC');
                }
                if($errCount > 0){
                    $this->grav->fireEvent('onFormValidationError', new Event(['form' => $form, 'message' => implode('<br>',$errMsg)]));
                    $event->stopPropagation();
                    return;
                }
                break;
        }
    }
}
---
11 years ago

Yeah, this PR solves the Problem. Thanks!

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 2288 9 years ago
Archive · by Muut Archive, 9 years ago
2 1500 9 years ago
Archive · by Muut Archive, 9 years ago
2 4753 9 years ago
Archive · by Muut Archive, 9 years ago
1 3570 9 years ago
Archive · by Muut Archive, 9 years ago
3 1627 9 years ago