Philipp M Philipp M - 1 month ago 25
PHP Question

TYPO3 - how to get FE UID via Viewhelper

How can I fetch and render the uid of the FE User via a Viewhelper? The below is working via a Controller ... but not in a Viewhelper. Where is the difference? I'm using 7.6.11 and at the end I would like to have the uid of the FE User and the usergroup uid of him and further use it in the html of the extension and in general partials ...

/typo3conf/ext/extension/Classes/ViewHelpers/UserViewHelper.php

<?php

namespace Vendor\Extension\ViewHelpers;

class UserViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {

/**
* User Repository
*
* @var \TYPO3\CMS\Extbase\Domain\Repository\FrontendUserRepository
* @inject
*/
protected $userRepository;

/**
* @var \TYPO3\CMS\Extbase\Domain\Repository\FrontendUserGroupRepository
* @inject
*/
protected $frontendUserGroupRepository;

public function render() {

$userIDTest = $this->userRepository->findByUid($GLOBALS['TSFE']->fe_user->user['uid']);
$this->view->assign('userIDTest', $userIDTest);

}

}


List.html

<f:layout name="Default" />
<f:section name="main">

{userIDTest.uid}

</f:section>


As suggested by Dimitry I replaced

$this->view->assign('userIDTest', $userIDTest);


with

return $userIDTest;


And in List.html I have this:

{namespace custom=Vendor\Extension\ViewHelpers}

<f:layout name="Default" />
<f:section name="main">

<f:alias map="{user: '{custom:user()}'}">
{user.uid} {user.username}
</f:alias>

</f:section>


... and after clearing all Caches (FE/BE/Install) and deleting typo3temp ... now its working!

Answer

if you want to return the user or the uid of the user in the viewhelper, just return it.

instead of

$this->view->assign('userIDTest', $userIDTest);

do this

return $userIDTest;

In your fluid you can use the user variables in different ways. The easiest one is to use the "alias" viewhelper: https://fluidtypo3.org/viewhelpers/fluid/master/AliasViewHelper.html

<f:alias map="{user: '{namespace:user()}'}">
    {user.uid} {user.username}
</f:alias>