-
Notifications
You must be signed in to change notification settings - Fork 40
Description
Let's say I've a Model called User. The User has id, username, and password.
When someone makes:
$dt = new DataTable(new User, ['id', 'username', 'password']);
$r = $dt->make();
echo json_encode($r);
It'll return:
{
...
data : [
[ 1, "sample_user", "sample_password"],
...
]
}
It happens because the code (L146-149, DataTable.php) is:
$result = [];
foreach ($this->columnNames as $column) {
$result[] = $data[$column];
}
The code (L148) : $result[] = $data[$column]; only pushes an array.
If L148 is like that, this code(L152): $data = $this->formatRowIndexes($data); is nothing, because:
if (isset($data['id']))
is obviously searching for a key in a serial array, which will always be false.
In order to resolve this issue, there are three ways:
- On the developer's end, transform
$result[] = $data[$column];to$result[$column] = $data[$column]; - On the developers end again, create another function similar to that so the user can have a choice between an array of serial arrays or an array of associative arrays that will eventually become objects when
json_encoded. - On the user's end, supply a certain anonymous function for the 3rd argument of the constructor. Such function must have something like
$result[$column] = $data[$column];
If any of the three is done. The result can look like this when json_encoded:
{
...
data : [
{ id: 1, username: "sample_user", password: "sample_password"},
...
]
}
Should a serial array be returned by make(), the DataTable() of jQuery Data Tables will throw an error if its columns option is not null (where an array of correct values are supplied). Otherwise, it'll work fine, but not when dealing with DataTables Editor.