Thursday, March 5, 2015

Symfony 2 hari 22: Aksi logout di Symfony 2

Artikel ini dirunut berdasarkan Jobeet Tutorial, yang dibuat oleh Fabien Potencier, untuk Symfony 1.4.

Logout Symfony 2 

Ketika user sudah selesai melakukan aktivitasnya maka ia harus logout agar akunnya tidak disalah gunakan. Untuk melakukan proses logout tersebut edit file config/security.yml dan tambahkan kode berikut:

app/config/security.yml

security:
    firewalls:
        # ...
        secured_area:
            # ...
            logout:
                path:   /logout
                target: /
    # ...


====================================== 

Selanjutnya kita harus menambahkan url /logout di routing aplikasi kita. Untuk itu edit file routing dan tambahkan kode berikut:

src/Ibw/JobeetBundle/Resources/config/routing.yml

# ...

logout:
    pattern:   /logout

# ...


============================================

Agar user dapat mengakses url /logout mari kita tambahkan link logout di halaman admin, untuk melakukan hal ini kita harus melakukan override Sonata admin bundle dengan menambahkan file user_block.html.twig di dalam folder app/Resources/SonataAdminBundle/views/Core.


app/Resources/SonataAdminBundle/views/Core/user_block.html.twig

{% block user_block %}<a href="{{ path('logout') }}">Logout</a>{% endblock%}
===============================================
Sekarang jika kamu mengakses halaman admin maka kamu akan menemukan link logout di bagian atas halaman.

User session Symfony 2

Symfony 2 mempunyai object yang dapat digunakan untuk menyimpan sesi user ketika mereka sudah login ke dalam aplikasi. Kamu dapat menyimpan session dengan mudah di mana di dalam controller mu dengan menggunakan kode berikut.

Cotroller mu di Symfony 2
 
$session = $this->getRequest()->getSession();
 
// store an attribute for reuse during a later user request
$session->set('foo', 'bar');

// in another controller for another request
$foo = $session->get('foo');

=================================

Ok kita bisa menggunakan fitur ini untuk membuat histori kunjungan user, untuk melakukan hal tersebut tambahkan kode berikut ini di JobController.php 

src/Ibw/JobeetBundle/Controller/JobController.php

// ...

public function showAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('IbwJobeetBundle:Job')->getActiveJob($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Job entity.');
    }

    $session = $this->getRequest()->getSession();

    // fetch jobs already stored in the job history
    $jobs = $session->get('job_history', array());

    // store the job as an array so we can put it in the session and avoid entity serialize errors
    $job = array('id' => $entity->getId(), 'position' =>$entity->getPosition(), 'company' => $entity->getCompany(), 'companyslug' => $entity->getCompanySlug(), 'locationslug' => $entity->getLocationSlug(), 'positionslug' => $entity->getPositionSlug());

    if (!in_array($job, $jobs)) {
        // add the current job at the beginning of the array
        array_unshift($jobs, $job);

        // store the new job history back into the session
        $session->set('job_history', array_slice($jobs, 0, 3));
    }

    $deleteForm = $this->createDeleteForm($id);

    return $this->render('IbwJobeetBundle:Job:show.html.twig', array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
    ));
}


===============================================

Dan tambahkan kode berikut di layoutnya sebelum #content div:

src/Ibw/JobeetBundle/Resources/views/layout.html.twig

<!-- ... -->
 
<div id="job_history">
    Recent viewed jobs:
    <ul>
        {% for job in app.session.get('job_history') %}
            <li>
                <a href="{{ path('ibw_job_show', { 'id': job.id, 'company': job.companyslug, 'location': job.locationslug, 'position': job.positionslug }) }}">{{ job.position }} - {{ job.company }}</a>
            </li>
        {% endfor %}
    </ul>
</div>
 
<div id="content">
 
<!-- ... -->
 

Flash message Symfony 2

Flash message merupakan pesan kecil yang memberikan informasi singkat yang dapat membantu pengguna untuk mengtahui proses jalannya aplikasi yang terjadi. Kita akan membuat flash message untuk proses publish, untuk itu tambahkan kode berikut di JobController.php 

src/Ibw/JobeetBundle/Controller/JobController.php


// ...

public function publishAction($token)
{
    // ...

    $this->get('session')->getFlashBag()->add('notice', 'Your job is now online for 30 days.');

    // ...
}
 

=============================================

Kemudian tambahkan kode berikut di file template untuk menampilkan pesannya. 

src/Ibw/JobeetBundle/Resources/views/layout.html.twig

 
<!-- ... -->
 
{% for flashMessage in app.session.flashbag.get('notice') %}
    <div>
        {{ flassMessage }}
    </div>
{% endfor %}
 
<!-- ... -->
     
 






No comments:

Post a Comment