I have two joined tables. With print_r I am getting something like this
Array
(
[0] => GameShelf\UsersBundle\Entity\Ownership Object
(
[id:GameShelf\UsersBundle\Entity\Ownership:private] => 1
[type:GameShelf\UsersBundle\Entity\Ownership:private] => 1
[time:GameShelf\UsersBundle\Entity\Ownership:private] => 2010-02-05 11:00:00
[game:GameShelf\UsersBundle\Entity\Ownership:private] => Doctrine\ORM\PersistentCollection Object
(
[snapshot:Doctrine\ORM\PersistentCollection:private] => Array
(
[0] => GameShelf\GamesBundle\Entity\Game Object
(
[id:GameShelf\GamesBundle\Entity\Game:private] => 1
[parent_id:GameShelf\GamesBundle\Entity\Game:private] => 0
[name:GameShelf\GamesBundle\Entity\Game:private] => Somebody
[slug:GameShelf\GamesBundle\Entity\Game:private] => somebody
[reldate:GameShelf\GamesBundle\Entity\Game:private] => 2010-10-10
[genres:GameShelf\GamesBundle\Entity\Game:private] => 1,2
[platforms:GameShelf\GamesBundle\Entity\Game:private] => 1,2
[developers:GameShelf\GamesBundle\Entity\Game:private] => 1,2
[description:GameShelf\GamesBundle\Entity\Game:private] => Lipsum
[desc_src:GameShelf\GamesBundle\Entity\Game:private] => http://onet.pl
[rate:GameShelf\GamesBundle\Entity\Game:private] => 0
[ownership:GameShelf\GamesBundle\Entity\Game:private] => GameShelf\UsersBundle\Entity\Ownership Object
*RECURSION*
)
)
What I want, is to print name:GameShelf\GamesBundle\Entity\Game:private] => Somebody, but I don't know how. I use Twig, my current template is:
{% for game in games %}
{{ game.id }}
{% endfor %}
But it outputs only id from Ownership table.
My controller:
public function getOwnedAction($type = 1, $user = 1) {
$games = $this->getDoctrine()
->getRepository('GameShelfUsersBundle:Ownership')
->getOwned();
echo '<pre>';
//print_r($games);
echo '</pre>';
return $this->render('GameShelfUsersBundle:Default:index.html.twig',
array(
'games' => $games->getGame()
));
}
Repo:
public function getOwned($type = 1, $user = 1) {
$query = $this->getEntityManager()
->createQuery('
SELECT o, g FROM GameShelfUsersBundle:Ownership o
JOIN o.game g
WHERE o.type = :type
')
->setParameter('type',$type);
try {
return $query->getResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
It works only when I set getSingleResult instead of getResult.
In Twig you use the same methods to access Entity information.
[edit] After looking at the recursion, you might need to do it this way:
{% for owners in games %}
{% for game in owners.getGame() %}
{{ game.getId() }}
{{ game.getName() }}
{{ game.getParentId() }}
{# etc... #}
{% endfor %}
{% endfor %}
Related
I'm running Symfony 3.4 LTS and I have an entity Attribute:
<?php
class Attribute
{
private $id;
private $code;
private $value;
private $active;
// My getters and setters
Below the database table:
I would like to get, in a form, all the rows with code == 'productstatus'. I tried:
<?php
$attributes = $this->getDoctrine()->getRepository(Attribute::class)->findBy(['code' => 'productstatus']);
// $attributes contains array with 3 objects 'Attribute'
$form = $this->createFormBuilder($attributes);
$form->add('value', TextType::class);
$output = $form->getForm()->createView();
If I dump() the $output var in Twig:
... I'm unable to make a loop to display the 3 fields with values.
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
Result :
My goal is to allow the user to edit all the values of a specific attributes in the same form (or multiple forms, but in the same page). I already tried with CollectionType without success.
I found a solution: create 2 nested forms and use CollectionType. Hope it helps.
<?php
// Controller
$attributes = $this->getDoctrine()->getRepository(Attribute::class)->findBy(['code' => 'productstatus']);
$form = $this->createForm(AttributeForm::class, ['attributes' => $attributes]);
// AttributeForm
$builder
->add('attributes', CollectionType::class, [
'entry_type' => AttributeValueForm::class,
'allow_add' => true,
'by_reference' => false,
'allow_delete' => true,
]);
// AttributeValueForm
$builder
->add('value', TextType::class, ['label' => false, 'required' => false])
->add('active', CheckboxType::class, ['label' => false, 'required' => false])
// Twig view
{{ form_start(form) }}
{% for attribute in form.attributes.children %}
<tr>
<td>{{ form_widget(attribute.value) }}</td>
<td>{{ form_widget(attribute.active) }}</td>
</tr>
{% endfor %}
{{ form_end(form) }}
You an use an if statement in the your AttributeType like in the example below:
$builder
->add('entree', EntityType::class, array('class'=>'cantineBundle:plat',
'choice_label'=>function($plat){
if($plat->getType()=='Entree'&&$plat->getStatus()=="non reserve"){
return $plat->getNomPlat();
}
},
'multiple'=>false)
);
I have route that is using cUrl.
The cUrl returns Json data.
So, I did $data = json_decode($results);
It returns:
(
.....
[dovecot] => stdClass Object
(
[info_str] => Running
[name] => Dovecot
[version] => 2.3.4
)
[exim] => stdClass Object
(
[info_str] => Running
[name] => Exim
[version] => 4.91
)
.......
}
So when I do return $data; on my route to twig and do:
{% for info in data %}
{{ info }}
{% endfor %}
It doesn't show anything.
My point point is to print only the [name], so I also tried:
{% for info in data %}
{{ info.name }}
{% endfor %}
And it's not working.
I'm currently creating a Drupal 8 module. I would like to be able to use a custom template to display a select element in a form. Here is the code I have written so far:
File my_module/templates/colorselector.html.twig:
{% spaceless %}
<div class="select-wrapper">
{% set classes = ['form-control', 'color-selector'] %}
<select{{ attributes.addClass(classes) }}>
{% for option in options %}
<option value="{{ option.value }}" data-color="{{ option.code }}"{{ option.selected ? ' selected="selected"' }}>{{ option.label }}</option>
{% endfor %}
</select>
</div>
<script>
$('.color-selector').colorselector();
</script>
{% endspaceless %}
File my_module/my_module.module:
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\RenderElement;
function my_module_theme($existing, $type, $theme, $path) {
return [
// ...
'colorselector' => [
'render element' => 'select'
]
];
}
function my_module_preprocess_colorselector(&$variables) {
$element = $variables['element'];
Element::setAttributes($element, ['id', 'name', 'size']);
RenderElement::setAttributes($element, ['form-select']);
$variables['attributes'] = $element['#attributes'];
$variables['options'] = [];
foreach ($element['#options'] as $colorName => $colorCode) {
$option = [];
$option['value'] = $colorName;
$option['label'] = $colorName;
$option['code'] = $colorCode;
$variables['options'][] = $option;
}
}
File my_module/src/Form/MyCustomForm.php:
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class MyCustomForm extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
// ...
$form['color'] = [
'#type' => 'select',
'#theme' => 'colorselector',
'#title' => $this->t('Couleur'),
'#required' => TRUE,
'#options' => $options
];
// ...
return $form;
}
// ...
}
I get the following error message when I try to display the form: The website encountered an unexpected error. Please try again later.
If I remove '#theme' => 'colorselector' from $form['color'], it displays the form correctly but it does not use my template obviously.
Do you know where the error comes from and how to fix it?
Thanks!
Your hook_theme function should be like this.
function my_module_theme($existing, $type, $theme, $path) {
return array(
'color_selector' => array(
'variables' => array('params' => null),
'template' => 'colorselector'
)
);
}
Now, your template name might be my_module/templates/colorselector.html.twig
[Entity file][1]
Controller
thx for your help
In Controller
$images = array();
$em = $this->getDoctrine->getManager();
$probleme = $em->getRepository('PiCrowdRiseWebBundle:Probleme')->findAll();
foreach ($probleme as $key => $entity) {
$images[$key] = base64_encode(stream_get_contents($entity->getFoto()));
}
// ...
return $this->render('PiCrowdRiseWebBundle:Probleme:problemList.html.twig', array(
'problemes' => $probleme,
'images' => $images,
));
View:
{% for key, entity in problemes %}
{# ... #}
<img alt="Embedded Image" src="data:image/png;base64,{{ images[key] }}" />
{# ... #}
{% endfor %}
What is best practice to include another info in form from another entity?
I have Student Entity, Group Entity, StudentsGroup and Attendance Entity.
Student have id, code, and name.
Group have id and name.
StudentsGroup have id, group_id, and student_id.
Attendance have id, students_group_id, date and status.
Group can have many Student which saved in StudentsGroup. Why I make StudentsGroup? Because actually 1 Group can have some sub groups like SubjectsGroup etc. And Attendance save student information by StudentsGroup Id which same student can have different students_group_id.
Now, the problem is : How to show Student information in collection form of attendance?
All Entity relationship is declared as object, so actually we can access em freely from any entity. But I don't know how to do that in form. Here my form :
<?php
/* Collection Form */
$tanggal = new \DateTime($request->request->get('sifo_adminbundle_studentsgrouping')['tanggal']);
$attendances = new StudentsGrouping();
foreach ($entities as $temp) {
$entity = new Attendance();
$entity = $em->getRepository('SifoAdminBundle:Attendance')->findOneBy(array('studentsGrouping' => $temp, 'date' => $tanggal));
if ($entity){
$attendances->getAttendances()->add($entity);
}
}
$form = $this->createCollectionForm($attendances, $id, $tanggal);
return $this->render('SifoAdminBundle:DftAbsensi:manage.html.twig', array(
'form' => $form->createView(),
));
This is how I render it in twig :
{{ form_start(form_collection) }}
{{ form_row(form_collection.tanggal) }}
{% for attendance in form_collection.attendances %}
{{ form_row(attendance.status) }}
{% endfor %}
{{ form_end(form_collection) }}
## Concept ##
I'm thinking about creating entity and pass it into form like this :
foreach ($entities as $temp) {
$entity = new Student();
$entity = $em->getRepository('SifoAdminBundle:Student')->find($temp->getId());
if ($entity){
$entities[i] = $entity;
}
$i++
}
and then in twig show it like this :
{{ form_start(form_collection) }}
{{ form_row(form_collection.tanggal) }}
{% for key, attendance in form_collection.attendances %}
{{ entities[key].code }}
{{ entities[key].name }}
{{ form_row(attendance.status) }}
{% endfor %}
{{ form_end(form_collection) }}
But I feel not comfort with this. Am I really need to make new entity just for showing name and code from Student Entity? Is there a best practice to do this?
You can use entity field.
$builder->add('users', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'multiple' => true, /* you can choose more than one */
'mapped' => false, /* if you are using the form with an entity */
'query_builder' => function(EntityRepository $er) {
/* use query builder to get correct results */
return $er->createQueryBuilder('u')->orderBy('u.username', 'ASC');
},
));
There are two important keys in above.
'multiple' => true ----- you can able to choose more than one
'mapped' => false ----- if you are using form with an entity, your form will automatically looks for a connection between these entities and if can not found, throws exception. to avoid of that problem you should set this option to false
http://symfony.com/doc/current/reference/forms/types/entity.html