How to pass an array in a redirect - symfony

I'm trying to pass an array in a redirect
$qtedispo = array($x,$c,$s);
return $this->redirect($this->generateUrl('demandeveh_afficherConf',array('qte'=>$qtedispo));
but when i try to call that array in twig
{%for q in qte %}
{{qte[0]}}
{%endfor%}
it tells me that the variable qte is unknown. Any help please?

You are making an HTTP redirection with an array as parameter.
If the route (on which you are making the redirection) is waiting for an argument (e.g. function afficherConf(array $qte)), you have to go into and pass the $qte parameter to the rendered template.
For instance:
// _controller part of to route "demandeveh_afficherConf"
public function afficherConfAction(array $qte)
{
// ...
return $this->render('AppBundle:Demandeveh:afficherConf.html.twig', array('qte' => $qte));
}
Then in the template ("afficherConf.html.twig" for this example), you should be able to do:
{% for q in qte %}
{{ q }}
{% endfor %}
Depending on the number of dimensions of your $qte var.
Note:
You should have a look at the doc.

Related

Get current route in Symfony 3.3 and Twig

I would like to have the current route in Symfony 3 in a Twig view.
I already did some research, but I didn't find any solution. I try the following in my Twig view:
{{ app.request.uri }}
It returns something like: http://localhost:8000/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3DFOSUserBundle%253ASecurity%253Alogin
{{ app.request.get('_route') }}
Always returns NULL.
{{ app.request.getpathinfo }}
Always have: /_fragment
What I need is very simple. For an URL like localhost:8000/article/5, I would like to retrieve /article/5.How to do this?
The following code snippet will do the trick:
{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')) }}
app.request.attributes.get('_route') - returns current route name.
app.request.attributes.get('_route_params') - returns current route params.
path() - generates route path by route name and params.
This approach will not work for forwarded requests. In case of forward request, there is a workaround: you should pass "_route" and "_route_params" to a forwarded params list.
return $this->forward('Yourbundle:Controller:action', array(
//... your parameters...,
'_route' => $this->getRequest()->attributes->get('_route'),
'_route_params' => $this->getRequest()->attributes->get('_route_params');
));
Also you can use app.request to access any Request object functions, such as getPathInfo(), which should return current route path.
{{ app.request.pathInfo }}

How to pass an Twig expression as a parameter to a template, and then execute it with template's context?

I define a template which built select dropdown inputs for my forms:
<p id="{{key | ucfirst}}">
<span>{{label}} : </span>
<select required disabled>
{% for d in data %}
<option value="{{attribute(d, optionValue)}}" {{(attribute(d, optionValue) == selectedValue)?'selected'}}>{{attribute(d, optionIntitule)}}</option>
{% endfor %}
</select>
<span><em>{{initialValue | default("")}}</em></span>
</p>
Then I just need to include it, and passing it some data:
{% include 'selectForm.twig' with {'label': 'Manager'
, 'key': context.manager.id
, 'initialValue': projet.manager.username
, 'data': users
, 'keyValue': 'id'
, 'keyIntitule': 'username'
, 'selectedValue': projet.manager.id) }
%}
It works fine, but I want to do more. For instance I would like to show a value more usefull for end user into option's label: <option>Username (email)</option> instead of <option>Username</option>
So I think I can't use anymore the attribute function.
I thought I could pass an expression to my template like following:
{% include 'selectForm.twig' with {..., 'keyIntitule': "#{d.username (d.email)}"} %}
But the expression is evaluated with immediate context, not template's one. So it doesn't work.
I also tried with template_from_string but I don't suceed in (I never used this function before...)
Is there a way to pass an expression to another template, and make it evaluate the expression with it's own context?
If you want to block the immediate context you can use include function instead of include tag. Then you can disable context this way (example taken from the documentation) :
{# only the foo variable will be accessible #}
{{ include('template.html', {foo: 'bar'}, with_context = false) }}
I found the solution with Twig's template_from_string function:
{% include 'selectForm.twig' with {..., 'keyIntitule': template_from_string("{{d.username}} ({{d.email}})")} %}
And then I use keyIntitule variable as a template:
<option value="{{attribute(d, optionValue)}}">{% include(keyIntitule) %}</option>
Works also with:
<option value="{{attribute(d, optionValue)}}">{{ include(keyIntitule) }}</option>
If you working with objects you could set keyIntitule to uniqueName and in the user entity define new method:
public function getUniqueName()
{
return sprintf('%s (%s)', $this->getUsername(), $this->getEmail());
}
Twig will call corresponding getter method. In this case uniqueName transforms to getUniqueName()

Using doctrine database object in a template

I am new to Symfony and am finally beginning to understand how to query a database using a Doctrine. However, I am lost as far understanding how to use the database object content in a Twig template.
Lets say my database object contains product Id's, names, prices, for 50 different products. After I am done querying the database in the controller, I do the following, to pass the database object into the Twig template:
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
$dataObject; // contains query results
return $this->render('GreatBundle:Default:search.html.twig', array('word' => $word));
}
This is where I am stuck. Now I have a Twig template, I would like to pass the DB object from the controller and then print out the database data in my Twig template.
I appreciate any suggestions as to how I can accomplish this.
Many thanks in advance!
I'll respond with an example (more easier for me to explain)
You want to search something with a slug (the var $word in your example). Let's say you want to find a article with that.
So your controller :
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
// Search the list of articles with the slug "$word" in your model
$articleRepository = $this->getDoctrine()->getRepositoy('GreatBundle:Article');
$dataObject = $articleRepository->findBySlug($word);
// So the result is in $dataObject and to print the result in your twig, your pass the var in your template
return $this->render('GreatBundle:Default:search.html.twig', array('result' => $dataObject));
}
The twig template 'GreatBundle:Default:search.html.twig'
{% for item in result %}
{{ item.title }} : {{ item.content }}
{% endfor %}
Just look the second example in the Symfony2 Book (Sf2 Book - templating), you have to use the function "for" to parse your object (like an array in php !)
Example in your twig template :
{% for item in word %}
{{ item.id }} - {{ item.name }} - {{ item.description }}{# etc... #}<br>
{% else %}
<h2>Aoutch ! No data !</h2>
{% endfor %}
Ah, and it's not the good var in your render method (but it's was for your example !)
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
$dataObject; // contains query results
return $this->render('GreatBundle:Default:search.html.twig', array('word' => $dataObject));
}

How to get the current page name in Silex

I'm wondering how to get the current page name, basically 'just' the last parameter in the route (i.e. /news or /about). I'm doing this because I want to be able to have the current page in the navigation highlighted.
Ideally, I'd like to store the current page name in a global variable so that in Twig I can just compare the current page name against the link and add a class accordingly.
I can't figure out how to add the current page name to a global variable though. I've tried using something like this:
$app['twig']->addGlobal('current_page_name', $app['request']->getRequestUri());
at the top of my app.php file, but an 'outside of request scope' error. But I wouldn't like to have to include this in every route.
What's the best way to do this?
If you put it into an app-level before middleware like this, that'll work:
$app->before(function (Request $request) use ($app) {
$app['twig']->addGlobal('current_page_name', $request->getRequestUri());
});
The "page name" part of your question is unclear, are you looking for the current route's name? You can access that via $request->get("_route") even in the before middleware, as it gets called when routing is already done.
You could also generate navigation list directly in stand alone nav twig template. And then import it in to the main template. Then you would only have to get silex to pass to the view the current page identifier. Simplest way... for example from Silex you would have to pass in the "path" variable to your view. Probably it would more convenient to to fetch nav_list from database and pass it in to twig template as global array variable instead. However this example is the simplest you could get to do what you intend.
nav.twig
{% set nav_list = [
["./", "home"],
["./contact", "contact"],
["./about", "about us"]
{# ... #}
] %}
{% set link_active = path|default("") %}
{% for link in nav_list %}
<li><a href="{{ link[0] }}" class="{% if link[0] == link_active %} activeClass {% endif %}" >{{ link[1] }}</a></li>
{% endfor %}
app.php
//...
$app->match('/about', function (Request $request) use ($app) {
return $app['twig']->render('about.twig', array(
'path' => './'.end(explode('/', $request->getRequestUri()))
));
});
//...

How to apply a filter whose name is stored in a variable

Basically, I am looking for the filter equivalent of the attribute() function for objects and arrays. I want to be able to apply a filter, whose name is stored in a variable.
{#
This works and is really useful
prints object.someVar
#}
{% set varName = 'someVar' %}
{{ attribute(object,varName) }}
{#
The function "filter" does not exist
#}
{% set filterName = 'somefilter' %}
{{ filter(object,filterName) }}
To reach this goal you have to extend your TwigFilter.
How to initially write you Extension you can read here.
Assuming that you have created you extension, you have define your function, let's say applyFilter.
//YourTwigFilterExtension.php
public function getFunctions()
{
return array(
...
'apply_filter' => new \Twig_Function_Method($this, 'applyFilter'),
);
}
Then, you have to define this function
public function applyFilter($context, $filterName)
{
// handle parameters here, by calling the
// appropriate filter and pass $context there
}
After this manipulations you'll be able to call in Twig:
{{ apply_filter(object, 'filterName') }}
Cheers ;)

Resources