How to check if user is sorting table's column in datatables - laravel

I'm using yajra's datatables on Laravel 8, trying to implement "default sorting" on the server-side. It's already working, but I'm trying to find other solutions because the implementation feels a bit hacky.
I have something like this in my controller:
$myData = new MyData;
if ($request->order[0]['column'] === '0') {
$myData->orderBy('priority');
}
return DataTables::of($myData)->make(true);
Please notice the if ($request->order[0]['column'] === '0') part. The idea here is that if the table is initiated for the first time, alias users haven't made any column sorting by themselves, then the data should be sorted by whatever is defined inside the if-statement. The datatables itself doesn't have a defined order property, thus the sorting is given to column 0 by default.
I'm doing the sorting from the server-side because it's a bit complicated and will be easier to be done from the server rather than datatables. Once again, the code above IS working, but I just feel that this is a bit hacky. Is there any other alternatives I can use? Should I change the code, or is this alright?

So in your blade code on the front add this to your function to fill the datatable...
order: [],
This will tell datatables to not do any sorting of the data and use what you give it as the first sort order. Basically giving it an empty array.
Then you can get rid of the condition totally. Then just sort your data like you normally would in your eloquent collection you are making to fill said datatable.
Here is the documentation for this:
https://datatables.net/reference/option/order

Related

Laravel - Shuffle Merge and Paginate Collection

I am struggling with a pretty difficult thing and hope you can help me out.
Right now I've got the following:
$ads = Ad::where('status', 1)
->whereIn('ad_type', [1, 2, 3])
->where('expire_at', '>', date('Y-m-d H:i:s'))
->where('special_ad', 'standard_ad')
->orderByRaw(DB::raw("FIELD(ad_type,2,3,1)"));
Info:
This is working because it is an Eloquent Collection and I can Paginate this (needed for my Infinite Scroll)
But now I want to shuffle the ad_types in itself, meaning:
ad_type 1 could have, let's say, 30 entries. They will all be returned in the usual order. I want to shuffle those 30 every time I run this query.
I thought about doing ->toArray(); but then again, no pagination (Pagination only works on Eloquent Queries right?)
Then I thought, hey, let's merge this.
But as soon as I did that, the returned collection is no longer an Eloquent Collection but a Support Collection (right? I am not 100% sure it is a Support Collection) thus the Pagination does not work anymore.
I read upon many posts as how to solve this problem, and figured out one solution may be to "create my own paginator instance"
But heck, I am not that good yet. I do really not know, even after studying the laravel documentation, how to create my own paginator.
Important Infos you might need:
Using Laravel 5.2
$ads are dynamical, meaning depending on the case, the requests sent with Ajax, the query might differ at a later point (something might get included).
Thank you very much for your time reading this and hopefully, you can help me and future readers by solving this particular problem.
Greetings, and a great weekend to all of you.
Firstly just to note:
Pagination does not only work for database queries. You can manually paginate using LengthAwarePaginator but manually is the keyword here. The query builder (not Eloquent) can do it automatically for you using paginate.
You can "shuffle" the results by doing something like
$ads = Ad::where('status', 1)
->whereIn('ad_type', [1, 2, 3])
->where('expire_at', '>', date('Y-m-d H:i:s'))
->where('special_ad', 'standard_ad')
->orderByRaw("FIELD(ad_type,2,3,1)")
->orderByRaw("RAND()");
This will order by the ad_type field first and order by a random number (different for every row) as a secondary sort.

Can a PowerApps gallery be sorted from a derived column?

I have a PowerApps gallery that lists data from 3 different tables and have it normally sorted by the following:
SortByColumns(Filter(Personnel, !Dismissed, txtMSSearchBox.Text in MemberName), "MemberName", If(SortDescending1, SortOrder.Descending, SortOrder.Ascending))
One of the fields is displayed from the below:
Last(SortByColumns(Filter(PersonnelEvents, MemberNumber.Id = ThisItem.ID, EventType.Value="Promotion"), "Date", SortOrder.Ascending)).Title
What I would like to do is sort the gallery by this derived data. Is this even possible?
Can you try making On visible of the screen have an UpdateContext function which saves this formula as a variable.
You can then reference this variable as the column you want to sort by.
i.e something like UpdateContext({mySortColumn: Last(SortByColumns(Filter(PersonnelEvents, MemberNumber.Id = ThisItem.ID, EventType.Value="Promotion"), "Date", SortOrder.Ascending)).Title})
I just hope I really understand what you are trying to achieve, but if this doesn't work, maybe you can explain better what you are trying to do and hopefully I'll be able to help
I have decided to use Flow to update a column in my main table to show the relevant data and thereby sort by that field. I believe this would be an easier way to accomplish what I want.

Sorting Issue After Table Render in Laravel DataTables as a Service Implementation

I have implemented laravel dataTable as a service.
The initial two columns are actual id and names so, I am able to sort it asc/desc after the table renders.
But the next few columns renders after performing few calculations, i.e. these values are not fetched directly from any column rather it is processed.
I am unable to sort these columns where calculations were performed, and I get this error. And I know it is looking for that particular column for eg outstanding_amount which I don't have in the DB, rather it is a calculated amount from two or more columns that are in some other tables.
Any Suggestions on how to overcome this issue?
It looks like you're trying to sort by values that aren't columns, but calculated values.
So the main issue here is to give Eloquent/MySql the data it needs to provide the sorting.
// You might need to do some joins first
->addSelect(DB::raw('your_calc as outstanding_amount'))
->orderBy('outstanding_amount') // asc can be omitted as this is the default
// Anternative: you don't need the value sorted by
// Don't forget any joins you might need
->orderByRaw('your_calc_for_outstanding_amount ASC')
For SQL functions it'll work as follow
->addSelect(DB::raw('COUNT(products.id) as product_count'));
->orderByRaw(DB::raw('COUNT(products.id)'),'DESC');

datatables + adding a filter per column

How do I get the search/filter to work per column?
I am making small steps in building, and constantly adding to my data table, which is pretty dynamic at this stage. It basically builds a datatable based on the dat that is fed into it. I have now added the footer to act as a search/filter, but unfortunately this is where I have become stuck. I cannot get the filer part to work. Advice greatly appreciated.
here is my sample data tables that I am working on http://live.datatables.net/qociwesi/2/edit
It basically has dTableControl object that builds by table.
To build my table I need to call loadDataFromSocket which does the following:
//then I have this function for loading my data and creating my tables
//file is an array of objects
//formatFunc is a function that formats the data in the data table, and is stored in options for passing to the dTableControl for formatting the datatable - not using this in this example
//ch gets the keys from file[0] which will be the channel headers
//then I add the headers
//then I add the footers
//then I create the table
//then i build the rows using the correct values from file
//then I draw and this then draws all the row that were built
//now the tricky part of applying the search to each columns
So i have got this far but the search per column is not working. How do I get the search/filter to wrok per column?
Note this is a very basic working example that I have been working off: http://jsfiddle.net/HattrickNZ/t12w3a65/
You should use t1.oTable to access DataTables API, see updated example for demonstration.
Please compare your code with jsFiddle in your question, notice its simplicity and consider rewriting your code.

iterating over linq entity column

i need to insert a record with linq
i have a namevaluecollection with the data from a form post..
so started in the name=value&name2=value2 etc.. type format
thing is i need to inset all these values into the table, but of course the table fields are typed, and i need to type up the data before inserting it
i could of course explicitly do
linqtableobj.columnproperty = convert.toWhatever(value);
but i have many columns in the table, and the data coming back from the form, doesnt always contain all fields in the table
thought i could iterate over the linq objects columns, getting their datatype - to use to convert the appropriate value from the form data
fine all good, but then im still stuck with doing
linqtableobj.columnproterty = converted value
...if there is one for every column in the table
foreach(col in newlinqrowobj)
{
newlinqobj[col] = convert.changetype(namevaluecollection[col.name],col.datatype)
}
clearly i cant do that, but anything like that possible.. or
is it possible to loop around the columns for the new 'record' setting the values as i go.. and i guess grabbing the types at that point to do the conversion
stumped i am
thanks
nat
If you have some data type with a hundred different properties, and you want to copy those into a completely different data type with a hundred different properties, then somehow somewhere in your code you are going to have to define a hundred different "mapping" instructions. It doesn't matter what framework you are using, or whether the "mapping" instructions are lines of C# code, XML elements, lambda functions, proprietary "stuff", or whatever. There's no getting away from it.
Bearing that in mind, having one line of code per property looks to me like the fastest, simplest, most readable and maintainable solution.
If I understood your problem correctly, you could use reflection (or dynamic code generation if it is performance sensitive) to circumvent your typing problems
There is a preety good description of how to do something like this at codeproject.
Basically you get a PropertyInfo for the property you want to set (if it's not a property I think you would need dynamic code generation) and use it's setValue method (after calling the appropriate Convert.ChangeType of course). This will basicall circumvent the whole static typing, so there you are.

Resources