CakePHP FormHelper

FormHelper contains supportive library files of form for performing the different operations in CakePHP.  The FormHelper focuses on efficiently developing of the form so, that validation, re-population, and design can be simplified. In FormHelper, there are various tags of the form which we will use to create a form in the template folder. Furthermore, the FormHelper is a versatile that means it will do almost everything in the form which you want to show by use of correct syntax and method for performing a specific result. It’s one line of code is more enough than html code because we have to write a huge code for creating the form but in FormHelper, we have to write a simple syntax for the form.

This is the source path where FormHelper define:-www\CakePHP3.8\vendor\cakephp\cakephp\src\View\Helper\FormHelper

Various tags of the form

1) create():- It is the starting phase for creating the CakePHP form operation. Or you can say that your CakePHP form tag starts with this method to create the form.

 Syntax:

      echo $this->Form-> create ();

2) end() :- This method define that your cakephp form tag has been closed.

Syntax;

    echo $this ->Form-> end () ;  

Here is the body of CakePHP, where we have to define all the operations of form Helper in between two methods of the form.

 <?php
           echo $this-> Form-> create ();
       ----------------------------------- // it is a body of form tag for performing different                                                      
       -----------------------------------// operation in cakephp
          echo $this-> Form-> end ();
 ?>  

3) text :- It is an empty text box for entering the data in form.

      echo $this-> Form->text ("enter your name");

4) control() :- This method will show a text box along with a name which you want to show.

    echo $this-> Form-> control ("enteryour name");

Or you can write this way

echo $this-> Form-> control ('Name',['type' => 'text','placeholder' => 'enter your name']);

Placeholder: - The placeholder attribute specifies a short hint that describes the expected value of an input field / textarea. The little indication is displayed in the field before entering a value.

5) input() – It shows same output as above control() method.

         echo $this-> Form-> input ('username',['type' => 'text']) ;

These methods contain two arguments. In the first argument, they contain a string that you want to display, and in the second argument, they define which method you want to define in type.

  • 'type' - Allows you to choose the type of form to create. If no type is provided, then it will be autodetected based on the form background. Valid values for type:
  • 'get' - Will set the form method to HTTP GET.
  • 'file' - Will set the form method to POST and the 'enctype' to “multipart/form-data”.
  • 'post' - Will set the method to POST.
  • 'put', 'delete', 'patch' - Will override the HTTP method with PUT, DELETE, or PATCH, respectively, when the form is submitted.

Similarly, you can define for a password by ‘type’=>’password’, or you can define password tag in form like this-

echo $this-> Form-> password(‘pass’);

6) Checkbox: It gives choices between more than one possible mutually exclusive options. For example, the user can select more than one item in the restaurant.

 echo $this-> Form-> input ( 'Terms & condition' , [ 'type'=> 'checkbox'] ) ;

It will create a checkbox for string “Terms & condition”. And if you want to create more checkbox option then you have to define these given parameters.

        $this-> Form-> select ( 'gender', $options, [ 'multiple' => 'checkbox' ] );
                               $options = [
                                            'M' => 'Masculine',
                                            'F' => 'Feminine',
                                          'N' => 'Neuter'
                                 ]); 

Here $options is an array which contains data in key-value pairs and if we define multiple in checkbox then it provides accessibility to select or check more than one data item.

There are two option of Checkbox:

  • 'checked' - A Boolean is used to indicate whether the check box will be checked. By default, it takes false.
  • 'disabled' - Create a disabled checkbox input.

And if you want to disable some parameter then

 echo $this-> Form-> select ('gender', $options, [
     'disabled' => ['M', 'N']
 ]); 

7) Radio button: A radio button is a graphical control element that allows the user to select only one options from the multiple declared values.

      echo $this-> Form-> radiobutton ("gender");

This will create a single radio button for gender and if you want to add more fields in radio button then here is the code.

 $this-> Form-> radio (
     'favorite_color',
     [
         ['value' => 'r', 'text' => 'Red', 'style' => 'color:red;'],
         ['value' => 'u', 'text' => 'Blue', 'style' => 'color:blue;'],
         ['value' => 'g', 'text' => 'Green', 'style' => 'color:green;'],
     ]
 ); 

8) Dropdown box/ selection/select box: It is a list of items that appear when clicking on a button or text selection

 $this-> Form-> select ("select", ['select', 'RED' , 'BLUE' , 'BLACK' , 'GREEN']);

2nd method :

 echo $this-> Form-> select ('field', [
     'Value 1' => 'Label 1',
     'Value 2' => 'Label 2',
     'Value 3' => 'Label 3'
 ]); 

9) Submit :- It defines a submit button which submits all form values to a form-handler.

echo $this-> Form-> button('Submit');

10) Email :- It define to take email as input from user.

echo $this-> Form-> control ('email', ['type' => 'email']);

11) Textarea: A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).

The size of a textarea can be specified with the cols and rows attributes.

echo
$this-> Form -> textarea ("enter your address", ["rows"=>3
, "cols"=>10,                                       "value"=>" Delhi"]);

Setting a URL for the Form

A url method is used in the form to transfer a specific action in the current controller or the in another controller of the application.

For example, if you'd like to point the form to the publish() action of the current controller, you would supply a $options array, like the following:

echo $this-> Form-> create ($article, ['url' => ['action' => 'publish']]);

Output:

 <form method="post" action="/articles/publish">
 Or you can also define the form action as follows.
 echo $this-> Form-> create (null, [
     'url' => [
         'controller' => 'Articles',
         'action' => 'publish'
     ]
 ]); 

Output:

<form method="post" action="/articles/publish">

Login and Registration Form

For login and registration page, we have to create a controller name RegisterController.php in which we defined an action file login.ctp and add.ctp for creating a login page as well registration page. Here we have created a Register controller.

RegisterController.php

 <?php
 namespace App\Controller;
 class RegistersController extends AppController
 {   public $row;
     public function initialize()
     {
         parent::initialize();
         $this->loadComponent('Flash'); 
     }
     public function login()
     {  
 }
        public function add()
         {
 }
 ?>       

And this is our login.ctp file which is invoked in RegistersController.php.

login.ctp file

 <br><br>
 <div class="row">
 <?php 
 echo $this-> Form-> create();
 echo $this-> Form-> controls(
     [   
         'email'=> ['required'=>true, 'placeholder'=>'Enter your Email','type'=>'email'],
         'password'=>['required'=>true, 'placeholder'=>'Enter your password'],
     ],
     ['legend'=>'Login Here']
     );
     echo $this-> Form-> button ('Submit');
  echo $this-> Form-> end();   
     ?>
    </div> 

And this is also an action file name as add.ctp file for creating the registration page of CakePHP. It is also invoked in the Controller file.

Add.ctp file

 <div class="form-conrol">
 <h3>Registration Details</h3>
 <?php
     echo $this->Form-> create ($row);
     echo $this->Form-> control ('username', ['placeholder'=>'Enter Your Full Name']);
             echo $this-> Form-> control ('email', ['type'=>'email', 'placeholder'=>'Enter Your Email']);
     echo $this->Form-> control ('password', ['placeholder'=>'Enter your Password']);
     echo $this->Form-> control ('address', ["rows"=>3, "cols"=>10, 'placeholder'=>'Enter Your Address']);
     echo '<label for="gender"> Gender</label>';
     echo $this-> Form-> radio(
         "gender",
             [
                 ['value' => 'm', 'text' => 'Male'],
                 ['value' => 'f', 'text' => 'Female'],    
             ]
         );
     echo '<label for="field">State</label>';
     echo $this-> Form-> select ("field",  
       [  [ 'Value 1' => 'select'],
         ['Value 2' => 'Uttar Pradesh'],
         ['Value 3' => 'Delhi'],
         ['value 4'=> 'Haryana'],
         ['value 5'=>'Others'],
     ]);
     echo '<div>'.$this->Form-> checkbox ('terms').
 '<label for="terms">Terms &Conditions</label></div>';
     echo $this-> Form-> button ('Register');
     echo $this-> Form-> end ();
 ?>
 </div> 

Now we will run our code in localhost like localhost/CakePHP3.8/Registers/login

Then it will show the given below Output.

CakePHP FormHelper

Now we will run our next code for showing the registration page in localhost like localhost/CakePHP3.8/Registers/add

Then it will show the given below Output.

CakePHP FormHelper 1