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

PHPUnit No such file or directory

$
0
0

I'm trying to test my RoomRepository with PHPUnit and Symfony 4. I installed symfony/phpunit-bridge using composer. I created a simple entity called Room with one id and name attributs and a repository method to get a Room by its id.

public function get(int $id): ?Room
{
   /** @var Room $room */
   $room = $this->findOneBy(['id' => $id]);

   return $room;
}

My test is quite simple as you can see :

public function testGet(): void
{
    /** @var RoomRepository $repository */
    $repository = $this->em->getRepository(Room::class);

    $room = $repository->get(1);

    $this->assertCount(1, $room);
}

I am new with test and I don't know if it's the right way to proceed. I followed the Symfony documentation.

So, when I execute the following command :

./vendor/bin/simple-phpunit

I am getting this error :

Doctrine\DBAL\Exception\ConnectionException: An exception occurred in driver: SQLSTATE[HY000] [2002] No such file or directory

I am pretty sure this is a commun mistake and very easy to fix...

Furthermore, I wrote other simple asserts that worked very well. I don't think it's about PHPUnit configuration.

Here some informations about my env :

  • PHP 7.1
  • Symfony4.0.5
  • PHPUnit 5.7.27
  • Docker with Laradock (containers : mysql, apache2, workspace)

Thanks guys for reading my post and have a nice day :)


Symfony wildcard host route with no named parameter

$
0
0

I want to host 2 different domains inside a single Symfony 4 application, so I'm using @Route's host parameter to declare the domain each page belongs to:

/**
 * @Route("/foo", name="foo", host="example.com")
 */

This works fine; however, for my local dev server, I will typically use a domain like example.dev instead. So the route needs to match multiple extensions. I tried using a named placeholder for this purpose:

/**
 * @Route("/foo", name="foo", host="example.{ext}")
 */

This works fine for routing, but not for URL generation. For example, if a Twig template attempts to use {{ path('foo') }}, I now get the following error:

Some mandatory parameters are missing ("ext") to generate a URL for route "foo".

Is there a way to add a wildcard for the host, while still allowing route generation without passing a parameter?

I know the question sounds odd, as routing must be bi-directional, but how is this typically handled when one needs to have a dev environment with different domains?

Is there maybe a way to provide a global, default value for the ext parameter?

How to generate entity and repository from an existing database? [duplicate]

$
0
0

This question already has an answer here:

I already have a database created. Now I need to generate the entities from this given database. I tried following commands:

php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/Entity

and to generate getters and setters.

php bin/console make:entity --regenerate

By this, it is creating the Entity but Repository is not being created.

Configure a default host for routes in Symfony 4

$
0
0

So far my Symfony app was hosting a single domain. Now, I need to host a few pages on another domain. For business reasons, this must appear as a separate domain to the user, even though it actually belongs to the same app.

Say my app is hosted on example1.com. I need to host some pages on newsletter.example2.com.

So I created a new controller:

class NewsletterController extends AbstractController
{
    /**
     * @Route("/unsubscribe", name="newsletter_unsubscribe", host="newsletter.example2.com")
     */
    public function unsubscribe(): Response
    {
        return $this->render('newsletter/unsubscribe.html.twig');
    }
}

This works fine; the page is served correctly, and the /unsubscribe path in only routed when requested on newsletter.example2.com. On example1.com, it returns a 404 as expected.

The issue is, now all routes intended to be matched on the main domain example1.com, are also matched on newsletter.example.com, which is not what I want.

Of course, I could change all other @Route annotations to include host="example1.com", but this is cumbersome and prone to mistakes in the future.

Is there a way to require a host for all routes by default, unless overridden in the @Route annotation?

Alice Fixtures for Nested Set Tree Entity

$
0
0

I'm upgrading:

hautelook/alice-bundle v1.4.1 -> v2.5.1
doctrine/doctrine-fixtures-bundle v2.4.1 -> 3.3.0
theofidry/alice-data-fixtures -> v1.1.2

I have a Group entity, which is setup as a nested set @Gedmo\Tree(type="nested") using Atlantic18/DoctrineExtensions

The question is pretty much an exact duplicate of Generating Doctrine fixture data for Nested Set entity with Alice Fixtures. However the solution discussed there no longer works with the newer hautelook/alice-bundle.

AppBundle\Entity\Group:
  group_root:
    title: <word()>

  sub_group:
    parent: '@group_root'
    title: <word()>

Apparently, now that bundle works differently, flushing all fixtures at once. And the tree structure cannot be created with one flush as the child group doesn't yet have the id to it's parent. The result is:

Binding entities to query parameters only allowed for entities that have an identifier.

So I guess my question is, how could I modify the fixture loading process so it leaves certain fixtures to be flushed as a second step? Or could there be an alternative solution?

PHP - Convert base64 file content to PDF

$
0
0

I have an API in Symfony and a front with React. I'm trying to upload documents (jpg, png or pdf) but I only want to store pdf file in my directory. So, when a user send an image, i want to convert it in pdf before uploading.

    public function upload($rawData, $extension, $key, &$contentType)
    {
        $rawData = explode(';base64,', $rawData);
        $contentType = substr($rawData[0], 5);
        $rawFileData = $rawData[1];

        if ($extension !== "pdf"&& $extension !== "PDF") {
            $tmpDir = '/tmp';
            $image = $tmpDir . '/' . $key . '.' . $extension;
            file_put_contents($image, base64_encode($rawFileData));

            $imagick = new \Imagick();
            $imagick->readImage($image) ;
            $imagick->writeImages($tmpDir. '.pdf', false) ;
        }
    }

I've tried with Imagick library but it's give me an error like 'convert : Not a JPEG file'. What's wrong or is it another better library to do it?

Symfony 4 Warning: filemtime() [closed]

$
0
0

it's an update form, if i try to update the first time it works but the second time i got this error:

Warning: filemtime(): stat failed for .../vendor/ocramius/proxy-manager/src/ProxyManager/GeneratorStrategy/EvaluatingGeneratorStrategy.php(54) : eval()'d code

and the exception is catched here:

 $form->handleRequest($request);

What i understood that's liated to cache, so i cleared it. But i got always the same problem : it works just the first time after i got the same error

symfony annotations access to another field

$
0
0

I wanna have a start date and end date field in the database, but start date cant be greater than end date (logically) but is there any way to use Entity to make a comparison (with Assert/Constraints) or I have to do it elsewhere(and where)

in this example I use

/**
 * @ORM\Column(type="date")
 * @Assert\GreaterThanOrEqual("today")
 */
private $start_date;

/**
 * @ORM\Column(type="date")
 */
private $end_date;

is it possible at $end date to have @Assert\GreaterThan($start_date) somehow

can I access that or I need to have some custom function for that kind of check, and what is best practice to create that kind of check in Symfony


Symfony 4 - Customizing form error messages

$
0
0

I have a simple form on my website. The submitting and database entry works perfectly, but the problem is the error message display, I want to use two ways, not sure if they also work together.

I want to show errors messages declared in the form class file:

->add('firstname', TextType::class, array(
'required'  => true,
'label'     => 'Name(s)',
'attr'      => array(
    'class'  => 'form-control',
    'data-required-message' => 'Please enter patient name!'
),
'constraints' => array(
    new Constraints\NotBlank()
)))

AND / OR

I want to show errors that are declared in the entity class file:

 /**
 * @var string
 * @ORM\Column(type="string",name="first_name", length=50)
 * @Assert\NotBlank
 */ 
protected $firstName;

Currently I have neither of the above, but what I'm trying to do is to get errors the following way, via the controller:

/**
* @Route("/patient/add", name="patient_add")
*/      
public function add(Request $request)
{
    $formOptions = array(
        'FacilityRepositoryObject'  => $this->getDoctrine()->getRepository(Facility::class),
        'SFGuardUserObject'         => $this->getDoctrine()->getRepository(SFGuardUser::class)
    );
    $errors = array();
    $patientAddForm = $this->createForm(PatientForm::class, null, $formOptions);

    $patientAddForm->handleRequest($request);

    if($patientAddForm->isSubmitted()) {
        $formData = $patientAddForm->getData();

        if($patientAddForm->isValid()) {
            $this->addPatient($formData);
        } else {
            $errors = $patientAddForm->getErrors();
        }
    }

    return $this->render('patient/add.html.twig', array(
        'addForm'   => $patientAddForm->createView(),
        'errors'        => $errors;
    ));
}

I need 3 things please:-

  • To be able to display error messages defined in the entity class file.
  • To be able to display error messages defined in the form classfile.
  • To fetch error messages via the controller and display them in the twig template file.

The other way I read about was the use of normalizers when you serialize the "$patientAddForm->getErrors()" method and get the output to display in the twig file but that only returns an empty array, I also read somewhere that this needs a normalizer/serializer to get the errors from it.

PLEASE HELP! :)

Regards, Mzimhle

How to write a query with multiple where condition and IN condition?

$
0
0

I have a query from single table with multiple where condition, IN condition and order by condition.

Basically, my query is like this.

SELECT 
    DISTINCT 
     name, 
     model, 
     plattform 
FROM   
    customer 
WHERE  
    model IN( 'a', 'b', 'c', 'd' ) 
AND column_1 > 2018 
AND status = 0 

ORDER BY 
    name, 
    model 

I have written this query using query builder as follows:

$cols = array(
              "DISTINCT version.name",
              "version.model",
              "version.plattform"
            );

$inArray = array(...);

$query = $this->createQueryBuilder("version")
        ->addSelect($cols);

$query->add("where", $query->expr()->in("version.model", $inArray))
     ->add("where", $query->expr()->gte("version.column_1", 2018))
     ->add("where", $query->expr()->eq("version.status", 0));

$query->orderBy("version.name", "version.model");


$result = $query->getDQL();

But the DQL from the query builder is not returning the result same as first one.

Can anybody please help me sort this issue.

Thank You.

Attempted to call function "yaml_parse_file" from the global namespace

$
0
0

I am new to Symfony, Facing problem while trying to run the cron job. I am really clueless, whats wrong here. It seems that I am trying to access some functions present in app/config/functions.php from the global namespace, But I can't figure out which namespace is it. Following is my code.

<?php

namespace App\Command;

use App\Services\Upcontent\Upcontent;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class UpcontentRefreshCommand extends Command
{
protected static $defaultName = 'app:upcontent-refresh';
private $upcontent;

public function __construct(Upcontent $upcontent)
{
    $this->upcontent = $upcontent;

    parent::__construct();
}

protected function configure()
{

}

protected function execute(InputInterface $input, OutputInterface $output)
{
    $output->writeln([
        '',
        '=================',
        'Upcontent Refresh',
        '=================',
        '',
    ]);

    $output->writeln('Clearing Cache...');
    clear_cache();
    $output->writeln('Cache Cleared');

    $output->writeln('Refreshing Sports Topic...');
    $output->writeln('Loading, be patient...');
    $sports = $this->upcontent->getTopic('########');

    $output->writeln([
        '',
        '=====================',
        'End Upcontent Refresh',
        '=====================',
        '',
    ]);
}
}

?>

The error occur when I run, php72 bin/console app:upcontent-refresh Please help. Thanks in advance.

Symfony 4 - Cannot create an instance of DateTime from serialized data

$
0
0

I want to persist some Json data in a entity with Symfony 4.3. As example, I usually do this :

public function storeMetadata(EncoderInterface $encoders, ObjectNormalizer $normalizers, EntityManagerInterface $entityManager): Response
{

  $data = [
      'url' => 'www.google.com',
      'title' => 'Nice title',
      'created' => '2019-12-15 11:40:00'
  ];

  $data = json_encode($data);

  $serializer = new Serializer([$normalizers], [$encoders]);
  $documentMetadata = $serializer->deserialize($data, DocumentMetadata::class, 'json');

  $entityManager->persist($documentMetadata);
  $entityManager->flush();
}

But, because I have a datetime field, I got an error "Cannot create an instance of DateTime from serialized data because its constructor requires parameter "time" to be present."

I understand that my date is a string and it should be a datetime object, but how can I serialize this date? Thanks!

My Entity

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

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

public function setCreated(?\DateTimeInterface $created): self
{
   $this->created = $created;

   return $this;
}

Symfony Warning: filemtime(): stat failed

$
0
0

it's an update form, if i try to update the first time it works but the second time i got this error:

Warning: filemtime(): stat failed for project-path/vendor/ocramius/proxy-manager/src/ProxyManager/GeneratorStrategy/EvaluatingGeneratorStrategy.php(54) : eval()'d code

and the exception is catched here:

 $form->handleRequest($request);

What i understood that's liated to cache, so i cleared it. But i got always the same problem : it works just the first time after i got the same error.

What's the solution please? thank's

Symfony 4 : "must implement interface DateTimeInterface" Error

$
0
0

I'm creating an admin with easy admin bundle, i'm really new to Symfony4.

I've a button "create a category" and when i click on it, I've this error :

Return value of App\Entity\Category::getCreatedAt() must implement interface DateTimeInterface, null returned

Code:

<?php

namespace App\Entity;

use DateInterval;
use DateTimeZone;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
 */
class Category
{

    use TimestampableTrait;

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

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="categoryId")
     */
    private $products;

    /**
     * Category constructor.
     */
    public function __construct()
    {
        $this->products = new ArrayCollection();
    }

    /**
     * @return int|null
     */
    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return string|null
     */
    public function getRef(): ?string
    {
        return $this->ref;
    }

    /**
     * @param string $ref
     * @return $this
     */
    public function setRef(string $ref): self
    {
        $this->ref = $ref;

        return $this;
    }

    /**
     * @return Collection|Product[]
     */
    public function getProducts(): Collection
    {
        return $this->products;
    }

    /**
     * @param Product $product
     * @return $this
     */
    public function addProduct(Product $product): self
    {
        if (!$this->products->contains($product)) {
            $this->products[] = $product;
            $product->setCategoryId($this);
        }

        return $this;
    }

    /**
     * @param Product $product
     * @return $this
     */
    public function removeProduct(Product $product): self
    {
        if ($this->products->contains($product)) {
            $this->products->removeElement($product);
            // set the owning side to null (unless already changed)
            if ($product->getCategoryId() === $this) {
                $product->setCategoryId(null);
            }
        }

        return $this;
    }

    /**
     * (PHP 5 &gt;=5.5.0)<br/>
     * Returns the difference between two DateTime objects
     * @link https://secure.php.net/manual/en/datetime.diff.php
     * @param DateTimeInterface $datetime2 <p>The date to compare to.</p>
     * @param bool $absolute <p>Should the interval be forced to be positive?</p>
     * @return DateInterval
     * The https://secure.php.net/manual/en/class.dateinterval.php DateInterval} object representing the
     * difference between the two dates or <b>FALSE</b> on failure.
     *
     */
    public function diff($datetime2, $absolute = false)
    {
        // TODO: Implement diff() method.
    }

    /**
     * (PHP 5 &gt;=5.5.0)<br/>
     * Returns date formatted according to given format
     * @link https://secure.php.net/manual/en/datetime.format.php
     * @param string $format <p>
     * Format accepted by  {@link https://secure.php.net/manual/en/function.date.php date()}.
     * </p>
     * @return string
     * Returns the formatted date string on success or <b>FALSE</b> on failure.
     *
     */
    public function format($format)
    {
        // TODO: Implement format() method.
    }

    /**
     * (PHP 5 &gt;=5.5.0)<br/>
     * Returns the timezone offset
     * @return int
     * Returns the timezone offset in seconds from UTC on success
     * or <b>FALSE</b> on failure.
     *
     */
    public function getOffset()
    {
        // TODO: Implement getOffset() method.
    }

    /**
     * (PHP 5 &gt;=5.5.0)<br/>
     * Gets the Unix timestamp
     * @return int
     * Returns the Unix timestamp representing the date.
     */
    public function getTimestamp()
    {
        // TODO: Implement getTimestamp() method.
    }

    /**
     * (PHP 5 &gt;=5.5.0)<br/>
     * Return time zone relative to given DateTime
     * @link https://secure.php.net/manual/en/datetime.gettimezone.php
     * @return DateTimeZone
     * Returns a {@link https://secure.php.net/manual/en/class.datetimezone.php DateTimeZone} object on success
     * or <b>FALSE</b> on failure.
     */
    public function getTimezone()
    {
        // TODO: Implement getTimezone() method.
    }

    /**
     * (PHP 5 &gt;=5.5.0)<br/>
     * The __wakeup handler
     * @link https://secure.php.net/manual/en/datetime.wakeup.php
     * @return void Initializes a DateTime object.
     */
    public function __wakeup()
    {
        // TODO: Implement __wakeup() method.
    }
}

My TimestampableTrait

<?php

namespace App\Entity;

/**
 * You must add the following comment on all the entities:
 * @ORM\HasLifecycleCallbacks()
 */
trait TimestampableTrait
{

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="createdBy")
     * @ORM\JoinColumn(nullable=true)
     */
    protected $createdBy;

    /**
     * @return User|null
     */
    public function getCreatedBy(): ?User
    {
        return $this->createdBy;
    }

    /**
     * @param User|null $createdBy
     * @return $this
     */
    public function setCreatedBy(?User $createdBy): self
    {
        $this->createdBy = $createdBy;

        return $this;
    }

    /**
     * @var \DateTime
     * @ORM\Column(type="datetime", nullable=true)
     */
    protected $createdAt;

    /**
     * @var \DateTime
     * @ORM\Column(type="datetime", nullable=false)
     */
    protected $updatedAt;

    /**
     * Set the created at value on create
     * @ORM\PrePersist()
     * @param \DateTimeInterface $createdAt
     * @return self
     */
    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;
        return $this;
    }

    /**
     * Set the updated at value on update
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     * @param \DateTimeInterface $updatedAt
     * @return self
     */
    public function setUpdatedAt(\DateTimeInterface $updatedAt): self
    {

        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get - Created At
     *
     * @return \DateTimeInterface
     */
    public function getCreatedAt(): \DateTimeInterface
    {
        return $this->createdAt;
    }

    /**
     * Get - Updated At
     *
     * @return \DateTimeInterface|null
     */
    public function getUpdatedAt(): \DateTimeInterface
    {
        return $this->updatedAt;
    }

}

I really don't get where is the problem.

How to handle i18n translations with API first architecture?

$
0
0

With I18n enabled app, Front handles its own translations, so with API, what is best suited:

1) API gives all system message as key e.g. email_invalid, firstname_required etc... and then front should translate them.

2) API gives all system messages as translated in given locale which means we are enabling i18n translation API side.


Problème de mise en place base de donnée sqlite [closed]

$
0
0

Bonjour,

en faite j'ai un problème avec symfony 4.4 pour remplacer la base de donnée mysql par sqlite , et donc en faite j'ai déja fait des recherches sur le sujet et donc j'ai déja fait certaine choses comme :

mais , je tombe à chaque fois sur ces lignes d'érreur écrites en rouge

en tout cas merci d'avance pour vôtre aide

Notice: Array to string conversion in Symfony

$
0
0

I have problem with my code. I have entity

<?php

namespace CP\API\Entity;

use CP\Model\Configuration;
use CP\Model\Content;
use CP\Model\Language;
use CP\Model\MenuTranslation;
use CP\RestBundle\Model\Locator;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;


/**
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Table(name="cp_menu")
 * @ORM\Entity(repositoryClass="CP\API\Repository\MenuRepository")
 */
class Menu
{
    /**
     * @var int
     *
     * @ORM\Id()
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var Locator
     *
     * @ORM\ManyToOne(targetEntity="Locator", cascade={"persist"})
     * @ORM\JoinColumn(name="locator_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $locator;

    /**
     * Parent Menu
     *
     * @ORM\ManyToOne(targetEntity="Menu", inversedBy="children", cascade={"persist"})
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $parent;

    /**
     * @ORM\ManyToOne(targetEntity="DataPool",cascade={"persist"})
     * @ORM\JoinColumn(name="datapool_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $dataPool;

    /**
     * @ORM\ManyToOne(targetEntity="Product")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=true)
     */
    protected $product;

    /**
     * @var string
     *
     * @ORM\Column(name="identifier", type="string", nullable=true)
     */
    protected $identifier;

    /**
     * @var array
     *
     * @ORM\Column(name="data", type="text", length=65535)
     */
    protected $data = [];

    /**
     * @var boolean
     *
     * @ORM\Column(name="display", type="boolean")
     */
    protected $display;

    /**
     * @var boolean
     *
     * @ORM\Column(name="display_children", type="boolean")
     */
    protected $displayChildren;

    /**
     * @var string
     *
     * @ORM\Column(name="path_string", type="string", nullable=false)
     */
    protected $pathString;

    /**
     * @var int
     *
     * @ORM\Column(name="priority", type="integer")
     */
    protected $priority;

    /**
     * @var int
     *
     * @ORM\Column(name="status", type="smallint", length=1)
     */
    protected $status;

    /**
     * @var boolean
     *
     * @ORM\Column(name="produce", type="boolean")
     */
    protected $produce = false;

    /**
     * @var int
     *
     * @ORM\Column(name="inheritance_priority", type="integer", nullable=false, options={"default" : 0})
     */
    protected $inheritancePriority;

    /** @var DateTime */
    protected $creation;

    /** @var DateTime */
    protected $modification;

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

    /**
     * @param int $id
     */
    public function setId(int $id): void
    {
        $this->id = $id;
    }

    /**
     * @return Locator
     */
    public function getLocator(): Locator
    {
        return $this->locator;
    }

    /**
     * @param Locator $locator
     */
    public function setLocator(Locator $locator): void
    {
        $this->locator = $locator;
    }

    /**
     * @return mixed
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * @param mixed $parent
     */
    public function setParent($parent): void
    {
        $this->parent = $parent;
    }

    /**
     * @return mixed
     */
    public function getDataPool()
    {
        return $this->dataPool;
    }

    /**
     * @param mixed $dataPool
     */
    public function setDataPool($dataPool): void
    {
        $this->dataPool = $dataPool;
    }

    /**
     * @return mixed
     */
    public function getProduct()
    {
        return $this->product;
    }

    /**
     * @param mixed $product
     */
    public function setProduct($product): void
    {
        $this->product = $product;
    }

    /**
     * @return string
     */
    public function getIdentifier(): string
    {
        return $this->identifier;
    }

    /**
     * @param string $identifier
     */
    public function setIdentifier(string $identifier): void
    {
        $this->identifier = $identifier;
    }

    /**
     * @return array
     */
    public function getData(): array
    {
        return $this->data;
    }

    /**
     * @param array $data
     */
    public function setData(array $data)
    {
        $this->data = $data;
    }

    /**
     * @return bool
     */
    public function isDisplay(): bool
    {
        return $this->display;
    }

    /**
     * @param bool $display
     */
    public function setDisplay(bool $display): void
    {
        $this->display = $display;
    }

    /**
     * @return bool
     */
    public function isDisplayChildren(): bool
    {
        return $this->displayChildren;
    }

    /**
     * @param bool $displayChildren
     */
    public function setDisplayChildren(bool $displayChildren): void
    {
        $this->displayChildren = $displayChildren;
    }

    /**
     * @return string
     */
    public function getPathString(): string
    {
        return $this->pathString;
    }

    /**
     * @param string $pathString
     */
    public function setPathString(string $pathString): void
    {
        $this->pathString = $pathString;
    }

    /**
     * @return int
     */
    public function getPriority(): int
    {
        return $this->priority;
    }

    /**
     * @param int $priority
     */
    public function setPriority(int $priority): void
    {
        $this->priority = $priority;
    }

    /**
     * @return int
     */
    public function getStatus(): int
    {
        return $this->status;
    }

    /**
     * @param int $status
     */
    public function setStatus(int $status): void
    {
        $this->status = $status;
    }

    /**
     * @return bool
     */
    public function isProduce(): bool
    {
        return $this->produce;
    }

    /**
     * @param bool $produce
     */
    public function setProduce(bool $produce): void
    {
        $this->produce = $produce;
    }

    /**
     * @return int
     */
    public function getInheritancePriority(): int
    {
        return $this->inheritancePriority;
    }

    /**
     * @param int $inheritancePriority
     */
    public function setInheritancePriority(int $inheritancePriority): void
    {
        $this->inheritancePriority = $inheritancePriority;
    }

    /**
     * @return DateTime
     */
    public function getCreation(): DateTime
    {
        return $this->creation;
    }

    /**
     * @param DateTime $creation
     */
    public function setCreation(DateTime $creation): void
    {
        $this->creation = $creation;
    }

    /**
     * @return DateTime
     */
    public function getModification(): DateTime
    {
        return $this->modification;
    }

    /**
     * @param DateTime $modification
     */
    public function setModification(DateTime $modification): void
    {
        $this->modification = $modification;
    }


}

and my method in MenuRepository:

/**
     * @param Menu $menu
     * @return mixed
     */
    public function addMenu(Menu $menu)
    {
        try {

            $this->getEntityManager()->beginTransaction(); // suspend auto-commit
            $this->getEntityManager()->persist($menu);
            $this->getEntityManager()->flush($menu);
            $this->getEntityManager()->commit();


            $this->getEntityManager()->detach($menu);


            return $menu;
        } catch (\Exception $e) {
            throw new RepositoryException($e->getMessage());
        }

When i have add new record to database, i got error:

In MenuRepository.php line 79:  
Notice: Array to string conversion  

line 79 is:

throw new RepositoryException($e->getMessage());

My Command code to add new record:

$menuData = new Menu();
$menuData->setStatus(1);
$menuData->setData([]);
$dataPool = new DataPoolEntity();
$dataPool->setIsReadonly(true);
$dataPool->setName("qwerty");
$dataPool->setDescription("tester");
$dataPool->setChildren(null);
$menuData->setDataPool($dataPool);
$menuData->setPathString('qwertty');
$menuData->setPriority(1);
$menuData->setDisplayChildren(true);
$menuData->setDisplay(true);
$menuData->setIdentifier("qwery");
$menuData->setInheritancePriority(1);

In my var.log i have this message:

[2019-12-21T20:35:49.313897+01:00] console.ERROR: Error thrown while running command "sdk:menu:create -vvvvv". Message: "Notice: Array to string conversion" {"exception":"[object] (CP\\Model\\Exception\\RepositoryException(code: 0): Notice: Array to string conversion at C:\\Users\\rever\\PhpstormProjects\\cp-base\\vendor\\cp\\web-core\\src\\Model\\Repository\\MenuRepository.php:79)","command":"sdk:menu:create -vvvvv","message":"Notice: Array to string conversion"} []

I don't have idea what is wrong with my code :( For several hours I have been looking for the cause of the error and I can't deal with it, that's why I wrote. I have already tried to add some value rigidly, but it will give the same problem.

How to use conditionType 'ON' with Doctrine?

$
0
0

I have an issue with Doctrine concerning the condition ON. I have read here that:

Now in doctrine 2 I have never seen a situation where ON can be used. In fact using ON always ends up in an exception saying you should use WITH.

But I need to redefine the join conditions. Here is my query:

$qb = $this->createQueryBuilder('fu');
$qb
    ->addSelect('cra')
    ->innerJoin('fu.chatRoomAdmins', 'cra')
    ->where('cra.operator = :operatorId')
    ->setParameter('operatorId', $operatorId);
$foreignUsers = $qb->getQuery()->getResult();

And here is the (important part) generated sql query (I change the name of table to be more readable):

SELECT *
FROM   fu
       INNER JOIN cra
               ON fu.id = cra.operator_id
WHERE  ( cra.operator_id = 'an_id');

But I need to change the ON condition to this: ON fu.id = cra.operator_id OR cra.operator_id IS NULL

If I use the WITH condition like this :

$qb
//..
    ->innerJoin('fu.chatRoomAdmins', 'cra', 'WITH', 'cra.operator IS NULL')
//..
$foreignUsers = $qb->getQuery()->getResult();

It changes my query like this:

SELECT *
FROM   fu
       INNER JOIN cra
               ON fu.id = cra.operator_id 
                  AND ( cra.operator_id IS NULL ) 
WHERE  ( cra.operator_id = 'an_id' ); 

But I want this ON condition : ON fu.id = cra.operator_id OR ( cra.operator_id IS NULL )

That why I tried to replace WITH by ON in my queryBuilder :

$qb
//..
    ->innerJoin('fu.chatRoomAdmins', 'cra', 'ON', 'cra.operator IS NULL')
//..
$foreignUsers = $qb->getQuery()->getResult();

But now I got an error : Expected end of string, got 'ON' (i'm using symfony 4)

Do you know a way to have this ON condition : ON fu.id = cra.operator_id OR ( cra.operator_id IS NULL ) ?

Symfony 4 : ADD SQLITE DATABASE

How to solve error An exception occurred in driver: SQLSTATE[HY000] [2002] Connection timed out error in symfony 4 project deployed on amazon aws

$
0
0

My symfony project is working fine on localhost . i am able to connect to amazon aws rds on localhost .I have set mysql configuration in .env file of the symfony project . when i have uploaded/deployed the same project on the amazon-aws . i am getting this error :


An exception occurred in driver: SQLSTATE[HY000] [2002] Connection timed out

Question:
How can i debug this error ?
Is this issue is related to the amazon aws configuration ?

Viewing all 3918 articles
Browse latest View live


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