I have a create form and edit form that incredibly similar, in fact there is only one key difference between them and this is where I need some help.
I want to extract the form into a partial so that I'm not repeating myself with it however I have a bit of an issue.
I'm saving a genetics array (genetics[]
) to my DB as a JSON object, it can look like below for example:
{
"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"
}
Below is an extract of code for the Bell-Albino
field to show you how the rest of them are set up in the create
view. I have to set the key for the value. Upon submission with errors, the Request::old()
does what it needs to do and retains the value absolutely fine. This works fine and isn't broken:
<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'))
!!}
And similarly, here is the same bit of code from the edit
view. Once again, this works fine but it isn't DRY which is what concerns me.
<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'))
!!}
In order for the genetics array values to be shown/displayed/selected properly when the page loads I had to json_decode
my field value into a different array like this above my form
:
<?php $genetics[] = json_decode($gecko->genetics, true); ?>
For those interested, so you know how the decoded object looks, this is the dump of $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"
]
]
Now from the 2 pieces of code above you can see that the only real difference is where I'm using Request::old()
. Is there any way to achieve a DRY way of using this form with a JSON object?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire