Passing serialized form data to my (Laravel) controller - php

I have a form that asks the user to make 10 game picks and then sort the picks based on confidence. I'm using jQuery's sortable function and then populating a hidden form element (order-array) with a serialized string on each update to the order. My problem is how to deal with this array of serialized data in my controller after submission so I can store it (plus the actual game picks) into my database.
My Form View
{{ Form::open() }}
<h1>Games for Week {{ $weeknum }} </h1>
<h3>Visitors # Hometeam</h3>
<input type="hidden" name="order-array" id="order-array" value="">
<ul id="gamelist">
<?php $count = 1; ?>
#foreach($games as $game)
<li class="game-rank" id="c_{{ $count }}">
<input type="radio" name="{{ "pick_".$game->id }}" value="{{ $game->visitor }}">
{{ $game->visitor }} #
<input type="radio" name="{{ "pick_".$game->id }}" value="{{ $game->hometeam }}">
{{ $game->hometeam }}
<input type="hidden" name="{{ "game_".$count }}" value="{{ $game->id }}">
</li>
<?php $count++; ?>
#endforeach
</ul>
#if(Auth::check())
{{ Form::hidden('player', $player) }}
{{ Form::submit('Submit Picks', array('class' => 'link-button')) }}
#endif
{{ Form::close() }}
The serialized confidence data being passed to the controller
"c[]=1&c[]=3&c[]=9&c[]=4&c[]=5&c[]=6&c[]=2&c[]=7&c[]=8&c[]=10"
My controller function
public function post_new()
{
$confidence = Input::get('order-array');
for ($i=1;$i<=10;$i++) {
$array_index = $i-1;
$pick = new Pick;
$pick->user_id = Input::get('player');
$pick->game_id = Input::get("game_$i"); // game number
$pick->pick = Input::get("pick_$i"); // teamname
$pick->confidence = $confidence[$array_index];
$pick->save();
}
return Redirect::to ('users');
}
Everything works except for the confidence data. What adjustments do I need to make to my controller?
Thanks!!

Related

Custom form fields in Laravel 8.x - Any scope for improvement?

To satisfy the requirement (Add support for custom form fields without any plugin or library), I developed a module which allows admin to perform below actions.
Admin can create custom form fields.
Fields data should be encrypted when stored into database.
It can be mapped with multiple countries so if user belongs to that country, selected custom form fields will appear in profile.
Below is my code. Kindly suggest if there are any improvements needed.
Migration file to create custom form fields
public function up()
{
Schema::create('custom_forms', function (Blueprint $table) {
$table->id();
$table->string('title', 250);
$table->string('field_title', 250);
$table->string('field_name', 250);
$table->string('field_input_name', 250);
$table->enum(
'field_type',
[
'text',
'textarea',
'number',
'email',
'date',
'time',
'select',
'radio',
'checkbox',
'tel',
'url'
]
)->default('text');
$table->string('field_min_value', 10)->nullable();
$table->string('field_max_value', 10)->nullable();
$table->text('field_option_values')->nullable();
$table->string('field_validation_pattern', 250)->nullable();
$table->string('field_validation_message', 250)->nullable();
$table->string('field_placeholder', 250)->nullable();
$table->tinyInteger('is_required')->default(0);
$table->integer('country_id');
$table->tinyInteger('is_active')->default(1);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('custom_forms');
}
Migration file to store custom form field values
public function up()
{
Schema::create('custom_form_values', function (Blueprint $table) {
$table->id();
$table->foreignId('form_id')->references('id')->on('custom_forms');
$table->foreignId('user_id')->references('id')->on('users');
$table->mediumText('value')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('custom_form_values');
}
White creating a custom form field, admin can select multiple countries for single. So, I've created a loop for all selected countries and stored the data.
CustomFormController.php
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
foreach ($request->country_id as $country) {
$custom_form = new CustomForm();
$custom_form->title = $request->name;
$custom_form->field_title = $request->name . '-' . Str::random(10);
$custom_form->field_name = $request->field_name;
$custom_form->field_input_name = preg_replace('/\s+/', '', $request->name) . '-' . Str::random(10);
$custom_form->field_type = $request->field_type;
$custom_form->field_min_value = $request->field_min_value;
$custom_form->field_max_value = $request->field_max_value;
$custom_form->field_option_values = $request->field_option_values;
$custom_form->field_validation_pattern = $request->field_validation_pattern;
$custom_form->field_validation_message = $request->field_validation_message;
$custom_form->field_placeholder = $request->field_placeholder;
$custom_form->is_required = $request->field_is_required;
$custom_form->country_id = $country;
$custom_form->save();
}
return redirect()->route('admin.custom-forms.index');
}
In CustomForm.php model, added relation to the values to get data for selected custom form field.
public function values()
{
return $this->belongsTo(CustomFormValue::class, 'id', 'form_id')->select(['id', 'value','form_id']);
}
In CustomFormValue.php model, defined encrypted field to match requirement no. 2.
protected $casts = [
'value' => 'encrypted',
];
Below code is from edit_profile.blade.php to display all custom form fields.
#forelse ($custom_forms as $form)
<div class="form-group">
<label class="required"
for="{{ $form->field_input_name }}">{{ $form->field_name }}</label>
{{-- FOr Text area --}}
#if ($form->field_type === 'textarea')
<textarea class="form-control" type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}" id="{{ $form->field_input_name }}"
minlength="{{ $form->field_min_value }}"
maxlength="{{ $form->field_max_value }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
{{ $form->is_required == 1 ? 'required' : '' }}>{{ $form->values ? $form->values->value : null }}</textarea>
<span class="help-block">{{ $form->field_placeholder }}</span>
{{-- for select option --}}
#elseif ($form->field_type === 'select')
#php
$option_values = explode(',', $form->field_option_values);
$is_selected = $form->values ? $form->values->value : '';
#endphp
<div class="form-group">
<select class="form-control" type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}"
id="{{ $form->field_input_name }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
{{ $form->is_required == 1 ? 'required' : '' }}>
#forelse ($option_values as $value)
<option #if ($value == $is_selected) selected #endif value="{{ $value }}">
{{ $value }}</option>
#empty
#endforelse
</select>
<span class="help-block">{{ $form->field_placeholder }}</span>
</div>
{{-- for radio buttons --}}
#elseif ($form->field_type === 'radio')
#php
$option_values = explode(',', $form->field_option_values);
$is_selected = $form->values ? $form->values->value : '';
#endphp
<div class="col-sm-10">
#forelse ($option_values as $value)
<div>
<label>
<input class=" " type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}"
id="{{ $form->field_input_name }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
value="{{ $value }}" #if ($value == $is_selected) checked #endif
{{ $form->is_required == 1 ? 'required' : '' }}>{{ $value }}
</label>
</div>
#empty
#endforelse
</div>
{{-- for checkbox --}}
#elseif ($form->field_type === 'checkbox')
#php
$option_values = explode(',', $form->field_option_values);
$is_selected = $form->values ? $form->values->value : '';
#endphp
<div class="col-sm-10">
#forelse ($option_values as $value)
<div>
<label>
<input class=" " type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}[]"
id="{{ $form->field_input_name }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
value="{{ $value }}" #if (str_contains($is_selected,$value)) checked #endif
>{{ $value }}
</label>
</div>
#empty
#endforelse
</div>
#else
<input class="form-control " type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}" id="{{ $form->field_input_name }}"
minlength="{{ $form->field_min_value }}"
maxlength="{{ $form->field_max_value }}" {{-- pattern="{{ $form->field_validation_pattern }}" --}}
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
value="{{ $form->values ? $form->values->value : null }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
{{ $form->is_required == 1 ? 'required' : '' }}>
<span class="help-block">{{ $form->field_placeholder }}</span>
#endif
</div>
#empty
{{-- Message to display if there is no custom field added--}}
#endforelse
To store user entered custom form field values, in UserController.php
foreach ($custom_values as $key => $value) {
$form_value = Str::contains($key, 'custom_form_');
if ($form_value == 1) {
$form_id = str_replace('custom_form_', '', $key);
$custom_form_value = CustomFormValue::updateOrCreate([
'form_id' => $form_id,
'user_id' => Auth::user()->id
], [
'form_id' => $form_id,
'user_id' => Auth::user()->id,
'value' => is_array($value) ? implode(', ', $value) : $value
]);
}
}
One user can have many custom form field values. So, in User.php model,
public function customFormValue()
{
return $this->hasMany(CustomFormValue::class, 'user_id');
}
And finally, to display custom form values, in profile.blade.php
#forelse ($custom_forms as $form)
<tr>
<td>
{{ $form->field_name }}: <strong class="pull-right">{{ $form->values ? $form->values->value : '' }}</strong>
</td>
</tr>
#empty
{{-- Message if any --}}
#endforelse
So, this is what I have done so far to add support for custom form field without any plugin or library. Let me know if there is any room for improvement.
I hope it may help others who are looking for something similar.
Here are some points that you can implement for a better scalable system.
1) custom_forms table
We can store the nullable fields in JSON. So we can avoid the multiple nullable fields because it can be possible to have 50% nullable values. It is effective for storage purposes and will make a more efficient and scalable DB design.
2) custom_form_values table
$table->mediumText('value')->nullable() TO $table->json('value')->nullable()
NOTE - The JSON column type is recommended as it allows you to do SQL queries on JSON data. Here is a quick doc link https://dev.mysql.com/doc/refman/8.0/en/json.html
3) CustomFormController.php
Here we can do the bulk insertion. So the query will not fire every time. Reference - https://stackoverflow.com/a/29723968/7796116
4) edit_profile.blade.php
AVOID USING MULTIPLE IF/ELSE. IT WILL CREATES ISSUES AT TIME OF SCALIBILITY. Use components instead so it will make code more readable and scalable.
Here is the laravel components doc https://laravel.com/docs/9.x/blade#components
5) General Tips
Try to use the Null Coalescing operator instead ternary.
Hope this will help you.

I want to use the Delete route, but it is not supported. How can I use this route?

I want to delete the record selected from the index list, but I'm having trouble using deleteRoute
web.php
Route::delete('/destroy/{id}', 'ProjectController#destroy')->name('despro');
Controller
public function destroy($id)
{
Project::destroy($id);
return redirect('/project');
}
index.blade.php
#foreach($view as $v)
<tr>
<td>{{$v->id}}</td>
<td>{{$v->project_name}}</td>
<td>{{$v->name}}</td>
<td>{{$v->division}}</td>
<td>{{$v->content}}</td>
<td>{{$v->date}}</td>
<td>{{$v->preferred_date}}</td>
<td>{{$v->user_name}}</td>
<td>
#foreach($cats as $cat)
#if($v->category_id == $cat->id)
{{$cat->name}}
#endif
#endforeach
</td>
<td>{{$v->status}}</td>
<td>{{$v->estimated_work_time}}</td>
<td>delete</td>
</tr>
#endforeach
Will be deleted and redirected to index.blade.php but
The GET method is not supported for this route. Supported methods: DELETE.
Come out
delete route require DELETE method.
If you're using Laravel 5.1 or later
<form action="{{ route('despro', ['id' => $v->id]) }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button>delete</button>
</form>
If you're using Laravel 5.6 or later then
<form action="{{ route('despro', ['id' => $v->id]) }}" method="POST">
#method('DELETE')
#csrf
<button>delete</button>
</form>

How to display in the view edit-add.blade.php only some tables in Voyager?

It's my first time using blade and I'm a little confused with this. I need to show a form like what it comes with the default edit-add view in Voyager, but I need to display some inputs based on roles. I am filtering by the current user that is logged in and that is working fine, but I need to hide/display some inputs of the form based on that.
How can I accomplish this in the blade view?
Here is how Voyager take the data in the blade view:
#php
$dataTypeRows = $dataType->{(isset($dataTypeContent->id) ? 'editRows' :'addRows' )};
#endphp
#foreach($dataTypeRows as $row)
<!-- GET THE DISPLAY OPTIONS -->
#php
$options = json_decode($row->details);
$display_options = isset($options->display) ? $options->display : NULL;
#endphp
#if ($options && isset($options->formfields_custom))
#include('voyager::formfields.custom.' . $options->formfields_custom)
#else
<div class="form-group #if($row->type == 'hidden') hidden #endif #if(isset($display_options->width)){{ 'col-md-' . $display_options->width }}#else{{ '' }}#endif" #if(isset($display_options->id)){{ "id=$display_options->id" }}#endif>
{{ $row->slugify }}
<label for="name">{{ $row->display_name }}</label>
#include('voyager::multilingual.input-hidden-bread-edit-add')
#if($row->type == 'relationship')
#include('voyager::formfields.relationship')
#else
{!! app('voyager')->formField($row, $dataType, $dataTypeContent) !!}
#endif
#foreach (app('voyager')->afterFormFields($row, $dataType, $dataTypeContent) as $after)
{!! $after->handle($row, $dataType, $dataTypeContent) !!}
#endforeach
</div>
#endif
#endforeach
If my table 'example' contains: id, name, address and phone. How do I display in this view form only inputs for name and address?
Thanks in advance.
You should try this:
public function edit(Request $request, $id)
{
$user = Example::find($id);
return view(‘viewname’,compact(‘user’));
}
edit-add.blade.php
<input type = “text” name=”name” value=”#if(isset($user->name)){{ old('name', $user->name) }}#else{{old('name')}}#endif”>
<input type = “text” name=”name” value=”#if(isset($user->address)){{ old('address', $user->address) }}#else{{old('address')}}#endif”>
i cant understand what do you mean but
for showing a value in input in a view first you should send the value to view for example in controller you have :
public function test()
{
.....
return view('myView',compact('user'));
}
then in your view :
<input type="text" value"{{$user->address}}">
<input type="text" value"{{$user->first_name}}">
You can edit it from ADMIN interface without using any code
Just go to the settings menu and click BREAD

Laravel selectbox selected attribute with pivot column

I have a bit of a problem what i am stuck with.
I have a ManyToMany relation storing body measurements in my database and these are serialized arrays,
My measurements table
id | name | value
1 | Height | a:61:{i:0;s:6:"150 cm";i:1;s:6:"151 cm";i:2;s:6:"152 cm";i:3;s:6:"153 cm";i:4;s:6:"154 cm";i:5;s:6:"155 cm";i:6;s:6:"156 cm";i:7;s:6:"157 cm";i:8;s:6:"158 cm";i:9;s:6:"159 cm";i:10;s:6:"160 cm";i:11;s:6:"161 cm";i:12;s:6:"162 cm";i:13;s:6:"163 cm";i:14;s:6:"164 cm";i:15;s:6:"165 cm";i:16;s:6:"166 cm";i:17;s:6:"167 cm";i:18;s:6:"168 cm";i:19;s:6:"169 cm";i:20;s:6:"170 cm";i:21;s:6:"171 cm";i:22;s:6:"172 cm";i:23;s:6:"173 cm";i:24;s:6:"174 cm";i:25;s:6:"175 cm";i:26;s:6:"176 cm";i:27;s:6:"177 cm";i:28;s:6:"178 cm";i:29;s:6:"179 cm";i:30;s:6:"180 cm";i:31;s:6:"181 cm";i:32;s:6:"182 cm";i:33;s:6:"183 cm";i:34;s:6:"184 cm";i:35;s:6:"185 cm";i:36;s:6:"186 cm";i:37;s:6:"187 cm";i:38;s:6:"188 cm";i:39;s:6:"189 cm";i:40;s:6:"190 cm";i:41;s:6:"191 cm";i:42;s:6:"192 cm";i:43;s:6:"193 cm";i:44;s:6:"194 cm";i:45;s:6:"195 cm";i:46;s:6:"196 cm";i:47;s:6:"197 cm";i:48;s:6:"198 cm";i:49;s:6:"199 cm";i:50;s:6:"200 cm";i:51;s:6:"201 cm";i:52;s:6:"202 cm";i:53;s:6:"203 cm";i:54;s:6:"204 cm";i:55;s:6:"205 cm";i:56;s:6:"206 cm";i:57;s:6:"207 cm";i:58;s:6:"208 cm";i:59;s:6:"209 cm";i:60;s:6:"210 cm";}
2 | Weight | a:76:{i:0;s:5:"35 kg";i:1;s:5:"36 kg";i:2;s:5:"37 kg";i:3;s:5:"38 kg";i:4;s:5:"39 kg";i:5;s:5:"40 kg";i:6;s:5:"41 kg";i:7;s:5:"42 kg";i:8;s:5:"43 kg";i:9;s:5:"44 kg";i:10;s:5:"45 kg";i:11;s:5:"46 kg";i:12;s:5:"47 kg";i:13;s:5:"48 kg";i:14;s:5:"49 kg";i:15;s:5:"50 kg";i:16;s:5:"51 kg";i:17;s:5:"52 kg";i:18;s:5:"53 kg";i:19;s:5:"54 kg";i:20;s:5:"55 kg";i:21;s:5:"56 kg";i:22;s:5:"57 kg";i:23;s:5:"58 kg";i:24;s:5:"59 kg";i:25;s:5:"60 kg";i:26;s:5:"61 kg";i:27;s:5:"62 kg";i:28;s:5:"63 kg";i:29;s:5:"64 kg";i:30;s:5:"65 kg";i:31;s:5:"66 kg";i:32;s:5:"67 kg";i:33;s:5:"68 kg";i:34;s:5:"69 kg";i:35;s:5:"70 kg";i:36;s:5:"71 kg";i:37;s:5:"72 kg";i:38;s:5:"73 kg";i:39;s:5:"74 kg";i:40;s:5:"75 kg";i:41;s:5:"76 kg";i:42;s:5:"77 kg";i:43;s:5:"78 kg";i:44;s:5:"79 kg";i:45;s:5:"80 kg";i:46;s:5:"81 kg";i:47;s:5:"82 kg";i:48;s:5:"83 kg";i:49;s:5:"84 kg";i:50;s:5:"85 kg";i:51;s:5:"86 kg";i:52;s:5:"87 kg";i:53;s:5:"88 kg";i:54;s:5:"89 kg";i:55;s:5:"90 kg";i:56;s:5:"91 kg";i:57;s:5:"92 kg";i:58;s:5:"93 kg";i:59;s:5:"94 kg";i:60;s:5:"95 kg";i:61;s:5:"96 kg";i:62;s:5:"97 kg";i:63;s:5:"98 kg";i:64;s:5:"99 kg";i:65;s:6:"100 kg";i:66;s:6:"101 kg";i:67;s:6:"102 kg";i:68;s:6:"103 kg";i:69;s:6:"104 kg";i:70;s:6:"105 kg";i:71;s:6:"106 kg";i:72;s:6:"107 kg";i:73;s:6:"108 kg";i:74;s:6:"109 kg";i:75;s:6:"110 kg";}
Relation table users_measurements
user_id | measurement_id | value
1 | 1 | 160 cm
1 | 2 | 50 kg
measurements controller
public function measurements()
{
$user = Auth::user();
$measurements = Measurement::all();
$this->layout->title = "Measurements";
$this->layout->content = View::make('user::settings/measurements')
->with('user', $user)
->with('measurements', $measurements);
}
And my view, i loop through the results to generate a form
View
{{ Form::open(array('id' => 'ajax-', 'class' => 'ui fluid form segment')) }}
<div class="two fields">
#foreach($measurements as $measurement)
<div class="field">
<label for="{{ $measurement->id }}">{{ $measurement->name }}</label>
<select name="{{ $measurement->id }}" id="{{ $measurement->id }}" class="form-select">
<option value="">{{ $measurement->name }} kiválasztása</option>
#foreach(unserialize($measurement->value) as $value)
<option value="{{ $value }}" >{{ $value }}</option>
#endforeach
</select>
</div>
#endforeach
</div>
{{ Form::submit('Módosítások mentése', array('class' => 'ui tiny orange button')) }}
{{ Form::close() }}
So i am really stuck how to solve to add the actual selected attribute to my selectbox
I tried a few things.
In my controller i store the logged in user in the $user variable.
I tried
$user-measurement->lists('value');
This gave back the following result
array(2) { [0]=> string(1095) "a:61:{i:0;s:6:"150 cm";i:1;s:6:"151 cm";i:2;s:6:"152 cm";i:3;s:6:"153 cm";i:4;s:6:"154 cm";i:5;s:6:"155 cm";i:6;s:6:"156 cm";i:7;s:6:"157 cm";i:8;s:6:"158 cm";i:9;s:6:"159 cm";i:10;s:6:"160 cm";i:11;s:6:"161 cm";i:12;s:6:"162 cm";i:13;s:6:"163 cm";i:14;s:6:"164 cm";i:15;s:6:"165 cm";i:16;s:6:"166 cm";i:17;s:6:"167 cm";i:18;s:6:"168 cm";i:19;s:6:"169 cm";i:20;s:6:"170 cm";i:21;s:6:"171 cm";i:22;s:6:"172 cm";i:23;s:6:"173 cm";i:24;s:6:"174 cm";i:25;s:6:"175 cm";i:26;s:6:"176 cm";i:27;s:6:"177 cm";i:28;s:6:"178 cm";i:29;s:6:"179 cm";i:30;s:6:"180 cm";i:31;s:6:"181 cm";i:32;s:6:"182 cm";i:33;s:6:"183 cm";i:34;s:6:"184 cm";i:35;s:6:"185 cm";i:36;s:6:"186 cm";i:37;s:6:"187 cm";i:38;s:6:"188 cm";i:39;s:6:"189 cm";i:40;s:6:"190 cm";i:41;s:6:"191 cm";i:42;s:6:"192 cm";i:43;s:6:"193 cm";i:44;s:6:"194 cm";i:45;s:6:"195 cm";i:46;s:6:"196 cm";i:47;s:6:"197 cm";i:48;s:6:"198 cm";i:49;s:6:"199 cm";i:50;s:6:"200 cm";i:51;s:6:"201 cm";i:52;s:6:"202 cm";i:53;s:6:"203 cm";i:54;s:6:"204 cm";i:55;s:6:"205 cm";i:56;s:6:"206 cm";i:57;s:6:"207 cm";i:58;s:6:"208 cm";i:59;s:6:"209 cm";i:60;s:6:"210 cm";}" [1]=> string(1300) "a:76:{i:0;s:5:"35 kg";i:1;s:5:"36 kg";i:2;s:5:"37 kg";i:3;s:5:"38 kg";i:4;s:5:"39 kg";i:5;s:5:"40 kg";i:6;s:5:"41 kg";i:7;s:5:"42 kg";i:8;s:5:"43 kg";i:9;s:5:"44 kg";i:10;s:5:"45 kg";i:11;s:5:"46 kg";i:12;s:5:"47 kg";i:13;s:5:"48 kg";i:14;s:5:"49 kg";i:15;s:5:"50 kg";i:16;s:5:"51 kg";i:17;s:5:"52 kg";i:18;s:5:"53 kg";i:19;s:5:"54 kg";i:20;s:5:"55 kg";i:21;s:5:"56 kg";i:22;s:5:"57 kg";i:23;s:5:"58 kg";i:24;s:5:"59 kg";i:25;s:5:"60 kg";i:26;s:5:"61 kg";i:27;s:5:"62 kg";i:28;s:5:"63 kg";i:29;s:5:"64 kg";i:30;s:5:"65 kg";i:31;s:5:"66 kg";i:32;s:5:"67 kg";i:33;s:5:"68 kg";i:34;s:5:"69 kg";i:35;s:5:"70 kg";i:36;s:5:"71 kg";i:37;s:5:"72 kg";i:38;s:5:"73 kg";i:39;s:5:"74 kg";i:40;s:5:"75 kg";i:41;s:5:"76 kg";i:42;s:5:"77 kg";i:43;s:5:"78 kg";i:44;s:5:"79 kg";i:45;s:5:"80 kg";i:46;s:5:"81 kg";i:47;s:5:"82 kg";i:48;s:5:"83 kg";i:49;s:5:"84 kg";i:50;s:5:"85 kg";i:51;s:5:"86 kg";i:52;s:5:"87 kg";i:53;s:5:"88 kg";i:54;s:5:"89 kg";i:55;s:5:"90 kg";i:56;s:5:"91 kg";i:57;s:5:"92 kg";i:58;s:5:"93 kg";i:59;s:5:"94 kg";i:60;s:5:"95 kg";i:61;s:5:"96 kg";i:62;s:5:"97 kg";i:63;s:5:"98 kg";i:64;s:5:"99 kg";i:65;s:6:"100 kg";i:66;s:6:"101 kg";i:67;s:6:"102 kg";i:68;s:6:"103 kg";i:69;s:6:"104 kg";i:70;s:6:"105 kg";i:71;s:6:"106 kg";i:72;s:6:"107 kg";i:73;s:6:"108 kg";i:74;s:6:"109 kg";i:75;s:6:"110 kg";}" }
I tried so many methods to process this data to return the actual users pivot column values, but no luck
If anybody could help me out would really make my day, or any hint please
Thank you
{{ Form::select($measurement->id, unserialize($measurement->value), $user->value, array("id" => $measurement->id, "class" => "form-select") ) }}
Try this.
Okay if anybody else needs help with this i wrote a function in my user model
public function selectedMeasurement()
{
foreach ($this->measurement as $measurement)
{
$selected[] = $measurement->pivot->value;
}
if (!empty($selected))
{
return $selected;
}
else
{
return array();
}
}
And in my view
{{ Form::open(array('id' => 'ajax-', 'class' => 'ui fluid form segment')) }}
<div class="two fields">
#foreach($measurements as $measurement)
<div class="field">
<label for="{{ $measurement->id }}">{{ $measurement->name }}</label>
<select name="{{ $measurement->id }}" id="{{ $measurement->id }}" class="form-select">
<option value="">{{ $measurement->name }} kiválasztása</option>
#foreach(unserialize($measurement->value) as $value)
<option value="{{ $value }}" {{ in_array($value, $user->selectedMeasurement()) ? 'selected="selected"' : "" }} >{{ $value }}</option>
#endforeach
</select>
</div>
#endforeach
</div>
{{ Form::submit('Módosítások mentése', array('class' => 'ui tiny orange button')) }}
{{ Form::close() }}
I had the same problem and that is how I solved it.
I added this in my controller, in the edit method and passed it into the view:
$selectedTags = $product->tags()->pluck('tag_id')->toArray();
And in the view file I added it like this:
<option value="{{$row->id}}"{!! in_array($row->id, $selectedTags) ? ' selected="selected"' : '' !!}>{{$row->name}}</option>

Symfony 2 form not pre-populating with pre-saved data

Im taking over a project in Symfony 2 (of which I have little knowledge) and am having problems with one of the existing forms. It should be pre-populating the form fields with existing data but is failing to do so. Can anybody give and suggestions as to why it may not be working?
Heres my code:
/**
* #Route("/admin/pressrelease/{id}")
* #Template("ImagineCorporateBundle:Admin:Pressrelease/edit.html.twig")
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getRepository('ImagineCorporateBundle:PressRelease');
$pr = $repo->find($id);
if(!$pr->getDocument())
{
$doc = new Document();
$doc->setType('child');
$doc->setTemplate('child');
$pr->setDocument($doc);
}
$dateHelper = $this->get('helper.datehelper');
$years = $dateHelper->dateRangeAction();
$form = $this->createForm(new PressreleaseType(), array($pr , $years) );
if($this->getRequest()->getMethod() == 'POST')
{
$form->bindRequest($this->getRequest());
if($pr->getDocument())
{
$pr->getDocument()->setType('child');
$pr->getDocument()->setTemplate('child');
$pr->getDocument()->setTitle($pr->getTitle());
}
if($form->isValid())
{
$pr->upload('../web/upload/general/');
$em->persist($pr);
$em->persist($pr->getDocument());
$em->flush();
$pr->index(
$this->get('search.lucene'),
$this->generateUrl(
'imagine_corporate_pressrelease_view',
array('id' => $pr->getId(), 'title' => $pr->getTitle())
)
);
return $this->redirect($this->generateUrl('imagine_corporate_pressrelease_admin'));
}
}
return array('pressrelease' => $pr, 'form' => $form->createView());
}
And the view template:
{% extends "ImagineCorporateBundle:Admin:base.html.twig" %}
{% block heading %}Edit Press Release{% endblock %}
{% block content %}
<p>
Upload Attachment |
New Person
</p>
<form action="" method="post" {{ form_enctype(form) }}>
<div>
{{ form_label(form.title) }}
{{ form_errors(form.title) }}
{{ form_widget(form.title) }}
</div>
<div>
{{ form_label(form.author) }}
{{ form_errors(form.author) }}
{{ form_widget(form.author) }}
</div>
<div>
{{ form_label(form.postdate) }}
{{ form_errors(form.postdate) }}
{{ form_widget(form.postdate) }}
</div>
<div>
{{ form_label(form.imageUpload) }}
{{ form_errors(form.imageUpload) }}
{{ form_widget(form.imageUpload) }}
</div>
<div>
{{ form_label(form.thumbnailUpload) }}
{{ form_errors(form.thumbnailUpload) }}
{{ form_widget(form.thumbnailUpload) }}
</div>
<fieldset>
<div><input type="checkbox" class="checkallWebsites"> Check all</div>
{{ form_label(form.websites) }}
{{ form_errors(form.websites) }}
{{ form_widget(form.websites) }}
</fieldset>
<fieldset>
<div><input type="checkbox" class="checkallMagazines"> Check all</div>
{{ form_label(form.magazines) }}
{{ form_errors(form.magazines) }}
{{ form_widget(form.magazines) }}
</fieldset>
<fieldset>
<div><input type="checkbox" class="checkallDept"> Check all</div>
{{ form_label(form.department) }}
{{ form_errors(form.department) }}
{{ form_widget(form.department) }}
</fieldset>
<script>
$(function () {
$('.checkallWebsites').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});
$(function () {
$('.checkallMagazines').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});
$(function () {
$('.checkallDept').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});
</script>
{{ form_widget(form) }}
<div id="submit">
<input type="submit" class="addnew-submit" />
</div>
</form>
{% endblock %}
Thanks in advance!
Your issue is this line in your controller:
$form = $this->createForm(new PressreleaseType(), array($pr , $years) );
If your form is based on an entity then you can bind the entity to the form by just passing the object on it's own like so:
$form = $this->createForm(new PressreleaseType(), $pr);
If it's a more complicated form then your array needs to be key value with the form field names as the keys. For example (you may have to substitute the actual field names if they differ as we cannot see your form class):
$form = $this->createForm(
new PressreleaseType(),
array(
'press_release_name' => $pr->getName(),
'years' => $years
)
);
EDIT:
It's possible that both of those values are needed in the constructor of the form class if it has been customised so if the above doesn't help you then please add your form class code.

Categories