Retrieving input from Form Select - Laravel - php

When I select a class from in my view and click on Genrate, I try to retrieve the value of the selected class but I am not able to get the value of the class selected.
When I return $condition, it returns empty. In the url after submitting, it shows like http://localhost:8000/generate/timetable?class=
Why is this happening?
<div class="row">
<div class="col-xl-4 col-lg-12 col-md-12 mb-1">
<fieldset class="form-group">
<label for="squareText">Type</label>
{{ Form::select('class',$classes,$selectedClass,['class'=>'form-control','required'=>'true'])}}
<br>
<button class="btn btn-primary pull-left square" type="submit"><i class="glyphicon glyphicon-th"></i> Generate</button>
</fieldset>
</div>
</div>
Controller
$condition = Input::get('class');
if (!isset($condition['class']))
$condition['class'] = 0;
$courses = $course->where('class',$condition)->get()->toArray();
return $condition;

Your button is inside a link:
<a href="/generate/timetable?class={{ request('class') }}">
<button class="btn btn-primary pull-left square" type="submit"> ... </button>
</a>
Clicking it is actually clicking the <a href> link, not clicking the button and submitting the form. So instead of submitting the form, you are simply browsing to the URL the the link points to.
It isn't clear from your question what the link is there for, but if clicking the button is supposed to submit the form, you probably want to put your form elements inside an actual <form>.
It looks like you're using Laravel Collective ({{ Form::select('class .... looks like that), so see those docs on how to open a form:
{!! Form::open(['url' => '/generate/timetable?class=' . request('class')]) !!}
{{ Form::select('class' .... }}
<button class="btn btn-primary pull-left square" type="submit"> ... </button>
{!! Form::close() !!}
You'll probalby also need to add a CSRF token, it is also described in the Laravel Collective docs, as well as in the Laravel docs.

Related

How to Transfer Value From One Form Field to Another Field in Laravel?

The code below is used to show all plans. As you can see there is a SELECT plan option. I want for any plan when I click on SELECT it should pass its ID to the second field.
I used $request->gate->id but it did not work in my Blade file.
#foreach($pack as $gate)
<div>
<p style="color: #000">Amount: {{$gate->min_amount}} {{$general->symbol}} -
</div>
<div class="panel-footer">
<button class="btn btn-primary btn-block">SELECT</button>
</div>
#endforeach
{{csrf_field()}}
<input type="text" name="package_id" value="{{$gate->id}}"> // I want to Transfer here when click on select.
You need to use some jQuery code to set the gate id as the value of the input field with the name package_id
Try this:
#foreach($pack as $gate)
<div>
<p style="color: #000">Amount: {{$gate->min_amount}} {{$general->symbol}}
</div>
<div class="panel-footer">
<button class="btn btn-primary btn-block" data-gate-id="{{$gate->id}}">SELECT</button>
</div>
#endforeach
<input type="text" name="package_id" value="">
Use this jQuery code on the same page:
$('.btn-block').on('click', function() {
var gate_id = $(this).data('gate-id'); // get gate id from button custom attribute data-gate-id on click
$("input[name='package_id']").val(gate_id); // set gate id in input field
});

Laravel - Approve and decline buttons on one form for same controller with form action

I have two buttons on my form, Approve and Decline
{{ Form::open(['route' => ['holidays.update', $holidayRequest->id]]) }}
<button type="submit" class="btn btn-success">
<i class="fa fa-check"></i>Approve
</button>
<button type="submit" class="btn btn-danger">
<i class="fa fa-times"></i>Decline
</button>
{{ Form::close() }}
There is an object called $holidayRequest which I have passed to this form from the controller, and my intention is to send a value of the $holidayRequest->status back to the controller. That is, one of the following should occur:
User clicks on Approve: $holidayRequest->status == 'approved' is sent to controller.
User clicks on Decline: $holidayRequest->status == 'declined' is sent to controller.
Should I use the attribute formactionto achieve this goal or something else? How do I go about this with as little or no JS as possible?
Try something like this using jquery():
Html:
<button type="button" id="approved" class="btn btn-success response">
<i class="fa fa-check"></i>Approve
</button>
<button type="button" id="declined" class="btn btn-danger response">
<i class="fa fa-times"></i>Decline
</button>
Jquery:
$('.response').click(function(){
var resposne = $(this).attr('id');
// It gives you: approved or declined
// make an ajax call with this response and update the data in database
});
Note: Do not forget to include jquery library in your page.
If you don't want javascript then try submitting them individually.
{{ Form::open(['route' => ['holidays.update', $holidayRequest->id]]) }}
<input type="hidden" status="approved"/>
<button type="submit" class="btn btn-success">
<i class="fa fa-check"></i>Approve
</button>
{{ Form::close() }}
{{ Form::open(['route' => ['holidays.update', $holidayRequest->id]]) }}
<input type="hidden" status="declined"/>
<button type="submit" class="btn btn-danger">
<i class="fa fa-times"></i>Decline
</button>
{{ Form::close() }}

Laravel multiple forms with a only one submit button?

I have a form that can edit multiple areas in multiple tables, but it does not work unless I have a submit button within each form , is there any way to do this with one submit button?
{!!Form::model($pregunta,['route'=>['seleccion.update',$pregunta->id],'method'=>'PUT','files' => true])!!}
{!!Form::label('categoria','Categoria: ')!!}
{!!Form::select('categorias_id', $categoria,null,['id'=>'categoriaSelSimple','class'=>'form-control',
'placeholder'=>'Seleccione una opcion..','required'])!!}<br>
{!!Form::label('subcategoria','Sub-categoria: ')!!}
{!!Form::select('sub_categorias_id', $subcategoria,null,['id'=>'subcategoriaSelSimple','class'=>'form-control',
'placeholder'=>'Seleccione una opcion..','required'])!!}<br>
#foreach($opcion as $key => $value)
{!!Form::model($value,['route'=>['opciones.update',$value->id],'method'=>'PUT'])!!}
<div class="form-group option-container">
<div class="input-group ">
#if($value->correcto == 1)
<span class="input-group-addon">
{!!Form::select('correcto[]', ['0' => 'Incorrecto','1' => 'Correcto'])!!}
</span>
#else
<span class="input-group-addon">
{!!Form::select('correcto[]', ['1' => 'Correcto','0' => 'Incorrecto'])!!}
</span>
#endif
{!!Form::text('opcion[]',$value->opcion,['class'=>'form-control']) !!}
{{-- {!!Form::text('opcion[]',null,['class'=>'form-control', 'placeholder'=>'Ingresa una opcion..'])!!} --}}
<span opcion-id="{{$value->id}}" class="input-group-btn">
<button class="btn btn-outline btn-danger btn-remove" type="button">X</button>
</span>
</div>
</div>
{{Form::close()}}
#endforeach
<button type="button" class="btn btn-outline btn-success btn-lg btn-block btn-add-more-options">Agregar opción</button>
<h1 class="page-header"></h1>
{!!Form::submit('Actualizar',['class'=>'btn btn-outline btn-primary'])!!}
</div>
<!-- /.col-lg-8 -->
<!-- /.col-lg-4 -->
</div>
{!!Form::close()!!}
I have multiple forms, one main and the others added through a foreach (how many depends of the table ), so i need to update these fields generated by the foreach but it doesn't work because i dont have a submit button for each form, how i can do this??
Using only HTML, no, multiple forms cannot be submitted with a single submit button.
This could be done using a bit of JavaScript. For each form you would need to track which values had been changed, then submit those forms via AJAX.
Another thing to consider is combining all the forms into a single HTML form and let the controller->action() put the information where it belongs.

CRUD Laravel 5 how to link to destroy of Resource Controller?

I have a link
<a class="trashButton" href="{{ URL::route('user.destroy',$members['id'][$i]) }}" style="cursor: pointer;"><i class="fa fa-trash-o"></i></a>
this link is supposed to direct to the destroy method of the Usercontroller , this is my route Route::resource('/user', 'BackEnd\UsersController');
UserController is a Resource Controller. But at this moment it is directing me to the show method rather than directing to the destroy method
You need to send a DELETE request instead of a GET request. You can't do that with a link, so you have to use an AJAX request or a form.
Here is the generic form method:
<form action="{{ URL::route('user.destroy', $members['id'][$i]) }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button>Delete User</button>
</form>
If you're using Laravel 5.1 or later then you can use Laravel's built-in helpers to shorten your code:
<form action="{{ route('user.destroy', $members['id'][$i]) }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button>Delete User</button>
</form>
If you're using Laravel 5.6 or later then you can use the new Blade directives to shorten your code even further:
<form action="{{ route('user.destroy', $members['id'][$i]) }}" method="POST">
#method('DELETE')
#csrf
<button>Delete User</button>
</form>
You can read more about method spoofing in Laravel here.
This is because you are requesting the resources via GET method instead DELETE method. Look:
DELETE /photo/{photo} destroy photo.destroy
GET /photo/{photo} show photo.show
Both routes have the same URL, but the header verb identifies which to call. Looks the RESTful table. For example, via ajax you can send a DELETE request:
$.ajax({
url: '/user/4',
type: 'DELETE', // user.destroy
success: function(result) {
// Do something with the result
}
});
I use this template 'resources/views/utils/delete.blade.php'
<form action="{{ $url or Request::url() }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type='submit' class="{{ $class or 'btn btn-danger' }}" value="{{ $value or 'delete' }}">{!! $text or 'delete' !!}</button>
</form>
Called as this:
#include('utils.delete',array( 'url' => URL::route('user.destroy',$id),'text' => '<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> delete me'))
If you're looking to do this via a regular link instead of through AJAX or another type of form request you can set up a special route that will respond to a normal GET request:
In your routes, define this in addition to the resource:
Route::get('user/{site}/delete', ['as' => 'user.delete', 'uses' => 'UserController#destroy']);
In your view:
Delete this user
In your controller:
public function destroy(User $user)
{
$user->delete();
return redirect()->route('users.index');
}
If we need to use an anchor to trigger the destroy route, and we don't want to use ajax, we can put a form inside our link, and submit the form using the onclick attribute:
<a href="javascript:void(0);" onclick="$(this).find('form').submit();" >
<form action="{{ url('/resource/to/delete') }}" method="post">
<input type="hidden" name="_method" value="DELETE">
</form>
</a>
If you really want to visit the destroy action on delete route by HTML, then there is an approach to use HTTP Method Spoofing which means that you could visit a delete HTTP method by adding a hidden input named _method with the value of `"DELETE". Same way can be used for "PUT" and "PATCH" HTTP method.
Below is a sample for DELETE method.
<form action="/tasks/5" method="POST">
<input type="hidden" name="_method" value="DELETE">
</form>
will get the route
DELETE /tasks/{id} destroy tasks.destroy
if you use laravel collective, you can write this way in your views.
{!! Form::open(['url' => '/tasks/'.$cat->id, 'method' => 'delete']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
In case someone came here to find how to replace standard laravel form for delete, from button in it to link, you can just replace:
{!! Form::open(['method' => 'DELETE', 'route' => ['tasks.destroy', $task->id],'onsubmit' => 'return confirm("Are you sure?")', 'id'=>'himan']) !!}
{!! Form::submit('Delete') !!}
{!! Form::close() !!}
TO
{!! Form::open(['method' => 'DELETE', 'route' => ['tasks.destroy', $task->id],'onsubmit' => 'return confirm("Are you sure?")', 'id'=>'himan']) !!}
Delete
{!! Form::close() !!}
Just replace button with simple <a href="#"... but with onclick attribute to submit the form!
If you want to use a link, you can use a library I have created that lets people make links that behave like POST, DELETE... calls.
https://github.com/Patroklo/improved-links
GET and DELETE Both routes have the same URL, but the header verb identifies which to call.
Here are my code snippets for edit and delete. I use bootstrap modal confirmation for delete action
<div class="btn-group">
<a href="{{ route('locations.edit', $location->id) }}"
class="btn btn-default btn-sm">
<i class="fa fa-pencil"></i>
</a>
<span class="btn btn-danger btn-sm formConfirm"
data-form="#frmDelete-{{$location->id}}"
data-title="Delete Location"
data-message="Are you sure you want to delete this Location ?">
<i class="fa fa-times"></i>
</span>
<form method="POST"
style="display: none"
id="frmDelete-{{$location->id}}"
action="{{ route('locations.destroy' , $location->id) }}">
{!! csrf_field() !!}
{{ method_field('DELETE') }}
<input type="submit">
</form>
BootStrap Modal
<div class="modal fade" id="formConfirm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span
class="sr-only">Close</span></button>
<h4 class="modal-title" id="frm_title">Delete</h4>
</div>
<div class="modal-body" id="frm_body"></div>
<div class="modal-footer">
<button style='margin-left:10px;' type="button" class="btn btn-primary col-sm-2 pull-right"
id="frm_submit">Yes
</button>
<button type="button" class="btn btn-danger col-sm-2 pull-right" data-dismiss="modal" id="frm_cancel">
No
</button>
</div>
</div>
</div>
And Finally JS code
$('.formConfirm').on('click', function (e) {
e.preventDefault();
var el = $(this);
var title = el.attr('data-title');
var msg = el.attr('data-message');
var dataForm = el.attr('data-form');
$('#formConfirm')
.find('#frm_body').html(msg)
.end().find('#frm_title').html(title)
.end().modal('show');
$('#formConfirm').find('#frm_submit').attr('data-form', dataForm);
});
$('#formConfirm').on('click', '#frm_submit', function (e) {
var id = $(this).attr('data-form');
$(id).submit();
});
My, non-ajax version. I use it in dropdowns (bootstrap) in resource list (datatables as well). Very short and universal.
Global jQuery method:
$('.submit-previous-form').click(function (e) {
e.preventDefault();
$($(this)).prev('form').submit();
});
And then we can use everywhere something like this:
{{ Form::open(['route' => ['user.destroy', $user], 'method' => 'delete']) }} {{ Form::close() }}
<i class="icon-trash"></i> Delete him
Recommend: It's easy to integrate with confirms scripts for example swal.
you can try this: (you can pass your id)
<form action="{{ route('tasks.destroy', $dummy->id) }}" method="post">
#csrf
#method('DELETE')
<a href="#" class="btn btn-danger" title="Delete" data-toggle="tooltip" onclick="this.closest('form').submit();return false;">
<i class="bi bi-trash-fill" style="color:white"></i>
</a>
</form>
requires route like:
Route::get('/tasks/delete/{id}', 'TasksController#destroy')
->name('tasks.destroy');
your controller:
public function destroy($id)
{
$task = Task::find($id);
$task->delete();
return redirect('/home')->with('success','Task Deleted Successfully');
}
or you can try this
{!! Form::open(['method' => 'DELETE','route' => ['reports.destroy', $dummy->id],'class'=>'']) !!}
{{ Form::button('<i class="bi bi-trash-fill" style="color:white"></i>', ['type' => 'submit', 'class' => 'delete get-started-btn-two'] ) }}
{!! Form::close() !!}

Laravel lightbox to show view/form

I have fleshed out a Laravel project but wanting to do something a little different, I am using Bootstrap so the standard nav and modal for the popout.
I am wanting to show the modal with the registration or login form inside, but as you can appreciate the way it is currently built, once you hit the login or register link it just renders the page view.
So I have my views/layouts/navigation.blade.php
<div class="container navigation">
<nav class="navbar navbar-default navbar-top">
<li class="navbar-right">Home</li>
<div class="container">
#if(Auth::check())
<li>Sign out</li>
<li>Change password</li>
#else
<li>Login</li>
<li><button type="button" class="btn btn-default navbar-btn data-toggle="modal" data-target="#myModal"">Sign Up</button></li>
#endif
</div>
</nav>
</div>
And seperate to this I have my views/account/create.blade.php & views/account/signin.php
#extends('layout.main')
#section('content')
<form action="{{ URL::route('account-create-post') }}" method="post">
<div class="field">
Email: <input type="text" name="email"{{ (Input::old('email')) ? ' value="' . e(Input::old('email')) . '"' : '' }}>
#if($errors->has('email'))
{{ $errors->first('email') }}
#endif
</div>
<div class="field">
Username: <input type="text" name="username"{{ (Input::old('email')) ? ' value="' . e(Input::old('username')) . '"' : '' }}>
#if($errors->has('username'))
{{ $errors->first('username') }}
#endif
</div>
<div class="field">
Password: <input type="password" name="password">
#if($errors->has('password'))
{{ $errors->first('password') }}
#endif
</div>
<div class="field">
Password Again: <input type="password" name="password_again">
#if($errors->has('password_again'))
{{ $errors->first('password_again') }}
#endif
</div>
<input type="submit" value="Create Account">
{{ Form::token() }}
</form>
#stop
Really I wanting the button in the nav to fire up the modal and show the forms inside? Amy ideas on how to approach this?
You'll basically be using Javascript on the client to display the form and process the request to the server and the server's response. I would:
Pick a CSS/Javascript framework that will display a modal form for you
Put your normal form generation inside the dialog it shows
Have a Javascript handler on the submit button of the modal dialog that makes an AJAX post to a new RESTful HTTP endpoint in Laravel that calls the same logic your standard signup form uses, but sends back a response your AJAX code will understand (e.g. either successful or failed, with an error message).
I hope i got the question right. The Key to achieve what you want should be a concept called nested views, which is very well explained on this coderwall. Also, check out the laravel docs on views (passage Passing A Sub-View To A View).
You would have to create a view for your login-form an nest it in the login modal as well as in the standard login-view (if you have one). Hope this helps.

Categories