Select Cascade Using jQuery and PHP in Laravel 4 - laravel

I'm trying to populate a select box based on a previous select box value in Laravel 4. Here's what I have so far:
My JS:
var url = document.location.hostname + '/cream/public/list-contacts';
var contacts;
$.ajax({
async: false,
type: 'GET',
url: url,
dataType: 'json',
success : function(data) { contacts = data; }
});
$('#account_id').change(function() {
alert(url);
label = "<label class='control-label'>Contacts</label>";
select = $("<select name='contact_id[]' id='contact_id'>");
console.log(contacts);
for(var i in contacts) {
alert(contacts[i]['account_id']);
if(contacts[i]['account_id'] == $(this).val()) {
select.append('<option value="' + contacts[i]['id'] + '">' + contacts[i]['name'] + '</option>');
}
}
$('.contacts').html(select).prepend(label);
});
My list-contacts route declaration:
Route::get('list-contacts', 'ContactListController#contacts');
My contacts() method in my ContactListController:
public function contacts()
{
return Contact::select('contacts.id', 'contacts.account_id', DB::raw('concat(contacts.first_name," ",contacts.last_name) AS name'))->get()->toArray();
}
The form in my view:
{{ Form::open(array('action' => 'DelegatesController#store', 'class' => 'view-only pull-left form-inline')) }}
{{ Form::label('account_id', 'Account', array('class' => 'control-label')) }}
{{ Form::select('account_id', $accounts) }}
<div class="contacts"></div>
{{ Form::label('delegate_status_id', 'Status', array('class' => 'control-label')) }}
{{ Form::select('delegate_status_id', $delegate_statuses) }}
{{ Form::label('price', 'Price', array('class' => 'control-label')) }}
{{ Form::text('price', '', array('class' => 'input-small')) }}
{{ Form::hidden('event_id', $event->id) }}
{{ Form::submit('Add Delegate', array('class' => 'btn btn-success')) }}
{{ Form::close() }}
EDIT: I've modified my code above. When I visit /list-contacts it gets the correct data I need, it's just not assigning that data to the contacts variable in my AJAX request in my JS? Any help would be appreciated.
Error: This is the error that is shown in my console log for the contacts variable:
file: "/Applications/MAMP/htdocs/cream/vendor/laravel/framework/src/Illuminate/Routing/Controllers/Controller.php"
line: 290
message: ""
type: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException"

I now have this working. It was to do with the generated URL in the AJAX request. I removed the document.location.hostname and hard coded the url without localhost.
Here's the working code for those interested:
My JS:
var url = '/cream/public/list-contacts';
var contacts;
$.ajax({
async: false,
type: 'GET',
url: url,
dataType: 'json',
success : function(data) { contacts = data; }
});
$('#account_id').change(function() {
select = $("<select name='contact_id' id='contact_id'>");
for(var i in contacts) {
if(contacts[i]['account_id'] == $(this).val()) {
select.append('<option value="' + contacts[i]['id'] + '">' + contacts[i]['name'] + '</option>');
}
}
$('.delegates .contacts').show();
$('.delegates .contacts .controls').html(select);
});
My list-contacts route declaration:
Route::get('list-contacts', 'ContactListController#contacts');
My contacts() method in my ContactListController:
public function contacts()
{
return Contact::select('contacts.id', 'contacts.account_id', DB::raw('concat(contacts.first_name," ",contacts.last_name) AS name'))->get();
}
The form in my view:
{{ Form::open(array('action' => 'DelegatesController#store', 'class' => 'delegates pull-left form-horizontal add-delegate')) }}
<div class="control-group">
{{ Form::label('account_id', 'Account', array('class' => 'control-label')) }}
<div class="controls">
{{ Form::select('account_id', $accounts) }}
</div>
</div>
<div class="control-group contacts">
{{ Form::label('contact_id', 'Contacts', array('class' => 'control-label')) }}
<div class="controls">
</div>
</div>
<div class="control-group">
{{ Form::label('delegate_status_id', 'Status', array('class' => 'control-label')) }}
<div class="controls">
{{ Form::select('delegate_status_id', $delegate_statuses) }}
</div>
</div>
<div class="control-group">
{{ Form::label('price', 'Price', array('class' => 'control-label')) }}
<div class="controls">
{{ Form::text('price', '', array('class' => 'input-small')) }}
</div>
</div>
{{ Form::hidden('event_id', $event->id) }}
{{ Form::close() }}

Related

Symfony redirect by ajax

The page login use ajax, in controller response in view web browser {"response":true,"data":{"from":"apachecms_api_login_submit","to":"/dashboard"}} and not redirect.
function to ajax when success
function beforeSuccess(data){
if(data.data.from=='apachecms_api_login_recovery_submit'){
loading.hide();
$.toast({
heading: "{{ 'success' | trans }}",
text: "{{ 'forgot.password.sending' | trans }}",
position: 'top-right',
icon: 'success',
hideAfter: 5000,
stack: 10
});
changeForm('login')
}else if(data.data.from=='apachecms_api_login_submit'){
location.href=data.data.to;
}else if(data.data.from=='apachecms_api_login_create_submit'){
location.href=data.data.to;
}
}
Whats happend?
LoginController.php extends BaseController
public function loginAction(Request $request){
$form=$this->createForm(LoginType::class, null,array('action'=>$this->generateUrl('apachecms_api_login_submit'),'method' => 'POST'));
$form->handleRequest($request);
if($errors=$this->ifErrors($form)) return $errors;
try {
$entity = $this->getDoctrine()->getRepository('ApachecmsBackendBundle:Customer')->findOneBy(array('email'=>$form->get('_username')->getData(),'isDelete'=>false));
if(!$entity)
throw new Exception(null,200);
$encoder_service = $this->get('security.encoder_factory');
$encoder = $encoder_service->getEncoder($entity);
if(!$encoder->isPasswordValid($entity->getPassword(), $form->get('_password')->getData(), $entity->getSalt()))
throw new Exception(null,200);
$token = new UsernamePasswordToken($entity, $form->get('_password')->getData(), "main", $entity->getRoles());
$this->get("security.token_storage")->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
return $this->responseOk(array('from'=>'apachecms_api_login_submit','to'=>$this->generateUrl('apachecms_frontend_dashboard'))); // HERE RETURN RESPONSE
}catch (Exception $excepcion) {
return $this->responseFail(array(array('property'=>'_username','code'=>'invalid_credentials','message'=>$this->get('translator')->trans('invalid.credentials'),'data'=>null)),200);
}
}
BaseController.php
public function responseOk($data=array(),$code=200){
try{
// if(!$data)
// throw new Exception('No se encontró el registro',200);
return new Response($this->get('jms_serializer')->serialize(
array('response'=>true,'data'=>$data),
'json',$this->context),$code);
}catch (Exception $excepcion) {
return $this->responseFail(array(array(
'property'=>null,
'message'=>$excepcion->getMessage(),
'code'=>'not_found',
'data'=>null
)),$excepcion->getCode());
}
}
index.html.twig <= Login Page
{{ form_start(formLogin, {'attr': {'id':'loginform','novalidate':'novalidate','class':'form-horizontal form-material sendToApi login'} }) }}
<div class="form-group">
<div class="col-xs-12">
{{form_widget(formLogin._username)}}
<small class="text-danger error">{{ form_errors(formLogin._username) }}</small>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
{{form_widget(formLogin._password)}}
<small class="text-danger error">{{ form_errors(formLogin._password) }}</small>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<div class="checkbox checkbox-info pull-left p-t-0"></div>
<a href="javascript:changeForm('recovery')" id="to-recover" class="text-dark pull-right">
<i class="fa fa-lock m-r-5"></i> {{ 'forgot.password' | trans }}</a>
</div>
</div>
<div class="form-group text-center">
<div class="col-xs-12 p-b-20">
{{form_widget(formLogin.submit,{ 'attr':{ 'class':'btn btn-block btn-lg btn-info btn-rounded','secondary-label':'loading' | trans}})}}
</div>
</div>
{{ include('ApachecmsFrontendBundle::Login/social.html.twig') }}
<div class="form-group m-b-0">
<div class="col-sm-12 text-center">
{{ 'not.account' | trans }}
<a href="javascript:changeForm('register')" class="text-info m-l-5">
<b>{{ 'register' | trans }}</b>
</a>
</div>
</div>
{{ form_end(formLogin) }}
Ajax
// pre-submit callback
function showRequest(formData, form, options) {
loading.show('{{ 'loading' | trans }}');
var url = form.attr("action");
var method = form.attr("method").toUpperCase();
var dataForm = form.serialize();
var submitBtn = form.closest('form').find(':submit');
var inputs=form.closest('form').find(':input:not(.dropify)');
inputs.removeClass('error');
inputs.next('small').html('');
BtnSecondaryLabel=submitBtn.attr('secondary-label');
BtnHtml=submitBtn.html();
submitBtn.html('<i class="fa fa-gear fa-spin"></i> '+BtnSecondaryLabel);
submitBtn.attr('disabled',true);
return true;
}
// post-submit callback
function showResponse(data, statusText, xhr, form) {
var submitBtn = form.closest('form').find(':submit');
submitBtn.attr('disabled',false);
submitBtn.html(BtnHtml);
if(data.response==true){
beforeSuccess(data);
}
}
$(function (){
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$( "form.sendToApi" ).ajaxForm(options); <= capture class to form sendToApi
})
function beforeSuccess(data){
if(data.data.from=='apachecms_api_login_recovery_submit'){
loading.hide();
$.toast({
heading: "{{ 'success' | trans }}",
text: "{{ 'forgot.password.sending' | trans }}",
position: 'top-right',
icon: 'success',
hideAfter: 5000,
stack: 10
});
changeForm('login')
}else if(data.data.from=='apachecms_api_login_submit'){
location.href=data.data.to;
}
}

How to update user status using button without update all parameters in laravel

i want to update status user just pass parameter of 'status'.
this is my code, but i don't know, why i can not update user status. how to fix this problem?
my controller
public function activation()
{
// dd('test');
$action = Input::get('status');
if (Input::get('activate'))
{
$this->activateUser($action);
}
elseif (Input::get('inactivate'))
{
$this->deactivateUser($action);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
public function activateUser($user)
{
//dd('active');
User::findOrNew($user)->update(['status' => "1"]);
}
public function deactivateUser($user)
{
// dd('nonactive');
User::findOrNew($user)->update(['status' => "0"]);
}
my route
Route::post('admins-users/status', 'Backend\StatusController#activation');
my view
{!! Form::open(array('url' => 'admins-users/status')) !!}
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
After trying several ways. finally, i was found the answer for this problem using Ajax and select option. i add hash id before pass to controller and decode again in controller. i thinks id that pass must be concerned.
my controller
public function control(Request $request){
$status = $request->status;
$iduser = $request->iduser;
$key = Hashids::connection('main')->decode($iduser)[0] ?? abort(404);
$update = User::where('id', $key)->update(['status'=> $status]);
if($update)
{
return redirect(route('admins-users.index'))->with('message-post', 'Status user was updated successfully');
}
}
my form
using hash id to encode id user
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
{!! Form::hidden(null,$parameter, ['id'=> 'iduser'.$parameter ])!!}
{!! Form::select(
'status',
array(1=>'Active',0=>'Not Active'),
$user->exists ? $user->status : null,
[
'id' => 'action'.$parameter,
'placeholder' => 'Choose a status'
]
)
!!}
script
$(document).ready(function(){
#foreach($users as $user)
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
$("#action{{ $parameter }}").change(function(){
var status = $("#action{{ $parameter }}").val();
var iduser = $("#iduser{{ $parameter }}").val();
if(status==""){
alert("Please select an option");
}
else{
if (confirm('Do you want to change {{ $user->name }} status to {{ $user->status ? 'InActive' : 'Active' }}?')) {
$.ajax({
url: '{{ url("/action") }}',
data: 'status=' + status + '&iduser=' + iduser,
type: 'get',
success:function(response){
console.log(response);
}
});
document.location.reload();
}
}
});
#endforeach
});
Try with this
{!! Form::open(['url' => 'admins-users/status', 'method' => 'get' !!}
<input type="hidden" name="user_id" value="{{ $user->id }}">
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
Your route
Route::get('admins-users/status', 'Backend\StatusController#activation');
Your Controller Method
public function activation(Request $request)
{
$user_id = $request->user_id
if ($request->acticate) {
$this->activateUser($user_id);
}
elseif ($request->inactiavte) {
$this->deactivateUser($user_id);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
Hope this helps :)

How to pass array to flash message?

I want to send array of additional_feature that they are exist to flash message. Now i only send one additional_feature. Any suggestion how can i do that?
if(!empty($additional_features)){
foreach($additional_features as $additional_feature){
$data = [
'name' => $additional_feature,
];
if (!Feature::where('name', '=', $additional_feature)->exists()) {
$additional = Feature::firstOrCreate($data);
$additional_ids[] = $additional->id;
}
else{
return redirect()->back()->withFlashMessage($additional_feature . ' exists!');
}
}
}
You can use session() instead of with():
session->flash('someVar', $someArray);
Another thing you could try is to seriallize array and pass it as string. Then unserilize it and use.
Also, you could save an array using simple session:
session(['someVar' => $someArray]);
Then get it and delete manually:
session('somevar');
session()->forget('someVar');
We had the same problem and forked the package. you can find it here:
Forked at first from Laracasts/Flash to use multiple message
#if (Session::has('flash_notification.message'))
#if (Session::has('flash_notification.overlay'))
#include('flash::modal', ['modalClass' => 'flash-modal', 'title' => Session::get('flash_notification.title'), 'body' => Session::get('flash_notification.message')])
#else
<div class="alert alert-{{ Session::get('flash_notification.level') }}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{!! Session::get('flash_notification.message') !!}
</div>
#endif
#endif
And the content of the include flash::modal
#if (Session::has('flash_notification.messages'))
#foreach (Session::get('flash_notification.messages') as $flashMessage)
#foreach($flashMessage as $type => $message)
<script>
$(function() {
var message = ('{{ $message }}<br>').replace(/'/g, "’");
customFlashMessage({
type: "{{ $type }}",
message: message
});
});
</script>
#endforeach
#endforeach
#endif
return redirect()->back()->with(['session1' => $value, 'session2' => $value]);
In the blade template:
{{ Session::get('session1') }}
{{ Session::get('session2') }}

controller not recognizing data from view laravel 4.2

hi so i have this function where the user edits a certain record. In my view, i already populated the input form it looks like this
behind the view here is my code
{{ Form::model($list, array('route' =>array('modfyFilesave',$list->subcategoryid , $list->fileid),'method'=>'PUT')) }}
<h6>Filename : </h6>
{{ Form::text('x', $list->filename , array('class' => 'validate')) }}
<h6>File type : {{ $list->filetype }} </h6>
#if($list->filetype == 'ppt' || $list->filetype == 'pptx')
<img src="{{ asset('img/ico/pptico.PNG') }}" class="imgico">
#elseif($list->filetype == 'doc' || $list->filetype == 'docx')
<img src="{{ asset('img/ico/wordico.PNG') }}" class="imgico">
#elseif($list->filetype == 'pdf')
<img src="{{ asset('img/ico/pdfico.PNG') }}" class="imgico">
#elseif($list->filetype == 'xls' || $list->filetype == 'xlsx')
<img src="{{ asset('img/ico/excelico.PNG') }}" class="imgico">
#elseif($list->filetype == 'txt')
<img src="{{ asset('img/ico/txtico.PNG') }}" class="imgico">
#elseif($list->filetype == 'csv')
<img src="{{ asset('img/ico/csvico.PNG') }}" class="imgico">
#endif
<h6>Size : {{ $list->filesize }} </h6>
#if($list->confidential == 'true')
{{ Form::checkbox('conf', 'true', true , array('id' => 'test5')) }}
<label for="test5">confidential</label>
#else
{{ Form::checkbox('conf', 'true', null , array('id' => 'test5')) }}
<label for="test5">confidential</label>
#endif
{{Form::select('sCategory',[ $list->subcategoryid =>'CURRENT CATEGORY : ' . $list->subcategoryname . ' | ' . $list->maincategoryname] + $cats )}}
{{ Form::submit('save', array('class' => 'btn btn-primary defcolor')) }}
{{ Form::close()}}
then the function that receive this is here
public function savemodfile($scid , $id)
{
$rules = array(
'x' => 'required|min:2|max:250|unique:nsa_fileuploads,filename'
);
$messages = array(
'x.required' => 'Please provide a filename.',
'x.min' => 'Filename should have atleast 2 characters.',
'x.max' => 'Filename can only have maximum of 250 characters.',
'x.unique' => 'Filename already exist.'
);
$validator = Validator::make(Input::all(), $rules , $messages);
if ($validator->fails())
{
dd('some errors');
}
else
{
dd('okay');
}
}
the thing is, it always go inside the if($validator->fails()) even tho in my view, there is data. anybody who could point out my error? or improve my code? thanks so much in advance!
Try dumping the errors the validator returns, the messages given should give you a direction what exactly failed when validating.
// dump errors
dd($validator->messages()->toArray());
For more information, see: https://laravel.com/docs/4.2/validation#error-messages-and-views

Laravel form submit with route and controller

1.How can i get correct routing into form open phrase.
2.I wanted to generate the URL: dgrs/2014-31-01.
form in only view file: dgrs/show.blade.php
{{ Form::open(array('action'=>'DgrsController#ddgr')) }}
Select Date:
{{ Form::input('date', 'dgrdate', $dt, array('class' => 'input-md')) }}
{{ Form::submit('View', array('class'=>'btn btn-primary')) }}
{{ Form::close() }}
routes.php
Route::match(array('GET', 'POST'), 'dgrs/(:date)', ['as'=>'ddaily', 'uses'=>'DgrsController#ddgr']);
DgrsController.php
public function ddgr($date)
{
$dt=isset($date) ? $date : date("Y-m-d"); //date selection from user
...
return View::make('dgrs.show', compact('dfinal', 'dt'));
//dfinal is db query and dt is selected date back to show.blade.php
}
view is the form file: dgrs/show.blade.php
Please advise.
Here is a solution with jQuery
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
{{ Form::open(array('action'=>'DgrsController#ddgr' , 'id' => 'myFrm')) }}
Select Date:
{{ Form::input('date', 'dgrdate', $dt, array('class' => 'input-md' , 'id' => 'txtDate')) }}
{{ Form::submit('View', array('class'=>'btn btn-primary')) }}
{{ Form::close() }}
<script>
$(document).ready(function(){
$("#txtDate").change(function(){
var baseUrl = "{{ URL::to("dgrs") }}" + "/" + $(this).val();
$("#myFrm").attr("action",baseUrl);
});
});
</script>
so what i have done is when ever date changes form action url is changes according to that date.

Resources