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

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")

Related

How do I update records in a loop in Laravel 8

I am developing a student portal in Laravel 8. I would love to update the class subjects.
Here is my controller
public function UpdateAssignSubject(Request $request, $class_id)
{
if ($request->subject_id == null) {
$notification = [
'message' => 'Sorry You did not Select any Subject',
'alert-type' => 'error'
];
return redirect()->route('assign.subject.edit', $class_id)->with($notification);
} else {
$countClass = count($request->subject_id);
AssignSubject::where('class_id', $class_id)->delete();
for ($i = 0; $i < $countClass; $i++) {
$assign_subject = new AssignSubject();
$assign_subject->class_id = $request->class_id;
$assign_subject->subject_id = $request->subject_id[$i];
$assign_subject->full_mark = $request->full_mark[$i];
$assign_subject->pass_mark = $request->pass_mark[$i];
$assign_subject->subjective_mark = $request->subjective_mark[$i];
$assign_subject->save();
} // End For Loop
}// end Else
$notification = [
'message' => 'Assigned Subject Updated Successfully',
'alert-type' => 'success'
];
}
This very piece of code AssignSubject::where('class_id', $class_id)->delete(); is giving me issues since I am using the AssignSubject as a pivot table thus deleting the Id's produces errors in the long run.
Here is my view
#foreach($subjects as $subject)
<option value="{{ $subject->id }}" {{ ($edit->subject_id == $subject->id)? "selected": ""
}}>{{ $subject->name }}</option>
#endforeach
<div class="form-group">
<h5 style="color:black">Full Mark <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="full_mark[]" value="{{ $edit->full_mark }}" class="form-control"
style="background-color: rgb(176, 172, 216);color:black" >
</div>
<div class="col-md-2">
<div class="form-group">
<h5 style="color:black">Pass Mark <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="pass_mark[]" value="{{ $edit->pass_mark }}" class="form-control"
style="background-color: rgb(176, 172, 216);color:black">
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<h5 style="color:black">Subjective Mark <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="subjective_mark[]" value="{{ $edit->subjective_mark }}" class="form-
control" style="background-color: rgb(176, 172, 216);color:black">
</div>
</div>
</div>
Please how can I update the record without deleting first. Any help would be greatly appreciated.
Instead of deleting all entities, you can simply update them if they do exist.
In case they do not, you need to create a new one, like you did in your for loop.
I adjusted your code, to check if a subject already exists, if it does it updates it, otherwise a new one is created
$countClass = count($request->subject_id);
// remove this line
// AssignSubject::where('class_id', $class_id)->delete();
for ($i = 0; $i < $countClass; $i++) {
// a class can only have each subject 1 time, so you can filter for it
$entity = AssignSubject::where('class_id', $class_id)
->where('subject_id', $request->subject_id[$i])
->first();
// if entry does not exist, ->first() will return null, in this case, create a new entity
$assign_subject = $entity ?? new AssignSubject();
// update columns
$assign_subject->class_id = $request->class_id;
$assign_subject->subject_id = $request->subject_id[$i];
$assign_subject->full_mark = $request->full_mark[$i];
$assign_subject->pass_mark = $request->pass_mark[$i];
$assign_subject->subjective_mark = $request->subjective_mark[$i];
// save changes
$assign_subject->save();
}

how to read Currencies Exchange Rates right?

Does anyone know a way to read the currency exchange rates right in laravel?
We develop web exchange currency so I have a problem when I put right rates but get a different results.
Example: Exchange between USD TO EGP : 1 USD = 15.70 EGP So i need to Put the Currency USD TO get 15.70 EGP but if i put this will get Rates - 1 USD = 4 EGP not 15.70
Follow the pictures to understand
1-
2-
3-
4-
So my question is:
Does anybody know a way to solve these rates?
Home Blade
<form class="exchange-form" method="POST" action="{{ route('user.exchange') }}">
#csrf
<div class="form-group">
<label for="send">#lang('You Send')</label>
<input type="text" name="send_amount" id="send_val" placeholder="#lang('Send')" required
onkeyup="this.value = this.value.replace (/^\.|[^\d\.]/g, '')">
<select class="select-bar" name="send" id="send">
<option value="">#lang('Select Currency')</option>
#foreach ($currencys_sell as $currency)
<option value="{{ $currency->id }}"
data-min_max="{{ filterCollection($currency, 'rate', 'sell_at', 'buy_at', 'fixed_charge', 'percent_charge', 'reserve', 'min_exchange', 'max_exchange', 'cur_sym', 'payment_type_sell') }}">
{{ $currency->name }} {{$currency->cur_sym}}
</option>
#endforeach
</select>
<div class="exchange-limit exchange-buy d-none">
<div class="item">
<span class="subtitle">#lang('Min')</span>
<span class="amount min-amount"></span>
</div>
<div class="item">
<span class="subtitle">#lang('Max')</span>
<span class="amount max-amount"></span>
</div>
</div>
</div>
<div class="form-group receiveData">
<label for="receive">#lang('You Get')</label>
<input type="text" name="receive_amount" id="receive_val" min="0" placeholder="#lang('Receive')"
readonly>
<select class="select-bar" name="receive" id="receive">
<option value="" class="wrap">#lang('Select Currency')</option>
#foreach ($currencys_buy as $currency)
<option value="{{ $currency->id }}"
data-min_max="{{ filterCollection($currency, 'cur_sym', 'rate', 'sell_at', 'buy_at', 'fixed_charge', 'percent_charge', 'reserve', 'min_exchange', 'max_exchange', 'payment_type_sell') }}">
{{ $currency->name }} {{$currency->cur_sym}}
</option>
#endforeach
</select>
<div class="exchange-limit reserve-section d-none">
<div class="item reserve">
<span class="subtitle">#lang('Reserve')</span>
<span class="amount"></span>
</div>
<div class="item reserve">
<span class="subtitle">#lang('Rate')</span>
<span class="amount conversion"></span>
</div>
</div>
</div>
Home Controller
public function exchange(Request $request)
{
session()->forget('Track');
$receive = Currency::find($request->receive);
$send = Currency::find($request->send);
if ($receive == null) {
$notify[] = ['error', 'Select any method that we send u the money'];
return back()->withNotify($notify);
}
if ($send == null) {
$notify[] = ['error', 'Select any method that we get money'];
return back()->withNotify($notify);
}
$field = json_decode($receive->user_input);
$validate_array = [
'send' => 'required|numeric',
'send_amount' => 'required|numeric|gt:0',
'receive' => 'required|numeric',
'receive_amount' => 'required|numeric|gt:0',
];
foreach ($field as $value) {
if (strtolower($value->type) === 'email') {
$validate_array[$value->field_name] = "sometimes|{$value->validation}|email";
continue;
}
$validate_array[$value->field_name] = "sometimes|{$value->validation}";
}
$this->validate($request, $validate_array);
// new Calculation for covert amount
$percentCharge = ($request->send_amount * $send->percent_charge) / 100;
$totalCharge = $percentCharge + $send->fixed_charge;
$totalSendAmount = $request->send_amount - $totalCharge;
$sendAmountConvertInBaseCurrency = $totalSendAmount * $send->buy_at;
$userReceiveAmount = $sendAmountConvertInBaseCurrency / $receive->sell_at;

How to remove unwanted values from arrayed input?

I just wanted to ask how can we avoid this kind of output from arrayed input. Every time I update it, these symbols ["\"[ keeps on multiplying. I'll show you the problem and the code below.
Thank you your future answers.
Route::resource('setups','SetupController');
public function index()
{
$data = DB::table('setups')->first();
if (!empty($data)) {
$socials = explode(',',$data -> social);
}else{
$socials = [];
}
return view ('adminpanel.setup.index',['data' => $data,'socials' => $socials]);
}
index.blade.php
<form action="{{ route('setups.edit',$data->id) }}">
<div class="row">
<div class="col-md-12" id="socialGroup">
#foreach($socials as $social)
<div class="form-group socialField">
<label class="bmd-label-floating">Social Links</label>
<input type="text" name="social[]" value="{{$social}}" class="form-control" disabled>
<i class="fa fa-plus"></i>
</div>
#endforeach
<div class="alert alert-danger" id="socialError">
<p><strong>Sorry! </strong>You've reached the max number for social links form.</p>
</div>
</div>
</div>
<form>
.
public function edit($id)
{
$data = DB::table('setups')->first();
$setup = DB::table('setups')->where('id', $id)->first();
if (!empty($data)) {
$socials = explode(',',$data -> social);
}else{
$socials = [];
}
if($setup){
return view ('adminpanel.setup.edit',['data' => $data,'socials' => $socials]);
}else{
return redirect('setups');
}
}
.
edit.blade.php
<form method="POST" action="{{ route('setups.update', $data->id) }}">
<div class="row">
<div class="col-md-12" id="socialGroup">
#foreach($socials as $social)
<div class="form-group socialField">
<label class="bmd-label-floating">Social Links</label>
<input type="text" name="social[]" value="{{ $social }}" class="form-control">
<i class="fa fa-plus"></i>
</div>
#endforeach
<div class="alert alert-danger" id="socialError">
<p><strong>Sorry! </strong>You've reached the max number for social links form.</p>
</div>
</div>
</div>
<form>
.
public function update(Request $request, Setup $setup)
{
$data = Input::except('_token', 'submit', '_method');
$tbl = decrypt($data['tbl']);
unset ($data['tbl']);
$data['updated_at'] = date('Y-m-d H:i:s');
DB::table($tbl)->where(key($data), reset($data))->update($data);
session::flash('message','Setup updated successfully!!!');
return redirect()->route('setups.index');
}
Solved! I just added this code in my SetupController#update to illuminate those unwanted divider or separator(whatever) before
sending to database.
if (Input::has('social')) {
$data['social'] = implode(',',$data['social']);
}
laravel escaped data by default. It was not giving any error,whenever
you retrieve data from database to throw in your blade view.Database
data escaping is good practice.
As you showed your data,there is some unwanted data.Before you attempt to save your data,you may trim($yourString) to remove unwanted white-space from start & end of a string.
And You must not let blank or empty string to view in your blade. So, you might use blank($var) to check whether it is blank or not?
<form method="POST" action="{{ route('setups.update', $data->id) }}">
<div class="row">
<div class="col-md-12" id="socialGroup">
#foreach($socials as $social)
#if(!blank($social))
<div class="form-group socialField">
<label class="bmd-label-floating">Social Links</label>
<input type="text" name="social[]" value="{{ $social }}" class="form-control">
<i class="fa fa-plus"></i>
</div>
#endif
#endforeach
<div class="alert alert-danger" id="socialError">
<p><strong>Sorry! </strong>You've reached the max number for social links form.</p>
</div>
</div>
</div>
Solved! I just added this code in my SetupController#update
if (Input::has('social')) {
$data['social'] = implode(',',$data['social']);
}

How to add an PHP IF statement in this Script?

$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
I want to be able to add an if statement in this result_2 string.
This is for displaying a product, and i would like to display price depending on users session value?
eg.
if ($_SESSION['customer_x'] == a) {
display price a
}
else if ($_SESSION['customer_x'] == b) {
display price b
}
Is this the correct method to be able to add an if statement to a JSON query?
After Starting your while loop, put a if else there,
$price ="";
if ($__SESSION['customer_x'] == a) {
$price='display price a';
}
else if ($_SESSION['customer_x'] == b) {
$price='display price b';
}
and now echo this price where ever you want to in your html
this is more neet and less messy way
You can use a ternary if operator to have conditional statements inside strings, example
$bool = false;
echo "The value of \$bool is " . ($bool == true ? "TRUE" : "FALSE");
Example in use
To add that you can keep doing the same but:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ // the next of the content
$priceOfSession = ($__SESSION['customer_x'] == a) ? 'pricea' : 'priceb';
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
'.$priceOfSession.'
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
</div>
';
}
So if you want to evaluate only two conditions if otherwise the if you want, simply add it there. Do as you add the $ row but before defining value.

return error with dynamic field

I have this view
<div id="div_email" class="panel panel-default">
<div class="panel-heading">
<div style="float:left;margin-top:7px;">
Email
</div>
<div align="right" >
<a class="btn btn btn-default btn-square" onclick="add_email()"><i class="fa fa-plus" ></i></a>
</div>
</div>
<div class="panel-body">
<div id="dynamic_email" class="form-group input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
{{ Form::text('email', Input::old('email'), array('id'=>'email1','name'=>'email[]','class'=>'remove_err_onkeyup form-control','placeholder'=>'Email', 'onblur'=>'fetchRecord()', 'autocomplete' => 'off')) }}
</div>
#if($errors->has('email'))
<div class="err text-danger">
#foreach($errors->get('email') as $key => $message)
{{ $message }}
#if($key + 1 < count($errors->get('email')))
<br>
#endif
#endforeach
</div>
#endif
</div>
</div>
which will call a jquery function to add additional textbox when the + button is clicked
function add_email()
{
var ctr = $("#dynamic_email").length + 1;
var email_html = $('<div class="form-group input-group"><span class="cs_icon_cursor input-group-addon" onclick="remove_input($(this))" onmouseover="$(this).children(\'i\').attr(\'class\',\'fa fa-times\').css(\'width\',\'14px\')" onmouseout="$(this).children(\'i\').attr(\'class\',\'fa fa-envelope\')"><i class="fa fa-envelope"></i></span><input id="email'+ ctr +'" class="form-control" type="text" name="email[]" placeholder="Email"></div>');
email_html.hide();
$("#dynamic_email").after(email_html);
email_html.fadeIn('slow');
}
The form will then be submitted through form submit, the input data will be
'email' =>
array (
0 => 'abc#email.com',
1 => 'def#email.com',
)
so I do my own validation to validate the email
//check if email is set prevent error
if(isset($inputs['email']))
{
//check if theres an email set
if(count($inputs['email']) > 0)
{
//loop through the email
foreach($inputs['email'] as $email)
{
if($email)
{
//check email format if valid
if(filter_var($email, FILTER_VALIDATE_EMAIL) == FALSE)
{
// display_output('invalid email');
$validator->getMessageBag()->add('email','Invalid Email: '.$email);
$err_flag++;
}
else
{
//if email format is valid. next check domain if valid
//get domain name
$domain = explode('#',$email)[1];
//check domain if valid
if(checkdnsrr($domain, "ANY") == FALSE )
{
// display_output('invalid domain');
$validator->getMessageBag()->add('email','Invalid domain: '.$domain);
$err_flag++;
}
}
}
}
}
}
if($err_flag > 0)
{
return Redirect::to('researcher/create')
->withInput()
->withErrors($validator);
}
My question is, will it be possible during form submit, to return the old emails value into the textbox? I am getting this error
htmlentities() expects parameter 1 to be string, array given
From my understanding, the input being returned to the email input is array, how can I add the correct textbox count and the value inside the textbox?
Try using a loop to iterate over all your emails. The error tells you that Input::old('email') returns an array, which is obvious since you have multiple email fields.
#if(is_array(Input::old('email')))
#foreach(Input::old('email') as $index => $email)
<!-- your other html -->
{{ Form::text('email', $email, array('id'=>'email'.($index+1),'name'=>'email[]' /* ... */)) }}
#endforeach
#else
<!-- your other html -->
{{ Form::text('email', $email, array('id'=>'email1', 'name'=>'email[]' /* ... */)) }}
#endif

Categories