我有一个非常相似的创建表单和编辑表单,实际上它们之间只有一个关键区别,这就是我需要帮助的地方。
我想将表单提取为部分,以便我不会重复自己,但是我有点问题。
我将遗传数组(genetics[]
)作为JSON对象保存到我的数据库中,它可能如下所示:
{
"Bell-Albino":"BA",
"Rainwater-Albino":"na",
"Tremper-Albino":"na",
"Murphys-Patternless":"mp",
"Eclipse":"EC",
"Marble-Eye":"na",
"Blizzard":"b",
"Mack-Snow":"na",
"Super-Snow":"SS",
"Gem-Snow":"na",
"TUG-Snow":"na",
"Line-Bred-Snow":"na",
"Enigma":"EN",
"White-and-Yellow":"WY",
"Wildtype":"na",
"Giant":"na"
}
以下是Bell-Albino
字段的代码摘录,向您展示如何在create
视图中设置其余内容。我必须设置值的键。在提交错误后,Request::old()
执行它需要做的事情并保持绝对正确的值。这个工作正常并且没有被破坏:
<label for="genetics">Bell Albino</label>
<?php $options = array('na' => 'N/A', 'BA' => 'Visual', 'ba' => 'Recessive'); ?>
{!! Form::select(
'genetics[Bell-Albino]',
$options,
Request::old('genetics[Bell-Albino]'),
array('class' => 'form-control'))
!!}
同样,这里是edit
视图中的相同代码。再一次,这个工作正常但它不是DRY,这是我关心的问题。
<label for="genetics">Bell Albino</label>
<?php $options = array('na' => 'N/A', 'BA' => 'Visual', 'ba' => 'Recessive'); ?>
{!! Form::select(
'genetics[Bell-Albino]',
$options,
$genetics[0]['Bell-Albino'],
array('class'=>'form-control'))
!!}
为了在页面加载时正确显示/显示/选择遗传数组值,我必须将json_decode
我的字段值放入不同的数组中,如上所述form
:
<?php $genetics[] = json_decode($gecko->genetics, true); ?>
对于那些感兴趣的人,所以你知道解码对象的外观,这是$genetics
的转储:
array:1 [▼
0 => array:16 [▼
"Bell-Albino" => "BA"
"Rainwater-Albino" => "na"
"Tremper-Albino" => "na"
"Murphys-Patternless" => "mp"
"Eclipse" => "EC"
"Marble-Eye" => "na"
"Blizzard" => "b"
"Mack-Snow" => "na"
"Super-Snow" => "SS"
"Gem-Snow" => "na"
"TUG-Snow" => "na"
"Line-Bred-Snow" => "na"
"Enigma" => "EN"
"White-and-Yellow" => "WY"
"Wildtype" => "na"
"Giant" => "na"
]
]
现在从上面的两段代码可以看出,唯一真正的区别在于我正在使用Request::old()
。是否有任何方法来实现将此表单与JSON对象一起使用的干燥方式?
答案 0 :(得分:1)
无论你的&#34;线索&#34;是告诉您它是编辑表单还是创建表单,在ternary statement中使用不同的一行:
<label for="genetics">Bell Albino</label>
<?php $options = array('na' => 'N/A', 'BA' => 'Visual', 'ba' => 'Recessive'); ?>
{!! Form::select(
'genetics[Bell-Albino]',
$options,
$isEdit ? $genetics[0]['Bell-Albino'] : Request::old('genetics[Bell-Albino]'), // here!
array('class' => 'form-control'))
!!}
例如,这可能在您的&#34;创建&#34;页:
@include('my.form', ['isEdit' => false]);
这可能出现在你的&#34;编辑&#34;页:
@include('my.form', ['isEdit' => true]);
其中my.form
包含上述Form::select
。