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

Symfony validator with dependencies

$
0
0

I want to validate an object with constraint annotations, and use dependencies (entityManager) at the validator.

The validator does not work, if it has dependencies (eg. entityManager) in the constructor.

I followed the docs, but it does not work: https://symfony.com/doc/current/validation/custom_constraint.html#constraint-validators-with-dependencies

"ClassNotFoundException Attempted to load class "validator_question_exists" from the global namespace. Did you forget a "use" statement?"

I try to validate the 'Question' object like this (maybe here is the problem):

$validator = Validation::createValidatorBuilder()
    ->enableAnnotationMapping()
    ->getValidator()
;

$question = new Question();
$errors = $validator->validate($question);

Question (the object to validate)

/** @App\Validator\Constraint\Question\QuestionExists() */
class QuestionReadInput{
    ....
}

services.yaml

services:
    validator.unique.question_exists:
        class: App\Validator\Constraint\Question\QuestionExistsValidator
        tags:
            - { name: validator.constraint_validator, alias: validator_question_exists}

Constraint

namespace App\Validator\Constraint\Question;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class QuestionExists extends Constraint
{
    public $message;

    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }

    public function validatedBy()
    {
        //if i delete this function, symfony cant autowire the entitymanager to the validator
        //this throws an error, wants to make a new validator_question_exists(), which not exists, because its a service alias, the docs said it should be okay
        return 'validator_question_exists';
    }
}

Validator

class QuestionExistsValidator extends ConstraintValidator
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function validate($value, Constraint $constraint)
    {
          die('I dont see this message...');
    }

debug:container


Information for Service "validator.unique.question_exists"
 ---------------- -------------------------------------------------------------------
  Option           Value
 ---------------- -------------------------------------------------------------------
  Service ID       validator.unique.question_exists
  Class            App\Validator\Constraint\Question\QuestionExistsValidator
  Tags             validator.constraint_validator (alias: validator_question_exists)
                   validator.constraint_validator
  Public           no
  Synthetic        no
  Lazy             no
  Shared           yes
  Abstract         no
  Autowired        yes
  Autoconfigured   yes

How to add user to Sentry in Symfony4 for all exceptions?

$
0
0

I added Sentry to my project, but it doesn't add the currently logged in user for some events.

I added an event subscriber, but I'm not sure anymore if I really need it. For excepctions like ArgumentCountError everything works fine. For NotFoundHttpException it doesn't. After a bit of debugging I found, that ExceptionListener->onKernelRequest isn't called with every exception. I already emptied skip_capture in sentry.yaml, but this didn't help. What am I missing. My guess would be that propagation is stopped somewhere. But where? And how can I change this?

<?php
// src/EventSubscriber/SentrySubscriber

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Sentry\SentryBundle\SentrySymfonyEvents;
use Symfony\Component\HttpKernel\KernelEvents;

class SentrySubscriber implements EventSubscriberInterface {

    /** @var \Raven_Client */
    protected $client;
    private $username;

    public function __construct(\Raven_Client $client) {
        $this->client = $client;
    }

    public static function getSubscribedEvents() {
        return array(
            SentrySymfonyEvents::PRE_CAPTURE => 'preCapture',
            SentrySymfonyEvents::SET_USER_CONTEXT => 'setUserContext',
        );
    }

    public function preCapture(GetResponseForExceptionEvent $event, $eventName, EventDispatcher $dispatcher) {
// username is empty, because setUserContext wasn't executed
// echo 'preCapture';var_dump($this->username);var_dump($this->client->_user);
        $this->client->user_context(['username' => $this->username]);
    }

    public function setUserContext(\Sentry\SentryBundle\Event\SentryUserContextEvent $event) {
//      echo 'setUserContext';      var_dump($event->getAuthenticationToken()->getUsername());
        $this->username = $event->getAuthenticationToken()->getUsername();
    }

}

My config:

// config/services.yaml
services:
    App\EventSubscriber\SentrySubscriber:
        arguments:
          - '@sentry.client'
        tags:
          - { name: kernel.event_subscriber }

// config/packages/sentry.yaml
sentry:
    dsn: '%env(SENTRY_DSN)%'
    options:
        curl_method: async
        release: '%env(RELEASE)%'

    skip_capture: # nothing else here, because everything should be captured

GraphQl query for message thread with Symfony API-Platform

$
0
0

I am trying to create a website members' message system that should work just like any web mail, where the inbox shows a conversation thread.

Getting the inbox and outbox as such seems to work, but the thread is posing some issues. So far I have been able to get all threads but I have not been able to get only the threads where a specific user is involved.

In my current set up, that would require a query that accepts OR condition, which does not seen to be available.

To be specific, in the messages query below I should be able to query for where the user appears either as sender or receiver. I can do one, not both.

It just might be the case that the whole set up is not correct.

My current query looks like below:

query(
  $user: ID!, 
  $hasChildren: MessageFilter_exists,
  $isDeletedBySender: Boolean,
  $isDeletedByReceiver: Boolean
){
user(id: $user){
id
username
  // gets all inbox messages showing parent, if exists 
inbox(isDeletedByReceiver: $isDeletedByReceiver){
  id
  sentAt
  isDeletedByReceiver
  sender{
    username
  }
  parent{
    id
  }
}
  // shows all on outbox 
outbox(isDeletedBySender: $isDeletedBySender) {
  id
  sentAt
  isDeletedBySender
  receiver{
    username
  }
}
}
 // shows ALL messages that have children, ie, a thread but IT IS NOT SPECIFIC TO THE USER
messages(exists: $hasChildren){
 id
 sender{
   id
   username
 }
 receiver{
   username
 }
 children{
  id
  sentAt
  sender...
  receiver...
 }
}

Variables:

{
  "user": "/api/users/296",
  "hasChildren": {
    "children": true
  },
  "isDeletedBySender": false,
  "isDeletedByReceiver": false
}

The User entity properties concerning messages:

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Message", mappedBy="sender")
 */
private $outbox;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Message", mappedBy="receiver", orphanRemoval=true)
 */
private $inbox;

The concerned properties of the Message entity:

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="outbox")
 * @ORM\JoinColumn(nullable=false)
 * @Groups({"post", "get"})
 */
private $sender;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="inbox")
 * @ORM\JoinColumn(nullable=false)
 * @Groups({"post", "get"})
 */
private $receiver;

/**
 * @ORM\ManyToOne(targetEntity="Message", inversedBy="children")
 * @ORM\JoinColumn(referencedColumnName="id", onDelete="CASCADE")
 * @Groups({"get"})
 */
private $parent;

/**
 * @ORM\OneToMany(targetEntity="Message", mappedBy="parent")
 * @ORM\OrderBy({"sentAt" = "DESC"})
 * @Groups({"get"})
 */
private $children;

Use custom method controller for a custom route

$
0
0

I created a custom controller for PUT item operation. I used the _invoke method to make the default action but I tried to used a custom method to a second PUT action on the same item.


I tried this configurations without success.

*         "activate"={
*             "method"="PUT",
*             "path"="/safety_rooms/{id}/activate",
*             "requirements"={"id"="\d+"},
*             "controller"=SafetyRoomPutItem::activeRoom,
*          },

but I get [Semantical Error] Couldn't find constant App\Controller\SafetyRoomPutItem::activeRoom, class App\Entity\SafetyRoom.


I tried this configurations without success.

*         "activate"={
*             "method"="PUT",
*             "path"="/safety_rooms/{id}/activate",
*             "requirements"={"id"="\d+"},
*             "controller"=SafetyRoomPutItem::class.activeRoom,
*          },

but I get [Syntax Error] Expected Doctrine\Common\Annotations\DocLexer::T_CLOSE_CURLY_BRACES, got '.' at position 1274 in class App\Entity\SafetyRoom.


I tried this configurations without success.

*         "activate"={
*             "method"="PUT",
*             "path"="/safety_rooms/{id}/activate",
*             "requirements"={"id"="\d+"},
*             "controller"=SafetyRoomPutItem::class(activeRoom),
*          },

I tried this configurations without success.

*         "activate"={
*             "method"="PUT",
*             "path"="/safety_rooms/{id}/activate",
*             "requirements"={"id"="\d+"},
*             "controller"=SafetyRoomPutItem::class:activeRoom,
*          },

I tried this configurations without success.

*         "activate"={
*             "method"="PUT",
*             "path"="/safety_rooms/{id}/activate",
*             "requirements"={"id"="\d+"},
*             "controller"=SafetyRoomPutItem:activeRoom,
*          },

I tried this configurations without success.

*         "activate"={
*             "method"="PUT",
*             "path"="/safety_rooms/{id}/activate",
*             "requirements"={"id"="\d+"},
*             "controller"=[SafetyRoomPutItem::class, "activeRoom"],
*          },

but I get [Syntax Error] Expected PlainValue, got '[' at position 1250 in class App\Entity\SafetyRoom.


[PHPUnit], [Symfony]: test that Entity was saved in DB

$
0
0

I have problem with my test. I learn how to write phpunit test and how i can mock object, services etc.. I have this method on my ProductService:

<?php

namespace App\Service;

use App\Entity\Product;
use App\Repository\ProductRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class ProductService
{
    /**
     * @var ProductRepository
     */
    private $productRepository;
    /**
     * @var EntityManager
     */
    private $entityManager;
    /**
     * @var ValidatorInterface
     */
    private $validator;

    /**
     * ProductService constructor.
     * @param ProductRepository $productRepository
     * @param EntityManagerInterface $entityManager
     * @param ValidatorInterface $validator
     */
    public function __construct(ProductRepository $productRepository, EntityManagerInterface $entityManager, ValidatorInterface $validator)
    {
        $this->productRepository = $productRepository;
        $this->entityManager = $entityManager;
        $this->validator = $validator;
    }

    /**
     * @param $productData
     * @return Product|string
     */
    public function createProduct($productData)
    {
        $name = $productData['name'];
        $quantity = $productData['quantity'];
        $sku = $productData['sku'];

        $product = new Product();
        $product->setName($name);
        $product->setQuantity($quantity);
        $product->setProductSerial($sku);

        $errors = $this->validator->validate($product);

        if (count($errors) > 0) {
            $errorsString = (string)$errors;

            return $errorsString;
        }

        try {
            $this->entityManager->persist($product);
            $this->entityManager->flush();
            return $product;
        } catch (\Exception $ex) {
            return $ex->getMessage();
        }
    }
}

and i write this test:

<?php

namespace App\Tests\Service;

use App\Entity\Product;
use App\Repository\ProductRepository;
use App\Service\ProductService;
use Doctrine\Common\Persistence\ObjectRepository;
use PHPUnit\Framework\TestCase;

class ProductServiceTest extends TestCase
{
    /**
     * Create product test
     */
    public function testCreateProduct()
    {
        $product = new Product();
        $product->setName('tester');
        $product->setQuantity(2);
        $product->setProductSerial('Examplecode');

        $productService = $this->createMock(ProductService::class);
        $productService->method('createProduct')->will($this->returnSelf());
        $this->assertSame($productService, $productService->createProduct($product));
    }
}

When i run phpunit test, then i always have success but my database is empty. How can I be sure that the test works correctly? What is worth fixing and what is not? I wanted to make the launch of tests result in, for example, adding records to the test database, but I have no idea how to do it and how to properly mock it. I using phpunit + Symfony 4.

I used to write tests, but those that asked the endpoint API, and here I want to test services and repositories without endpoints.

I would like to learn how to test and mock websites, repositories, various classes etc.

When i apply answer then i have:

PHPUnit 7.5.17 by Sebastian Bergmann and contributors.

Testing Project Test Suite
?[31;1mE?[0m                                                                   1 / 1 (100%)

Time: 542 ms, Memory: 10.00 MB

There was 1 error:

1) App\Tests\Service\ProductServiceTest::testCreateProduct
Doctrine\Common\Persistence\Mapping\MappingException: The class 'App\Repository\ProductRepository' was not found in the chain configured namespaces App\Entity, Gesdinet\JWTRefreshTokenBundle\Entity

D:\warehouse-management-api\vendor\doctrine\persistence\lib\Doctrine\Common\Persistence\Mapping\MappingException.php:22
D:\warehouse-management-api\vendor\doctrine\persistence\lib\Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain.php:87
D:\warehouse-management-api\vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\ClassMetadataFactory.php:151
D:\warehouse-management-api\vendor\doctrine\persistence\lib\Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory.php:304
D:\warehouse-management-api\vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\ClassMetadataFactory.php:78
D:\warehouse-management-api\vendor\doctrine\persistence\lib\Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory.php:183
D:\warehouse-management-api\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php:283
D:\warehouse-management-api\vendor\doctrine\doctrine-bundle\Repository\ContainerRepositoryFactory.php:44
D:\warehouse-management-api\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php:713
D:\warehouse-management-api\vendor\doctrine\persistence\lib\Doctrine\Common\Persistence\AbstractManagerRegistry.php:215
D:\warehouse-management-api\tests\Service\ProductServiceTest.php:28

?[37;41mERRORS!?[0m
?[37;41mTests: 1?[0m?[37;41m, Assertions: 0?[0m?[37;41m, Errors: 1?[0m?[37;41m.?[0m

My Product entity

<?php

namespace App\Entity;

use DateTime;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
 */
class Product
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     */
    private $name;

    /**
     * @ORM\Column(type="integer")
     * @Assert\NotBlank()
     */
    private $quantity;

    /**
     * @Gedmo\Mapping\Annotation\Timestampable(on="create")
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @Gedmo\Mapping\Annotation\Timestampable(on="update")
     * @ORM\Column(type="datetime")
     */
    private $updatedAt;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */
    private $product_serial;


    public function __construct() {
        $this->setCreatedAt(new \DateTime());
        $this->setUpdatedAt();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getQuantity(): ?int
    {
        return $this->quantity;
    }

    public function setQuantity(int $quantity): self
    {
        $this->quantity = $quantity;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(): self
    {
        $this->updatedAt = new \DateTime();

        return $this;
    }

    public function getProductSerial(): ?string
    {
        return $this->product_serial;
    }

    public function setProductSerial(string $product_serial): self
    {
        $this->product_serial = $product_serial;

        return $this;
    }
}

ProductRepository

<?php

namespace App\Repository;

use App\Entity\Product;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;

class ProductRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Product::class);
    }
}

doctrine.yaml

doctrine:
    dbal:
        # configure these for your database server
        driver: 'pdo_mysql'
        server_version: '5.7'
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci

        url: '%env(resolve:DATABASE_URL)%'
    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

Symfony4 stop handleRequest() from removing values of my object

$
0
0

I am submitting a form and in my controller i use handleRequest to validate the form.

Lets say i try to update my object name 'object' It has an id, name and color field.

On the same page I also show a lost with the names of all my objects that i fetch from the database

Here is my code:

$object = self::getObjectById($objectId);

$objects = self::getAllObjects();

$objectForm = self::CreateObjectForm($object);

$objectFormForm->handleRequest($request);

dd($objects);

When I submit the form and I leave the name field open, It throws an error that the field is required when it reloads the page, the name field of the form is still empy wich is normal.

But here is the problem, in the list of objects that is also showing on this page the name of the object I tried to update has no name showing anymore in this list.

I don't know why this is happening since i fetched this list of objects completely seperatly from the form object. When I dd() the objects after the handleRequest() I cans see in the dumped vars that indeed the name field is empty. When i check the database, the name field is not empty and still holds the old name. Wich makes sence because the object is not persisted and flushed to de db. When I dd() the same list before the handleRequest() everything is normal.

How can I prevent this behaviour? And why is this happening?

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 AbstractType



public 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()]);
    }
}

Symfony 4 "Easy admin" upload directory does not change when "upload_dir" option is used

$
0
0

I have some troubles on the bundle easy_admin in Symfony 4.3

I do not find where the upload directory is defined by the bundle. He still uses the default configuration even if I define my upload_dir option in the field.

My configuration

easy_admin:
  entities:
    Images:
      new:
        fields:
          - { property: 'name', type: 'file_upload', upload_dir: 'uploads/images/', download_path: 'uploads/images/', allow_add: true, type_option: { multiple: true }}

The error message

Invalid upload directory "C:\Users\My\Desktop\Project/C:\Users\My\Desktop\Project/public/uploads/files/\" it does not exist or is not writable.

Thank's for the help.


How in a Symfony 4 pass context to the custom event subscriber?

$
0
0

I'm using Symfony 4 and there are custom event and subscriber, e.g. CustomEvent and CustomEventSubscriber. There is module which dispatch CustomEvent, e.g. CustomModule. And that module is using in the controller (ControllerA) and command (CommandB).

In other words possible two follow scenarios:

ControllerA -> CustomModule -> CustomEventSubscriber(CustomEvent)

Or

CommandB -> CustomModule -> CustomEventSubscriber(CustomEvent)

Logic in the CustomEventSubscriber little bit different depends on where was called CustomModule (ControllerA or CommandB).

How to pass that information to the CustomEventSubscriber?

I can add $context property to the CustomEvent and set it in the CustomModule. But in that case I should pass info about context to the CustomModule.

Or maybe I can use some global settings, e.g. container?

Or create two different event subscribers per CustomEvent, disable auto-wiring, and 'manually' init and add to the dispatcher in ControllerA and CommandB?

Symfony API, Reactjs and Nginx: No 'Access-Control-Allow-Origin' header is present on the requested resource in production

$
0
0

I have two app running on nginx server: My Symfony API: https://dev-front******.com and my React App: https://dev-api******.com

I'm using a jwt authentication but i'm not able to connect to my API because of cors policy. It's also not working with nelmio cors bundle but there is no problem with Postman.

My nelmio cors config:

nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Content-Type', 'Authorization']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['*']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600

My nginx config:

  location / {
    if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Allow-Origin''*';
      add_header 'Access-Control-Allow-Methods''GET, POST, OPTIONS';
      #
      # Custom headers and headers various browsers *should* be OK with but aren't
      #
      add_header 'Access-Control-Allow-Headers''DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
      #
      # Tell client that this pre-flight info is valid for 20 days
      #
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type''text/plain; charset=utf-8';
      add_header 'Content-Length' 0;
      return 204;
    }
    try_files $uri /index.php$is_args$args;
  }

What my browser 'Request-Headers' display:

:authority: dev-api******.com
:method: OPTIONS
:path: /api/1.0/login_check
:scheme: https
accept: */ *
accept-encoding: gzip, deflate, br
accept-language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
access-control-request-headers: content-type
access-control-request-method: POST
origin: https://dev-front******.com
referer: https://dev-front******.com
sec-fetch-mode: cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36

How to deny access to a route for logged user?

$
0
0

I want to deny access of the signup/signin route for logged user directly in the access_controls of security.yaml

Anyone know how to do it cause in the documentation? I didn't see stuff like that.

current access_controls :

access_control:

    - { path: ^/signin$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/signup$, roles: IS_AUTHENTICATED_ANONYMOUSLY}
    - { path: ^/product$, roles: IS_AUTHENTICATED_ANONYMOUSLY }

how create database symfony 4? [closed]

$
0
0

I installed symfony 4 for my project , everything is right now good

I use php version 7.1 and wampserver as localhost I set the command php bin/console server:run and thanks god it work

Next I want to create my database

php bin/console doctrine:database:create

And HERE THE PROBLEM it show me

Access denied for user 'db_user'@'localhost' (using password YES)

Someone have already have an idea about database creation in symfony and solve it ?

Symfony 4 Error 500 after submit upload FileType Form

$
0
0

This project gets an error 500 when I upload a file to a FileType Form in Symfony, however I have no clue where the issue is. The controller and twig both seem fine, additionally the form behaved as expected shortly before an ENV devops issue, therefore I'm not even sure it's an issue with the code.

Facts

  1. The project is set in DEV in the settings, however the server run command launches it in PROD (no debug bar)
  2. The upload has worked prior to a server env change
  3. The error 500 doesn't point me in any direction

The Controller

    {
        $form = $this->createForm('AppBundle\Form\SearchType');
        $form->handleRequest($request);

        $verifyForm = $this->createForm('AppBundle\Form\VerifyType');
        $verifyForm->handleRequest($request);

        $uploadForm = $this->createForm('AppBundle\Form\UploadType'); //this is the bugged form
        $uploadForm->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->get('session')->set('search', $form->getData());
            return $this->redirectToRoute('results');
        }

        $series = $this->getDoctrine()->getManager()
            ->getRepository('AppBundle:BacCandidatSerie')
            ->findAll();

        if ($verifyForm->isSubmitted() && $verifyForm->isValid()) {

            $ine = $verifyForm->getData(); 
            $ineValidator = new CodeValidator($ine['numero_ine']);
            if($ineValidator->testINE()){
                return $this->render('default/index.html.twig', array(
                    'form' => $form->createView(),
                    'verifyForm' => $verifyForm->createView(),
                    'valid' => true,
                    'uploadForm' => $uploadForm->createView(),
                    'series' => $series,
                    'isTested' => true,
                    'isInvalid' => false
                ));
            }
            else{
                return $this->render('default/index.html.twig', array(
                    'form' => $form->createView(),
                    'verifyForm' => $verifyForm->createView(),
                    'valid' => false,
                    'uploadForm' => $uploadForm->createView(),
                    'series' => $series,
                    'isTested' => true,
                    'isInvalid' => true,
                ));
            }
        }

        if ($uploadForm->isSubmitted() && $uploadForm->isValid()) {
            $file = $uploadForm['fichier_ine']->getData(); //this worked previously but now seems not to
            dump($file);
            die();
        }

        return $this->render('default/index.html.twig', array(
            'form' => $form->createView(),
            'verifyForm' => $verifyForm->createView(),
            'valid' => false,
            'uploadForm' => $uploadForm->createView(),
            'series' => $series,
            'isTested' => false,
            'isInvalid' => false
        ));
    }```

**The UploadFile Form**
```class UploadType extends AbstractType implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('fichier_ine', FileType::class, array('required' => false))
            ->add('sendfile', SubmitType::class, ['label' => 'Vérifier les numéros'])
        ;
    }
}```

I'm looking for leads having spent 2 hours without any progress and being a junior beginner developer.

Semantical Error line 0, col 64 near 'k': Error: Class App\Entity\.... has no association named

$
0
0

I am trying to join two tables to do a query:

public function findByFile_Ref_Id($query) {

$query = $query['ids'];

$q = $this->createQueryBuilder('h');

$result = $q

->leftJoin('h.file_ref_id', 'k')

//->add('where', $q->expr()->in('k.product_code', $query))

->getQuery()

->getResult();

//dump($result);die;

return $result;

}

I'm using a many-to-one unidirectional association:

/**

* @ORM\ManyToOne(targetEntity="KstoreHikashopProduct", inversedBy="hikashopFile")

* @ORM\JoinColumn(name="file_ref_id", referencedColumnName="product_id")

* @ORM\Column(type="integer")

*/

private $file_ref_id;

how is this possible?! what am I doing wrong?

How to use libphonenumber.phone_number_util in Symfony 4

$
0
0

To parse phone number I need to use libphonenumber.phone_number_util in my controller ( Symfony 4) as like as :

$parsed = $this->get('libphonenumber.phone_number_util')->parse($phoneNo);

as we have libphonenumber.phone_number_util in private I wanted to make it public by adding this helper in service as below:

services:
   libphonenumber\PhoneNumberUtil:
      alias: libphonenumber.phone_number_util
      public: true

But this returns Exception and message:

"message": "The \"libphonenumber.phone_number_util\" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.",
            "class": "Symfony\\Component\\DependencyInjection\\Exception\\ServiceNotFoundException",

How to access the value of one attribute from one table to another by using One to One bi directional in Symfony 4

$
0
0

I have two tables (application and employee) that related with One to One, bi directional. In application table I have four attributes (

name_app, responsible_app, responsible_app_backup_1 and responsible_app_backup_2)

and in employee table I have also three attributes ( uid_employee, first_name and last_name ).
So how can I list out uid, first name and last name for each responsible_app? Thanks

how to get access to the methods of the target entity of unidirectional ManyToOne association

$
0
0

I am stuck here I execute the query:

public function findByFile_Ref_Id($query) {

$query = $query['ids'];



$q = $this->createQueryBuilder('h');

$result = $q

->join('h.file_ref_id', 'k')

->add('where', $q->expr()->in('k.product_code', $query))

->getQuery()

->getResult();

return $result;

}

and I get something like this:

array:5 [▼

0 => HikashopFile {#417 ▼

-file_id: 2207

-file_path: "1TAHBIO.jpg"

-file_ref_id: KstoreHikashopProduct {#363 ▼

+isInitialized: true

-product_id: 6

-product_name: "Tahina bio"

-product_description: "

La Tahina è una crema di sesamo biologica. Rafforza il sistema immunitario grazie alla presenza di sali e vitamine, contiene un elevato contenuto di calcio, ▶"

-product_quantity: 3

-product_code: "1TAHBIO"…2 } }

I want to access the methods of that target entity to do some tasks.

but when I try I get :

Return value of App\Entity\HikashopFile::getFileRefId() must be of the type int or null, object returned

or

Attempted to call an undefined method named "getProductName" of class "App\Entity\HikashopFile".

there is clearly something wrong in my code.

help would be appreciated!

How can I replace a Symfony field's option value within Event listeners?

$
0
0

One of my form's fields is added/attached depending on other fields' value.

All works fine, the field is added using $form->add(…) in a PRE_SET_DATA event listener and is then replaced in a PRE_SUBMIT event listener (because the conditionnal field submitted data may differ from the initial value).

But I actually only want to replace 'choice' and/or 'query_builder' options from within PRE_SUBMIT listener, and because the piece of code $event->getForm()->add(/*…*/) is redundant between these two listeners, I am looking for a way to clean the logic.

Question:
I could wrap the redundant snippet in a new method and call it where appropriate but I wondered if I could directly replace the form's options instead within the PRE_SUBMIT … Is that possible? Because form configuration reached via $event->getForm()->getConfig() does not seem to expose any such setter …

$builder
    ->add(
        'building',
        SelectType::class,
        ['multiple' => false]
    )
    ->add(
        'breedType',
        SelectType::class,
        [
            'multiple' => false,
            'choices'  => [
                'Bred' => Breed::TYPE_BRED,
                'Mixed-bred' => Breed::TYPE_MIX,
                'Alley' => Breed::TYPE_ALLEY
            ]
        ]
    )
    /* … */
    ->addEventListener(
        FormEvents::PRE_SET_DATA,
        function (FormEvent $event) {
            $model = $event->getData();
            $breedType = $model ? $model->getBreedType() : null;
            $building = $model ? $model->getBuilding() : null;

            $event->getForm()->add(
                "cats",
                EntityType::class,
                array_merge(
                    $building && in_array((int)$breedType, [Breed::TYPE_BRED, Breed::TYPE_MIX])
                    ? [
                        'query_builder' => function (CatRepository $er) use ($building, $breedType) {
                            return $er->getByBuildingAndBreed($building, $breedType);
                        }
                    ]
                    : ['choices' => []],
                    [
                        'mapped' => true
                        , 'multiple' => ture
                        , 'class' => Cat::class
                        , 'required' => false
                        , 'label' => 'Select sheltered cats'
                    ]
                )
            );
        }
    )
    ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $data = $event->getData();
        $breedType = $data['breedType'] ?? null;
        $building = isset($data['building']) && !empty($data['building'])
            ? $this->entityManager->getReference(Building::class, $data['building'])
            :  null
        ;

        $event->getForm()->add(
            "cats",
            EntityType::class,
            array_merge(
                $building && in_array((int)$breedType, [Breed::TYPE_BRED, Breed::TYPE_MIX])
                ? [
                    'query_builder' => function (CatRepository $er) use ($building, $breedType) {
                        return $er->getByBuildingAndBreed($building, $breedType);
                    }
                ]
                : ['choices' => []],
                [
                    'mapped' => true
                    , 'multiple' => ture
                    , 'class' => Cat::class
                    , 'required' => false
                    , 'label' => 'Select sheltered cats'
                ]
            )
        );
    })
;

How to pass array from Twig to Javascript using JSON

$
0
0

I need your help to work miracles.

I want to convert Twig array to Javascript array and then use it in a loop and create markers for the Google API.

<script>
    var map, marker, i, e;
    var companies = {{ companies.items | json_encode() | raw }};

    console.log(companies);
    var address = {{ search.city.first.name | json_encode() | raw }};

    function initMap() {
        var geocoder = new google.maps.Geocoder();

        map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 44.8333, lng: -0.5667},
            zoom: 12,
            disableDefaultUI: true
        });

        //for (i = 0; i < locations.length; i++) {
            //marker = new google.maps.Marker({
                //position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                //map: map
            //});

    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEYLOL&callback=initMap"></script>

When I get my array back, companies show me an empty array.

Screen of empty array of console.log(companies)

But when I dump this on twig my array is ok ..

Dump array on Twig

Can someone help me?

doctrine does not generate columns in migrations

$
0
0

I`m little bit confused. I've generated my Entity class by bin/console make:entity with columns id, title and etc. When I run bin/console doctrine:migrations:diff, doctrine created me migrations. But do not create any another columns besides Id? where is my problem? Symfony 4, Postgres 11

Viewing all 3924 articles
Browse latest View live


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