Customizing table headers in Yajra Laravel Datatables

I am encountering an issue with category sorting on my list of products. When I click on category sorting, it only shows the same category and product name repeatedly. All other sorting functions are working correctly, except for category sorting. I have tried changing category.name to category_name, but that causes category sorting to stop working altogether. I am at a loss as to why this is happening and how to resolve it.
Is there a way to use an Alias for the category name? And which file do I need to modify in order to make these changes?

    var table = $('#product-table').DataTable({
                processing: true,
                serverSide: true,
                bStateSave: true,
                ordering: true,
                dom: 'Bfrtip',
                buttons:[],
                ajax: '{{ URL::to('/admin/products.data') }}',
                order: [[1, 'asc']],
                columnDefs: [
                    { orderable: false, targets: 0 }
                ],
                columns: [
                    {data: 'edit', name: '', searchable:false},
                    {data: 'name', name: 'name'},
                    {data: 'product_code', name: 'product_code'},
                    {data: 'category_name', name: 'category.name'},
                    {data: 'impa_code', name: 'impa_code'},
                    {data: 'issa_code', name: 'issa_code'},
                    {data: 'status', name: 'is_active'}
                ],
                "deferRender": true
            });


**This is my blade file**


`<div class="row clearfix">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 m-t-50">
        <div class="card">
            <div class="body">
                <table class="table table-striped table-hover dataTable" id="product-table">
                    <thead>
                    <tr>
                        <th class="col-sm-1"></th>
                        <th>{{ Lang::get('views.name') }}</th>
                        <th>{{ Lang::get('views.shipskart_code') }}</th>
                        <th>{{ Lang::get('views.category_name') }}</th>
                        <th>{{ Lang::get('views.impa_code') }}</th>
                        <th>{{ Lang::get('views.issa_code') }}</th>
                        <th>{{ Lang::get('views.status') }}</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</div>`




This is Controller



` ->editColumn('product_code', function ($product) {
                $productCode = $product['product_code'];
                return $productCode;
            })
            ->addColumn('category_name', function ($product) {
                return empty($product->category) ? 'N/A' : $product->category->name ;
            })
            ->editColumn('impa_code', function ($product) {
                $impaCode = $product->impa_code;
                return $impaCode;
            })
            ->editColumn('issa_code', function ($product) {
                $issaCode = $product->issa_code;
                return $issaCode;`

Answer №1

My understanding is that this pertains to the Laravel datatable.

In Case of a Naming Issue

If you wish to modify the header name to something like category.name in the blade view displaying the table, locate the headers and make the necessary adjustments there.

Replace this line:

<th>{{ Lang::get('views.category_name') }}</th>

with:

<th>{{ the new name }}</th>

If you want it to reflect the language code as well, update your language files.

Go to the Views, in the specific language you want to modify, and edit the category_name file.

For instance, if you want to change category_name to CAT title in English language, navigate to /resources/lang/en or wherever your lang/en folder is located and adjust the line.

'category_name' => 'CAT title'

If It's a Data Issue

If the data isn't reflecting what you expect, always examine the link causing the problem, such as

/admin/products.data

Here, you can determine exactly what data is being received so you can display it correctly in your table. Consult the DataTable Manual for guidance.

For example, if you're getting a product array with a key named name, in JavaScript it would be referred to as product.name as per how JSON is interpreted.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Code snippet for fetching JavaScript file using Angular's caching mechanism

Currently in my project, I am utilizing $.getScript to dynamically load specific sections of code. Here's a snippet of how it looks: var mainJs = "/main.js"; $.getScript( mainJs ) .then(function () { console.log("main.js loaded"); }); ...

What is the most efficient way to add an attribute in jQuery - using the attr() method, passing attributes as a key-value object, or directly?

There are three ways that I am aware of for adding a href attribute with a relative link in jQuery: using (1) .attr(), (2) attributes as key-value pair in an argument, or (3) direct writing (if you know other methods, please share in your response so I can ...

npm causing problems with babel-cli

While working on building a section of my library with Babel, I've encountered some issues when running Babel commands through npm. In my npm script named "build," the following commands are executed: { "prebuild": "rm -rf && mkdir dist", ...

What exactly entails static site generation?

I have been exploring the concept of static site generation (SSG). The interesting question that arises is how SSG can fetch data at build time. In my latest application, I implemented an event handler to retrieve data based on a user's search keyword ...

Using Node/Express to split the request headers with the .split() method

I am currently working on a way to determine if a specific item exists in the req.headers in order to make a decision on what to send back to the user. Here is my code snippet: function serveAppData(req, res) { console.log("CHECKME", req.headers); //var h ...

Converting an onclick event to onsubmit: Tips for doing it right

Recently, I had to add validation to a file upload form for our Google Drive. After some research, I discovered that using onsubmit instead of onclick was the way to go. However, when I made the switch from onclick to onsubmit, the validation worked but t ...

Error: Trying to access the 'push' method of an undefined object of useHistory

import React from "react"; import { Route, Switch, HashRouter, useHistory } from "react-router-dom"; import Home from "../pages/home/HomeComponent"; import Splash from "../pages/splash/Splash"; import Education from ...

Access and retrieve data from a string using XPath with JavaScript

My HTML page content is stored as a string shown below: <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> </ ...

Automatically activate the next tab in Bootstrap

I have a modal that performs a count. Once the count is completed, the modal closes. My goal is to automatically switch to the next tab in Bootstrap when the modal closes. Here is the HTML: <ul class="nav nav-tabs namelocationtable"> <div clas ...

Having trouble formatting the date value using the XLSX Library in Javascript?

I'm having trouble separating the headers of an Excel sheet. The code I have implemented is only working for text format. Could someone please assist me? const xlsx = require('xlsx'); const workbook = xlsx.readFile('./SMALL.xlsx') ...

JavaScript will not prevent PHP form submissions from executing

I am currently facing an issue with JavaScript where it displays an error window, but surprisingly does not prevent the form submission. I have been trying to figure out what exactly is causing this problem without much success. Below is the code I am work ...

The action 'onDeleteClick' cannot be executed as the property is undefined

Why is the onDeleteClick function working on the first <div>, but returning undefined on the second one? I am able to access the reference of this, but when clicking, it shows "onDeleteClick of undefined". I am confused as to why the onDeleteClick f ...

Adding an Icon to a Tab in Ant Design - A Step-by-Step Guide

Is there a way to include an icon before the title of each open tab? I am currently using the antd library for tab creation, which doesn't provide a direct option for adding icons. Here is my code snippet along with a link to the jsfiddle https://jsfi ...

Updating state atoms in Recoil.js externally from components: A comprehensive guide for React users

Being new to Recoil.js, I have set up an atom and selector for the signed-in user in my app: const signedInUserAtom = atom<SignedInUser | null>({ key: 'signedInUserAtom', default: null }) export const signedInUserSelector = selecto ...

What could be causing my input to not activate my function?

I am having issues with my input buttons not triggering my functions. Can anyone provide some insight into this problem? <div id="windowBar"> <h3>Imagine you were a superhero...</h3> <input id="WindowClose" type="button" onclick=" ...

Why is this regular expression failing to match German words?

I am attempting to separate the words in the following sentence and enclose them in individual span elements. <p class="german_p big">Das ist ein schönes Armband</p> I came across this: How to get a word under cursor using JavaScript? $(&ap ...

Step-by-step guide to accessing the detail view upon selecting a table row in react.js

In my project, I have a table with multiple rows. When a row is selected, I want to display detailed information about that particular item. To achieve this functionality, I am utilizing react-router-dom v6 and MUI's material table component. Here is ...

Using javascript to extract values from nested JSON structures without prior key knowledge

My JSON data is structured as follows: {"sensors": {"-KqYN_VeXCh8CZQFRusI": {"bathroom_temp": 16, "date": "02/08/2017", "fridge_level": 8, "kitchen_temp": 18, "living_temp": 17, ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

Using JavaScript along with Ajax and JSON allows for sending complex data structures such as objects and

One of the features on my form allows users to input information about their clients. This versatile form enables users to add multiple phone numbers, email addresses, and physical addresses without any limitations. When adding a phone number or an email ...