Cygnite - A Modern Toolkit For Web Developers

The Elegant Way of Building Full-Featured Web Applications

Cygnite Dynamic Routing

Form Builder

Documentation

Form Builder

Dealing With Forms

Dealing with html form is one of the day to day and challenging task for a developer. Cygnite Framework gives you more freedom and easy way to build forms with most elegant syntax.

Make your view page much more simple and clean. Build your HTML Forms either inside a controller, view page or as a class and then render it in a view page.

Creating A Simple Form

You can build your amusing forms and render in your view. Suppose if you want to build a contact us form with add/edit functionalities, this is where Cygnite Framework makes you job much simple and takes your pain to create a form. Forms can be build 3 different ways

Get the form instance and add elements to it, create your amusing form. i. Building Form class. ii. Build Form without Closure. iii. Build Form beautiful syntax using Closure.

Building Form as Component


namespace Apps\Form;

use Cygnite\FormBuilder\Form;
use Cygnite\Foundation\Application;
use Cygnite\Common\UrlManager\Url;

/**
 * Sample Form using Cygnite Form Builder
 *
 */

class RegisterForm extends Form
{

    private $model;

    public $errors;

    private $segment;

    // We will set action url
    public $action = 'add';

    public function __construct($object = null, $segment = null)
    {
        $this->model = $object;
        $this->segment = $segment;
    }

    public function setValidator($validator)
    {
        $this->validator = $validator;

        return $this;
    }

    /**
     *  Build form and return object
     * @return Registration
     */
    public function buildForm()
    {
        $id = (isset($this->model->id)) ? $this->model->id : '';

        if (is_object($this->validation)) {
                        
            /* Set your custom validation errors*/
            //$this->validator->setCustomError('category_type_error', 'Your Custom Error');
        }

        $this->open(
                    'category', [
                    'method' => 'post',
                    'action' => Url::sitePath('category/type/' . $id . '/' . $this->segment),
                    'role' => 'form',
                    'style' => 'width:500px;margin-top:35px;float:left;'
                        ]
                )
                ->addElement('label', 'Category Type', [
                    'class' => 'col-sm-2 control-label',
                    'style' => 'width:100%;'
                        ]
                )
                ->addElement('text', 'category_type', [
                    'value' => (isset($this->model->category_type)) ? $this->model->category_type : '',
                    'class' => 'form-control'])
                ->addElement('label', 'Category Name', ['class' => 'col-sm-2 control-label', 'style' => 'width:100%;'])
                ->addElement('text', 'category_name', [
                    'value' => (isset($this->model->category_name)) ? $this->model->category_name : '',
                    'class' => 'form-control'])
                ->addElement('label', 'Short Description', ['class' => 'col-sm-2 control-label',  'style' => 'width:100%;'])
                ->addElement('textarea', 'description', [
                    'value' => (isset($this->model->description)) ? $this->model->description : '',
                    'class' => 'form-control'])
                ->addElement('submit', 'btnSubmit', [
                    'value' => 'Save',
                    'class' => 'btn btn-primary',
                    'style' => 'margin-top:15px;'
                        ]
                )
                ->close()
                ->createForm();

        return $this;
    }

    /**
     * Render form
     * @return type
     */
    public function render()
    {
        return $this->buildForm()->getForm();
    }
}


Rendering Form


use Apps\Form\RegisterForm;

// your $id form id if set then edit page else add
if (isset($id) && $id !== null) {
    // Update the category
    $model = array();
    $model = Category::find($id);
    $form = new RegisterForm($model, Url::segment(4));
    $form->errors = $errors;
    $form->validator = $validator;//Set validator instance to form builder to set error to form elements

    echo $form->render(); // render update form with values
} else {

    //Add a new Category
    $form = new RegisterForm();
    $form->errors = $errors;
    $form->validator = $validator;// set the validator instance

    echo $form->render(); // Render your category view page

}

Cygnite also shipped with sample crud application, if you may want to have a look at.

Build Form without Closure

Create an array of elements and pass to closure to create your awesome form.



 use Cygnite\FormBuilder\Form;

 $form = Form::make()
        ->open(
            'contact',
            [
                'method' => 'post',
                'action' => Url::sitePath('contact/add'),
                'role' => 'form',
                'style' => 'width:500px;margin-top:35px;float:left;'
            ]
        )
        ->addElement('label', 'Name', [
            'class' => 'col-sm-2 control-label',
            'style' => 'width:37.667%;'
        ])
        ->addElement('text', 'user_name' , [
            'value' => '',
            'class' => 'form-control'])
        ->addElement('label', 'Email Address', ['class' => 'col-sm-2 control-label'])
        ->addElement('text', 'email_address', [
            'value' => '',
            'class' => 'form-control'])
        ->addElement('label', 'Document', ['class' => 'col-sm-2 control-label'])
        ->addElement('file', 'document', [
            'value' => '',
            'class' => 'form-control'])
        ->addElement('submit', 'btnSubmit', [
            'value' => 'Save',
            'class' => 'btn btn-primary',
            'style' => 'margin-top:15px;'
        ])
        ->close()
        ->createForm();

  echo $form->getForm();


iii. Using Closure Syntax

Build Form using most expressive syntax.



 use Cygnite\FormBuilder\Form;

  $form = Form::make(
     function ($form) {
       return $form->open(
            'users',
            [
                'method' => 'post',
                'action' => Url::sitePath('welcome/upload'),
                'enctype' => 'multipart/form-data'
            ]
          )
          ->addElement('label', 'Name', [
            'class' => 'col-sm-2 control-label',
            'style' => 'width:37.667%;'
            ])
          ->addElement('text', 'name' , [
            'value' => '',
            'class' => 'form-control'])
          ->close()
          ->createForm();
     }
 );

 echo $form->getForm();


Build Form With Array of Elements.

Alternatively you can also create stack of elements as array and pass into addElements() method to generate your form.


  $elements = [
        [
            'Name' => [
                'class' => 'text-box',
                'type' => 'label',
            ],
            'name' => [
                'value' => 'Cygnite Framework',
                'class' => 'text-box',
                'type' => 'text',
            ],
            'Email' => [
                'class' => 'text-box',
                'type' => 'label',
            ],
            'email-address' => [
                'value' => 'sanjoy@hotmail.com',
                'class' => 'text-box',
                'type' => 'text',
            ],
            'document' => [
                'class' => 'text-box',
                'type' => 'file',
            ],
            'submit' => [
                'value' => 'Submit',
                'type' => 'submit',
            ]
        ]
    ];

 $form = Form::make(function ($form) use($elements) {
            return $form->open(
                'users', [
                    'method' => 'post',
                    'action' => Url::sitePath('welcome/register'),
                    'enctype' => 'multipart/form-data'
                ]
            )
            ->addElements($elements)
            ->close()
            ->createForm();
        }
    );

 echo $form->getForm();


Creating Other HTML Elements

Similarly you can render other html tags, you just have to provide field type in order to render.

For example

If you want to render other html elements simply pass first parameter as type of the element (addElement()) or If you are using array of element then pass as type as below.

Checkbox


    $form->addElement('checkbox', 'user_name' , [
                'value' => '',
                'class' => 'form-control'])

Creating File HTML Element



  $elements = array('document' => [
                'class' => 'text-box',
                'type' => 'file',
            ]);

  $form->addElements($elements);

  OR

  $form->addElement('file', 'document', [
            'value' => '',
            'class' => 'form-control'])


Creating Radio Button



 $form->addElement('radio', 'gender' , [
                'value' => '',
                'class' => 'form-control'])
  or 

 $element = [
             'gender' => [
                'class' => 'text-box',
                'type' => 'radio',
            ]
 ];
 

Select Box



 $form->addElement("select", "Country", 
                  ["options" => ['Select Country', 'America', 'China', 'India', 'Bangladesh'], 
                  "class" => "form-control"]
 );

 // Default value to select box

 
 $form->addElement("select", "Country", 
                  ["options" => ['Select Country', 'America', 'UK', 'India', 'Australia'],
                  "selected" => 3,
                  "class" => "form-control"]
 );
 

Creating A Block With Elements

You may wish to create some block and elements into it, or may be applying different style to the DIV block. Form builder makes it simple, using same addElement() method you can add a block to elements.



 $form->addElement('openTag', 'div_1' , ['style' => 'border:1px solid red;height:40px;'])
             ->addElement("text", "name", ["value" => "", "class" => "form-control"])
      ->addElement('closeTag', 'div_1')


 $form->addElement('openTag', 'span_2' , ['style' => 'background:#FAFAFA;'])
            ->addElement("text", "address", ["value" => "", "class" => "form-control"])
      ->addElement('closeTag', 'span_2')

 

Adding Custom Elements

You may also wish to apply some custom tag before or after the form elements, you can achieve it same way adding a DIV block.


 $form->addElement('custom', 'dl', ['name' => 'Custom Tag','style' => 'background:green;']);


Follow Us On Facebook Twitter Google+ Linkedin
Released Under The MIT Public License. Copyrights @2012-2017. Powered by- Sanjoy Dey Productions.