I'm trying to figure out how to have a table where each row has data including a unique ID and an edit button. When the edit button is clicked I would like for another section of the page to show a form to edit the data on that line. So far I have something like:
//linePage.blade.php
<table>
#foreach($lineList as $line)
<tr>
<td>{{ $line->Name }}</td>
<td>Edit</td>
</tr>
#endforeach
</table>
#if (!empty($lineSelected))
{{-- show form --}}
#endif
//routes.php
Route::get('/LinePage/{lineSelected?}', 'Forms#linePage');
Route::post('/LinePage/{lineSelected?}', 'Forms#updateLinePage');
//Forms.php
public function linePage($lineSelected = NULL){
$data = array('lineSelected=>$lineSelected);
return View::make('Forms\linePage',$data);
}
public function updateLinePage($lineSelected = NULL){
$data = array('lineSelected=>$lineSelected);
return View::make('Forms\linePage',$data);
}
This is working for me but I feel like I'm making it more complicated than it needs to be. Am I going about this correctly? Also, I don't like how the address bar shows localhost/LinePage/LineName once the line is selected. Is it possible to somehow hide the data being passed within the page?
Thanks
a simpler method for this is to use Javascript (and/or) jQuery .
The basic idea is, when you click a button in the table, you will make an ajax request. In that ajax request, you have only the form for that particular lineName . In this way, the page will not be reloaded, and you won't get to change the URL, and it's more fast .
If you choose to do this with jQuery. You will have something like :
//linePage.blade.php
<table>
#foreach($lineList as $line)
<tr>
<td>{{ $line->Name }}</td>
<td>Edit</td>
</tr>
#endforeach
</table>
//in the footer somewhere, after you load query
<script>
$(function()
{
$('a.btn-line').click(function(event){
var id = event.target.id;
fieldName = id.split('-');
lineName = fieldName[1];
$.get(
"{{action('Forms#lineForm'}}?lineName="+lineName,
function(data){
$('div#line-form').html(data);
}
);
});
</script>
in your routes :
Route::get('/linePage/form/', 'Forms#lineFormPage');
and in your controller, you will return the view with only the form
Maybe this is not the easiest way to do, but you won't need to refresh every time you need to reload the form, + it keeps things more separated
Related
I am trying to pass id of currently selected row inside for loop when someone clicks on it
And pass that id to vue component
My index.blade file
#foreach($cats as $cat)
<tr>
<td class="catme" data-id="{{$cat->id}}">{{$cat-> title}}</td></tr>
#endforeach
<car-component i want to pass prop here></car-component>
<script>
$('.catme').on('click',function(){
var a = $('.catme').attr('data-id')
})
</script>
I am unable to set that a varaiable value to that component
<----- GOAL ----->
My requirements is to have a component inside a blade file and to have forloop with multiple records such that if one row is selected its id is passed as prop to the component but it is outside the loop
You can try the below function and it should work
<script>
$('.catme').on('click',function(){
var a = $(this).data('id')
this.$refs.component.prop = a;
});
</script>
I am trying to show all data from my table in my laravel blade view.
Controller
public function search()
{
$search = request('show');
$users = User::query();
foreach ($search as $field=>$value)
{
if($value!=NULL)
{
$users = $users->where($field, 'LIKE', '%'.$value.'%');
}
}
if(request()->has('sort'))
{
$order = explode(',',request('sort'));
$users = $users->orderBy($order[0],$order[1]);
}
$users = $users->SimplePaginate(15);
return view('nabil.homepage',compact('users'));
}
Blade
#foreach($users as $user)
<tr>
#if(session()->has('show'))
#foreach(session()->get('columns') as $column)
#if(in_array($column,session()->get('show')))
<td>{{ $user->$column }}</td>
#endif
#endforeach
#endif
</tr>
#endforeach
</table>
{{ $users->appends(Illuminate\Support\Facades\Input::except('page'))->links() }}
If I search something then it works perfectly. But if I search with blank value. Then it doesn't work. The first page comes without any problem but then it breaks.
Case 1 (problematic case):
I input an empty value in search. So the search url is /search?show%5Bbango%5D= .
However, when I click next then the url becomes /search?page=2 (And returns error)
If I manually input /search?show%5Bbango%5D=&page=2 in url address then it works perfectly.
Case 2:
I input some data like '123' in search. Then my url becomes /search?show%5Bbango%5D=123 .
In that case everything works perfectly.
Case 3:
It may be irrelevant. But if I run query in more than one field then it works ok but somehow all empty inputs get removed from url when I use pagination.
I may try to search with two input fields (example: name and bango). If I keep the name field empty and put '123'in bango then the url becomes like /search?show%5Bbango%5D=123&show%5Bname%5D=.
However, if I try to go to next page. then the url becomes /search?show%5Bbango%5D=123&page=2.
Although, the showed results are good but url suddenly drops the name field.
How can I make sure that the pagination still works for empty input. I checked in some similar questions and tried appending query request. But it still doesn't work for me.
Since you are using foreach, it is expecting an array. Try to set
$search = request('show') ?? [];
on the controller.
Hi there once again SO community. I've been developing a site and so far it's going pretty well. But today after a long day searching for a solution I can't understand nor find what the right path is...
I want to click on a button and a profile page where you can edit the fields appear. I can redirect to the page I want but I don't know how to send the user data so I can populate the fields.
Here is my button code on my view
<button class="btn btn-xs btn-warning dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false" style="border-color: black" id="dados_{{ $user->username }}"> Alterar Dados Pessoais
<i class="glyphicon glyphicon-cog"></i>
</button>
Here is the button AJAX request handler
if((this.id).indexOf("dados") != -1){
var content = this.id.replace("dados_", "");
$.get('callPermissions', {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
And here is my callPermission Controller
public function callPermissions(Request $request)
{
if($request->ajax()){
$usernames = Input::get('usernameSend');
if(isset($usernames)){
$user = User::Where('username', '=', $usernames)->first();
$returnHTML = view('userOptions.settings')->render();
return view('userOptions.settings');
}else{
Log::warning("Username não existe na base de dados.");
}
}
}
and here my Settings Controller
public function settings(Request $request)
{
return view('userOptions.settings');
}
And here is the route
Route::get('/callPermissions', 'SidebarController#callPermissions');
I know the controller is wrong and from what I've read I should verify if the AJAX is successful and if it is handle i on the AJAX request. But from what I've understand I'm not using the Controller at all (even though it goes there). How should I send the user information (in this case the username, then I can get everything from the database) and then send it to the view? I've been searching and trying out stuff that doesn't work...since the return view("your_view") on the Controller doesn't work.
Sorry if I've been confusing and if you need additional information feel free to ask!
Thanks for your help!!
Edit: If I return this on the controller
return view('userOptions.settings', compact('user'));
and do a replace with the Ajax request as show above and add this to the settings view
<p> {{ $user->name }} </p>
I get the following error Undefined variable: user (View: C:\wamp64\www\siteXL\ideiasxl\resources\views\userOptions\settings.blade.php)
Is there anyway to send the parameters with a compact alike or I need to send it through the link? Was avoiding to show the username on the url.
Edit2: For further clarification, this works as intended
<button onclick="window.location='{{url('/settings/' . $user->username)}}'" type="button" id="dadosPessoais" class="btn btn-default">Alterar Dados Pessoais
<i class="glyphicon glyphicon-wrench"></i>
</button>
but I was trying not to send id's and usernames through the URL.
If this is not achievable it's ok, but if there's a way I can't find it, that's why I'm asking
I think you have to add a parameter in the Route and receive the data in the controller function. I'd do something like this:
Route:
Route::get('/callPermissions/{user}', 'SidebarController#callPermissions');
Controller:
public function callPermissions(Request $request, $user)
{
//get data related to $user
}
Ajax call:
$.get('callPermissions/'+userIdVariable, {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
This would send the user id through the route.
To get the user id with JavaScript, you can make a hidden field in the Blade file and set the user id as the value. For example, if you using Form helper:
{{ Form::hidden('user_id', $user->id, array('id' => 'js-user-id')) }}
And then, in the JavaScript, you can get the value using something like this:
var userIdVariable = $('#js-user-id')->val();
View
{!! Form::open(array('url'=>'storeID/'.$id)) !!}`
#foreach($itemlist as $items)
<tr>
<td>{!! Form::text('max_' . $items->id, old('max', $items->max_qty) !!}</td>
</tr>
#endforeach
<button type="submit" class="btn btn-complete">Save</button>
Controller
public function storeItem(Request $request, $id_b)
{
$id = Prod::where('id_b', $id_b)->pluck('id_p')->toArray();
foreach($id as $key => $val)
{
$max_qty = 'max_'.$val;
$p = Prod::where('id_b', $id_b)->where('id_p', $val)->first();
$p->max_qty = Input::get($max);
$p->save();
}
}
}
JS
$('#form').on('submit', function(e){
var form = this;
// Encode a set of form elements from all pages as an array of names and values
var params = table.$('input,select,textarea').serializeArray();
// Iterate over all form elements
$.each(params, function(){
// If element doesn't exist in DOM
if(!$.contains(document, form[this.name])){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
});
});
I want to store the value of input field from data table into database, but it only allows to save the page where is active only, the other field value will became null. For example, there are 2 pages of data, i only allow to save the data on current active page, other pages value will get null. Any solution to solve this issue?
Your key for old() is incorrect:
<td>{!! Form::text('max_' . $items->id, old('max', $items->max_qty) !!}</td>
Should be
<td>{!! Form::text('max_' . $items->id, old('max_' . $items->id, $items->max_qty) !!}</td>
I'm not sure I understand your question entirely. By active do you mean the page currently displayed in the browser? Only the input in the form you submit will be sent to the server unless you're appending data via JavaScript post submission.
I have a Laravel application where I create a page layout, adding a table to it as a "content" variable (pretty much all from tutorials I found). Here's the controller action:
public function getMain() {
$js_config = Category::all();
$resources = Resource::all()->take(100);
$this->layout->content = View::make('categories.show')->with('js_config', $js_config)->with('resources', $resources);
}
This uses the main layout template and inserts this table using the content variable:
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
</thead>
<tbody>
#foreach($resources as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->title }}</td>
</tr>
#endforeach
</tbody>
</table>
But then comes the problem: I have a jstree where the user can select nodes, triggering a jQuery method:
$('#jstree2').on("changed.jstree", function (e, data) {
console.log(data.selected);
$.get("filter", { category: data.selected })
.done(function (resultdata) {
//Test only, this returns the data wanted in json, which I stringify just to display in test
alert("Data Loaded: " + JSON.stringify(resultdata));
});
});
The jQuery calls this action method in the controller:
public function getFilter()
{
$input = Input::get('category.0');
$categories = Category::find($input);
//category is the name from the model below
return Response::json(array(
'error' => false,
'category' => $categories->toArray()),
200
);
}
(The reason there's an array as input is I eventually want to be able to allow picking multiple nodes in the tree)
This action gets the data from the DB correctly and returns it as json. The callback in the jQuery above then alerts this at the moment, just as a test.
But what I really want to do, of course, is to repopulate the table. Now, as you can see I have used Bootstrap to create a pretty table and all, and I just want to be able to let the user repopulate it at will, without refreshing the page.
But I don't know how to do that, except by painstakingly recreate this table in some sort of string return value, but that doesn't seem like a good idea.
I'm hoping there's some way of passing the return value back to the view and have it reload the values in the table, utilizing the same "sub view" that I loaded in the php variable "content" as described above?
Any help greatly appreciated!
EDIT:
As requested, here's a sample of the json (taken from the browser console output, and it's actually not the categories table, but the same format):
[{"id":"1","title":"Transportation AC 4494","created_by":"4","modified_by":null},{"id":"2","title":"Safety First AC 4294","created_by":"3","modified_by":null},{"id":"3","title":"Warranty AC 34066","created_by":"4","modified_by":null}]
EDIT 2 (Just realized there was some crap from the controller in the previous edit of the json, so I changed it to a cleaner sample now)
EDIT 3:
I have made this work by creating the table rows in jQuery:
var trHTML = '';
$.each(resultdata, function (i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.title + '</tr>';
});
$('#ajaxtable').html(trHTML);
But mainly I'm hoping this might explain my question better: this is not what I wanted to do. What I would have wanted was to just create a partial view and then load that ready-made view with the jquery:
A partial view like this:
<table class="table table-striped table-bordered" id="resultstable">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
</thead>
<tbody id="ajaxtable">
#foreach($resources as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->title }}</td>
</tr>
#endforeach
</tbody>
</table>
I tested this by creating and calling a new function in the controller from the jquery code:
public function getTable()
{
$resources = Resource::all()->take(5);
return View::make('categories.results')->with('resources', $resources);
}
But it doesn't work. Although it does indeed give me the html of that view, it is unprocessed. I.e, the foreach loop is not resolved, but still there as code in the table. See the image:
So how can I load this view with the jquery code? It feels to me that even if the jquery creation of table rows works, doing the view in php and then just loading it with jquery should be the more correct way of doing it...?
Have you looked into the Datatables jQuery plugin? There is actually a nice package for Laravel that helps integrate Laravel and Datatables. The Laravel package generates the json and you can use Datables+AJAX to repopulate the data. Might be working checking out...
https://github.com/Chumper/datatable
http://datatables.net/
Otherwise, you'll just need to use AJAX to repopulate the table.
As Sirago answered, using jQuery Datatables is a good option to load data into tables in ajax manner.
In addition to what Sirago suggested, here is another great Laravel 4 package which is dedicated to generate JSON data from server side.
https://github.com/bllim/laravel4-datatables-package
But apart from server side configuration(modifying files like composer.json, config/app.php etc.), you need to code in Javascript, utilizing Datatables as well.