Laravel 4 Form builder Custom Fields Macro

落花浮王杯 提交于 2019-11-30 15:20:44

Here's what I did:

in my view I added the following macro

<?php
Form::macro('datetime', function($value) {
    return '<input type="datetime" name="my_custom_datetime_field" value="'.$value.'"/>';
});
...
...
// here's how I use the macro and pass a value to it
{{ Form::datetime($datetime) }}
Rafa Gómez Casas

I added in app/start/global.php the following:

Form::macro('date', function($name, $value = null, $options = array()) {
    $input =  '<input type="date" name="' . $name . '" value="' . $value . '"';

    foreach ($options as $key => $value) {
        $input .= ' ' . $key . '="' . $value . '"';
    }

    $input .= '>';

    return $input;
});

But the "good way" would be to extend the Form class and implement your methods.

Using a macro is not necessary. Just use Laravel's built-in Form::input method defining date as your desired input type:

{{ Form::label('event_start', 'Event Date', array('class' => 'control-label')) }}
{{ Form::input('date', 'event_start', $default_value, array('class'=>'form-control')) }}

This appears not to be in the main docs but is in the API docs as linked above.

I've found another way to do this which is putting my macros in a file named macros.php then place it under app/ directory along with filters.php and routs.php, then in the app/start/global.php I added the following line at the end

require app_path().'/macros.php'; 

this will load your macros after the app has started and before the view is constructed. it seamed neater and following the Laravel's convention because this is the same way Laravel uses to load the filters.php file.

this works for me:

Form::macro('date', function($name, $value = null, $options = array()) {
$attributes = HTML::attributes($options);
$input =  '<input type="date" name="' . $name . '" value="' . $value . '"'. $attributes.'>';
return $input;
});

instead of doing

    foreach($options)

you can use

    HTML::attributes($options)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!