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

An exception has been thrown during the rendering of a template ("Asset manifest file "../manifest.json" does not exist.")

$
0
0

I cloned a Symfony 4 web application (which work on the server) to a fresh installed VM, but after installing all the packages, I get this error message :

An exception has been thrown during the rendering of a template ("Asset manifest file "/var/www/html/kyc/htdocs/public/build/manifest.json" does not exist.").

I tried this solution without success :

Symfony Error: "An exception has been thrown during the rendering of a template"

Any idea ?

Thank you.


How to update roles in security token in Symfony 4 without re-logging in

$
0
0

I'm trying to update User's roles after the user confirms its phone number.

I make the update in the database:

$user->setRoles(["ROLE_USER"]);
$em->persist($user);

That works fine and updates the users's role in the database. (Before, users have "ROLE_UNACTIVATED" group).

However, it doesn't update the user's roles in the session (security token), so the user needs to logout and then log in one more time.

So, the question is how to update User's roles in security token?

MyPOS Checkout usingSymfony

$
0
0

Actually im about to configure myPOS Checkout with my somfony 4 project but their documentation about the configuration not that clear have no idea from where to begin. If anyone can help it would be a big favour. Thanks All

Image upload with sonata admin

$
0
0

See EDIT above

I think the issue is pretty simple to solve but I can't find any clear answer right now. I hope you might have an idea.

I'm trying to upload an image with sonata admin.

In my entity I have this field

/**
 * @ORM\Column(type="string", length=2000)
 * @Assert\File(mimeTypes={ "image/png", "image/jpeg" })
 */
private $image;

When I go to the sonata admin form view. The button Upload file is there and defined as below

$formMapper->add('image', FileType::class);

But when I try to send the form, I'm getting this error

The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Symfony\Component\HttpFoundation\File\File.

I hint this is due to the doctrine string type. But I don't think doctrine has a "File" type.

Thanks for your help.

EDIT:

Considering the link provided in comment, here is the new error

The current field image is not linked to an admin. Please create one for the target entity : ``

<?php

  namespace App\Entity;
  // src/Entity/Image.php

  class Image{
  const SERVER_PATH_TO_IMAGE_FOLDER = '/public/images';

  /**
   * Unmapped property to handle file uploads
   */
  private $file;

  /**
   * @param UploadedFile $file
   */
  public function setFile(UploadedFile $file = null)
  {
      $this->file = $file;
  }

  /**
   * @return UploadedFile
   */
  public function getFile()
  {
      return $this->file;
  }

  /**
   * Manages the copying of the file to the relevant place on the server
   */
  public function upload()
  {
      // the file property can be empty if the field is not required
      if (null === $this->getFile()) {
          return;
      }

     // we use the original file name here but you should
     // sanitize it at least to avoid any security issues

     // move takes the target directory and target filename as params
     $this->getFile()->move(
         self::SERVER_PATH_TO_IMAGE_FOLDER,
         $this->getFile()->getClientOriginalName()
     );

     // set the path property to the filename where you've saved the file
     $this->filename = $this->getFile()->getClientOriginalName();

     // clean up the file property as you won't need it anymore
     $this->setFile(null);
 }

 /**
  * Lifecycle callback to upload the file to the server.
  */
 public function lifecycleFileUpload()
 {
     $this->upload();
 }

 /**
  * Updates the hash value to force the preUpdate and postUpdate events to fire.
  */
 public function refreshUpdated()
 {
    $this->setUpdated(new \DateTime());
 }

 // ... the rest of your class lives under here, including the generated fields
 //     such as filename and updated
 }

In my ForumAdmin, now I have

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper->add('name', TextType::class);
    $formMapper->add('description', TextAreaType::class);
    $formMapper->add('weight', IntegerType::class);
    $formMapper->add('category', EntityType::class, [
        'class' => Category::class,
        'choice_label' => 'name',
    ]);
    $formMapper
        ->add('image', AdminType::class)
    ;
}

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper->add('name');
    $datagridMapper->add('category');
}

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper->addIdentifier('name');
    $listMapper->addIdentifier('description');
    $listMapper->addIdentifier('category');
    $listMapper->addIdentifier('weight');
    $listMapper->addIdentifier('createdAt');
    $listMapper->addIdentifier('updatedAt');
    $listMapper->addIdentifier('image');
}

public function prePersist($object)
{
    parent::prePersist($object);
    $this->manageEmbeddedImageAdmins($object);
    if($object instanceof Forum){
        $object->setCreatedAt(new \DateTime('now'));
        $object->setUpdatedAt(new \DateTime('now'));
        $object->setStatus("NO_NEW");
    }

}

public function preUpdate($page)
{
    $this->manageEmbeddedImageAdmins($page);
}

private function manageEmbeddedImageAdmins($page)
{
    // Cycle through each field
    foreach ($this->getFormFieldDescriptions() as $fieldName => $fieldDescription) {
        // detect embedded Admins that manage Images
        if ($fieldDescription->getType() === 'sonata_type_admin'&&
            ($associationMapping = $fieldDescription->getAssociationMapping()) &&
            $associationMapping['targetEntity'] === 'App\Entity\Image'
        ) {
            $getter = 'get'.$fieldName;
            $setter = 'set'.$fieldName;

            /** @var Image $image */
            $image = $page->$getter();

            if ($image) {
                if ($image->getFile()) {
                    // update the Image to trigger file management
                    $image->refreshUpdated();
                } elseif (!$image->getFile() && !$image->getFilename()) {
                    // prevent Sf/Sonata trying to create and persist an empty Image
                    $page->$setter(null);
                }
            }
        }
    }
}

I also have this ImageAdmin even if I don't see why it would be usefull

final class ImageAdmin extends AbstractAdmin{
protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('image', FileType::class);
}

public function prePersist($image)
{
    $this->manageFileUpload($image);
}

public function preUpdate($image)
{
    $this->manageFileUpload($image);
}

private function manageFileUpload($image)
{
    if ($image->getFile()) {
        $image->refreshUpdated();
    }
}

// ...
}

Need documentation : How to create custom formType from EntityType ? (can't find anything similar in Symfony Documentation)

$
0
0

I 'm trying to create a custom formType From an Entity with 1 checkbox, 2 labels and 1 text field :

Something like that :

[ ] My label : My label 2 [__________]

So, I create a class CheckboxWithDetailsType extended from abstractType and add function getParent() wich return EntityType::class (because the labels are in database) and configure option with 'compound' => true.

Then, I call my CheckboxWithDetailsType in a form ->add('myField',CheckboxWithDetailsType::class, ["query_builder" ... "choice_label"=>function(....

All labels and checkbox are displayed fine (like a standard EntityType).

And now... I need to get parameters from my Entity to get the second label, the text field reference etc...

My question : Can you give me link of documentation or similar example of what I 'm trying to do ? (I can't find anything like that in documentation and I believe that I'm in the wrong way to create this kind of custom formType !)

Problem with Command line symfony version 4.12.4

$
0
0

When I use the symfony new project command, the terminal answers me that it is done and that the project is ready but I have absolutely no files created, it worked before the update ... Do you have a solution?

my command symfony version is 4.12.4 my php version is 7.3.5

thank you!

how to configure knp_snappy bundle to generate a different page format

$
0
0

I'm working on an app using Symfony 4 , i encounter a problem while doing the print function or the generation of the Pdf from html for different format, my app does release bills using a controller action with the help of Knp_snappy ,
i have configure the knp snappy to generate a A4 page pdf and its working great no problem at this stage, now i have another controller action that release a receipt for each bill paid and that's where I'm stuck , i can't reconfigure the knp_snapp and adjust the format for the appropriate size of the receipt which is 9cm also i don't want to print a receipt on a big page as A4.
So, I'm wondering is there a way to override the knp_snappy in yaml file on the action controller when i attempt to release a receipt ?

Thank you,

Designing and Tuning Website with Many Data Sources [closed]

$
0
0

I work in Identity & Access Management and routinely produce web-based tools for viewing and managing identity data. The data sources I use are many and varied: Oracle, LDAP, AD and other services/applications with REST, SOAP, etc. I regularly reference combinations of these sources to produce a single page. The problem is that the user's browser just spins while the controller serially goes to each source to gather the data.

Here's what I've gone through so far:

  • Import non-Oracle data into Oracle. In other words, have cron jobs which periodically copy data into Oracle. This would work nicely, except that the data usually needs to be realtime.
  • Use browser concurrency. The pages loads, and the browser's ability to make asynchronous calls can load from each source by separating out the responsibility in the controller from one monolithic method to one for each source, or each specific data request. This is what I'm currently trying. It's OK. But I don't like the UX. The page loads with spinners going wild while waiting for each AJAX call to return.
  • Use controller concurrency This should load as quick the AJAX-based solution but would keep the page from being a spinner farm. It's been quite a while since I've used concurrency (outside of AJAX), and have never done so in the platform behind my current major application (Symfony PHP, and so, pthreads).

Is there a magic bullet for such situations? How have you resolved similar situations in your experience?


Symfony Validator: validate by comparing the old value from the DB

$
0
0

I'm working with Symfony 4.4,

For security reason, when submitting OrderProduct entity that embedd Product entity, I have to control some values of OrderProduct taken from Product.

So, it's an Symfony API, I receive an orderProduct in a JSON format:

{
   "product" : { "id" : 82 },
   "price" : 9.7,
   "quantity": 3,
   //...
}

I have to get the product from the database, to test if the price is correct.

OrderProduct Entity:

Symfony 4 + Sonata Admin - No metadata found for property in inherited property

$
0
0

I've got an error for some time now when I try to add filters to an Admin. There are two entities: Client and Order.

In the OrderAdmin file, the following filters work:

$datagridMapper
    ->add('id')
    ->add('client.email')
    ->add('client.id')
;

But if I add this line ->add('client.name') it triggers this error:

No metadata found for property `App\Entity\Order::$client.name. Please make sure your Doctrine mapping is properly configured.

The Client entity is inherited by two others entities. Both of them contain the property name. While the id and email are both present in the parent entity. I'm guessing this is why the error appears:

* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="type", type="string")
* @ORM\DiscriminatorMap({"user_1" = "one", "user_2" = "two"})

This used to work fine on previous versions. Any idea of how to solve the problem? (Transferring the name property to the parent class isn't really a solution for me).

Integrating Gitlab giving authentication issue in symfony

$
0
0

I am trying to implement Gitlab authentication in my Symfony project. These are the list of my files.

GitlabAuthController.php

/**
 * Class GitlabAuthController.
 * @Route("/api")
 */
class GitlabAuthController extends AbstractController
{
    /**
     * Link to this controller to start the "connect" process.
     *
     * @Route("/connect/gitlab", name="connect_gitlab_start")
     *
     * @param ClientRegistry $clientRegistry
     *
     * @return RedirectResponse
     */
    public function connectAction(ClientRegistry $clientRegistry): RedirectResponse
    {

        // will redirect to gitlab!
        return $clientRegistry
            ->getClient('gitlab') // key used in config/packages/knpu_oauth2_client.yaml
            ->redirect()
            ;
    }

security.yaml

security:
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        app_user_provider:
            id: App\Security\UserProvider
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: lazy

    access_control:
        - { path: ^/api/connect, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: ROLE_USER }

But I am receiving following error:

Full authentication is required to access this resource.

Can anybody please help me fix this issue.

Thank You.

Problem on Symfony Mailer with SMTP and certificate ssl not valid

$
0
0

Symfony version(s) affected: 4.4.3

Mailer component (not swiftmailer)

Description i try to send a mail on the SMTP server but this one don't have a certicate valid. So How to disable the ssl ?

How to reproduce the error :

Warning: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed

Install twig/extensions on a Symfony 4 or Symfony 5 new project

$
0
0

I'm preparing to migrate a huge website from Symfony 3.4 to Symfony 4.4. To do this, I'm starting from a new fresh installation of Symfony 4.4, and as the intial project requires the use of Twig Extensions I try to install it on this new Symfony 4.4 project. But composer indicates Your requirements could not be resolved to an installable set of packages.

The error message is obvious, but I don't understand why this situation happens on a fresh symfony 4.4 project.

What I tried :

  • I create a new Symfony symfony new --full --version=lts testproject that installed Symfony 4.4 and right after composer require twig/extensions =>Your requirements could not be resolved to an installable set of packages.

  • I create a new Symfony symfony new --full testproject that installed Symfony 5.0 and right after composer require twig/extensions =>Your requirements could not be resolved to an installable set of packages.

  • I tried with Symfony flex but same problem =>Your requirements could not be resolved to an installable set of packages.

    • I retried after clearing the composer cache but no change.

This worked : - I create a new Symfony symfony new --full --version=3.4 testproject that installed Symfony 3.4 and right after composer require twig/extensions => OK

I understand that dependencies conflits occur for Symfony 4.4 and more, but according to Symfony doc How to Write a custom Twig Extension no further actions are required and it should work.

What I'm missing ? Does someone faced the same problem ? Thanks

How are Symfony services private by default?

$
0
0

From the official release, Symfony services are private by default. But when I run debug command on my Symfony-4.4 container:

bin/console debug:container

It still lists a lot of Symfony framework built-in services as public.

Does this private/public feature not apply to command line operations?

There is no user provider for user, symfony 3.4.37

$
0
0

Since the upgrade to Symfony 3.4.37, I'm having this issue

There is no user provider for user "Mybundle\Myuser".

With version 3.4.36 and previous, it was working fine.

security.yml

security:
  providers:
    myprovider:
        id: myuser.provider

services.yaml

myuser.provider:
    class: Mybundle\MyUserProvider
    public: true
    arguments: 
        - '@arg1'
    tags:
        - { name: monolog.logger, channel: app.oneid.provider }

Any idea on how to fix this issue?

Edit: The support class of my user provider:

public function supportsClass($class)
{
    return MyUserProvider::class === $class;
}

Symfony - duplicate entity object setting

$
0
0

I am targeting all entity objects from one table to fill the other with the same data.

I want to set results that I have found in CardBalances table to Balances tablefind by the same card_id in first table.

I wrote method but it throws error:

"Call to a member function setBalance() on array" (error for all objects)

The closest that I get is:

$newBalance = null;

    $existingBalances = $this->getCardBalanceRepository()->findBy(['gpsCard' => $gpsCard]);

    foreach ($existingBalances as $balance) {

        $id = $gpsCard->getId();

        if(isset($id)) {
            $newBalance = $existingBalances;
        } else {
            $newBalance = new Balance();
            $this->em->persist($newBalance);
        }

        $newBalance->setBalance($balance->getBalance());
        $newBalance->setCurrency($balance->getCurrency());
        $newBalance->setisMain($balance->getisMain());
    }

    $this->em->flush();

I want to set data if they are not in the database, and if are to update existing.

Migrate to docker desktop 2.2 generate acl errors

$
0
0

Description:

One of my team member has migrate docker desktop to version 2.2.
Since, the php service won't start due to setfacl command from an entrypoint.sh.

Context:

We are working on a api-platform project in version 2.4.7.

Php Dockerfile:

# the different stages of this Dockerfile are meant to be built into separate images
# https://docs.docker.com/develop/develop-images/multistage-build/#stop-at-a-specific-build-stage
# https://docs.docker.com/compose/compose-file/#target


# https://docs.docker.com/engine/reference/builder/#understand-how-arg-and-from-interact
ARG PHP_VERSION=7.3
ARG NGINX_VERSION=1.15
ARG VARNISH_VERSION=6.0


# "php" stage
FROM php:${PHP_VERSION}-fpm-alpine AS api_platform_php

RUN  apk add --no-cache --virtual .build-deps $PHPIZE_DEPS icu-dev openldap-dev && \
    docker-php-ext-install ldap  && \
    docker-php-ext-enable ldap && \
    apk del .build-deps


# persistent / runtime deps
RUN apk add --no-cache \
        acl \
        file \
        gettext \
        git \
    ;

ARG APCU_VERSION=5.1.17
RUN set -eux; \
    apk add --no-cache --virtual .build-deps \
        $PHPIZE_DEPS \
        icu-dev \
        libzip-dev \
        zlib-dev \
    ; \
    \
    docker-php-ext-configure zip --with-libzip; \
    docker-php-ext-install -j$(nproc) \
        intl \
        pdo_mysql \
        zip \
    ; \
    pecl install \
        apcu-${APCU_VERSION} \
    ; \
    pecl clear-cache; \
    docker-php-ext-enable \
        apcu \
        opcache \
    ; \
    \
    runDeps="$( \
        scanelf --needed --nobanner --format '%n#p' --recursive /usr/local/lib/php/extensions \
            | tr ',''\n' \
            | sort -u \
            | awk 'system("[ -e /usr/local/lib/" $1 " ]") == 0 { next } { print "so:" $1 }' \
    )"; \
    apk add --no-cache --virtual .api-phpexts-rundeps $runDeps; \
    \
    apk del .build-deps

COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
RUN ln -s $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini
COPY docker/php/conf.d/api-platform.ini $PHP_INI_DIR/conf.d/api-platform.ini

# https://getcomposer.org/doc/03-cli.md#composer-allow-superuser
ENV COMPOSER_ALLOW_SUPERUSER=1
# install Symfony Flex globally to speed up download of Composer packages (parallelized prefetching)
RUN set -eux; \
    composer global require "symfony/flex" --prefer-dist --no-progress --no-suggest --classmap-authoritative; \
    composer clear-cache
ENV PATH="${PATH}:/root/.composer/vendor/bin"

WORKDIR /srv/api

# build for production
ARG APP_ENV=prod
ARG TRUSTED_HOSTS=localhost
ARG SENTRY_DSN=<SENTRY_DSN>
ARG BLACKFIRE_PROFILE_ON=false

# prevent the reinstallation of vendors at every changes in the source code
COPY composer.json composer.lock symfony.lock ./
# do not use .env files in production
RUN echo '<?php return [];'> .env.local.php
RUN set -eux; \
    composer install --prefer-dist --no-dev --no-autoloader --no-scripts --no-progress --no-suggest; \
    composer clear-cache

# copy only specifically what we need
COPY bin bin/
COPY config config/
COPY public public/
COPY src src/

RUN set -eux; \
    mkdir -p var/cache var/log; \
    composer dump-autoload --classmap-authoritative --no-dev; \
    composer run-script --no-dev post-install-cmd; \
    chmod +x bin/console; sync
VOLUME /srv/api/var

COPY docker/php/docker-entrypoint.sh /usr/local/bin/docker-entrypoint
RUN chmod +x /usr/local/bin/docker-entrypoint

# Blackfire php probe
RUN version=$(php -r "echo PHP_MAJOR_VERSION.PHP_MINOR_VERSION;") \
    && curl -A "Docker" -o /tmp/blackfire-probe.tar.gz -D - -L -s https://blackfire.io/api/v1/releases/probe/php/alpine/amd64/$version \
    && mkdir -p /tmp/blackfire \
    && tar zxpf /tmp/blackfire-probe.tar.gz -C /tmp/blackfire \
    && mv /tmp/blackfire/blackfire-*.so $(php -r "echo ini_get('extension_dir');")/blackfire.so \
    && printf "extension=blackfire.so\nblackfire.agent_socket=tcp://blackfire:8707\n"> $PHP_INI_DIR/conf.d/blackfire.ini

ENTRYPOINT ["docker-entrypoint"]
CMD ["php-fpm"]


# "nginx" stage
# depends on the "php" stage above
FROM nginx:${NGINX_VERSION}-alpine AS api_platform_nginx

COPY docker/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf

WORKDIR /srv/api

COPY --from=api_platform_php /srv/api/public public/


# "varnish" stage
# does not depend on any of the above stages, but placed here to keep everything in one Dockerfile
FROM cooptilleuls/varnish:${VARNISH_VERSION}-alpine AS api_platform_varnish

COPY docker/varnish/conf/default.vcl /usr/local/etc/varnish/default.vcl

docker-entrypoint:

#!/bin/sh
set -e

# first arg is `-f` or `--some-option`
if [ "${1#-}" != "$1" ]; then
    set -- php-fpm "$@"
fi

if [ "$1" = 'php-fpm' ] || [ "$1" = 'php' ] || [ "$1" = 'bin/console' ]; then
    PHP_INI_RECOMMENDED="$PHP_INI_DIR/php.ini-production"
    if [ "$APP_ENV" != 'prod' ]; then
        PHP_INI_RECOMMENDED="$PHP_INI_DIR/php.ini-development"
    fi
    ln -sf "$PHP_INI_RECOMMENDED""$PHP_INI_DIR/php.ini"

    mkdir -p var/cache var/log
    setfacl -R -m u:www-data:rwX -m u:"$(whoami)":rwX var
    setfacl -dR -m u:www-data:rwX -m u:"$(whoami)":rwX var

    if [ "$APP_ENV" != 'prod' ]; then
        composer install --prefer-dist --no-progress --no-suggest --no-interaction
    fi

    echo "Waiting for db to be ready..."
    until bin/console doctrine:query:sql "SELECT 1"> /dev/null 2>&1; do
        sleep 1
    done

#   if [ "$APP_ENV" != 'prod' ]; then
#       bin/console doctrine:schema:update --force --no-interaction
#   fi
fi

crond -L /srv/api/logs/crond.log -b

exec docker-php-entrypoint "$@"

Commands in cause (in docker-entrypoint.sh):

mkdir -p var/cache var/log setfacl -R -m u:www-data:rwX -m u:"$(whoami)":rwX var setfacl -dR -m u:www-data:rwX -m u:"$(whoami)":rwX var

Errors (durring php service up):

setfacl: var/log: Not supported
setfacl: var/log/dev.log: Not supported

Search line:

A new feature of docker-desktop is "New file sharing implementation" that replace (a kind of file sharing system) Samba by FUSE. It's made for developpers like us to improve performances when running symfony or react app through docker.

  • docker-desktop 2.2 release note here
  • a docker blog post about FUSE here

Do anyone has a same probleme and maybe a solution ?

Symfony - set expiration time automatically

$
0
0

I am setting new entity in my form and I have field 'created' which I want to use to set expiration time automatically. I want for expired field to be set on true 30 minutes after entity is set.

I have some logic created but I think it won't work.

My part of the code:

 $dateNow = new \DateTime();
    $entity->setCreated($dateNow)->modify("+33 Minutes");
    if($dateNow >= $entity){
        $entity->setExpired(true);
        $this->em->persist($entity);
        $this->em->flush();
    }

if($entity->isExpired()) {
        throw new /Exception('Sorry,it is expired.');
    }

Do you have any idea how to do this when using setter in Doctrine? Thanks

bugsnag + symfony - report notices and deprecations

$
0
0

We used Bugsnag to aggregate and report issues on a symfony 4 project. All works well except the fact that notices are logged but not sent into bugsnag.

From what I see in code for the bugsnag listener to "hear" that something bad occurred it has to be over the monolog action_level tier. This means that in order to see notices in bugsnag I would have to set the action level to "notice" like below:

monolog:
handlers:
    main:
        type: fingers_crossed
        action_level: critical
        handler: deduplicated

The problem with this is that if I set that to notice, each time a notice occurs the user will see a 500 page. That is correct but not exactly a desired result.

What I would like to achieve is to keep current action_level to critical (so the user is not traumatized by 500 pages because some 3rd party deprecated something), but to send everything (including warnings, notices and deprecations) to bugsnag (so our developers see them and fix them). Any idea how to do that?

How to dynamically change form in Symphony 4 basing on several inputs

$
0
0

I have to update the form dynamically when it is submitted.

There is a documentation for it (https://symfony.com/doc/current/form/dynamic_form_modification.html#how-to-dynamically-generate-forms-based-on-user-data) that says that I need to use get() method to fetch the 'main' field that I want to base on, and then to use getParent() method to add a new field to form.

To get the received field I need to use getData() method.

The problem is that I need to add a new field which depends on three fields, not on one.

When I try to fetch the whole form I get an error that I can't add field to form after it is submitted:

$builder->addEventListener(
    FormEvents::POST_SUBMIT,
    function (FormEvent $event)
    {
        $form = $event->getForm();

        $form->add('table_id', EntityType::class,[
            'class' => ClubTable::class,
            'query_builder' => // here I need to use three posted fields
        ]);
    }
);

If I add getParent() like $form->getParent()->add(...) I get an error that 'getParent() is NULL'.

The documentation says that if I want to be able to use getParent() method, I need to fetch not the whole form, but only one field of that form to have like $builder->get('field')->addEventListener(...). That really works but, as I said, I need to get values of three posted fields, not one.

How is it possible?

Viewing all 3924 articles
Browse latest View live


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