typo3extbaseuserid

TYPO3 get the user from cruser_id field


i would like to show the user who created an element. The TCA looks like this:

  'ctrl' => [
    'title' => 'Title',
    'label' => 'title',
    'tstamp' => 'tstamp',
    'crdate' => 'crdate',
    'cruser_id' => 'cruser_id',

With getter i can get the tstamp and the crdate. But with the cruser_id this doesn't work. How can i get the user name of the user with the cruser_id?


Solution

  • The following example, works on TYPO3 11.5.8 and should work with TYPO3 10 as well.

    First you need your getters und setters on your model (\YourVendor\YourExtension\Domain\Model\YourModel)

    /**
     * @var int
     */
    protected int $cruserId = 0;
    
    /**
     * @return int
     */
    public function getCruserId(): int
    {
        return $this->cruserId;
    }
    
    /**
     * @param int $cruserId
     */
    public function setCruserId(int $cruserId): void
    {
        $this->cruserId = $cruserId;
    }
    

    Then you need to add the TCA configuration for this specific field. You do not need to add it on types or anywhere else. TYPO3 just needs the configuration so it knows what to do with it.

    'cruser_id' => [
        'config' => [
           'type' => 'input',
           'size' => 10,
           'max' => 255,
       ],
    ],
    

    Last and not least, you need to map it on the right column. So under your your_extension/Configuration/Extbase/Persistence/Classes.php you need to add your Model and the property:

     \YourVendor\YourExtension\Domain\Model\YourModel::class => [
      'columns' => [
            'cruserId' => [
                'mapOnProperty' => 'cruser_id'
            ]
        ]
     ]
    

    Here is a reference: TYPO3 v10 How do i get an object's crdate or the tstamp in FrontEnd


    Backend User Object

    If you want to get the Backend user information, the steps are the same but some changes need to be made.

    Model

    use TYPO3\CMS\Beuser\Domain\Model\BackendUser
    
    /**
     * @var BackendUser|null
     */
    protected ?BackendUser $cruserId = null;
    
     /**
     * @return BackendUser|null
     */
    public function getCruserId(): ?BackendUser
    {
        return $this->cruserId;
    }
    
    /**
     * @param ?BackendUser $cruserId
     */
    public function setCruserId(?BackendUser $cruserId): void
    {
        $this->cruserId = $cruserId;
    }
    

    TCA

    'cruser_id' => [
       'config' => [
         'type' => 'select',
         'renderType' => 'selectSingle',
         'foreign_table' => 'be_users',
         'foreign_table_where' => 'ORDER BY username',
       ],
    ],
    

    This will give you the following:

    enter image description here

    Hope it helped