How to display username instead of id in a list in octobercms?

by herminia_bruen , in category: PHP CMS , 6 months ago

How to display username instead of id in a list in octobercms?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 6 months ago

@herminia_bruen 

To display a username instead of an ID in a list in OctoberCMS, you can use the belongsTo relationship available in the model file.


Assuming you have a model named MyModel with a user_id column referring to the user ID, follow these steps:


Step 1: Define the relationship in the MyModel model file. In the MyModel model file, add the belongsTo relationship to define the connection between the user_id column and the User model's id column.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class MyModel extends Model
{
    // ...

    public $belongsTo = [
        'user' => ['RainLabUserModelsUser']
    ];

    // ...
}


Step 2: Use the relationship in the list view file. In the list view file (e.g., partials/list.htm), you can access the user relationship defined in the model to display the username instead of the ID.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<table>
    <thead>
        <th>Username</th>
        <!-- Other table headers -->
    </thead>
    <tbody>
        {% for item in items %}
        <tr>
            <td>{{ item.user.username }}</td>
            <!-- Other table columns -->
        </tr>
        {% endfor %}
    </tbody>
</table>


Note: Ensure that the user_id column in your MyModel table corresponds to the id column in the users table.


With the above steps, you should be able to display the username instead of the ID in your list in OctoberCMS.