Skip to main content

Form macros in Laravel

Form macros are a really cool part of Laravel. They are described in the documentation, but that doesn't show you exactly how to use them in your application. So here is how I do it.

Load macros on the start of the application

To register the macros if we follow the docs we simply need to do something like

Form::macro('myField', function()
{
    return '<input type="awesome" >';
});

But how do we get this to load when needed? My solutions is to simply have it load on the start of the application. I do this by making a folder in my app directory called "misc" which just holds files for different things that I have to startup this way. Inside of that folder I make a file called "form_macros.php". To load this file on startup, we are going to require it within app/start/global.php. Simply add
require app_path() . 'misc/form_macros.php';
to the end of the global.php file. This will make sure that the form macros are loaded up on every run of the software.

Create the macro

Here is the initial code for a quick custom macro:

<?php

Form::macro(
    'myInput',
    function ($name, $text, $placeholder = null, $type = 'text') {
        $label = Form::label($name, $text, array('class' => 'control-label'));
        $input = Form::input($type, $name, null, array('placeholder'=>$placeholder));

        $item = <<<HTML
            <div class="control-group">
                $label
                <div class="controls">
                      $input
                </div>
            </div>
HTML;
        return $item;
    }
);

This is going to create a macro which only requires two parameters. First the name which goes into the for attribute of the label and the name attribute of the input. Then it requires the text to be displayed for the label. That is it. You can optionally pass a placeholder for the input item in, along with a different type of input. Upon being called, this will return whatever markup you set in the $item.

Use the macro

Now that your macro file is being loaded and it has a macro in it, just drop into a pages view to test it real fast. For the example macro we will use the following:

 {{ Form::myInput('first_name', 'First Name', 'John/Jane') }}
Upon loading the page you should see an input field which as a label of "First Name", which if clicked will also put the cursor into the input field.

That is all there is to loading, creating, and using custom form macros. Now go forth and make maintaining forms a breeze by using custom macros.

Update!

This post applies to Laravel 4.x applications. The HTML component was removed by default in 5.0 and how you echo raw output has been modified as well. So do be aware that using this in 5.0 will require changes and (a bit) more work, but it is possible if you really wish to do so.

Popular posts from this blog

My PHP Wishlist

PHP Wishlist These are things that I think would help developers build better programs with far fewer lines of code. Simple enough? Let's get to it.
Scalar Type Hints and a Strict Mode Currently one of the hottest RFCs in PHP history perhaps, Scalar Type Hints. This is a feature that allows developers to specify any type a given parameter should be. Currently PHP only supports object types and arrays for type hinting. This allows for string, integer, boolean, and the like. 
However, nothing is simple in PHP. With this, some developers want conversion to happen if the wrong type is given (string to integer for example if '3' is passed in) while others want strict enforcing of types. The RFC has a middle-ground of loose typing by default like everything else in PHP, but the option to turn on a strict mode.
My issue with the RFC is... The syntax is horrible for declaring strict mode. I was actually entirely for it up until a few days ago. I read a comment on Reddit. This per…

Running supervisord on Codio

Codio currently does not provide a parts install for supervisord. This can make developing apps that uses Laravel queues an issue since you'd then have to keep a terminal open at all times. So let's keep things simple, and install supervisord manually.

Installing the tools The only thing from parts that we will need, is pip. This is a python package management tool, which is what supervisord is written in. Just grab this to your box like so: parts install pip Now that we have pip, we can pull in supervisord through it. pip install supervisord Configuring environment Now that supervisord is installed, we need to setup the boxes configuration to make it easier to use. We need to:

Add the python bin to the path.Make the configuration directory for supervisorMake a log directory To add the python bin folder to your path, open up /home/codio/.bash_profile and add the following: $home/.parts/packages/python2/2.7.6-2/bin to the first path entry. Remember to separate it with a colon betwe…

Laravel, Codio, and Nginx

I have recently come across a *sweet* online IDE, this would be Codio. Codio lets you develop in the cloud and run the code on an actual server. This way you can write your code and run it in the cloud, keeping your development environment universal and in my case safe-guarding against my own nonsense. While Codio does offer their own documentation on getting Laravel going, it uses Apache and MySQL. So here is getting going with Nginx, MariaDB, and PHP-FPM on Codio for Laravel development.

Create your project Create a project just how you normally would, except select "Git" as the method for getting the base code into the workspace. This will give you an input where you can either put in an HTTP or SSH based git repository URL. If you are using SSH and you haven't setup the SSH key on your repository, it will prompt you to do so automatically with a key Codio generates. For now, I'm going to just use the standard HTTP URL for Laravel which is https://github.com/larav…