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

How to delete a redis stream after success processing

$
0
0

I use redis as transport in messenger, I thought that after processing a flow the deletion was automatic but alas not. I do not know how to delete a repeat stream when the processing has been carried out with success.

I use symfony 4.4.latest and redis server 6.0

Thanks


Symfony unique restriction in autogenerated pivot entity

$
0
0

I have a classic many-to-many Doctrine relation, and Doctrine autogenerated a pivot table ("article_tag").

I can not figure out how to set a unique constraint, so that every entry in that pivot table (there is no separate Entity class for that table) is unique.Could someone, maybe, share an example?

Syfony 4 / Doctrine Query Builder, How To Hydrate An Entity From Custom Query?

$
0
0

I have the following code that performs a search on the database on the property table, the issue i have here is that a custom query like this doesn't return the actual hydrated entity, which would be something i need it to do:

/**     * @param string $term     * @return array|null     */    public function search(string $term): ?array    {        $term = str_replace('','', $term);        $builder = $this->createQueryBuilder('ppp');        //$builder->select('ppp')        $builder->select('ppp.buildingNumber')            ->leftJoin('ppp.saleValuations','sv')            ->addSelect('COUNT(sv.id) AS TotalSaleValuations')            ->leftJoin('ppp.lettingValuations','lv')            ->addSelect('COUNT(lv.id) AS TotalLettingValuations')            ->addSelect('ppp.id')            ->addSelect('ppp.streetName')            ->addSelect('ppp.buildingNumber')            ->addSelect('ppp.buildingName')            ->addSelect('ppp.town')            ->addSelect('ppp.county')            ->addSelect('ppp.postcode')            ->addSelect('CONCAT_WS(\',\',ppp.buildingName,ppp.buildingNumber,ppp.streetName,ppp.town,ppp.county,ppp.postcode) AS streetAddress')            ->where('LOWER(REPLACE(CONCAT_WS(\',\',ppp.buildingName,ppp.buildingNumber, ppp.streetName, ppp.town,ppp.county,  ppp.postcode),\' \',\'\')) LIKE :term')            ->andWhere('ppp.deleted = false')            ->setParameter('term','%' . strtolower($term) . '%')            ->groupBy('ppp.id');        return $builder->getQuery()->getResult();    }

Does anyone know how to return the entity Property with all the joined entities included from my query instead of an array of selected fields? What i'd like to actually do is remove the TotalSaleValuations counter and have it hydrated as the collection mapped to the property entity, but only return the specific fields i'm querying.

Symfony Check if at least one of two fields isn't empty on form validation of CollectionType

$
0
0

In a previous question (Symfony Check if at least one of two fields isn't empty on form validation) I had asked help for form validation using Callback. The answer given by @hous was right, but it doesn't work for elements in a CollectionType, reason why I'm opening a new question.

Based on the previous answer I have done the following:

Here is my "mother" Form:

class BookingVisitorType extends AbstractType{    private $router;    private $translator;    public function __construct()    {    }    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('visitors', CollectionType::class, ['entry_type' => VisitorType::class,'label' => 'entity.booking.visitors','allow_add' => true,'allow_delete' => true,'delete_empty' => true,'by_reference' => false,'entry_options' => ['label' => false,'delete-url' => $options['visitor-delete-url']                ],'constraints' =>[                    new Count(['min' => 1,'minMessage' => 'validator.visitor.at-least-one-visitor','max' => $options['numberOfPlaces'],'maxMessage' => 'validator.visitor.cannot-have-more-visitor-than-spaces','exactMessage' => 'validator.visitor.exact-message'                    ])                ]            ])        ;    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => Booking::class,'numberOfPlaces' => 1,'visitor-delete-url' => ''        ]);    }}

Here is my "son" Form:

class VisitorType extends AbstractType{    private $phone;    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('firstName', TextType::class, ['label' => 'entity.visitor.first-name','constraints' => [                    new NotBlank(),                    new Length(['min' => 2,'max' => 255                    ]),                    new Regex(['pattern' => "/[\pL\s\-]*/",'message' => 'validator.visitor.not-valide-first-name'                    ])                ]            ])            ->add('phone', TextType::class, ['label' => 'entity.visitor.phone-number','required' => false,'constraints' => [                    new Regex(['pattern' => "/[0-9\s\.\+]*/",'message' => 'validator.visitor.not-valide-phone-number'                    ]),                    new Callback(function($phone, ExecutionContextInterface $context){                        $this->phone = $phone;                    }),                ]            ])            ->add('email', TextType::class, ['label' => 'entity.visitor.email','required' => false,'constraints' => [                    new Email(),                    new Callback(function($email, ExecutionContextInterface $context){                        if ($this->phone == null && $email == null) {                            $context->buildViolation('validator.visitor.email-or-phone-required')->addViolation();                        }                    }),                ]            ])        ;    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => Visitor::class,'error_bubbling' => false,'delete-url' => '',        ]);    }}

My "booking" (shortened) class:

/** * @ORM\Entity(repositoryClass="App\Repository\BookingRepository") */class Booking{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\OneToMany(targetEntity="App\Entity\Visitor", mappedBy="booking", orphanRemoval=true, cascade={"persist"})     * @Assert\Valid     */    private $visitors;}

And finally my "visitor" (shortened) class:

/** * @ORM\Entity(repositoryClass="App\Repository\VisitorRepository") */class Visitor{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=45, nullable=true)     */    private $phone;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $email;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Booking", inversedBy="visitors")     * @ORM\JoinColumn(nullable=false)     */    private $booking;    /**    * @Assert\Callback    */    public function validateAtLeastEmailOrPhone(ExecutionContextInterface $context, $payload)    {        if ($this->getPhone() === null && $this->getEmail() === null) {            $context->buildViolation('validator.visitor.email-or-phone-required-for-all')->addViolation();        }    }}

I've been able to workaround the problem by adding a property to my VisitorType form that I define with the Callback constraint on the phone value and then check it with a Callback constraint on the email field, but it doesn't seem very "good practice".

If I only try to call the Callback constraint I get the following error message: "Warning: get_class() expects parameter 1 to be object, string given"

Any help is highly appreciated!

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.

Could not find package Symfony/skeleton with stability Stable in a version installable using your PHP version 7.0.2

$
0
0

I am new to Symfony skeleton. Can anyone please help to get out from this error for installation of Symfony?

php -v command give : 7.2.12( ubuntu 16.04)

when i execute this command : composer create-project symfony/website-skeleton myProject, i have this error :

Could not find package Symfony/skeleton with stability Stable in a version installable using your PHP version 7.0.2.

Symfony Entity id is null in Unit Test

$
0
0

Hi I have a question i have a script that has this

public function add(Request $request): UserResponse{    $user = new User();    /** @var $request UserRequest */    $user->setName($request->getName());    $user->setEmail($request->getEmail());    $this->dataService->addUpdate($user);    return new UserResponse(        $user->getId(),        $user->getName(),        $user->getEmail()    );}

Now I want to Unit Test this function, but it gives me the error that $user->getId() is null instead of an int (the UserResponse() want the first parameter to be int and not null)

But of course when I make a new User() object in my Unit Test it has no ID in it, that is set by the EntityManager (by for me, magic)

I already tried to do something with

$reflectionClass = new ReflectionClass(get_class($user));$idProperty = $reflectionClass->getProperty('id');$idProperty->setAccessible(true);$idProperty->setValue($user, 1);

But this will not help, anyone knows how to fix this error:

1) App\Tests\Service\UserServiceTest::addTestExpectation failed for method name is equal to 'addUpdate' when invoked 1 time(s)Parameter 0 for invocation App\Service\DataService::addUpdate(App\Entity\User Object (...)): void does not match expected value.Failed asserting that two objects are equal.--- Expected+++ Actual@@ @@ App\Entity\User Object (-    'id' => 1+'id' => null'name' => 'test''identifier' => null'email' => 'test@test.nl'

Symfony 4 API Response OneToMany Relation is Empty Array

$
0
0

Company Entity has OneToMany relation with Address Entity. PUT and POST actions have no errors or wrongs.

Addresses and Companies raletions are empty response when i request from api with postman. (Method GET)

Company Entity:

<?phpnamespace App\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Validator\Constraints as Assert;/** * @ORM\Entity(repositoryClass="App\Repository\CompanyRepository") * @ORM\HasLifecycleCallbacks() */class Company implements \JsonSerializable{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=150, nullable=true)     */    private $taxOffice;    /**     * @ORM\Column(type="string", length=15, nullable=true)     */    private $taxNumber;    /**     * @ORM\Column(type="boolean")     */    private $isBranch;    /**     * @ORM\Column(type="datetime", nullable=true)     */    private $establishment;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Company", inversedBy="companies")     */    private $mainBranch;    /**     * @ORM\OneToMany(targetEntity="App\Entity\Company", mappedBy="mainBranch")     */    private $companies;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Definition")     * @ORM\JoinColumn(nullable=false)     * @Assert\NotBlank()     */    private $companyType;    /**     * @ORM\Column(type="datetime")     */    private $createdAt;    /**     * @ORM\Column(type="datetime")     */    private $updatedAt;    /**     * @ORM\Column(type="string", length=13, nullable=true)     */    private $telephone;    /**     * @ORM\Column(type="string", length=13, nullable=true)     */    private $mobilePhone;    /**     * @ORM\Column(type="string", length=100, nullable=true)     */    private $kepAddress;    /**     * @ORM\Column(type="string", length=13, nullable=true)     */    private $fax;    /**     * @ORM\OneToMany(targetEntity="App\Entity\Person", mappedBy="company")     */    private $people;    /**     * @ORM\Column(type="string", length=150)     */    private $companyName;    /**     * @ORM\Column(type="string", length=200)     */    private $companyTitle;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $email;    /**     * @ORM\Column(type="text", nullable=true)     */    private $description;    /**     * @ORM\Column(type="string", length=25, nullable=true)     */    private $tradeRegisterNumber;    /**     * @ORM\OneToMany(targetEntity="App\Entity\Address", mappedBy="company")     */    private $addresses;    /**     * Specify data which should be serialized to JSON     * @link https://php.net/manual/en/jsonserializable.jsonserialize.php     * @return mixed data which can be serialized by <b>json_encode</b>,     * which is a value of any type other than a resource.     * @since 5.4.0     */    public function jsonSerialize()    {        return array("id"                => $this->id,"mainBranch"        => $this->mainBranch,"companyName"       => $this->companyName,"companyTitle"      => $this->companyTitle,"taxOffice"         => $this->taxOffice,"taxNumber"         => $this->taxNumber,"isBranch"          => $this->isBranch,"companyType"       => $this->companyType,"telephone"         => $this->telephone,"mobilePhone"       => $this->mobilePhone,"kepAddress"        => $this->kepAddress,"fax"               => $this->fax,"addresses"         => $this->addresses,"companies"         => $this->companies,"establishment"     => null === $this->establishment ? '' : $this->establishment->format('Y-m-d H:i:s'),'createdAt'         => null === $this->createdAt ? '' : $this->createdAt->format('Y-m-d H:i:s'),'updatedAt'         => null === $this->updatedAt ? '' : $this->updatedAt->format('Y-m-d H:i:s')        );    }}

And Address Entity:

<?phpnamespace App\Entity;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass="App\Repository\AddressRepository") * @ORM\HasLifecycleCallbacks */class Address implements \JsonSerializable{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=100)     */    private $name;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\City")     * @ORM\JoinColumn(nullable=false)     */    private $city;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\District")     * @ORM\JoinColumn(nullable=false)     */    private $district;    /**     * @ORM\Column(type="string", length=255)     */    // TODO eğer adres => address olursa POST işleminde this value is invalid hatası veriyor. Bunu araştıralım    private $adres;    /**     * @ORM\Column(type="boolean")     */    private $isDefault;    /**     * @ORM\Column(type="boolean")     */    private $isInvoice;    /**     * @ORM\Column(type="datetime", nullable=true)     */    private $createdAt;    /**     * @ORM\Column(type="datetime", nullable=true)     */    private $updatedAt;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Company", inversedBy="addresses")     */    private $company;    /**     * Specify data which should be serialized to JSON     * @link https://php.net/manual/en/jsonserializable.jsonserialize.php     * @return mixed data which can be serialized by <b>json_encode</b>,     * which is a value of any type other than a resource.     * @since 5.4.0     */    public function jsonSerialize()    {        return array("id"            => $this->id,"city"          => $this->city,"district"      => $this->district,"adres"         => $this->adres,"isDefault"     => $this->isDefault,"isInvoice"     => $this->isInvoice,'createdAt'     => null === $this->createdAt ? '' : $this->createdAt->format('Y-m-d H:i:s'),'updatedAt'     => null === $this->updatedAt ? '' : $this->updatedAt->format('Y-m-d H:i:s')        );    }}

And API Response:

{"id": 1,"mainBranch": null,"companyName": "Mustapayev AŞ","companyTitle": "Mustapayev İnşaat Müt. AŞ","taxOffice": null,"taxNumber": null,"isBranch": false,"companyType": {"id": 8,"parentDefinition": {"id": 1,"parentDefinition": null,"title": "Kuruluş Tipi"        },"title": "Anonim Şirket"    },"telephone": null,"mobilePhone": null,"kepAddress": null,"fax": null,"addresses": {},"companies": {},"establishment": "","createdAt": "2019-10-04 14:56:33","updatedAt": "2019-10-04 14:56:33"}

How to enter in textarea in WYSIWYG from behat

$
0
0

I'm trying to insert text into a textarea with a wysiwyg editor (summernote) from a form, i'm using behat featurecontext file for this. The textarea doesn't have a id tag so i need to select the class using javascript code:document.getElementsByClassName('note-editing-area').item(0).innerText="something"

But when i do this, also the innerhtml is overwritten with the text from innerText.

Any suggestions?

A Reservation Form in Symfony

$
0
0

I really want to know how to build a reservation form in symfony 4 for a hospital managment. User chooses a docotor, a date and then in this page appears availability time for this doctor in this date. Thanks!This is my code:

**This is my ReservationFormType:**public function buildForm(FormBuilderInterface $builder, array $options){    $builder        ->add('medicalStaff',EntityType::class,['class'=>MedicalStaff::class,'label'=>false,'required'=>true        ])        ->add('invoiceDate', DateType::class, ['widget' => 'single_text','input' => 'datetime',        ])        ->add('availableTimes', ChoiceType::class)        ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {            // get the form from the event            $form = $event->getForm();            $formOptions = $form->getConfig()->getOptions();            //helpers            //$availableTimeHandler = $formOptions['availableTimes'];            // get the form data, that got submitted by the user with this request / event            $data = $event->getData();            //get date            $preferredDate = $data['invoiceDate'];            // get the availableTimes element and its options            $fieldConfig = $form->get('availableTimes')->getConfig();            $fieldOptions = $fieldConfig->getOptions();             $times =             [                  ['time' => '10:00', 'disabled' => false],                  ['time' => '11:00', 'disabled' => true],                  ['time' => '12:00', 'disabled' => true],             ];            $choices = [];            foreach ($times as $time) {                $choices[] = [$time['time'] => $time['time']];            }            //update choices            $form->add('availableTimes', ChoiceType::class,                array_replace(                    $fieldOptions, ['choices' => $choices                    ]                )            );        });}

Then this is the function that I implemented to reservation.twig.html

<script>    var path = "{{ path('app_profile_main') }}";    $('.reservation-date').datepicker({        format:'yyyy.MM.dd',    });    $(".reservation-hour").change(function () {        $.ajax({            type: "GET",            dataType: "json",            url: path,            data: {},            success: function (data) {                $(".reservation-times").empty();                $.each(data, function (key, value) {                    //popullimi me                    let disabled = (value.disabled === true ? "disabled" : '');                    $(".reservation-times").append('<option '+ disabled +' value='+ value.time +'>'+ value.time +'</option>');                })            }            ,            error: function (error) {                console.log(error);            }        });    })</script>

I only want that, when a clicked the date to show the available hour in my form. My problems is when I click a date(ex datepicker) my dropdown list doesn't show any available hour for a doctor.

Custom error pages not working when exception controller is enabled

$
0
0

When implementing fos_rest bundle with symfony, I cannot seem to have Symfony's normal behavior when handling custom error pages on a 404, 405, 500 or any other error triggered by Symfony.

It works fine for every error triggered with the rest bundle in a normal rest controller.

But on my landing page (and about us and so on), which is not using fos_rest bundle, but twig instead, the custom error pages don't work, instead, it seems to be handled by the fos_rest bundle anyway, and always sends a default error 500 (even if it should be triggering a 404 error).

If I deactivate exceptions in fos_rest.yaml file (enabled: false), then, the custom error pages works fine (configured following this documentation here: https://symfony.com/doc/4.4/controller/error_pages.html )

fos_rest:    routing_loader:        default_format: json        include_format: false    body_listener: true    format_listener:        rules:            - { path: '^/myROUTE1', priorities: ['json'], fallback_format: json, prefer_extension: false }            - { path: '^/myROUTE2', priorities: ['json'], fallback_format: json, prefer_extension: false }            - { path: '^/myROUTE3', priorities: ['json'], fallback_format: json, prefer_extension: false }            - { path: '^/myROUTE4', priorities: ['json'], fallback_format: json, prefer_extension: false }            - { path: '^/', priorities: ['html', 'json'], fallback_format: 'html' }    param_fetcher_listener: true    access_denied_listener:        json: true    view:        view_response_listener: 'force'        formats:            json: true    exception:        enabled: true        exception_controller: 'fos_rest.exception.controller:showAction'        codes:            Doctrine\ORM\EntityNotFoundException: 404            \LogicException: 400            \DomainException: 400        messages:            Doctrine\ORM\EntityNotFoundException: true            \LogicException: true            \DomainException: true

How do I set up fos_rest bundle to only handle exceptions for the routes handled by my rest controllers, and leave the normal Symfony 4 behavior for the rest of the site?

No route found for "GET /inscription"

$
0
0

I've been trying to add a form on my blog app. I had one controller for the moment and everything were just fine (display my home page, display all articles, display one specific article with it's comments, and create an article). I created a new SecurityController to manage the users registration/login etc.But I can't display the simplest view. Here's what I have :

class SecurityController extends AbstractController    /**     * @Route("/inscription", name="security_registration")     */    public function registration()    {        $user = new User();        $form = $this->createForm(RegistrationType::class, $user);        return $this->render('security/registration.html.twig', ['form' => $form->createView()        ]);    }

registration.html.twig :

    {% extends 'base.html.twig' %}    {% block body %}<h1>Hello world</h1>    {% endblock %}

I got the error : No route found for "GET /inscription"Why is that ? Thanks :D

How to enter in textarea in WYSIWYG editor in behat

$
0
0

I'm trying to insert text into a textarea with a wysiwyg editor (summernote) from a form, i'm using behat featurecontext file for this. The textarea doesn't have a id tag so i need to select the class using javascript code:document.getElementsByClassName('note-editing-area').item(0).innerText="something"

But when i do this, also the innerhtml is overwritten with the text from innerText.

Any suggestions?

Symfony 4 Mock service in functional test

$
0
0

I am testing a service which essentially is mostly serializing an object and sending it via a service to an external system.

If I create the typical unittest I would mock the response of the serializer and of the service, which contacts the external system. In fact there would be not much left to test except calling a bunch of setter Methods in my object.

The alternative would be using a KernelTestCase and creating a functional test, which would be fine except I don't want to contact the external system, but to use a mock only for this "external" service.

Is there any possibility to achieve this in Symfony 4?Or is there another approach to this?

What I am doing now is the following:

<?phpnamespace App\Tests\Service;use App\Service\MyClassService;use App\Service\ExternalClient\ExternalClient;use JMS\Serializer\Serializer;use JMS\Serializer\SerializerInterface;use Psr\Http\Message\RequestInterface;use Psr\Log\LoggerInterface;use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;use Symfony\Component\HttpFoundation\Request;class MyClassServiceTest extends KernelTestCase{    /** @var LoggerInterface */    private $logger;    /** @var Serializer */    private $serializer;    /** @var ExternalClient */    private $externalClient;    /** @var RequestInterface */    private $request;    /** @var MyClassService */    private $myClassService;    public function setUp()    {        $kernel = self::bootKernel();        $this->logger = $kernel->getContainer()->get(LoggerInterface::class);        $this->serializer = $kernel->getContainer()->get(SerializerInterface::class);        $this->externalClient = $this->createMock(ExternalClient::class);    }    public function testPassRegistrationData()    {        $getParams = ['amount'          => '21.56','product_id'      => 867,'order_id'        => '47t34g','order_item_id'   => 2,'email'           => 'kiki%40bubu.com',        ];        $this->generateMyClassService($getParams);        $userInformation = $this->myClassService->passRegistrationData();        var_dump($userInformation);    }    /**    * generateMyClassService    *    * @param $getParams    *    * @return MyClass    */    private function generateMyClassService($getParams)    {        $this->request = new Request($getParams, [],  [], [], [], [], null);        $this->myClassService = new MyClassService(            $this->logger,            $this->serializer,            $this->externalClient,            $this->request        );    }}

Give back this error:

Symfony\Component\DependencyInjection\Exception\RuntimeException: Cannot autowire service "App\Service\MyClassConfirmationService": argument "$request" of method "__construct()" references class "Symfony\Component\HttpFoundation\Request" but no such service exists.

pass a variable from view to controller SYMFONY [closed]

$
0
0

I know that passing a variable from view to controller is something that can't be done but I am using symfony and on the purchase form page I need to pass the purchase total to controller to save it in the database.

I have created the form with a formType.php and I don't want to pass the value of the total through the url. Nor would it store it in an input since they can modify it even if it is disabled. And the total price is somewhat variable since discounts can be applied among other things.

I don't know how to approach it or how to do it.

**AppController.php

    /**     * @Route("/compra", name="compra")     * Method({"GET", "POST"})     */    public function compra(Request $request, $pack)    {        $user = $this->getUser();        if ($user) {            $compra = new Compra();            $form = $this->createForm(CompraType::class, $compra);            $form->handleRequest($request);            if ($form->isSubmitted() && $form->isValid()) {                $entityManager = $this->getDoctrine()->getManager();                $fecha = date('Y-m-d H:i:s');                $compra->setFecha($fecha);                $entityManager->persist($compra);                $entityManager->flush();                return $this->redirectToRoute('emailCompra'));            }        } else {            return $this->redirectToRoute('new_user'));        }    }

Thank you.


symfony 4 - Change logger output path

$
0
0

I got an error 500 on production env so I spent a lot of time to search where error was displaying. I found that symfony log errors using logger who send output to stderr by default so apache's error log is used in my case. I want to send messages to symfony's env.log (e.g var/log/dev.log and var/log/prod.log)

Documentation says :

The minimum log level, the default output and the log format can also be changed by passing the appropriate arguments to the constructor of Logger. To do so, override the "logger" service definition.

But I can't figure out how I can change logger's output, for testing purpose I changed logger construct in vendor/symfony/http-kernel/Log/Logger.php as following with success:

public function __construct(string $minLevel = null, $output = 'abspath/to/project/var/log/dev.log', callable $formatter = null)

but I can't edit files in vendor dir.

So How I can override the "logger" service definition ?

Swiftmail doesn't send mail but no error, symfony on docker container

$
0
0

I'm working on a symfony project on docker container and i set up a Mailer service which use swiftmailer and notfloran/mjml-bundle to send mail.the mjml bndle needs mjml binary which i installed on the container with npm install mjml. In the code :

$mail = new \Swift_Message();$mail     ->setFrom($from)     ->setTo($to)     ->setSubject($subject)     ->setBody($body)     ->setContentType('text/mjml');$this->mailer->send($mail);

The thing is that when i request the function which send the mail via the docker container, there is no error but it does not send the mail.But when i start a server with php -S adress -t public and i request the function which send the mail, the mail is sent.

EDIT: i tried to log the processus. In the log there is a mjml binary not found but when i enter in the container the mjml command works

How to fetch addSelect query result as single entity?

$
0
0

I got

Foo entity:

class Foo{  private $name;  /**    * @ORM\OneToMany(targetEntity="App\Entity\Bar", mappedBy="foo", orphanRemoval=true)    */  private bars;  ...}

Bar entity

class Bar{  private $baz   /**     * @ORM\ManyToOne(targetEntity="App\Entity\Foo", inversedBy="bars")     * @ORM\JoinColumn(nullable=false)     */  private $foo;  ...}

Foo repositiory:

$qb = $this->createQueryBuilder('f')            ->select('f as foo')            ->leftJoin('f.bars', 'b')            ->addSelect('b')            ->addSelect('SUM(b.baz) as baz_total')            ->having('SUM(b.baz) > 0')            ->groupBy('f.id')            ->orderBy('f.id', 'ASC')->getQuery()->getResult();

a single row the result looks like:

array('foo' => array( // Foo Entity      ...'name' => ...,'bars' => array(...)), //ArrayCollection 'baz_total' //scalar value )

and temple looks like:

{% for row in foos %}  {{ row.foo.name }}  {{ row.baz_total}}{% endfor %}

Is there any way make it works like:

result:

array('name' => ...,'bars' => array(...)), //ArrayCollection 'baz_total' // extra select as part of entity ) ...

template:

{% for foo in foos %}  {{ foo.name }}  {{ foo.baz_total}}{% endfor %}

How to display a select with another select?

$
0
0

I would like to display the field form.childNumber and form.childFoyerFiscal according to the answer of form.child

If the person chosen TRUE : -- Display"enfantNombre" and "enfantFoyerFiscal"

If the person chosen is FALSE: - Do not display anything

All this must change without refreshing the page (with AJAX for example)

Something like that : enter image description here

class SimulationType extends AbstractTypepublic function buildForm(FormBuilderInterface $builder, array $options){    $builder        /* Partie 1 - Situation */        ->add('situationFamilliale', ChoiceType::class,$this->getConfigurationChoice("Votre situation familliale ?", "input"))        ->add('anneeDeNaissance', IntegerType::class,$this->getConfigurationInteger("Quelle est votre année de naissance ?", "input"))        ->add('enfant', ChoiceType::class,$this->getConfigurationBoolean("Avez vous des enfants ?", "radioButton"))        ->add('enfantNombre', IntegerType::class,$this->getConfigurationInteger("Combien avez-vous d'enfants ?", "input"))        ->add('enfantFoyerFiscal', IntegerType::class,$this->getConfigurationInteger("Combien sont encore dans votre foyer fiscal ?", "input"))        ->add('pension', ChoiceType::class, $this->getConfigurationBoolean("Payez vous une pension ?", "radioButton"))        ->add('pensionPrix', IntegerType::class, $this->getConfigurationInteger("Combien vous coûte cette pension mensuellement?", "input"))        /* Partie 2 - Patrimoine */        ->add('residencePrincipale', ChoiceType::class, $this->getConfigurationResidence("Concernant votre résidence principale vous êtes :", "radioButton", "Proprietaire", "Locataire", "Heberge gratuitement"))            // Propriétaire            ->add('creditResidencePrincipale', ChoiceType::class, $this->getConfigurationBoolean("Avez-vous un crédit sur la résidence principale ?", "radioButton"))                // Propriétaire -> Oui                ->add('proprietaireCreditPrix', IntegerType::class, $this->getConfigurationInteger("Combien vous coûte ce crédit par mois ?", "input"))                ->add('proprietaireCreditTemps', IntegerType::class, $this->getConfigurationInteger("Quelle est la durée restante (en année) ?", "input"))            //Locataire            ->add('locataireCreditLoyer', IntegerType::class, $this->getConfigurationInteger("Quel est la montant de votre loyer /mois ?", "input"))        //Investissement Locatif        ->add('investissement_bis', ChoiceType::class, $this->getConfigurationBoolean("Avez-vous déjà un investissement locatif en cours ?", "radioButton"))            //Investissement Locatif -> Oui            ->add('investissement', CollectionType::class, ['entry_type' => InvestissementType::class, 'allow_add' => true]) // Créer les différents investissements        // Credit (Autres qu'immobilier)        ->add('credit', ChoiceType::class, $this->getConfigurationBoolean("Avez-vous des crédits? (Autres qu'immobilier)", "radioButton"))            //Credit (Autres qu'immobilier) --> Oui            ->add('creditAdd', CollectionType::class, ['entry_type' => CreditType::class, 'allow_add' => true])        ->add('revenuMensuel', IntegerType::class, $this->getConfigurationInteger("Quel est le revenu net MENSUEL de votre foyer ?", "input"))        /* Partie 3 - Epargne */        ->add('epargne', ChoiceType::class, $this->getConfigurationEpargne("A combien estimez-vous votre épargne?", "radioButton", "Moins de 10.000€", "Entre 10.000€ et 20.000€", "Entre 20.000€ et 50.000€", "Entre 50.000€ et 100.000€", "Plus de 100.000€"))        ->add('apportInvestissement', ChoiceType::class, $this->getConfigurationBoolean("Envisagez vous de mettre un apport dans votre investissement?", "radioButton"))            // qpportInvestissement -> Oui            ->add('apportPrix', IntegerType::class, $this->getConfigurationInteger("Combien apporteriez-vous ?", "input"))        ->add('reductionImpot', ChoiceType::class, $this->getConfigurationBoolean("Avez-vous déjà des réductions d'impôts ?", "radioButton"))            // reductionImpot -> Oui            ->add('reductionImpotPrix', IntegerType::class, $this->getConfigurationInteger("De combien réduisez vous votre impôt par an ?", "input"))        /* Partie 4 - Objectifs */        ->add('objectifsPrincipaux', ChoiceType::class, $this->getConfigurationObjectifsPrincipaux("Choisissez vos 3 objectifs principaux", "radioButton", "input", "input1", "input2", "input3", "input4", "input5", "input6"))        ->getForm();}public function configureOptions(OptionsResolver $resolver){    $resolver->setDefaults(['data_class' => Client::class,    ]);}/** * Permet d'avoir la configuration de base d'un IntegerType * * @param string $label * @param string $class * @return array */private function getConfigurationInteger($label, $class){    return  ['label' => $label,'attr' =>['class' => $class            ],'required' => true    ];}/** * Permet d'avoir la configuration de base d'un button de type RADIO * * @param string $label * @param string $class * @return array */private function getConfigurationBoolean($label, $class): array{    return ['label' => $label,'attr' =>['class' => $class        ],'choices' => ['Oui' => true,'Non' => false,        ],'expanded' => false,'multiple' => false,    ];}/** Permet d'avoir le choix en plusieurs proprositions (Max 5)* L'utilisation de cette function peut servir quand il y a plusieurs choix à faire.**/public function getConfigurationObjectifsPrincipaux($label, $class, $choix1, $choix2, $choix3, $choix4, $choix5, $choix6, $choix7): array{    return ['label' => $label,'attr' =>['class' => $class        ],'choices' => [            $choix1 => "patrimoineImmobilier",            $choix2 => "antipationRetraite",            $choix3 => "reductionFiscalite",            $choix4 => "augmentationRendementEpargne",            $choix5 => "constitutionCapital",            $choix6 => "transmissionEnfant",            $choix7 => "revenuComplementaire",        ],'expanded' => true,'multiple' => true,    ];}/** Configuration de base d'un ChoiceType* Permet d'avoir le choix en plusieurs proprositions (Max 5)* L'utilisation de cette function peut servir quand il y a plusieurs choix à faire.**/public function getConfigurationResidence($label, $class, $choix1, $choix2, $choix3): array{    return ['label' => $label,'attr' =>['class' => $class        ],'choices' => [            $choix1 => strtolower(str_replace('','',$choix1)),            $choix2 => strtolower(str_replace('','',$choix2)),            $choix3 => strtolower(str_replace('','',$choix3)),        ],'expanded' => false,'multiple' => false,    ];}/** Configuration de base d'un ChoiceType* Permet d'avoir le choix en plusieurs proprositions (Max 5)* L'utilisation de cette function sert quand il y a plusieurs choix à faire.**/public function getConfigurationEpargne($label, $class, $choix1, $choix2, $choix3, $choix4, $choix5): array{    return ['label' => $label,'attr' =>['class' => $class        ],'choices' => [            $choix1 => "10k",            $choix2 => "20k",            $choix3 => "50k",            $choix4 => "100k",            $choix5 => "1000k",        ],'expanded' => false,'multiple' => false,    ];}/** * L'utilisation de cette fonction est unique (Partie 1) * * @param $label * @param $class * @return array */private function getConfigurationChoice($label, $class): array{    return        ['label' => $label,'attr' =>['class' => $class                ],'choices' => ['Célibataire' => 'celibataire','Marié(e)' => 'marie','Pacsé(e)' => 'pacse','En concubinage' => 'concubinage','Divorcé(e)' => 'divorce','Veuf/Veuve' => 'veuf'            ]        ];}

SimulationController

class SimulationController extends AbstractController/** * @Route("/simulation", name="simulation") * @param Request $request * @param ObjectManager $manager * @return Response */public function formulaire(Request $request, ObjectManager $manager){    $Client = new Client();    $form = $this->createForm(SimulationType::class, $Client); //SimulationType = Formulaire avec les champs    /**     * Permet d'agir en fonction des résultats des formulaires     */    $form->handleRequest($request);    dump($Client);    /* Est ce que le formulaire est bien valide ? */    if ($form->isSubmitted() && $form->isValid()) {        // Si la formulaire est correct --> Direction la page Patrimoine        return $this->render('content/verification.html.twig', ['form' => $form->createView()]);    } elseif ($form->isSubmitted() && $form->isValid() == false) {        // Si la page n'est pas correct, il affiche la page de vérification        return $this->render('/content/verification.html.twig', ['form' => $form->createView()]);    } else {        return $this->render('/content/simulation.html.twig', ['form' => $form->createView()]);    }}

Using a different service.yaml for test, dev and prod environment?

$
0
0

Is it possible to use a different service.yaml files for test, dev and prod environment?If so, where do I need to place the files? And will they be automatically loaded?Or is this not possible at all?

I searched the symfony documentation without luck...

Viewing all 3928 articles
Browse latest View live


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