How to change the sort order of the item's field list

Erstellt am: Dienstag 7 Februar 2017  |  Letzte Änderung am: Samstag 11 August 2018

You might be surprised, when you try to display the fields of an item ordered by their position, that you have defined by drag and drop under the fields menu:

$userid = 1;
$imanager = imanager();
$user = $imanager->getItem('slug=Users', $userid);
echo '<h2>User data</h2>';
echo '<table>';
foreach ($user->fields as $data) 
{
    echo '
        <tr>
            <td><strong>'.$data->label.': </strong></td>
            <td>'.$data->value.'</td>
        </tr>
    ';
}
echo '</table>';

The output might look like this:

The thing is that, usually IM doesn't care about the sorting of fields. By default, the fields are simply sorted by their Id's and not by position - which saves execution time. Sometimes, however, the fields need to be displayed automatically according to their position. Solution: To display the fields according to their position or other required criteria, you'll need to use FieldMapper::filterFields() function:

$userid = 1;
$imanager = imanager();
$user = $imanager->getItem('slug=Users', $userid);
$fieldMapper = new FieldMapper();
$fields = $fieldMapper->filterFields('position', 'ASC', (array) $user->fields);
echo '<h2>User data</h2>';
echo '<table>';
foreach ($fields as $data)
{
     echo '
        <tr>
            <td><strong>'.$data->label.': </strong></td>
            <td>'.$data->value.'</td>
        </tr>
    ';
}
echo '</table>';

Unfortunately, the sorting is done at runtime and if this order is desired permanently, it is better to save the fields accordingly:

Perform a backup of the /data/imanager folder before executing the code.

// Reoder item fields on position
$imanager = imanager();
$category = $imanager->getCategory('slug=Users');
$users = $imanager->getItems($category->id);
$fieldMapper = new FieldMapper();
foreach($users as $user) 
{
    $fields = $fieldMapper->filterFields('position', 'ASC', (array) $user->fields);
    foreach($fields as $field) 
    {
        $field->id = $field->position;
        $field->save();
        $user->fields->{$field->name}->id = $field->position;
    }
    $user->save();
}

Now the fields should be automatically displayed in the correct order.

Autor: Bigin  |  Tags:  FrameworkPHPGetSimpleDevelopmentItemManager