egeloen/ivory-google-map load only one map - symfony

I am using egeloen/ivory-google-map library to show map for each registered user. But in all user list only one map is showing.
This is my method:
public function findCompaniesAction() {
$em = $this->getDoctrine()->getManager();
$companies = $em->createQueryBuilder()
->select('b')
->from('RFQIronilBundle:User', 'b')
->where('b.acc_type = 1')
->getQuery()
->getResult();
foreach ($companies as $key => $company) {
$map = $this->get('ivory_google_map.map');
$map->setMapOption('mapTypeId', MapTypeId::ROADMAP);
$map->setMapOption('mapTypeId', 'roadmap');
$company->map = $map;
}
return $this->render('RFQIronilBundle:Default:find-companies.html.twig', array(
'companies' => $companies
));
}
and in my view I use:
{% for companies in companies %}
{{ google_map_container(companies.map) }}
{{ google_map_js(companies.map) }}
{% endfor %}
All is fine, but map is showing for only first user. What I have missed?

Try giving each map a unique container id. I use something like this:
$map->setHtmlContainerId('map_canvas_'.md5($address));
where $address is a simple address string.

Related

render a user image and account link in the menu.html.twig

I want to display a user picture (avatar) and some more fields in the menu.html.twig template.
I know that we can display these fields in a user.html.twig template.
{{ content.user_picture }}
{{ user.getDisplayName() }}
{{ content.field_name_user[0] }}
and etc.
But I want to display these fields in the menu.html.twig template.
As I think. we can make a variable in preprocess_block () and print the desired value.
Or if there is no necessary variable in the template - do it in the preprocessor of this template!
Help please make a decision on this issue. And what code you need to write.
It is better to write a pre-process and define a variable and insert the desired elements in it.
hook_preprocess_menu__menu_name(array &$variables) {
$userDetails = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
/**
fetch the desired elements and pass to $variables eg:
**/
$variables['userPictureUrl'] = $userDetails->user_picture->entity->url();
}
You can use hook_preprocess_menu:
function YOURMODULE_preprocess_menu(&$variables)
{
$uid = \Drupal::currentUser()->id();
if($uid > 0)
{
// Load user
$user = User::load($uid);
$userName = $user->getUsername();
// If user have a picture, add it to variable
if(!$user->user_picture->isEmpty()){
$pictureUri = $user->user_picture->entity->getFileUri();
// Add style to picture
$userPicture = [
'#theme' => 'image_style',
'#style_name' => 'profile_picture',
'#uri' => $pictureUri,
];
}
// Set variables
$variables['MYMODULE'] = [
'profile_name' => $userName,
'profile_picture' => $userPicture,
'profile_id' => $userId
];
}
}
End show in your menu.html.twig file:
{{ YOURMODULE.profile_name }}
{{ YOURMODULE.profile_picture }}
{{ YOURMODULE.profile_id }}

Symfony FOSUserBundle Role array

I use This function to get data
public function UserAction()
{
$easyuser = $this->getDoctrine()->getrepository('AppBundle:User')->findall();
foreach($easyuser as $user){
$id = $user->getid();
$username = $user->getUsername();
$email = $user->getEmail();
$roles = $user->getRoles();
}
return $this->render('easycall/user.html.twig', ['easyuser' => $easyuser, 'roles' => $roles]);
}
and in twig i use this code to show data
{% for entity in easyuser %}
<tr>
<td>{{entity.id}}</td>
<td>{{entity.username}}</td>
<td>{{entity.email}}</td>
{% for role in entity.roles %}
<td>{{role}}</td>
{% endfor %}
</tr>
{% endfor %}
The problem is that i get all the roles if the user is ROLE_SUPER_ADMIN, i want to get only the first value from every array.
i tried something like reset() but it did'nt work, any suggestion??
This is also a picture how the results look likes.
1st item from array shoul be somethink like
{{entity.roles | first}}
but it's simply 1st item from array, i'm not sure if it always be more "powerfull role"

Get value from collection field in Twig

I have collection form and need to access the value to show in my view. The problem is seems the key variable declared as Integer and I got error like this :
Impossible to access an attribute ("nama") on a integer variable ("0")
in SifoAdminBundle:DftAbsensi:manage.html.twig at line 65
Here my Twig :
{% for key, absensi in form_edit %}
<li>{{ form_edit.vars.value.statusS.key.nama }}</li>
{% endfor %}
If I change {{ form_edit.vars.value.statusS.key.nama }} into {{ form_edit.vars.value.statusS.1.nama }} its works fine.
Here my controller :
/* Show data */
$emShow = $this->getDoctrine()->getManager();
$collectionAbsensi = new CollectionAbsensi();
foreach ($entityGrupPelajar as $temp) {
$entity = new DftAbsensi();
$entity = $emShow->getRepository('SifoAdminBundle:DftAbsensi')->findOneBy(array('idGrupPelajar' => $temp, 'tanggal' => $tanggal));
if ($entity)
{
$entityPelajar = $emShow->getRepository('SifoAdminBundle:MstPelajar')->find($temp->getIdPelajar());
$dftAbsensi = new DftAbsensi();
$dftAbsensi->setId($entity->getId())
->setIdGrupPelajar($entity->getIdGrupPelajar())
->setTanggal($entity->getTanggal())
->setStatus($entity->getStatus())
->setNis($entityPelajar->getNis())
->setNama($entityPelajar->getNama())
;
$collectionAbsensi->getStatusS()->add($dftAbsensi);
}
}
$emShow->flush();
$formEdit = $this->createForm(new CollectionAbsensiType(), $collectionAbsensi);
$formEdit->add('save', 'submit', array('attr' => array('class' => 'btn btn-info')));
return $this->render('SifoAdminBundle:DftAbsensi:manage.html.twig', array(
'form_edit' => $formEdit->createView(),
));
I have searched for this problem also read the issue #902 but still this problems occurs in my Symfony 2.4 on PHP 5.4
Is there any ways to get that value in iteration without key?
Try changing
form_edit.vars.value.statusS.key.nama
To
form_edit.vars.value.statusS[key].nama
The former is equivalent to $form_edit['vars']['value']['statusS']['key']['nama'] (which does not exist) while the latter is equivalent to $form_edit['vars']['value']['statusS'][$key]['nama']

How to reload part of twig with ajax

I need to reload part of my html.twig:
in controller:
$entity = $em->getRepository('PublishDemandsBundle:Demands')->find($id);
In twig:
{% for n in entity %} {{ n.Id }} {% endfor %}.
i need how to reload $entity with ajax.Can someone help me and thanks.
You can do this with jQuery. I think the best way to do this (I think) is to have a method in your controller that do nothing but a findAll() on your Demands repo :
public function demandsAction()
{
$entity = $em->getRepository('PublishDemandsBundle:Demands')->findAll();
return $this->render('PublishDemandsBundle:Demands:liste.html.twig', array(
'entity' => $entity
));
}
Make sure this Action can be called by a route, let's say /ajax/demands/
Then, in your twig template, just do :
<div id="demands">
{{ render(controller("PublishDemandsBundle:MainController:demands")) }}
</div>
reload
With a bit of jQuery :
$('#reload').click(function() {
$.get("/ajax/demands", function( data ) {
$('#demands').html( data );
});
I haven't tested this yet, and it might be adapted to your case, but again, I would do it this way.

symfony trying to export a csv file from a link

I have this function in the controller, that returns a form with a select box. When the values are selected, I retrieve them with
$manifestations = $form['manifestations']->getData();
then put them in a repository function that queries the database $invites = $repository->searchInviteByManif($manifestations);
public function indexAction() {
$entity = new Invite();
$form = $this->createForm(new ManifSearchType(), $entity);
$request = $this->get('request');
$invites = null;
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
$message = '';
$manifestations = $form['manifestations']->getData();
$repository = $this->getDoctrine()
->getManager()
->getRepository('PrifProtocoleBundle:Invite');
$invites = $repository->searchInviteByManif($manifestations);
$response1 = $this->render('PrifProtocoleBundle:Invite:index.html.twig', array(
'form' => $form->createView(),
'entities' => $invites,
'message' => $message,
));
return $response1;
}
return array(
'form' => $form->createView(),
'entities' => $invites,
);
}
This function then returns a view index.html.twig with a table and all the fields found in the db.
What I want is to export all the queried data $invites in a CSV file, by clicking on a link directly from the HTML table.
So I've put an href="" link in the Twig file,
{% if message is defined %}
<div class="pdf">
<img height="40px" width="40px" src={{ asset('bundles/prifprotocole/images/excel.jpg') }}>
{% for entity in entities %}
<tr class="{{ cycle(['odd', 'even'], loop.index0) }}">
<td>{% if entity.etat == 1 %} Actif {% else %} Inactif {% endif %}</td>
<td>{{ entity.titreGrade }} {{ entity.prenom }} {{ entity.nom }}</td>
<td>{{ entity.fonction }}</td>
This is how I use to export the CSV file without the link :
$response2 = $this->render('PrifProtocoleBundle:Invite:export.csv.twig', array(
'entities' => $invites));
$response2->headers->set('Content-Type', 'text/csv');
$csvfile = $response2->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
return $csvfile;
export.csv.twig file
{% for entity in entities %}
Id {{ entity.id }};
Etat {{ entity.etat }};
Titregrade {{ entity.titreGrade }};
Prenom {{ entity.prenom }};
Nom {{ entity.nom }};
Fonction {{ entity.fonction }};
{% endfor %}
Can someone give me a detailed solution on how to perform this? Much thanks!
You should simply pass the filter criterias, here the $manifestations array as a route parameter, by serializing it first.
Then, you should put a controller like downloadCsvAction() handling this route, querying the $invites from the database, and rendering your export.csv.twig template.
Another option, if you cannot serialize the data in URI, is to create a form with hidden fields containing the data. Then you replace the download link with the submit button of this hidden form.
Guillaume's answer is great if you don't mind fetching your data twice. Once when you display your page, and then when you download the CSV. Another way to do this is to cache the answer. I will give an example using memcache (which is what I use).
First, make sure that memcache is active in your php.ini.
Then before rendering your first page (after fetching the data), cache it:
$key = "csv.$userId";
$memcache = new \Memcache();
$memcache->connect($yourServerHost, $yourServerPort);
$memcache->set($key, json_encode($invites), MEMCACHE_COMPRESSED, 86400); // 24h
The trick is to find a good key, to add your report to the cache, and then be able to retrieve it. It has to be unique. Here, I assume that you have a user that is logged in, and I use the user ID to create a key. If that is not the case, you could create yourself a token, and pass it when rendering the page (along with $invites). This way, you can add the token to the URL to generate the CSV.
Then, in your second action, where you download the CSV, you just fetch the cached data:
$memcache = new \Memcache();
$memcache->connect($yourServerHost, $yourServerPort);
$json = $memcache->get($key);
$invites = json_decode($json , true);
That's it. You should probably create yourself a service for Memcache, so you don't have to create an object, and connect everytime.

Resources