PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label symfony. Show all posts
Showing posts with label symfony. Show all posts

Wednesday, November 23, 2022

[FIXED] How do typehint a parameter of a function in php

 November 23, 2022     php, phpstan, symfony     No comments   

Issue

I am having issue getting the return type for this function as I have mixed types in the switch. I have used mixed, it blew up. I have used string|bool and several type for union type.

* @param  $value 
* @param  string $type

public function __construct(string $type,  $value)
    {  
        $this->type    = $type;
        $this->value   = $value;
    }

I have tried everything but it didn't pass the CI/CD pipeline (AWS)

public function getValue(bool $typed = false)
    {
        if (false === $typed) {
            return $this->value;
        }

        switch ($this->type) {
            case 'boolean':
                return (bool) $this->value;
            case 'datetime':
                if (empty($this->value)) {
                    return null;
                }

                return new \DateTime($this->value);
            case 'option_tags':
                return json_decode($this->value);
            default:
                return $this->value;
        }
    }

ERROR The following are the error

  Method App\Model\Resources::getValue() has no return typehint specified.  
  Parameter #1 $time of class DateTime constructor expects string, string|true given.                                 
  Parameter #1 $json of function json_decode expects string, bool|string given.

Solution

In modern PHP you can either provide a list of all possible types:

// Tweak type list your exact needs
public function getValue(bool $typed = false): bool|DateTime|null

... or use mixed if the method can indeed return anything:

public function getValue(bool $typed = false): mixed

In older versions, you can only use the @return tag in the docblock:

/**
 * @param bool $typed
 * @return mixed
 * @throws Exception
 */

I understand PHPStan will be happy with all options.



Answered By - Álvaro González
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 20, 2022

[FIXED] how to do a preg_replace in twig

 November 20, 2022     preg-match, preg-replace, symfony, twig     No comments   

Issue

I currently am trying to make a variable using the current url for the view. To get the url, I am using {% set uri = app.request.uri %} (uri being my variable which is the current url for that particular view). The thing is, I am only interested in what makes the url unique (the end of it - a unique object from an array - happens to be a uri), and not the beginning (path to my application). I was thinking I could use a preg_replace to do so, but TWIG doesn't have this function. Just wondering if someone would know how to accomplish what I am trying to do?

I'm new to Symfony (and fairly new to PHP), so my explanations may not be clear (sorry).

Ex.

{% set uri = app.request.uri %}

output: http://website.com/http://item.org/1

I want to modify the uri variable to ONLY have http://item.org/1 (and not the path to my website).

I'm thinking creating a Twig Extension with the preg_replace will allow me to do this ..but not sure if it's the best way to go (inexperienced).


Overall goal: The unique value for "uri" in the view is appended to the websites path by another view from an array of objects ($results) with attributes, one being "uri". My ultimate goal is to only display all associated attributes (or row) for an object in my $results array. I was thinking I could do this by first creating a key (my uri variable) in a foreach, and returning the row in the array which matches this key. This is why I am trying to create a variable with the url so that I can use it as a key for my foreach loop to iterate over $results. I am NOT using a database or Doctrine.

Thank you ahead of time for the help!


Solution

The best way is to move the logic from template to the controller.

If you need preg_replace in twig you must create custom extension.



Answered By - Alexey B.
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 13, 2022

[FIXED] How to connect to (Plesk Obsidian) database

 November 13, 2022     database, plesk, symfony     No comments   

Issue

I'm trying to connect to my Abonnement Database 'mydatabase' under the localhost.

telnet localhost 3306 is working and connects successfully.

symfony tells me the following error: 'An exception occurred in driver: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution'

if I try to connect without a password it finds the server gives me the correct error message. What is the correct way to connect to Database in Plesk?

Symfony .env

DATABASE_URL=mysql://dbuser:dbpass@localhost:3306/mydatabase

Solution

Ok, after searching many hours i find the solution:

My Database password had incorrect Characters, in my case $ and ?. I think '?' is not allowed in my case. After change the password all is going fine.

Thx for reading and i hope someone need this info as helpful.



Answered By - Daniel Richter
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do you start a memcached session in symfony2?

 November 13, 2022     memcached, php, session, symfony     No comments   

Issue

I'll try to be as detailed as possible because I was searching for now , 75 hours for a solution ..

Brace yourselves.. here we go :

I'm trying to implement the MemcacheD session handler for Symfony2 :
I have downloaded the necessary libraries and then configured Symfony2 as follows:

In app/config.yml :

imports:
    # ....
    - { resource: services/session.yml }

framework:
    # ....
    session:
      handler_id:     session.handler.memcached

app/config/parameters.yml:

session_memcached_host:     127.0.0.1
session_memcached_port:     11211
session_memcached_prefix:   ng_
session_memcached_expire:   43200

app/services/session.yml :

services:
    session.memcached:
        class: Memcached
        arguments:
            persistent_id: %session_memcached_prefix%
        calls:
            - [ addServer, [ %session_memcached_host%, %session_memcached_port% ]]

    session.handler.memcached:
        class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler
        arguments: [@session.memcached, { prefix: %session_memcached_prefix%, expiretime: %session_memcached_expire% }]

My biggest Question so far is : How do you start a session ?

Normally, you would have $session = new Session(); but not for handlers, since the documentation states (code converted to Memcached):

$storage = new NativeSessionStorage(array(), new MemcachedSessionHandler());
$session = new Session($storage); 

and this is some really weird, because the constructor needs a Memcached instance for argument, which is not given in the example of the official docs

What I did was to get the instance from the service running :

$memcached = $this->get('session.memcached');
$storage = new NativeSessionStorage(array(), new MemcachedSessionHandler($memcached));
$session = new Session($storage); 

This didn't throw any exception but then again, so I filled the session with data:

$session->set('userName', $name);
$session->set('userfName', $fname);
$session->set('userPass', $pass);
$session->set('userId', $userId);
$session->set('userPost', $userPost);
$session->set('userImage', $userImage);
$session->set('logged', true);

Everything is perfect? Wait for it...I go on another controller and run the following:

$session = $this->get('session');
var_dump($session->get('userId')); // returns null

This means that either the session was not persisted (Memcached log says otherwise) or I don't do it right, which leads to my second question: How do I read sessions from the Memcached Server?

Please, I really need this to work because I need them in websockets project.

Following the comments this is what I did:

app/config/config.yml:

session:
    cookie_lifetime: 43200
    # handler_id set to null will use default session handler from php.ini
    handler_id:  session
    save_path: ~

app/config/services.yml:

services:
    session.memcached:
        class: Memcached
        arguments:
            persistent_id: %session_memcached_prefix%
        calls:
            - [ addServer, [ %session_memcached_host%, %session_memcached_port% ]]

session:
    class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler
    arguments: [@session.memcached, { prefix: %session_memcached_prefix%, expiretime: %session_memcached_expire% }]

The error I get:

PHP Catchable fatal error: Argument 1 passed to Symfony\Component\HttpFoundation\Request::setSession() must implement interface Symfony\Component\HttpFoundation\Session\SessionInterface, instance of Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler given


Solution

Symfony full stack framework

If you use the full stack Symfony framework, than configuring memcached as a session handler is as simple as specifying it in your php.ini:

session.save_handler=memcached
session.save_path=localhost:11211

Make sure that the handler_id is set to null (~) in your app/config/config.yml. This way Symfony will use the native php handler:

framework:
    session:
        # handler_id set to null will use default session handler from php.ini
        handler_id:  ~

Now you can start using your session. It is going to be stored in memcached.

Accessing the session

Session can be accessed from the Request object:

$request->getSession()->set('name', 'Kuba');

HttpFoundation component

The same can be set up outside of a full stack framework with the HttpFoundation component alone:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;

$storage = new NativeSessionStorage(array());
$session = new Session($storage, new NamespacedAttributeBag());

$request = Request::createFromGlobals();
$request->setSession($session);

The above snippet sets the session up just like the full stack framework does (by default). This way, the script you'll put this code in, will share the session with a full Symfony application.



Answered By - Jakub Zalas
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to use FOSUSERBUNDLE and MEMCACHED?

 November 13, 2022     fosuserbundle, memcached, php, session, symfony     No comments   

Issue

I injected the services.yml like that

services:
    memcache:
        class: Memcache
        calls:
            - [ addServer, [ %session_memcached_host%, %session_memcached_port% ]]  
    session.handler.memcache:
            class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler
            arguments: [@memcache]

and my config.yml

handler_id: session.handler.memcache

and my php.ini

    extension="memcache.so"
    session.save_handler= memcache

    session.save_path= tcp://127.0.0.1:11211

and i installed memcached using this link but the problem when i load fosbundle login page i get this error

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

Solution

An easy way to integrate symfony with memcached is to use an existing bundle. I use leaseweb/memcache-bundle and it's super simple - just follow the instructions here: https://github.com/LeaseWeb/LswMemcacheBundle. And remember to start memcached first ;)

Yet to integrate this fully with FOSUserBundle, however it does support php sessions.



Answered By - beterthanlife
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When redeploying app on heroku PHP sessions disappear

 November 13, 2022     heroku, memcached, memcachier, php, symfony     No comments   

Issue

I have a Symfony app on Heroku which uses sessions (eg. to keep user logged in).



I have configured memcachier (output of heroku addons command):

Add-on                             Plan  Price
─────────────────────────────────  ────  ─────
memcachier (memcachier-flat-XXXX)  dev   free



I have also created file .user.ini in the root of my project with the following contents:

session.save_handler=memcached
memcached.sess_binary=1
session.save_path="PERSISTENT=myapp_session ${MEMCACHIER_SERVERS}"
memcached.sess_sasl_username=${MEMCACHIER_USERNAME}
memcached.sess_sasl_password=${MEMCACHIER_PASSWORD}



Also I have added to composer.json this requirement for ext-memcached:

  "require": {
        "php": ">=5.3.9",
        "ext-memcached" : "*",
        "symfony/symfony": "2.7.*",



So when I login to instance via heroku run bash and check if memcahed module is installed - it all seems fine (also phpinfo() executed served via nginx and php5-fpm returns same configuration values)

~ $ php -i | grep memcache
/app/.heroku/php/etc/php/conf.d/110-ext-memcached.ini
memcached
memcached support => enabled
libmemcached version => 1.0.18
memcached.compression_factor => 1.3 => 1.3
memcached.compression_threshold => 2000 => 2000
memcached.compression_type => fastlz => fastlz
memcached.serializer => php => php
memcached.sess_binary => 0 => 0
memcached.sess_connect_timeout => 1000 => 1000
memcached.sess_consistent_hash => 0 => 0
memcached.sess_lock_expire => 0 => 0
memcached.sess_lock_max_wait => 0 => 0
memcached.sess_lock_wait => 150000 => 150000
memcached.sess_locking => 1 => 1
memcached.sess_number_of_replicas => 0 => 0
memcached.sess_prefix => memc.sess.key. => memc.sess.key.
memcached.sess_randomize_replica_read => 0 => 0
memcached.sess_remove_failed => 0 => 0
memcached.sess_sasl_password => no value => no value
memcached.sess_sasl_username => no value => no value
memcached.store_retry_count => 2 => 2
memcached.use_sasl => 1 => 1
Registered save handlers => files user memcached 



However when inspect instance via heroku run bash and running php -i | grep session you can see that session.save_handler is still files despite configuring in .user.ini session.save_handler = memcached

session
session.auto_start => Off => Off
session.cache_expire => 180 => 180
session.cache_limiter => nocache => nocache
session.cookie_domain => no value => no value
session.cookie_httponly => Off => Off
session.cookie_lifetime => 0 => 0
session.cookie_path => / => /
session.cookie_secure => Off => Off
session.entropy_file => /dev/urandom => /dev/urandom
session.entropy_length => 0 => 0
session.gc_divisor => 1000 => 1000
session.gc_maxlifetime => 1440 => 1440
session.gc_probability => 1 => 1
session.hash_bits_per_character => 5 => 5
session.hash_function => 0 => 0
session.name => PHPSESSID => PHPSESSID
session.referer_check => no value => no value



session.save_handler => files => files
                        ^^^^^^^^^^^^^^    WTF ???


session.save_path => no value => no value
session.serialize_handler => php => php
session.upload_progress.cleanup => On => On
session.upload_progress.enabled => On => On
session.upload_progress.freq => 1% => 1%
session.upload_progress.min_freq => 1 => 1
session.upload_progress.name => PHP_SESSION_UPLOAD_PROGRESS => PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix => upload_progress_ => upload_progress_
session.use_cookies => On => On
session.use_only_cookies => On => On
session.use_strict_mode => Off => Off
session.use_trans_sid => 0 => 0

So I wonder why isn't .user.ini configuration not taking effect with real php.ini configuration?


Solution

this is a common misconception. heroku run bash spins up a separate instance of your project. ".user.ini" conditionally gets applied when you do an actual http or https call to the project because of the path the server(nginx in your case) is taking to the file it is trying to access (web.php). Basically ".user.ini" does not apply globally nor will it ever.



Answered By - Derick F
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, November 12, 2022

[FIXED] how to inject "memcache" to service.yml?

 November 12, 2022     memcached, php, session, session-cookies, symfony     No comments   

Issue

I installed memcache lib and added it to

framework:  
    session:
        handler_id: session.handler.memcache

but when I trying to use it I get this error

  [Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException]  
  You have requested a non-existent service "session.handler.memcache".       

Solution

You want to use memcache or memcached? These are two different extensions, so be aware of that. And I suggest to use memcached, memcache is dead.

Serivce session.handler.memcache is not defined, so you have to define one implementing SessionHandlerInterface, in your case MemcacheSessionHandler.

First, we need to define memcache instance as a service, so we can pass it to MemcacheSessionHandler constructor:

memcache:
    class: \Memcache
calls:
    - [ addServer, [ %host_parameter%, %port_parameter% ]]

Then, your session handler:

session.handler.memcache:
        class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler
        arguments: [@memcache]

You can also use a bundle like cache/adapter-bundle to register a PSR-6 compatible service (or even a symfony cache component, introduced in 3.1) and use Psr6SessionHandler.

If you want to use memcached, it's almost the same configuration-wise.



Answered By - Mateusz Sip
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to use Memcache with symfony

 November 12, 2022     memcached, php, session, symfony     No comments   

Issue

I using symfony 2 and I want to use Memcache with it but the problem is I can't find any explain for Memcache I just found for memcached so are they the same setup steps ? I added this lines to install Memcache on symfony?

config.yml

framework:
  session:
    handler_id: session.handler.memcached

for parameters.yml

parameters:   
  memcached_host: 127.0.0.1
  memcached_port: 11211
  memcached_prefix: custom_key_
  memcached_expire: 14400

services.yml

services:
  session.handler.memcached:
    class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler
    arguments: [ "@session.memcached", { prefix: '%memcached_prefix%', expiretime: '%memcached_expire%' } ]


services:
  session.memcached:
    class: Memcached
    arguments:
      persistent_id: %memcached_prefix%
    calls:
      - [ addServer, [ %memcached_host%, %memcached_port% ]]



services:
  session.memcached:
    class: Madisoft\AppBundle\Utils\MemcachedWrapper
    arguments:
      persistent_id: '%memcached_prefix%'
    calls:
      - [ addServer, [ '%memcached_host%', '%memcached_port%' ] ]

Solution

There is only one Memcached software, and it's the one available at https://memcached.org/.

There are two well-known PHP libraries for Memcached, called memcache (http://php.net/manual/en/book.memcache.php) and memcached (http://php.net/manual/en/book.memcached.php), so this is probably where your confusion comes from.

To use Memcached with Symfony 2 I suggest to use an external bundle by LeaseWeb which provides all the required documentation: https://github.com/LeaseWeb/LswMemcacheBundle.

Starting with Symfony 3.3 there will be a native Memcached adapter: see http://symfony.com/blog/new-in-symfony-3-3-memcached-cache-adapter.



Answered By - Francesco Abeni
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 9, 2022

[FIXED] How to serialize empty array to JSON object (curly braces) with JMS Serializer in Symfony

 November 09, 2022     jms-serializer, jmsserializerbundle, php, serialization, symfony     No comments   

Issue

Having the following PHP class

class SampleObject 
{
    private $map;

    private $array;

    public function getMap(): array 
    {
        return $map;
    }

    public function setMap(array $map) 
    {
        $this->map = $map;
    }

    public function getArray(): array
    {
        return $this->array;
    }

    public function setArray(array $array) {
        $this->array = $array;
    }
}

and two instances:

$inst1 = new SampleObject();
$inst2 = new SampleObject();
$inst1->setMap(['key' => 'value']);
$inst1->setArray([1]);
$inst2->setMap([]);
$inst2->setArray([]);

When they are serialized with JMS Serializer to json, the first one becomes:

{"map": {"key": "value"}, "array": [1]}

and the second one:

{"map": [], "array": []}

How to force the serializer to serialize the second object as {"map": {}, "array": []}?


Solution

As @EmanuelOster suggested in the comment, the custom handler can be used for this purpose. While the solution is not perfect (an annotation on the field would be much better), it works. Here is a sample handler

class SampleObjectSerializer implements SubscribingHandlerInterface {
    public static function getSubscribingMethods() {
        return [
            [
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
                'format' => 'json',
                'type' => SampleObject::class,
                'method' => 'serialize',
            ],
        ];
    }

    public function serialize(JsonSerializationVisitor $visitor, SampleObject $object, array $type, Context $context) {
        return [
            'array' => $object->getArray(),
            'map' => $this->emptyArrayAsObject($object->getMap()),
        ];
    }

    /**
     * Forces to searialize empty array as json object (i.e. {} instead of []).
     * @see https://stackoverflow.com/q/41588574/878514
     */
    private function emptyArrayAsObject(array $array) {
        if (count($array) == 0) {
            return new \stdClass();
        }
        return $array;
    }
}

If using Symfony, you need to register it.



Answered By - fracz
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the difference between the serializer virtualProperty and the accessor?

 November 09, 2022     jms-serializer, jmsserializerbundle, php, serialization, symfony     No comments   

Issue

Per the Serializer virtualProperty documentation

Note: This only works for serialization and is completely ignored during deserialization.

Other than this limitation, what is the difference between using a virtualProperty and an accessor?

If nothing, why would one want to use it, as the accessor does not have this limitation.


Solution

Best explanations have a concrete example for illustrational purposes. Therefore I'll try to give an example for using both virtualProperty and accessor to show their differences.

We have an entity Person, it has many different properties. One of them is birthdate. Let's see the example:

class Person
{
    /**
     * @Accessor(getter="getFormattedBirthdate", setter="setBirthdate")
     */
    private $birthdate;

    public function setBirthdate(\DateTimeInterface $birthdate): self
    {
        $this->birthdate = $birthdate;

        return $this;
    }

    public function getBirthdate(): \DateTimeInterface
    {
        return $this->birthdate;
    }

    public function getFormattedBirthdate(): string
    {
        return $this->birthdate->format('j F Y');
    }

    /**
     * @VirtualProperty()
     */
    public function getAge(): int
    {
        $today = new \DateTime('today');
        $age = $today->diff($this->birthdate);

        return $age->y;
    }
}

We use the Accessor to specify which getter and setter method will be used during serialization and deserialization respectively. Per default getBirthdate and setBirthdate would have been used. We'd like however to use getFormattedBirthdate for serialization.

The VirtualProperty helps us to display the calculated age. It will be used during serialization. Because it's not a real property, it has no setter and it makes no sense to deserialize it.

I hope the example helps to understand the difference between Accessor and VirtualProperty.



Answered By - cezar
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How configure JMSSerializer in Symfony to serialize custom class to/from int?

 November 09, 2022     jms-serializer, symfony     No comments   

Issue

I am working on a Symfony 3.4 based web app project which uses JMSSerializer to serialize different custom classes to JSON to send this data to mobile apps.

How can I serialize/deserialize a custom class to/from to int?


Assume we have the following classes:

<?php

// AppBundle/Entity/...

class NotificationInfo {
    public $date;      // DateTime
    public $priority;  // Int 1-10
    public $repeates;  // Boolean

    public function toInt() {
        // Create a simple Int value
        //  date = 04/27/2020
        //  priority = 5
        //  repeats = true
        //  ==> int value = 4272020 5 1 = 427202051
    }

    public function __construnct($intValue) {
       // ==> Split int value into date, priority and repeats...
    }
}


class ToDoItem {
    public $title;
    public $tags;
    public $notificationInfo;
}


// AppBundle/Resources/config/serializer/Entiy.ToDoItem.yml
AppBundle\Entity\ToDoItem:
exclusion_policy: ALL
properties:
    title:
        type: string
        expose: true
    tags:
        type: string
        expose: true
    notificationInfo:
        type: integer
        expose: true

So the class NotificationInfo also has function to create it from int and to serialize it to in. How to tell the serializer that it should serialize the value of $notificationInfo to int?

I could use the following instead:

    notificationInfo:
        type: AppBundle\Entity\NotificationInfo
        expose: true

However in this case I need to configure the serialization of NotificationInfo where I can only specify which property should serialized to which value...


EDIT:

This is the JSON I would like to create:

{
    "title": "Something ToDO",
    "tags": "some,tags",
    "notificationInfo": 427202051
}

This is what I am NOT looking for:

{
    "title": "Something ToDO",
    "tags": "some,tags",
    "notificationInfo": {
        "intValue": 427202051
    }
}

Solution

After a lot more digging I found the following solution for my problem: I added a custom serialization Handler which tells JMSSerializer how to handle my custom class:

class NotificationInfoHandler implements SubscribingHandlerInterface {

    public static function getSubscribingMethods() {
        return [
            [
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
                'format' => 'json',
                'type' => 'NotificationInfo',
                'method' => 'serializeNotificationInfoToJson',
            ],
            [
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
                'format' => 'json',
                'type' => 'NotificationInfo',
                'method' => 'deserializeNotificationInfoToJson',
            ],
        ;


    public function serializeNotificationInfoToJson(JsonSerializationVisitor $visitor, NotificationInfo $info, array $type, Context $context) {
        return $info->toInt();
    }

    public function deserializeNotificationInfoToJson(JsonDeserializationVisitor $visitor, $infoAsInt, array $type, Context $context) {
        return (is_int($infoAsInt) ? NotificationInfo::fromInt($infoAsInt) : NotificationInfo::emptyInfo());
    }

}

Thanks to autowire the handler is automatically added and can be used in the serializer metadata:

notificationInfo:
    type: NotificationInfo
    expose: true


Answered By - Andrei Herford
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to serialize object as its own property (array) using JMS Serializer EventSubscriberInterface (php, symfony)

 November 09, 2022     jms-serializer, jmsserializerbundle, php, serialization, symfony     No comments   

Issue

I need to serialize an object as its own property (it's type is array), I mean that the object has an array property books, and after transforming it I want to skip the books key, so the structure will be more flat [book1, book2] (not [books => [book1, book2]]. I have the following classes:

<?php

class Store
{
    private ?BooksCollection $booksCollection = null;

    public function __construct(?BooksCollection $booksCollection = null)
    {
        $this->booksCollection = $booksCollection;
    }

    public function getBooksCollection(): ?BooksCollection
    {
        return $this->booksCollection;
    }
}

class BooksCollection
{
    /** @var Book[] */
    private array $books;

    public function __construct(Book ...$books)
    {
        $this->books = $books;
    }

    public function getBooks(): array
    {
        return $this->books;
    }
}

class Book
{
    private string $title;

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

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

and serialization config:

Store:
  exclusion_policy: ALL
  properties:
    booksCollection:
      type: BooksCollection
BooksCollection:
  exclusion_policy: ALL
  properties:
    books:
      type: array<int, Book>
Book:
  exclusion_policy: ALL
  properties:
    title:
      type: string

The test I want to pass:

<?php

use JMS\Serializer\ArrayTransformerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class StoreSerializeTest extends KernelTestCase
{
    /** @var ArrayTransformerInterface */
    private $serializer;

    protected function setUp(): void
    {
        self::bootKernel();
        $this->serializer = self::$kernel->getContainer()->get('jms_serializer');
    }

    public function testSerialization(): void
    {
        $store = new Store(new BooksCollection(new Book('Birdy'), new Book('Lotr')));

        $serializedStore = $this->serializer->toArray($store);
        $storeUnserialized = $this->serializer->fromArray($serializedStore, Store::class);

        self::assertSame(
            [
                'books_collection' => [
                    ['title' => 'Birdy'],
                    ['title' => 'Lotr']
                ]
            ],
            $serializedStore
        );
        self::assertEquals($store, $storeUnserialized);
    }
}

As you can see below the test is failing. How can I get rid of one nesting 'books'? jms serializer

The main idea I had, was to use EventSubscriberInterface and onPreSerialize event, but I really can't figure out how can I replace an object BooksCollection with an array made of its own property books. Is there anyone who already know how to do it?


Solution

Finally, I figured it out. I implemented SubscribingHandlerInterface

<?php

use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigatorInterface;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\JsonSerializationVisitor;
use Book;
use BooksCollection;

class BooksCollectionHandler implements SubscribingHandlerInterface
{
    public static function getSubscribingMethods(): array
    {
        return [
            [
                'type' => BooksCollection::class,
                'format' => 'json',
                'method' => 'serialize',
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
            ],
            [
                'type' => BooksCollection::class,
                'format' => 'json',
                'method' => 'deserialize',
                'direction' => GraphNavigatorInterface::DIRECTION_DESERIALIZATION,
            ]
        ];
    }

    public function serialize(
        JsonSerializationVisitor $visitor,
        BooksCollection $booksCollection,
        array $type,
        Context $context
    ) {
        return $visitor->visitArray($booksCollection->getBooks(), ['name' => 'array'], $context);
    }

    public function deserialize(
        JsonDeserializationVisitor $visitor,
        array $data,
        array $type,
        Context $context
    ): BooksCollection {
        $collection = [];

        foreach ($data as $book) {
            $collection[] =
                $visitor->getNavigator()->accept($book, ['name' => Book::class], $context);
        }

        return new BooksCollection(...$collection);
    }
}

service config:

    books_handler:
        class: BooksCollectionHandler
        tags:
            - { name: jms_serializer.subscribing_handler }



Answered By - Borys Zielonka
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, October 26, 2022

[FIXED] How to map Product entity so that it is managed by Doctrine?

 October 26, 2022     doctrine, php, prestashop, prestashop-1.7, symfony     No comments   

Issue

I am trying to build a module under PS 1.7.6.1.

In design, I have a manyToOne relationship between a Product and a Preorder (many preorders can be associated to one product).

The Preorder object is an ORM entity:

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

    /**
     * @var int
     *
     * @ORM\Column(name="id_product", type="integer")
     */
    private $productId;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=64)
     */
    private $email;

    setter and getter
}

In controller:

//src/mymodule/src/Controller


use Doctrine\DBAL\Types\TextType;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use Doctrine\ORM\EntityManagerInterface;
use MyModule\Entity\Preoder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\HttpFoundation\Request;
use Product;

class PreorderController extends FrameworkBundleAdminController
{
public function createAction(Request $request){

        $preorder = new Preorder();
        $preorderForm = $this->createFormBuilder($preorder)
                ->add('email', EmailType::class)
                ->add('productId', EntityType::class, [
                    'class' => Product::class,
                ])
                ->getForm();

        $bookingForm->handleRequest($request);

// validate and persist
}}

The problem is that the form builder doesn't recognize the Product entity. It throws a runtime exception:

Class "Product" seems not to be a managed Doctrine entity. Did you forget to map it?

I can't find in the core files an example where such a scenario is handled. Thank you very much in advance for guiding/helping me the resolve this issue.


Solution

The main issue is that product_id is not an entity so there is 0 chance that The formbuilder handle it with the EntityType::class. you need to properly define (as explained in the doc) your ManyToOne relation with objects

on the product side :

/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
 */
class Product
{
    // usual stuff

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="product", cascade={"persist"})
     */
    private $preorders;
}

and on the preorder side:

/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
 */
class Product
{
    // usual stuff

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="preorders")
     */
    private $product;
}

In your formBuilder, product will be an entity and recognize by as such by the EntityType::class

EDIT

If your product is a legacy class unmapped by the ORM then you can use the dataTransformer to help your formBuilder recognize the legacy entity.

namespace App\DataTransformer;

class ProductToIdTransformer implements DataTransformerInterface
{
    public function transform($product)
    {
        if (null === $product) {
            return '';
        }

        return $product->getId();
    }

    public function reverseTransform($product_id)
    {
        if (!$product_id){
            return;
        } 

        //your db logic to retrieve the product

        if (null === $field){
            throw new TransformationFailedException(sprintf("the product '%s' does not exist!", $product_id));
        }

        return $product;

    }
}

Then in your formbuilder you'll use a CollectionType instead:

$preorderForm = $this->createFormBuilder($preorder)
    ->add('email', EmailType::class)
    ->add('product', CollectionType::class, [
        'class' => Product::class,
        //some logic to adapt the different choices to your needs
    ])
;

$preorderForm
    ->get('product')
    ->addModelTransformer(ProductToIdTransformer::class)
;

$preorderForm = $preorderForm->getForm();


Answered By - Pierrick Rambaud
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to call tcpdf non-static method in tpl file

 October 26, 2022     html, php, prestashop-1.7, symfony, tcpdf     No comments   

Issue

I have a problem generating Barcode in Delivery Slip template in Prestashop 1.7.6.x (or just 1.7) with the same template i was using in Prestashop 1.6

when i call the method via it give me error Using "$this when not in object context" this is the stack trace via Symfony debugger

Symfony\Component\Debug\Exception\FatalThrowableError:
Using $this when not in object context

 at vendor/tecnickcom/tcpdf/tcpdf.php:17060
 at TCPDF::serializeTCPDFtagParameters(array('6856616461MA', 'C39', '70.2', '34.5', '74.8', '21.3', '0.4', array('position' => 'R', 'label' => '*6856616461MA*', 'border' => true, 'padding' => 3, 'fgcolor' => array(0, 0, 0), 'bgcolor' => array(255, 255, 255), 'text' => true, 'font' => 'helvetica', 'fontsize' => 12, 'stretchtext' => 4), 'N'))
    (var/cache/dev/smarty/compile/ea/e9/5b/eae95be0cc705554fab57fc3b0d03cf1e7597307_0.file.delivery-slip.tpl.php:31)
 at content_5d5c68664b85e2_58996534(object(SmartyCustomTemplate))
    (vendor/smarty/smarty/libs/sysplugins/smarty_template_resource_base.php:123)
 at Smarty_Template_Resource_Base->getRenderedTemplateCode(object(SmartyCustomTemplate))
    (vendor/smarty/smarty/libs/sysplugins/smarty_template_compiled.php:114)
 at Smarty_Template_Compiled->render(object(SmartyCustomTemplate))
    (vendor/smarty/smarty/libs/sysplugins/smarty_internal_template.php:216)
 at Smarty_Internal_Template->render(false, 0)
    (vendor/smarty/smarty/libs/sysplugins/smarty_internal_templatebase.php:232)
 at Smarty_Internal_TemplateBase->_execute(object(SmartyCustomTemplate), null, null, null, 0)
    (vendor/smarty/smarty/libs/sysplugins/smarty_internal_templatebase.php:116)
 at Smarty_Internal_TemplateBase->fetch('/home/data/data/pdf/delivery-slip.tpl', null, null, null, false, true, false)
    (classes/Smarty/SmartyCustom.php:112)
 at SmartyCustomCore->fetch('/home/data/data/data/delivery-slip.tpl')
    (classes/pdf/HTMLTemplateDeliverySlip.php:139)
 at HTMLTemplateDeliverySlipCore->getContent()
    (classes/pdf/PDF.php:128)
 at PDFCore->render()
    (override/controllers/admin/AdminPdfController.php:18)
 at AdminPdfController->generatePDF(object(PrestaShopCollection), 'DeliverySlip')
    (controllers/admin/AdminPdfController.php:170)
 at AdminPdfControllerCore->generateDeliverySlipPDFByIdOrder(2837)
    (controllers/admin/AdminPdfController.php:82)
 at AdminPdfControllerCore->processGenerateDeliverySlipPDF()
    (classes/controller/AdminController.php:988)
 at AdminControllerCore->postProcess()
    (controllers/admin/AdminPdfController.php:30)
 at AdminPdfControllerCore->postProcess()
    (classes/controller/Controller.php:280)
 at ControllerCore->run()
    (classes/Dispatcher.php:515)
 at DispatcherCore->dispatch()
    (adminfolder/index.php:97)

pdf/delivery-slip.tpl

{$style_tab}
{assign var=nejma value="*"}
{assign var=code value="`$nejma``$order->shipping_number``$nejma`"}
{assign var=black value=[0,0,0]}{assign var=white value=[255,255,255]}
{assign var=stuff value=['position'=>'R','label'=>$code, 'border'=>true, 'padding'=>3, 'fgcolor'=>$black, 'bgcolor'=>$white, 'text'=>true, 'font'=>'helvetica', 'fontsize'=>12, 'stretchtext'=>4]}
{assign var=params value=TCPDF::serializeTCPDFtagParameters($order->shipping_number, 'C39', '70.2', '34.5', '74.8', '21.3', '0.4', $stuff, 'N')}

<tcpdf method="write1DBarcode" params="{$params}"/>
{* {$bc} *}
<table border="1">
        {* logo *}
   <tr> 
      <th width="185" height="72" colspan="2" rowspan="2" >
         <div class="center" >{if $logo_path}
            <img src="{$logo_path}" style="width:auto; height:72px;" />
            {/if}
         </div>
      </th>
      <th class="header" width="71" height="42">
         <div class="center" >MONTANT CRBT</div>
      </th>
      <th class="header" width="71" height="42">
         <div class="center">CCP N°</div>
      </th>
      <th class="header" width="71" height="42">
         <div class="center">CODE DE COMMANDE</div>
      </th>
   </tr>
        {* beside logo (price ref ...) *}
    <tr>
        <td width="71" height="29" >
            <div class="center">{displayPrice currency=$order->id_currency price=$order->total_paid-$order->total_paid_real|string_format:"%.2f"}</div>
        </td>
        <td width="71" height="29">
            <div class="center">6571486/V</div>
        </td>
        <td width="71" height="29">
            <div class="center">{$order->getUniqReference()}</div>
        </td>
    </tr>
        {* ligne expediteur et code a barre *}
    <tr>
        <th class="header" width="185" height="10" >EXPEDITEUR</th>
        <th class="header" width="213" height="10">CODE A BARRE</th>
    </tr>
    <tr>
        <td class="center" width="185" height="80">{$shop_address}<br/>{$shop_phone}</td>
        {* <td  width="213" height="49" colspan="3"></td> *}
    </tr>
        {* destinataire date d'exp val poids *}
    <tr>
        <th class="header" width="185" height="10">DESTINATAIRE</th>
        <th class="header" width="91" height="10" >DATE D'EXPEDITION</th>
        <th class="header" width="71" height="10" >VALEUR</th>
        <th class="header" width="51" height="10" >POIDS</th>
    </tr>
    <tr>
      <td width="185" rowspan="2" class="center">{$delivery_address}</td>
      <td width="91" height="30"></td>
      <td width="71" height="30" class="header" >{displayPrice currency=$order->id_currency price=$order->total_products}</td>
      <td width="51" height="30"></td>
    </tr>
   <tr>
        <td width="213" height="62">
            <span class="left"> Instructions particulière de l'expediteur:</span><br/>
            {* <span class="bold"> {l s='□' pdf='true'} Remettre l'envoi au destinataire en personne.</span><br/> *}
            <span class="bold center">Livrer l'envoi à l'adresse.</span>
        </td>
   </tr>
</table>

override\classes\pdf\PDFGenerator.php

<?php

class PDFGenerator extends PDFGeneratorCore
{

    /**
     * @param bool $use_cache
     * @param string $orientation
     * @param string $format
     */

    public function __construct($use_cache = false, $orientation = 'P', $format = 'A5')
    {
        TCPDF::__construct($orientation, 'mm', $format, true, 'UTF-8', $use_cache, false);
        $this->setRTL(Context::getContext()->language->is_rtl);

    }
    public function writePage()
    {
        $this->SetHeaderMargin(3);
        $this->SetFooterMargin(3);
        $this->setMargins(3, 3, 3);
        $this->AddPage();
        $this->writeHTML($this->content, true, false, true, false, '');
        $this->output('document.pdf','I');
    }
}

override\classes\pdf\PDF.php

<?php

class PDF extends PDFCore
{

    public function __construct($objects, $template, $smarty, $orientation = 'P', $format = 'A5')
    {
        parent::__construct($objects, $template, $smarty, $orientation);
        $this->pdf_renderer = new PDFGenerator((bool)Configuration::get('PS_PDF_USE_CACHE'), $orientation, $format);
        $this->template = $template;
                /*
         * We need a Smarty instance that does NOT escape HTML.
         * Since in BO Smarty does not autoescape
         * and in FO Smarty does autoescape, we use
         * a new Smarty of which we're sure it does not escape
         * the HTML.
         */
        $this->smarty = clone $smarty;
        $this->smarty->escape_html = false;

        /* We need to get the old instance of the LazyRegister
         * because some of the functions are already defined
         * and we need to check in the old one first
         */
        $original_lazy_register = SmartyLazyRegister::getInstance($smarty);

        /* For PDF we restore some functions from Smarty
         * they've been removed in PrestaShop 1.7 so
         * new themes don't use them. Although PDF haven't been
         * reworked so every PDF controller must extend this class.
         */
        smartyRegisterFunction($this->smarty, 'function', 'convertPrice', array('Product', 'convertPrice'), true, $original_lazy_register);
        smartyRegisterFunction($this->smarty, 'function', 'convertPriceWithCurrency', array('Product', 'convertPriceWithCurrency'), true, $original_lazy_register);
        smartyRegisterFunction($this->smarty, 'function', 'displayWtPrice', array('Product', 'displayWtPrice'), true, $original_lazy_register);
        smartyRegisterFunction($this->smarty, 'function', 'displayWtPriceWithCurrency', array('Product', 'displayWtPriceWithCurrency'), true, $original_lazy_register);
        smartyRegisterFunction($this->smarty, 'function', 'displayPrice', array('Tools', 'displayPriceSmarty'), true, $original_lazy_register);
        smartyRegisterFunction($this->smarty, 'modifier', 'convertAndFormatPrice', array('Product', 'convertAndFormatPrice'), true, $original_lazy_register); // used twice
        smartyRegisterFunction($this->smarty, 'function', 'displayAddressDetail', array('AddressFormat', 'generateAddressSmarty'), true, $original_lazy_register);
        smartyRegisterFunction($this->smarty, 'function', 'getWidthSize', array('Image', 'getWidth'), true, $original_lazy_register);
        smartyRegisterFunction($this->smarty, 'function', 'getHeightSize', array('Image', 'getHeight'), true, $original_lazy_register);

        $this->objects = $objects;
        if (!($objects instanceof Iterator) && !is_array($objects)) {
            $this->objects = array($objects);
        }

        if (count($this->objects) > 1) { // when bulk mode only
            $this->send_bulk_flag = true;
        }

    }
}

override\controllers\admin\AdminPdfController.php

<?php

class AdminPdfController extends AdminPdfControllerCore
{
    public function generatePDF($object, $template)
    {
        switch($template) {
            case PDF::TEMPLATE_DELIVERY_SLIP:
                $format = 'A6';
                $orientation = 'L';
                break;
            default:
                $format = 'A5';
                $orientation ='P';
        }

        $pdf = new PDF($object, $template, Context::getContext()->smarty, $orientation, $format);
        $pdf->render();
    }
}

1.PS : when i exclude the barcode everything works well

2.PS2: the same code is still operating on Prestashop 1.6 without Problems

3.PS3: i set define('K_TCPDF_CALLS_IN_HTML', true); //was false so i can call tcpdf in tpl file.

4.PS4 : config file of tcpdf is at vendor\tecnickcom\tcpdf\config\tcpdf_config.php

any help would be apperciated thank you .


Solution

I'm not familiar with smarty, so the following is only a guess, but it might work...

Your file override\classes\pdf\PDF.php adds stuff to smarty. I'm not quite sure, if the version of smarty matches (you might have to check) but you theoretically can assign values:

 $this->smarty->assign('tcpdf', $this->pdf_renderer);

under the assumption, that your PDFGenerator ($this->pdf_renderer) actually extends TCPDF.

If that works, you should be able to do:

{assign var=params value=$tcpdf->serializeTCPDFtagParameters($order->shipping_number,...)}

hope this works ;o)



Answered By - Jakumi
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 18, 2022

[FIXED] Where to save your TWIG templates in Symfony framework

 October 18, 2022     symfony, twig     No comments   

Issue

What is the best place to keep your TWIG template and why?

app/Resources/views folder

or

YourBundle/Resources/views

Solution

Traditionally, Symfony developers stored the application templates in the Resources/views/ directory of each bundle. Then they used the logical name to refer to them (e.g. AcmeDemoBundle:Default:index.html.twig).

But for the templates used in your application, it's much more convenient to store them in the app/Resources/views/ directory. Syfmony Documentation

  • In Symfony 2, auto generated twig files were located in YourBundle/Resources/views
  • In Symfony 3, auto generated twig files are located in app/Resources/views


Answered By - niyasc
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I sort events lists depending on the status of the user who created it?

 October 18, 2022     database, symfony     No comments   

Issue

I am trying to display a list of events. So far I haven't had any problems. But I would be interested in dividing the list into two parts : events that are created by organizers and event that are created by members. I wrote my conditions saying that : "if some event exist" and "if the organizer who created the event is an organizer (or regular member)" (organizer and member depend on the status of the organizer). From the moment I wrote the second condition, I had this error :

Unexpected token "name" of value "events" ("end of statement block" expected). 

I noticed that when I added dd($events) in my controller file, organizer.id was informed but not his status which might be the problem.

events.html.twig file :

{% extends 'base.html.twig' %}

{% block title %}Liste des activités{% endblock %}

{% block main %}

<div class="events">

    <div class="vr fixed-top start-50"></div>

    <div class="row">

        <div class="col-12 col-md-6">

            <h2 class="text-center my-4">
                <img src="{{ asset('img/titres/zpeak-sorties.svg') }}" alt="Les Zpeak Sorties !">
            </h2>

            <ul class="list-group">

                {% if events and if events.organizer.status is 'organizer' %}
                    
                    {% for event in events %}

                    <a class="list-group-item list-group-item-action">
                        <img src="{{ asset('img/flag_images/' ~ event.spokenlanguage.image) }}" alt="Drapeau {{ event.spokenlanguage.name }}" class="me-2"> {{ event.title }}
                    </a>

                    {% endfor %}

                {% else %}

                    <p>Il n'y a pas de zpeak sortie organisée.</p>

                {% endif %}

            </ul>

        </div>

        <div class="col-12 col-md-6">

            <h2 class="text-center my-4">
                <img src="{{ asset('img/titres/zpeak-idees.svg') }}" alt="Les Zpeak Idées !">
            </h2>

            <ul class="list-group">

            {% if events and if events.organizer.status is 'member' %}
                    
                {% for event in events %}
                    
                <a class="list-group-item list-group-item-action">
                    <img src="{{ asset('img/flag_images/' ~ event.spokenlanguage.image) }}" alt="Drapeau {{ event.spokenlanguage.name }}" class="me-2"> {{ event.title }}
                </a>

                {% endfor %}

            {% else %}

                <p>Il n'y a pas de zpeak idée proposée.</p>

            {% endif %}

            </ul>
            
        </div>
    
    </div>

</div>

{% endblock %}

EventsController.php file

<?php

namespace App\Controller\Front;

use App\Form\SearchType;
use App\Repository\EventsRepository;
use App\Repository\CategoriesRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class EventsController extends AbstractController
{  
    #[Route('/events', name: 'events')]
    public function events(
        EventsRepository $eventsRepository, 
        CategoriesRepository $categoriesRepository
    ){
        $events = $eventsRepository->findAll();
        /* dd($events); */
        $categories = $categoriesRepository->findAll();
        return $this->render("front/events.html.twig", ['events' => $events, 'categories' => $categories]);
    }
}

Solution

Bonjour Emilie,

I suggest to remove the second if of each conditions and use == or is same as() rather than is only.

{% if events and events.organizer.status == 'organizer' %}


Answered By - Skuti
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I turn on the profiler in production mode (Symfony)?

 October 18, 2022     mode, production, profiler, symfony     No comments   

Issue

I have a strange error. My Symfony app works fine in dev mode. But in production mode I am not able to save any files. So I need to turn on the profiler in production mode for a second to see what is the error. How can I achieve this?


Solution

Symfony profiler shouldn’t be in prod mode. Symfony docs : "Never enable the profiler in production environments as it will lead to major security vulnerabilities in your project."

You need to focus on your logs server. But if you want to do this.

  1. Create a web_profiler.yaml (.../config/packages/prod)

  2. Insert this content :

    web_profiler:
      toolbar: true
      intercept_redirects: false
    
    framework:
      profiler: { only_exceptions: false }
    
  3. Remove this after your found your problem

Regards



Answered By - Yohann Daniel Carter
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make combination of two columns unique in Symfony 4 using Doctrine?

 October 18, 2022     doctrine, doctrine-orm, php, symfony     No comments   

Issue

I have a table named 'student_assignment' in which I have multiple columns from which I am showing 2 of them below:

Both of these columns are also foreign keys.

StudentId   assignmentId
    10           7           -> allowed
    10           8           -> allowed
    11           7           -> allowed
    11           7           -> not allowed, the combination of 11 7 already exists in table

I have tried this in my entity file, but it does not work.

/**
 * Webkul\CampusConnect\Entity\StudentAssignment
 *
 * @Table(name="student_assignment", 
 *    uniqueConstraints={
 *        @UniqueConstraint(name="assignment_unique", 
 *            columns={"student", "assignment"})
 *    }
 * )
 * @Entity
 */

Please how to implement this using ORM in symfony 4.

I have a link which does ther same but in Mysql. I want the solution for Symfony ORM. enter link description here

Error:

[Semantical Error] The annotation "@Table" in class Webkul\CampusConnect\En tity\StudentAssignment was never imported. Did you maybe forget to add a "u se" statement for this annotation?

Entity:

namespace Webkul\CampusConnect\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\Table;

/**
 * Webkul\CampusConnect\Entity\StudentAssignment
 *
 * @ORM\Table(name="student_assignment", 
 *    uniqueConstraints={
 *        @UniqueConstraint(name="assignment_unique", 
 *            columns={"student", "assignment"})
 *    }
 * )
 * @Entity
 */
class StudentAssignment
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Webkul\CampusConnect\Entity\Student", inversedBy="studentAssignments")
     * @ORM\JoinColumn(onDelete="CASCADE")
     */
    private $student;

Solution

You've edited, but you weren't using ORM as an imported alias, that was number 1 (see comments).

Then you missed adding ORM to the inner configuration, e.g. @ORM\UniqueConstraint instead of @UniqueConstraint. Also, the configuration of UniqueConstraint requires the use of the column names, not property.

You've not provided both sides of the join table'esque OtM - MtO relation, but I'll assume it exists. You should have:

namespace Webkul\CampusConnect\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(
 *    name="student_assignment", 
 *    uniqueConstraints={
 *        @ORM\UniqueConstraint(name="assignment_unique", columns={"student_id", "assignment_id"})
 *    }
 * )
 * @Entity
 */
class StudentAssignment
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(name="id", type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Webkul\CampusConnect\Entity\Student", inversedBy="studentAssignments")
     * @ORM\JoinColumn(name="student_id", onDelete="CASCADE")
     */
    private $student;

    /**
     * @ORM\ManyToOne(targetEntity="Webkul\CampusConnect\Entity\Assignment", inversedBy="studentAssignments")
     * @ORM\JoinColumn(name="assignment_id", onDelete="CASCADE")
     */
    private $assignment;

    // ...
}


Answered By - rkeet
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to run a background process in symfony

 October 18, 2022     php, symfony     No comments   

Issue

I have a symfony commad that needes few minutes to be completed. And i want to run it by a http request. The problem is that the server kills the command process just after sending response, he has a timeout.

i tried to use symfony process asynchronously But still not working ( i get always the timeout problem).

I dont want use the kernel.terminate event, since it is not a best practice. Here is the code in my controller :

            $commandProcess=new Process('php  bin/console app:doSomeThing');
            $commandProcess->setWorkingDirectory('./../');
            $commandProcess->start();
            $commandProcess->setTimeout(50000000);

Any response will be much appreciated.


Solution

I had to desibale the process output and add '&' after the command Here the answer:

     new Process('php  bin/console app:dosomthing &');

    $commandProcess=new Process('php  bin/console app:dosomthing &');
    $commandProcess->setWorkingDirectory('./../');
    $commandProcess->disableOutput();
    $commandProcess->setTimeout(1800);
    $commandProcess->start();


Answered By - Cheikh HAIBALA
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to pass value inside loop in template to jquery

 October 18, 2022     jquery, symfony, twig     No comments   

Issue

I want to pass a value inside a loop into a query. I made a list of rings and displayed those using a loop in a twig. and I wanted to edit one of them when I clicked the Anker.

This is my twig,

        {% set ring_id = ''%}
        {% for ring in rings%}
        <tr>
            <td><p>{{ ring.id }}</p></td>
            <td><p>{{ ring.ring_name }}</p></td>
            <td><p>{{ ring.ring_type }}</p></td>
            <td><p>{{ ring.ring_shape }}</p></td>
            <td><p>{{ ring.size }}</p></td>
            <td><p>{{ ring.price }}</p></td>
            {%set ring_id = ring.id %}
            
            <td><a href="#" id='ring_delete' >Delete</a></td>
            
        </tr>
        {% endfor %}

This is my query,

  <script>

$(function() {
    var ring_id = "{{ring_id}}";
    $('#ring_delete').on('click', function(e) {
     $.ajax({
            url: "{{ url('admin_product_custom_delete_ring') }}",
            type: "POST",
            dataType: 'json',
            data: { 
            },
            async: false
        }).done(function(data){
            alert('check' + data);
        }).fail(function(){
            alert("no");
        })

    });
 </script>

So I want to delete the ring that I chose by passing ring_id to the url. However, it says ring_id does not exist, even though I added {%set ring_id %}. How can I pass a value inside a loop using a twig into a jquery?


Solution

Try using data attributes.

<a href="#" class="ring_delete" data-id="{{ ring.id }}">Delete</a>
$('.ring_delete').on('click', function(e) {
  var ring_id = $(this).data('id');

Also notice I changed ring_delete from an id to a class. This is because ids need to be unique and there can only be one with that name. Since it's inside a loop and will be several, we should use classes instead to reference.



Answered By - Torsetha
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing