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

Symfony 4 dynamic select country, state city dropdown

$
0
0

Hello everyone i have a challenge on select 3 input dropdown.I have Country, in Country i have State and in State i have City.I have success to manage choose Country and state display but the issue is from State to get CityI got this error The identifier id is missing for a query of App\Entity\CountryState

My Form Builder is here

<?phpnamespace App\Form;use App\Entity\Country;use App\Entity\CountryState;use App\Entity\StateCities;use App\Entity\User;use App\Repository\CountryRepository;use App\Repository\CountryStateRepository;use App\Repository\StateCitiesRepository;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\EmailType;use Symfony\Component\Form\Extension\Core\Type\PasswordType;use Symfony\Component\Form\Extension\Core\Type\RepeatedType;use Symfony\Component\Form\Extension\Core\Type\TextType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\Form\FormEvent;use Symfony\Component\Form\FormEvents;use Symfony\Component\Form\FormInterface;use Symfony\Component\OptionsResolver\OptionsResolver;use Symfony\Component\Validator\Constraints\Length;use Symfony\Component\Validator\Constraints\NotBlank;use Symfony\Component\Validator\Constraints\Regex;class CreateBusinessFormType extends AbstractType{private $countryRepository;private $countryStateRepository;private $stateCitiesRepository;public function __construct(    CountryRepository $countryRepository,    CountryStateRepository $countryStateRepository,    StateCitiesRepository $stateCitiesRepository    ) {    $this->countryRepository = $countryRepository;    $this->countryStateRepository = $countryStateRepository;    $this->stateCitiesRepository = $stateCitiesRepository;}public function buildForm(FormBuilderInterface $builder, array $options){    $builder        ->add('country', EntityType::class, ['label' => 'Country','placeholder' => 'Select Country','required' => true,'class' => Country::class,'query_builder' => function (EntityRepository $entityRepository) {                return $entityRepository->createQueryBuilder('c')                    ->addOrderBy('c.name', 'ASC');            },'choice_label' => 'name','choice_value' => 'name','constraints' => [                new NotBlank(['message' => 'Country is required',                ]),            ],        ])        ->add('state', ChoiceType::class, ['choices' => [],        ]);    $formModifyState = function (FormInterface $form, Country $country = null) {        // Get States        $states = (null === $country) ? [] : $country->getCountryStates();        // Add State Form        $form->add('state', EntityType::class, ['class' => CountryState::class,'label' => 'State (Optional)','placeholder' => 'Select State','choices' => $states,'choice_label' => 'name','required' => false,                ]);    };    $formModifyCity = function (FormInterface $form, CountryState $countryState = null) {        // Get City        $cityOption = (null === $countryState) ? [] : $countryState->getStateCities();        //var_dump($city);        // Add City Form        $form->add('city', EntityType::class, ['class' => StateCities::class,'label' => 'City (Optional)','placeholder' => 'Select City','choices' => $cityOption,'choice_label' => 'name','required' => false,'constraints' => [                new NotBlank(['message' => 'State City is required',                ]),            ],        ]);    };    // Create Event Listener for State    $builder->addEventListener(                FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formModifyState) {                    // Get Data                    $data = $event->getData();                    // Get Country                    $country = (null === $data) ? null : $this->countryRepository->find($data);                    $formModifyState($event->getForm(), $country);                }            );    // Create Event Listener for City    $builder->addEventListener(        FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formModifyCity) {            // Get Data            $data = $event->getData();            // Get State            $state = $this->countryStateRepository->find($data);            //$test = $this->countryStateRepository->find($data);            //var_dump($data);            $formModifyCity($event->getForm(), $state);        }    );    // Bulder Country    $builder->get('country')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModifyState) {        // Get Data        $data = $event->getForm()->getData();        $formModifyState($event->getForm()->getParent(), $data);    });    // Bulder State    $builder->get('state')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModifyCity) {        // Get Data        $data = $event->getForm()->getData();        $formModifyCity($event->getForm()->getParent(), $data);    });}public function configureOptions(OptionsResolver $resolver){    $resolver->setDefaults([        //'data_class' => User::class,    ]);}}

And on Twig i have this Javascript

var $post_country = $('#create_business_form_country');    var $post_token = $('#create_business_form__token');    // Country on change    $post_country.change(function() {        $("#create_business_form_state").select2();        var $form = $(this).closest('form');        var data = {};        data[$post_token.attr('name')] = $post_token.val();        data[$post_country.attr('name')] = $post_country.val();        $('#create_business_form_state').prop('disabled', true);        // Replace Old State form to New        $.ajax({            url: $form.attr('action'),            type: $form.attr('method'),            data: data,            success: function (html) {                 // Replace current states field ...                $('#create_business_form_state').replaceWith(                    // ... with the returned one from the AJAX response.                        $(html).find('#create_business_form_state')                );                // Enable Input                $('#create_business_form_state').prop('disabled', false);                // Update Select2                $('#create_business_form_state').select2();            }        });    });

Any solution on this please, i try to google but no solution i get. Anyone please.


Symfony demo app install fails - pdo_sqlite missing

$
0
0

I am trying to use the Symfony 4 demo application https://github.com/symfony/demo but when I install it with composer I get the error described below. I am using Ubuntu 16.04 and php 7.1 installed via phpbrew.

My steps are as follows:

$ cd /var/www/html$ phpbrew use php-7.1.13$ sudo php composer.phar create-project symfony/symfony-demo

which yields this error:

Your requirements could not be resolved to an installable set of packages.  Problem 1- The requested PHP extension ext-pdo_sqlite * is missing from your system. Install or enable PHP's pdo_sqlite extension.

if I check which extensions are loaded:

$ phpbrew extension

I get

Loaded extensions:...[*] pdo_sqlite

so it appears that extension is loaded.

What am I doing wrong please?

How to filter relation data in EasyAdmin "Show view"

$
0
0

How to filter relation data in EasyAdmin "Show view"? I need to add some filter logic to show correct related data for user.S

Symfony logout. Change target path protocol from HTTP to HTTPS

$
0
0

My logout target path sends request by HTTP protocol. All on server works by HTTPS protocol. How to say that after logout redirect should be by HTTPS protocol?

enter image description here

enter image description here

enter image description hereenter image description here

Symfony Serializer xml encode append all strings with CDATA

$
0
0

Is it possible to append string with CDATA using Symfony Serializer (not JMS).By looking int to implementation it's only appends if string contains tag elements <>

    private function needsCdataWrapping(string $val): bool    {        return 0 < preg_match('/[<>&]/', $val);    }

Can you explicitly define specific attribute to be append with CDATA?

What would be the best way to secure uploaded files with symfony to logged in users, after the fact it needs security?

$
0
0

So a system we built didn't initially need any document/ uploaded file security, so it's all uploaded to a public folder.

Now, it actually needs every document securing, but the system is that big it would be a mammoth task to go around trying to change every url to the documents to point to a symony controller to do the auth.

Baring in mind we aren't using the symfony auth system, it's detached because the front end is in Angular so it's all ajax calls that send a security token in the request headers.

I considered a htaccess file that would redirect all file requests to an index.php file and then that would hook into symfony to check the token.

My problems with that are:

  1. Am i able to retrieve the header with the auth token from the htaccess and translate it to a url parameter? So we'd end up with something like index.php?filePath=XXXX&token=XXXXX

  2. How would i load symfony to use the entity manager outside of the framework? So the index.php file that takes the redirect from htaccess would need to somehow access the entity manager.

2a) Failing this, we could read the .env file and make a PDO connection to the database directly? - it's only to check the token exists really before allowing the file to be served.

I'm using symfony 4 for this.

Export user roles with Sonata admin

$
0
0

I'm using SonataAdmin and FosUserBundle with Symfony 4.I want to use the export feature to export whole users' data in CSV, JSON ...When a trigger the export, the roles column in the file is empty or null.

In the UserAdmin class, I have overridden the getExportFields function with the call of a specific method to get the role as explained in this post. Sonata admin export fields with collection fieldsBut it doesn't work.

Example in my case:

 public function getExportFields() {    return ['id','username','roles' => 'rolesExported'    ]; }

And in my User Entity:

public function getRolesExported(){    $exportedRoles = [];    foreach ($this->getRealRoles() as $role) {        $exportedRoles[] = $role->__toString();    }    return $this->rolesExported = implode(' - ', $exportedRoles);}

In this case, when I trigger the export, my web browser shows the error

'website is inaccessible' with no error in the dev.log.

When I delete 'roles' => 'rolesExported' in the getExportFields function, the export is well triggered.

  • SonataAdmin version : 3.35
  • FosUserBundle version : 2.1.2
  • Symfony version: 4.3.2 (I know that I need to update it)

Symfony Serializer xml encode append specified properties with CDATA

$
0
0

Is it possible to append string with CDATA using Symfony Serializer (not JMS).By looking int to implementation it's only appends if string contains tag elements <>

    private function needsCdataWrapping(string $val): bool    {        return 0 < preg_match('/[<>&]/', $val);    }

Can you explicitly define specific attribute to be append with CDATA?


Symfony Validation of DateTime fails due to not being string?

$
0
0

I have the following for:

formFactory->create(FormType::class);$form->submit(['startDate' => new \DateTime('2020-01-01')]);

Note: if I use 'startDate' => '2020-01-01' then it works.Within FormType I have the following:

$builder->add('startDate', DateType::class, ['widget' => 'single_text','format' => 'yyyy-MM-dd',]);

The config options are as follows:

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

And in the Event entity I have a field like this:

/**     * @var \DateTime     * @ODM\Field(type="date")     * @Assert\NotBlank()     */    private $startDate;

Yet I keep getting this error and not sure why?

"startDate":["This value is not valid."]

I have Symfony 4.4.10.

Symfony Form Validate start and end dates

$
0
0

I have symfony 4.10 and I am trying to ensure an endDate comes after a startDate. So I have this in my form:

$builder->add('endDate', DateType::class, ['widget' => 'single_text','format' => 'M d, yy',            ]);            $builder->add('startDate', DateType::class, ['widget' => 'single_text','format' => 'M d, yy H:i','constraints' => [                new GreaterThan(['propertyPath' => 'parent.all[endDate].data'                ]),            ]            ]);

But it does not seem to validate and the form thinks all is ok.

Is there a different way to compare the 2 values?

Is it possible to use the Symfony form component with React.js?

$
0
0

I am using the Symfony form component. I have many forms in my project.

To perfectly learn the form component was a long way to go, but now I love it. I love also the automatic validation and so on.

So. now I want to learn and use React.js in my project.

But it seems, there is no way I can use the validation and form builder like before for the projects? Am I right there?

symfony 4 : How to get "/public" from RootDir

$
0
0

I have an image under the public folder.
How can I get my image directory in symfony4 ?
In symfony 3, it's equivalent is :

$webPath = $this->get('kernel')->getRootDir() . '/../web/';

Phpunit reusable test methods in symfony

$
0
0

Let's assume that I have three entites: UserEntity, ZooEntity and AnimalEntity. In order to create zoo I have to create user, because zoo has to have owner. In order to create animal I have to create zoo.

Going further I have 3 controllers for each entity. I also have 3 test classes for controller testing.

  • UserControllerTest
  • ZooControllerTest
  • AnimalControllerTest

In animal test, every time, in each test (to make every test independent) I have to create user and then zoo. Therefore I created traits eg: UserTestTrait and ZooTestTrait which have createUser and createZoo(user) methods.

  1. I was wondering about chaning those traits into services. But then where I should keep them?Would be tests/services/ZooService a good place?

For now I such structure:

  • tests/Controller/Rest/ZooControllerTest
  • tests/Controller/Rest/traits/ZooTestTrait
  1. Assuming that I have those services and every service should have access to eg. entity manager, how can I access that in service? eg. ZooService located in tests/services/ZooService

  2. How can I use that service in controller? Lets assume that I would like to have it in setUp method:

     protected function setUp(): void {     $kernel = self::bootKernel();     // access the zoo service, that has access to the entity manager }

Getting "You are being redireced message" in symfony4.3

$
0
0

I have to redirect few requests from one domain to another domain when form submission happens. I can not replace form action with correct domain name due to some issue. I am using symfony event listener and on Kernel request I am checking the route and domain name and replacing URL like this.

Before getting redirected to test1.com domain I am getting message like "You are being redirected, If this does not happen click here to Continue".

Can someone tell me how to avoid this kind of error messages in symfony.

Example: <form action="test.com/verify" class="paymentWidgets" method="post"></form>

Event listener

if ($routeAccessed == "_verify" && $domain=="test.com") {    $redirectionUrl = "test1.com/verify";$redirect = new RedirectResponse($redirectionUrl, 308);$event->setResponse($redirect);}

Syntax Error line 0, col 60: Error: Expected end of string, got 'ON' - Symfony 4/Doctrine2

$
0
0

I have problem with query builider in Doctine 2 in Symfony 4.4 and Omines/Datables Bundle.

I have entity User and Log like that:

<?phpnamespace App\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass=UserRepository::class) */class User{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=50)     */    private $firstname;    /**     * @ORM\Column(type="string", length=50)     */    private $lastname;    /**     * @ORM\OneToMany(targetEntity=Log::class, mappedBy="user")     */    private $logs;    public function __construct()    {        $this->logs = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    public function getFirstname(): ?string    {        return $this->firstname;    }    public function setFirstname(string $firstname): self    {        $this->firstname = $firstname;        return $this;    }    public function getLastname(): ?string    {        return $this->lastname;    }    public function setLastname(string $lastname): self    {        $this->lastname = $lastname;        return $this;    }    /**     * @return Collection|Log[]     */    public function getLogs(): Collection    {        return $this->logs;    }    public function addLog(Log $log): self    {        if (!$this->logs->contains($log)) {            $this->logs[] = $log;            $log->setUser($this);        }        return $this;    }    public function removeLog(Log $log): self    {        if ($this->logs->contains($log)) {            $this->logs->removeElement($log);            // set the owning side to null (unless already changed)            if ($log->getUser() === $this) {                $log->setUser(null);            }        }        return $this;    }}

And second entity Log:

<?phpnamespace App\Entity;use App\Repository\LogRepository;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass=LogRepository::class) */class Log{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="datetime")     */    private $logStart;    /**     * @ORM\Column(type="string", length=15)     */    private $ip;    /**     * @ORM\ManyToOne(targetEntity=User::class, inversedBy="logs")     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)     */    private $user;    public function getId(): ?int    {        return $this->id;    }    public function getLogStart(): ?\DateTimeInterface    {        return $this->logStart;    }    public function setLogStart(\DateTimeInterface $logStart): self    {        $this->logStart = $logStart;        return $this;    }    public function getIp(): ?string    {        return $this->ip;    }    public function setIp(string $ip): self    {        $this->ip = $ip;        return $this;    }    public function getUser(): ?user    {        return $this->user;    }    public function setUser(?user $user): self    {        $this->user = $user;        return $this;    }}

With doctrine i also use omines/datatables budnle Documentation of this bundle and link to github

I try made custom query with left join to User entity my code in controller:

$table = $this->datatableFactory->create([])            ->add('id', TextColumn::class, ['label' => '#', 'className' => 'bold', 'searchable' => true])            ->add('firstname lastname', TextColumn::class, ['label' => $translator->trans('Customer name'), 'className' => 'bold', 'searchable' => true])            ->add('logStart', DateTimeColumn::class, ['label' => $translator->trans('Time'), 'className' => 'bold', 'searchable' => false])            ->createAdapter(ORMAdapter::class, ['entity' => Log::class,'query' => function (QueryBuilder $queryBuilder) {                    $queryBuilder                        ->select('l, u.firstname, u.lastname')                        ->from(Log::class, 'l')                        ->leftJoin(User::class, 'u', Join::ON, 'l.user = u');                                        }            ]);            $table->handleRequest($request);        if ($table->isCallback()) {            return $table->getResponse();        }  

And i got error: Syntax Error line 0, col 60: Error: Expected end of string, got 'ON'

But when i change ->leftJoin(User::class, 'u', Join::ON, 'l.user = u');

line to: ->leftJoin(User::class, 'u', Join::WITH, 'l.user = u.id'); i'm get error like:

Cannot read property "id" from an array. Maybe you intended to writethe property path as "[id]" instead.

Did anyone have idea what i doing wrong?Thx all 4 help :)


How to make HTTPClient request appear in Symfony profiler?

$
0
0

I'm using Symfony 4.4.7 and making http requests with HTTPClient (Symfony\Component\HttpClient\HttpClient) but requests doesn't shown in profiler. How to make this profiler tab work?

EasyAdmin 3 - Impersonate User in dashboard

$
0
0

I have tried to used easyAdmin3 for making an admin account quickly, but how do you make a proper impersonate user action ?

I have tried a lot of things but the best option are made custom action so this link appear in page but it's don't works properly...

Impersonate works but on only page linked in url (impersonate has stopped if page change) and User don't change in Symfony Toolbar...

My custom Action :

    public function configureActions(Actions $actions): Actions    {        $impersonate = Action::new('impersonate', 'Impersonate')            ->linkToRoute('web_account_index', function (User $entity) {               return ['id' => $entity->getId(),'?_switch_user' => $entity->getEmail()               ];            })        ;        return parent::configureActions($actions)            ->add(Crud::PAGE_INDEX, Action::DETAIL)            ->add(Crud::PAGE_INDEX, $impersonate)            ;    }

Result :Dashboard link for each user

After click on impersonate, I have this url :

https://blog-community.wip/account/7?eaContext=37a8719&?_switch_user=user7@user.com

Content are ok (page account for user 7) but Symfony Profiler show User admin instead of impersonated User :

Symfony profiler user logged

Change page exit impersonate...

Real Symfony impersonate keep impersonation even if page changes because profiler user logged are different Symfony profiler user logged with impersonate directly in url

documentation not refer this functionality, EasyAdmin's Github issues too ans this website too.

Thanks for help

.htaccess for symfony 4.4 in subdomain

$
0
0

I created a project in Symfony framework 4.4.

I have a "example.com" domain where my project was uploaded and works fine.

But If I copy it to a "testing.example.com" subdomain I get a "Error 404 - Not Found" message.

This is my .htaccess in both, the domain and the subdomain.

<IfModule mod_rewrite.c>    Options -MultiViews    RewriteEngine On    RewriteCond %{REQUEST_FILENAME} !-f    RewriteRule ^(.*)$ index.php [QSA,L]</IfModule><IfModule !mod_rewrite.c><IfModule mod_alias.c>        RedirectMatch 302 ^/$ /index.php/</IfModule></IfModule>

Any ideas?

Route not found/matched when using symfony 4 inside a subfolder

$
0
0

I have this apache server configured in mydomain.com/applications and inside that folder I have

  • /project1/ - using silex
  • /project2/ - using symfony 4

The server uses mod_rewrite and mydomain.com is represented by /var/www/html which is mapped as DocumentRoot in apache configuration.

In my local environment, /project2/ is mapped as project2.test and routes made with annotations works very well.

However, when moving the project to a directory, its routes doesn't work (whether in production or local env).

I'm pretty sure the routes were created correctly, but I guess I'm missing some symfony configuration when using symfony inside a subfolder.

I also tried to use RewriteBase "/application/project2/" in my /project2/.htaccess but didn't work.

Any help is appreciated.

Symfony 4.4 serializer problem when one or more items from entity's array collection are removed

$
0
0

I've noticed an unusual problem with Symfony 4.4 serializer which I use for entity data serialization in a controller for the rest API.

Under normal conditions, it works fine but in case if I want to serialize entity which contains property type array collection and I remove one of the array collection items without saving the entity it outputs the array collection with array containing key => value pairs instead of array of objects.

This is a quick sample:

<?phpuse Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\Serializer\SerializerInterface;use App\Entity\SomeEntity;class BaseController extends AbstractController{/** * @Route("/test/{testEntityId}", methods={"GET"}, name="api.v1.test") */public function getTestResult(string $testEntityId, SerializerInterface $serializer){    $testEntityRepository = $this->getDoctrine()->getRepository(TestEntity::class);    $testEntity = $this->testEntityRepository->findOneBy($testEntityId);    // ## > The code in this scope messes up with the serializer    if ($testEntity && $testEntity->hasSomeItems()) {        $someItem = $testEntity->getSomeItems()->getFirst();        $testEntity->removeSomeItem($someItem);    }    $serialized_data = $this->serializer->serialize($entity, 'json', ['groups' => ['test']]);    $headers = ['Content-type' => 'application/json'];    return new Response($serialized_data, 200, $headers);}}

This would return

{ "someItems": [ "1": { someItem 02 object }, "2": { someItem 03 object }, etc. ] }

instead of

{ "someItems": [ { someItem 02 object }, { someItem 03 object }, etc. ] }

as it would normally.

This happens because removeSomeItem($someItem) calls method removeElement of ArrayCollection which removes item with array key 0 and the remaining items keep their keys unchanged.

I managed to get a normal response if I force the following line into Symfony's ArrayCollection removeElement method: $this->elements = array_values($this->elements); to reset the order of the array item keys.

I need a solution to fix this in a controller instead of changing the core code of the Symfony. Saving the entity with the entity manager is not applicable because I just need to remove some incompatible items for older API clients from the array collection to keep backward compatibility and don't want to persist such changes.

Any good ideas?

Thank you in advance!

Viewing all 3924 articles
Browse latest View live


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