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
Related
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();
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']);
}
good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$product=new productModel();
// start add
$product->name=$request->input('name');
$product->save();
$add=$product->id;
$poducten=new productEnModel();
$poducten->id_product=$add;
$poducten->name=$request->input('name');
$poducten->price=$request->input('price');
$poducten->save();
$dataview['message']='data addes';
}else{
$dataview['message']='name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
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 .
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")