home-icon
Adding form logic
Last updated: Jul 18, 2024

Introduction

Forms are a great way of interacting with the website visitors. Forms can be as simple as contact forms, but for the more demanding forms, it may be handy to be able to add your own logic to the form.

Webigniter offers a nice and clean way of adding logic to a form.

Adding logic

Adding your own logic after form submission is very simple.

You can use the file /Webigniter/Extending/FormsExtend.php to handle your logic. Just create a function with the same name as your form (lowercase) and prepend it with pre_ or post_. If you prepend the name with pre_, your code will be executed before all other processes, if your prepend it with post_, it will run your code after everything else is completed.

Here's a little example:

<?php

namespace App\Extending;

class FormsExtend
{
    private array $formData;

    function __construct(array $formData, Webigniter $webigniter)
    {
        $this->formData = $formData;
        $this->webigniter = $webigniter;
    }

    public function pre_contact(): bool
    {
        if(date('H') !== 23)
        {
           $this->webigniter->setFlashdata('errors', ['It\'s not happy hour yet']);
           return false;
        }

     return true;
    }
}

You can see that we created the pre_contact function here, this means this function will be executed before the submission is sent to the Webigniter CMS.

In this case it checks if it's between 23:00 and 23:59, and if not, a flash message is sent to the form page with an error. It also returns false to tell the code that it doesn't have to send the submission to the Webigniter CMS. If the function returns true, the submission will be sent to the Webigniter CMS and the regular validation (if any) will be done.

Table of Contents
  1. Introduction
  2. Adding logic