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

Symfony 4.3 validation doesn't work - not even the automatic

$
0
0

everyone. There is a similar question posted here, but the answer does not solve my error.

I'm trying to use Symfony 4.3 automatic validation on an entity, but it just doesn't work.

I've uncommented the two lines from validator.yaml and I have enabled validation: {enable_annotations: true} in framework.yaml config file, and it still does not work.

Even if I add or remove @Assert annotations from the entity, the validation always returns a zero-length array.

This is my entity class:

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Company
 *
 * @ORM\Table(name="company")
 * @ORM\Entity(repositoryClass="App\Repository\CompanyRepository")
 */

class Company
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="type", type="string", length=255, nullable=false)
     * @Assert\NotNull
     */
    public $type;
}

As you can see, the type attribute cannot be null, but the validation is not working as expected. This is it:

$company = new Company();
$validator = Validation::createValidator();
$errors = $validator->validate($company);

At this point, $errors is just an empty array.

Is there any extra configuration needed? Does anybody have a theory?


How to have the placeholder translated in an EntityType?

$
0
0

I'm building a form which has an EntityType element, the problem I have is that I'm unable to have the placeholder translated.

Here is my code:

$builder
        ->add('Products', EntityType::class, [
            'mapped' => false,
            'expanded' => true,
            'multiple' => false,
            'required' => false,
            'class' => Product::class,
            'choices' => $options['step']->getProducts(),
            'placeholder' => 'form.mat.alreadyOwned',
            'label' => 'form.mat.alreadyOwned',
            'translation_domain' => 'messages'
        ])

When I use the form.mat.alreadyOwnedtranslation as the label it works fine, but I would like to use it in the placeholder instead. What am I missing?

Looking forward to any tips or tricks that you have to offer!

Extract translations from FormType in Symfony4

$
0
0

Is it possible to extract placeholders and titles translations from FormType class in Symfony4 using console command php bin/console translation:update --force uz ?

  {
      $builder
          ->add('title', null, [
              'attr' => ['placeholder' => 'job_title_placeholder'],
              'attr_translation_parameters' => [
                  'job_title_placeholder' => 'What needs to be done',
              ],
          ])
          ->add('description', TextareaType::class, [
              'attr' => ['placeholder' => 'job_description_placeholder'],
              'attr_translation_parameters' => [
                  'job_description_placeholder' => 'Describe project details',
              ],
          ])

After successful extracting keys 'job_title_placeholder' and 'description_title_placeholder' are not added to translation file

Convert Mailbox E-mail to Case

$
0
0

During email synchronization emails from mailbox doesn't convert in to case (or lead). How could I run this process?

I use oro crm 4 application, reconfigured mailbox according to documentation.
Email synchronization runs successfully by 'oro:cron:imap-sync' command. There are no errors or exceptions during executing, but also no new cases (or leads).

Omines Datatables - Depth > 2, multiple relation support with orderable/search functionalities

$
0
0

I tried to get this working:

$table = $this->createDataTable()
                ->add('firstname', TextColumn::class, ['label' => 'Vorname', 'orderable'=> true, 'field' => 'personalData.firstname'])
                ->add('lastname', TextColumn::class, ['label' => 'Nachname', 'orderable'=> true, 'field' => 'personalData.lastname'])
                ->add('email', TextColumn::class, ['label' => 'Nachname', 'orderable'=> true, 'field' => 'personalData.lastname'])
                ->add('phone', TextColumn::class, ['label' => 'Telefon', 'orderable'=> true, 'field' => 'personalData.phone'])
                ->add('mobilePhone', TextColumn::class, ['label' => 'Mobil', 'orderable'=> true, 'field' => 'personalData.mobilePhone'])
                ->add('gender', TextColumn::class, ['label' => 'Gender', 'orderable'=> true, 'field' => 'personalData.gender.abbreviation'])
                ->add('lastModified', DateTimeColumn::class, ['label' => 'letzte Änderung', 'orderable'=> true, 'format' => 'd.m.Y H:i:s'])
                ->add('dateCreated', DateTimeColumn::class, ['label' => 'Datum Erstellung', 'orderable'=> true, 'format' => 'd.m.Y H:i:s'])
                ->add('actions', TextColumn::class, ['label' => 'Aktionen', 'orderable'=> false, 'render' => function($value, $context) {
                        $user_id = $context->getId();
                        return sprintf('<button type="button" data-user-id="%s" class="btn btn-primary edit-user-btn"><i class="fas fa-pencil-alt fa-fw fa-fw"></i></button><button type="button" data-user-id="%s" class="btn btn-danger del-user-btn margin-left-10"><i class="fas fa-trash fa-fw fa-fw"></i></button>', $user_id, $user_id);
                    }])
                ->createAdapter(ORMAdapter::class, [
            'entity' => User::class,
        ]);

This results in the following error: Catchable Fatal Error: Object of class App\Entity\Gender could not be converted to string

So as workaround I could add the __toString method to the entity but unfortunately it does not solve the problem so that this column is also orderable.

Then I tried this approach:

$table = $this->createDataTable()
                ->add('firstname', TextColumn::class, ['label' => 'Vorname', 'orderable'=> true, 'field' => 'personalData.firstname'])
                ->add('lastname', TextColumn::class, ['label' => 'Nachname', 'orderable'=> true, 'field' => 'personalData.lastname'])
                ->add('email', TextColumn::class, ['label' => 'Nachname', 'orderable'=> true, 'field' => 'personalData.lastname'])
                ->add('phone', TextColumn::class, ['label' => 'Telefon', 'orderable'=> true, 'field' => 'personalData.phone'])
                ->add('mobilePhone', TextColumn::class, ['label' => 'Mobil', 'orderable'=> true, 'field' => 'personalData.mobilePhone'])
                ->add('gender', TextColumn::class, ['label' => 'Geschlecht', 'orderable'=> true, 'render' => function($value ,$context) {
                        $user_id = $context->getId();

                        $user = $this->getDoctrine()
                                ->getRepository(User::class)
                                ->findOneBy(['id' => $user_id]);

                        return $user->getPersonalData()->getGender()->getAbbreviation();
                    }])
                ->add('lastModified', DateTimeColumn::class, ['label' => 'letzte Änderung', 'orderable'=> true, 'format' => 'd.m.Y H:i:s'])
                ->add('dateCreated', DateTimeColumn::class, ['label' => 'Datum Erstellung', 'orderable'=> true, 'format' => 'd.m.Y H:i:s'])
                ->add('actions', TextColumn::class, ['label' => 'Aktionen', 'orderable'=> false, 'render' => function($value, $context) {
                        $user_id = $context->getId();
                        return sprintf('<button type="button" data-user-id="%s" class="btn btn-primary edit-user-btn"><i class="fas fa-pencil-alt fa-fw fa-fw"></i></button><button type="button" data-user-id="%s" class="btn btn-danger del-user-btn margin-left-10"><i class="fas fa-trash fa-fw fa-fw"></i></button>', $user_id, $user_id);
                    }])
                ->createAdapter(ORMAdapter::class, [
            'entity' => User::class,
        ]);

Now I can see the table loading but if I try to order the table I'm getting the following error message:

Doctrine\ORM\Query\QueryException:
[Syntax Error] line 0, col -1: Error: Expected Doctrine\ORM\Query\Lexer::T_IDENTIFIER, got end of string.

  at vendor/doctrine/orm/lib/Doctrine/ORM/Query/QueryException.php:54
  at Doctrine\ORM\Query\QueryException::syntaxError('line 0, col -1: Error: Expected Doctrine\\ORM\\Query\\Lexer::T_IDENTIFIER, got end of string.', object(QueryException))
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:457)
  at Doctrine\ORM\Query\Parser->syntaxError('Doctrine\\ORM\\Query\\Lexer::T_IDENTIFIER')
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:325)
  at Doctrine\ORM\Query\Parser->match(102)
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:1022)
  at Doctrine\ORM\Query\Parser->ResultVariable()
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:1521)
  at Doctrine\ORM\Query\Parser->OrderByItem()
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:1408)
  at Doctrine\ORM\Query\Parser->OrderByClause()
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:884)
  at Doctrine\ORM\Query\Parser->SelectStatement()
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:848)
  at Doctrine\ORM\Query\Parser->QueryLanguage()
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:261)
  at Doctrine\ORM\Query\Parser->getAST()
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:360)
  at Doctrine\ORM\Query\Parser->parse()
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query.php:286)
  at Doctrine\ORM\Query->_parse()
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query.php:234)
  at Doctrine\ORM\Query->getResultSetMapping()
     (vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php:902)
  at Doctrine\ORM\AbstractQuery->iterate(array(), 1)
     (vendor/doctrine/orm/lib/Doctrine/ORM/Query.php:689)
  at Doctrine\ORM\Query->iterate(array(), 1)
     (vendor/omines/datatables-bundle/src/Adapter/Doctrine/ORMAdapter.php:205)
  at Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapter->getResults(object(Query))
     (vendor/omines/datatables-bundle/src/Adapter/AbstractAdapter.php:51)
  at Omines\DataTablesBundle\Adapter\AbstractAdapter->getData(object(DataTableState))
     (vendor/omines/datatables-bundle/src/DataTable.php:372)
  at Omines\DataTablesBundle\DataTable->getResultSet()
     (vendor/omines/datatables-bundle/src/DataTable.php:331)
  at Omines\DataTablesBundle\DataTable->getResponse()
     (src/Controller/UsersController.php:100)
  at App\Controller\UsersController->getUsers(object(Request))
     (vendor/symfony/http-kernel/HttpKernel.php:151)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
     (vendor/symfony/http-kernel/HttpKernel.php:68)
  at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
     (vendor/symfony/http-kernel/Kernel.php:198)
  at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
     (public/index.php:24)

So I have an Entity "User" and this has a relation to the entity "personalData" - in addition "personalData" has a relation to "gender" --> I want to have the gender data displayed in the datatables and keep the order and search functionalities working

Is there any workaround or is this a bug?

How to create a composer package for Symfony [closed]

$
0
0

I'm using Symfony 4 and want to create a composer package.

I want to put my Symfony project files on GitHub and create a composer package from the repository.

Does anyone have any advise on how to go about this.

Symfony 4.3 : Dynamic form management

$
0
0

I'm trying to implement a dynamic form with Symfony 4.3 based on the official documentation.

To simplicify, I have 3 entities: product, category and subcategory related to each other with OneToMany relationships as follows: a category can have multiple subcategories and a subcategory can have multiple products. By choosing a category (sport for example), I wanted to have the list of sport sub-categories displayed in the following field.

class ProductType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('nom')
        ->add('categorie', EntityType::class, [
            'class'       => 'App\Entity\Categorie',
            //'placeholder' => '',
        ])
    ;



    $formModifier = function (FormInterface $form, Categorie $categorie = null) {
        $subcategories = null === $categorie ? [] : $categorie->getSubcategories();
        //var_dump($subcategories);
        $form->add('subcategorie', EntityType::class, [
            'class' => 'App\Entity\Subcategorie',
            //'placeholder' => '',
            'choices' => $subcategories,
        ]);
    };

    $builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function (FormEvent $event) use ($formModifier) {
            // this would be your entity
            $data = $event->getData();
            //var_dump($data);
            //die;
            $formModifier($event->getForm(), $data->getCategorie());
        }
    );

    $builder->get('categorie')->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) use ($formModifier) {
            $categorie = $event->getForm()->getData();

            $formModifier($event->getForm()->getParent(), $categorie);
        }
    );
//...
}

My concern is that I can not getthe value of my dumps ($data and $subcategories): they are always on NULL. So, I can not find my subcategories in the form.

I'm asking because I'm really blocked for a while and I can not find the bug in this code based on the Symfony documentation.

Symfony 4 - Some difficults with Cascade={'persist','remove'}

$
0
0

and sorry for my English, I'm French so I use a translator. Here is a part of my model to illustrate my words:

enter image description here

So that's the trouble. I am in my Admin Settings page. On this page I will be able to add / delete holiday types. But when I delete types of holidays, it would have to delete things cascading in the database.

In fact the principle of the site is the following:

Users ask for their holidays. For that they give the type of leave for which they will be absent. And for each type of holiday, users have a balance.

So I have this:

ParametresAdmin.php:

/**
     * @ORM\OneToMany(targetEntity="App\Entity\TypeConge", mappedBy="parametresAdmin", orphanRemoval=true, cascade={"persist", "remove"})
     */
    private $typesConges;

TypeConge.php:

/**
     * @ORM\Column(type="string", length=255, unique=true)
     */
    private $nom;
/**
     * @ORM\OneToMany(targetEntity="App\Entity\Absence", mappedBy="typeConge", cascade={"persist", "remove"})
     */
    private $absences;

SoldeConges.php:

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\TypeConge", cascade={"persist", "remove"})
 * @ORM\JoinColumn(nullable=false)
 */
private $typeConge;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="soldeConges")
 * @ORM\JoinColumn(nullable=false)
 */
private $user;

/**
 * @ORM\Column(type="float", nullable=true)
 */
private $solde;

Absence.php:

/**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="absences")
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;
/**
     * @ORM\ManyToOne(targetEntity="App\Entity\TypeConge", inversedBy="absences")
     * @ORM\JoinColumn(nullable=false)
     */
    private $typeConge;

User.php:

/**
     * @ORM\OneToMany(targetEntity="App\Entity\SoldeConges", mappedBy="user", orphanRemoval=true, fetch="EAGER", cascade={"remove"})
     */
    private $soldeConges;
/**
     * @ORM\OneToMany(targetEntity="App\Entity\Absence", mappedBy="user", orphanRemoval=true)
     */
    private $absences;

So, in my admin settings, if I delete a type of leave, it must follow this pattern:

  • Suppression of absences related to the type of leave.
  • Removal of the 'soldeUser' from User, for balances that are related to the type of leave.
  • Suppression of the 'typeConge' (type of holiday)

But whith my code, I've this error when I try to delete a type of holiday :

An exception occurred while executing 'DELETE FROM type_conge WHERE id = ?' with params [9]:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (congestest2.solde_conges, CONSTRAINT FK_BE0A8BDB753BDA5 FOREIGN KEY (type_conge_id) REFERENCES type_conge (id))


Symfony 4 : DataFixtures directory not found

$
0
0

I'am using symfony 4

I have created an make called Ad:entity with this commande php bin/console make:entity

Ad.php

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

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

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

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

/**
 * @ORM\Column(type="float")
 */
private $price;

/**
 * @ORM\Column(type="text")
 */
private $introduction;

/**
 * @ORM\Column(type="text")
 */
private $content;

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

/**
 * @ORM\Column(type="integer")
 */
private $rooms;

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

public function getTitle(): ?string
{
    return $this->title;
}

public function setTitle(string $title): self
{
    $this->title = $title;

    return $this;
}

public function getSlug(): ?string
{
    return $this->slug;
}

public function setSlug(string $slug): self
{
    $this->slug = $slug;

    return $this;
}

public function getPrice(): ?float
{
    return $this->price;
}

public function setPrice(float $price): self
{
    $this->price = $price;

    return $this;
}

public function getIntroduction(): ?string
{
    return $this->introduction;
}

public function setIntroduction(string $introduction): self
{
    $this->introduction = $introduction;

    return $this;
}

public function getContent(): ?string
{
    return $this->content;
}

public function setContent(string $content): self
{
    $this->content = $content;

    return $this;
}

public function getCoverImage(): ?string
{
    return $this->coverImage;
}

public function setCoverImage(string $coverImage): self
{
    $this->coverImage = $coverImage;

    return $this;
}

public function getRooms(): ?int
{
    return $this->rooms;
}

public function setRooms(int $rooms): self
{
    $this->rooms = $rooms;

    return $this;
}
}

And i want to use a package : orm-fixtures

so i runed this command : composer require orm-fixtures --dev

But i don't see the DataFixtures in my project folder, screenshot : https://user.oc-static.com/upload/2019/11/01/15726034821433_Screenshot%20from%202019-11-01%2011-12-38.png

Symfony 4 custom deserializer returns empty properties in entity

$
0
0

I have a custom Symfony 4 deserializer

class CardImageDecoder implements EncoderInterface, DecoderInterface
{
    public function encode($data, $format, array $context = [])
    {
        if($format !== 'json') {
            throw new EncodingFormatNotSupportedException(sprintf('Format %s is not supported by encoder %s', $format, __CLASS__));
        }

        $result = json_encode($data);

        if(json_last_error() !== JSON_ERROR_NONE) {
            // don't bother with a custom error message
            throw new \Exception(sprintf('Unable to encode data, got error message: %s', json_last_error_msg()));
        }

        return $result;
    }

    public function supportsEncoding($format)
    {
        return 'json' === $format;
    }

    public function decode($data, $format, array $context = [])
    {
        if($format !== 'array') {
            throw new DecodingFormatNotSupportedException(sprintf('Format %s is not supported by encoder %s', $format, __CLASS__));
        }

        if(!is_array($data)) {
            throw new \UnexpectedValueException(sprintf('Expected array got %s', gettype($data)));
        }

        $cardInstance = new CardImages();
        $cardInstance->setHeight($data['h'] ?? 0);
        $cardInstance->setPath($data['url'] ?? '');
        $cardInstance->setWidth($data['w'] ?? 0);

        return $cardInstance;
    }

    public function supportsDecoding($format)
    {
        return 'array' === $format;
    }
}

The way I'm deserializing is pretty straight forward:

$json = '
{
"url": "some url",
"h": 1004,
"w": 768
}';

$encoders = [new CardImageDecoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);

$cardImage = $serializer->deserialize(json_decode($json, true), CardImages::class, 'array');

/** @var $cardImage CardImages */
var_dump($cardImage);

However, I get this result returned:

object(App\Entity\CardImages)#158 (5) {
  ["id":"App\Entity\CardImages":private]=>
  NULL
  ["path":"App\Entity\CardImages":private]=>
  NULL
  ["height":"App\Entity\CardImages":private]=>
  NULL
  ["width":"App\Entity\CardImages":private]=>
  NULL
  ["movie":"App\Entity\CardImages":private]=>
  NULL
}

Now, if I were to do a dump, just before the return in the decode part of the decoder, I'd get this:

...
$cardInstance->setWidth($data['w'] ?? 0);

var_dump($cardInstance);

object(App\Entity\CardImages)#153 (5) {
  ["id":"App\Entity\CardImages":private]=>
  NULL
  ["path":"App\Entity\CardImages":private]=>
  string(8) "some url"
  ["height":"App\Entity\CardImages":private]=>
  int(1004)
  ["width":"App\Entity\CardImages":private]=>
  int(768)
  ["movie":"App\Entity\CardImages":private]=>
  NULL
}

Ignoring the not set properties(which I'm fine with), it should work quite nicely, but it doesn't.

For the life of me I can't figure out what's wrong.

Any help is appreciated.

Is it possible to move symfony 1.x project to symfony 4.x (latest)?

$
0
0

I have a project which is using symfony 1.x with PHP 5.3. I want to upgrade it to the latest version of symfony which is 4.x.

My first question is, is it possible ?

If it is how to do that ?

else do I have to code it from the scratch using the symfony 4 ?

The service "security.authentication.provider.guard.main" has a dependency on a non-existent service "App\Security\LoginFormAuthenticator"

$
0
0

i have a project developed with symfony 4.3, i try to add the guard authentication service using make:auth command.

i have this line error :

The service "security.authentication.provider.guard.main" has a dependency on a non-existent service "App\Security\LoginFormAuthenticator"

User Deprecated: Auto-injection of the container for "App\Controller\SecurityController" is deprecated since Symfony 4.2. Configure it as a service instead.

in the services.yaml, i put these lines:

App\:
    resource: '../src/*'
    exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

# controllers are imported separately to make sure Services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

Symfony 4 handling null DateType form field

$
0
0

I have a form in Symfony 4 where I implement the DateType as a text field

->add('DateOfBirth', DateType::class, array(
    'required' => false,
    'widget' => 'single_text',
    'empty_data' =
))

however the field is optional to fill in for the form. When I submit the form with an empty value for that field I receive the error:

Expected argument of type "DateTimeInterface", "NULL" given.

erroring on the line

$form->handleRequest($request);

It seems I need to pass in a default value (i.e. - 1/1/1990) as null is not a valid DateTime value? What is the correct way to handle this? I looked on this page and tried various things (i.e. - changing input type) but nothing seems to fix this.

Thanks in advance!

My Entity:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use NoProtocol\Encryption\MySQL\AES\Crypter;

/**
 * @ORM\Entity(repositoryClass="App\Repository\PatientsRepository")
 * @ORM\Table(name="Patients")
 */
class PatientSearch
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="integer")
     */
    private $PatientId;

    /**
     * @ORM\Column(type="string", length=100, nullable=true)
     */
    private $Address1;

    /**
     * @ORM\Column(type="string", length=100, nullable=true)
     */
    private $Address2;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $City;

    /**
     * @ORM\Column(type="string", length=2, nullable=true)
     */
    private $State;

    /**
     * @ORM\Column(type="date", nullable=true)
     */
    private $DateOfBirth;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $LastName;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $FirstName;

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

    public function getPatientId(): ?int
    {
        return $this->PatientId;
    }

    public function setPatientId(int $PatientId): self
    {
        $this->PatientId = $PatientId;

        return $this;
    }

    public function getAddress1(): ?string
    {
        return $this->Address1;
    }

    public function setAddress1(string $Address1): self
    {
        $this->Address1 = $Address1;

        return $this;
    }

    public function getAddress2(): ?string
    {
        return $this->Address2;
    }

    public function setAddress2(string $Address2): self
    {
        $this->Address2 = $Address2;

        return $this;
    }

    public function getCity(): ?string
    {
        return $this->City;
    }

    public function setCity(string $City): self
    {
        $this->City = $City;

        return $this;
    }

    public function getState(): ?string
    {
        return $this->State;
    }

    public function setState(string $State): self
    {
        $this->State = $State;

        return $this;
    }

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

    public function setDateOfBirth(\DateTimeInterface $DateOfBirth): self
    {
        $this->DateOfBirth = $DateOfBirth;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->LastName;
    }

    public function setLastName(string $LastName): self
    {
        $this->LastName = $LastName;

        return $this;
    }

    public function getFirstName(): ?string
    {
        return $this->FirstName;
    }

    public function setFirstName(string $FirstName): self
    {
        $this->FirstName = $FirstName;

        return $this;
    }
}

Type:

<?php

namespace App\Form;

use App\Entity\PatientSearch;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PatientSearchType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('FirstName', TextType::class, array('required' => false))
            ->add('LastName', TextType::class, array('required' => false))
            ->add('DateOfBirth', DateType::class, array(
                'required' => false,
                'widget' => 'single_text',
                'empty_data'  => '',
                ))
        ;
    }

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

Controller:

<?php

namespace App\Controller;

use App\Form\PatientSearchType;
use App\Entity\PatientSearch;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;

class PatientSearchController extends AbstractController
{
    /**
     * @Route("/patient/search", name="patient_search")
     */
    public function index(Request $request)
    {
        $form = $this->createForm(PatientSearchType::class);

        $form->handleRequest($request);

        dump($form);
        dump($form->isValid());

        $search = null;
        if ($form->isSubmitted() && $form->isValid()) {
            $searchFormData = $form->getData();
            dump($searchFormData);
            $search = $this->getDoctrine()
                ->getRepository(PatientSearch::class)
                ->findBy(array(
                    'LastName' => $searchFormData->getLastName(),
                    'FirstName' => $searchFormData->getFirstName(),
                    'DateOfBirth' => $searchFormData->getDateOfBirth(),
                    ));

        }

        return $this->render('patient_search/index.html.twig', [
            'search_form' => $form->createView(),
            'search' => $search
        ]);
    }
}

Error Dump (after setting 'empty_data' =>'1/1/2000)':

FormErrorIterator {#542 ▼
  -form: Form {#507 ▼
    -config: FormBuilder {#508 ▶}
    -parent: null
    -children: OrderedHashMap {#509 ▼
      -elements: array:3 [▼
        "FirstName" => Form {#510 ▶}
        "LastName" => Form {#513 ▶}
        "DateOfBirth" => Form {#516 ▼
          -config: FormBuilder {#517 ▶}
          -parent: Form {#507}
          -children: OrderedHashMap {#518 ▶}
          -errors: array:1 [▼
            0 => FormError {#825 ▼
              #messageTemplate: "This value is not valid."
              #messageParameters: array:1 [▼
                "{{ value }}" => "1/1/2000"
              ]
              #messagePluralization: null
              -message: "This value is not valid."
              -cause: ConstraintViolation {#794 ▼
                -message: "This value is not valid."
                -messageTemplate: "This value is not valid."
                -parameters: array:1 [▶]
                -plural: null
                -root: Form {#507}
                -propertyPath: "children[DateOfBirth]"
                -invalidValue: "1/1/2000"
                -constraint: Form {#532 ▶}
                -code: "1dafa156-89e1-4736-b832-419c2e501fca"
                -cause: TransformationFailedException {#520 ▶}
              }
              -origin: Form {#516}
            }
          ]
          -submitted: true
          -clickedButton: null
          -modelData: null
          -normData: null
          -viewData: "1/1/2000"
          -extraData: []
          -transformationFailure: TransformationFailedException {#520 ▼
            #message: "Unable to reverse value for property path "DateOfBirth": Date parsing failed: U_PARSE_ERROR"
            #code: 0
            #file: "/mnt/c/Users/ElementZero/source/php/phleb-manager/vendor/symfony/form/Form.php"
            #line: 1137
            -previous: TransformationFailedException {#523 ▶}
            trace: {▶}
          }
          -defaultDataSet: true
          -lockSetData: false
        }
      ]
      -orderedKeys: array:3 [▶]
      -managedCursors: []
    }
    -errors: []
    -submitted: true
    -clickedButton: null
    -modelData: PatientSearch {#501 ▶}
    -normData: PatientSearch {#501 ▶}
    -viewData: PatientSearch {#501 ▶}
    -extraData: []
    -transformationFailure: null
    -defaultDataSet: true
    -lockSetData: false
  }
  -errors: []
}

symfony 4 app engine deploy Attempted to load class "Kernel" from namespace "App"

$
0
0

Error below not occuring on local machine, sounds like PSR issues but PSR if correctly configured

Attempted to load class "Kernel" from namespace "App". Did you forget a "use" statement for "Symfony\Component\HttpKernel\Kernel"

Autoload in composer file

"autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },

Symfony version 4.3

Unable to run dev- server (npm)

$
0
0

For some reason i cant launch npm run dev-server

enter image description here

If someone have a solution to solve this problem please, let me know.


how to encode password with special character for swiftmailer .env

$
0
0

I'm using Swiftmail to send emails with gmail.I have configured the MAILER_URL in my .env. But my password has got a special character in it. I've read that you must encode your password when there is a special character but I don't know how.

# For Gmail as a transport, use: "gmail://username:password@localhost"
# For a generic SMTP server, use: "smtp://localhost:25?encryption=&auth_mode="
# Delivery is disabled by default via "null://localhost"
MAILER_URL=gmail://landabravo@gmail.com:landaB/24@localhost
###< symfony/swiftmailer-bundle ###```

How to set default choiceType in symfony or twig

$
0
0

I am trying to get default radio checked with symfony or twig but i am not able to do

for example i have a gender form field that contains male and female and i want to have one of them to be checked by default

i looked in symfony documentation but i din't find any solution

This is the formfield that i want to set a default

->add('gender', ChoiceType::class, [
      'choices' => [
           'Male' => 'male',
           'Female' => 'female',
       ],
       'expanded' => true
])

This is twig code

{% for gender in form.member.gender %}
  {{
       form_row(gender, {label_attr: {'class': 'radio-custom'}})
  }}
{% endfor %}

Requirements could not be resolved

$
0
0

I am on Linux Ubuntu and I have a Symfony 4 project and I did not succeed to make that functions. After updating my OS, I have a problem. When I launch for this project:

composer install

I got this message:

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for nexylan/slack v2.0.0 -> satisfiable by nexylan/slack[v2.0.0].
    - nexylan/slack v2.0.0 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
  Problem 2
    - Installation request for symfony/framework-bundle v4.0.14 -> satisfiable by symfony/framework-bundle[v4.0.14].
    - symfony/framework-bundle v4.0.14 requires ext-xml * -> the requested PHP extension xml is missing from your system.
  Problem 3
    - Installation request for symfony/debug-bundle v4.0.4 -> satisfiable by symfony/debug-bundle[v4.0.4].
    - symfony/debug-bundle v4.0.4 requires ext-xml * -> the requested PHP extension xml is missing from your system.
  Problem 4
    - symfony/framework-bundle v4.0.14 requires ext-xml * -> the requested PHP extension xml is missing from your system.
    - symfony/maker-bundle v1.4.0 requires symfony/framework-bundle ^3.4|^4.0 -> satisfiable by symfony/framework-bundle[v4.0.14].
    - Installation request for symfony/maker-bundle v1.4.0 -> satisfiable by symfony/maker-bundle[v1.4.0].

  To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/7.4/cli/php.ini
    - /etc/php/7.4/cli/conf.d/10-opcache.ini
    - /etc/php/7.4/cli/conf.d/10-pdo.ini
    - /etc/php/7.4/cli/conf.d/20-apcu.ini
    - /etc/php/7.4/cli/conf.d/20-calendar.ini
    - /etc/php/7.4/cli/conf.d/20-ctype.ini
    - /etc/php/7.4/cli/conf.d/20-exif.ini
    - /etc/php/7.4/cli/conf.d/20-ffi.ini
    - /etc/php/7.4/cli/conf.d/20-fileinfo.ini
    - /etc/php/7.4/cli/conf.d/20-ftp.ini
    - /etc/php/7.4/cli/conf.d/20-gettext.ini
    - /etc/php/7.4/cli/conf.d/20-iconv.ini
    - /etc/php/7.4/cli/conf.d/20-imagick.ini
    - /etc/php/7.4/cli/conf.d/20-json.ini
    - /etc/php/7.4/cli/conf.d/20-phar.ini
    - /etc/php/7.4/cli/conf.d/20-posix.ini
    - /etc/php/7.4/cli/conf.d/20-readline.ini
    - /etc/php/7.4/cli/conf.d/20-shmop.ini
    - /etc/php/7.4/cli/conf.d/20-sockets.ini
    - /etc/php/7.4/cli/conf.d/20-sysvmsg.ini
    - /etc/php/7.4/cli/conf.d/20-sysvsem.ini
    - /etc/php/7.4/cli/conf.d/20-sysvshm.ini
    - /etc/php/7.4/cli/conf.d/20-tokenizer.ini
    - /etc/php/7.4/cli/conf.d/20-xdebug.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Can you help me to solve this problem?

Show form errors

$
0
0

I would like to show error messages in the top of my registration form. I created my registration form:

<div class="example-wrapper">
<h1>Register</h1>
{{ form_start(form) }}
    {{ form_row(form.email) }}
    {{ form_row(form.plainPassword.first) }}
    {{ form_row(form.plainPassword.second) }}
    {{ form_row(form.firstname) }}
    {{ form_row(form.lastname) }}
    {{ form_row(form.termsAccepted) }}
    <button type="submit">Register!</button>
{{ form_end(form) }}
</div>

And on my UserType class, I added all necessaries input:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
       ->add('email', EmailType::class)
       ->add('plainPassword', RepeatedType::class, array(
            'type' => PasswordType::class,
            'first_options' => array('label' => 'Password'),
            'second_options' => array('label' => 'Repeat Password'),
            'constraints' => [
                new NotBlank([
                    'message' => 'Enter a valid password.'
                ]),
                new Length([
                    'min' => 8,
                    'minMessage' => 'Password must be at least 8 characters.'
                ])
            ]
         ))
         ->add('firstname', TextType::class)
         ->add('lastname', TextType::class)
         ->add('termsAccepted', CheckboxType::class, array(
              'mapped' => false,
              'constraints' => new IsTrue(),
         ))
        ;
    }}

Every time I get an error message, correctly displayed, I found it under the concerned input and not in the top of my registration form. I added this on my form but don't help:

{{ form_errors(form) }}

Any suggestion?

@IsGranted annotation on property of subject

$
0
0

I have annotation (working)

@IsGranted("editBlog", subject="company")

but I want something like this (not working):

@IsGranted("edit", subject="company.blog")

"Company" and "Blog" are Doctrine Entities with OneToOne relation. But my action have only "company" parameter.

    /**
     * @IsGranted("editBlog", subject="company")
     * @param CompanyEntity $company
       ...
     * @return Response
     */
    final public function defaultAction(
        CompanyEntity $company,
        ...
    )
    {
     ...
    }

How to access a variable in a subject?

Thanks!

Viewing all 3917 articles
Browse latest View live


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