Creating Form Macros

Problem

You'd like to extend the Form facade with additional functionality.

Solution

Use the Form::macro() method.

Form::macro() allows you to extend the Form facade with your own methods.

First you register a macro, then later you can access the macro as you would any of the Form methods.

Let's say you add the following code to your app/start/global.php file.

Form::macro('sumthin', function()
{
    return '<input type="sumthin" value="default">';
});

Then later, in a Blade template, you can access it.

{{ Form::sumthin() }}

This would output the following.

<input type="sumthin" value="default">

Add macros that take arguments

Let's update the sumthin macro to take three arguments. First the implementation.

Form::macro('sumthin', function($value, $count = 10, $start = 1)
{
    $build = array();
    while ($count > 0)
    {
        $build[] = sprintf('<input type="sumthun" value="%s" index="%s">',
          $value, $start);
        $start += 1;
        $count -= 1;
    }
    return join("\n", $build);
});

Now Form::sumthin() has one required argument and two optional ones. If you don't pass the required argument, Laravel will generate an error.

Use it in a template.

{{ Form::sumthin('test', 5) }}

The output would be.

<input type="sumthin" value="test" index="1">
<input type="sumthin" value="test" index="2">
<input type="sumthin" value="test" index="3">
<input type="sumthin" value="test" index="4">
<input type="sumthin" value="test" index="5">

Discussion

Examine the source code.

If you look at FormBuilder.php in your vendor/laravel/src/Illuminate\Html directory you can see several undocumented public methods of the Form facade that you can use in your macros.

Your macro code doesn't have access to $this, but you can call any of the following handy methods:

Or you can call the standard methods:

You even can call other macros from your macro.

comments powered by Disqus