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

Redirect to another page with data

$
0
0

I have a Javascript array in page 1 and i need it in page 2.

I tried with JQuery post method but i couldn't make it work :

   $.post( "{{path('result')}}", mydata );

How do i properly redirect the user from page 1 to page 2 with that array ?

Are cookies or sessions useful in this case ?

I'm using Symfony4 with Twig.

Thank you.


How can I edit the sql commands of symfony doctrine when updating a schema?

$
0
0

I have the following error when I'm trying to update my database schema :

SQLSTATE[HY000]: General error: 1833 Cannot change column 'IdEcole': used in a foreign key constraint 'appartient_ibfk_2' of table 'tuteure.appartient'

However, I don't have anything that make the IdEcole AUTO_INCREMENT (in database or in my Entitites, only in the migrations.

When I execute the following line php bin/console doctrine:schema:update --dump-sql I have the following response :

ALTER TABLE Ecole CHANGE IdEcole IdEcole INT AUTO_INCREMENT NOT NULL;

So how can I edit this line to delete it ? Where is this line stored and where it comes from ?

API to download content as file

$
0
0

I would like to create an API which returns a text file. In Symfony I have a controller which is :

            throw $this->createNotFoundException($message);
        }
        $response = new Response();
        $response->headers->set('Content-Type', "text/cfg;charset=utf-8");
        $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '.cfg"');
        $response->headers->set('Pragma', "no-cache");
        $response->headers->set('Expires', "0");
        $response->headers->set('Content-Transfer-Encoding', "binary");
        $response->headers->set('Content-Length', strlen($data));
        $response->setContent($data);
        return $response;

Is there any alternative option with api-platform to explain this format ? I'm in symfony 4 with api-plateform

Thanks in advance

Symfony Messenger: retry delay not working with Redis transport

$
0
0

I have a Symfony 4 application using the Symfony Messenger component (version 4.3.2) to dispatch messages. For asynchronous message handling some Redis transports are configured and they work fine. But then I decided that one of them should retry a few times when message handling fails. I configured a retry strategy and the transport actually started retrying on failure, but it seems to ignore the delay configuration (keys delay, multiplier, max_delay) and all the retry attempts are always made without any delay, all within one second or a similarly short timespan, which is really undesirable in this use case.

My Messenger configuration (config/packages/messenger.yaml) looks like this

framework:
  messenger:
    default_bus: messenger.bus.default

    transports:
      transport_without_retry:
        dsn: '%env(REDIS_DSN)%/without_retry'
        retry_strategy:
          max_retries: 0
      transport_with_retry:
        dsn: '%env(REDIS_DSN)%/with_retry'
        retry_strategy:
          max_retries: 5
          delay: 10000 # 10 seconds
          multiplier: 3
          max_delay: 3600000
    routing:
      'App\Message\RetryWorthMessage': transport_with_retry

I tried replacing Redis with Doctrine (as implementation of the retrying transport) and voila - the delays started to work as expected. I therefore suspect that the Redis transport imlementation doesn't support delayed retry. But I read the docs carefully, searched related Github issues, and still didn't find a definite answer.

So my question is: does Redis transport support delayed retry? If it does, how do I make it work?

symfony4, api-platform upload file : Format "multipart/form-data" is not supported

$
0
0

I would like to do an API with symfony 4, api-platform which allow to upload file and run a system commande with it and delete it. I want use in a controle somethink like :

$uploadedConfig = $request->files->get('cfgfile');
exec("mycall ".$uploadedConfig->getPathname());

But I have the following errors : Format "multipart/form-data" is not supported

my test is :

curl -X POST -F 'cfgfile=/tmp/maconf' http://<IP>/api/config -H "Content-Type: multipart/form-data"

thanks Thomas

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

$
0
0

I've been turning this around in my head for quite a while now and still wasn't able to find a solution to my problem. Using Symfony 4 forms and constraints I'm unable to setup a check to say that at least one of two fields must not be empty when submitting form that contains a sub-form.

I have a Booking entity which contains a Visitor entity which has a phoneNumber property and a email property. I'd like to be able to create a Booking which has a "visitors" CollectionType (where I'm allowed to add visitors from the BookingType form).

My BookingType form (a bit simplified):

class BookingType extends AbstractType
{
    private $router;
    private $translator;

    public function __construct(UrlGeneratorInterface $router, TranslatorInterface $translator)
    {
        $this->router = $router;
        $this->translator = $translator;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('bookableTimeSlot', EntityType::class, [
                'label' => 'entity.booking.bookable-time-slot',
                'class' => BookableTimeSlot::class,
                'choice_label' => function ($bookableTimeSlot) {
                    return $bookableTimeSlot->getStartDateTime()->format('d.m.Y h\hi');
                }
            ])
            ->add('visitors', CollectionType::class, [
                'entry_type' => VisitorType::class,
                'label' => 'entity.booking.visitors',
                'allow_add' => true,
                'by_reference' => false,
                'entry_options' => ['label' => false]
            ])
        ;
    }

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

My Visitor entity (a bit simplified):

<?php

namespace App\Entity;

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

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

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

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

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

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Booking", inversedBy="visitors")
     * @ORM\JoinColumn(nullable=false)
     */
    private $booking;

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

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

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

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

        return $this;
    }

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

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

        return $this;
    }

    public function getPhone(): ?string
    {
        return $this->phone;
    }

    public function setPhone(string $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getBooking(): ?Booking
    {
        return $this->booking;
    }

    public function setBooking(?Booking $booking): self
    {
        $this->booking = $booking;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(?string $email): self
    {
        $this->email = $email;

        return $this;
    }
}

And finaly my VisitorType form (a bit simplified):

class VisitorType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', TextType::class, [
                'label' => 'entity.visitor.first-name',
            ])
            ->add('lastName', TextType::class, [
                'label' => 'entity.visitor.last-name',
            ])
            ->add('phone', TextType::class, [
                'label' => 'entity.visitor.phone-number',
                'required' => false,
            ])
            ->add('email', TextType::class, [
                'label' => 'entity.visitor.email',
                'required' => false,
                'constraints' => [
                    new Email()
                ]
            ])
        ;
    }

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

I've tried to add an Expression constraint to the email and phone field which looked something like this:

new Expression([
    'expression' => 'this.getPhone() == null && this.getEmail() == null'
])

Also tried to add constraint directly to the entity, but nothing seems to work correctly for me.

Any help would be greatly appreciated.

Denormalizer on MongoDb Embedded Document in Symfony API Platform

$
0
0

I am attempting to run a denormalizer (data in) on an embedded mongodb document with Symfony 4.4 using the Api Platform bundle. This works as expected for normalization (data out), but for the denormalization process nothing is fired on the embedded data, just on the parent data.

If this is the way it works, then I may need to move the logic for denormalization into the parent. Or perhaps I am just doing something wrong. What I am attempting to accomplish is throw exceptions on inbound requests that contain fields which have been deprecated. The classes which parse the annotations and scan the attributes works as expected, its just determining where to plug it in and I was hoping the denormalization process on embedded documents would work.

Here is my services.yaml:

'App\Serializer\InvestmentNormalizer':
    arguments: [ '@security.authorization_checker' ]
    tags:
        - { name: 'serializer.normalizer', priority: 64 }
'App\Serializer\InvestmentDenormalizer':
    tags:
        - { name: 'serializer.denormalizer', priority: 64 }
'App\Serializer\ProjectNormalizer':
    tags:
        - { name: 'serializer.normalizer', priority: 64 }
'App\Serializer\ProjectDenormalizer':
    tags:
        - { name: 'serializer.denormalizer', priority: 64 }

Then my denormalizer class which never gets executed:

class ProjectDenormalizer implements DenormalizerInterface
{
    private const ALREADY_CALLED = 'PROJECT_DENORMALIZER_ALREADY_CALLED';

    public function denormalize($data, $class, $format = null, array $context = [])
    {
        $context[self::ALREADY_CALLED] = true;

        return $this->removeDeprecatedFields($data);
    }

    public function supportsDenormalization($data, $type, $format = null)
    {
        if (isset($context[self::ALREADY_CALLED])) {
            return false;
        }

        return $type == get_class(new Project());
    }

    private function removeDeprecatedFields(array $normalizedData) : array
    {
        $apiPropertyReader = new AnnotationReader(Project::class, ApiProperty::class);
        $deprecatedProperties = $apiPropertyReader->readAllHavingAttribute('deprecationReason');

        $errors = [];

        foreach (array_keys($deprecatedProperties) as $deprecatedPropertyName) {

            if (!isset($normalizedData[$deprecatedPropertyName])) {
                continue;
            }

            $errors[] = $deprecatedPropertyName . ' has been deprecated';
        }

        if (!empty($errors)) {
            throw new DeprecatedFieldException(implode('. ', $errors));
        }

        return $normalizedData;
    }
}

I am trying to get a list of users with their main picture in Symfony 4

$
0
0

I am having a hard time showing the main picture in a list of users. The query seems to do his job I can see in the log. These are my tables and code:

table user

id | username

table meta

id | user_id | plaats_id

table picture

id | user_id | naam| mainfoto

These are my Entities:

User.php

     /**
     * @var int
     *
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;   

    /**
     * @var string
     *
     * @ORM\Column(type="string", unique=true)
     * @Assert\NotBlank()
     * @Assert\Length(min=2, max=50)
     */
    private $username;

     /**
     * @ORM\OneToMany(targetEntity="App\Entity\Pictures", mappedBy="user", orphanRemoval=true)
     */
    private $pictures;

Meta.php

     /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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


    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Plaats", inversedBy="metas")
     * @ORM\JoinColumn(nullable=true)
     */
    private $plaats;

Pictures.php

     /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

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

MetaRepository.php

public function getSingles()
    {
        return $this->createQueryBuilder('meta')
            ->addselect('u')           
            ->addSelect('pics')
            ->Join('meta.user', 'u')            
            ->Join('u.pictures', 'pics')
            ->andWhere('pics.mainfoto = 1')
            ->getQuery()
            ->execute();
    }

SinglesController.php

public function index(Request $request, int $page, MetaRepository $metas): Response
    {

        $this->em = $this->getDoctrine()->getManager();       
        $singlesList = $metas->getSingles();

        return $this->render('singles/singles_list.html.twig', ['singles' => $singlesList]);
    }

singles_list.html.twig

  {% for single in singles %}

        <div class="row">
            <div class="col-sm">
                {{ single.user.pictures.getMainFoto() }}
            </div>
            <div class="col-sm">
                {{ single.user.username }}
            </div>
            <div class="col-sm">
                {{ single.user.geboortedatum.diff((date('NOW'))).format('%y jaar') }}
            </div>
            <div class="col-sm">
                {{ single.plaats }}
            </div>
        </div>



    {% else %}
        <div class="well">{{ 'database.no_message_found'|trans }}</div>
    {% endfor %}

{% endblock %}

Update query with multiple where conditions

$
0
0

I am trying to update the row. Here I have multiple where conditions. This is the query I have tried.

$this->createQueryBuilder("jv")
->update()
->set("jv.pictureStatus", "?1")
->set("jv.pictureStatusId", "?2")
->andWhere("jv.aa = ?3")
->andWhere("jv.bb = ?4")
->andWhere("jv.cc = ?5")
->andWhere("jv.dd = ?6")
->andWhere("jv.ee = ?7")
->andWhere("jv.ff = ?8")
->andWhere("jv.gg = ?9")
->setParameter(1, "100")
->setParameter(2, "200")
->setParameter(3, $wheres["aa"])
->setParameter(4, $wheres["bb"])
->setParameter(5, $wheres["cc"])
->setParameter(6, $wheres["dd"])
->setParameter(7, $wheres["ee"])
->setParameter(8, $wheres["ff"])
->setParameter(9, $wheres["gg"])
->getQuery()->execute();

When I execute this query it returns 0 but nothing is getting updated.

Querying with the Query Builder

$
0
0

I'M USING SYMFONY 4.12 I'm trying to write queries to filter my jobs(I've job table ,départements one) I first try with experience but I'm stuck in here is my offerController:

/**
 * @Route("/offres", name="offres")
 * @param Request $request
 * @param PaginatorInterface $paginator
 * @param FormFactoryInterface $formFactory
 * @return Response
 */
public function offreSearch(Request $request, PaginatorInterface $paginator ,FormFactoryInterface $formFactory):Response
{

    $datas =new OffreEmploi();
    $formFilter=$formFactory->create(OfferFilterForm::class,$datas);
    $offres = $this->repository->findSearch($datas);

    $formFilter->handleRequest($request);

    return $this->render('offre/index.html.twig', [
        'controller_name' => 'OffreController',
        'offres' => $offres,
        'formulaire'   =>$formFilter->createView(),

    ]);
}

} and this is my query in the offerRepositor:

  public function findSearch(OffreEmploi $data):?array
{
    $query = $this->createQueryBuilder('o');
    if ($data->getExperience() !== null) {

        $query
            ->where('o.experience > :experience')
            ->setParameter('experience', $data->getExperience());

    }
    return $query->getQuery()->getResult();
}

when it come to enter any number IT give the same thing it show all the jobs stored in the database,I don't know where the problem is, some one can help me to solve this . THE RESULT

need help on symfony 4 [duplicate]

$
0
0

I'm trying to import Excel data to my database... here is my function but when I start the import I get this error on screen: Undefined index: C

I use the PhpSpreadsheet library.


public function newImport(Request $request, SaleRequestRepository $saleRequestRepository, ObjectManager $em): Response { $saleRequest = new SaleRequest();

    $form = $this->createForm(ImportFileType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $myexcel = $form->get('importFile')->getData();
       // dd($myexcel);

        $reader = new Xlsx();
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($myexcel);

       $worksheet = $spreadsheet->getActiveSheet();
        $highestRow = $worksheet->getHighestRow();
        $highestColumn = $worksheet->getHighestColumn();
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
        $ligne=[$highestRow][$highestColumn];
        for($row=1; $row < $highestColumnIndex ; $row++){
            $saleRequest->setDate(  $ligne[$row][0]);
            $saleRequest->setReference($ligne[$row][1]);

            $em = $this->getDoctrine()->getManager();
            $em->persist($saleRequest);
            $em->flush();

        }

      }

    return $this->render('sale/sale_request/importFile.html.twig', [
        'saleRequest' => $saleRequest,
        'form' => $form->createView(),
    ]);
}

How to return extra information from a voter in Symfony4?

$
0
0

I have a voter that I use to check if the current user can access an object. The access can be refused for several reasons, and I would like to know which in the Controller. However, the voter can only return a boolean, same for isGranted() in the Controller, so I'm not sure by which channel I can pass the extra information I want. Throwing an exception wouldn't do, as there may be other voters that haven't been called yet.

The closer thing I can think of are flash messages, which can be used to pass information outside of function arguments and return values, but it feels like hack to use them in this situation.

EasyAdminBundle transliterator_transliterate error for file uploads

$
0
0

I have an EasyAdmin form field setup in easy_admin.yaml:

- { property: 'imageFile', type: 'file_upload', type_options: { upload_dir: 'public/data/gallery/images/', upload_filename: '[uuid]-[timestamp].[extension]'}}

When I try to upload a file I get an error:

Attempted to call function "transliterator_transliterate" from namespace "EasyCorp\Bundle\EasyAdminBundle\Form\Type".

If I remove this part - it works fine:

upload_filename: '[uuid]-[timestamp].[extension]'

What is wrong with this part of the config?

CKFinder error when browsering (Symfony4 + EasyBundle + CKEditor)

$
0
0

Here's my stack :

  • Symfony4
  • EasyAdmin
  • Webpack
  • FOSCkEditor
  • CKFinder

And here's my problem :

I got a form with a WYSIWYG field, and when I click on the "Image" icon, a popup open with all the properties of the image (size, alt, border, link, etc.). As I installed the Symfony bundle "ckfinder", there's now a new button "Browser".

When I click on the button, a new window open, calling this URL :

/bundles/cksourceckfinder/ckfinder/ckfinder.html?CKEditor=article_content&CKEditorFuncNum=1&langCode=fr

And here's the error I get :

No route found for "GET /bundles/cksourceckfinder/ckfinder/core/connector/php/connector.php" (from "http://192.168.2.1:8000/bundles/cksourceckfinder/ckfinder/ckfinder.html?CKEditor=article_content&CKEditorFuncNum=1&langCode=fr")

I followed the documentation but I think I missed something.

There is no file name connector.php in my code, should I create it ?

Here's my configuration for fosckeditor :

twig:
    form_themes:
        - '@FOSCKEditor/Form/ckeditor_widget.html.twig'

fos_ck_editor:
    default_config: default
    configs:
        default:
            toolbar: full      
            fullscreen: true

And ckfinder's configuration :

ckfinder:
    connector:
        authenticationClass: App\CustomCKFinderAuth\CustomCKFinderAuth

Do I need to create a route ? A new template ? I'm stuck.

Please, if you know how to deal with this, help me !

Thanks and take care.

Register custom Doctrine type in Symfony4

$
0
0

So I have this custom Doctrine type

namespace App\Doctrine\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Types\TextType;

class MyType extends TextType
{
   private $prefix='';

   public function getName()
   {
      return 'my_type';
   }
   public function setPrefix(string $prefix)
   {
      $this->prefix=$prefix;
   }
}

I registerd in in the config/packages/doctrine.yml:

doctrine:
    dbal:
        types:
            my_type: App\Doctrine\Types\MyType

Then in Kernel boot() I'm trying to add some parameters to this type:

public function boot() {
   parent::boot();

   $myType=Type::getType('my_type');
   $myType->setPrefix('abc');
}

This works perfectly the first time I run the app. The prefix is set for the type and can be used through the whole app. However, the second time I get an Exception:

Unknown column type "encrypted_text" requested. Any Doctrine type that you use has to be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a list of all the known types with \Doctrine\DBAL\Types\Type::getTypesMap(). If this error occurs during database introspection then you might have forgotten to register all database types for a Doctrine Type. Use AbstractPlatform#registerDoctrineTypeMapping() or have your custom types implement Type#getMappedDatabaseTypes(). If the type name is empty you might have a problem with the cache or forgot some mapping information.

I then changed boot() to :

    public function boot() {
       parent::boot();
       if (!Type::hasType('my_type')) {
           Type::addType('my_type', 'App\Doctrine\Types\MyType');
       }
       $myType=Type::getType('my_type');
       $myType->setPrefix('abc');
   }

Now the exception is gone, but the prefix is not set. I know the exceptions gives me information about what to do but I really don't know where to start.

Can anyone point me in the right direction?


How to avoid multiple user sessions in symfony 4?

$
0
0

How can I prevent a user from accessing the site from multiple devices?

I create a function onSecurityInteractiveLogin in a EventListener, but i can't get if the user is logged in other device and close that session.

Can anybody explain me how i get if a User is logged in?

How to import external routes in Akeneo 4.0

$
0
0

I'm building a custom bundle for Akeneo v4.0. I'm trying to import routes from that bundle to the rest of the app. So far I've done:

# config/bundles.php
<?php

return [
    JBieliauskas\MyServerBundle\MyServerBundle::class => ['dev' => true, 'test' => true],
];
# src/MyServerBundle/Resources/config/routing.yml
my_server_index:
  path: /my-server
# config/routes/routes.yml
jb_my_server:
  resource: "@MyServerBundle/Resources/config/routing.yml"
  prefix: /

Then I run:

$ bin/console cache:clear
$ bin/console debug:router | grep my_server

and nothing shows up. What am I missing?

I know that src/Kernel.php is looking for routes using a glob pattern, but I don't understand it:

protected function configureRoutes(RouteCollectionBuilder $routes): void 
{
    // ...
    $this->loadRoutesConfiguration($routes, $this->getProjectDir() . '/config', $this->environment);
}

// ...

private function loadRoutesConfiguration(RouteCollectionBuilder $routes, string $confDir, string $environment): void
{
    // ...
    $routes->import($confDir . '/{routes}/*.yml', '/', 'glob');
}

So it should detect the file config/routes/routes.yml, no?

Call js function from external file Symfony Twig

$
0
0

I'm having issues calling functions from twig views in Symfony 4.4. This view is called UserList.html.view and it extends base.html.twig

The beginning of the file is as following :

{% extends 'base.html.twig' %}
{% block body %}
{% block javascripts %}
    <script src="{{ asset('build/js/custom.js') }}"></script>
...

I also tried with Encore by adding an entry but it's not working. The only way to access external functions is to call them from the parent view which is not what I want obviously.

The error I get :

Uncaught ReferenceError: coucou is not defined at HTMLButtonElement.onclick (VM3883 manageAccounts:183) onclick @ VM3883 manageAccounts:183

I read some other posts about this but none of them actually provided a working solution.

Thank you for your help !

mpdf fails to open image when run from console command

$
0
0

I'm using Symfony 4.3
I have an InvoiceService, which generates invoice into pdf file.
For html content I use \Twig\Environment::render() method. In the template I use twig asset() function for an image.

When I run this service from controller, the invoice is generated without problems, but when I run this service from a console command I get errors:

Warning: fopen(/img/core-img/logo.png): failed to open stream: No such file or directory

and

Warning: fopen(invoice/3fd61732f249385ba369b9a764fa47f553d284f5e845c3c80b4bd05364dd4961-9db972eb28f054d9d988e6396ac6ec20997e61e71ade580b5448346d10760d0b.pdf): failed to open stream: No such file or directory

Should the Mpdf or Twig Environment be used in a different way, when not run from the controller?

This is the code responsible:

$html = $this->twig->render(
                'invoice.html.twig',
                array(
                    'reservation' => $reservation,
                )
            );
            $waterMarkText = ($this->kernel->getEnvironment() !== 'production') ? $this->translator->trans('invoice.test_document') : $this->translator->trans('invoice.paid');
            $this->mpdf->SetProtection(array('print'));
            $this->mpdf->SetTitle("Apartamenty Grodowa 2 - faktura");
            $this->mpdf->SetAuthor("Gall");
            $this->mpdf->SetWatermarkText($waterMarkText);
            $this->mpdf->showWatermarkText = true;
            $this->mpdf->watermark_font = 'DejaVuSansCondensed';
            $this->mpdf->watermarkTextAlpha = 0.1;
            $this->mpdf->SetDisplayMode('fullpage');
            $this->mpdf->WriteHTML($html);
            $this->mpdf->Output('invoice/' . $reservation->getHash() . '-' . $reservation->getInvoice()->getFileName() . '.pdf',
                Destination::FILE);

With $this->twig being \Twig\Environment passed through Dependency Injection
and $this->mpdf being

new Mpdf([
                'margin_left' => 20,
                'margin_right' => 15,
                'margin_top' => 48,
                'margin_bottom' => 25,
                'margin_header' => 10,
                'margin_footer' => 10
            ]);

Symfony Doctrine query builder find entity with many to one relation

$
0
0

I'm building a website with Symfony for a project which will act like "booking.com" websites but much simplier and with some variations.

Some errors on the database fields but not really important for my issue.

enter image description here

As you can see, these tables concern two entities : apartment and visit. A customer can ask for a visit of an apartment. It is a many to one relationship.

I have a search form to search for apartments with criterias. I want to only show apartments that don't have any visits between the arrival and departure dates that the user provided. So I ended up making a function in apartmentRepository to manage that and other cases.

Problem is: how can I get these apartments ?

Here is a draft of this function which is of course not finished neither perfect (if you have some comments to improve it, it would be great !).

public function findByCustom($parameters): ?array
{
   $query =  $this->createQueryBuilder('a');

   foreach ($parameters as $key=> $parameter){
       if($key != 'keywords' and $key!= 'priceMin'& $key!='priceMax' and $key!="typeAp" and $key!="searchVisitDate") $query->orWhere('a.'.$key." = '".$parameter."'");

       if($key == "typeAp")
       {
           $typeApQuery = "";
           foreach ($parameters[$key] as $index => $type)
           {
               if($index !== count($parameters[$key])-1)
               {
                   $typeApQuery.=" a.typeAp = '".$type."' or";
               }
               else
               {
                   $typeApQuery.= " a.typeAp = '".$type."'";
               }
           }
           $query->andWhere($typeApQuery);
       }
   }

   $query->andWhere('a.rentPrice >='.$parameters['priceMin']." and a.rentPrice <= ".$parameters['priceMax']);
   $withoutInner = $query;
   $query
       ->join('App\Entity\Visit', 'v', Join::ON, 'a = v.apartment')
       ->where("v.date between '2020-03-15' and '2020-03-19'");
    $query->getQuery()->getResult();
    $sorted = $withoutInner->andWhere($this->createQueryBuilder('a')->expr()->notIn('a.id', $query));

   return array($sorted);

Of course apartment has a collection of visits and visit as a field named "apartment" which is related to the apartment object.

I really didn't find a proprer way to do it and I want to avoid doing SQL, to improve my understanding of Doctrine.

Thank you for your help because I'm stuck right now :/

Viewing all 3918 articles
Browse latest View live


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