Laravel & jQuery - Add form fields dynamically using template - php

I am using Laravel and I have a Booking model that has a one to many relationship with a Service. So a booking can have many services.
I have set up all the relationships in the models and its working fine.
In my bookings create view file I have a panel where I want to allow users to dynamically add services.
{{ Form::open(array('url' => 'bookings')) }}
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title">Services</h3></div>
<div class="panel-body" id="newServices">
Add Service
</div>
</div>
{{ Form::submit('Create Booking', array('class' => 'btn btn-primary btn-vostra')) }}
{{ Form::close() }}
I have a template view file bookings.service which has some input elements:
#extends('layouts.app')
#section('content')
<div class="form-group">
{{ Form::label('customer_name', 'Customer Name') }}
{{ Form::text('customer_name', Input::old('customer_name'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('customer_address_line_1', 'Address Line 1') }}
{{ Form::text('customer_address_line_1', Input::old('customer_address_line_1'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('customer_address_line_2', 'Address Line 2') }}
{{ Form::text('customer_address_line_2', Input::old('customer_address_line_2'), array('class' => 'form-control')) }}
</div>
#endsection
My question is how do I dynamically add the services view template file into the bookings view file?
Here is what I have so far but its incomplete:
$('#addService').click(function(e) {
e.preventDefault();
var html = {};
$('#newServices').append(html);
});

in case someone is still actively looking for the answer, first of all,
just put the js code at the bottom of your laravel page, right before #endsection.
But make sure you also write the reference to app.js cause you need it to add javascript to your page (and jquery if you want to)
here is how it will looks
#extends('layouts.app')
#section('content')
<div class="form-group">
{{ Form::label('customer_name', 'Customer Name') }}
{{ Form::text('customer_name', Input::old('customer_name'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('customer_address_line_1', 'Address Line 1') }}
{{ Form::text('customer_address_line_1', Input::old('customer_address_line_1'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('customer_address_line_2', 'Address Line 2') }}
{{ Form::text('customer_address_line_2', Input::old('customer_address_line_2'), array('class' => 'form-control')) }}
</div>
<script>{{ asset('js/app.js') }}</script>
<script>
$(document).ready(function(){
$('#addService').click(function(e) {
e.preventDefault();
var html = {};
$('#newServices').append(html);
});
});
</script>
#endsection
okay now for how to dynamically add form, honestly, i can't really tell how using your example. But if it can help, here is how i did it
<table id="add-me" class="table table-bordered">
<thead>
<tr>
<th>Quantity</th>
<th>Item</th>
<th>Selling Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody >
#foreach($invoice_items as $item)
<tr>
<td id="quantity" class="col-md-2"><input onkeypress='return event.charCode >= 48 && event.charCode <=57'
type="text" value="{{ $item->quantity }}" name="quantity[]" class="form-control" autofocus="" /></td>
<td class="col-md-7"><select class="form-control" id="item" name="item[]">
#foreach($products as $product)
#if($product->item == $item->item && $product->price == $item->price)
<option selected value={{$product->id}}>{{$product->item}} - {{$product->price}}</option>
#endif
<option value={{$product->id}}>{{$product->item}} - {{$product->price}}</option>
#endforeach
</select></td>
<td class="col-md-3"><input type="text" value="{{ $item->price }}" name="price[]" class="form-control" /></td>
<td class="col-md-2">
<button type="button" class="btn btn-danger">
Delete</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="action-buttons">
<button id="add-form" type="button" class="btn btn-default">Add New Form</button>
<button type="submit" class="btn btn-success">Add Invoice</button>
</div>
<script>
$(document).ready(function(){
var i = 1;
$('#add-form').click(function() {
i++;
$('#list').replaceWith('<input type="hidden" id="list" name="list" value='+i+'></input>');
$('#add-me').append(
'<tbody id="row'+i+'"><tr>'+
'<td class="col-md-2">'+
'<input id="quantity" onkeypress="return event.charCode >= 48 && event.charCode <=57" type="text" name="quantity[]" class="form-control"/>'
+'</td>'
+'<td class="col-md-7">'
+'<select class="form-control" id="item" name="item[]">'
+'#foreach($products as $product)'
+'<option value={{$product->id}}>{{$product->item}} - {{$product->price}}</option>'
+'#endforeach'
+'</select>'
+'</td>'
+'<td class="col-md-3">'
+'<input type="text" name="price[]" class="form-control" />'
+'</td>'
+'<td class="col-md-2">'
+'<button id="+i+" type="button" class="btn btn-danger delegated-btn">Delete</button>'
+'</td>'
+'</tr></tbody>'
);
});
});
</script>

Related

How do i check if database row exist in laravel?

Hello how do i check if database row insert exist in laravel? i want to display something entries if > 0 and i want to display else if entries = 0. but i don t know how to do that. i tried with forelse, if else and i got same error. Undefined variable $istProj.
<div class="card-body">
#if ($istoric->isEmpty())
#forelse ($istoric as $istProj)
<div class="mb-3">
<table class='table'>
<tr class="table-row-heads">
<th>Id Proiect</th>
<th>Tip actiune </th>
<th>Colaborator </th>
<th>Suma </th>
<th>Data </th>
</tr>
<tr class="table-row-data">
<td>{{ $istProj->id_proiect }}</td>
<td>{{ $istProj->action_type }}</td>
<td>{{ $istProj->colaborator_id }}</td>
<td>{{ $istProj->suma }}</td>
<td>{{ $istProj->data }}</td>
</tr>
</table>
</div>
#empty
<div class="card-body">
<h1>Nu au fost gasite inregistrari</h1>
</div>
#endforelse
#endif
</div>
<form action="{{ url('/') }}" method="POST">
#csrf
#method('PUT')
<div class="mb-3">
<label class="form-label">Id proiect</label>
<input type="text" class='form-control' value="{{ $proiecte->id }}" name='id_proiect' id='id_proiect' placeholder="Id proiect">
</div>
<div class="mb-3">
<label class="form-label">Tip actiune</label>
<select class="form-select" aria-label="Default select example" name='Status_Tranzactii'>
<option selected>Alege tipul actiunii (0 = cheltuiala, 1 = plata, 2 = incasare)</option>
<option value="cheltuiala">0</option>
<option value="plata">1</option>
<option value="incasare">2</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Colaborator</label>
<select class="form-select" aria-label="Default select example" name="Colab_id">
<option selected>Alege colaboratorul (daca este cazul)</option>
#foreach ($colaborator as $colaboratori)
<option value="{{ $colaboratori->id }}">{{ $colaboratori->id }} </option>
#endforeach
</select>
</div>
<div class="mb-3">
<label class="form-label">Suma</label>
<input type="text" class='form-control' value="{{ $istProj->suma }}" name='suma' placeholder="Introduceti suma">
</div>
<div class="mb-3">
<label class="form-label">Data</label>
<input type="text" class='form-control' value="{{ $istProj->data }}" name='data' placeholder="Introduceti data">
</div>
<button type='submit' class='btn btn-primary' style="float: right;">Adauga</button>
</form>
How can i make that to work?
Error on line with "Suma"
If I understand well, you already have a Collection result (From Eloquent or anywhere) and you need to do different action based on that result.
I'm,right? If yes....
To check the amount or entries you can use $result->count(), so in Blade you can:
#if($result->count() > 0)
Do something
#else
Do anotherthing
#endif

Laravel HTML form issue

<form action="/group/{id}/save/group" method="POST">
#csrf
<table id="modal-table">
#foreach($user_list->get() as $f)
<tr>
<td>
<div class="image">
#if($f->follower->avatar_location)
<img src="{{asset('storage/'.$f->follower->avatar_location)}}" class="img-circle" style="max-height:50px;" />
#else
<img src="{{url('/')}}/assets/media/icons/socialbuttons/user.png" class="img-circle" style="max-height:50px;"/>
#endif
</div>
<div class="detail">
#if($f->follower->verified == 1)
{{ $f->follower->name }}<img id="verified_img_sm_mess_list" src="{{url('/')}}/assets/media/icons/socialbuttons/octagonal_star.png" alt="Recensioni">
#else
{{ $f->follower->name }}</h3>
#endif
<small id="mess_list_uname">{{ '#'.$f->follower->username }}</small>
</div>
<input name="group" value="{{ $group->hobby->id }}">
<input name="person" value="{{ $f->follower->id }}">
<button type="submit" class="btn-link">Go</button>
</td>
</tr>
#endforeach
</table>
</form>
Hey a small problem! in the Foreach loop and every member in the list, I tried some bare-bones to get each users id and hobby id (to add to database, but that's not important). For some reason, when I take the input 'name' and click the Go button, All "id's" of everyone in the list are executed, Not the individual id of each user. Meaning.. each user displays their individual id and a go button, but click go and all id's are collected, not just one. It's probably really obvious but any ideas why this is happening?? Thanks!
Like said Tim Lewis in the comment, you need to put your form inside your foreach, so when the "Go" button is clicked, only the corresponding form will send the data, like this :
<table id="modal-table">
#foreach($user_list->get() as $f)
<form action="/group/{id}/save/group" method="POST">
#csrf
<tr>
<td>
<div class="image">
#if($f->follower->avatar_location)
<img src="{{asset('storage/'.$f->follower->avatar_location)}}" class="img-circle" style="max-height:50px;" />
#else
<img src="{{url('/')}}/assets/media/icons/socialbuttons/user.png" class="img-circle" style="max-height:50px;"/>
#endif
</div>
<div class="detail">
#if($f->follower->verified == 1)
{{ $f->follower->name }}<img id="verified_img_sm_mess_list" src="{{url('/')}}/assets/media/icons/socialbuttons/octagonal_star.png" alt="Recensioni">
#else
{{ $f->follower->name }}</h3>
#endif
<small id="mess_list_uname">{{ '#'.$f->follower->username }}</small>
</div>
<input name="group" value="{{ $group->hobby->id }}">
<input name="person" value="{{ $f->follower->id }}">
<button type="submit" class="btn-link">Go</button>
</td>
</tr>
</form>
#endforeach
</table>
<table id="modal-table">
#foreach($user_list->get() as $f)
<form action="/group/{id}/save/group" method="POST">
#csrf
<tr>
<td>
<div class="image">
#if($f->follower->avatar_location)
<img src="{{asset('storage/'.$f->follower->avatar_location)}}" class="img-circle" style="max-height:50px;" />
#else
<img src="{{url('/')}}/assets/media/icons/socialbuttons/user.png" class="img-circle" style="max-height:50px;"/>
#endif
</div>
<div class="detail">
#if($f->follower->verified == 1)
{{ $f->follower->name }}<img id="verified_img_sm_mess_list" src="{{url('/')}}/assets/media/icons/socialbuttons/octagonal_star.png" alt="Recensioni">
#else
{{ $f->follower->name }}</h3>
#endif
<small id="mess_list_uname">{{ '#'.$f->follower->username }}</small>
</div>
<input name="group" value="{{ $group->hobby->id }}">
<input name="person" value="{{ $f->follower->id }}">
<button type="submit" class="btn-link">Go</button>
</td>
</tr>
</form>
#endforeach
</table>
check this part of Jérôme W post
<form action="/group/{id}/save/group" method="POST">
Change to this
<form action="/group/{{$group->id}}/save/group" method="POST">

How to submit form without refreshing?

I am trying to remove the refresh time after I click the end button to submit the form into the database.
I am not that experienced when it comes to jquery and I rely only to video tutorials and forums at this current time but I am on my learning curve. as you can see I already converted the start button into jquery to remove the refresh time when I click start button.
<tbody class="table table-bordered table-striped">
#foreach($user as $task)
<tr class="form-group">
{{-- <form action="{{ route('amber.timestone.home.start') }}" method="POST" class="align-center"> --}}
{{csrf_field()}}
<td class="d-flex">
<input type="hidden" name="id" id="hidden-id_{{$task->id}}" value="{{ $task->id }}">
<button type="button" id="str-btn" data-id="{{$task->id}}" class="btn btn-primary"
#if(!empty($task->start))
disabled
#elseif(!empty($task->duration))
readonly
#endif
>Start</button>
{{-- <span class="btn btn-primary" onclick="myAlert({{$task->id}})">Test</span> --}}
</td>
{{-- </form> --}}
<form action="{{ route('amber.timestone.home.end', $task->id) }}" method="POST">
{{csrf_field()}}
<td>
<input class="my-2" type="text" id="ref_{{$task->id}}" name="ref" value="{{ $task->ref }}"
#if(empty($task->start))
readonly
#elseif(!empty($task->duration))
readonly
#endif
>
{{-- <input class="my-2" type="hidden" name="ref" value="{{ $task->ref }}"> --}}
</td>
<td>
<textarea name="remarks" id="remarks_{{$task->id}}" cols="30" rows="4"
#if(empty($task->start))
readonly
#elseif(!empty($task->duration))
readonly
#endif
>{{ $task->remarks }}</textarea>
</td>
<td>
<select id="campaign_{{$task->id}}" class="custom-select custom-select-lg mb-3" name="campaign"
#if(empty($task->start))
disabled
#elseif(!empty($task->duration))
disabled
#endif
>
<option #if($task->campaign == 'cert') selected #endif value="cert">Cert Focus</option>
<option #if($task->campaign == 'omni') selected #endif value="omni">Omni</option>
<option #if($task->campaign == 'textblast') selected #endif value="textblast">TextBlast</option>
</select>
</td>
<td>
<select id="type_{{$task->id}}" class="custom-select custom-select-lg mb-3" name="type"
#if(empty($task->start))
disabled
#elseif(!empty($task->duration))
disabled
#endif
>
<option #if($task->type == 'cert') selected #endif value="cert">Cert</option>
<option #if($task->type == 'email') selected #endif value="email">Email Support</option>
<option #if($task->type == 'chat') selected #endif value="chat">Chat Support</option>
</select>
</td>
<td>
<p id="startTime"></p>
{{ $task->start }}
</td>
<td>
{{ $task->end }}
</td>
<td>
{{ $task->duration }}
</td>
<td class="d-flex">
<input type="hidden" name="id" value="{{ $task->id }}">
<button type="submit" id="end-btn_{{$task->id}}" class="btn btn-danger float-right ml-3"
#if(!empty($task->end))
disabled
#elseif(empty($task->start))
disabled
#endif
>End</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
#endsection
#section('reporter')
<script>
$(document).ready(function() {
$('#report').DataTable( {
"bLengthChange": false,
"lengthMenu": [ 3, 10 ],
searching: false
});
$('#str-btn').click(function(e){
var id = $(this).data('id');
$.ajax({
url: "{{ url('amber/timestone/start') }}"+'/'+id,
type: "GET",
success: function(data){
console.log(data)
$("#startTime").text(data.start)
$("#end-btn_"+id).removeAttr("disabled");
$("#ref_"+id).removeAttr("readonly");
$("#remarks_"+id).removeAttr("readonly");
$("#campaign_"+id).removeAttr("disabled");
$("#type_"+id).removeAttr("disabled");
$("#str-btn").Attr("disabled");
}
})
$(this).prop("disabled", true);
});
});
You can get your form and add listener on submit, then you can call to event.preventDefault() to avoid refreshing.
Would be something like this:
<form action="{{ route('amber.timestone.home.start') }}" method="POST" class=" form-data-table align-center">
...
Javascript part:
$('.form-data-table').on('submit', function(event){
event.preventDefault();
... remaining code
})

Method links do not exist - Laravel 5.5

I'm getting the following error:
Method links do not exist
I also tried render function which gives me the same result.
This is my code:
public function welcome() {
$products = DB::table('products')->paginate(12);
return view('welcome', compact('products', $products));
}
When I call {{ $products->links() }}, it shows an error but if I remove {{ $products->links() }} I can see the results.
This is my view:
#foreach($products as $product)
<div class="col-sm-6 col-md-4 col-lg-3">
<!-- Product item -->
<div class="product-item hover-img">
<a href="product_detail.html" class="product-img">
<img src="images/default.png" alt="image">
</a>
<div class="product-caption">
<h4 class="product-name">{!! $product->name !!}</h4>
<div class="product-price-group">
<span class="product-price">{!! $product->price !!} KM</span>
</div>
</div>
<div class="absolute-caption">
<form action="{!! route('store') !!}" method="POST">
{!! csrf_field() !!}
<input type="hidden" name="id" value="{{ $product->id }}">
<input type="hidden" name="name" value="{{ $product->name }}">
<input type="hidden" name="price" value="{{ $product->price }}">
<input type="submit" class="btn btn-success btn-lg" value="Dodaj u korpu">
</form>
</div>
</div>
</div>
#endforeach
{{ $products->links() }}
You should use Eloquent instead of query builder.
Use:
$products = \App\Product::paginate(12);
instead of
$products = DB::table('products')->paginate(12);
to make it work.
(Of course you need to have created Product model first extending Eloquent model)

Laravel delete button with HTML form

I'm using the HTML form, not Laravel Collective.
For now I've successfully created a CRUD for a users in my CMS, but one thing bothers me:
How can I set a Delete button in my list of users, instead of the specific edit page?
Also, it will be nice when a user clicks on the Delete button to show up confirmation popup for deleting the specific user.
So, here's my code:
The controller:
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
return redirect('/admin/users');
}
The list of users page:
#extends('layouts.backend')
#section('content')
<h1>Users</h1>
<a class="btn btn-primary" href="/admin/users/create">Create new user</a>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Created</th>
<th>Updated</th>
<th>Operations</th>
</tr>
</thead>
<tbody>
#if($users)
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->role ? $user->role->name : 'User has no role'}}</td>
<td>{{$user->status == 1 ? 'Active' : 'Not active'}}</td>
<td>{{$user->created_at->diffForHumans()}}</td>
<td>{{$user->updated_at->diffForHumans()}}</td>
<td>
Edit
<a class="btn btn-danger" href="">Delete</a> // HOW TO ACHIEVE THIS?
</td>
</tr>
#endforeach
#endif
</tbody>
</table>
#endsection
The specific edit user page:
#extends('layouts.backend')
#section('content')
<h1>Edit user</h1>
<form method="POST" action="/admin/users/{{$user->id}}">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" class="form-control" value="{{$user->name}}">
</div>
<div class="form-group">
<label>Email:</label>
<input type="text" name="email" class="form-control" value="{{$user->email}}">
</div>
<div class="form-group">
<label>Role:</label>
<select name="role_id" class="form-control">
#if($user->role_id == 1)
<option value="1" selected>Administrator</option>
<option value="2">Editor</option>
#else
<option value="1">Administrator</option>
<option value="2" selected>Editor</option>
#endif
</select>
</div>
<div class="form-group">
<label>Status:</label>
<select name="status" class="form-control">
#if($user->status == 1)
<option value="1" selected>Active</option>
<option value="0">Not active</option>
#else
<option value="1">Active</option>
<option value="0" selected>Not active</option>
#endif
</select>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" value="{{$user->password}}">
</div>
<div class="form-group">
<input type="submit" name="submit" value="Update user" class="btn btn-primary">
</div>
</form>
<form id="delete-form" method="POST" action="/admin/users/{{$user->id}}">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<div class="form-group">
<input type="submit" class="btn btn-danger" value="Delete user">
</div>
</form>
#include('inc.errors')
#endsection
The route:
Route::group(['middleware'=>'admin'], function(){
Route::resource('admin/users', 'AdminUsersController');
Route::get('/admin', function(){
return view('admin.index');
});
// Route::resource('admin/posts', 'AdminPostsController');
});
It's not obvious from the code you posted, but your DELETE route expects DELETE method. As it should!
But on your list you're trying to access it with GET method.
Really you should just reuse the code from the edit page, which fakes DELETE method already.
Something like this:
...
<td>
Edit
<form method="POST" action="/admin/users/{{$user->id}}">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<div class="form-group">
<input type="submit" class="btn btn-danger delete-user" value="Delete user">
</div>
</form>
</td>
...
...
// Mayank Pandeyz's solution for confirmation customized for this implementation
<script>
$('.delete-user').click(function(e){
e.preventDefault() // Don't post the form, unless confirmed
if (confirm('Are you sure?')) {
// Post the form
$(e.target).closest('form').submit() // Post the surrounding form
}
});
</script>
As you have stated it will be nice when a user clicks on the Delete button to show up confirmation popup for deleting the specific user. For this you have to use jquery and ajax. Change the following code:
<a class="btn btn-danger" href="">Delete</a>
to
<a class="btn btn-danger delete_user" href="javascript:void(0);" id="{{$user->id}}">Delete</a>
and put an event listener like:
$('.delete_user').click(function(){
if( confirm('Are you sure?') )
{
var id = $(this).attr('id');
// Make an ajax call to delete the record and pass the id to identify the record
}
});
You can update your code like:
<a class="btn btn-danger" href="/admin/users/{{$user->id}}/delete" >Delete</a>
OR you should delete user using route name like:
Delete
option with "laravel form helper" and jquery
<div class="actions">
<a href="#" class="list-icons-item delete-action">
<i class="icon-trash"></i>
</a>
{{ Form::open(['url' => route('admin.users.destroy', $user), 'method' => 'delete']) }}
{{ Form::close() }}
</div>
<script>
$(document).ready(function () {
$('.delete-action').click(function (e) {
if (confirm('Are you sure?')) {
$(this).siblings('form').submit();
}
return false;
});
});
</script>
Using route closures to delete
show.blade.php
<form>
<h1>Title: {{$tutorial->title}}</h1>
<p>Title Description: {{$tutorial->title_description}}</p>
<p>Video: {{$tutorial->video}}</p>
<form action="{{ route('delete-tutorial', [$tutorial->id])}}"
method="post">
#csrf
#method('DELETE')
<button class="btn btn-primary" onclick="return confirm('Are you sure?')"
type="submit" name="Delete">Delete</button>
</form>
for the route for deleting
Route::delete('tutorial/{id}',function($id){
$tutorial = Tutorial::findOrFail($id)->first();
$tutorial->delete();
return redirect('tutorial');
})->name('delete-tutorial');
Also don't forget to add this on your routes/web.php
use App\Models\Tutorial;

Categories