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

Upoaded image's too big : a circular reference occurs

$
0
0

I'm trying to build a subscription form with Symfony4 and I tought it was working but it appears that when I try to upload a profile picture that is too big, I've got the following error : A circular reference has been detected when serializing the object of class "App\Entity\User" (configured limit: 1)

However I did set a constraint on my property profilePicture regarding the file's maxSize the user will try to upload so I do not understand why this is happening (I've got all the other errors displaying well).

Here is the part of code regarding the property profilePicture :

/**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank(message="Merci de bien vouloir sélectionner une image")
     * @Assert\Image(
     *     minRatio="1",
     *     maxRatio="1",
     *     minWidth="250",
     *     minHeight="250",
     *     minRatioMessage="Votre photo de profil doit avoir un ratio de 1:1",
     *     maxRatioMessage="Votre photo de profil doit avoir un ratio de 1:1",
     *     minWidthMessage="Votre image doit faire minimum {{ minWidth }} de large",
     *     maxWidthMessage="Votre image doit faire minimun {{ minHeight }} de hauteur", 
     *     maxSize="2M",
     *     maxSizeMessage="Votre image ne peut pas fait plus de 2M")
     */
    private $profilePicture;

The HomeController dealing with the subscription form :

/**
     * @Route("/", name="home")
     */
    public function index(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        //To Manage registration
        $user = new User();
        $form = $this->createForm(RegistrationFormType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && !$form->isValid()) {
            return $this->json([
                "status" => "error(s)",
                "errors" => $form->getErrors(true, true)
            ], 200);
        }
        if ($form->isSubmitted() && $form->isValid()) {
            // move the file from the temp folder
            $fileUploader = new FileUploader($this->getParameter('profile_pictures_directory'));
            $profilePicture = $form['userProfile']['profilePicture']->getData();
            if ($profilePicture) {
                $profilePictureFilename = $fileUploader->upload($profilePicture);
                $user->getUserProfile()->setProfilePicture($profilePictureFilename);
            }
            // encode the plain password
            $user->setPassword(
                $passwordEncoder->encodePassword(
                    $user,
                    $form->get('plainPassword')->getData()
                )
            );
            $user->setCreationDate(new \DateTime());

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();

            // do anything else you need here, like send an email

            return $this->json(["status" => "success"]);
        }

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

The FileUploader service :

<?php
namespace App\Service;

use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileUploader
{
    private $targetDirectory;

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

    public function upload(UploadedFile $file)
    {
        $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
        $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
        $fileName = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
        try {
            $file->move($this->getTargetDirectory(), $fileName);
        } catch (FileException $e) {

        }

        return $fileName;
    }

    public function getTargetDirectory()
    {
        return $this->targetDirectory;
    }
}

There is a OneToOne relation between the entity User and the entity UserProfile where complementary data regarding the User are stored.

I'd like this to simply display the error message regarding the file size like it does for all the other types of errors. Let me know if you need other parts of my code.


Change database connection in Migration class in Symfony

$
0
0

In migration class depending on logic, I need to use different types of database connections. How in migration class to get new connection by connection name?

Currently in doctrine.yaml file I have connection names "default", "user", "admin" and "cron".

My migration class:

final class Version20190711123152 extends AbstractMigration
{
     public function up(Schema $schema) : void
     { 
        ...

        if($someCondition) {
            $this->setConnection($wantedConnection) // how to set $wantedConnection for example on "admin" connection
        }
     }

    /**
     * @param Connection $connection
     */
    public function setConnection(Connection $connection): void
    {
        $this->connection = $connection;
    }

I am using Symfony 4.3

Embedded form render wrong input type

$
0
0

To allow customisation of the registration form, some form fields are generated from database informations and the form in embedded into the registration form.

While each fields of the embedded form is typed, for some reason, when I render them using twig, some types like url or number are rendered as text type input.

Yet, all fields form the main form (nom, prenom, email, plainPassword) are rendered with the assigned type.

As you can see in the code fragments, I'm properly using form_widget and form_widget to render each input, thus type handling is done by Symfony.

When I dump each formView for each field, within field.vars.block_prefixes (array), I can find the type of the input as it should be.

As example, this is the content of a text input :

"block_prefixes" => array:3 [▼
  0 => "form"
  1 => "text"
  2 => "_security_extraDataCollection_datum-30"
]

The content of a url input :

"block_prefixes" => array:4 [▼
  0 => "form"
  1 => "text"
  2 => "url"
  3 => "_security_extraDataCollection_datum-31"
]

And the content of a number input :

"block_prefixes" => array:3 [▼
  0 => "form"
  1 => "number"
  2 => "_security_extraDataCollection_datum-33"
]

At first, I thought that was because I was using material-component-web, but even without CSS, this problem occur.

Any idea as to why url and number type are turned to text type when I render them from enbedded form?

Registration form

public function buildForm(FormBuilderInterface $builder, array $options) {
    /** @var array $extraData */
    $extraData=$options['extra_data'];

    $builder->add('nom')
            ->add('prenom')
            ->add('email', EmailType::class)
            ->add('plainPassword', PasswordType::class, array(
                'mapped'=>false,
                'constraints'=>array(
                    new NotBlank(array(
                        'message'=>'Please enter a password',
                    )),
                    new Length(array(
                        'min'=>6,
                        'max'=>4096,
                    )),
                ),
            ));

    if($extraData !== null && is_array($extraData) && count($extraData)) {
        $builder->add('extraDataCollection', UnmappedMixedType::class, array(
            'mapped'=>false,
            'data'=>$extraData,
        ));
    }
}

UnmappedMixedType form

public function buildForm(FormBuilderInterface $builder, array $options) {
    /** @var array $extraData */
    $extraData=$options['data'];

    /** @var ExtraData $extraDatum */
    foreach($extraData as $extraDatum) {
        if($extraDatum->getType() == 'text') {
            $builder->add('datum-'.$extraDatum->getId(), TextType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
            ));
        } elseif($extraDatum->getType() == 'url') {
            $builder->add('datum-'.$extraDatum->getId(), UrlType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
            ));
        } elseif($extraDatum->getType() == 'number') {
            $builder->add('datum-'.$extraDatum->getId(), NumberType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
            ));
        } elseif($extraDatum->getType() == 'checkbox') {
            $builder->add('datum-'.$extraDatum->getId(), CheckboxType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
            ));
        } elseif($extraDatum->getType() == 'choice' && $extraDatum->getChoix() !== null && count($extraDatum->getChoix()) >= 1) {
            $builder->add('datum-'.$extraDatum->getId(), ChoiceType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
                'multiple'=>$extraDatum->getIsChoixMultipleUtilisateur(),
                'choices'=>array_combine($extraDatum->getChoix(), $extraDatum->getChoix()),
            ));
        }
    }
}

Twig view

{% if form.extraDataForm is defined %}
    <div class="app-auth-left-frame-extra">
        <div class="app-form-container">
            <div class="app-form_field-container">
                {% for field in form.extraDataForm %}
                    {{ dump(field) }}
                    {% if field.vars.block_prefixes[1] == 'text' or field.vars.block_prefixes[1] == 'number' %}
                        <div class="mdc-text-field mdc-text-field--outlined">
                            {{ form_widget(field, {'attr': {'class': 'mdc-text-field__input'}}) }}
                            <div class="mdc-notched-outline">
                                <div class="mdc-notched-outline__leading"></div>
                                <div class="mdc-notched-outline__notch">
                                    {{ form_label(field, null, {'label_attr': {'class': 'mdc-floating-label'}}) }}
                                </div>
                                <div class="mdc-notched-outline__trailing"></div>
                            </div>
                        </div>
                    {% elseif field.vars.block_prefixes[1] == 'checkbox' %}
                        <div class="mdc-form-field">
                            <div class="mdc-checkbox">
                                {{ form_widget(field, {'attr': {'class': 'mdc-checkbox__native-control'}}) }}
                                <div class="mdc-checkbox__background">
                                    <!--suppress HtmlUnknownAttribute -->
                                    <svg class="mdc-checkbox__checkmark" viewBox="0 0 24 24">
                                        <path class="mdc-checkbox__checkmark-path" fill="none" d="M1.73,12.91 8.1,19.28 22.79,4.59"></path>
                                    </svg>
                                </div>
                            </div>
                            {{ form_label(field, null, {'label_attr': {'class': 'app-txt-light-emphasis'}}) }}
                        </div>
                    {% elseif field.vars.block_prefixes[1] == 'choice' %}
                        <div>{{ form_widget(field) }}</div>
                    {% endif %}
                {% endfor %}
            </div>
        </div>
    </div>
{% endif %}

Doctrine only inserts one record after foreach loop

$
0
0

I have a simple array with some values that need to be inserted into the DB. Out of all the values only the last one is actually inserted.

When I put the flush(); inside the loop, records do get inserted.

When I dump the entity manager before the flush (outside the foreach) I do see references to all the values (entities).

Though, only the last record is inserted. It does get id #3, so it seems the other ones are lost somewhere.

    $values = [
        "val1", "val2", "val3"
    ];

    foreach ($values as $value) {
      $i = new MyEntityClass();
      $i->setVerified(false);
      $i->setName($value);
      $this->em->persist($i);
    }
    $this->em->flush();

Update: I hooked up a eventlistener to pre and post flush.

  public function preFlush(PreFlushEventArgs $args) {
    $em = $args->getEntityManager();

    foreach ($em->getUnitOfWork()->getScheduledEntityInsertions() as $entity) {
      dump($entity->getName());
    }
  }

  public function postFlush(PostFlushEventArgs $args) {
    dd($args->getEntityManager()->getUnitOfWork()->getScheduledEntityInsertions());
  }

In the preFlush all values are clearly printed and the postFlush dump is empty.

Update 2: I'm using a uuid_binary_ordered_time as follows

  /**
   * @ORM\Id
   * @ORM\Column(type="uuid_binary_ordered_time", unique=true)
   * @GeneratedValue(strategy="CUSTOM")
   * @CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidOrderedTimeGenerator")
   * @Groups({"uuid"})
   */
  protected $id;

Using 10.4.8-MariaDB and php v7.3.10

Update 3: I'm still trying to figure this out and and now have a different scenario, but am still running into the problem that multiple actions are not executed. Might this be DB configuration related instead of Doctrine?

Case: Gather data from table A and table B, insert data into Table C, delete record from table A.

By following the suggestion from @Jakumi (or looking into the logs) I can see the following queries being executed (spoiler, the row in table A is deleted, but there's no new row in table C):

"queries": {
  "1": {
    "sql": "SELECT t0.email AS email_1, t0.status AS status_2, t0.payment_provider_id AS payment_provider_id_3, t0.payment_method AS payment_method_4, t0.quantity AS quantity_5, t0.price_total AS price_total_6, t0.created_on AS created_on_7, t0.updated_on AS updated_on_8, t0.paid_on AS paid_on_9, t0.id AS id_10, t0.s_uuid AS s_uuid_11, t0.product_id AS product_id_12 FROM payment_pending t0 WHERE t0.payment_provider_id = ? LIMIT 1",
    "params": [
      "tr_S432rV6fhM"
    ],
    "types": [
      "string"
    ],
    "executionMS": 0.0005559921264648438
  },
  "2": {
    "sql": "SELECT t0.username AS username_1, t0.roles AS roles_2, t0.password AS password_3, t0.email AS email_4, t0.email_verified AS email_verified_5, t0.created_on AS created_on_6, t0.registration_method AS registration_method_7, t0.has_premium AS has_premium_8, t0.premium_until AS premium_until_9, t0.verified_mobile AS verified_mobile_10, t0.active AS active_11, t0.facebook_id AS facebook_id_12, t0.google_id AS google_id_13, t0.id AS id_14, t0.s_uuid AS s_uuid_15, t16.is_a AS is_a_17, t16.wants_a AS wants_a_18, t16.firstname AS firstname_19, t16.lastname AS lastname_20, t16.screen_name AS screen_name_21, t16.function_title AS function_title_22, t16.mobile_number AS mobile_number_23, t16.birthday AS birthday_24, t16.age AS age_25, t16.zipcode AS zipcode_26, t16.city AS city_27, t16.id AS id_28, t16.s_uuid AS s_uuid_29, t16.user_id AS user_id_30 FROM user t0 LEFT JOIN user_extra t16 ON t16.user_id = t0.id WHERE t0.email = ? LIMIT 1",
    "params": [
      "some@email.com"
    ],
    "types": [
      "string"
    ],
    "executionMS": 0.0007460117340087891
  },
  "3": {
    "sql": "\"START TRANSACTION\"",
    "params": null,
    "types": null,
    "executionMS": 0.00010800361633300781
  },
  "4": {
    "sql": "INSERT INTO user_payments (status, payment_provider_id, payment_method, quantity, price_total, created_on, updated_on, paid_on, id, s_uuid, user_id, product_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
    "params": {
      "1": "open",
      "2": "tr_S432rV6fhM",
      "3": "paypal",
      "4": 1,
      "5": "17.95",
      "6": "2019-10-24T07:27:22+00:00",
      "7": null,
      "8": null,
      "9": "9dd4af76-f630-11e9-90f2-024216133c1a",
      "10": "9dd4af76-f630-11e9-90f2-024216133c1a",
      "11": "c2abb28c-f62f-11e9-b71f-024216133c1a",
      "12": "bce559e8-f5bc-11e9-85f8-024216133c1a"
    },
    "types": {
      "1": "string",
      "2": "string",
      "3": "string",
      "4": "integer",
      "5": "decimal",
      "6": "datetime",
      "7": "datetime",
      "8": "datetime",
      "9": "uuid_binary_ordered_time",
      "10": "uuid",
      "11": "uuid_binary_ordered_time",
      "12": "uuid_binary_ordered_time"
    },
    "executionMS": 0.0003437995910644531
  },
  "5": {
    "sql": "DELETE FROM payment_pending WHERE id = ?",
    "params": [
      "b836c012-f62f-11e9-80b0-024216133c1a"
    ],
    "types": [
      "uuid_binary_ordered_time"
    ],
    "executionMS": 0.0003409385681152344
  },
  "6": {
    "sql": "\"COMMIT\"",
    "params": null,
    "types": null,
    "executionMS": 0.09281802177429199
  }
},
"enabled": true,
"start": 1571902427.83485,
"currentQuery": 6

How can I stop Symfony Console from converting notices to exceptions

$
0
0

I have issues with custom commands in Symfony Console failing hard due to notices being converted to uncaught exceptions.

My code causes some E_NOTICE due do deliberate coding decisions. Mostly these are caused by 'Undefined index'. Symfony has, as I've understood it, an error handling routine that throws Exceptions in place of these. This causes the entire command to exit with an error code.

What is the preferred method of dealing with issues like this? I've tried using --no-debug, but for some reason that causes my commands not to be found by Symfony.

$user = ['id' => 1, 'name' => 'John Doe'];
$admin = ($user['role'] === true); //E_NOTICE
In MyCustomCommand.php line 10:

Notice: Undefined index: role  

Process finished with exit code 1

What I would like to do is to do something equivalent to setting error_reporting to a more reasonable level, but since I'm new to Symfony I naively expect this to be handled in a more thought-through fashion.

I'd be very happy if I didn't have to rewrite all lines to be super bulky with duplicated expressions wrapped in isset(), which I guess is my only alternative.

Api Platform with Swift Mailer

$
0
0

I would know if API Platform is reliable to Swift Mailer. In fact, I woul use Swift Mailer to send a email when a new task has add. It works good when I use my controller, but not working with Postman or Swagger UI.

//mail sending
       $message = (new \Swift_Message('New task has done !'))
           ->setContentType('text/html')
           ->setFrom("fromAdresse@sample.fr")
           ->setTo('sample@email.com')
           ->setBody(
               $this->renderView('email/new.html.twig',
                    ['work' => $work]));
        $mailer->send($message);

I would use the same thing when users pass by the API UI, it's possible to handle the request ? Because controller and API hasn't the same route.

API : /api/works (POST) to add an element

Controller : work/new (POST) to add an element too

How I can use Swift Mailer on the API platform Request ? Or How I can handle the request with custom controller ?

Thx for advice and answers, I'm beginer with both.

How to get the current session array count in twig?

$
0
0

In my bootstrap file where I instantiate my twig I have:

$twig->addGlobal('cart', $session->get('cart'));

and in top navbar of my twig I have a badge to show how many items are in added in cart as below:

{{ cart|length }}

and my main file that is called after bootstrap file I said above, I have:

if (!empty($_getvars['id'])) {
    $data = $session->get('cart');
    if(!isset($data[$_getvars['id']])) {
        $data[$_getvars['id']] = 0;
    }
    $data[$_getvars['id']] += 1;
    $session->set('cart', $data);
} 
print_r($session->get('cart'));

adding to sessions is working fine, and print debug above shows that it is accurate, but in the top navbar badge I always get the previous amount of items rather than current amount unless otherwise I refresh the page to show the current. How to fix it?

How to create a spinner field with symfony form?


How to display a datepicker on Symfony?

$
0
0

I want to set up a date-picker for my date type fields based on symfony documentation. I have installed the package since packagist 'eternicode / bootstrap-datepicker'. I am able to apply my defined conditions for entering the date field in my js (like the date format) but the display is still impossible. I do not have an error message in my js console. I don't even see the datepikcer component..

My Form Type:

   ->add('date_entree', DateType::class, [ 
                'widget' => 'single_text',
                          'html5' => false,
                          'attr' => ['class' => 'js-datepicker'],
                ])

My JS:

    $(document).on('ready', function() {
         $('.js-datepicker').datepicker({
              format: 'dd-mm-yyyy',
         });
     });

Have you please an idea about this issue?

Doctrine get relation IDs with queryBuilder of OneToMany

$
0
0

I am starting to use Symfony 4 and Doctrine.

I have these entities with composite keys:

/**
 * Shops
 *
 * @ORM\Entity
 */
class Shops
{
    /**
     * @var \App\Entity\Registers[]
     *
     * @ORM\OneToMany(targetEntity="Registers", mappedBy="shop")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="shop_id", referencedColumnName="id"),
     *   @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
     * })
     */
    private $registers;
}
/**
 * Registers
 *
 * @ORM\Entity
 */
class Registers
{
    /**
     * @var \App\Entity\Shops
     *
     * @ORM\ManyToOne(targetEntity="Shops", inversedBy="registers")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="shop_id", referencedColumnName="id"),
     *   @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
     * })
     */
    private $shop;
}

I want to dynamically get list of ID's from Shops.registers

When doing

SELECT t, PARTIAL registers.{id} FROM App:Shops t JOIN t.registers

I get error stating The partial field selection of class App\Entity\Registers must contain the identifier

Doing

$entityManager
    ->getClassMetadata("App:Shops")
    ->getAssociationMapping('registers');

does not return any information on keys (when association type == ONE_TO_MANY(4)`)

Question

How to get Shop.register PK on OneToMany relation?

I want to dynamically get list of ID's from Shops.registers

How to fix "but the new value must be an array or an instance of \Traversable" error in Symfony

$
0
0

I build a management app of bagages and voyages with Symfony 4, I created a "ManyToMany" relation between this entities.

When I want to add a new bagage with a destination (voyage) I have this error :

screen

I have addVoyage and removeVoyage in my classes Voyage and Bagage.

You will find above my classes Bagage.php, my form BagageType.php and my controller BagageController.php

Bagage.php

<?php

namespace 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\BagageRepository")
 */
class Bagage
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     * @Assert\Length(min=5, max=50)
     */
    private $nom;

    /**
     * @ORM\Column(type="json", nullable=true)
     */
    private $objets = [];

    /**
     * @ORM\Column(type="datetime")
     */
    private $dateCreation;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Voyage", mappedBy="bagages")
     */
    private $voyages;

    public function __construct()
    {
        $this->voyages = new ArrayCollection();
    }

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

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getObjets(): ?array
    {
        return $this->objets;
    }

    public function setObjets(?array $objets): self
    {
        $this->objets = $objets;

        return $this;
    }

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

    public function setDateCreation(\DateTimeInterface $dateCreation): self
    {
        $this->dateCreation = $dateCreation;

        return $this;
    }

    /**
     * @return Collection|Voyage[]
     */
    public function getVoyages(): Collection
    {
        return $this->voyages;
    }

    public function addVoyage(Voyage $voyage): self
    {
        if (!$this->voyages->contains($voyage)) {
            $this->voyages[] = $voyage;
            $voyage->addBagage($this);
        }

        return $this;
    }

    public function removeVoyage(Voyage $voyage): self
    {
        if ($this->voyages->contains($voyage)) {
            $this->voyages->removeElement($voyage);
            $voyage->removeBagage($this);
        }

        return $this;
    }

}
?>

BagageType.php

<?php

namespace App\Form;

use App\Entity\Voyage;
use App\Entity\Bagage;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BagageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nom')
            ->add('voyages', EntityType::class, [
                'class' => Voyage::class,
                'choice_label' => 'lieu'
            ]);
    }

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

BagageController.php

<?php
/**
     * @Route("/bagages/nouveau", name="bagage_creation")
     * @Route("/bagages/{id}/edit", name="bagage_edit")
     */
    public function form(Bagage $bagage = null, Request $request, ObjectManager $manager)
    {
        if(!$bagage){
            $bagage = new Bagage();
        }

        $form = $this->createForm(BagageType::class, $bagage);

        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()) {
            if(!$bagage->getId()){
                $bagage->setDateCreation(new \Datetime());
            }

            $manager->persist($bagage);
            $manager->flush();

            return $this->redirectToRoute('bagage_show', [
                'id' => $bagage->getId()
            ]);
        }

        return $this->render('bagages/create.html.twig', [
            //creation d'une vue pour twig pour afficher le formulaire
            'formBagage' => $form->createView(),
            'editMode' => $bagage->getId() !== null
        ]);
    }
?>

Does it miss an addVoyage call in my controller ?

EDIT

Voyage.php

<?php

namespace 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\VoyageRepository")
 */
class Voyage
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Bagage", inversedBy="voyages")
     */
    private $bagages;

    public function __construct()
    {
        $this->bagages = new ArrayCollection();
    }

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

    public function getLieu(): ?string
    {
        return $this->lieu;
    }

    public function setLieu(string $lieu): self
    {
        $this->lieu = $lieu;

        return $this;
    }

    /**
     * @return Collection|Bagage[]
     */
    public function getBagages(): Collection
    {
        return $this->bagages;
    }

    public function addBagage(Bagage $bagage): self
    {
        if (!$this->bagages->contains($bagage)) {
            $this->bagages[] = $bagage;
        }

        return $this;
    }

    public function removeBagage(Bagage $bagage): self
    {
        if ($this->bagages->contains($bagage)) {
            $this->bagages->removeElement($bagage);
        }

        return $this;
    }
}

Api Platform custom swagger/openapi context body

$
0
0

I am using Api Platform with Symfony 4, and I want to create a custom endpoint. Everything works fine, but I cannot change 2 things: body and response format (in openapi documentation).

Parameters and responses status codes works just fine.

*          "login"={
 *              "route_name"="api_login",
 *              "method" = "post",
 *              "openapi_context" = {
 *                  "parameters" = {},
 *                  "body" = {
 *                      "description" ="Username and password",
 *                      "schema" = {
 *                          "type" = "object",
 *                          "required" = {"email","password"},
 *                          "properties" = {
 *                                   "email" = {
 *                                      "type" = "string"
 *                                   },
 *                                   "password" = {
 *                                      "type" = "string"
 *                                   }
 *                          }
 *                      }
 *                  },
 *                  "responses" = {
 *                      "200" = {
 *                          "description" = "User logged in",
 *                          "schema" =  {
 *                              "type" = "object",
 *                              "required" = {
 *                                  "token",
 *                                  "refresh_token"
 *                              },
 *                              "properties" = {
 *                                   "token" = {
 *                                      "type" = "string"
 *                                   },
 *                                   "refresh_token" = {
 *                                      "type" = "string"
 *                                   }
 *                              }
 *                          }
 *                      },
 *                      "401" = {
 *                          "description" = "invalid password or email"
 *                      }
 *                  },
 *                  "summary" = "Login user in application",
 *                  "consumes" = {
 *                      "application/json",
 *                      "text/html",
 *                   },
 *                  "produces" = {
 *                      "application/json"
 *                   }
 *              }
 *          }

Set custom port when starting symfony local web server

$
0
0

I want to start a server with symfony server:start using the port that is set in my .env file. Is there a way to do this?

Must fix var folder permission after each cache clear , Symfony 4

$
0
0

I'm using Symfony 4 and my website is hosted on ubuntu 18.04 server.

The problem is each time when I do clear cache I must run chmod 777 -R var/ .

Is there a command to fix permission permanently ?

SonataAdmin create entity with boolean field

$
0
0

I have this entity, if I create a record like this.

$synopsis = new Synopsis();
$synopsis->setPartOne("a");
$synopsis->setPartTwo("b");
$synopsis->setTitle("A");
$synopsis->setSubtitle("B");
$synopsis->setEnabled(false);

$em->persist($synopsis);
$em->flush();

And then I go to my Admin, I see the enabled field to "no" which is expected.

But now, If I use the sonata admin new form field, even if I choose enabled "no", the record is created with enabled = true. And I don't really see why it would be like that.

Here is what I have in my SynopsisAdmin

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper->add('title', TextType::class);
    $formMapper->add('subtitle', TextType::class);
    $formMapper->add('partOne', TextAreaType::class);
    $formMapper->add('partTwo', TextAreaType::class);
    $formMapper->add('enabled', BooleanType::class);
}

This is how the enabled field is defined in the entity

/**
 * @ORM\Column(type="boolean")
 */
private $enabled;

Thanks for your help.

EDIT: Fun facts too, even if I see no in the sonata view list, when I go to the form view, I see yes instead.

I suspect an error within the sonata core functionnality.


How to import an existing database that not contain primary key in Symfony4?

$
0
0

I want to import an existing database that not contain any primary key. What should I do with the command line?

I have changed some code in my DatabaseDriver.php

enter image description here

enter image description here

This is after I have changed the code in DatabaseDriver.php, and I try to import existing database.

enter image description here

What should I do with the code ??

Unable change Swagger UI location path

$
0
0

I made an api with api-platform.

I tried to edit the swagger_ui path '/' to '/docs' according to api-platform documentation and allow '/' redirect to custom twig i made.

The swagger_ui documentation is available in /docs path but also still available in '/' path instead of my custom twig file.

Here is my config :

app/config/packages/api_platform.yaml

api_platform:
mapping:
    paths: ['%kernel.project_dir%/src/Entity']
    enable_swagger_ui: true
    enable_re_doc: true
    enable_docs: true

app/config/routes/api_platform.yaml

api_platform:
resource: .
type: api_platform
prefix: /

app/config/route.yaml

swagger_ui:
  path: /docs
  controller: api_platform.swagger.action.ui
hello-world:
  path: /
  controller: App\Controller\HelloController::index

Thanks by advance for your answer, if i haven't be clear, just le me know :)

How to pass variables from jquery fetch function to symfony routes.yaml?

$
0
0

So I want to call a controller in symfony by passing in my route declared in routes.yaml with a jquery fetch function and I want to pass to variables from jquery to the controller. How can I do that ?

Here's my jquery. I call this route and I want to pass the two variable on top with it.

var longitudde = lonLat[0];
var latudde = lonLat[1];
fetch('/weather_request)
.then(function(response) {
  return response.json();
}).then(function(json) {
  // ...
});

To pass those variables to routes.yaml in Symfony:

weather_request:
    path:     /weather_request
    controller: App\Controller\WeatherController::weather
    methods: [get]
    defaults:
      longitude: longitude
      latitude: latitude

To finaly pass them in the weather function in WeatherController:

public function weather($longitude, $latitude)
{
    return $this->render('weather/index.html.twig', ['weatherInfos' => $this->weatherService->getWeather($longitude, $latitude)]);
}

So how can I pass the longitude and latitude from jquery fetch to the controller here ? I'm new to Symfony so I could be completely wrong.

Convert string to timestamp in symfony 4

$
0
0

I have a variable recover from ajax and in the controller

dd($gethour);
"Sat Oct 26 2019 00:00:04 GMT+0200 (heure d’été d’Europe centrale)"
$from = \DateTime::createFromFormat('m-d-y H:i:s', $gethour);
dd($form);

Result:false

My problem is how to convert string to timestamp seen in the base HoursPass is a type timestamp

Symfony4 deploy to shared hosting getting error 500

$
0
0

I have deployed my symfony4 project to a shared hosting (infinityFree). but when I go to my website I get a 500 Internal Server Error :

Oops! An Error Occurred The server returned a "500 Internal Server Error".

Something is broken. Please let us know what you were doing when this error occurred. We will fix it as soon as possible. Sorry for any inconvenience caused.

My project works fine on local with dev mode.

In htdocs/var/log/prod.depreciations.log :

[2019-09-20 15:01:41] php.INFO: User Deprecated: The "Symfony\Component\Config\Definition\Builder\TreeBuilder::root()" method called for the "liip_imagine" configuration is deprecated since Symfony 4.3 ... etc


[2019-09-20 15:01:41] php.INFO: User Deprecated: A tree builder without a root node is deprecated since Symfony 4.2 ... etc


[2019-09-20 15:01:41] php.INFO: User Deprecated: The "Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser" class is deprecated since Symfony 4.3 ... etc

[2019-09-20 15:01:43] php.INFO: User Deprecated: The spaceless tag in "@LiipImagine/Form/form_div_layout.html.twig" at line 2 is deprecated since Twig 2.7, use the spaceless filter instead. {"exception":"[object] (ErrorException(code: 0): User Deprecated: The spaceless tag in \"@LiipImagine/Form/form_div_layout.html.twig\" at line 2 is deprecated since Twig 2.7 ... etc

There is no error log in htdocs/var/log/. My project is deployed in htdocs, and in my htaccess as a sibling of the public folder I have :

php_value display_errors On
php_flag magic_quotes 1
php_flag magic_quotes_gpc 1
php_value mbstring.http_input auto
php_value date.timezone Europe/Paris
DirectoryIndex public/index.php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>
    RewriteEngine On
    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]
    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ public/index.php [L]
    #Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

In Cpanel php version is 7.3 (default) and I don't have ssh access with infinityfree. Ive followed this tutorial https://symfony.com/doc/current/deployment.html

Viewing all 3924 articles
Browse latest View live


Latest Images

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