Creating a Front-end Login Form

We review the code needed to create a login form for Craft CMS front-end members.

Now that we’re reg­is­tered, let’s review the login form. We won’t code this one togeth­er since it’s a basic login form and we’re redo­ing some of what we’ve already done in the pre­vi­ous video on the reg­is­tra­tion form. 

At the top, you’ll see we have the cond­tion­al to check for a currentUser; if there is one then we redi­rect the user to the dash­board since they don’t need to be logged in. From there they can log out, if needed.

We’re also import­ing the errors macro and doing some error response check­ing and then dis­play­ing the errors.

{% import '_macros/forms' as forms %}
{% set user = user ?? null %}
{{ user ? forms.errorsList(user.getErrors('loginName')) }}

For this form we’re also just doing a stan­dard POST request via the nor­mal brows­er means.

{% if errorMessage is defined %}  
 	<div class="rounded-lg bg-red-50 p-4 mt-4 border-2 border-red-100">  
 		<div class="flex">  
 			<div class="ml-3">  
 				<p class="text-sm font-medium text-red-800">  
 					{{ errorMessage }}  
 				</p>  
 			</div>  
 		</div>  
 	</div>  
{% endif %}

After a suc­cess­ful login, we want to always redi­rect the logged-in user to the dash­board. We can enforce that in a set­ting rather than putting it in code. In the general.php con­fig file, let’s add:

'postLoginRedirect' => '/dashboard',

And now we’re ready to test our new form!