Laravel 4 Form builder Custom Fields Macro

2019-02-10 21:11发布

Im trying to create a custom HTML 5 date field for using in a laravel 4 framework view.

{{
    Form::macro('datetime', function($field_name)
    { 
        return '';
    });         
}}

{{ Form::label('event_start', 'Event Date', array('class' => 'control-label')) }}
{{ Form::datetime('event_start') }}

The only problem is the value is not being populated, and i do not know how to do this.

Im using this form to create and edit a model called Event.

how can i populate the value of this field?

5条回答
太酷不给撩
2楼-- · 2019-02-10 21:20

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.

查看更多
聊天终结者
3楼-- · 2019-02-10 21:22

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.

查看更多
来,给爷笑一个
4楼-- · 2019-02-10 21:24

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.

查看更多
劳资没心,怎么记你
5楼-- · 2019-02-10 21:28

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)
查看更多
▲ chillily
6楼-- · 2019-02-10 21:33

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) }}
查看更多
登录 后发表回答