Symfony - Form with multiple entity objects - symfony

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)
);

Related

symfony Admin lte Bundle personalize datetype form

I'm using the kevinPast adminLte bundle on symfony 5. Every datetype got their own format(dd-MM-YYYY) and you can't update it as a normal way by writing 'format' => 'yyyy-MM-dd' inside the form for example. The problem occurs also for other datetype, like birthday.
I also try to use my own datepicker function to override the existing one, but it's a bundle, so it first not work, then it broke also the existing js.
You can see the different try i did:
->add('startTime', DateTimeType::class, [
'required' => true,
'error_bubbling' => false,
'date_widget' => 'single_text',
// #todo Can we make this format configurable?
'date_format' => 'yyyy-MM-dd', // must match data-date-format as defined in field.html.twig
'minutes' => range(0, 55, 5)
])
it will show the data like that
it use the block date_widget on twig, the single_text area
{% block date_widget %}
{% if widget == 'single_text' %}
<div class="input-group">
<div class="input-group-addon">
<i class="far fa-calendar-alt"></i>
</div>
{% if type is not defined or type != 'date' %}
{% if attr.class is defined %}
{% set class = attr.class ~ ' timepicker' %}
{% else %}
{% set class = ' timepicker' %}
{% endif %}
{% set attr = attr|merge({'class' : class, 'data-datepickerenable':'on'}) %}
{% endif %}
{{ block('form_widget_simple') }}
</div>
{% else %}
{% set date_pattern = '<div class="row">' ~ date_pattern ~ '</div>'|raw %}
{{ date_pattern|replace({
'{{ year }}' : '<div class="col-xs-4">{{ year }}</div>',
'{{ month }}' : '<div class="col-xs-4">{{ month }}</div>',
'{{ day }}' : '<div class="col-xs-4">{{ day }}</div>',
})|raw|replace({
'{{ year }}': form_widget(form.year),
'{{ month }}': form_widget(form.month),
'{{ day }}': form_widget(form.day),
})|raw }}
{% endif %}
{% endblock %}
I also try to override it by using the following code:
Js part:
$(document).ready(function() {
$('.datepicker').datepicker({
format: "DD/MM/YYYY h:mm"
});
});
form part
->add('startTime', DateTimeType::class, [
'required' => true,
'error_bubbling' => false,
'date_widget' => 'single_text',
//<input type="text" class="form-control" data-inputmask-alias="datetime" data-inputmask-inputformat="dd/mm/yyyy" data-mask="" im-insert="false">
// #todo Can we make this format configurable?
'date_format' => 'yyyy-MM-dd', // must match data-date-format as defined in field.html.twig
'minutes' => range(0, 55, 5),
'attr' => ['class' => 'datepicker'],
])
This one overide the actual datepicker, but first doesn't fix the problem(you still have the standard format DD-MM-YYY) then it also broke the js used by the bundle(some navigation button doesn't work etc)
If I found a fix, i will also write the answer here.
So after few work on it and if someone got the same problem, I found one solution, maybe not the best but it's work.
I checked the demo used with adminLte bundle on symfony (Kimai2)
So to be able to edit your calendar and format your date, you need to follow these step:
1 : create a dateTimePickerType and use it instead of default DatetimeType
<?php
namespace App\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
class DateTimePickerType extends AbstractType
{
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['attr'] = array_merge($view->vars['attr'], [
'data-datetimepicker' => 'on',
'autocomplete' => 'off',
'placeholder' => strtoupper($options['format']),
'data-format' => $options['format_picker'],
'data-time-picker-increment' => $options['time_increment'],
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'label' => '',
'widget' => 'single_text',
'html5' => false,
'format' => 'YYYY-MM-DD',
'format_picker' => 'YYYY-MM-DD',
'with_seconds' => false,
'time_increment' => 1,
]);
}
/**
* {#inheritdoc}
*/
public function getParent()
{
return DateTimeType::class;
}
}
and on the formType
->add('startTime', DateTimePickerType::class, [
'required' => true,
'error_bubbling' => false,
'label' => 'startTime',
'format' => "yyyy-MM-dd'T'HH:mm:ss",
'attr' => ['class' => 'js-datepicker-hours'],
])
Then the javascript part, you need to install daterangerpicker from www.daterangepicker.com
and use these following function:
const $ = require('jquery');
global.$ = global.jQuery = $;
const Moment = require('moment');
global.moment = Moment;
require('moment/locale/en-gb');
require('daterangepicker');
$(document).ready(function() {
$('.js-datepicker').daterangepicker({
language: "en",
singleDatePicker: true,
showDropdowns: true,
minYear: 1901,
//maxYear: parseInt(moment().format('YYYY'),10)
});
$('.js-datepicker-hours').daterangepicker({
language: "en",
timePicker: true,
singleDatePicker: true,
showDropdowns: true,
locale: {
format: 'yyyy-MM-DD HH:mm:ss'
}
//maxYear: parseInt(moment().format('YYYY'),10)
});

Getting the string of the chosen option in a drop down that comes from an entity repository

I am trying to pull in a repository into a form in Symfony 3.4 and then use the chosen option when the form is submitted.
Here's the form code:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('text', TextareaType::class, [
'label' => 'Text'
])
->add('category', EntityType::class, [
'class' => Category::class,
'choice_label' => 'name',
'query_builder' => function(CategoryRepository $repo) {
return $repo->createQueryBuilder('c')
->groupBy('c.name');
}
])
->add('subcategory', EntityType::class, [
'class' => Category::class,
'choice_label' => 'subcategory',
'query_builder' => function(CategoryRepository $repo) {
return $repo->createQueryBuilder('c')
->groupBy('c.subcategory');
}
]);
}
With this I can render the form and it looks good. I can choose the various options in the CategoryRepository.
{% block body %}
{{ form_start(form) }}
{{ form_label(form.name) }}
{{ form_errors(form.name) }}
{{ form_widget(form.name) }}
{{ form_label(form.subcategory) }}
{{ form_errors(form.subcategory) }}
{{ form_widget(form.subcategory) }}
{{ form_end(form) }}
On submit, when checking with Xdebug, the category is the object Category. I can see the correct values present (those chosen in the drop down of the form) but I want just the string, e.g. category.name. How do I do that?
Also, it might need a different question, but when I select one of the categories, I'd like the subcategory to be updated to exclude those that don't belong to that chosen category. I realise this may require jquery.
I'm certain there are better ways, but one solution would be to
$category = $data->getCategory();
$data->setCategory($category->getName());
$data->setSubcategory($category->getSubcategory());
And to exclude the subcategories I use jQuery / JavaScript to retrieve the filtered results from a controller / repository, then remove or add those options in the HTML.

Symfony 2.8 Form EntityType Returns Single Value

Just trying to get a select field populated from a database table. This is just a simple table with a primary key column and another column named type.
Just for testing, the example table consists of:
id type
1 Sample 1
2 Sample 2
3 Sample 3
When I create a form:
$builder
->add('account_type', EntityType::class, array(
'class' => 'AppBundle:AppAccountTypes',
'choice_label' => 'type'
));
My select dropdown simply repeats the first entry 3 times.
<select id="add_account_form_account_type" name="add_account_form[account_type]" class="form-control">
<option value="1">Sample 1</option>
<option value="1">Sample 1</option>
<option value="1">Sample 1</option>
</select>
For testing sake, the controller is just using:
$account = new Account();
$form = $this->createForm(new AddAccountForm(), $account);
return $this->render('account/new.html.twig', array(
'page_title' => 'Create Account',
'form' => $form->createView()
));
Twig template:
{% extends 'base.html.twig' %}
{% block body %}
<h1>{{ page_title }}</h1>
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
{% endblock %}
What am I missing here?
May be you need to use below code:
$builder
->add('account_type', EntityType::class, array(
'class' => 'AppBundle:AppAccountTypes(Your Entity Class)',
'mapped' => false,
'choice_label' => 'type'
));
Because as i see in your code there is no field which name is account_type, May be this is the problem.
Change your controller as below:
$form = $this->createForm(AddAccountForm::class (Your form class), $account);

Drupal 8 module - How to use a template to display a form element?

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

How to pass another entity info into form in Symfony2?

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

Resources