Skip to content Skip to sidebar Skip to footer

Radio And Checkbox Inside Label With Laravel

Is there any way to use Form::label with checkboxes and radio inputs to generate a markup that bootstrap suggests? The aim is to have input fields inside labels instead of attachin

Solution 1:

Thanks to Saint Genius for his answer, which led me in the right direction. +1

However, he is missing several semicolons, didn't include the name attribute on the checkbox field, and broke up the $html string over several lines, making it hard to read.

I have rewritten it a bit:

Form::macro('labelCheckbox', function($name, $value, $label)
{
    $html = "<label>
                <input name='$name' type='checkbox' value='$value' /> $label
            </label>";

    return $html;
});

And then in the view:

{{ Form::labelCheckbox('fruits', 'apple', 'Apple') }}

Solution 2:

You can just write your own form macro and use that to build the html however you like.

http://laravel.com/docs/4.2/html#custom-macros

Something like:

Form::macro('bootCheckbox', function($value, $label)
{
 $html = '<div class="checkbox"><label><input type="checkbox" value="';
 $html .= $value;
 $html .= '">';
 $html .= $label;
 $html .= '</label></div>'
 return $html
}

And then you can call it like this in your view:

{{ Form::bootCheck('i_dont_know_what_value_youd_like', 'Option one is this and that&mdash;be sure to include why it's great') }}

Of course you can pass any value you like to the macro and build whatever you want (given your code on the macro side is sound). The example above here should output a checkbox as you showed, but it's not too clean and I haven't tested it.

As for where to put the code, you can put it anywhere as long as you link it. My form macro's (which are a bit more extensive) live in /app/start/form_macros.php and required in /app/start/global.php by just adding require dirname(__FILE__) . '/form_macros.php'; to the end of it.


Post a Comment for "Radio And Checkbox Inside Label With Laravel"