繁体   English   中英

Laravel 4表单构建器自定义字段宏

[英]Laravel 4 Form builder Custom Fields Macro

我试图创建一个自定义HTML 5日期字段,以便在laravel 4框架视图中使用。

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

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

唯一的问题是价值没有被填充,我不知道如何做到这一点。

我正在使用此表单来创建和编辑名为Event的模型。

我怎样才能填充这个领域的价值?

我在app / start / global.php中添加了以下内容:

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;
});

但“好方法”是扩展Form类并实现您的方法。

这是我做的:

在我看来,我添加了以下宏

<?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) }}

不需要使用宏。 只需使用Laravel的内置Form::input方法定义date作为您想要的输入类型:

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

这似乎不在主文档中,而是在上面链接的API文档中。

我找到了另一种方式来做到这一点这是把我的宏在一档名为macros.php然后将其放置在app/连同目录filters.phprouts.php ,然后在app/start/global.php我加最后一行

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

这将在应用程序启动后和构建视图之前加载宏。 它接缝整洁并按照Laravel的约定,因为这是同样的方式Laravel用于加载filters.php文件。

这对我有用:

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

而不是做

    foreach($options)

您可以使用

    HTML::attributes($options)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM