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

Symfony, update 3.4 => 4.4. Monolog error

$
0
0

I am trying to update a simple web application from Symfony 3.4 to Symfony 4.4.

Eventually I get the following error

>php bin/console debug:configIn ScalarNode.php line 36:Invalid type for path "monolog.handlers.main.channels.elements.0". Expected scalar, but got object. 

I am not sure what that means. Is there some new way to configure Monolog?


Form Collection how to avoid creating duplicate record (OneToMany - ManyToOne)

$
0
0

The problem

I have two entities, one called Question that can be self-referencing, it has an association with QuestionSubQuestions (it was necessary to add some extra fields like filter) so it can have Many questions, but the same questions can be used as children in many Questions. The intention of it is to have a single entity that can have many Children (Questions) and re-using the existing ones.

The problem I'm facing is that when I add an existing Question as a child, it creates a new Question record in the database instead of using the existing record for the association.

I have a web interface where the user can pick form a list of existing questions and add it as a child to the main one. The form POST all the info (including the id of the entity) and doctrine process it by itself.

Everything is saved and removed correctly when adding non-existing questions (new ones) but when picking an existing one makes the mentioned error. But this doesn't happen when the Question gets updated, doctrine persists the existing relations correctly and the create duplicated records don't appear.

Also, the controller doesn't contain anything special, but when dumping the form's data I can see that the added question doesn't have the __isInitialized__ property, so I can guess doctrine doesn't really know that that entity already exist. You can see in the dump (see code section) that child with index 0 has the parameter and the one with index 1 doesn't.

The question

So, how I can fix this? Maybe is there a way to check if the entity exists while processing the form data and attach the entity again to the EntityManager? I know I can make a Listener for that, but I don't know if is a good practice.

Any help will be apreciated.

The actual code

Form data dump:

Question^ {#1535 ▼  -id: 56  -question: "TestB1"  -children: PersistentCollection^ {#1562 ▼    -owner: Question^ {#1535}    -association: array:15 [ …15]    -em: EntityManager^ {#238 …11}    -isDirty: true    #collection: ArrayCollection^ {#1563 ▼      -elements: array:3 [▼        0 => QuestionSubQuestion^ {#1559 ▼          -question: Question^ {#1535}          -subQuestion: Question^ {#1592 ▼+__isInitialized__: true            -id: "57"            -question: "P-1"          }          -filter: "affirmative"        }        1 => QuestionSubQuestion^ {#2858 ▼          -question: Question^ {#1535}          -subQuestion: Question^ {#2863 ▼            -id: "57"            -question: "P-1"          }          -filter: "negative"        }      ]    }    #initialized: true  }}

Question.php

class Question{    /**     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    private $id;    ...    /**     * @var ArrayCollection     * @ORM\OneToMany(targetEntity="QuestionSubQuestion", mappedBy="question", fetch="EAGER" ,cascade={"persist"}, orphanRemoval=true)     */    private $children;    ...    /**     * @param QuestionSubQuestion $children     */    public function addChild(QuestionSubQuestion $children): void    {        if ($this->children->contains($children)) {            return;        }        $children->setQuestion($this);        $this->children->add($children);    }    /**     * @param mixed $children     */    public function removeChild(QuestionSubQuestion $children): void    {        if (!$this->children->contains($children)) {            return;        }        $this->children->removeElement($children);        // needed to update the owning side of the relationship!        $children->setSubQuestion(null);    }}

QuestionSubQuestion.php

class QuestionSubQuestion{    /**     * @ORM\Id     * @ORM\ManyToOne(targetEntity="Question", inversedBy="children", cascade={"persist"})     * @ORM\JoinColumn(nullable=false)     */    private $question;    /**     * @ORM\Id     * @ORM\ManyToOne(targetEntity="Question", cascade={"persist"})     * @ORM\JoinColumn(nullable=false)     */    private $subQuestion;    /**     * @ORM\Id     * @ORM\Column(type="string")     * @ORM\JoinColumn(nullable=false)     */    private $filter;}

Form QuestionType.php

class QuestionType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('question')            ->add('children', CollectionType::class, ['entry_type' => SubQuestionEmbeddedForm::class,'allow_add' => true,'allow_delete' => true,'label' => false,'by_reference' => false,'prototype_name' => '__subQuestion__',            ]);    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(array('data_class' => Question::class,        ));    }}

Embedded form SubQuestionEmbeddedForm.php

class SubQuestionEmbeddedForm extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('subQuestion', SubQuestionType::class)            ->add('filter', HiddenType::class)        ;    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(array('data_class' => QuestionSubQuestion::class,        ));    }}

Edit controller

$question = $questionRepository->find($questionId);$form = $this->createForm(QuestionType::class, $question);$form->handleRequest($request);if ($form->isSubmitted() && $form->isValid()) {    $question = $form->getData();    $questionRepository->save($question);    return $this->redirect($request->getUri());}

AOuth login can't store session token, but userdata is stored correctly in DB with HWIAOuthBundle

$
0
0

I am using HWIAOuthBundle and Custom UserProvider on Symfony 4.4

in MyUserProvider

It stored the access_token and create new user. It works successfully.

namespace App\Security;use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;use HWI\Bundle\OAuthBundle\Security\Core\User\EntityUserProvider;use Doctrine\ORM\EntityManagerInterface;class MyUserProvider extends EntityUserProvider implements OAuthAwareUserProviderInterface {   private $entityManager;   /**   * {@inheritdoc}   */   public function loadUserByOAuthUserResponse(UserResponseInterface $response)   {      $username = $response->getUsername();      $email = $response->getEmail();      $user = $this->em         ->getRepository(\App\Entity\User::class)         ->findOneByEmail($response->getEmail());  //when the user is registrating      if (null === $user) {         $service = $response->getResourceOwner()->getName();         $setter = 'set'.ucfirst($service);         $setter_id = $setter.'Id';         $setter_token = $setter.'AccessToken';      // create new user here         $user = new \App\Entity\User();         $user->$setter_id($username);         $user->$setter_token($response->getAccessToken());         //I have set all requested data with the user's username         //modify here with relevant data      //   $user->setUsername($username);         $user->setEmail($email);         $user->setPassword($username);         $user->setEnabled(true);         $this->em->persist($user);         $this->em->flush();         //$this->userManager->updateUser($user);         return $user;      }    //if user exists - go with the HWIOAuth way      $user = parent::loadUserByOAuthUserResponse($response);      $serviceName = $response->getResourceOwner()->getName();      $setter = 'set' . ucfirst($serviceName) . 'AccessToken';   //update access token      $user->$setter($response->getAccessToken());      return $user;   }}

However even the user is created correctly in Database, but not login-ed

$this->getUser(); in Controller returns null.

enter image description here

So, I am confused that where the user login accomplished???

my setting is below

security:    firewalls:        main:            oauth:                resource_owners:                    facebook:            "/login/check-facebook"                    google:              "/login/check-google"                    twitter:             "/login/check-twitter"                login_path:        /login                use_forward:       false     #          failure_path:      /login                oauth_user_provider:                    service: my.user.provider

services.yml

my.user.provider:    class:        App\Security\MyUserProvider    arguments: ['@doctrine', App\Entity\User , { facebook: facebook_id, twitter: twitter_id, google: google_id }]hwi_oauth:    resource_owners:        facebook:            type:           facebook            client_id:      '%env(FB_ID)%'            client_secret:  '%env(FB_SECRET)%'            scope:          "email user_posts"        google:            type:                google            client_id:           <client_id>            client_secret:       <client_secret>            scope:               "email profile"        twitter:            type:                twitter            client_id:           XXXXXXX            client_secret:       XXXXXX            scope:               "email profile"

Additional

   $token = $this->container->get('security.token_storage')->getToken();   var_dump($token);

There is only annonymous.

object(Symfony\Component\Security\Core\Authentication\Token\AnonymousToken)#664 (6) { ["secret":"Symfony\Component\Security\Core\Authentication\Token\AnonymousToken":private]=> string(7) "QZZau69" ["user":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> string(5) "anon." ["roles":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> array(0) { } ["roleNames":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> array(0) { } ["authenticated":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> bool(true) ["attributes":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> array(0) { } }

So, I think MyUserProvider or somewhere( like AuthenticationListener??) else that should store the token failed.

symfony server:start command throwing an error

$
0
0

I try to run

symfony server:start

It returns an error message

The local web server is already running for this project at port 8000

But lsof -wni tcp:8000 isn't returning anything, I'm sure there isn't any softwares using the port 8000.

Starting by doing

bin/console server:start

is working like a charm.

Symfony 4 Environment variable not found composer install

$
0
0

I'm completly new to Symfony and tried the following guide: https://github.com/thecodingmachine/symfony-vuejs ... but without docker (I have a simple webspace, I can't use docker there).

Now I'm stuck right in the beginning, when calling composer install in the app root. I get the following message:

In EnvVarProcessor.php line 131:    Environment variable not found: "DATABASE_URL".

Well, that sounds easy, I have to setup an enviroment variable ... but I'm not using docker and I don't want to set up a temporarly variable in the shell. Few seconds of google helped me, that I can use .env for my problem like descriped here: https://symfony.com/doc/current/configuration.html#configuration-based-on-environment-variables

In the example project is already a .env file, so I extendet it by DATABASE_URL. But suddenly it is not taking that variable.

I'm working on a macbook with a simple apache/php setup without forther configuration.

What am I missing?

How to change root namespace for Symfony 4 maker bundle?

$
0
0

I'm trying to change the default App namespace to AppBundle (the project uses S4, but the directory structure is still 3.4, currently) for Symfony 4 MakerBundle as instructed here: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html#configuration. It states I need to create a file in config/packages/dev/maker.yaml, but it does not specify what that is relative to? I've tried /app/config/packages/dev/maker.yaml, /config/packages/dev/maker.yaml, /src/AppBundle/Resources/config/packages/dev/maker.yaml, but it seems to just ignore any of those and try to create it in App. I've followed the format of the documentation:

# config/packages/dev/maker.yaml# create this file if you need to configure anythingmaker:    # tell MakerBundle that all of your classes lives in an    # Acme namespace, instead of the default App    # (e.g. Acme\Entity\Article, Acme\Command\MyCommand, etc)    root_namespace: 'AppBundle'

Is it possible to have different database connections per country but with same entities/model on Symfony 4 or 5?

$
0
0

Using Symfony 4 or 5, im trying to have a single app that talks to doctrine through the entity manager transparently using the default EM but changing connection based on locale.

The idea is to some how check the locale on run time and decide for the correct db connection to use for the entire request. That is, $doctrine->getEntityManager() should return a manager with the correct connection both for use on the repositories but also by the firewall handling auth and any other service that connects to DB.

BONUS should be possible when running commands to specify what connection to use.

Details:
- Symfony 4 or greater.
- PHP 7>.
- The same model is used for every country.
- For http requests the locale is in the url.
- The url to all databases are in the env files

My own attempt at this:

If tried extending Doctrine\DBAL\Connection to make a wrapper using doctrines config but have failed to find a way to change all connection settings. (change the URL to master and slave DBs) For both requests and console.

Any help is greatly appreciated

Twig: Unexpected Variable does not exist Error after Sulu CMS upgrade

$
0
0

I have the following (simplified) code, which used to work:

main.html.twig

{% extends "base.html.twig" %}{% set hasContent = content is defined %}{% if hasContent %}    {% set headline = content.headline is defined and content.headline ? content.headline : content.title %}{% endif %}{% block content %}<div class="row">            {% block row %}<section class="col-sm-8 main-content">                    {% if hasContent and headline is defined%}<h1 class="headline" property="title">{{ headline }}</h1>                    {% endif %}

Now I get the following error for this line {% if hasContent and headline is defined%}: Variable "hasContent" does not exist. (main.html.twig line 43)

It feels like as if {% block content %} is now it's own scope and has no access anymore to variables defined outside of it...

Has anybody encountered this before and knows how to get arround it?

My setup is the following:

  • sulu 2.0 (cms based on symfony 4), upgraded from sulu 1.6 - version 2.0.6
  • symfony/twig-bridge - version 4.4.7
  • symfony/twig-bundle - version 4.4.7
  • sulu/theme-bundle - version 2.0.0
  • liip/theme-bundle - version 1.7.0
  • twig - version 2.12.5

Symfony controller always returns response. How to handle a web beacon?

$
0
0

I've used symfony for many applications, and understand the Controller request->response model. I am implementing a javascript based web beacon that sends a POST to a url handled by my symfony application, with a payload of data. There is no response required or accepted for the web beacon request. It is a one-way deal, kind of like logging.

How can this be implemented in Symfony? I need to accept a request, access the database (I use doctrine) but NOT provide a response!

Symfony 4. Parameters for custom service

$
0
0

I've created a service MailService. Where is the right place for the service configuration? Is it the file services.yml? If I write

App\Service\MailService:      someparam: somevalue

I get the error message The configuration key someparam is unsupported for definition App\Service\MailService.How to configure the service properly? How to read the params within my service?

class MailService{    public function __construct()    {    }}

How do I deserialize a nested JSON object using JMS and Symfony?

$
0
0

I'm trying to deserialize some JSON into a plain old PHP object using JMS via Symfony 4.4 (LTS).

The JSON looks something like this:

{"id": "c9cde632-ca23-4ed0-8b6d-05dfcbf1d994","someProperty": "This is the value","active": true,"nestedProperty": {"id": "78d46fb8-5f1a-4a00-89a6-4b96482b9ef6","name": "The Name"    }}

I have a PHP class that looks something like:

<?phpclass NestedExample{    /** @var string $id */    private $id;    /** @var string $someProperty */    private $someProperty;    /** @var bool $active */    private $active;   // Fluent Getters and Setters   // ...}

And this correctly deserializes the above fields into the object.

However, I want to get the nested object values into this class as well, by doing something like:

/** @var string $nestedPropertyId */private $nestedPropertyId;/** @var string $nestedPropertyName */private $nestedPropertyName;

Or maybe even:

private $nestedProperty;// Fluent Getter and Setter for $nestedProperty/** @VirtualProperty("nestedPropertyId") */public function getNestedPropertyId () {    return $this->getNestedProperty()->id;}

But nothing works.

Am I doing it wrong? I never intend to serialize this class back into JSON. The transformation will always be one way.

Class could not be determined for Controller identified by

$
0
0

I get this error:

Class could not be determined for Controller identified by "FillFormBundle\Controller\ApiLoginController".

./config/routing_api.yml:

fillform:    type: rest    resource: "@FillFormBundle/Resources/config/routing.yml"    prefix:   /

./src/FillFormBundle/Resources/config/routing.yml:

fillform_login:  type: rest  resource: "@FillFormBundle/Controller/ApiLoginController.php"  name_prefix: api_fillform_form:  type:        rest  resource:    "@FillFormBundle/Controller/Form/FormRestController.php"  name_prefix: api_

./src/FillFormBundle/Resources/config/services.yml:

services:   _defaults: { public: true }  fillform.login:    class: FillFormBundle\Controller\ApiLoginController  fillform.form:    class: FillFormBundle\Controller\Form\FormRestController    arguments: ['@request_stack']    calls:      - [setContainer, ['@service_container']]      - [setObjectClass, ['Form', 'FormFillBundle:Form']]      - [setForm, ['Form', '@fillform.form_form']]  fillform.form_form:    class: FillFormBundle\Form\FormType    arguments:      - '@service_container'      - 'FormFillBundle:Form'

My directory structure is:

./src/FillFormBundle/Controller

Doctrine Add column onSchemaCreateTable Event

$
0
0

I have some ManyToMany table relations.I'd like those to have a "created_at" field set when INSERT INTO.

Following Symfony and Doctrine Documentation, i tired this :

app/config/services_dev.yaml

[...]    App\Event\Listener\ManyToManyListener:        tags:            - { name: doctrine.event_listener, event: onSchemaCreateTable }

app/src/Event/Listener/ManyToManyListener.php

[.....]class ManyToManyListener implements EventSubscriber{    public function getSubscribedEvents()    {        return ['onSchemaCreateTable'];    }    public function onSchemaCreateTable(SchemaCreateTableEventArgs  $event)    {        $columns = $event->getTable()->getColumns();        if (count($columns) <= 2 && !array_key_exists("created_at", $columns)) {            $tableName = $event->getTable()->getName();            $sql = "ALTER TABLE $tableName ADD COLUMN created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP;";            $event->addSql($sql);              //dump($sql);        }    }}

I can dump my SQL code inside, it works.

I also tried this code (inside the if statement)

$event->getTable()->addColumn("created_at","datetime",                ["default" => "CURRENT_TIMESTAMP"]            );

This never execute the SQL statement.For example, while php bin/console doctrine:schema:update --dump-sql, I can't see my query.

Loading Fixtures fails in behat tests

$
0
0

When I try load fixtures in behat by:

     /**     * @BeforeScenario @fixtures     */    public function loadFixtures()    {        $loader = new ContainerAwareLoader($this->kernel->getContainer());        $loader->loadFromDirectory(__DIR__.'/../../src/DataFixtures');        $executor = new ORMExecutor($this->getEntityManager());        $executor->execute($loader->getFixtures(), true);    }

It fails in UserFixture and gives following error:

╳  Type error: Too few arguments to function App\DataFixtures\UserFixtures::__construct(), 0 passed in vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Loader.php on line 231 and exactly 2 expected (Behat\Testwork\Call\Exception\FatalThrowableError)

It fails in constructor of UserFixture which use Dependency injection:

    private $passwordEncoder;    private $userImageManager;    public function __construct(UserPasswordEncoderInterface $passwordEncoder, ImagesManagerInterface $userImageManager)    {        $this->passwordEncoder = $passwordEncoder;        $this->userImageManager = $userImageManager;    }

For me it looks like kernel doesn't see that services.Of course without that one fixture others works fine and if I run all fixtures from command line it works too. Someone can help me find solution?? Thanks a lot for any reply.

Visual Studio Code PHP Intelephense get errors wich aren't

$
0
0

I'm working on a Symfony 4 project using Visual Studio Code with Intelephense.

Intelephense gets errors which aren't. There are some examples :

Undefined method 'uasort'.

This error corrsponding to this code :

            // Collection creation of seasons used in the periods         $seasons = new ArrayCollection();        $sortedSeasons = new ArrayCollection();        //Search seasons used by periods        foreach ($advert->getPeriods() as $period)         {            $season = $period->getSeason();            if (! $seasons->contains($season))             {                $seasons->add($season);            }        }        // Sort seasons by ascending cost         $iterator = $seasons->getIterator();        $iterator->uasort(function ($a, $b) {            return $a->getCost() <=> $b->getCost();        });

An other example :

Undefined method 'getAdvertMinPrice'.

$minPrices = $this->getDoctrine()->getRepository(Price::class)->getAdvertMinPrice($advert);

However, the method exists in the PriceRepository :

<?phpnamespace App\Repository\advert;use App\Entity\advert\Price;use Symfony\Bridge\Doctrine\RegistryInterface;use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;/** * @method Price|null find($id, $lockMode = null, $lockVersion = null) * @method Price|null findOneBy(array $criteria, array $orderBy = null) * @method Price[]    findAll() * @method Price[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */class PriceRepository extends ServiceEntityRepository{    public function __construct(RegistryInterface $registry)    {        parent::__construct($registry, Price::class);    }   /**     * Get the minimum price from an advert     *     * @param [type] $advert     * @return Price[]     */     public function getAdvertMinPrice($advert): array    {        return $this->createQueryBuilder('p')            ->andWhere('p.price = (                                    SELECT MIN(p2.price)                                    FROM ' . $this->_entityName . ' p2                                    WHERE p2.advert = :val                                  )'                      )            ->setParameter('val', $advert)            ->getQuery()            ->getResult()        ;    }}

There is the Price name space :

<?phpnamespace App\Entity\advert;use App\Entity\advert\Advert;use App\Entity\advert\Period;use App\Entity\backend\Season;use App\Entity\backend\Duration;use Doctrine\ORM\Mapping as ORM;use Doctrine\Common\Collections\Collection;use Doctrine\Common\Collections\ArrayCollection;use Symfony\Component\Validator\Constraints as Assert;use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;/** * @ORM\Entity(repositoryClass="App\Repository\advert\PriceRepository") *  * @UniqueEntity( *     fields={"duration", "season"}, *     message="A price already exists for this season and this duration." * ) */class Price{

And the use command in the file where I have the problem :

<?phpnamespace App\Controller\advert;use App\Entity\backend\VAT;use App\Entity\advert\Price;

I don't understand where is the problem. I have searched for days without result.

Somebody would have an idea about this problem origin?

Thank you by advance for your help.


Use query_builder on CollectionType in symfony4 forms?

$
0
0

In a symfony 4 form, I need to use something like a query_builder option that is available on EntityType but from a CollectionType. There is a similar question here with no good answers.

In my project, each Site entity has many Goal. Each Goal has a numeric goal and a specific date. I'd like to edit the goals of a site for a specific date only. The problem is that a CollectionType form pulls all goals to show in the form, but I only want to pull the goals for a given date. How? There is no query_builder on a CollectionType like there is on an EntityType. I could change the getter in my Site entity, but I don't know how to pass the needed date to my getter.

For now my work-around is to render the entire form (with ALL associated goals for a given site), and then use some javascript to hide all goals except those with the date to edit. This works, but it's a terrible solution for sites with lots of goals spanning a range of dates.

My Site entity (only relevant code is shown):

class Site{    public function __construct()    {        $this->goals = new ArrayCollection();    }    /** @ORM\OneToMany(targetEntity="App\Entity\Goal", mappedBy="site") */    private $goals;    public function getGoals()    {        return $this->goals;    }}

and my related Goal entity:

class Goal{    /** @ORM\Column(type="date") */    private $goalDate;    /** @ORM\Column(type="integer") */    private $goal;    /** @ORM\ManyToOne(targetEntity="App\Entity\Site", inversedBy="goals") */    private $site;    // ...}

My forms:

class SiteGoalsAdminForm extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('goals', CollectionType::class, ['entry_type' => GoalsEmbeddedForm::class,            ]);    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => Site::class        ]);    }}

and the individual goal form:

class GoalsEmbeddedForm extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('goal', IntegerType::class)            ->add('goalDate', DateType::class);    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => Goal::class,        ]);    }}

Dynamic Form Modifications In An Edit Page

$
0
0

RE: https://symfony.com/doc/current/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms

I've followed the guide above (with customizations) however I'm running into an issue that I haven't been able to pinpoint. It works when creating a New Task, but not in Edit Task.

The error is "Uncaught PHP Exception Symfony\Component\PropertyAccess\Exception\InvalidArgumentException: "Expected argument of type "int", "null" given at property path "direction"." at C:...\vendor\symfony\property-access\PropertyAccessor.php line 198"

TaskController.php

/** * @Route("/new", name="task_new", methods={"GET","POST"}) */public function new(Request $request): Response{    $task = new Task();    $form = $this->createForm(TaskType::class, $task, ['action' => $this->generateUrl('task_new'),    ]);    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $entityManager = $this->getDoctrine()->getManager();        $entityManager->persist($task);        $entityManager->flush();        return $this->redirectToRouteWithAjaxSupport($request, 'task_index');    }    return $this->render('task/new.html.twig', ['task' => $task,'form' => $form->createView(),    ]);}/** * @Route("/{id}/edit", name="task_edit", methods={"GET","POST"}) */public function edit(Request $request, Task $task): Response{    $form = $this->createForm(TaskType::class, $task, ['action' => $this->generateUrl('task_edit', ['id' => $task->getId(),        ]),    ]);    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $this->getDoctrine()->getManager()->flush();        return $this->redirectToRouteWithAjaxSupport($request, 'task_index');    }    return $this->render('task/edit.html.twig', ['task' => $task,'form' => $form->createView(),    ]);}

TaskType.php

class TaskType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('direction', ChoiceType::class, ['required' => true,'choices' => ['Not applicable' => 0,'Incoming' => 1,'Outgoing' => 2,                ],            ])            ->add('associationType', ChoiceType::class, ['mapped' => false,'required' => true,'choices' => ['Contact' => 'Contact','Customer' => 'Customer','Supplier' => 'Supplier',                ],            ])        ;        $builder->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'onPreSetData']);        $builder->get('associationType')->addEventListener(FormEvents::POST_SUBMIT, [$this, 'onPostSubmitAssociationType']);    }    private function getFormModifier()    {        return function (FormInterface $form, $associationType = null) {            $this->addAssociationWithField($form, $associationType);        };    }    private function addAssociationWithField(FormInterface $form, $associationType)    {        if (in_array($associationType, ['Contact', 'Customer', 'Supplier'])) {            $form->add('associationWith', EntityType::class, ['class' => 'App\\Entity\\'.$associationType.'\\'.$associationType,'mapped' => false,'required' => true,            ]);        } else {            $form->add('associationWith', ChoiceType::class, ['mapped' => false,'required' => false,'disabled' => true,            ]);        }    }    public function onPreSetData(FormEvent $event)    {        $task = $event->getData();        $formModifier = $this->getFormModifier();        $formModifier($event->getForm(), $task->getAssociationType());    }    public function onPostSubmitAssociationType(FormEvent $event)    {        $associationType = $event->getForm()->getData();        $formModifier = $this->getFormModifier();        $formModifier($event->getForm()->getParent(), $associationType);    }}

_form.html.twig

<script>    var $associationType = $('#task_associationType');    $associationType.change(function() {        var $form = $(this).closest('form');        var data = {};        data[$associationType.attr('name')] = $associationType.val();        $.ajax({            url : $form.attr('action'),            type: $form.attr('method'),            data : data,            success: function(html) {                $('#task_associationWith').replaceWith(                    $(html).find('#task_associationWith')                );            }        });    });</script>

declare form_theme once for several forms Twig

$
0
0

I have three forms on a twig: form1, form2 and form3. Is there a way to import my custom theme once?

I mean, now i have this

{% form_theme form 'customTwigForms.html.twig' %}{% form_theme form2 'customTwigForms.html.twig' %}{% form_theme form3 'customTwigForms.html.twig' %}

and i want somthing like

{% form_theme form1, form2, form3 'editDefaultsTwigForms.html.twig' %}

i`m using symfony 4.4 and twig v2

How to change input "id" in FormType.php Symfony 4

$
0
0

I have tried to change the attr "id" in a FormType.php file :

->add('content', TextareaType::class,(['label' => "Description détaillée",'attr' => ['placeholder' => "Donnez une description qui donne vraiment envoe de venir chez vous !",'id' => "test_id"                ]            ]))

NB : I WANT TO CHANGE ONLY THE "ID"

Thank you

TWIG form template: call variable in attr

$
0
0

In a twig form template in Symfony 4 app I need to have an attribute with a variable.

Exemple:

{{ form_widget(myform.field, {'attr': {'class': 'bidding-slider','data-slider-value': '800'}}) }}

I need to put a variable in 'data-slider-value' instead of a manual value.

I tried :

{{ form_widget(myform.field, {'attr': {'class': 'bidding-slider','data-slider-value': '{{ variable }}'}}) }}

but it do not work...

{{ variable }} alone return well the value I need to put in 'data-slider-value'.

Second tried:

I have Extended form class 'TextType' method buildView.To do that I added this file : src/Form/Extension/TextTypeExtension.php

// src/Form/Extension/TextTypeExtension.phpnamespace App\Form\Extension;use Symfony\Component\Form\AbstractTypeExtension;use Symfony\Component\Form\Extension\Core\Type\FileType;    class TextTypeExtension extends AbstractTypeExtension{    /**     * Return the class of the type being extended.     */    public static function getExtendedTypes(): iterable    {        // return FormType::class to modify (nearly) every field in the system        return [TextType::class];    }    public function buildView(FormView $view, FormInterface $form, array $options)    {    $tjm = $form->get('dailyrate')->getData();    $view->vars['attr']['data-slider-value'] = $tjm;    }}

But now I am not sure of the way to use that in my form template...

Thank you very much for helping me.

Alex

Viewing all 3925 articles
Browse latest View live


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