在laravel中,是否有某种方法可以在表单中嵌套相关资源?
说我有这个:
class Person extends Eloquent {
public function addresses() {
return $this->hasMany("Address");
}
}
class Address extends Eloquent {
public function person() {
return $this->belongsTo("Person");
}
}
我想要一个Person
表单来收集有关Person
Address
个accepts_nested_attributes_for :address
的信息。 laravel是否以与Rails'fields_for :address
和Address
等效的方式为此提供了便利?
我只想简单地将Person
字段与Address
表单的结果包含在一起,因为Person
除了{{{ Form::model(new Person, array("action" => "admin\PersonController@store", "method" => "POST")) }}
{{ Form::text("name", array(...)) // <input name='person[name]' ... /> }}
{{ Form::email("email", array(...)) // <input name='person[email]' ... /> }}
{{ Form::fields_for("addresses"/* Would be name of relation */) }}
{{ Form::text("street_address") // <input name='person[addresses][][street_address]' ... /> }}
{{ Form::close_fields() }}
{{ Form::close() }}
之外并不存在1}}。这有意义吗?
==编辑==
这是假设代码
我正在寻找的是类似于此的东西:
{{1}}
答案 0 :(得分:12)
您在输入名称的正确轨道上。
<强>表格强>
// Form open, Person fields, etc...
<h2>Addresses</h2>
@foreach ($addresses as $address)
<fieldset>
{{ Input::text('addresses['.$address->id.'][address_1]', $address->address_1) }}
{{ Input::text('addresses['.$address->id.'][address_1]', $address->address_2) }}
{{ Input::text('addresses['.$address->id.'][city]', $address->city) }}
{{ Input::text('addresses['.$address->id.'][state]', $address->state) }}
{{ Input::text('addresses['.$address->id.'][zip]', $address->zip) }}
</fieldset>
@endforeach
// Form Close
如果要添加地址,则需要生成一些随机密钥而不是地址ID。这将使字段保持分组。
控制器逻辑
这是我处理输入的方式,使用'fillable'来过滤进入模型的数据。
// Get the Person model, fill, save, etc...
$addressIds = array();
foreach (Input::get('addresses', array()) as $id => $addressData)
{
$address = Address::find($id) ?: new Address;
$address->fill($addressData);
$address->save();
$addressIds[] = $address->id;
}
$changes = $person->addresses()->sync($addressIds);
// Delete the unused addresses
foreach ($changes['detached'] as $detachedAddressId)
{
$address = Address::find($detachedAddressId);
if (!empty($address)) $address->delete();
}
答案 1 :(得分:1)
现在,您可以使用“modelform”包为各种模型甚至一组关系形式创建表单。
答案 2 :(得分:0)
您应该从控制器管理所有这些。从表单中收集数据并随意使用:
// Controller Code
$person = new Person(array(
'field_1' => Input::get('field_1'),
'field_2' => Input::get('field_2'),
.............
));
$person->save();
$address = new Address(array(
'field_x' => Input::get('field_x'),
'field_y' => Input::get('field_y'),
.............
));
$person->addresses()->save($address);