Prevent other forms from submitting - php

I have a form which has another form inside it.
Everytime I submit the inner form, the outer form also submits. I would just like to submit my inner form via ajax.
Here's my twig template:
<div id="askDiv">
{{ form_start(form, { 'attr' : { 'novalidate' : 'novalidate', 'class' : 'col-md-offset-3 form-control-static col-md-7' } }) }}
<div class="col-lg-12" style="margin-bottom: 30px;">
<span id="titleLabel" data-toggle="popover" data-container="body" data-placement="left" data-trigger="manual" data-html="true" data-content='{{form_errors(form.title)}}' class="col-lg-1 text-left askLabels">{{ form_label(form.title) }}</span>
{{form_widget(form.title, { 'attr' : { 'class' : 'right form-control col-lg-8' } })}}
</div>
{{ form_widget(form.content, { 'attr' : { 'data-toggle' : 'popover', 'data-container' : 'body', 'data-placement' : 'left', 'data-trigger' : 'manual', 'data-html' : 'true', 'data-content' : form_errors(form.content), 'class' : 'col-lg-12' } }) }}
<div class="col-lg-12" style="margin-top: 20px;">
<input id="fieldTags" type="hidden" value="{{ tags|join(',') }}">
<label id="tagLabel" data-toggle="popover" data-container="body" data-placement="left" data-trigger="manual" data-html="true" data-content='{{form_errors(form.tags)}}' class="col-lg-1 text-left askLabels" for="tagField">Tags</label>
<div class="col-lg-8">
{{ form_widget(form.tags) }}
</div>
{% if app.user.reputati on >= 100 %}
<a id="addTag" title="Add New Tag" data-toggle="tooltip modal" data-placement="left" class="col-lg-3" href="#"><i class="fa fa-plus-circle"></i></a>
{% endif %}
</div>
<div style="margin-top: 20px; ">
{{ form_widget(form.submit, { 'attr' : { 'class' : 'col-md-offset-5 col-md-3 btn btn-primary' } }) }}
</div>
<div hidden id="errors">
{{ form_errors(form.title) }}
{{ form_errors(form.content) }}
{{ form_errors(form.tags) }}
{{ form_errors(form) }}
{{form_rest(form)}}
</div>
<div id="mymodal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add New Tag</h4>
</div>
<form class="tagForm" id="tag-form" action="{{ path('tag_create') }}" method="post">
<div class="modal-body">
<label for="tagName">Tag Name: </label>
<input id="tagName" class="form-control" type="text"/>
</div>
<div id="responseDiv" ></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input id="tag-form-submit" type="submit" class="btn btn-primary" value="Add Tag">
</div>
</form>
</div>
</div>
My Script:
$(document).ready(function() {
$('#tag-form').submit(function(e) {
e.preventDefault();
var options = {
url: $('#tag-form').attr('action'),
type: 'post'
};
$('#tag-form').ajaxSubmit(options);
$('form[name="verysoft_askmebundle_question"]').submit(function(ev) {
ev.preventDefault();
});
});
});
Seems like my forms aren't nested after all. Sorry about that. My current problem is that everytime I hit the submit button of one of the forms, the other one submits also.

Nested forms is invalid HTML markup since it's not supported and not part of the w3c standard according to HTML5 draft:
Content model: Flow content, but with no form element descendants.
So you'll need separate your forms and apply the same logic but different jQuery code.

Related

How to send the correct ID to the controller with ajax?

How do I add code to the input button so that the value of the Id is sent to the Controller?
I have eight images. Then I click on the id of 116, open this image.
When I click on the biggest photo, Open a bootstrap modal for me.
This action tag form is written to this ID 120, While I have selected ID 116.
http://localhost:8000/admin/products/4/galleries/120
#section('content')
<div class="col-md-10 p-5 pt-2">
<form method="post" action="{{ route('products.galleries.store', $product->id) }}" enctype="multipart/form-data" class="dropzone" id="dropzone">
#csrf
</form>
<hr>
<div class="col-md-6 mx-auto">
<div class="row">
<div class="mx-auto" id="showImage">
<img src="{{ asset("storage/{$gallery->image}") }}" class="img-fluid cursor-pointer" onclick="deleteImage('{{ $gallery->id }}', '{{ route('products.galleries.delete', [$product->id, $gallery->id]) }}')">
</div>
</div>
<div class="row">
#foreach($galleries as $gallery)
<div class="col-md-2">
<img src="{{ asset("storage/{$gallery->image}") }}" class="img-fluid cursor-pointer" onclick="showImage('{{ asset("storage/{$gallery->image}") }}', '{{ $gallery->id }}')"><br><div class="text-center text-danger">{{ $gallery->id }}</div>
</div>
#endforeach
</div>
</div>
</div>
<div class="modal fade" id="delete" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="delete" aria-hidden="true">
<div class="modal-dialog modal-sm">
<form action="{{ route('products.galleries.delete', [$product->id, $gallery->id]) }}" method="post">
#csrf
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">This action is not reversible.</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to delete the image?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">Delete</button>
</div>
</div>
</form>
</div>
</div>
#endsection
#push('script')
<script src="{{ asset('themes/js/dropzone.min.js') }}"></script>
<script>
function showImage(url, id) {
let route = "'"+'{{ route('products.galleries.delete', [$product->id, $gallery->id]) }}'+"'";
let image = '<img src='+url+' onclick="deleteImage('+id+','+route+')" class="img-fluid cursor-pointer" />';
$('#showImage').html(image);
}
function deleteImage(id, url) {
$('#delete').modal(id, url);
}
</script>
#endpush
web.php
Route::post('products/{product}/galleries/{gallery}', 'GalleryController#delete')->name('products.galleries.delete');

How to send the to controller with ajax?

How do I add code to the input button so that the value of the Id is sent to the Controller?
I have eight images. Then I click on the id of 116, open this image.
When I click on the biggest photo, Open a bootstrap modal for me.
This action tag form is written to this ID 120, While I have selected ID 116.
http://localhost:8000/admin/products/4/galleries/120
#section('content')
<div class="col-md-10 p-5 pt-2">
<form method="post" action="{{ route('products.galleries.store', $product->id) }}" enctype="multipart/form-data" class="dropzone" id="dropzone">
#csrf
</form>
<hr>
<div class="col-md-6 mx-auto">
<div class="row">
<div class="mx-auto" id="showImage">
<img src="{{ asset("storage/{$gallery->image}") }}" class="img-fluid cursor-pointer" onclick="deleteImage('{{ $gallery->id }}', '{{ route('products.galleries.delete', [$product->id, $gallery->id]) }}')">
</div>
</div>
<div class="row">
#foreach($galleries as $gallery)
<div class="col-md-2">
<img src="{{ asset("storage/{$gallery->image}") }}" class="img-fluid cursor-pointer" onclick="showImage('{{ asset("storage/{$gallery->image}") }}', '{{ $gallery->id }}')"><br><div class="text-center text-danger">{{ $gallery->id }}</div>
</div>
#endforeach
</div>
</div>
</div>
<div class="modal fade" id="delete" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="delete" aria-hidden="true">
<div class="modal-dialog modal-sm">
<form action="{{ route('products.galleries.delete', [$product->id, $gallery->id]) }}" method="post">
#csrf
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">This action is not reversible.</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to delete the image?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">Delete</button>
</div>
</div>
</form>
</div>
</div>
#endsection
#push('script')
<script src="{{ asset('themes/js/dropzone.min.js') }}"></script>
<script>
function showImage(url, id) {
let route = "'"+'{{ route('products.galleries.delete', [$product->id, $gallery->id]) }}'+"'";
let image = '<img src='+url+' onclick="deleteImage('+id+','+route+')" class="img-fluid cursor-pointer" />';
$('#showImage').html(image);
}
function deleteImage(id, url) {
$('#delete').modal(id, url);
}
</script>
#endpush
You are looping through the gallery images, after loop iterations are done you written your code for modal, the last value of gallery which you used for modal is the last index in your collection of gallery images.
This peice of code may help you
$gallery = 5;
$galleries = [5,6,7,9,8];
foreach($galleries as $gallery) {
// code
}
// now your $gallery variable does not hold 5 instead it has 8 as you assigned its value through loop
As you used $gallery vairable before, You can fix your code like this
#foreach($galleries as $_gallery)
<div class="col-md-2">
<img src="{{ asset("storage/{$_gallery->image}") }}" class="img-fluid cursor-pointer" onclick="showImage('{{ asset("storage/{$_gallery->image}") }}', '{{ $_gallery->id }}')"><br><div class="text-center text-danger">{{ $_gallery->id }}</div>
</div>
#endforeach

Add data from a datatable to a modal in laravel

The spanish version failed me, so I'll test my luck here
I have the following code and I would like to know how I can pass the data from my table to the modal
This is my code in edit.blade.php. The modal does work but I don't know how to make the data show up in the modal, I'll do POST to the database myself but I just want to know how I make that data show up so I can edit it.
The data that I want to appear in the modal are the id, the name and the email.
This is my code in editar.blade.php
<script src="{{ url('/js/vendor/jquery-1.12.4.min.js') }} "></script>
<script src="{{ url('/js/bootstrap.min.js') }} "></script>
<link rel="stylesheet" href="{{ url('/css/bootstrap.min.css') }} ">
<script src="{{ url('/js/jquery.dataTables.min.js') }} "></script>
<div class="container">
<h2>Editar estudiante</h2>
<div class="container">
<h2>Laravel DataTables Tutorial Example</h2>
<table id="user_table" class="table table-bordered table-striped">
<thead>
<tr>
<th width="35%" id="name">Name</th>
<th width="35%" id="email">Email</th>
<th width="30%">Action</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-labelledby="edit-modal-label" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="edit-modal-label">Edit Data</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="attachment-body-content">
<form id="edit-form" class="form-horizontal" method="POST">
<div class="card text-white bg-dark mb-0">
<div class="card-header">
<h2 class="m-0">Edit</h2>
</div>
<div class="card-body">
<!-- id -->
<input type="hidden" name="modal-input-id" class="form-control" id="modal-input-id" required>
<!-- /id -->
<!-- name -->
<div class="form-group">
<label class="col-form-label" for="modal-input-name">Name</label>
<input type="text" name="modal-input-name" class="form-control" id="modal-input-name" required autofocus>
</div>
<!-- /name -->
<!-- description -->
<div class="form-group">
<label class="col-form-label" for="modal-input-description">Email</label>
<input type="text" name="modal-email" class="form-control" id="modal-input-email" required>
</div>
<!-- /description -->
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Done</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#user_table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('getdata') }}",
},
columns: [
{
data: 'name',
name: 'name',
className: 'user-name',
},
{
data: 'email',
name: 'email',
className: 'user-email',
},
{
data: 'action',
name: 'action',
orderable: false
}
]
});
$(document).on('click', "#edit-item", function() {
//obtenemos la instancia de la fila
$tr = $(this).closest('tr');
//rellenamos los campos en el modal
$('#modal-input-name').val($('user-name', $tr).text());
$('#modal-input-email').val($('user-email', $tr).text());
// Mostramos el modal
$('#edit-modal').modal('show');
})
// on modal hide
$('#edit-modal').on('hide.bs.modal', function() {
$('.edit-item-trigger-clicked').removeClass('edit-item-trigger-clicked')
$('#edit-form').trigger('reset');
})
});
</script>
This is my get route in web.php
Route::get('/editar', 'AdminController#editar')->name('editar');
This is my function to bring data to the Datatable in AdminController.php
public function getPosts(Request $request)
{
if($request->ajax()){
$data = StudentModel::latest()->get();
return DataTables::of($data)
->addColumn('action', function($data){
$button = '<button id="edit-item" type="button" name="edit-item" data-target-id="'.$data->id.'" class="edit btn btn-primary btn-sm" data-toggle="modal" data-target="edit-modal">Edit</button>';
$button .= ' <button type="button" name="edit" data-target-id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('editar');
}
Can you try this?
$('#modal-input-name').val($tr.find('td.user-name').text());
$('#modal-input-email').val($tr.find('td.user-email').text());
And also I would suggest that you use a css class for targeting a click event, as Id is normally for a unique identifier, and by doing your way you are having many table rows with the same Id which defeats the original idea.

Cant update form data laravel

I’m trying to update a modal form but for some reason nothing changed after I click the update button. I have tried to dd request->role_name, but it looks like it didn’t catch the value that I input with select form. The delete and create works perfectly fine. I will provide the create and delete controller if you all want to know.
The table that I used:
bas_role
id
name
bas__app
id
app_name
bas_role_app
id
role_id(f_key)
app_name(f_key)
Route:
Route::get('/roleapp', 'RoleAppController#display');
Route::post('/roleapp/update/{roleapp}', 'RoleAppController#update');
Route::get('ajaxdata/getapp','RoleAppController#getroleapp')->name('ajaxdata.getroleapp');
Controller:
public function display(Request $request)
{
$routes = preg_match('/([a-z]*)#([a-z]*)/i', Route::currentRouteAction(), $matches);
$routes = $matches[0];
$action = $matches[2];
if (Auth::check()) {
$id = Auth::id();
DB::beginTransaction();
try {
$profile_data = User::find($id);
ActivityLog::create([
'inserted_date' => Carbon::now()->TimeZone('asia/jakarta'),
'username' => $profile_data->username,
'application' =>$routes,
'creator' => "System",
'ip_user' => $request->ip(),
'action' => $action,
'description' => $profile_data->username. " is looking at roleApp",
'user_agent' => $request->server('HTTP_USER_AGENT')
]);
// $pagination = TRUE;
$app =DB::table('bas_role_app')
->join('bas_role_app','bas_app.app_name','=','bas_role_app.app_name')
->join('bas_role','bas_role_app.role_id','=','bas_role.id')
->from('bas_app')
->distinct()
// ->where('role_user.role_id', 4)
->select('bas_role_app.app_name','bas_role.name','bas_role_app.id','bas_role_app.role_id')
// ->from('bas_app')
// // ->where('role_user.role_id', 4)
->groupBy('bas_app.app_name','bas_role.name','bas_role_app.id')
->Orderby('bas_role_app.id')
->get();
// dd($app);
$bas_role = Role::distinct()->select('id','name')->get();
$bas_app =App::distinct()->select('id','app_name')->get();
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
return response()->json(['error' => $ex->getMessage()], 500);
}
return view('/roleapp', ['app' => $app, 'bas_app'=> $bas_app, 'bas_role' => $bas_role]);
// return view('/roleapp', ['app' => $app, 'bas_app' => $bas_app]);
}else {
return view("login");
}
}
public function getroleapp(){
$app = DB::table('bas_role_app')
->join('bas_role_app','bas_app.app_name','=','bas_role_app.app_name')
->join('bas_role','bas_role_app.role_id','=','bas_role.id')
->from('bas_app')
->select('bas_role_app.app_name','bas_role.name','bas_role_app.id')
->get();
return Datatables::of($app)->make(true);
}
public function update(Request $request, $id)
{
$routes = preg_match('/([a-z]*)#([a-z]*)/i', Route::currentRouteAction(), $matches);
$routes = $matches[0];
$action = $matches[2];
if (Auth::check()) {
$idUser = Auth::id();
DB::beginTransaction();
DB::table('bas_role_app')
->where('id', $id)
->update([
'role_id' => $request->role_name ,
'app_name' => $request->app_name,
]);
// dd($request->role_name);
return redirect('/roleapp')->with('message', 'Role App data update success!');
} else {
return view("login");
}
RoleApp.blade.php
#extends('layouts.master')
#section('title','Role App')
#section('content')
#if($errors->any())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{ implode(', ', $errors->all(':message')) }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
<div class="container mt-5">
<div class="row">
<div class="col-12">
<!-- Modal -->
<div class="float-left">
<div class="form-group mx-sm-3 mb-2">
<form class="form-inline">
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#exampleModalCenter">
<i class="ni ni-fat-add"></i>
</button>
</div>
</form>
</div>
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Add New Role</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
//Create new role app
<div class="modal-body">
<form action="roleapp/create" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label">Role Name:</label>
<select class="form-control select2bs4" data-live-search="true" data-placeholder="Choose Role Name" tabindex="1" name="role_name" style="width: 100%;" required>
<option value="">Choose Role Name.......</option>
#foreach ($bas_role as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="control-label">App Name:</label>
<select class="form-control select2bs4" data-placeholder="Choose App Name" tabindex="1" name="app_name" style="width: 100%;" required>
<option value="">Choose App Name.......</option>
#foreach ($bas_app as $category)
<option value="{{ $category->app_name }}">{{ $category->app_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"><i class="ni ni-fat-remove"></i></button>
<button type="submit" class="btn btn-primary"><i class="ni ni-check-bold"></i></button>
</div>
</form>
</div>
</div>
</div>
//show role app table
<table class="table table-striped" id="app">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Role Name</th>
<th scope="col">App Name</th>
<th scope="col">Action</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody id="dynamic-row">
</tbody>
</table>
#foreach ($app as $p)
<div class="modal fade" id="modal_edit_{{$p->id}}" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Edit RoleApp</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
//Update a role app
<div class="modal-body">
<form id="app_form_{{$p->id}}" action="{{ url('roleapp/update', [$p->id]) }}" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}" form="app_form_{{$p->id}}" />
<div class="form-group">
<label class="control-label">Role Name:</label>
<select class="form-control select2bs4" data-placeholder="Choose Role Name" tabindex="1" name="role_name" style="width: 100%;" required>
<option value="{{$p->id}}">{{$p->name}}</option>
#foreach ($bas_role as $category)
<option value="{{ $p->role_id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="control-label">App Name:</label>
<select class="form-control select2bs4" data-placeholder="Choose App Name" tabindex="1" name="app_name" style="width: 100%;" required>
<option value="{{$p->app_name}}">{{$p->app_name}}</option>
#foreach ($bas_app as $category)
<option value="{{ $p->app_name }}">{{ $category->app_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"><i class="ni ni-fat-remove"></i></button>
<button type="submit" form="app_form_{{$p->id}}" class="btn btn-primary"><i class="ni ni-check-bold"></i></button>
</div>
</form>
</div>
</div>
</div>
#endforeach
//delete a roleapp
#foreach ($app as $p)
<div class="modal fade" id="modal_hapus_{{$p->id}}" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Data akan dihapus</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Data yang dihapus tidak dapat dikembalikan!
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal"><i class="ni ni-fat-remove"></i></button>
<i class="ni ni-check-bold"></i>
</div>
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
<link rel="stylesheet" href="{{ asset('css/breadcrumb.css') }}">
<script>
//load search, individual or not
var row = 0;
$(document).ready(function() {
$('#app thead tr').clone(true).appendTo( '#app thead' );
$('#app thead tr:eq(1) th').each( function (i) {
if (row < 3) {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
} else {
$(this).html('');
}
row++;
$( 'input', this ).on( 'keyup change', function () {
if ( table.column(i).search() !== this.value ) {
table
.column(i)
.search( this.value )
.draw();
}
} );
} );
//load datatable processing, using serverside yajra, with pagination option, also action button as well
var table = $('#app').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('ajaxdata.getroleapp') }}",
"lengthMenu" : [[20, 50, 100, 500, 1000, -1],[20, 50, 100, 500, 1000, "All"]],
"columns":[
{ "data": "id" },
{ "data": "name" },
{ "data": "app_name" },
{
sortable: false,
"render": function ( data, type, full, meta ) {
return '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_edit_'+full.id+'"><i class="ni ni-single-02"></i></button>';
}
},
{
sortable: false,
"render": function ( data, type, full, meta ) {
return '<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#modal_hapus_'+full.id+'"><i class="ni ni-fat-delete"></i></button>';
}
},
],
});
$('.selectpicker').selectpicker({
style: 'btn-default',
// size: false
});
} );
</script>
{{--
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script> --}}
#endsection
please change the route HTTP verb for update -
Like Below
Route::put('/roleapp/update/{roleapp}', 'RoleAppController#update');
or
Route::match(['PUT','PATCH'],'/roleapp/update/{roleapp}', 'RoleAppController#update')
and update your blade view -
//Update a role app
<div class="modal-body">
<form id="app_form_{{$p->id}}" action="{{ url('roleapp/update', [$p->id]) }}" method="POST">
#method('PUT')
#csrf

Passing data attribute value into blade route

I'm building a blog to learn Laravel (5.4.13). In my posts show view I'm looping through all the corresponding post comments. Beside each comment is an edit button and a delete button. For comment editing, I'm attempting to use a modal instead of redirecting to the typical edit view. Currently I'm storing the specific comment data within two data-attributes, and then retrieving those values using jQuery. Then I'm using jQuery again to pass the data into the modal. This is working fine except I'm not sure how to pass the $comment->id into the form route. Any help is much appreciated.
#extends('main')
#section('title', 'View Post')
#section('content')
<div class="row">
<div class="col-md-8">
<h1>{{$post->title}}</h1>
<small>Published: <i class="fa fa-clock-o"></i> {{ $post->created_at->format('M Y, h:i a') }}</small>
<hr class="light-hr">
<p class="lead">{{ str_limit($post->body, $limit = 200, $end = '...') }}</p>
<hr>
<div class="tags">
#foreach($post->tags as $tag)
<span class="label">
{{ $tag->name }}
</span>
#endforeach
</div>
<br>
<br>
{{-- Display comments associated with posts --}}
<h4>Related Posts <i class="fa fa-level-down"></i></h4>
#foreach($post->comments as $comment)
<?php $avatars = array('monsterid', 'identicon', 'wavatar', 'retro'); ?>
<?php $randAvatars = urlencode($avatars[array_rand($avatars)]); ?>
<div class="comments">
<div class="author-info">
<div class="author-img">
<img src={{"https://www.gravatar.com/avatar/".md5(strtolower(trim($comment->email)))."?s=55&d=".$randAvatars}} class="img-circle" alt="user profile image">
</div>
<div class="author-meta">
<b>{{$comment->name}}</b>
made a post.
<h6>Published: <i class="fa fa-clock-o"></i> {{ $comment->created_at->format('M Y, h:i a') }}</h6>
</div>
<div class="comment-controls pull-right">
<button
type="button"
class="btn btn-primary btn-sm fa fa-pencil edit-comment"
data-toggle="modal"
data-comment="{{$comment->comment}}"
data-comment-id="{{$comment->id}}"
data-target="#editComment">
</button>
<button type="button" class="btn btn-danger btn-sm fa fa-trash"></button>
</div>
</div>
<div class="author-comment">
<hr>
<p>{{$comment->comment}}</p>
</div>
</div>
#endforeach
</div>
<div class="col-md-4">
<div class="well">
<dl class="dl-horizontal">
<dt>Created:&nbsp</dt>
<dd> {{ $post->created_at->format('M jS, Y') }}</dd>
<dd><i class="fa fa-clock-o"></i> {{ $post->created_at->format('h:i:s a') }}</dd>
</dl>
<dl class="dl-horizontal">
<dt>Last Updated:&nbsp</dt>
<dd>{{ $post->updated_at->format('M jS, Y') }}</dd>
<dd><i class="fa fa-clock-o"></i> {{ $post->updated_at->format('h:i:s a') }}</dd>
</dl>
<dl class="dl-horizontal">
<dt>Post Slug:&nbsp</dt>
<dd>{{ url('blog/'.$post->slug) }}</dd>
</dl>
<dl class="dl-horizontal">
<dt>Category:&nbsp</dt>
<dd>{{ $post->category->name }}</a></dd>
</dl>
<hr>
<div class="row">
<div class="col-sm-6">
Edit
</div>
<div class="col-sm-6">
<form action="{{ route('posts.destroy', $post->id) }}" method="POST">
<input type="submit" value="Delete" class="btn btn-danger btn-block">
<input type="hidden" name="_token" value="{{ Session::token() }}">
{{ method_field('DELETE') }}
</form>
</div>
<div class="col-sm-12">
Back to <i class="fa fa-long-arrow-right" aria-hidden="true"></i> Posts
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="editComment" tabindex="-1" role="dialog" aria-labelledby="editCommentLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="editCommentLabel">Edit Comment</h4>
</div>
<div class="modal-body">
<form action="{{route('comments.update', $comment->id)}}" method="POST">
<div class="modal-body">
<div class="form-group">
<textarea name="comment" class="form-control current-comment"></textarea>
<span class="test"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="Save Changes" class="btn btn-primary">
<input type="hidden" name="_token" value="{{ Session::token() }}">
{{ method_field('PUT') }}
</div>
</form>
</div>
</div>
</div>
</div>
#section('scripts')
<script>
$('.edit-comment').on('mousedown', function(){
var comment = $(this).attr('data-comment');
var comment_id = $(this).attr('data-comment-id');
$('.current-comment').html(comment);
$('.test').html(comment_id);
});
</script>
#endsection
#endsection
// Comments Routes
Route::post('comments/{id}', ['uses' => 'CommentsController#store', 'as' => 'comments.store']);
Route::put('comments/{id}', ['uses' => 'CommentsController#update', 'as' => 'comments.update']);
You're almost there. I would suggest that you don't need to pass the {id} since you use the [PUT] method to pass the data in your {form}.
We can set a new hidden {input} type inside your {form} (e.g input[name="edit_comment_id"]) and remove the request parameter from the url in your form's {action} attribute.
Like this:
<form action="{{route('comments.update')}}" method="POST" id="update-comment">
<div class="modal-body">
<div class="form-group">
<input type="hidden" name="edit_comment_id" /> //place the {id} in here
<textarea name="comment" class="form-control current-comment"></textarea>
<span class="test"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="Save Changes" class="btn btn-primary">
<input type="hidden" name="_token" value="{{ Session::token() }}">
{{ method_field('PUT') }}
</div>
</form>
Then in your {scripts} section:
$('.edit-comment').on('mousedown', function(){
var comment = $(this).attr('data-comment');
var comment_id = $(this).attr('data-comment-id'); // (e.g 12)
var oFormUpdateComment = $('#update-comment'); //add an {id} attribute on your form name 'update-comment' as given above.
oFormUpdateComment.find('input[name="edit_comment_id"]').val(comment_id);
});
And since we didn't pass a request parameter next to the 'comments' url anymore, You will update your [routes.php] like this:
Route::post('comments', ['uses' => 'CommentsController#store', 'as' => 'comments.store']);
Route::put('comments', ['uses' => 'CommentsController#update', 'as' => 'comments.update']);
Then in your [CommentsController], Since you already know how to get those values:
use Illuminate\Support\Facades\Input;
class CommentsController extends Controller
{
protected function store()
{
print_r('<pre>');
var_dump(Input::get('edit_comment_id'));
}
protected function update()
{
print_r('<pre>');
var_dump(Input::all());
}
}
Hope this helps for your case.
I was reluctant to answer this myself but was able to get it to work after rethinking my approach. Instead of trying to alter the blade url in the form somehow, I left the action attribute blank and built the url dynamically when the event fired. So as I did before, I grabbed the data from the data attributes, but instead of trying to alter the blade tag in the form, the url is built and then added to the action attribute. This thread was a great help. I posted my updated code incase it helps anyone.
#extends('main')
#section('title', 'View Post')
#section('content')
<div class="row">
<div class="col-md-8">
<h1>{{$post->title}}</h1>
<small>Published: <i class="fa fa-clock-o"></i> {{ $post->created_at->format('M Y, h:i a') }}</small>
<hr class="light-hr">
<p class="lead">{{ str_limit($post->body, $limit = 200, $end = '...') }}</p>
<hr>
<div class="tags">
#foreach($post->tags as $tag)
<span class="label">
{{ $tag->name }}
</span>
#endforeach
</div>
<br>
<br>
{{-- Display comments associated with posts --}}
<h4>Related Posts <i class="fa fa-level-down"></i></h4>
#foreach($post->comments as $comment)
<?php $avatars = array('monsterid', 'identicon', 'wavatar', 'retro'); ?>
<?php $randAvatars = urlencode($avatars[array_rand($avatars)]); ?>
<div class="comments">
<div class="author-info">
<div class="author-img">
<img src={{"https://www.gravatar.com/avatar/".md5(strtolower(trim($comment->email)))."?s=55&d=".$randAvatars}} class="img-circle" alt="user profile image">
</div>
<div class="author-meta">
<b>{{$comment->name}}</b>
made a post.
<h6>Published: <i class="fa fa-clock-o"></i> {{ $comment->created_at->format('M Y, h:i a') }}</h6>
</div>
<div class="comment-controls pull-right">
{{-- Store comment specific data to built URL for modal --}}
<button
type="button"
class="btn btn-primary btn-sm fa fa-pencil edit-comment"
data-toggle="modal"
data-comment="{{$comment->comment}}"
data-comment-id="{{$comment->id}}"
data-target="#editComment">
</button>
<button type="button" class="btn btn-danger btn-sm fa fa-trash" ></button>
</div>
</div>
<div class="author-comment">
<hr>
<p>{{$comment->comment}}</p>
</div>
</div>
#endforeach
</div>
<div class="col-md-4">
<div class="well">
<dl class="dl-horizontal">
<dt>Created:&nbsp</dt>
<dd> {{ $post->created_at->format('M jS, Y') }}</dd>
<dd><i class="fa fa-clock-o"></i> {{ $post->created_at->format('h:i:s a') }}</dd>
</dl>
<dl class="dl-horizontal">
<dt>Last Updated:&nbsp</dt>
<dd>{{ $post->updated_at->format('M jS, Y') }}</dd>
<dd><i class="fa fa-clock-o"></i> {{ $post->updated_at->format('h:i:s a') }}</dd>
</dl>
<dl class="dl-horizontal">
<dt>Post Slug:&nbsp</dt>
<dd>{{ url('blog/'.$post->slug) }}</dd>
</dl>
<dl class="dl-horizontal">
<dt>Category:&nbsp</dt>
<dd>{{ $post->category->name }}</a></dd>
</dl>
<hr>
<div class="row">
<div class="col-sm-6">
Edit
</div>
<div class="col-sm-6">
<form action="{{ route('posts.destroy', $post->id) }}" method="POST">
<input type="submit" value="Delete" class="btn btn-danger btn-block">
<input type="hidden" name="_token" value="{{ Session::token() }}">
{{ method_field('DELETE') }}
</form>
</div>
<div class="col-sm-12">
Back to <i class="fa fa-long-arrow-right" aria-hidden="true"></i> Posts
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="editComment" tabindex="-1" role="dialog" aria-labelledby="editCommentLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="editCommentLabel">Edit Comment</h4>
</div>
<div class="modal-body">
<form id="comment-edit-modal" action="" method="POST">
<div class="modal-body">
<div class="form-group">
<textarea name="comment" class="form-control current-comment"></textarea>
<span class="test"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="Save Changes" class="btn btn-primary">
<input type="hidden" name="_token" value="{{ Session::token() }}">
{{ method_field('PUT') }}
</div>
</form>
</div>
</div>
</div>
</div>
#section('scripts')
<script>
$('.edit-comment').on('mousedown', function(){
var comment = $(this).attr('data-comment');
$('.current-comment').html(comment);
var comment_id = $(this).attr('data-comment-id');
var form = $('#comment-edit-modal')
// Set current URL
var comment_edit_URL = {!! json_encode(url('/comments')) !!} + '/' + comment_id;
// Append currrent URL
form.attr('action', comment_edit_URL);
});
</script>
#endsection
#endsection

Categories