我想在Laravel中使用表单模型绑定。下面的(简化的)示例工作得很好:
{{ Form::model($user, array('class'=>'form-horizontal')) }}
{{ Form::token() }}
{{ Form::label('email', 'Email Address') }}
{{ Form::text('email') }}
{{ Form::close() }}
然而,我想在name
属性中使用数组,这是现在非常标准的。换句话说,将user[email]
作为字段名,这样我就可以在后端将所有表单元素放在一个数组中。
这是可能的模型绑定吗?当我使用{{ Form::text('user[email]') }}
时,邮件没有被填写。我试着在Form::model
函数中添加array('user'=>$user)
,以防它需要一个嵌套的值,但没有运气。
Form::model(array('user' => $user))
是正确的解决方案,但不幸的是,表单模型绑定的实现是相当糟糕的,因为它不容易工作在嵌套,数组和对象的混合集。见https://github.com/laravel/framework/pull/5074
你可以试试Form::model(array('user' => $user->toArray()))
或Form::model((object) array('user' => $user))
。
您可以这样做,假设您将有一个单个$user
和 multiple $types
Form::macro('userTypes', function($user,$types)
{
foreach ($types as $type) {
$concat = $user . "_" . $type;
return '<input type="{$type}" name="{$concat}">';
}
});
并使用您的表单样式定制输出,甚至可能需要为函数添加更复杂的内容。
然后简单地调用例如
$user = "johndoe";
$types = array("email","text");
Form::userTypes($user,$types);
结果是
<input type="email" name="johndoe_email">
<input type="text" name="johndoe_phone">
如果你想在一行中完成并且假设你有一个单个$user
和一个单个$type
你可以这样做
Form::macro('userType', function($user,$type)
{
return '<input type="{$type}" name="{$user[$type]}">';
});
和呼叫
$user = [ "mail" => "some_mail_value" ];
Form::userType($user,"mail");
会导致
<input type="mail" name="some_mail_value">
或者您可能想要使用单个$user键值数组作为:
Form::macro('userType', function($user)
{
$keys = array_keys($user);
foreach ($keys as $key => $value) {
return '<input type="{$key}" name="{$value}">';
}
});
和呼叫
$user = ["mail" => "mail_value" , "text" => "text_value"];
Form::userType($user);
结果是
<input type="mail" name="mail_value">
<input type="text" name="text_value">
最后,我没有找到一个直接的方法来做它与默认表单模型绑定,因为它要求字段名是相同的模型属性,但你可以做一个变通
Form::macro('customBind', function($user_model,$type)
{
return '<input type={$type} name="user[{$type}]" value="{$user_model->$type}">';
});
然后
$user = new User();
$user->email = "johndoe@gmail.com";
Form::customBind($user,"email");
会产生类似
的内容<input type="email" name="user[email]" value="johndoe@gmail.com">
要点是,基本上你的问题的解决方案是创建一个宏,我已经提供了一些变通办法,但你需要细化到你的具体需要。