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

Symfony add logic to logout route

$
0
0

In a Symfony 5.0 Application I want to add custom logic for cleanup reasons when the user loggs out.What I have currenty is what is described in the docs:

https://symfony.com/doc/current/security.html#logging-out

As the logout() function in the SecurityController is intercepted by Symfony it won't work to add logic there.

So - where CAN I add logic which is allways executed when a user loggs out?Couldn't find anything in the docs so far...


Deployment Symfony 4 with React js application on Heroku

$
0
0

My application developed with Symfony 4 in the backend and React js in the frontend, then I want to deploy it on Heroku. I have already connected heroku with my github repository. Finally after I configured everything, I launched the command git push heroku master, then I found the following error shown below:

git push heroku masterEnumerating objects: 255, done.Counting objects: 100% (255/255), done.Delta compression using up to 4 threadsCompressing objects: 100% (250/250), done.Writing objects: 100% (255/255), 159.41 KiB | 2.61 MiB/s, done.Total 255 (delta 144), reused 0 (delta 0)remote: Compressing source files... done.remote: Building source:remote:remote: -----> PHP app detectedremote: -----> Bootstrapping...remote: -----> Installing platform packages...remote:        - php (7.4.4)remote:        - ext-gd (bundled with php)remote:        - ext-mbstring (bundled with php)remote:        - apache (2.4.41)remote:        - nginx (1.16.1)remote: -----> Installing dependencies...remote:        Composer version 1.10.1 2020-03-13 20:34:27remote:        Loading composer repositories with package informationremote:        Installing dependencies from lock fileremote:        Package operations: 91 installs, 0 updates, 0 removalsremote:          - Installing ocramius/package-versions (1.4.2): Downloading (100%)remote:          - Installing symfony/flex (v1.6.0): Downloading (100%)remote:remote:        Prefetching 89 packagesremote:          - Downloading (100%)remote:remote:          - Installing doctrine/lexer (1.2.0): Loading from cacheremote:          - Installing doctrine/annotations (v1.8.0): Loading from cacheremote:          - Installing doctrine/reflection (v1.0.0): Loading from cacheremote:          - Installing doctrine/event-manager (1.1.0): Loading from cacheremote:          - Installing doctrine/collections (1.6.4): Loading from cacheremote:          - Installing doctrine/cache (1.10.0): Loading from cacheremote:          - Installing doctrine/persistence (1.3.3): Loading from cacheremote:          - Installing doctrine/inflector (1.3.1): Loading from cacheremote:          - Installing doctrine/common (v2.11.0): Loading from cacheremote:          - Installing doctrine/instantiator (1.3.0): Loading from cacheremote:          - Installing psr/container (1.0.0): Loading from cacheremote:          - Installing symfony/service-contracts (v1.1.8): Loading from cacheremote:          - Installing symfony/stopwatch (v4.3.9): Loading from cacheremote:          - Installing symfony/polyfill-php73 (v1.13.1): Loading from cacheremote:          - Installing symfony/polyfill-mbstring (v1.13.1): Loading from cacheremote:          - Installing symfony/console (v4.3.9): Loading from cacheremote:          - Installing zendframework/zend-eventmanager (3.2.1): Loading from cacheremote:          - Installing zendframework/zend-code (3.4.1): Loading from cacheremote:          - Installing ocramius/proxy-manager (2.2.3): Loading from cacheremote:          - Installing doctrine/dbal (v2.10.0): Loading from cacheremote:          - Installing doctrine/migrations (2.2.0): Loading from cacheremote:          - Installing willdurand/negotiation (v2.3.1): Loading from cacheremote:          - Installing willdurand/jsonp-callback-validator (v1.1.0): Loading from cacheremote:          - Installing symfony/event-dispatcher-contracts (v1.1.7): Loading from cacheremote:          - Installing symfony/security-core (v4.3.9): Loading from cacheremote:          - Installing symfony/routing (v4.3.9): Loading from cacheremote:          - Installing symfony/polyfill-php72 (v1.13.1): Loading from cacheremote:          - Installing symfony/polyfill-intl-idn (v1.13.1): Loading from cacheremote:          - Installing symfony/mime (v4.3.9): Loading from cacheremote:          - Installing symfony/http-foundation (v4.3.9): Loading from cacheremote:          - Installing symfony/event-dispatcher (v4.3.9): Loading from cacheremote:          - Installing psr/log (1.1.2): Loading from cacheremote:          - Installing symfony/debug (v4.3.9): Loading from cacheremote:          - Installing symfony/http-kernel (v4.3.9): Loading from cacheremote:          - Installing symfony/finder (v4.3.9): Loading from cacheremote:          - Installing symfony/filesystem (v4.3.9): Loading from cacheremote:          - Installing symfony/dependency-injection (v4.3.9): Loading from cacheremote:          - Installing symfony/config (v4.3.9): Loading from cacheremote:          - Installing symfony/var-exporter (v4.3.9): Loading from cacheremote:          - Installing psr/cache (1.0.1): Loading from cacheremote:          - Installing symfony/cache-contracts (v1.1.7): Loading from cacheremote:          - Installing symfony/cache (v4.3.9): Loading from cacheremote:          - Installing symfony/framework-bundle (v4.3.9): Loading from cacheremote:          - Installing friendsofsymfony/rest-bundle (2.6.0): Loading from cacheremote:          - Installing jdorn/sql-formatter (v1.2.17): Loading from cacheremote:          - Installing symfony/inflector (v4.3.9): Loading from cacheremote:          - Installing symfony/property-access (v4.3.9): Loading from cacheremote:          - Installing symfony/security-http (v4.3.9): Loading from cacheremote:          - Installing symfony/security-guard (v4.3.9): Loading from cacheremote:          - Installing symfony/security-csrf (v4.3.9): Loading from cacheremote:          - Installing symfony/security-bundle (v4.3.9): Loading from cacheremote:          - Installing namshi/jose (7.2.3): Loading from cacheremote:          - Installing lcobucci/jwt (3.3.1): Loading from cacheremote:          - Installing lexik/jwt-authentication-bundle (v2.6.5): Loading from cacheremote:          - Installing nelmio/cors-bundle (2.0.1): Loading from cacheremote:          - Installing phpdocumentor/reflection-common (2.0.0): Loading from cacheremote:          - Installing phpdocumentor/type-resolver (1.0.1): Loading from cacheremote:          - Installing psr/simple-cache (1.0.1): Loading from cacheremote:          - Installing markbaker/matrix (1.2.0): Loading from cacheremote:          - Installing markbaker/complex (1.4.7): Loading from cacheremote:          - Installing phpoffice/phpspreadsheet (1.10.1): Loading from cacheremote:          - Installing sensio/framework-extra-bundle (v5.5.2): Loading from cacheremote:          - Installing symfony/apache-pack (v1.0.1): Loading from cacheremote:          - Installing symfony/doctrine-bridge (v4.3.9): Loading from cacheremote:          - Installing symfony/dotenv (v4.3.9): Loading from cacheremote:          - Installing symfony/options-resolver (v4.3.9): Loading from cacheremote:          - Installing symfony/intl (v4.3.9): Loading from cacheremote:          - Installing symfony/polyfill-intl-icu (v1.13.1): Loading from cacheremote:          - Installing symfony/form (v4.3.9): Loading from cacheremote:          - Installing egulias/email-validator (2.1.15): Loading from cacheremote:          - Installing symfony/mailer (v4.3.10): Loading from cacheremote:          - Installing symfony/google-mailer (v4.3.11): Loading from cacheremote:          - Installing nikic/php-parser (v4.3.0): Loading from cacheremote:          - Installing symfony/maker-bundle (v1.14.3): Loading from cacheremote:          - Installing monolog/monolog (1.25.2): Loading from cacheremote:          - Installing symfony/monolog-bridge (v4.3.9): Loading from cacheremote:          - Installing symfony/monolog-bundle (v3.5.0): Loading from cacheremote:          - Installing doctrine/orm (v2.7.0): Loading from cacheremote:          - Installing doctrine/doctrine-bundle (2.0.2): Loading from cacheremote:          - Installing doctrine/doctrine-migrations-bundle (2.1.2): Loading from cacheremote:          - Installing symfony/orm-pack (v1.0.7): Loading from cacheremote:          - Installing symfony/serializer (v4.3.9): Loading from cacheremote:          - Installing symfony/property-info (v4.3.9): Loading from cacheremote:          - Installing webmozart/assert (1.6.0): Loading from cacheremote:          - Installing phpdocumentor/reflection-docblock (4.3.2): Loading from cacheremote:          - Installing symfony/serializer-pack (v1.0.2): Loading from cacheremote:          - Installing symfony/translation-contracts (v1.1.7): Loading from cacheremote:          - Installing symfony/validator (v4.3.9): Loading from cacheremote:          - Installing symfony/yaml (v4.3.9): Loading from cacheremote:        Package zendframework/zend-eventmanager is abandoned, you should avoid using it. Use laminas/laminas-eventmanager instead.remote:        Package zendframework/zend-code is abandoned, you should avoid using it. Use laminas/laminas-code instead.remote:        Generating optimized autoload filesremote:        Deprecation Notice: Class FOS\RestBundle\Examples\RssHandler located in ./vendor/friendsofsymfony/rest-bundle/Resources/doc/examples/RssHandler.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///tmp/build_cf339a6abd921797e6f08d60cb51e78d/.heroku/php/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201remote:        ocramius/package-versions:  Generating version class...remote:        ocramius/package-versions: ...done generating version classremote:        Executing script cache:clear [KO]remote:         [KO]remote:        Script cache:clear returned with error code 255remote:        !!  PHP Fatal error:  Uncaught Error: Class 'Symfony\Bundle\TwigBundle\TwigBundle' not found in /tmp/build_cf339a6abd921797e6f08d60cb51e78d/src/Kernel.php:23remote:        !!  Stack trace:remote:        !!  #0 /tmp/build_cf339a6abd921797e6f08d60cb51e78d/vendor/symfony/http-kernel/Kernel.php(429): App\Kernel->registerBundles()remote:        !!  #1 /tmp/build_cf339a6abd921797e6f08d60cb51e78d/vendor/symfony/http-kernel/Kernel.php(130): Symfony\Component\HttpKernel\Kernel->initializeBundles()remote:        !!  #2 /tmp/build_cf339a6abd921797e6f08d60cb51e78d/vendor/symfony/framework-bundle/Console/Application.php(159): Symfony\Component\HttpKernel\Kernel->boot()remote:        !!  #3 /tmp/build_cf339a6abd921797e6f08d60cb51e78d/vendor/symfony/framework-bundle/Console/Application.php(65): Symfony\Bundle\FrameworkBundle\Console\Application->registerCommands()remote:        !!  #4 /tmp/build_cf339a6abd921797e6f08d60cb51e78d/vendor/symfony/console/Application.php(149): Symfony\Bundle\FrameworkBundle\Console\Application->doRun()remote:        !!  #5 /tmp/build_cf339a6abd921797e6f08d60cb51e78d/bin/console(42): Symfony\Component\Console\Application->run()remote:        !!  #6 {main}remote:        !!    t in /tmp/build_cf339a6abd921797e6f08d60cb51e78d/src/Kernel.php on line 23remote:        !!remote:        Script @auto-scripts was called via post-install-cmdremote:  !     WARNING: There was a class not found error in your coderemote:remote:  !     ERROR: Dependency installation failed!remote:  !remote:  !     The 'composer install' process failed with an error. The causeremote:  !     may be the download or installation of packages, or a pre- orremote:  !     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 ofremote:  !     the problem, ensure the code you're pushing is functioningremote:  !     properly, and that all local changes are committed correctly.remote:  !remote:  !     For more information on builds for PHP on Heroku, refer toremote:  !     https://devcenter.heroku.com/articles/php-supportremote:  !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 coderemote:remote:  !     Push rejected, failed to compile PHP app.remote:remote:  !     Push failedremote: Verifying deploy...remote:remote: !       Push rejected to agro-interest.remote:To https://git.heroku.com/agro-interest.git ! [remote rejected] master -> master (pre-receive hook declined)error: failed to push some refs to 'https://git.heroku.com/show-agro-interest.git'

Can anyone give me any solution or suggestion? Thanks

My custom Form Type Template is ignored when rendering form

$
0
0

I created a custom field type class BootstrapToggleType extends AbstractType which is child of CheckboxType I also prefixed it just in case as follows

public function getBlockPrefix(): string{    return 'bootstrap_toggle';}
public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {            $form = $event->getForm();            $config = $form->getParent()->get($form->getName())->getConfig();            $options = $config->getOptions();            $defaultDataOptions = $this->_bootstrapToggleDataDefaults;            $form->getParent()->add($form->getName(), CheckboxType::class, array_replace_recursive($options, ['attr' => $defaultDataOptions,            ]))            ;        });    }

I added custom form theme to twig.yaml form_themes: ['Form/custom_types.html.twig', 'bootstrap_4_layout.html.twig'] and created mentioned file with following code

{% block bootstrap_toggle_row %}    {% for child in form.children if not child.rendered %}<div class="my-custom-wrapper"><div class="form-group">                {{ form_label(child) }}                {{ form_widget(child) }}                {{ form_help(child) }}                {{ form_errors(child) }}</div></div>    {% endfor %}{% endblock %}

However the field is rendered using standard theme ignoring bootstrap_toggle_row What am I doing wrong?

The problem is basically with this part of code $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { . However I need to use such construction to create a field using name provided by FormType object $builder->add('is_published', BootstrapToggleType::class)

if I change that part of code to something like that

public function buildForm(FormBuilderInterface $builder, array $options){    $builder->addChild('testName', CheckboxType::class);}

my custom template is rendered correctly.

added

Because I re-added another child I have to provide it's correct block prefix.

$form->getParent()->add($form->getName(), CheckboxType::class, array_replace_recursive($options, ['attr' => $defaultDataOptions,'block_prefix' => 'bootstrap_toggle'            ]));

Then in my custom template I need to reffer directly to the form variable as a single child, not an array. So instead of looping over children

{% for child in form.children if not child.rendered %}

just direct call

{{ form_label(form) }}{{ form_widget(form) }}{{ form_help(form) }}{{ form_errors(form) }}

Now it works.

Symfony 4 : good practice controller render

$
0
0

I just begun to use Symfony, and I came from CodeIgniter. In this framwork you pass parameters to the view with an array called $data. So if you want to pass the same variables in each views of a controller, you simply instanciate the $data array in the consctrutor and add what ever you want.

For symfony it's a bit different, and I have imagine something to do the same. It's work great, but I ask myself if they doesn't exist a better way to do it. Or do I have to rethink the way I design my code to avoid this sort of things, for example add another twig layout for specify title in each route of the controller, but what if it's a parameter than I have to use for each render ?

First I define this function :

public function default_data(array $parameters): array{    $default_parameters = array('controller_name' => 'AdminController','navbar_title' => 'Suivis Satisfaction Utilisateurs',    );    return array_merge($default_parameters, $parameters);}

Then, in my controller I call render this way :

return $this->render('my_view.html.twig', $this->default_data(array('my_new_parameter' => 'new_data')));

Thanks for reading.

Symfony 4 - VichUploaderBundle - filename is not persisted in the database

$
0
0

I have an entity "Support"on witch i want to link a file(PDF, DOC,...). I've followed the documentations and some videos to help, but i alway have this error :

SQLSTATE[23000]: Integrity constraint violation: 1048 The field 'filename' can't be empty (null)

and i don't have any persistance in my database.here is my entity "Support" : `

        namespace App\Entity;        use Doctrine\Common\Collections\ArrayCollection;        use Doctrine\Common\Collections\Collection;        use Doctrine\ORM\Mapping as ORM;        use Symfony\Component\HttpFoundation\File\File;        use Vich\UploaderBundle\Mapping\Annotation as Vich;        /**         * @ORM\Entity(repositoryClass="App\Repository\SupportRepository")         * @Vich\Uploadable         */        class Support        {            /**             * @ORM\Id()             * @ORM\GeneratedValue()             * @ORM\Column(type="integer")             */            private $id;            /**             * @var string|null             * @ORM\Column(type="string", length=255)             *              */            private $filename;            /**             * @Vich\UploadableField(mapping="support_file", fileNameProperty="filename", size="fileSize")             * @var File|null             */            private $supportFile;            /**             * @ORM\Column(type="integer")             *             * @var int|null             */            private $fileSize;            /**             * @ORM\Column(type="datetime")             *             * @var \DateTimeInterface|null             */            private $updatedAt;            /**             * @ORM\Column(type="string", length=255)             */            private $titre;            /**             * @ORM\Column(type="text", nullable=true)             */            private $desciption;            /**             * @ORM\ManyToMany(targetEntity="App\Entity\Salle", mappedBy="supports")             */            private $salles;            /**             * @ORM\ManyToOne(targetEntity="App\Entity\TypedeSupport", inversedBy="supports")             * @ORM\JoinColumn(nullable=false)             */            private $typedeSupport;            /**             * @ORM\ManyToOne(targetEntity="App\Entity\Matiere", inversedBy="supports")             */            private $matiere;            public function __construct()            {                $this->salles = new ArrayCollection();            }            public function getId(): ?int            {                return $this->id;            }            public function getTitre(): ?string            {                return $this->titre;            }            public function setTitre(string $titre): self            {                $this->titre = $titre;                return $this;            }            public function getUrl(): ?string            {                return $this->url;            }            public function setUrl(string $url): self            {                $this->url = $url;                return $this;            }            public function getDesciption(): ?string            {                return $this->desciption;            }            public function setDesciption(?string $desciption): self            {                $this->desciption = $desciption;                return $this;            }            /**             * @return Collection|Salle[]             */            public function getSalles(): Collection            {                return $this->salles;            }            public function addSalle(Salle $salle): self            {                if (!$this->salles->contains($salle)) {                    $this->salles[] = $salle;                    $salle->addSupport($this);                }                return $this;            }            public function removeSalle(Salle $salle): self            {                if ($this->salles->contains($salle)) {                    $this->salles->removeElement($salle);                    $salle->removeSupport($this);                }                return $this;            }            public function getTypedeSupport(): ?TypedeSupport            {                return $this->typedeSupport;            }            public function setTypedeSupport(?TypedeSupport $typedeSupport): self            {                $this->typedeSupport = $typedeSupport;                return $this;            }            public function getMatiere(): ?Matiere            {                return $this->matiere;            }            public function setMatiere(?Matiere $matiere): self            {                $this->matiere = $matiere;                return $this;            }            public function getFilename(): ?string            {                return $this->filename;            }            public function setFilename(?string $filename): Support            {                $this->fileName = $filename;                return $this;             }            /**             * @return null|File             */            public function getSupportFile(): ?File            {                return $this->supportFile;            }             public function setSupportFile(?File $supportFile = null): Support            {                $this->supportFile = $supportFile;                if (null !== $supportFile) {                    // It is required that at least one field changes if you are using doctrine                    // otherwise the event listeners won't be called and the file is lost                    $this->updatedAt = new \DateTimeImmutable();                }                return $this;             }              public function setFileSize(?int $fileSize): void            {                $this->fileSize = $fileSize ;            }            public function getFileSize(): ?int            {                return $this->fileSize;            }        }

here is my 'SupportType' to generate the Form: `

        namespace App\Form;        use App\Entity\Support;        use Symfony\Component\Form\AbstractType;        use Symfony\Component\Form\Extension\Core\Type\FileType;        use Symfony\Component\Form\FormBuilderInterface;        use Symfony\Component\OptionsResolver\OptionsResolver;        class SupportType extends AbstractType        {            public function buildForm(FormBuilderInterface $builder, array $options)            {                $builder                    ->add('titre')                    ->add('supportFile', FileType::class)                    ->add('desciption')                ;            }            public function configureOptions(OptionsResolver $resolver)            {                $resolver->setDefaults(['data_class' => Support::class,                ]);            }        }

and then the configuration File :vich_uploader: db_driver: orm mappings: support_file: uri_prefix: /supports/teste upload_destination: '%kernel.project_dir%/public/supports/teste' namer: vich_uploader.namer_uniqid

the view : <div class="col-md-4"><div class="card text-white bg-primary mb-3"><div class="card-header text-center" style="font-size: 2.3rem;">Modifier le support</div><div class="card-body"><p class="card-text">
{% if error is defined and error %}<div class=" alert alert-danger" style="font-size: 1.3rem;"> {{error}}</div> {% endif %} {% for message in app.flashes('success') %}<div class=" alert alert-success" style="font-size: 1.7rem;"> {{message}}</div> {% endfor %}</p><form method="post" action="" accept-charset="UTF-8"><input type="hidden" name="action" value="users/send-password-reset-email"><div class="form-group"> {{form_row(form.titre)}}</div><div class="form-group"> {{form_row(form.supportFile)}}</div><div class="form-group"> {{form_row(form.desciption)}}</div> {{ form_rest(form) }}<input type="submit" value="{{ button_label|default('Save') }}" class="btn btn-success col-12"></form><br><br></div></div>
</div>

despite the videos and forum i used, i've not found any solution. i need your Helpthanks :-)

Symfony 4 - 3rd-party bundle commands are no longer automatically discovered

$
0
0

According to the documentation, a command class must extend Command or ContainerAwareCommand to be automatically discovered and registered (provided its bundle is registered in the Kernel, of course).

Since Symfony 4+, this discovery doesn't work as expected.

Try this:

composer create-project symfony/skeleton test-maxmind-sf4cd test-maxmind-sf4composer req cravler/maxmind-geoip-bundle dev-masterphp bin/console list

You will notice that:

  • cravler:maxmind:geoip-update is not registered (nothing under a "cravler" namespace
  • Cravler\MaxMindGeoIpBundle\Command\UpdateDatabaseCommand extends ContainerAwareCommand
  • Bundle Cravler\MaxMindGeoIpBundle\CravlerMaxMindGeoIpBundle is registered in config/bundles.php for all environments (auto-generated recipe)

Now when I do exactly the same thing with Symfony 3, everything works properly.

composer create-project symfony/skeleton test-maxmind-sf3 ^3.0cd test-maxmind-sf3composer req cravler/maxmind-geoip-bundle dev-masterphp bin/console list

What's missing there?

Thank you,

Ben

Data Transformer vs.Constraints

$
0
0

I stumbled upon a question regarding Symfony's DataTransformers and how to properly use them. While I know how to implement and add them to my form field, I was wondering how DataTransformers are supposed to be combined with Constraints.

The following code shows my use case.

The Form

<?phpnamespace AppBundle\Form;use AppBundle\Form\DataTransformer\Consent\ConsentTransformer;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\Extension\Core\Type\CheckboxType;use Symfony\Component\Form\Extension\Core\Type\SubmitType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\Validator\Constraints\IsTrue;class ConsentTestForm extends AbstractType{    /** @var ConsentTransformer $consentTransformer */    private $consentTransformer;    /**     * ConsentTestForm constructor.     * @param ConsentTransformer $consentTransformer     */    public function __construct(ConsentTransformer $consentTransformer)    {        $this->consentTransformer = $consentTransformer;    }    /**     * @inheritDoc     */    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder->add('accountConsent', CheckboxType::class, ['constraints' => [                new IsTrue()            ]        ]);        $builder->get('accountConsent')->addModelTransformer($this->consentTransformer);        $builder->add('submit', SubmitType::class);    }}

The Model

<?phpclass User extends Concrete implements \Pimcore\Model\DataObject\DirtyIndicatorInterface{    protected $accountConsent;    /**     * ...     */    public function getAccountConsent () {        // ...    }    /**     * ...     */    public function setAccountConsent ($accountConsent) {        // ...    }}

A lot of code was omitted for the sake of brevity. The model is a Pimcore class.

The DataTransformer

<?phpnamespace Passioneight\Bundle\FormBuilderBundle\Form\DataTransformer\Consent;use Pimcore\Model\DataObject\Data\Consent;use Symfony\Component\Form\DataTransformerInterface;class ConsentTransformer implements DataTransformerInterface{    /**     * @inheritDoc     * @param Consent|null $consent     */    public function transform($consent)    {        return $consent instanceof Consent && $consent->getConsent();    }    /**     * @inheritDoc     * @param bool|null $consented     */    public function reverseTransform($consented)    {        $consent = new Consent();        $consent->setConsent($consented ?: false);        return $consent;    }}

As you can see any submitted value (i.e., null, true, false) will be converted to a Consent and vice-versa.

The Controller

<?phpnamespace AppBundle\Controller;use AppBundle\Form\ConsentTestForm;use AppBundle\Model\DataObject\User;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\Annotation\Route;/** * Class TestController * @package AppBundle\Controller * * @Route("/test") */class TestController extends AbstractFrontendController{    /**     * @Route("/form")     * @param Request $request     * @return Response     */    public function formAction(Request $request)    {        $user = new User();        $form = $this->createForm(ConsentTestForm::class, $user);        $form->handleRequest($request);        if ($form->isSubmitted()) {            if ($form->isValid()) {                p_r("VALID");                p_r($user);            } else {                p_r("NOT VALID");            }        };        return $this->renderTemplate(':Test:form.html.twig', ["form" => $form->createView()        ]);    }}

Note how a new User() is passed as entity in order to automatically populate it with the submitted values.

The View

{{ form(form) }}

The Problem

The form can be built just fine, ultimately, displaying a checkbox with my specified label. Due to the transformer, the checked-state is even correctly displayed, as the transform method converts the Users Consent into a boolean.

However, when submitting the form, an error is displayed, saying that the account-consent is required. While this is fine when it comes to submitting the form without giving consent, it's not quite the desired outcome when acutally consenting.

When consenting, the submitted value is converted to a Consent, which will then hold the value true. But since the transformation is done before the submitted value is validated the beforementioned error is displayed. This happens, because the accountConsent field that was added in the form has a Constraint set, namely, IsTrue. Due to this, the IsTrueValidator validates the Consent (instead of the actually submitted value).

Obviously, the IsTrueValidator cannot know about Pimcore's Consent class.

The Question

All of this leaves me with the question: how do I properly combine the IsTrue-constraint with my ConsentDataTransformer?

Impossible to use Twig Reference from Symfony in override default error template

$
0
0

I overide custom 404 page by creating structuretemplates/bundles/TwigBundle/Exception/error404.html.twig

Like was told here.

But Twig Reference from Symfony not working there. I tried path(), url() and tag trans

Standard twig functions like min() work coretly. I use Symfony 4.4.5

How can I use them in that template??


bug in filter with Symfony 4

$
0
0

I'm creating a filter(for 'offre' entity) by departement ,experience, type(of contract) and a key word all the filters give the right result but experience I don't know why it doesn't respond however I make it alone without the other filter or with the problem I don't know where is the problem because it's a ChoiceType as ('type' attribut (with type of contract I don't have any problem))here is the offreEmploi.php:

`<?phpnamespace App\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;use Cocur\Slugify\Slugify;use App\Entity\Candidat;/** * OffreEmploi * @ORM\Entity */class OffreEmploi{    /**     * @var int     *     * @ORM\Column(name="id", type="integer", nullable=false)     * @ORM\Id     * @ORM\GeneratedValue(strategy="IDENTITY")     */    private $id;    /**     * @var titre     *     * @ORM\Column(name="titre", type="string", length=255)     */    private $titre;    /**     * @var string     *     * @ORM\Column(name="description", type="text", length=0, nullable=false)     */    private $description;    /**     * @var \DateTime     *     * @ORM\Column(name="create_at", type="datetime", nullable=false)     */    private $createAt;    /**     * @var string|null     *     * @ORM\Column(name="experience", type="string", nullable=false)     */    private $experience;    /**     * @var \DateTime     *     * @ORM\Column(name="date", type="date", nullable=false)     */    private $date;    /**     * @var int|null     *     * @ORM\Column(name="remuneration", type="integer", nullable=true)     */    private $remuneration ;    /**     * @var string|null     *     * @ORM\Column(name="remarque", type="text", length=0, nullable=true)     */    private $remarque ;    /**     * @var string|null     *     * @ORM\Column(name="reponse", type="text", nullable=true)     */    private $reponse ;    /**     * @var string|null     *     * @ORM\Column(name="etude_qualification", type="text", nullable=true)     */    private $etudeQualification;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Metier", inversedBy="offreEmplois")     * @ORM\JoinColumn(nullable=false,name="nom_metier",referencedColumnName="nom_metier")     */    private $metier;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Departement", inversedBy="offreEmplois")     * @ORM\JoinColumn(nullable=false,name="code_departement", referencedColumnName="code_departement")     */    private $departement;    /**     * @var string|null     *     * @ORM\Column(name="type", type="string", nullable=false)     */    private $type;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Entreprise", inversedBy="offres")     * @ORM\JoinColumn(nullable=false, name="email", referencedColumnName="email")     */    private $entreprise;    /**     * @ORM\OneToMany(targetEntity="App\Entity\ApplyOffre", mappedBy="offre", orphanRemoval=true)     */    private $applies;    public function __construct()    {        $this->applies = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    public function getTitre():?string    {        return $this->titre;    }    public function setTitre(string $titre): self    {        $this->titre = $titre;        return $this;    }    public function getDescription(): ?string    {        return $this->description;    }    public function setDescription(string $description): self    {        $this->description = $description;        return $this;    }    public function getCreateAt(): ?\DateTimeInterface    {        return $this->createAt;    }    public function setCreateAt(\DateTimeInterface $createAt): self    {        $this->createAt = $createAt;        return $this;    }    public function getExperience(): ?string    {        return $this->experience;    }    public function setExperience(?string $experience): self    {        $this->experience = $experience;        return $this;    }    public function getDate(): ?\DateTimeInterface    {        return $this->date;    }    public function setDate(\DateTimeInterface $date): self    {        $this->date = $date;        return $this;    }    public function getRemuneration(): ?int    {        return $this->remuneration;    }    public function setRemuneration(?int $remuneration): self    {        $this->remuneration = $remuneration;        return $this;    }    public function getRemarque(): ?string    {        return $this->remarque;    }    public function setRemarque(?string $remarque): self    {        $this->remarque = $remarque;        return $this;    }    public function getReponse(): ?string    {        return $this->reponse;    }    public function setReponse(?string $reponse): self    {        $this->reponse = $reponse;        return $this;    }    public function getEtudeQualification(): ?string    {        return $this->etudeQualification;    }    public function setEtudeQualification(?string $etudeQualification): self    {        $this->etudeQualification = $etudeQualification;        return $this;    }    public function getMetier(): ?Metier    {        return $this->metier;    }    public function setMetier(?Metier $metier): self    {        $this->metier = $metier;        return $this;    }    public function getSlug():string{        return (new Slugify())->slugify($this->metier);    }    public function getDepartement(): ?Departement    {        return $this->departement;    }    public function setDepartement(?Departement $departement): self    {        $this->departement = $departement;        return $this;    }    public function getType(): ?string    {        return $this->type;    }    public function setType(?string $type): self    {        $this->type = $type;        return $this;    }    public function getEntreprise(): ?Entreprise    {        return $this->entreprise;    }    public function setEntreprise(?Entreprise $entreprise): self    {        $this->entreprise = $entreprise;        return $this;    }    public function __toString()    {        return $this->getTitre();    }    /**     * @return Collection|ApplyOffre[]     */    public function getApplies(): Collection    {        return $this->applies;    }    public function addApply(ApplyOffre $apply): self    {        if (!$this->applies->contains($apply)) {            $this->applies[] = $apply;            $apply->setOffre($this);        }        return $this;    }    public function removeApply(ApplyOffre $apply): self    {        if ($this->applies->contains($apply)) {            $this->applies->removeElement($apply);            // set the owning side to null (unless already changed)            if ($apply->getOffre() === $this) {                $apply->setOffre(null);            }        }        return $this;    }}

` and here is a part of filterType as form :

'

<?phpnamespace App\Form;    use App\Entity\Departement;    use App\Entity\Domaine;    use App\Entity\Metier;    use App\Entity\Region;    use App\Entity\Type;    use App\searchData\Filter;    use App\searchData\OffreSearchBar;    use App\searchData\OffreSearchSide;    use Doctrine\ORM\EntityRepository;    use Symfony\Bridge\Doctrine\Form\Type\EntityType;    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;    class OffreFilterType extends AbstractType    {        public function buildForm(FormBuilderInterface $builder, array $options)        {            $builder                    ->add('type', ChoiceType::class,['choices' =>['CDI'       =>'cdi','CDD'       =>'cdd','ALTERNANCE'=>'alternance','STAGE'     =>'Stage','CTT'       =>'CTT'>  ],>                 'required'=>false,>                 'multiple'=>true,>                 'expanded'=>true,>                 'label'   =>false>             ])> > >             ->add('experience', ChoiceType::class, [>                 'choices'=>[>                     'tout'=>'tout',>                     '<= 1 ans'=>'<=1 ans',>                     '1 à 3 ans'=>'1 à 3 ans',>                     'de 3 à 6 ans'=>'de 3 à 6 ans',>                     '+ de 5 ans'=>'+ de 5 ans'>                 ],>                 'required' => false,>                 'multiple'=>false,>                 'expanded'=>true,>                 'label' => false,>                 'placeholder'=>false>             ])>         ;>         }>     public function configureOptions(OptionsResolver $resolver)>     {>         $resolver->setDefaults([>             'data_class' => Filter::class,>             'csrf_protection'=>false,>             'method'     =>'get'>         ]);>     } }'and here is the repository:     public function  findSearch(Filter $data){            $query=$this->createQueryBuilder('o');            if($data->metier || $data->motCle || $data->type || $data->departement|| $data->experience){                $query->join('o.metier','m')                    ->join('o.departement','d')                    ->addSelect('m')                    ->addSelect('d')                    //                  ->where('o.metier IN (:m)')                    ->where(                        $query->expr()->andX(                             $query->expr()->andX(                                    $query->expr()->eq('o.metier',':m'),                                    $query->expr()->like('o.titre', $query->expr()->literal('%' . $data->motCle . '%'))                             ),                             $query->expr()->andX(                                    $query->expr()->andX(                                          $query->expr()->eq('o.type',':type'),                                          $query->expr()->in('o.departement', (':d'))                                    ),                                   $query->expr()->andX(                                       $query->expr()->eq('o.experience',':experience')                                   )                             )                         )                    )                    ->setParameter('experience',$data->experience)                    ->setParameter('d',$data->departement)                    ->setParameter('m',$data->metier)                    ->setParameter('type',$data->type);            }           return  $query->getQuery()->getResult();        }    }'

someone can tell me why the when I add the filter(experience) it don't give the right result and when I omet the

  `$query->expr()->andX(       $query->expr()->eq('o.experience',':experience')      )`

it works (it give the right result for the other filter) and even when I add it alone in an other query it give zero result

Attempted to load class "LikeNotificationSubscriber" from namespace "App\EventListener". Did you forget a "use" statement for another namespace?

KnpPaginatorBundle: How to remove "p" parameter from pagination URL?

Attempted to load class "SensioFrameworkExtraBundle" from namespace "Sensio\Bundle\FrameworkExtraBundle" in Symfony 4

$
0
0

I am clone project in Symfony 4 fron git repositories on Windows 10, Xampp with php 7.4, then I run composer install and run migartion, but when I try run the web I obtain error Attempted to load class "SensioFrameworkExtraBundle" from namespace "Sensio\Bundle\FrameworkExtraBundle". Did you forget a "use" statement for another namespace?

When I the same project run in Linux server, the web is running. Why this is not running on Windows?

Symfony 4.2 and Nelmio Api Doc Bundle - Several documentation with multiple Controllers

$
0
0

I'm using Symfony 4 and Nelmio Api Doc Bundle to create a service that will be only accessible trough APIs (both public frontend and private back office will be created using a JS framework)

I need 2 documentations (maybe more later) :

  • /api/doc
  • /admin/doc

Right now I have some Controllers in src/Controllers/Admin and src/Controller/API since they are really different.

I don't understand how to use Nelmio Api Doc Bundle to handle the 2 documentations in 2 differents urls. I know there are areas but I just don't get how to deal with them...

Can someone help me by providing a simple example ?

Thanks

Symfony 4 self-referencing association for recommended article

$
0
0

I have entity article with column title and text. Now I want to add up 3 recommended another articles to each. In documentation I read about doctrine selfrefrencing associtin and I dont know If I use onetomany or manytomany. I have this code

/**     * @ManyToMany(targetEntity="Article", mappedBy="myRecommendation")     */    private $recommended;    /**     * @ManyToMany(targetEntity="Article", inversedBy="recommended")     * @JoinTable(name="recommended",     *      joinColumns={@JoinColumn(name="article_id", referencedColumnName="id")},     *      inverseJoinColumns={@JoinColumn(name="recommend_article_id", referencedColumnName="id")}     *      )     */    private $myRecommendation;

is this association right? And which is owning side? Which is method for adding recommende article?

Integration of API Platform into existing Symfony 4 project

$
0
0

I've got an requirement to integrate API Platform into existing Symfony 4 project. I'm total beginner with API Platform and just learning the basic concepts - but all I found were tutorials to create new API Platform project from scratch. Do you have any links or recommendations for step-by-step tutorials of implementing API Platform in already existing (and running) project?

Thank you in advance for any advice.


Expected response code "250" but got an empty response

$
0
0

I can send my emails in localhost!I get this error

Expected response code "250" but got an empty response.

I don't understand how update .env

# .env# .MAILER_DSN isn't a real address: it's a simple format that offloads most of the configuration work to mailer.MAILER_DSN=sendgrid://KEY@default

works in localhost but not in the hosting site.

I use Symfony 4.4.

Why SMTP mails are not working from server with same hostname as sender mail address?

$
0
0

I have a Symfony 4 application that sends mail with SMTP via OVH (with Swiftmailer). Let say the address i use to send mails is no-reply@domain1.com.

I have two OVH servers with the same configuration, just one is domain1.com and the other is domain2.com. (mail server for addresses @domain1.com is OVH hosted, not on my server)

On both servers i can send mail with command line and both have same firewall configuration.

My application mails works perfectly when i run the app locally on my desktop. It also work perfectly on my second server.

MAILER_URL=smtp://ssl0.ovh.net:587/?username=no-reply@domain1.com&password=aWorkingPassword

But when i run the application on the server 1, mails are not sent but the application seems to work fine. I don't have anything in server mail logs.

Can the fact that the first server has the same configured hostname as the mail address interfere with the SMTP process ?

How to post a nested relation without IRI api-platform

$
0
0

I have 2 entities: Question and Answer where Question has a OneToMany relation Answer. I try to send a JSON with nested document, but the reponse show only data Question without nested Answer.

Follow online, they use IRI to solve to add, but I want to use denormalization to solve it but my code don't work correct

code:

Entity\Question

/** * @ApiResource( *     normalizationContext={"groups"={"question"}}, *     denormalizationContext={"groups"={"question"}}) * @ORM\Entity */class Question{    /**     * @Groups({"question"})     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    private $id;    /**     * @Groups({"question"})     * @ORM\Column     * @Assert\NotBlank     */    public $name = '';    /**     * @Groups({"question"})     * @ORM\OneToMany(targetEntity="Answer", mappedBy="question", cascade={"persist"})     */    private $answers;    public function __construct() {        $this->answers = new ArrayCollection();    }    public function getAnswers()    {        return $this->answers;    }    public function setAnswers($answers): void    {        $this->answers = $answers;    }    public function getName(): string    {        return $this->name;    }    public function setName(string $name): void    {        $this->name = $name;    }    public function getId(): ?int    {        return $this->id;    }}

Entity\Answer

/** * * @ApiResource * @ORM\Entity */class Answer{    /**     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    public $id;    /**     * @Groups({"question"})     * @ORM\Column     */    public $name;    /**     * @ORM\ManyToOne(targetEntity="Question", inversedBy="answers")     */    public $question;    public function getQuestion(): ?Question    {        return $this->question;    }    public function setQuestion(Question $question): void    {        $this->question = $question;    }    public function getName(): ?string    {        return $this->name;    }    public function setName(string $name): void    {        $this->name = $name;    }    public function getId(): ?int    {        return $this->id;    }}

Send a JSON without IRI:

{"name": "string","answers": [    {"name": "string"    }  ]}

and reponse:

Question

{"@context": "/contexts/Question","@id": "/questions/1","@type": "Question","id": 1,"name": "string","answers": []}

Answer:

{"@id": "/answers/1","@type": "Answer","id": 1,"name": "string","question": null}

How can I send JSON to POST without IRI

use an array variable in twig

$
0
0

I got a variable from a controller in the form of an array (variable ads), on twig, I used:

{% for ad in ads%}<tr> <td> {{ad.xxx}} {% if app.user and app.user == ad.author%}{{ad.yyyy}}{% endif%}</td> </tr>{$ endfor%}

there is no problem, it's classic. I want to use for example

{% if app.user and app.user == ad.author%}

just before the for loop, to hide a balise for logged in users but it’s not their announcement

How to test current date condition in behat?

$
0
0

I have feature that is based on current date, and the question is if it is good solution to write if condition in scenario. Simple example: if tested date is equal to current then other field is equal to 0 else equal 10. Meybe there are libraries to mock current date time in symfony 4.

Viewing all 3924 articles
Browse latest View live


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