问题
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?
回答1:
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) }}
回答2:
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:
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.
回答4:
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.
回答5:
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)
来源:https://stackoverflow.com/questions/16259488/laravel-4-form-builder-custom-fields-macro