Here is an example of a simple DQL query in a custom repository method meant to return a single array result. The following will return the latest result in case there are multiple contact records that match the “customerId” field, which is actually “customer_id” in the database, but remember that camelCase convention applies to Doctrine mappings of database fields.

// inside entity repository is the getMostRecentContact() method which is called on from any controller that has initialized this repository

function getMostRecentContact($customerId){

   $fields='c.firstName,c.lastName,c.email';

   $dql="SELECT $fields FROM \Main\DefaultBundle\Entity\Contact c 
         WHERE c.customerId=$customerId AND c.status='Active' ORDER by c.createdAt DESC";

   $contactArr=$this->_em->createQuery($dql)->setMaxResults(1) ->getArrayResult();

   return $contactArr;
}
Note: Using Symfony's built-in repository method findBy() is possible here, but with multiple "WHERE" conditions, this approach is usually more flexible.

In your controller, you can access the special global “_locale” variable from the Request object:

$request = $this->get('request');

$locale= $request->getLocale();

 


In Symfony, cookies are stored in the app.request object. Here’s how you access them in Twig:

{% app.request.cookies %}


To see if a cookie is set, use the if statement inside Twig:

{% if app.request.cookies.has('yourCookie') %}
  Cookie 'yourCookie' has been set.  {{ app.request.cookies.get('yourCookie') }} 
{% endif %}

In Symfony, you can alter the public request attribute from the $request object and set or add parameters. Example:

$request->request->set("formField1", "value1");
$request->request->set("formField2", "value2");

You can also add new form fields and values with ->add:

$request->request->add(array("formField1"=>"value1", "formField2"=>"value2"));

In Doctrine, there is no simple way to access the Doctrine object and get the status of the last attempt at inserting or updating the database. To overcome this glaring limitation of the DBAL (Database Abstraction Layer), we have to resort to older PHP techniques like using a try… catch condition.

Seems like a lot of code to do something we old-school PHP devs have been able to do with the mysql object for a decade now, but this is the reality of it.

try {
        $symfonyEntity= new symfonyEntity();
        $symfonyEntity->setTitle('Symfony Entity Title');
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($dataObject);
        $em->flush();

        $this->get('session')->setFlash('flashMsg',"Record inserted");

    } catch (Exception $e) {
        $this->get('session')->setFlash('flashMsg',"Record not inserted");
    }