Skip to content

Building

Piotr Kierzniewski edited this page Nov 9, 2017 · 2 revisions

Creating form instance

The first thing you need to make to create Motiforms form is creating insance of the form object. Form object instance is created by form factory.

$factory = mf_get_factory();

$form = $factory->create();

mf_get_factory function returns form factory instance and create method is creating form object instance. Now you can add fields to your form.

Adding fields to form

To add fields to form you must execute add method on form object instance.

$form->add( 'full_name', TextType::class );

Following code will add input field of type text and named full_name. Motiforms use the same fields types, which use Symfony framework. Read Symfony form component to learn more about field types.

Creating form classes

If your form is advanced and you want to seperate form logic from app logic you can create seperate form class.

// contact-form.php
namespace App;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

/**
 * Class provided for contact form
 */
class ContactForm extends AbstractType {

    /**
     * Build simple form
     *
     * @param FormBuilderInterface $builder Form builder.
     * @param array                $options Form options.
     */
    public function buildForm( FormBuilderInterface $builder, array $options ) {

        $builder
            ->add('full_name', TextType::class )
            ->add('email', EmailType::class )
            ->add('message', TextareaType::class )
            ->add('submit', SubmitType::class );
    }
}

Following class can be used in this way:

// controller.php
require 'contact-form.php'

namespace App;

use App\ContactForm;

function create_form() {

    $factory = mf_get_factory();
    $form = $factory->create( ContactForm::class );
}

Example above can be recreacted in the following way:

use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

$factory = mf_get_factory();
$form = $factory->create();

$form
    ->add('full_name', TextType::class )
    ->add('email', EmailType::class )
    ->add('message', TextareaType::class )
    ->add('submit', SubmitType::class );

It is up to you how you would like to create your forms.

Clone this wiki locally