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

Symfony - return non related rows

$
0
0

I have to related tables:

One - device Two - user

They are connected by the key of user_id in device table.

I need to return all results of users table that are not added in device table.

So, If I have four users in users table and two devices in device table and first is connected to user_1 and second to user_2 result will return other two users.

I think It could be done with leftJoin() but I am getting empty array result.

Code:

public function getUsersWithNoDevices()
{
    return $this->getDeviceRepository()
        ->createQueryBuilder('d')
        ->select('d', 'u')
        ->from(User::class, 'u')
        ->where('d.user IS NULL')
        ->setMaxResults(1)
        ->getQuery()
        ->getResult();
}

Maybe problem is as I meed NOT IN condition as I need to return results that not exists in device table?

Any suggestions?


Symfony 4, Doctrine and AWS RDS read replica usage

$
0
0

I'm about to embark on using RDS with a master read/write and slave read-only setup.

I've read about the Doctrine MasterSlaveConnection type.

However, there will be some endpoints I create that I would like to use the read-only replica (most of my GET endpoints) and some will need to write data (PUT, PATCH, DELETE endpoints).

I'm also using API Platform.

What is the best way of achieving this in Symfony 4 and Doctrine 2?

Confirming form after form has been submitted and validated in Symfony

$
0
0

I have a appointment form once it has been submitted you get a confirmation of the data you've filled in, The confirmation has a button that when pressed on it it should insert the data to the database.

My question is, how to implement the button on the confirmation so it inserts?


I was thinking of making a if statement as this:

if ($form->isSubmitted() && $form->isValid()) {

}

And within that if statement another if statement that would check if the button on the confirmation had been submitted so i could use the entitymanager to insert it in the database.

if ($form->isSubmitted() && $form->isValid()) {

  if () {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($appointment);
        $entityManager->persist($customer);
        $entityManager->flush();
  }

}

The appointment form: The appointment form

The confirmation template: The confirmation template


The appointment form:

{% block body %}

    <p>new appointment</p>

    {{ form_start(form) }}
    {{ form_widget(form) }}
    <button class="btn">{{ button_label|default('Plan In') }}</button>
    {{ form_end(form) }}

{% endblock %}

The confirmation template

{% block body %}

    <p>confirm appointment</p>

    <p>{{ customer_name }}</p>
    <p>{{ customer_phone }}</p>
    <p>{{ customer_email }}</p>
    <hr>
    <p>{{ barber_name }}</p>
    <p>{{ treatment_name }}</p>
    <p>{{ appointment_date|date('d-m-Y') }}</p>
    <p>{{ appointment_time|date('H:i') }}</p>

    <button class="btn">{{ button_label|default('Confirm') }}</button>

{% endblock %}

If there is any confusion within my question please ask for clarification, And if you believe there is a better way of achieving what I want to achieve please suggest so.

Any help is appreciated, Thanks in advance.

Easyadmin bundle + sf 4 : can't display a field in form

$
0
0

I'm trying to set up my product creation page, and configure the form. I have 2 entities : Product, and ProductTranslates

Database:

product enter image description here

product_translate enter image description here

There is a foreign key on product_id_id (don't know why i have twice "id"...)

I would like to use some product_translates fields, inside my product.yaml (see below)

For example, i'd like in my form, to add the "description". Do you know how i can do that please ? I can easily use the "product" properties, but don't know how to do with the product_translate, in the yaml file.

Thank you very much !!!

easy_admin:
  entities:
    # the configuration of this entity is very verbose because it's used as
    # an example to show all the configuration options available for entities
    # check out the configuration of the other entities to see how concise
    # can be the configuration of your backend
    Product:
      class: App\Entity\Product
      label: 'Produits'
      list:
        ...
      form:
        title: 'Créer un produit'
        fields:
          - { property: 'univers', label: 'univers' }
          - { property: 'product_code', label: 'Référence', type: 'number' }
          - { property: 'category_id', label: 'Catégorie', type: 'easyadmin_autocomplete', type_options: { class: 'App\Entity\Product' } }
          - { property: 'is_cocktail', label: 'Est-ce un cocktail ?', type: 'checkbox' }
          - { property: 'is_active', label: 'Voulez vous le publier ?', type: 'checkbox' }
          - { property: 'alcohol_volume', label: 'Degré d''alcool', type: 'number' }
          - { property: 'created_at', label: 'Date de création', type: 'datetime' }
          - { property: 'photo', type: 'file', label: 'Uploader une photo', help: 'Sélectionner le fichier' }
      edit:
        ...

Final result : enter image description here

Symfony 4 : localized twig date forms

$
0
0

I was used to redefine the date_widget in a form/fields.html.twig file in Symfony 2 and 3 to force twig generated date choices to french order : day month year with this code :

{%- block date_widget -%}


  {%- if widget == 'single_text' -%}
        {{ block('form_widget_simple') }}
    {%- else -%}
        <div {{ block('widget_container_attributes') }}>
            {{- date_pattern|replace({
                '{{ year }}':  form_widget(form.year),
                '{{ month }}': form_widget(form.day),
                '{{ day }}':   form_widget(form.month),
            })|raw -}}
        </div>
    {%- endif -%}

{%- endblock date_widget -%}

Now with Symfony 4.4, I get automagicaly this french order in my Linux station. But in the production server, the order is again US standard : month day year. If I redefine this order with the code sample above, I get french order in production server, but US order in my station.

Both systems have the php.ini defining date.timezone = 'Europe/Paris'

Also, the months names are in french and in english according to the month position. So where does TWIG search the locale to define this order?

Thanks

How to integrate Stripe Checkout into a Symfony project?

$
0
0

Ok I have this code and it works fine.

            var elements = stripe.elements();
            // Custom styling can be passed to options when creating an Element.
            var style = {
              base: {
                // Add your base input styles here. For example:
                fontSize: '16px',
                color: "#32325d",
              }
            };


            // Create an instance of the card Element.
            var card = elements.create('card', {hidePostalCode: true, style: style});

            // Add an instance of the card Element into the `card-element` <div>.
            card.mount('#card-element');


            // Create a token or display an error when the form is submitted.
            var form = document.getElementById('payment-form');
            form.addEventListener('submit', function(event) {
              event.preventDefault();

                stripe.createToken(card).then(function(result) {
                    if (result.error) {
                      // Inform the customer that there was an error.
                      var errorElement = document.getElementById('card-errors');
                      errorElement.textContent = result.error.message;
                    } else {
                      // Send the token to your server.
                      stripeTokenHandler(result.token);
                    }
                });

            });


            function stripeTokenHandler(token) {
              // Insert the token ID into the form so it gets submitted to the server
              var form = document.getElementById('payment-form');
              var hiddenInput = document.createElement('input');
              hiddenInput.setAttribute('type', 'hidden');
              hiddenInput.setAttribute('name', 'stripeToken');
              hiddenInput.setAttribute('value', token.id);
              form.appendChild(hiddenInput);

              // Submit the form
              form.submit();
            }

    /**
     * @param Request $request
     * @param ForfaitRepository $forfaitRepository
     * @param EntityManagerInterface $entityManager
     * @throws \Exception
     * @Route("/abonnement/don", name="don")
     */
    public function don(Request $request, EntityManagerInterface $entityManager){


            $tokenStripe = $request->request->get('stripeToken');

            $abonnement = new Abonnement();
            $montantSaisi = $request->request->get('montant');

            $montantEnCentime = $montantSaisi * 100;

                \Stripe\Stripe::setApiKey(self::PRIVATE_KEY_STRIPE);
                $token = $tokenStripe;

            
                $charge = \Stripe\Charge::create([
                    'amount' => 100,'currency' => 'eur','description' => "Ceci est un teste de don pour UWANDZANI",'source' => $token,
                ]);

The problem is that this code works but without respecting the SCA standards of Europe.

I would like to integrate stripe checkout in my application to comply with SCA standards. I have read and reread the stripe documentation, but I still can't figure out how to do it.

UploadedFile::getFilename() return an empty string

$
0
0

I am on Symfony 4.4.1, Php 7.2 When I upload a pdf file more than 2Mo, UploadedFile::getFilename() return an empty string

$pdf = $request->files->get('file');
dd($pdf->getFilename()); //EMPTY STRING IF PDF SIZE MORE THAN 2Mo

Someone have any idea?

symfony4 / doctrine add new property not found in preupdate/pre presist function [closed]

$
0
0

After add new property to class (and migrate it), I add new pre presist/pre update function, but the new property not found in this object


How to add classes to Symfony 4 “SubmitType” item labels?

$
0
0

I added input[type=submit] with label, but i dont know how add custom class to label? help me...

->add('save', SubmitType::class, [
         'label' => 'click me',
         'attr' => ['class' => 'c-form-input__input']
    ])

How to start local server with symfony 5 or downgrade version to 4.4?

$
0
0

I started a new project in new Symfony 5 and i can't open my local server.

On Symfony 4.4 the command PHP bin/console server:run is OK,

But with Symfony 5 the command appears not to be defined...

C:\Users\Chris\Code\api-test> php bin/console server:run
Command "server:run" is not defined.
Do you want to run "server:dump" instead?  (yes/no) [no]:

So how to downgrade or start the local server?

Symfony -> Composer require other project symfony

$
0
0

I have a problem with 2 project Symfony.

First project is base / core for second Project.

Composer will be require first project that correct in composer but...

Executing script assets:install public [KO]
 [KO]
Script assets:install %PUBLIC_DIR% returned with error code 1

It any idea what could I do for merge first project to second that less work, example change on bundle/lib/components?

Container extension "framework" is not registered

$
0
0

I deployed my project based on Symfony4 on a server. When I run composer install on it, I have this error on cache:clear :

Script cache:clear returned with error code 1
!!
!!  In ContainerBuilder.php line 213:
!!
!!    Container extension "framework" is not registered
!!
!!

I checked and no file is missing. On my computer, I don't have this error and all is running well with the exact same code.

Composer.json :

"require": {
    "php": "^7.1.3",
    "blackknight467/star-rating-bundle": "2.*",
    "doctrine/doctrine-bundle": "~1.6",
    "doctrine/doctrine-fixtures-bundle": "^3.0",
    "doctrine/orm": "^2.5",
    "friendsofsymfony/user-bundle": "^2.1",
    "jmose/command-scheduler-bundle": "^2.0",
    "phpoffice/phpspreadsheet": "^1.1",
    "pugx/multi-user-bundle": "dev-master",
    "sensio/framework-extra-bundle": "~5.1",
    "setasign/fpdi": "1.6.*",
    "setasign/fpdi-tcpdf": "1.6.2",
    "spipu/html2pdf": "5.0.*",
    "stof/doctrine-extensions-bundle": "^1.3",
    "symfony/apache-pack": "^1.0",
    "symfony/asset": "^4.0",
    "symfony/console": "^4.0",
    "symfony/expression-language": "^4.0",
    "symfony/flex": "^1.0",
    "symfony/form": "^4.0",
    "symfony/framework-bundle": "^4.0",
    "symfony/maker-bundle": "^1.1",
    "symfony/monolog-bundle": "~3.1",
    "symfony/orm-pack": "^1.0",
    "symfony/profiler-pack": "^1.0",
    "symfony/swiftmailer-bundle": "^3.1",
    "symfony/translation": "^4.0",
    "symfony/twig-bundle": "^4.0",
    "symfony/validator": "^4.0",
    "symfony/webpack-encore-pack": "^1.0",
    "symfony/yaml": "^4.0"
},
"require-dev": {
    "symfony/dotenv": "^4.0",
    "symfony/phpunit-bridge": "^4.0",
    "symfony/web-server-bundle": "^4.0"
},

Trying to do ManyToOne relationship where stored ID is encapsulated

$
0
0

Lets say I have two tables:

Users
id, class_id, name
1, #1#, John Smith
2, #2#, Joe Smith

Classes
id, code
1, Football
2, Soccer

In an old version of the project I encapsulated the class ID in the users table in "#", the plan at the time was to allow users in multiple classes so to store them like #1#,#2#. I cannot possibly tell you the reason for that looking back now. Regardless I'm trying to use the same database but write new frontend with symfony/doctrine.

I have manytoone relationships for all my other tables and it works great. I have come to a point where I need to access the class entity from the user entity to get the "code" field. I tried to just create the manytoone relationship and hope beyond hope that doctrine in the background would strip out the non-numeric characters. But instead I get a big fat "Entity of type for IDs id(0) was not found".

I would prefer to not iterate through the database to remove the "#" characters, even though this is probably the correct way, it would break the existing working code that is still being used and the transition goal would be to run both side by side during the transition.

Is there anything I can do?

Symfony 4 form Many to Many using join table with extra attributes

$
0
0

I cannot seem to figure out the way to embed forms together, I have used this SO question to try and get close but all I get is an out of memory error.

On the creation of a Buyer I want to add Contacts at the same time. I see examples of checkboxes for this but I want input fields and a contact might not exist.

Also contacts is a general storage for any contact to which they might be part of different buyers / sellers.

/**
 *
 * @ORM\Table(name="buyer")
 * @ORM\Entity
 */
class Buyer
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=30, nullable=false)
     */
    private $name;


    /**
     * @var string|null
     *
     * @ORM\Column(name="address", type="string", length=60, nullable=true)
     */
    private $address;

    /**
     * @var string|null
     *
     * @ORM\Column(name="city", type="string", length=60, nullable=true)
     */
    private $city;

    /**
     * @var string|null
     *
     * @ORM\Column(name="state", type="string", length=20, nullable=true)
     */
    private $state;

    /**
     * @var int|null
     *
     * @ORM\Column(name="zip", type="integer", nullable=true)
     */
    private $zip;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\BuyerContact", mappedBy="buyer")
     */
    protected $contacts;

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

...
/**
 *
 * @ORM\Table(name="buyer_contact", indexes={@ORM\Index(name="fk_buyer", columns={"buyer"}), @ORM\Index(name="fk_contact", columns={"contact"})})
 * @ORM\Entity
 */
class BuyerContact
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var Buyer
     *
     * @ORM\ManyToOne(targetEntity="App\Entity\Buyer", inversedBy="contacts")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="buyer", referencedColumnName="id")
     * })
     */
    private $buyer;

    /**
     * @var Contact
     *
     * @ORM\ManyToOne(targetEntity="App\Entity\Contact")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="contact", referencedColumnName="id")
     * })
     */
    private $contact;
...
/**
 *
 * @ORM\Table(name="contact")
 * @ORM\Entity
 */
class Contact
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string|null
     *
     * @ORM\Column(name="job_title", type="string", length=30, nullable=true)
     */
    private $jobTitle;

    /**
     * @var string|null
     *
     * @ORM\Column(name="name", type="string", length=60, nullable=true)
     */
    private $name;

    /**
     * @var string|null
     *
     * @ORM\Column(name="email", type="string", length=120, nullable=true)
     */
    private $email;

class BuyerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('buyer', TextType::class,[
                'required'=>true,
                'label'=>'Buyer',
                'help'=>'The business name of the buyer'
            ])
            ->add('address', TextType::class, [
                'required'=>false,
                'label'=>'Address 1',
                'help'=>'Address line one.'
            ])
            ->add('city', TextType::class, [
                'required'=>false,
                'label'=>'City',
            ])
            ->add('state', TextType::class,[
                'required'=>false,
                'label'=>'State',
            ])
            ->add('zip', NumberType::class, [
                'required'=>false,
                'label'=>'Zip',
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Buyer::class,
        ]);
    }
}
class BuyerContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('buyer')
            ->add('contact')
        ;
    }

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

Testing a service in Symfony4 : class not found

$
0
0

I want to test my service in Symfony 4 using phpunit bridge, but when i launch the test i get :

Error: Class 'App\Service\CompanyManager' not found

My service is located at src/Service/CompanyManager.php

tests/Service/CompanyManagerTest.php :

namespace App\Tests\Service;

use App\Service\CompanyManager;
use PHPUnit\Framework\TestCase;
use App\Entity\Company;

class CompanyManagerTest extends TestCase
{
    public function testGetCompany()
    {
        $companyManager = new CompanyManager();
        $company = $companyManager->getCompany(2);
        $this->assertInstanceOf(Company::class,$company);
        $company = $companyManager->getCompany(1000);
        $this->assertNull($company);
    }
}

In config/services_test.yaml, there is this statement :

# If you need to access services in a test, create an alias
# and then fetch that alias from the container. As a convention,
# aliases are prefixed with test. For example:
#
# test.App\Service\MyService: '@App\Service\MyService'

So i tried to add :

test.App\Service\CompanyManager: '@App\Service\CompanyManager'

But i still get the error :

$ ./vendor/bin/simple-phpunit tests
PHPUnit 5.7.27 by Sebastian Bergmann and contributors.

Testing tests
E                                                                   1 / 1 
(100%)

Time: 364 ms, Memory: 4.00MB

There was 1 error:

1) App\Tests\Service\CompanyManagerTest::testGetCompany
Error: Class 'App\Service\CompanyManager' not found

C:\...\web\vp20\tests\Service\CompanyManagerTest.php:22

Line 22 is :

$companyManager = new CompanyManager();

Any idea ?

PS : sounds like someone has the same problem there : PHPUnit Error: Class not found


creating a Symfony project using composer

$
0
0

I'm trying to get Symfony in my Mac, so I installed symfony and composer in order to start developing, but when I create the project I have some problems:

composer create-project symfony/skeleton cost_management
Installing symfony/skeleton (v4.0.5)
  - Installing symfony/skeleton (v4.0.5): Loading from cache
Created project in cost_management
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 21 installs, 0 updates, 0 removals
  - Installing symfony/flex (v1.0.71): Loading from cache
  - Installing symfony/polyfill-mbstring (v1.7.0): Loading from cache
  - Installing symfony/console (v4.0.6): Loading from cache
  - Installing symfony/routing (v4.0.6): Loading from cache
  - Installing symfony/http-foundation (v4.0.6): Loading from cache
  - Installing symfony/yaml (v4.0.6): Loading from cache
  - Installing symfony/framework-bundle (v4.0.6): Loading from cache
  - Installing symfony/http-kernel (v4.0.6): Loading from cache
  - Installing symfony/event-dispatcher (v4.0.6): Loading from cache
  - Installing psr/log (1.0.2): Loading from cache
  - Installing symfony/debug (v4.0.6): Loading from cache
  - Installing symfony/finder (v4.0.6): Loading from cache
  - Installing symfony/filesystem (v4.0.6): Loading from cache
  - Installing psr/container (1.0.0): Loading from cache
  - Installing symfony/dependency-injection (v4.0.6): Loading from cache
  - Installing symfony/config (v4.0.6): Loading from cache
  - Installing psr/simple-cache (1.0.1): Loading from cache
  - Installing psr/cache (1.0.1): Loading from cache
  - Installing symfony/cache (v4.0.6): Loading from cache
  - Installing symfony/dotenv (v4.0.6): Loading from cache
Writing lock file
Generating autoload files
Symfony operations: 4 recipes (7c280e93acfad83db0b06dac8600cc2d)
  - Configuring symfony/flex (>=1.0): From github.com/symfony/recipes:master
  - Configuring symfony/framework-bundle (>=3.3): From github.com/symfony/recipes:master
  - Configuring symfony/console (>=3.3): From github.com/symfony/recipes:master
  - Configuring symfony/routing (>=4.0): From github.com/symfony/recipes:master
Executing script cache:clear [KO]
 [KO]
Script cache:clear returned with error code 255
!!  
!!  Fatal error: Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "FileResource" from namespace "App".
!!  Did you forget a "use" statement for "Symfony\Component\Config\Resource\FileResource"? in /Users/gate11/Desktop/cost_management/src/Kernel.php:39
!!  Stack trace:
!!  #0 /Users/gate11/Desktop/cost_management/vendor/symfony/framework-bundle/Kernel/MicroKernelTrait.php(80): App\Kernel->configureContainer(Object(Symfony\Component\DependencyInjection\ContainerBuilder), Object(Symfony\Component\Config\Loader\DelegatingLoader))
!!  #1 [internal function]: App\Kernel->Symfony\Bundle\FrameworkBundle\Kernel\{closure}(Object(Symfony\Component\DependencyInjection\ContainerBuilder))
!!  #2 /Users/gate11/Desktop/cost_management/vendor/symfony/dependency-injection/Loader/ClosureLoader.php(38): call_user_func(Object(Closure), Object(Symfony\Component\DependencyInjection\ContainerBuilder))
!!  #3 /Users/gate11/Desktop/cost_management/vendor/symfony/config/Loader/DelegatingLoader.php(40): Symfony\Component\DependencyInj in /Users/gate11/Desktop/cost_management/src/Kernel.php on line 39
!!  PHP Fatal error:  Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "FileResource" from namespace "App".
!!  Did you forget a "use" statement for "Symfony\Component\Config\Resource\FileResource"? in /Users/gate11/Desktop/cost_management/src/Kernel.php:39
!!  Stack trace:
!!  #0 /Users/gate11/Desktop/cost_management/vendor/symfony/framework-bundle/Kernel/MicroKernelTrait.php(80): App\Kernel->configureContainer(Object(Symfony\Component\DependencyInjection\ContainerBuilder), Object(Symfony\Component\Config\Loader\DelegatingLoader))
!!  #1 [internal function]: App\Kernel->Symfony\Bundle\FrameworkBundle\Kernel\{closure}(Object(Symfony\Component\DependencyInjection\ContainerBuilder))
!!  #2 /Users/gate11/Desktop/cost_management/vendor/symfony/dependency-injection/Loader/ClosureLoader.php(38): call_user_func(Object(Closure), Object(Symfony\Component\DependencyInjection\ContainerBuilder))
!!  #3 /Users/gate11/Desktop/cost_management/vendor/symfony/config/Loader/DelegatingLoader.php(40): Symfony\Component\DependencyInj in /Users/gate11/Desktop/cost_management/src/Kernel.php on line 39
!!  

I tried many ways to install it, I saw the commands in their website, so I did it but still having some problems installing it. If someone knows what's wrong with it, or if I need something else, I'm hoping for your help. Thanks.

How does PHP-DI Symfony Bridge work and how to set up it correctly?

$
0
0

I have some problems by getting the PHP-DI 6 & Symfony 4 combination working. So I'd like to get a deeper understanding, how this works / should work and check, whether I actually configured it correctly.

Symfony uses by default its own DI container, symfony/dependency-injection. In the App\Kernel there is a "hook" method configureContainer(...). In this method the DIC can be configured. Another place for the DIC configuration is the services.yaml.

Now I install the php-di/php-di and the php-di/symfony-bridge and set it up in the App\Kernel#buildPHPDIContainer(...) as in the PHP-DI docu explained:

/*
Cannot use ContainerBuilder as in the PHP-DI docu,
since its already in use by the AppKernel\configureContainer(...).
*/
use DI\ContainerBuilder as PhpDiContainerBuilder;
class AppKernel extends \DI\Bridge\Symfony\Kernel
{
    // ...
    protected function buildPHPDIContainer(PhpDiContainerBuilder $builder)
    {
        $builder->addDefinitions('/path/to/file/returning/definitions/array.php');
        return $builder->build();
    }
}

Theoretical part:

What happens / should happen after it? Does the Symfony DIC become inactive? If not, does it mean, that the application uses two DICs in the same time? Make it sense to disable the Symfony's DIC?

In general: What is the idea / approach of the PHP-DI Symfony Bridge -- to replace the framework's DIC or to integrate itself into it?

Practical part:

I described above the setup steps I to get PHP-DI working with Symfony. Is there something else to do? E.g. should the AppKernel\configureContainer(...) stay as it is or should it become a proxy to the PHP-DI's AppKernel\buildPHPDIContainer(...)? Should the services.yaml be removed?

memoryleak: discrepancies in reported php memory and process memory

$
0
0

We discovered a memoryleak in one of our microservices (php7.4, symfony4.3, long-running cli process inside a docker container) and we cant figure out where it comes from.

What it does:

The process continuously reads json-messages via php aws client from SQS. For each of those messages, it pulls some data from aws dynamodb, does calculations and pushes the result into a REST api. All happening with guzzle and the client libraries.

When the process starts, we can see that within a very small amount of messages (50-100) the php process running inside a docker container on a linux system, reports a massive memory consumption in the host systems process monitor to the tune of 200-300MB and growing until the host system freezes or the process is terminated.

With the help of symfonys Progress Bar, the memory consumption from inside php memory_get_usage($real_usage = true) remains stable, between 30-50MB and not growing.

Using blackfire also did not reveal any obvious memory leaks as the level remained stable.

There seems to be a discrepancy of the memory usage reported by php's memory_get_usage(true) function, that shows ~50MB in one instance, while Gnome's System Monitor shows 250MB+

How can we find out and investigate where the memory difference might be?

Does PaymentLoggerSubscriber break the convention of using a noun to name a class? [closed]

$
0
0

The convention for creating a class name is to create it as a noun or a noun phrase. Avoid using words like Manager, Processer, or Data in the name of a class. "Referenced from clean code Robert C Martin".

My question is .. does PaymentLoggerSubsbscriber break that convention and does it misrepresent what the class does in the code below?

class PaymentLoggerSubscriber implements EventSubscriberInterface
{     
    public const EVENTS = [PaymentLoggerEvent::class => 'paymentRegistered']

    public function paymentRegistered(PaymentRegistered $event) 
    {
        // logs the event
    }
}

Symfony 4 with Material Bootstrap Select Picker not being submitted

$
0
0

Setup

  1. PHP 7.1.3
  2. Symfony 4
  3. Bootstrap 4
  4. Twig 4.3
  5. JQuery / Ajax

All being run in docker containers (MySQL 8 and nginx)

For styling, I am using Creative Tim's Bootstrap Material Dashboard (https://www.creative-tim.com/product/material-dashboard-pro)

Issue

So, using Symfony 4 forms and creating a standard drop-down select works without error when using custom blocks for the rendering:

{%- block choice_widget_collapsed -%}
    {% if attr.hidden is not defined or attr.hidden == false %}
        {%- set attr = attr|merge({class: (attr.class|default('') ~ ' selectpicker')|trim}) -%}
    {% endif %}
    {%- if required and placeholder is none and not placeholder_in_choices and not multiple and (attr.size is not defined or attr.size <= 1) -%}
        {% set required = false %}
    {%- endif -%}
    <select {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %} class="{% if required %}required{% endif %} bmd-label-static"
                                                                                             data-style="select-with-transition">
        {%- if placeholder is not none -%}
            <option value=""{% if required and value is empty %} selected="selected"{% endif %}>{{ placeholder != '' ? (translation_domain is same as(false) ? placeholder : placeholder|trans({}, translation_domain)) }}</option>
        {%- endif -%}
        {%- if preferred_choices|length > 0 -%}
            {% set options = preferred_choices %}
            {{- block('choice_widget_options') -}}
            {%- if choices|length > 0 and separator is not none -%}
                <option disabled="disabled">{{ separator }}</option>
            {%- endif -%}
        {%- endif -%}
        {%- set options = choices -%}
        {{- block('choice_widget_options') -}}
    </select>
{%- endblock choice_widget_collapsed -%}

Whenever I submit a form which has a select in the base form, the select option is passed back to the controller (using ajax) as part of the form.

However, when the form is a collection type within a form (prototyping entities) as below:

$builder
    ->add('billRatesInput',
        CollectionType::class,
        [
            'entry_type' => BillRatesInputForm::class,
            'entry_options' =>
                [
                    'label' => false,
                    'disabled' => $options['isDisabled']
                ],
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false,
        ]

    )
;

When the parent form is submitted, it takes all the parent form values and all the child form (BillRatesInputForm) except the values associated with the select fields.

If I remove the block template and allow the rendering to be a basic select box, the submission works without error, but with the block template, the submission does not work, but only on the child forms.

Viewing all 3924 articles
Browse latest View live


Latest Images

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