Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all 3917 articles
Browse latest View live

Symfony 4 / Doctrine: Dynamic table name on entity => function with find () OK but createQueryBuilder () NOK

$
0
0

I have a database composed (among others) of tables of statistics dynamically named by period:
     MY_TABLE_2019_01
     MY_TABLE_2019_02
     ...
     MY_TABLE_2019_10

The idea is to create a single entity and manage it dynamically.

I manage to handle the call to the entity dynamically by setting the name of the table. When using the find() method, I do not have problems, the name change is done correctly and I can make several changes in the controller without encountering an error, however, since a call to a createQueryBuilder(), only the initial configuration is taken into account and the change of the name of the table is not taken into account after, yet there is a clear() performed ?

Question: Why with a find() the change is functional but not with the createQueryBuilder() ?

My Code

My entity, classic but no table name

    namespace App\Entity;

    use Doctrine\ORM\Mapping as ORM;

    /**
    * @ORM\Table()
    * @ORM\Entity(repositoryClass="App\Repository\MyTableRepository") 
    */
    class MyTable {
        /**
        * @ORM\Id()
        * @ORM\GeneratedValue()
        * @ORM\Column(name="ID", type="integer")
        */
        private $id;

CASE N ° 1, it works! :)

In my controller :

        $oEntityManager = $this->getDoctrine()->getManager();
        $metadata = $oEntityManager->getClassMetadata(MyTable::class);
        $metadata->setPrimaryTable(array('name' => 'MY_TABLE_2019_02')); //-- Dynamically manage the table
        echo $metadata->getTableName(); //-- 'MY_TABLE_2019_02'
        //--
        $oMyTable = $oEntityManager->getRepository(MyTable::class);
        //--
        $aRetour = $oMyTable->find(1); //-- SELECT ... FROM MY_TABLE_2019_02... OK
        $oMyTable->clear();
        //--
        $metadata->setPrimaryTable(array('name' => 'MY_TABLE_2019_06')); //-- Dynamically manage the table
        echo $metadata->getTableName(); //-- 'MY_TABLE_2019_06' OK
        $aRetour = $oMyTable->find(1); //-- SELECT ... FROM MY_TABLE_2019_06... OK ! IS GOOD :)

CASE N ° 2, it doesn't work! :(

In my repository :

        public function myFunction(): array {

            $oRequete = $this->createQueryBuilder('c')->setMaxResults(10);

            return $oRequete->getQuery()
                            ->getResult();
        }

In my controller :

        $oEntityManager = $this->getDoctrine()->getManager();
        $metadata = $oEntityManager->getClassMetadata(MyTable::class);
        $metadata->setPrimaryTable(array('name' => 'MY_TABLE_2019_02')); //-- Dynamically manage the table
        echo $metadata->getTableName(); //-- 'MY_TABLE_2019_02' OK
        //--
        $oMyTable = $oEntityManager->getRepository(MyTable::class);
        //--
        $aRetour = $oMyTable->myFunction(); //-- SELECT ... FROM MY_TABLE_2019_02... OK
        $oMyTable->clear();
        //--
        $metadata->setPrimaryTable(array('name' => 'MY_TABLE_2019_06')); //-- Dynamically manage the table
        echo $metadata->getTableName(); //-- 'MY_TABLE_2019_06' OK !!!!
        $aRetour = $oMyTable->myFunction(); //-- SELECT ... FROM MY_TABLE_2019_02... NOK !!!!!!!!! table name not change here !?

In this case 2, when I make $metadata->getTableName() I have a valid return, here 'MY_TABLE_2019_06', but when I call $oMyTable->myFunction(), the request generated via the createQueryBuilder() does not does not change ?

Do you have a solution or a research track to give me?


symfony 4.3 and Dropzone rename and show/delete existing files

$
0
0

I'm trying to implement an image upload for my application. My issues: - I tried all I could find online, but I am not able to rename the file before uploading. The file name on the server is always a hash or so. - I think that the thumbnail creation is not working, because I have to add a css to have the image in 120px width. - When removing one file it is not deleted.

Can anyone please explain how to realise that?

here my sources:

the template:
edit.html.twig

{% extends 'layout.html.twig' %}

{% block stylesheets %}
    {{ parent() }}
    <link rel="stylesheet" href="{{ asset('includes/dropzone/min/basic.min.css') }}"/>
{% endblock %}

{% block tron %}
<h2>{{component}} edit - {{ entity.monitorId|default(entity.id) }}</h2>
{% endblock %}

{% block body %}

<div class="row">
    <div class="col-sm-8">
        {{ form_start(form, {'attr': {'id': 'infomonitore_form' } }) }}

        {{ form_errors(form) }}

        {{ form_row(form.detail) }}
        {{ form_row(form.notizen) }}
        <div class="form-group row">
            <label class="col-form-label col-sm-2">
                Files to add:
            </label>
            <div class="col-sm-10">
                <div action="{{ oneup_uploader_endpoint('gallery', {id: entity.id}) }}" class="dropzone js-reference-dropzone" style="min-height: 100px">
                </div>
            </div>
        </div>

        <button type="submit" id="buttonSubmit" class="btn btn-primary">Update</button>
        <a href="{{ path('infomonitore_show_ID', {'id': entity.id }) }}" class="btn btn-dark">Show</a>

        {{ form_end(form) }}

    </div>
    <div class="col-sm-4">
    </div>
</div>

{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script type="text/javascript" src="{{ asset('js/jquery-3.4.1.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('includes/dropzone/dropzone.js') }}"></script>
    <script>

        Dropzone.autoDiscover = false;

        $(document).ready(function () {

            var dropzone = new Dropzone('.js-reference-dropzone', {
                autoProcessQueue: false,
                dictMaxFilesExceeded: 'Only 5 Image can be uploaded',
                acceptedFiles: 'image/*',
                maxFilesize: 10,  // in Mb
                addRemoveLinks: true,
                maxFiles: 5,
                resizeWidth: 1920,
                paramName: 'file',
                renameFile: function (file) {
                    let newName = $('#InfomonitoreFormType_monitorId').val() + '-' + new Date().getTime() + '.' + file.name.split('.').pop();
                    file.name = newName;
                    return file.renameFilename = newName;
                },
                params: {
                    infomonitor: $('#InfomonitoreFormType_monitorId').val()
                },
                init: function () {
                    console.log(this.files);
                    {% for image in entity.images %}
                        var mockFile = {name: "{{ image.imageFile }}", size: 12345, dataURL: "{{ asset('locations/')~image.imageFile }}",accepted: true};
                        this.files.push(mockFile);
                        this.emit("addedfile", mockFile);
                        //this.createThumbnailFromUrl(mockFile, mockFile.dataURL);
                        this.emit("thumbnail", mockFile, mockFile.dataURL)
                        this.emit("complete", mockFile);
                    {% endfor %}
                    this.on("success", function (file, response) {
                        console.log("Success wurde aufgerufen");
                        //e.preventDefault();
                        $('#infomonitore_form').submit();
                    });
                    this.on("error", function (tmp) {
                        console.log('error');
                        console.log(tmp);
                    });
                }
            });

        $('#buttonSubmit').click(function(e){
            if(dropzone.getQueuedFiles().length > 0) {
                e.preventDefault();
                dropzone.processQueue();
            }
        });

    });
</script>
{% endblock %}

and here my uploadListener (oneupUploader used):

class UploadListener
{
     /* @var EntityManager $manager*/
    private $manager;

    /* @var InfomonitoreRepository $infomonitor */
    private $infomonitor;

    /**
     * UploadListener constructor.
     * @param EntityManager $manager
     * @param InfomonitoreRepository $infomonitor
     */
    public function __construct(EntityManager $manager, InfomonitoreRepository $infomonitor)
    {
        $this->manager = $manager;
        $this->infomonitor = $infomonitor;
    }


    public function onUpload(PostPersistEvent $event)
    {
        $request = $event->getRequest();
        /* @var Infomonitore $monitorId */
        $monitorId = $this->infomonitor->find($request->get('infomonitor'));
        /* @var File $file */
        $file = $event->getFile();

        $fileName = $monitorId->getMonitorId().'-'.time().'.'.$file->guessExtension();

        $image = new Image();
        $image->setImageFile(basename($file));
        $image->setImageName($fileName);
        $image->setInfomonitor($monitorId);
        try {
            $this->manager->persist($image);
            $this->manager->flush();
        } catch (ORMException $e) {
            print_r($e);
        }

        // if everything went fine
        $response = $event->getResponse();
        $response['success'] = true;
        return $response;
    }
}

Thanks in advance.

New collection element overwrites the last element if it already exists when updating an entry

$
0
0

so I have a Mission entity connected to an Option entity through a ManyToMany relationship. At the time of creating a new mission it is possible to add several options (this point is ok). Now when updating a mission, when I add a new option it overwrites the last option if it already exists otherwise it fits well. I want to be able to add as many options when modifying a mission without overwriting the last existing option. I post my code:

Mission entity :

    /**
     * @var ArrayCollection $options
     *
     * @ORM\ManyToMany(targetEntity="App\Entity\Option", inversedBy="missionOptions", cascade={"persist","remove"})
     * @ORM\JoinColumn(nullable=true)
     */
    protected $options;

    /**
     * Mission constructor.
     */
    public function __construct()
    {
        $this->options = new ArrayCollection();
    }

    public function addOption(Option $option)
    {
        $tag->addMission($this);
        $this->options->add($option);
        return $this;
    }


    public function addOptions($options)
    {
        foreach($options as $option){
            $this->addOption($option);
        }
        return $this;
    }

    public function removeOption(Option $option)
    {
        $this->options->removeElement($option);
        return $this;
    }

    public function removeOptions($options)
    {
        foreach($options as $option){
            $this->removeOption($option);
        }
        return $this;
    }

    public function setOptions(Option $option)
    {
        $this->options[] = $option;
        return $this;
    }

    /**
     * Get options
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getOptions()
    {
        return $this->options;
    } 

Option entity:

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Mission", mappedBy="options", cascade={"persist","remove"})
     */
    private $missionOptions;

    /**
     * Option constructor.
     */
    public function __construct()
    {
        $this->missionOptions = new ArrayCollection();
    }

    public function setMission($missions)
    {
        $this->missionOptions = $missions;
    }

    public function getMission()
    {
        return $this->missionOptions;
    }

    public function addMission(Mission $mission)
    {
        if (!$this->missionOptions->contains($mission)) {
            $this->missionOptions->add($mission);
        }
        return $this;
    }

OptionType:

        $builder->add('tagname', TextType::class, array(
                'required' => true,
                'translation_domain' => 'FOSUserBundle',
                'label' => 'form.option_name',
                'attr' => array(
                    'class' => 'with-border',
                    'placeholder' => 'Nouvelle option'
                )
            ))
            ->add('prix', NumberType::class, array(
                'required' => true,
                'translation_domain' => 'FOSUserBundle',
                'label' => 'form.option_price',
                'attr' => array(
                    'min' => '2000',
                    'class' => 'with-border',
                    'placeholder'  => 'prix'
                )
            ))
        ;

MissionType:

          $builder->add('options', CollectionType::class, [
                'entry_type' => OptionType::class,
                'entry_options' => ['label' => false],
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'required' => false
            ])

In MissionController:

    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('App:Mission')->find($id);

        $originalOptions = new ArrayCollection();
        foreach ($entity->getOptions() as $option) {
            $originalOptions->add($option);
        }
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);
        if ($editForm->isSubmitted() && $editForm->isValid()) {

            foreach ($originalOptions as $option) {
                if ($option->getTagname() == null || $option->getPrix() == null) {
                    $option->getMission()->removeElement($entity);
                    $em->persist($option);
                    $em->remove($option);
                }
            }

            $em->flush();
            return $this->redirectToRoute('dashboard_missions');
        }
     }

In my twig:

<ul class="options" data-prototype="{{ form_widget(edit_form.options.vars.prototype)|e('html_attr') }}"></ul>

<script>
        var $collectionHolder;

        var $addTagButton = $('<button type="button" class="button add_option_link"> Ajouter une option</button>');
        var $newLinkLi = $('<li></li>').append($addTagButton);

        jQuery(document).ready(function() {
            $collectionHolder = $('ul.options');
            $collectionHolder.append($newLinkLi);
            $collectionHolder.data('index', $collectionHolder.find(':input').length);
            $addTagButton.on('click', function(e) {
                addTagForm($collectionHolder, $newLinkLi);
            });
        });

        function addTagForm($collectionHolder, $newLinkLi) {
            var prototype = $collectionHolder.data('prototype');
            var index = $collectionHolder.data('index');
            var newForm = prototype;
            newForm = newForm.replace(/__name__/g, index);
            $collectionHolder.data('index', index + 1);
            var $newFormLi = $('<li></li>').append(newForm);
            $newLinkLi.before($newFormLi);
            addTagFormDeleteLink($newFormLi);
        }

        function addTagFormDeleteLink($tagFormLi) {
            var $removeFormButton = $('<button style="margin-left: 10px" type="button" class="button"></button>');
            $tagFormLi.append($removeFormButton);
            $removeFormButton.on('click', function(e) {
                $tagFormLi.remove();
            });
        }
    </script>

Screening: Show edit :

enter image description here

When add new:

enter image description here

After update:

enter image description here

Thank you in advance for all help

Symfony 4.3 - Overriding template issue the EasyAdminBundle's layout.html.twig case

$
0
0

I'm integrating EasyAdminBundle to my Symfony 4.3 app. No problems except the overring template part .. Fllowing the documentation, the template's overriding mechanism seems not work at all...

I'm forcely missing something ..

Example with the layout of EasyAdminBundle (easycorp/easyadmin-bundle v2.3.0):

Following the documentation my structure is like :

my-project/
├─ ...
└─ templates/
   └─ bundles/
      └─ EasyAdminBundle/
         └─ default/
            ├─ layout.html.twig

This layout.html.twig (path:templates/bundles/EasyAdminBundle/default/layout.html.twig) is a copy of the vendor/easycorp/easyadmin-bundle/src/Resources/views/default/layout.html.twig + some modifications

Cache:clear in debug and refresh navigator doesn't change the layout ( the effective one is still : vendor/easycorp/easyadmin-bundle/src/Resources/views/default/layout.html.twig )

Any idea ?

How tro translate Symfony 4 security error message: "Invalid credentials"

$
0
0

I am developing a Vue.js application and want to handle the login via JSON login. This works already but I'd like to translate the error messages, e.g. "Invalid credentials."

My translation.yaml config file.

framework:
    default_locale: de
    translator:
        default_path: '%kernel.project_dir%/translations'
        fallbacks:
            - en

The Symfony Security component already has some German (de) translations in its translation directory:

https://github.com/symfony/security-core/blob/master/Resources/translations/security.de.xlf

<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">
        <body>
        ...
            <trans-unit id="4">
                <source>Invalid credentials.</source>
                <target>Fehlerhafte Zugangsdaten.</target>
            </trans-unit>
        ...
        </body>
    </file>
</xliff>

So I copied this file into my translations directory but still the english messages are being displayed. Also I always cleared my cache (thanks to Dylan's answer)

Form collection data pass [Symfony 4]

$
0
0

I'm coming to you to solve a brain killer issue.

So i've a basic form to generate sub forms. I would like to pass array data to the sub form but array pass are data distorted.

I've also got an error about CSRF token which I think is linked. CSFR Error

Controller :

public function evaluatemocep($id,Request $request): Response
    {
        if ($this->getUser()) {
            $em = $this->getDoctrine()->getManager();
            $efficiency = new Efficiency();
            $problem = $em->getRepository('App:Problem')->find($id);
            $efficiency->setLinkProblem($problem);
            $form = $this->createForm(EfficiencyForm::class,$problem,['data'=>['id' => $id]]);
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $em->persist($efficiency);
                $em->flush();
            }
                return $this->render('efficiency/efficiencyform.html.twig', [
                    'problem' => $problem,
                    'form' => $form->createView()]);
        }
        return new Response("You must be login");
    }

efficiencyform :

class EfficiencyForm extends AbstractType {

    /**
     * {@inheritDoc}
     */
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {

        $problem = $this->em->getRepository(Problem::class)->find($options['data']['id']);
        $MOCrepo = $problem->getMOC();
        $EOrepo = $problem->getEO();
        $MOCA = array();
        $EOA = array();
        foreach ($EOrepo as $eo){
            array_push($EOA, $eo);
        }
        foreach ($MOCrepo as $moc){
            array_push($MOCA, $moc);
        }
                $builder->add('EffCollection', CollectionType::class, [
                    'entry_type' => EfficiencyMOCEOType::class,
                    'entry_options' => array('label' => false, 'EOA' => $EOA, 'MOCA' => $MOCA),
                    'allow_add' => true,
                    'prototype' => true,
                    'by_reference' => false,
                    'allow_delete' => true,
                    'mapped' => false,
                    'label' => 'Thinking about health'
                ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'allow_extra_fields' => true
        ]);
    }

    public function getBlockPrefix() {
        return 'RateCouple';
    }

}

EfficiencyMOCEOType :

<?php

namespace App\Form;

use App\Entity\Efficiency;
use App\Entity\EO;
use App\Entity\MOC;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class EfficiencyMOCEOType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $EOA = $options['EOA'];
        $MOCA = $options['MOCA'];

        $builder
            ->add('EO', EntityType::class, [
                'class' => EO::class,
                'label' => 'Ethical objective',
                'choices' => $EOA,
                'choice_attr' => function ($choice){return ['title' => $choice->getDescription()];},
                'required' => true])
            ->add('MOC', EntityType::class,[
                'class' => MOC::class,
                'label' => 'Model Of Care',
                'choices' => $MOCA,
                'choice_attr' => function ($choice){return ['title' => $choice->getDescription()];},
                'required' => true])
            ->add('rateRiskCurrent', ChoiceType::class,[
                'label' => 'Evaluate the risks of the selected couple : ',
                'choices' => [
                    'High Risk' => 3,
                    'Medium Risk' => 2,
                    'Low Risk' => 1
                ],
                'required' => true
            ])
            ->add('rateBenefitCurrent', ChoiceType::class,[
                'label' => 'Evaluate the benefits of the selected couple : ',
                'choices' => [
                    'High Benefit' => 3,
                    'Medium Benefit' => 2,
                    'Low Benefit' => 1
                ],
                'required' => true
            ]);
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Efficiency::class,
            'MOCA' =>[],
            'EOA' => [],
            'allow_extra_fields' => true
        ]);
    }
}

twig file :

{% extends 'base.html.twig' %}

{% block title %}New efficiency evaluation{% endblock %}

{% block body %}
{{ form(form) }}

<div>
</div>
<fieldset>
    {{ form_start(form) }}

    <ul style="display: none" class="efficiencies" data-prototype="&lt;fieldset class=&quot;form-group&quot;&gt;&lt;div id=&quot;RateCouple_linkEfficiency___name__&quot;&gt;&lt;div class=&quot;form-group&quot;&gt;&lt;label class=&quot;required&quot; for=&quot;RateCouple_linkEfficiency___name___EO&quot;&gt;Ethical objective&lt;/label&gt;&lt;select id=&quot;RateCouple_linkEfficiency___name___EO&quot; name=&quot;RateCouple[linkEfficiency][__name__][EO]&quot; class=&quot;form-control&quot;&gt;&lt;option value=&quot;3&quot; title=&quot;DESC EO 1&quot;&gt;EO 1&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;&lt;div class=&quot;form-group&quot;&gt;&lt;label class=&quot;required&quot; for=&quot;RateCouple_linkEfficiency___name___MOC&quot;&gt;Model Of Care&lt;/label&gt;&lt;select id=&quot;RateCouple_linkEfficiency___name___MOC&quot; name=&quot;RateCouple[linkEfficiency][__name__][MOC]&quot; class=&quot;form-control&quot;&gt;&lt;option value=&quot;3&quot; title=&quot;DESC MOC 1&quot;&gt;MOC 1&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;&lt;div class=&quot;form-group&quot;&gt;&lt;label class=&quot;required&quot; for=&quot;RateCouple_linkEfficiency___name___rateRiskCurrent&quot;&gt;Evaluate the risks of the selected couple : &lt;/label&gt;&lt;select id=&quot;RateCouple_linkEfficiency___name___rateRiskCurrent&quot; name=&quot;RateCouple[linkEfficiency][__name__][rateRiskCurrent]&quot; class=&quot;form-control&quot;&gt;&lt;option value=&quot;3&quot;&gt;High Risk&lt;/option&gt;&lt;option value=&quot;2&quot;&gt;Medium Risk&lt;/option&gt;&lt;option value=&quot;1&quot;&gt;Low Risk&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;&lt;div class=&quot;form-group&quot;&gt;&lt;label class=&quot;required&quot; for=&quot;RateCouple_linkEfficiency___name___rateBenefitCurrent&quot;&gt;Evaluate the benefits of the selected couple : &lt;/label&gt;&lt;select id=&quot;RateCouple_linkEfficiency___name___rateBenefitCurrent&quot; name=&quot;RateCouple[linkEfficiency][__name__][rateBenefitCurrent]&quot; class=&quot;form-control&quot;&gt;&lt;option value=&quot;3&quot;&gt;High Benefit&lt;/option&gt;&lt;option value=&quot;2&quot;&gt;Medium Benefit&lt;/option&gt;&lt;option value=&quot;1&quot;&gt;Low Benefit&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;&lt;/div&gt;&lt;/fieldset&gt;">
    </ul>
        <ul class="efficiencies">
            {% for efficiency in form.EffCollection %}
                <li>
                    {{ form_row(efficiency.EO) }}
                    </br>
                    {{ form_row(efficiency.MOC) }}
                    </br>
                    {{ form_row(efficiency.rateRiskCurrent) }}
                    </br>
                    {{ form_row(efficiency.rateBenefitCurrent) }}

                </li>
            {% endfor %}
        </ul>
    <input type="submit" value="Submit" class="btn btn-primary btn-block" />

    {{ form_end(form) }}

    <script>

        var efficiency_template = document.getElementById("efficiencies");

        function addNewEfficiency(){
            var dup_efficiency_template = efficiency_template.cloneNode(true);
            document.getElementById("list_of_efficiency").append(dup_efficiency_template);
        }

    </script>

    {% endblock %}
    {% block javascripts %}
        <script>

            var $collectionHolderEfficiency;

            var $addEfficiencyButton = $('<button type="button" class="btn btn-secondary btn-success">Add an efficiency row</button>');

            var $newEfficiencyLinkLi = $('<li></li>').append($addEfficiencyButton);


            jQuery(document).ready(function() {
                $collectionHolderEfficiency = $('ul.efficiencies');

                $collectionHolderEfficiency.find('li').each(function () {
                    addEfficiencyFormDeleteLink($(this));
                });
                $collectionHolderEfficiency.append($newEfficiencyLinkLi);
                $collectionHolderEfficiency.data('index', $collectionHolderEfficiency.find(':input').length);
                $addEfficiencyButton.on('click', function (e) {
                    addEfficiencyForm($collectionHolderEfficiency, $newEfficiencyLinkLi);
                });
            });



            function addEfficiencyForm($collectionHolderEfficiency, $newEfficiencyLinkLi) {
                var prototype = $collectionHolderEfficiency.data('prototype');
                var index = $collectionHolderEfficiency.data('index');
                var newForm = prototype;
                newForm = newForm.replace(/__name__/g, index);
                $collectionHolderEfficiency.data('index', index + 1);
                var $newFormLi = $('<li></li>').append(newForm);
                addEfficiencyFormDeleteLink($newFormLi);
                $newEfficiencyLinkLi.before($newFormLi);
            }


            function addEfficiencyFormDeleteLink($efficiencyFormLi) {
                var $removeFormButton = $('<button type="button" class="btn btn-secondary btn-danger">Delete this efficiency row</button>');
                $efficiencyFormLi.append($removeFormButton);
                $removeFormButton.on('click', function(e) {
                    $efficiencyFormLi.remove();
                });
            }

        </script>
</fieldset>
    {% endblock %}

Any help will be grateful !

Symfony 4.3 translation update not working with container

$
0
0

In my controller, I use

$this->get('session.flash_bag')
    ->add('error', $this->get('translator')->trans('User cannot be activated',[],'messages'));

After team

php bin/console translation: update --dump-messages ru --domain=messages

I do not see new translations. Through tests, I realized that the container is not loaded and the translation is not visible. If you implement Translator in a method, then everything is fine. How can you do without implementation?

deploy symfony 4 demo application on wamp

$
0
0

i installed symfony 4 demo application and it works perfectly with the build-in server but not with wamp. i access to the homepage but scripts (css and js) are not loaded (404) it seems to be a path problem : it try to load "localhost/build/..." and not "localhost/demo/build". i tried to configure my apache as described here https://symfony.com/doc/current/setup/web_server_configuration.html

but it doesn't change anything

my httpd-vhosts.conf :

    Virtual Hosts
<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local
  </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName demo
    ServerAlias demo
    DocumentRoot "C:/wamp64/www/demo/public"
    <Directory "C:/wamp64/www/demo/public">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>

    <Directory "C:/wamp64/www/demo/">
         Options FollowSymlinks
     </Directory>
</VirtualHost>

Is the firewall declaration order significant in security.yaml?

$
0
0

In my project, I have 2 providers and 2 firewalls.

Is there an order to respect when declaring your firewalls? In my example, if I start with admin and then user, it works perfectly.

If I do the opposite, I can not connect with the admin anymore.

Why does this happen?

providers:
    app_user_provider:
        entity:
            class: App\Entity\User
            property: email
    app_user_admin_provider:
        entity:
            class: App\Entity\Useradmin
            property: email

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    admin:
        anonymous: true
        pattern: ^/admin
        provider: app_user_admin_provider
        guard:
            authenticators:
                - App\Security\AdminFormAuthenticator
        logout:
            path: /admin/logout
            target: home
    user:
        anonymous: true
        pattern: ^/
        provider: app_user_provider
        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator
        logout:
            path: /profile/logout
            target: home

access_control:
    - { path: ^/admin$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/profile, roles: ROLE_USER }

role_hierarchy:
    ROLE_ADMIN: ROLE_USER

Is it normal to combine methods of delivery dummy data in functional tests

$
0
0

It will be about the project written in Symfony 4 and testing with the participation of the database. There is an opinion that the test data should be exactly the same in each test and should be delivered only through fixtures (I mean the extensions of Doctrine\Bundle\FixturesBundle\Fixture). But I think, dummy data could be delivered to DB by different ways: by creation data inside test, by dataProvider method, and of course by fixtures. This is at the discretion of the developer. And, obviously, data could be different in each tests

class UsersTest extends WebTestCase
{

    private EntityManagerInterface $entityManager;
    private UserManager $userService;

    public function setUp(): void
    {
        $this->entityManager = self::$container->get(EntityManagerInterface::class);
        $this->userService = self::$container->get(UserManager::class);
    }

    //
    //    DATA CREATION INSIDE TEST
    //
    public function testCountUsers(): void
    {
        $user = new User();
        $this->entityManager->persist($user);
        $this->entityManager->flush();
        $count = $this->userService->getAllUsersCount();
        $this->assertEquals(1, $count);
    }

    //
    // DELIVERY DATA BY DATAPROVIDER
    //
    public function testCountUsers2(array $users, int $expectedCount): void
    {
        foreach ($users as $user) {
            $this->entityManager->persist($user);
        }
        $this->entityManager->flush();
        $count = $this->userService->getAllUsersCount();
        $this->assertEquals($expectedCount, $count);
    }

    public static function usersCountDataProvider(): array
    {
        return [
            [
                'users' => [new User(), new User(), new User()],
                'expectedCount' => 3
            ],
            [
                'users' => [],
                'expectedCount' => 0
            ],
        ];
    }

    //
    // DELIVERY DATA BY FIXTURE
    //
    public function testCountUsers3(): void
    {
        $this->loadFixtures([UsersFixtures::class]);
        $count = $this->userService->getAllUsersCount();
        $this->assertEquals(4, $count);
    }
}

How do you think, is that normal to make tests in such ways?

Symfony 4 how to implement Doctrine XML ORM mapping

$
0
0

Symfony 4 document is unclear about how to use XML orm mapping instead of annotations. It's rather frustrating to see no details for such important part in official documentation.

How to access not-injected services directly on Symfony 4+?

$
0
0

I'm trying to update Symfony 2.8 to Symfony 4 and I am having serious problems with the Services Injection.

I'm looking the new way to use Services inside Controllers, with auto-wiring:

use App\Service\AuxiliarService;
class DefaultController extends AbstractController
{
    public function index(AuxiliarService $service)
    {
        $var = $service->MyFunction();
        ....

This way works fine, but I dislike the explicit way to refer MyService as a parameter of the function. This way I don't even need to register the Service in the services.yaml

Is any way to use Services as in Symfony 2.8:

class DefaultController extends Controller
    {
        public function index()
        {
            $var = $this->get('AuxiliarService')->MyFunction(); /*Doesn't need to be explicit indicate before*/
            ....

With the services.yaml

services:
    auxiliar_service:
        class:        AppBundle\Services\AuxiliarService
        arguments: 
            entityManager: "@doctrine.orm.entity_manager"
            container: "@service_container" #I need to call services inside the service

This way I don't need to indicate the Service as a parameter in the function of the Controller. In some cases, inside a Service, I need to call more than 10 services depends on the data, so indicate them as a parameter in the function is annoying.

Another doubt in Symfony 4, is how to call a Service inside another Service without put as a argument or parameter. This case is because I injected the service container to be able to call a service inside a service:

$this->container->get('anotherService')

In Symfony 4, I think it is more expensive (in code) use Service because you have to explicit indicate them when you are going to use them.

Symfony 4 An exception occurred in driver: SQLSTATE[HY000] [2002] No such file or directory

$
0
0

I am trying to create a database in symfony 4 using php bin/console doctrine:database:create command in terminal, but I keep getting the same 3 errors:

In AbstractMySQLDriver.php line 93:

  An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused  


In PDOConnection.php line 31:

  SQLSTATE[HY000] [2002] Connection refused  


In PDOConnection.php line 27:

  SQLSTATE[HY000] [2002] Connection refused

There are a few similar problems which seem to be solved by changing 127.0.0.1 to localhost in the .env file DATABASE_URL line, but none of these solutions fix the problem. Changing to localhost for me gives the same error but 'no such file or directory' instead of 'connection refused'.

Any help would be greatly appreciated!

calculate difference between hours using twig symfony4

$
0
0

hey i have two fields of types dates i want to calculate just difference between two vairable by hour and minutes: I need only hour and minuts variable example 1 2019-10-28 00:10:21 variable example 2 2050-10-25 01:10:21

Result 01:10:21-00:10:21=01:00:00 I need to convert it to timestamp to calculate the difference

maker-bundle custom skeleton (symfony 4)

$
0
0

I would like to replace maker-bundle template by my own template skeleton https://github.com/symfony/maker-bundle/tree/master/src/Resources/skeleton/crud

In sensiolabs/SensioGeneratorBundle (SF3) it was easy, we just have to copy/paste into Ressources directory the customized skeleton.

I didn't find how to do same rendering with maker-bundle.

Do I have to build my own maker ? Others solutions ? It seems to be a common problem


My profiler isn't showing up in symfony 4.3.1

$
0
0

In my .env file, I have specified my app environment to be dev and debug to be true like so:

APP_ENV=dev
APP_DEBUG=true

In my config/packages/dev/web_profiler.yaml file I have the following:

web_profiler:
    toolbar: true
    intercept_redirects: false

framework:
    profiler: { only_exceptions: false }

The routing within config/routes/dev/web_profiler.yaml seems to be fine:

web_profiler_wdt:
    resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml'
    prefix: /_wdt

web_profiler_profiler:
    resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml'
    prefix: /_profiler

So when I run the server with symfony server:start everything is fine, but the profiler doesn't appear. Did I miss something that enables that feature within symfony?

EDIT To clarify, the page is outputting a proper HTML page with the appropriate content. There is just no profiler showing up.

How write a Symfony Flex recipe for a new bundle?

$
0
0

I tried to find any documentation about using Symfony Flex but so far no luck.

Almost all docs point to installing a bundle that uses symfony Flex, not how to create a bundle that is using it.

I even tried to reverse engineer some of the packages but again, no luck.

My goal is to generate a default configuration file for my bundle in config/packages/my_bundle.yaml.

What I need to know is where do I need to put it and what env variables (if any) will I have available?

Make an api accesible in 2 cases with and whitout jwt token

$
0
0

I have this this code :

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    login:
        pattern:  ^/api/public/login
        stateless: true
        anonymous: true
        json_login:
            check_path:               /api/public/login
            success_handler:          lexik_jwt_authentication.handler.authentication_success
            failure_handler:          lexik_jwt_authentication.handler.authentication_failure
    api:
        pattern:   ^/api/private
        stateless: true
        guard:
            authenticators:
                - lexik_jwt_authentication.jwt_token_authenticator
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_token_generator: security.csrf.token_manager
        oauth:
            resource_owners:
                facebook:         "/secured/login_facebook"
                google:           "/secured/login_google"
            login_path:        fos_user_security_login
            failure_path:      fos_user_security_login
            oauth_user_provider:
                service: app.provider.oauth
            default_target_path: /api/public/facebook/back

        logout:       true
        anonymous:    true

# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
    - { path: ^/login$,             role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/,             role: ROLE_ADMIN }
    - { path: ^/api/private/,       role: IS_AUTHENTICATED_FULLY }
    - { path: ^/api/public/,        role: IS_AUTHENTICATED_ANONYMOUSLY }

Now if I call the api : api/public/gifts, it works fine. But when I tried to retrieve the token I get : anonym. This is not correct for me because I want that this route be accessible in both : connected and unconnected. What I'm doing wrong ? When I call api/private/my-profile I get the right user in $tokenInterface->getToken()->getUser(). Help me please

Attempted to load class "WebProfilerBundle" from namespace "Symfony\Bundle\WebProfilerBundle" when deploying on Heroku using development dependencies

$
0
0

We have a Symfony 4.3 web application hosted on Heroku. This is a new setup and we never managed to have the dev mode to work correctly. There are plenty of similar issues online but none fixes the exact symptoms we are facing here.

The project was created with a command line:

composer create-project symfony/website-skeleton appName

Let me clarify that: we do not want to change from"dev"to"prod"

We need to be able to use the application in dev mode in order to take advantage of error debugging for PHP as per the article "How to Customize Error Pages" for Symfony 4.3 here

$ php bin/console about
 -------------------- ----------------------------------------------------
  Symfony
 -------------------- ----------------------------------------------------
  Version              4.3.5
  End of maintenance   01/2020
  End of life          07/2020
 -------------------- ----------------------------------------------------
  Kernel
 -------------------- ----------------------------------------------------
  Type                 App\Kernel
  Environment          dev
  Debug                true
  Charset              UTF-8
  Cache directory      ./var/cache/dev (12.1 MiB)
  Log directory        ./var/log (13 KiB)
 -------------------- ----------------------------------------------------
  PHP
 -------------------- ----------------------------------------------------
  Version              7.3.10
  Architecture         64 bits
  Intl locale          n/a
  Timezone             Europe/Berlin (2019-10-28T15:48:05+01:00)
  OPcache              false
  APCu                 false
  Xdebug               false
 -------------------- ----------------------------------------------------
  Environment (.env)
 -------------------- ----------------------------------------------------
  APP_ENV              dev
 *just a few removed before posting for privacy*
 -------------------- ----------------------------------------------------

If we change from 'dev' to 'prod' environment the application works but we cannot see the errors the way we wish to. We could use the command below (but this is not the point we are trying to solve here) in order to use "Symfony Var Dumper Server". We do not want to use this method.

./bin/console server:dump

It seems that we might be missing a dependency but composer update and composer install and composer dump-autoload did not solve anything.

Also note the message "Did you forget a "use" statement for another namespace? in /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/src/Kernel.php:23" - Is it possible that the WebProfilerBundle is broken in the master repository?

To further help understand the situation, below is the composer.json file

{
    "type": "project",
    "license": "proprietary",
    "require": {
        "php": "^7.1.3",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "phpmailer/phpmailer": "^6.1",
        "sensio/framework-extra-bundle": "^5.5",
        "symfony/asset": "4.3.*",
        "symfony/console": "4.3.*",
        "symfony/dotenv": "4.3.*",
        "symfony/expression-language": "4.3.*",
        "symfony/flex": "^1.3.1",
        "symfony/form": "4.3.*",
        "symfony/framework-bundle": "4.3.*",
        "symfony/http-client": "4.3.*",
        "symfony/intl": "4.3.*",
        "symfony/mailer": "4.3.*",
        "symfony/monolog-bundle": "^3.1",
        "symfony/orm-pack": "^1.0",
        "symfony/process": "4.3.*",
        "symfony/security-bundle": "4.3.*",
        "symfony/serializer-pack": "*",
        "symfony/swiftmailer-bundle": "^3.1",
        "symfony/translation": "4.3.*",
        "symfony/twig-bundle": "4.3.*",
        "symfony/twig-pack": "^1.0",
        "symfony/validator": "4.3.*",
        "symfony/web-link": "4.3.*",
        "symfony/webpack-encore-bundle": "^1.7",
        "symfony/yaml": "4.3.*"
    },
    "require-dev": {
        "symfony/debug-bundle": "4.3.*",
        "symfony/debug-pack": "*",
        "symfony/maker-bundle": "^1.14",
        "symfony/profiler-pack": "^1.0",
        "symfony/test-pack": "*",
        "symfony/web-profiler-bundle": "4.3.*",
        "symfony/web-server-bundle": "4.3.*"
    },
    "config": {
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "paragonie/random_compat": "2.*",
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php71": "*",
        "symfony/polyfill-php70": "*",
        "symfony/polyfill-php56": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "4.3.*"
        }
    }
}

Our obstacle: trying to deploy to heroku using dev mode.

git push heroku master

which fails with the following message:

remote:        Executing script cache:clear [KO]
remote:         [KO]
remote:        Script cache:clear returned with error code 255
remote:        !!  PHP Fatal error:  Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "WebProfilerBundle" from namespace "Symfony\Bundle\WebProfilerBundle".
remote:        !!  Did you forget a "use" statement for another namespace? in /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/src/Kernel.php:23
remote:        !!  Stack trace:
remote:        !!  #0 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/http-kernel/Kernel.php(429): App\Kernel->registerBundles()
remote:        !!  #1 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/http-kernel/Kernel.php(130): Symfony\Component\HttpKernel\Kernel->initializeBundles()
remote:        !!  #2 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/framework-bundle/Console/Application.php(159): Symfony\Component\HttpKernel\Kernel->boot()
remote:        !!  #3 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/framework-bundle/Console/Application.php(65): Symfony\Bundle\FrameworkBundle\Console\Application->registerCommands()
remote:        !!  #4 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/console/Application.php(149): Symfony\Bundle\FrameworkBundle\Cons in /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/src/Kernel.php
on line 23
remote:        !!
remote:        Script @auto-scripts was called via post-install-cmd
remote:  !     WARNING: There was a class not found error in your code
remote:
remote:  !     ERROR: Dependency installation failed!
remote:  !
remote:  !     The 'composer install' process failed with an error. The cause
remote:  !     may be the download or installation of packages, or a pre- or
remote:  !     post-install hook (e.g. a 'post-install-cmd' item in 'scripts')
remote:  !     in your 'composer.json'.
remote:  !
remote:  !     Typical error cases are out-of-date or missing parts of code,
remote:  !     timeouts when making external connections, or memory limits.
remote:  !
remote:  !     Check the above error output closely to determine the cause of
remote:  !     the problem, ensure the code you're pushing is functioning
remote:  !     properly, and that all local changes are committed correctly.
remote:  !
remote:  !     For more information on builds for PHP on Heroku, refer to
remote:  !     https://devcenter.heroku.com/articles/php-support
remote:  !
remote:  !     REMINDER: the following warnings were emitted during the build;
remote:  !     check the details above, as they may be related to this error:
remote:  !     - There was a class not found error in your code
remote:
remote:  !     Push rejected, failed to compile PHP app.
remote:
remote:  !     Push failed

We currently do not know how to install or verify that bundles are indeed present and operational for Symfony 4.3 - ideas in this direction might help but not only.

php bin/console config:dump-reference

Available registered bundles with their extension alias if available
====================================================================

 ---------------------------- ------------------------
  Bundle name                  Extension alias
 ---------------------------- ------------------------
  DebugBundle                  debug
  DoctrineBundle               doctrine
  DoctrineCacheBundle          doctrine_cache
  DoctrineMigrationsBundle     doctrine_migrations
  FrameworkBundle              framework
  MakerBundle                  maker
  MonologBundle                monolog
  SecurityBundle               security
  SensioFrameworkExtraBundle   sensio_framework_extra
  SwiftmailerBundle            swiftmailer
  TwigBundle                   twig
  TwigExtraBundle              twig_extra
  WebProfilerBundle            web_profiler
  WebServerBundle              web_server
  WebpackEncoreBundle          webpack_encore
 ---------------------------- ------------------------

 // Provide the name of a bundle as the first argument of this command to dump its default configuration. (e.g.
 // config:dump-reference FrameworkBundle)
 //
 // For dumping a specific option, add its path as the second argument of this command. (e.g.
 // config:dump-reference FrameworkBundle profiler.matcher to dump the
 // framework.profiler.matcher configuration)

Symfony4: Dynamic form with a Collection(Type) of ChoiceType with further requirements

$
0
0

Sorry folks, I feel too stupid to understand this part of the Symfony 4 documentation. I want to generate a form to create and edit a dataset with related subsets (normaly is that no problem at all).

First entity is called Case (for this question just one property).

<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CaseRepository")
 */
class Case
{
   // [...]

    /**
     * @ORM\Column(type="text", nullable=false)
     * @Assert\NotNull()
     * @var string
     */
    private $title;

    // [...]

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\CaseForecast", mappedBy="case",  cascade={"persist", "remove"},orphanRemoval=true)
     */
    private $caseForecasts;


    public function __construct()
    {
        // [...]
        $this->caseForecasts = new ArrayCollection();
    }

    // [...]

    /**
     * @return Collection|CaseForecast[]
     */
    public function getCaseForecasts(): Collection
    {
        return $this->caseForecasts;
    }

    public function addCaseForecastis(CaseForecast $caseForecastis): self
    {
        if (!$this->caseForecasts->contains($caseForecastis)) {
            $this->caseForecasts[] = $caseForecastis;
            $caseForecastis->setCase($this);
        }
        return $this;
    }

    public function removeCaseForecastis(CaseForecast $caseForecastis): self
    {
        if ($this->caseForecasts->contains($caseForecastis)) {
            $this->caseForecasts->removeElement($caseForecastis);
            // set the owning side to null (unless already changed)
            if ($caseForecastis->getCase() === $this) {
                $caseForecastis->setCase(null);
            }
        }
        return $this;
    }
}

The important relation at this time is CaseForecast. This is a ManyToOne relation. This is the entity:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CaseForecastRepository")
 */
class CaseForecast
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Case", inversedBy="caseForecasts")
     * @ORM\JoinColumn(nullable=false)
     */
    private $case;

    /**
     * @ORM\Column(type="integer")
     */
    private $itemNumber;

    /**
     * @ORM\Column(type="integer", options={"comment":"0 secure; 1 fragile; 2 reject"})
     *
     */
    private $forecast;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $comment;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getCase(): ?Case
    {
        return $this->case;
    }

    public function setCase(?Case $case): self
    {
        $this->case = $case;

        return $this;
    }

    public function getItemNumber(): ?int
    {
        return $this->itemNumber;
    }

    public function setItemNumber(int $itemNumber): self
    {
        $this->itemNumber = $itemNumber;
        return $this;
    }

    public function getForecast(): ?int
    {
        return $this->forecast;
    }

    public function setForecast(int $forecast): self
    {
        $this->forecast = $forecast;
        return $this;
    }

    public function getBegruendung(): ?string
    {
        return $this->begruendung;
    }

    public function setBegruendung(?string $begruendung): self
    {
        $this->begruendung = $begruendung;
        return $this;
    }

    public function __toString()
    {
        return $this->zahnNummer;
    }
}

The property itemNumber got a range of values 11..18,21..28,31..38,41..48 One entity Case got 32 CaseForecast as a ArrayCollection...every time! When I create a object Case I also create 32 objects CaseForecast. The property "forecast" is integer value of 0,1 or 2.

The form should look like this: Form with Collection of ChoiceTypes

What you see on the picture:
On the left the side the translated values for forecast.
Followed by the CaseForecast.forecast for the itemNumbers 11-18 and 28-21
Next "row" you see the itemNumbers in two lines.
Next row the CaseForecast for the itemNumbers 41-48 and 38-31
(yes, you're right, it's all about a denture)

In the first step I created the form manually because the data schema was different (wide table/big object with 32 ). Now I had to change the data scheme and now the point is reached where I surrender.

My FormType looks like this:

<?php

namespace App\Form;

use App\Entity\Case;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class CaseShortType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('titel', TextType::class, [
                'label' => "Title",
                'attr' => [
                    'tab-index' => 1
                ]
            ])
            ->add('caseForecasts', CollectionType::class, [
                'entry_type' => ChoiceType::class,
                'entry_options' => [
                    'choices' => [
                        'secure' => 0,
                        'fragile' => 1,
                        'reject' => 2
                    ],
                    'expanded' => true,
                ],
                'allow_add' => false,
                'allow_delete' => false,
            ])
            ->add("submit", SubmitType::class, [
                'label' => 'save',
                'attr' => ['class' => "btn btn-primary"]
            ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Case::class,
            'aktion' => null
        ]);
    }
}

I tried several tutorials and documentations on symfony.com, stackoverflow etc. I'm done and kind of depressed. Nothing fits, not even approximate (for me).

What I want:

  • I want to create the form from the screen above with this relationscheme.
  • I want to do it the "symfony-way", not manually.
  • When I edit the "Case" I want the choices are prechecked with the value from CaseForecast.forecast (callback on choice_value? How to access the current CaseForecast?)
  • I want the itemNumber as the key for the CollectionType Array (if it does not work this way, I have to translate that).

Maybe you have some tips for some other HowTos and documentations...

Thanks!

Viewing all 3917 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>