Delete record in database if checkbox is unchecked - php

I have a checkbox field in my form, I want to insert data to database if the checkbox is checked and delete the data in database if the checkbox is unchecked.
Here is my checkbox code:
<ul class="list-unstyled mb-0">
#foreach ($companies as $company)
<li class="d-inline-block mr-2 mb-1">
<fieldset>
<div class="checkbox">
<input type="checkbox" name="company_id[]"
class="checkbox-input" value="{{ $company->id }}"
id="{{ $company->id }}"
#foreach ($supervisor_company as $spv)
#if ($spv != null)
#if ($spv->company_id == $company->id)
checked
#endif
#endif
#endforeach>
<label for="{{ $company->id }}">{{ $company->name }}</label>
</div>
</fieldset>
</li>
<li class="d-inline-block mr-2 mb-1">
#endforeach
</ul>
And this is my controller:
if ($request->has('company_id')) {
foreach ($request->company_id as $key => $company) {
$spv_data = EmployeeSpvCompany::where('employee_id', $employee_id)->where('company_id', $company)->first();
if ($spv_data != null) {
EmployeeSpvCompany::where('employee_id', $employee_id)->where('company_id', $company)->update(['company_id' => $company]);
} else {
$emp_spv = new EmployeeSpvCompany;
$emp_spv->employee_id = $employee_id;
$emp_spv->company_id = $company;
$emp_spv->save();
}
}
}
Insert to database if the checkbox is checked is already working, but I don't know how to delete the data in database if the checkbox is unchecked

I expect the company_id field is a multi-select type so the value will be returned in the form of an array. I guess the following code will work in this situation.
$companyIds = $request->has('company_id'); // [1, 2]
if ($companyIds) {
foreach ($companyIds as $company_id) {
$employeeSpvCompanyInstance = EmployeeSpvCompany::firstOrCreate([
'employee_id' => $employee_id,
'company_id' => $company_id
]);
}
EmployeeSpvCompany::where('employee_id', $employee_id)->whereNotIn('company_id', $companyIds)->delete();
} else {
EmployeeSpvCompany::where('employee_id', $employee_id)->delete();
}

Ah!! I found something called whereNotIn. I just need to check if the data is not in my array request.
EmployeeSpvCompany::whereNotIn('company_id', $request->company_id)->delete();

Related

Filtering table results with drop down menu in Laravel

Created a drop down menu that is supposed to work as a filter. I am filtering with enum values so not sure how to make it work. The view + route are working fine. When the button is pressed the URL changes and adds the selected enum value /dropdown?filter_status=inactive. But the results are not filtered.
View:
<div class="container d-flex justify-content-start">
<div class="row">
<div class="col-md-12">
<form action="{{ route('dropdownView') }}" method="GET">
<div class="form-group">
<div>
<span>
<select class="mb-2" name="filter_status" >
<option value="Status" disabled selected>Status</option>
#foreach ($enumoption as $status)
<option value="{{ $status }}">{{$status}}</option>
#endforeach
</select>
<button type="submit" class="btn btn-primary btn-sm ms-1 mb-1">Filter</button>
</span>
</div>
</div>
</form>
</div>
</div>
</div>
Route:
Route::get("/dropdown", [CompetitionController::class, 'index'])->name('dropdownView');
Controller(getPossibleEnumValues is the function I am using in my model to get the enum values)
$enumoption = Competition::getPossibleEnumValues('competitions','status');
EDIT:
public static function getPossibleEnumValues($table, $column) {
$type = DB::select(DB::raw("SHOW COLUMNS FROM $table WHERE Field = '{$column}'"))[0]->Type ;
preg_match('/^enum\((.*)\)$/', $type, $matches);
$enum = array();
foreach( explode(',', $matches[1]) as $value )
{
$v = trim( $value, "'" );
$enum = Arr::add($enum, $v, $v);
}
return $enum;
}

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.

Problem with storing checkbox values in database

I am trying to store my checkbox values in database. I have these three tables.
fields
id name
1 gender
2 looking_for
field_values (here field_id references id on fields table)
id field_id value label
1 1 1 Men
2 1 2 Women
3 2 3 Relationship
4 2 4 Friendship
5 2 5 Marriage
user_interests (here field_id references field_id on field_values table and value_id references value on field_values table)
user_id field_id value_id
1 1 2
1 2 4
1 2 5
gender in blade uses option values and looking_for uses checkbox values. I made one function that is trying to update both of them. I use two foreaches in my function and I am able to successfully update gender option, but I am unable to update looking_for option. When I click submit button nothing happens, also when I dump anything inside that foreach that is supposed to update checkboxes it doesn't dump. Any help is greatly appreciated. Here is my code.
web.php
Route::patch('profile/interests', 'UserProfileController#updateInterestsData')->name('profile.update.interests.data');
UserProfileController.php
public function updateInterestsData(UpdateInterestsDataRequest $request)
{
$user = User::with('userProfile')->where('id', Auth::user()->id)->firstOrFail();
$request->validated();
$userId = $request->input('user_id') ? $request->input('user_id') : Auth::user()->id;
$data = $request->all();
$options = [
'gender' => 1,
'looking_for' => 2
];
foreach ($options as $fieldName => $fieldId) {
if (! empty($data[$fieldName])) {
DB::table('user_interests')
->where('user_id', $userId)
->where('field_id', $fieldId)
->delete();
if (is_array($data[$fieldName])) { // CHECKBOX FIELDS AND HERE IT DOESN'T WORK!!!
//dd('DIE!!!!!!') IT DOESN'T ENTER HERE!!!
foreach ($data[$fieldName] as $key => $value) {
DB::table('user_interests')->insert([
'user_id' => $userId,
'field_id' => $fieldId,
'value_id' => $value
]);
}
} else { // SELECT FIELDS!!!
DB::table('user_interests')->insert([
'user_id' => $userId,
'field_id' => $fieldId,
'value_id' => $data[$fieldName]
]);
}
}
}
$user->userProfile->update(
[
'age_from_preference' => $request->age_from_preference,
'age_to_preference' => $request->age_to_preference,
'updated_at' => Carbon::now()
]
);
$request->user()->save();
return redirect()->route('profile.show', [$user->username]);
}
index.blade.php
<form action="{{ route('profile.update.interests.data') }}" method="POST" class="flex">
#method('PATCH')
#csrf
<div class="form-group">
<span>Interessiert an</span>
{{-- wrong value - selected --}}
#isset($options)
#foreach($options as $name => $fieldData)
#if ($name == 'gender')
<div class="selectHolder">
<select name="{{ $name }}">
<option selected="true" disabled="disabled" value="" style="display:none">bitte auswählen</option>
#foreach($fieldData['data'] as $value => $label)
<option value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'selected' : '') : '' }}>
{{ $label }}
</option>
#endforeach
</select>
</div>
<?php
unset($options[$name]);
?>
#endif
#endforeach
#endisset
</div>
<div class="form-group">
<span>Im Alter von</span>
<input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_from_preference ?? "" }}" name="age_from_preference">
<span>Jahren bis</span>
<input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_to_preference ?? "" }}" name="age_to_preference">
<span>Jahren</span>
</div>
{{-- wrong value - checked --}}
#isset($options)
<div class="form-group flex mt-5">
#foreach($options as $name => $fieldData)
#if ($name == 'looking_for')
#foreach ($options[$name]['data'] as $value=>$label)
<div class="interestedIn">
<input type="checkbox" name="{{ $name.'-'.$value }}" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }}>
<label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>
#endforeach
#endif
#endforeach
</div>
#endisset
<div class="form-group">
<label for="" class="textBold">Button</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
code for $options variable
public static function getProfileLookingForDisplayOptions()
{
$options = [
'gender' => ['id' => 1, 'label' => "Interessiert an"],
'looking_for' => ['id' => 2, 'label' => ""]
];
$data_options = [];
foreach ($options as $field => $value) {
$data_options[$field]['data'] = Value::fieldValues($field);
$data_options[$field]['label'] = $options[$field];
if (!in_array($field, ['gender', 'looking_for'])) {
$data_options[$field]['data'][100] = "Doesn't matter";
}
}
//dd($data_options);
return $data_options;
}
If I understand your problem correctly, to deal with multiple checkboxes on PHP you need to add [] to its name property. That way, PHP knows it should interpret theses values as an array.
Also, your input name is not matching with $data[$fieldName].
Do it like this:
#isset($options)
<div class="form-group flex mt-5">
#foreach($options as $name => $fieldData)
#if ($name == 'looking_for')
#foreach ($options[$name]['data'] as $value=>$label)
<div class="interestedIn">
<input type="checkbox" name="{{ $name }}[]" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }} id="{{$name}}-{{ $value }}">
<label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>
#endforeach
#endif
#endforeach
</div>
#endisset

Laravel validate required_if when current input equals to a value that is inside an array (checkbox with input text)

I got a form with a list of checkboxes. The last one says "other", when clicked, an input text is enabled.
I have this rule where the user can check up to three options.
As you already know, checkboxes are stored in an array.
Should the user check on "other" option, without typing in the input, I want to prompt the user through an error message (validation) that they need to type in the input text, as well.
Here is options_list.blade.php view:
#section('content')
#if($errors->any())
<div class="alert alert-danger" role="alert">
<strong><i class="fas fa-exclamation-triangle"></i> Warning</strong>: The following errors have been found:
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="card">
<div class="card-body">
<div class="shadow p-3 mb-5 bg-white rounded">{{--Referencias: https://getbootstrap.com/docs/4.1/utilities/shadows/--}}
<p class="h6">
Here goes the question text
</p>
<p class="text-primary">You can choose up to three options</p>
</div>
<div class="shadow">
<form action="{{ route('survey1.post',$token) }}" method="post" id="myForm">
<div class="col-lg">
#foreach($lineasdeinvestigacion as $lineadeinvestigacion)
<div class="custom-control custom-checkbox my-1 mr-sm-2">
<input type="checkbox" class="custom-control-input" id="customControlInline{{ $loop->index + 1 }}" name="lineasdeinvestigacion[]" value="{{ $lineadeinvestigacion->linea }}" {{ old('lineasdeinvestigacion') && in_array($lineadeinvestigacion->linea,old('lineasdeinvestigacion')) ? 'checked' : (isset($encuesta) && ($encuesta->fortalecer_linea_1 == $lineadeinvestigacion->linea || $encuesta->fortalecer_linea_2 == $lineadeinvestigacion->linea || $encuesta->fortalecer_linea_3 == $lineadeinvestigacion->linea)) ? 'checked' : '' }}>
<label class="custom-control-label" for="customControlInline{{ $loop->index + 1 }}">{{ $lineadeinvestigacion->linea }}</label>
</div>
#endforeach
<div class="custom-control custom-checkbox my-1 mr-sm-2">
<input type="checkbox" class="custom-control-input" id="customControlInlineOtro" name="lineasdeinvestigacion[]" value="other" {{ old('lineasdeinvestigacion') && in_array('other',old('lineasdeinvestigacion')) ? 'checked' : (isset($encuesta) && ($encuesta->fortalecer_linea_1 == 'other' || $encuesta->fortalecer_linea_2 == 'other' || $encuesta->fortalecer_linea_3 == 'other')) ? 'checked' : '' }}>
<label class="custom-control-label" for="customControlInlineOtro">Other</label>
<input placeholder="" type="text" class="form-control form-control-sm" id="fortalecer_otro" name="fortalecer_otro" maxlength="255" value="{{ old('fortalecer_otro') ? old('fortalecer_otro') : '' }}" disabled>
</div>
#include('path.to.partials.buttons._continue'){{-- includes #csrf --}}
</div>
</form>
</div>
</div>
</div>
#endsection
And here is the optionsController.php:
public function store(Token $token, Request $request){
//dd($request->lineasdeinvestigacion);
//Validating input data
$this->validate($request,[
'lineasdeinvestigacion' => 'nullable|max:3',
'fortalecer_otro' => 'required_if:lineasdeinvestigacion.*,other|max:255',
],[
'lineasdeinvestigacion.max' => 'You cannot choose more than :max options.',
]);
}
This is the array of values chosen from the checkboxes list (dd($request->lineasdeinvestigacion);):
array:4 [▼
0 => "Procesos socio-culturales"
1 => "Ciencia, Innovación tecnológica y Educación"
2 => "Nuevas formas de movilidad"
3 => "other"
]
However, the validation is not working as it should, as it allows the input text #fortalecer_otro to be empty, when the "other" #customControlInlineOtro checkbox option is checked.
Way to solution
I think one workaround would be to separate the last item of the array, since the input to validate, if the last item (checkbox) has the other value, and add it as another element to be validated, as stated in this answer.
Or in this one, it talks about validating the last one. In my case, I would have to count the number of items and then, indicate to validate the number x, which would be the last item ...
How do I fix this? Any ideas?
Solved
I have realized, thanks to the second link that I should count the number of items in an array and then indicate inside the validation rules, which item check if value is other, then apply the required_if:
if($request->lineasdeinvestigacion){
$otro_item = count($request->lineasdeinvestigacion) - 1;
echo '<p>"other" is the item: '.$otro_item.'</p>';
}else{
echo '<p>Nothing was selected in the checkboxes list</p>';
}
//dd($request->lineasdeinvestigacion);
//Validating input data
$this->validate($request,[
'lineasdeinvestigacion' => 'nullable|max:3',
'fortalecer_otro' => 'required_if:lineasdeinvestigacion.'.$otro_item.',otro|max:255',
],[
'lineasdeinvestigacion.max' => 'No puede elegir más de :max opciones.',
]);
And that did the trick .
I have realized, thanks to the second link that I should count the number of items in an array and then indicate inside the validation rules, which item check if value is other, then apply the required_if:
if($request->lineasdeinvestigacion){
$otro_item = count($request->lineasdeinvestigacion) - 1;
echo '<p>"other" is the item: '.$otro_item.'</p>';
}else{
echo '<p>Nothing was selected in the checkboxes list</p>';
}
//dd($request->lineasdeinvestigacion);
//Validating input data
$this->validate($request,[
'lineasdeinvestigacion' => 'nullable|max:3',
'fortalecer_otro' => 'required_if:lineasdeinvestigacion.'.$otro_item.',otro|max:255',
],[
'lineasdeinvestigacion.max' => 'No puede elegir más de :max opciones.',
]);
And that did the trick .

Hide an element when a toggle is checked in PHP/Laravel

I am trying to hide an element on my page when I click a toggle and unhide it when I click the toggle again. Here is my HTML code:
<div class="form-group settings-row">
{{ Form::label('notificationSettings', 'Notification Settings', array('class' => 'col-md-2 control-label')) }}
<div class="col-md-10">
<table style="border-width:0; margin-top:4px;">
<tr>
<td>
Notifications Enabled
</td>
<td>
<div class="onoffswitch" style="margin:4px 0 0 7px;">
<input type="checkbox" #if($notificationsEnabled == true)checked #endif name="notifications_toggle" class="onoffswitch-checkbox" id="notifications_toggle">
<label class="onoffswitch-label" for="notifications_toggle">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
</td>
<td></td>
</tr>
</table>
<div class="col-md-10">
#foreach($notificationMessageRadios as $radio)
#if(isset($radio['text']))
<div class="row" style="margin-bottom:1em;">
<input type='radio' name='notificationMessage' id="notificationmessage-other" value="" #if($radio['selected']) checked #endif> {{$radio['message']}}
</div>
<input type="text" id="notificationMessageCustom" placeholder="Pick your own!" #if($radio['selected'])value="{{ $settingsForMessages->notification_message }}" #else value="Pick your own!" #endif name="notificationMessageCustom" class="form-control" #if(!$radio['selected'])style="display:none"#endif>
#else
<div class="row">
<input type='radio' name='notificationMessage' value="{{ $radio['message']}}" #if($radio['selected']) checked #endif> {{ $radio['message'] }}
</div>
#endif
#endforeach
</div>
</div>
</div>
Breakdown:
So when I click the onoffswitch to be on, I want the radios to appear. When I click the onoffswitch to be off, I want the radios to disappear.
I am being thrown into this project, so this code already existed and I am being tasked with editing some features. Any kind of help would be greatly appreciated.
As a bonus, here is the controller side:
$notificationsEnabled = ( $settings['notificationsEnabled'] == 1);
// Cast notification messages to a variable
$notificationMessageMsgs = \Config::get('customer_messages.notificationMessageArray');
$numNotificationMessageMsgs = count($notificationMessageMsgs);
$notificationMessageSelected = false;
// Determine which email subject radio button is checked
foreach($notificationMessageMsgs as $index => $msg) {
$isSelected = false;
if ($settingsForMessages->notification_message == null && $index == 0) {
$notificationMessageSelected = true;
$isSelected = true;
}
if($msg['message'] === $settingsForMessages->notification_message){
$isSelected = true;
$notificationMessageSelected = true;
}
if($index == $numNotificationMessageMsgs - 1 && !$notificationMessageSelected){
$isSelected = true;
}
$notificationMessageRadios[] = array_merge(['selected' => $isSelected], $msg);
}
I am NOT looking for hand holding. I am looking for guidance, that is all.
Maybe try out jQuery?
Try out jQuery Toggle : https://www.w3schools.com/jquery/eff_toggle.asp
$("button").click(function(){
$("p").toggle();
});
This is the code copies from the link . just target your "Class" , "ID" , "element" in the top row $("button") that needs to be clicked and than target the element that needs to be shown/hidden $("p")

Categories