Form builder

Create advanced, consistent and secure forms and validations.

Start by creating a new model file e.g. "app/Models/Forms/ContactForm.php" naming is completely up to you. The open the file and add the content bellow:

Form Modal

<?php

namespace Models\Forms;

class ContactForm extends AbstractForm
{
    /**
     * createForm method is an required, abstract method used to build form
     * @return void
     */
    protected function createForm(): void
    {
        $this->form->add([
            "firstname" => [
                "type" => "text",
                "label" => "First name",
                "validate" => [
                    "length" => [1, 60]
                ]
            ],
            "lastname" => [
                "type" => "text",
                "label" => "Last name",
                "validate" => [
                    "length" => [1, 80]
                ]
            ],
            "email" => [
                "type" => "text",
                "label" => "Email",
                "attr" => [
                    "type" => "email"
                ],
                "validate" => [
                    "length" => [1, 160]
                ]
            ],
            "message" => [
                "type" => "textarea",
                "label" => "Message",
                "validate" => [
                    "length" => [1, 2000]
                ]
            ]
        ]);
    }
}

I will cover all the the form field bellow.

Controller

Then you just need to build the ContactForm Modal inside your controller. Create the Controller bellow "app/Http/Controllers/ContactPage.php" and add the content bellow.

<?php
namespace Http\Controllers\Examples;

use MaplePHP\Http\Interfaces\ResponseInterface;
use MaplePHP\Http\Interfaces\RequestInterface;
use Http\Controllers\BaseController;
use MaplePHP\Foundation\Http\Provider;
use MaplePHP\Foundation\Form\Validate;
use Models\Forms\ContactForm;

class ContactPage extends BaseController
{
    protected $form;
    protected $validate;

    public function __construct(Provider $provider, ContactForm $form, Validate $validate)
    {
        $this->form = $form;
        $this->validate = $validate;
    }

    /**
     * Build the contact form
     * @param  ResponseInterface $response PSR-7 Response
     * @param  RequestInterface  $request  PSR-7 Request
     * @return void
     */
    public function contactUs(ResponseInterface $response, RequestInterface $request)
    {
        // This will build the form
        $this->form->build();
        
        // Set partial template view
        $this->view()->setPartial("form", [
            "tagline" => "Contact us",
            "name" => "Lorem ipsum dolor",
            "content" => "Lorem ipsum dolor sit amet.",
            "form" => [
                "method" => "post",
                "action" => $this->url()->getUrl(),
                "form" => $this->form,
                "submit" => "Send"
            ]
        ]);
    }
    
    /**
     * POST: Validate the contact form
     * @param  ResponseInterface $response PSR-7 Response
     * @param  RequestInterface  $request  PSR-7 Request
     * @return object json data
     */
    public function postContactUsForm(ResponseInterface $response, RequestInterface $request): object
    {
        if ($requests = $this->validate->validate($this->form, $request->getParsedBody())) {
            // The $requests variable will contain all "expected" form fields post values
            $this->responder()->message("Completed!");
        }
        
        // Responder will pass response to frontend and Stratox.js
        return $this->responder()->build();
    }
}

Add controller to your router

Open the app/Http/Routes/web.php file and add the rows bellow to expected place (see router section):

$routes->get("/{page:contact}", ['Http\Controllers\Examples\ContactPage', "contactUs"]);
$routes->post("/{page:contact}", ['Http\Controllers\Examples\ContactPage', "postContactUsForm"]);

Done you have now built a working form that also will be validated!

Form fields:

Most used form fields is available out of the box.

  • text

  • checkbox

  • radio

  • date

  • datetime

  • hidden

  • textarea

  • select

  • password

You can and it is even recommended that you create your own custom form field class. More on this later.

Create fields

As the example above shows, you add fields like bellow

$this->form->add([
    "formFieldName" => [
        "type" => "text",
        "label" => "The field label",
        "validate" => [
            "length" => [1, 60] // Validations
        ]
    ],
    ...
]

The key "formFieldName" is the form fields name attribute. The other parameters (e.g type, label, ...) will I go though bellow:

Field config

type (string)

Expects defined form type key Example: text, textarea, date, select, checkbox, radio and more. Required

label (string)

Define a input label Example: Email address

description (string)

Define a input label Example: We need your email to…

attr (array)

Add html attributens to field Example:

[
	class => inp-email, 
	type => email,
	placeholder => Fill in the email
]

items (array)

Add checkbox, radio or select list items. Example:

[
	1 => Yes, 
	0 => No
]

Is required for field types like select, checkbox and radio.

validate (array)

Add validation to form field Example:

[
	length => [1, 200],
	!email => NULL
]

The exclamation point before the email key means that it will only validate email if it is filled in else skip or do the other validation.

You can use every validation from the validation library. See all available validations here.

config (multidimensional array)

Pass on custom data for a custom field. Example:

[
	role => admin,
	user_id => 5212
]

The custom data is passed to your "Custom" form field template.

Breaking down the examples:

1. Create form with array

Build a whole form with array as bellow

$this->form->add([
    "firstname" => [
        "type" => "text", // Set form type (input text or textarea and so on.)
        "label" => "First name",
        "validate" => [
            "length" => [1, 80]
        ]
    ],
    "lastname" => [
        "type" => "text",
        "label" => "Last name",
        "validate" => [
            "length" => [1, 120]
        ]
    ],
    "email" => [
        "type" => "text",
        "label" => "Email",
        "description" => "We need you email so that we can contact you.",
        "attr" => [
            "type" => "email",
            "placeholder" => "john.doe@hotmail.com"
        ],
        "validate" => [
            "length" => [1, 120],
            "!email" => NULL
        ]
    ],
    "nested,item1" => [
        "type" => "radio",
        "label" => "Question 1",
        "validate" => [
            "length" => [1],
        ],
        "items" => [
            1 => "Yes",
            0 => "No"
        ],
        "value" => 1 // Default value
    ],
    "nested,item2" => [
        "type" => "radio",
        "label" => "Question 2",
        "validate" => [
            "length" => [1],
        ],
        "items" => [
            1 => "Yes",
            0 => "No"
        ],
        "value" => 1 // Default value
    ],
    "message" => [
        "type" => "textarea",
        "label" => "Message",
        "validate" => [
            "length" => [0, 2000]
        ]
    ],
    "gdpr" => [
        "type" => "checkbox",
        //"label" => "GDPR",
        "validate" => [
            "length" => [1, 1],
            "!equal" => [1]
        ],
        "items" => [
            1 => "I accept that my data will be saved according to GDPR"
        ]
    ]
    
]);

2. Set values if you want

If you have values from for example the database (accepts multidimensional array and object)

$this->form->setValues([
    "firstname" => "John",
    "lastname" => "John",
    "nested" => [
        "item1" => 0,
        "item2" => 1,
    ]
]);

3. Build the form

You will allways need to build the form before read or validations.

$this->form->build();

4. Read form

Now you can read the form by utilizing the form partial in the template engine.

// This will build the form
$this->form->build();

// Set partial template view
$this->view()->setPartial("form", [
    "tagline" => "Contact us",
    "name" => "Lorem ipsum dolor",
    "content" => "Lorem ipsum dolor sit amet.",
    "form" => [
        "method" => "post",
        "action" => $this->url()->getUrl(),
        "form" => $this->form,
        "submit" => "Send"
    ]
]);

5. Validate form

Lastly use the MaplePHP validation engine.

if ($requests = $this->validate->validate($this->form, $request->getParsedBody())) {
    // The $requests variable will contain all "expected" form fields post values
    $this->responder()->message("Completed!");
}

// Responder will pass response to frontend
// IF form is not valid then this will be showned on the HTML form.
return $this->responder()->build();

Much more will come in the future.

Last updated