Skip to content

The array returned by formatRow() are serial arrays instead of preferable associative arrays #11

Description

@makoru-hikage

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:

  1. On the developer's end, transform $result[] = $data[$column]; to $result[$column] = $data[$column];
  2. 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.
  3. 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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions