如何检查用户是否已登录 Symfony? [英] How can I check if a user is logged in in Symfony?
问题描述
我收到了这张表格:
{{ form_start(form) }}
<input type="submit" class="form_submit_button" name="register_interest" value="Add to favourites"/>
{{ form_end(form) }}
我想检查用户是否登录,我这样做了:
I want to check if user is logged in and I did this :
{% if is_granted('IS_AUTHENTICATED_FULLY') %}
如果用户未登录,它会隐藏按钮.
And it hides the button if the user is not logged in.
即使我没有登录,我也希望该按钮显示,并在提交表单后检查用户是否登录.
I want that button to show even if I am not logged in and after the form submit to check if the user is logged in .
我该怎么做?
谢谢!
推荐答案
必须在您的 php 控制器中执行检查.此外,您还可以执行 javascript 检查,以防止在用户未登录时提交表单.
The check must be performed in your php controller. Additionally, you can also perform a javascript check which prevents submitting the form if user is not logged in.
要检查控制器中的用户登录:
To check for user login in your controller:
if ($this->isGranted('ROLE_USER') == false) {
// show some error message, throw exception etc...
}
另一种方法:
$this->denyAccessUnlessGranted('ROLE_USER');
要检查客户端 (javascript),您可以执行以下操作:
To check on the client side (javascript), you could do something like this:
{% if not is_granted('IS_AUTHENTICATED_REMEMBERED') %}
<script>
// wrap into document.ready() if needed
$('#your_submit_button_id').on('click', function(e) {
e.preventDefault();
alert('You must be logged in to use this function');
});
</script>
{% endif %}
这篇关于如何检查用户是否已登录 Symfony?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!