In this article, I will guide you 5 quick tips of Symfony2 what you may be use:
For Symfony 2.0.x
Time configure in seconds
You can access user data in template (twig, php) or controller, service. If user not logged, you will receive NULL value.
In controller
Example, we has variable created & render this variable in Twig
This format, you can follow PHP date.
You can render current date:
- Set session timeout
- Check user login FOS User Bundle
- Get current logged user
- Print variable DateTime object in Twig
- Set invalid message form type
1. Set session timeout
If you want increment or reduce timeout of session in Symfony2, you can configure it in app/config/config.ymlFor Symfony 2.0.x
framework:
session:
lifetime: 3600
For Symfony >= 2.1.0framework:
session:
cookie_lifetime: 3600
Time configure in seconds
2. Check user login FOS USer Bunlde
If you use FOS User Bundle, you can check user login:if ($this->container->get('security.context')->isGranted('ROLE_USER'))
{
//User is logged in
}
if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY'))
{
//authenticated (NON anonymous)
}
3. Get current logged user
When user logged to Symfony system, you can grab profile data of this user.You can access user data in template (twig, php) or controller, service. If user not logged, you will receive NULL value.
In controller
public function getCategory($categoryID){
//short
$user</span> = <span class="hljs-variable">$this->getUser();
//full
$user</span> = <span class="hljs-variable">$this->container->get('security.context')->getToken()->getUser();
}
In template:{% set user = app.user %}
Hi {{ user.username }}
You can check role of user in template:{% if is_granted("ROLE_USER") %}
Hi {{ app.user.username }}
{% endif %}
4. Print variable Date Time object in Twig
In Twig template, you can render a variable type Date Time object with many format.Example, we has variable created & render this variable in Twig
/**
* @var DateTime
*
* @ORMColumn(name="created", type="date")
*/
private $created;
So we can render this use date filter format{{ created|date("Y-m-d H:i:s") }}
This example will output: 2014-05-21 17:16:20
This format, you can follow PHP date.
You can render current date:
{{ "now"|date("m/d/Y") }}
Useful link: Filter Date5. Set invalid message form type
You can set invalid message when build form typepublic function buildForm(FormBuilderInterface $builder</span>, array <span class="hljs-variable">$options) {
$fooTransformer</span> = <span class="hljs-keyword">new</span> FooToStringTransformer(<span class="hljs-variable">$this->em);
$builder->add('title', 'text', array(
'invalid_message' => 'You entered an invalid value - it should include %num% letters',
'invalid_message_parameters' => array('%num%' => 6)
)
);
}
Useful link: Data Transformers