1

I've activated public user registration using the register.twig template mentioned in the documentation: https://craftcms.com/knowledge-base/front-end-user-accounts#registration-form

Unfortunately the user variable doesn't get passed back if for any reason the user account cannot be created.

I'm using CraftCMS version 4.4 and can't find the issue.

Displaying flashes works fine, but it only tells the user, that the account cannot be created without individual validation errors.

3
  • Can you please post the code you're using? Also, are you using include() to display the form? If so, post that code as well.
    – MoritzLost
    Commented Sep 28, 2023 at 19:29
  • Thank you so much! That was the needed hint. I was including the form over several includes and at the beginning declared the passed variables individually and added an "only" to strip the rest. Just added "user: user ?? null" to the variables and now it works as expected.
    – Marc
    Commented Sep 29, 2023 at 6:23
  • Had a feeling that was the issue, I've encountered that a couple of times as well :) I've added an answer explaining the cause of the issue in case anyone else is looking for it, as well as an alternative solution that will work regardless of the context.
    – MoritzLost
    Commented Sep 29, 2023 at 12:12

1 Answer 1

1

The user variable is only passed to the template as a variable, but not set as a global variable in the Twig environment. This means that only the top-level template being rendered has access to it. If you use the include() function, the current context (variables) will be passed to the included template by default, so the user variable will be also be available in the included template. However, if you use with_context = false in the include() function, the context will not be passed down to the included template. The same applies to the {% embed %} tag with the with {} only keyword at the end. That's why the user variable may not be available in an included or embedded template.

If you prefer to use with_context = false so included templates only have access to variables that you pass explicitly, here's a solution that will work regardless of the current context. The user variable is set by the UsersController through the UrlManager as a route parameter. You can access the UrlManager instance directly and get the user model from there:

{% set routeParams = craft.app.getUrlManager().getRouteParams() %}
{% set user = routeParams.user ?? null %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.