Показаны сообщения с ярлыком sylius. Показать все сообщения
Показаны сообщения с ярлыком sylius. Показать все сообщения

суббота, 12 февраля 2022 г.

[SyliusResourceBundle] how to pass model into controller?

 Sometimes you don't need to use model instead of entity, and then save some data into entity and persist it. It means you cannot use it in Sylius ResourceControllers, because your model must implement ResourceInterface, create dedicated ResourceController, Repository, Manager, and model cannot do it.

If you want it, this means you doing it wrong, because it violated CRUD principles. The best solution is to use Symfony Data Transformers https://symfony.com/doc/current/form/data_transformers.html , add it to your form, implement transform() method, where it will create your model/DTO object from entity, and reverseTransform(), where DTO will be converted into Entity object.

четверг, 27 января 2022 г.

[hateoas] [jms] how to set custom serialization group

 The issue is using Hateoas + JmsSerializerBundle with custom serialization groups don't respond with embedded with needed fields, for me they respond only with {}. The workaround is make \JMS\Serializer\Exclusion\DisjunctExclusionStrategy::shouldSkipProperty() to return with false.

You can make it with custom class, which implements ExclusionStrategyInterface before all standard Strategies in Context like this:

$view->getContext()->addExclusionStrategy(new CustomDisjunctStrategy([]));

That's it, after it it should work (but without links). If you use Sylius bundles, you can use it in overriden ViewHandler like this:

<?php

namespace App\Serializer;


use FOS\RestBundle\View\View;

use FOS\RestBundle\View\ViewHandler as RestViewHandler;

use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration;

use Sylius\Bundle\ResourceBundle\Controller\ViewHandlerInterface;

use Symfony\Component\HttpFoundation\Response;


final class ViewHandler implements ViewHandlerInterface

{

    /** @var RestViewHandler */

    private $restViewHandler;


    public function __construct(RestViewHandler $restViewHandler)

    {

        $this->restViewHandler = $restViewHandler;

    }


    /**

     * {@inheritdoc}

     */

    public function handle(RequestConfiguration $requestConfiguration, View $view): Response

    {

        if (!$requestConfiguration->isHtmlRequest()) {

            if ($requestConfiguration->getSerializationGroups()) {

                $groups = $requestConfiguration->getSerializationGroups();

                $view->getContext()->addExclusionStrategy(new CustomDisjunctStrategy([]));

            } else {

                $groups = [];

            }

            $this->restViewHandler->setExclusionStrategyGroups($groups);


            if ($version = $requestConfiguration->getSerializationVersion()) {

                $this->restViewHandler->setExclusionStrategyVersion($version);

            }


            $view->getContext()->enableMaxDepth();

        }


        return $this->restViewHandler->handle($view);

    }

}



# services.yaml:

sylius.resource_controller.view_handler:

        class: App\Serializer\ViewHandler

        arguments:

            - "@fos_rest.view_handler"

четверг, 8 июля 2021 г.

[Sylius] GridHelper::renderGrid() must be an instance of Sylius\Component\Grid\View\GridView, instance of Pagerfanta\Pagerfanta - how to fix

 It means you forgot to put `grid: gridname` into your route configuration. For example:

admin_user_index:

    path: /users

    defaults:

        _controller: app.controller.user::indexAction

        _sylius:

            template: "@AdminBundle/grid/index.html.twig"

            grid: admin_user

понедельник, 19 апреля 2021 г.

[JMSSerializer] default serialization group are ignored fix

 If your default serialization group not working (does not ignore fields which should be shown only with specific group, not Default), check that \JMS\Serializer\Exclusion\GroupsExclusionStrategy is added into \JMS\Serializer\Context at  \JMS\Serializer\GraphNavigator::accept() method.

If you are using Sylius (or standalone bundles), it occurs when \FOS\RestBundle\Serializer\JMSSerializerAdapter does not add GroupsExclusionStrategy. You can fix it with adding serialization_groups: [Default] like this:

api_building_show:

    path: /exam/{id}

    methods: [GET]

    defaults:

        _controller: app.controller.building:showAction

        _sylius:

            serialization_groups: [Default]

суббота, 17 апреля 2021 г.

[FOSRestBundle] Showing custom Exception message no working fix

 If ./config/packages/fos_rest.yaml:

fos_rest:

    exception:

        messages:

            Symfony\Component\HttpKernel\Exception\HttpException: true

for you too, you can inject this service manually like this in services.yaml:

fos_rest.exception.messages_map:

        class: FOS\RestBundle\Util\ExceptionValueMap

        public: false

        arguments:

            - { Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: true }

thanks to https://github.com/FriendsOfSymfony/FOSRestBundle/issues/1522 

понедельник, 23 ноября 2020 г.

[Sylius] Argument 1 passed to Sylius\Component\Grid\Definition\Filter::setTemplate() must be of the type string, null given fix

 put `grid: <gridname>` into your route like this:

tests:
path: /tests
defaults:
_controller: app.controller.test:indexAction
_sylius:
template: tests/index.html.twig
grid: app_test

воскресенье, 22 ноября 2020 г.

[Monofony] how to create/get admin user?

 run `php bin/console app:install:database`, after then you will have user "admin@example.com" with password "admin". You can use it in 127.0.0.1:8000/admin/login

воскресенье, 1 декабря 2019 г.

sylius.resource_controller.flash_helper has a dependency on a non-existent parameter "locale" - fix

if you have the such error:

The service "sylius.resource_controller.flash_helper" has a dependency on a non-existent parameter "locale". Did you mean one of these: "kernel.default_locale", "stof_doctrine_extensions.default_locale"?

It means you do not have an locale service parameter. To fix this, add this to the beginning of your project config/services.yaml file:

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: en

воскресенье, 1 сентября 2019 г.

Ways to optimize a Sylius project in dev mode

If you feel that your Sylius dev configuration is slow, try this:

1) use nginx (or docker with nginx) instead of php bin/console server:run
2) be sure XDebug is disabled
3) add these lines to your php.ini:

opcache.memory_consumption=256
opcache.max_accelerated_files=20000
realpath_cache_size=4096K

четверг, 25 апреля 2019 г.

[Sylius] The page you are looking for does not exist. at /payment/capture/Nvh8PX4pKVmoPE3xLd-AkXdtebcn_onUdnHiXX1KT-8

It occurs when order is created with non-default locale, and at Payum method locale is reset, because route /payment/capture/{token} doesn't contains locale code placeholder.

You can fix it with adding to payum.xml route config /{locale} prefix in another route file, for example shop.yaml file.

[Sylius] fix mysql errors with INSERT INTO sylius_shipping_method_translation after services.yaml locale changing

If you have errors similar to INSERT INTO sylius_shipping_method_translation (name, description, locale, translatable_id) VALUES (?, ?, ?, ?)' with params [null, null, "lv", 1] error after services.yaml changing locale , also with another Sylius tables, try to manually add these records in database.

For example, if you have problems with product db table, go to admin/products/{id}/edit and add translation to your main locale, do it for every product.

It occurs when you switch the main locale, then adding something to cart (in another words create an order). Order entity has relation to Shipping method, which has relation to Shipping method translation entity, which doesn't exists with needed locale. So Doctrine thinks it should persist before creating an Order, so there occurs an error.

среда, 17 апреля 2019 г.

Another way to create Sylius Resource factory

Use this in services.yaml:

App\Factory\RideFactory:
        decorates: app.factory.ride
        arguments:
            - "@App\Factory\RideFactory.inner"


App\Factory\RideFactory:
<?php
declare(strict_types=1);

namespace App\Factory;

use App\Entity\Ride;
use Sylius\Component\Resource\Factory\FactoryInterface;

class RideFactory implements FactoryInterface
{
    /**
     * @var FactoryInterface
     */
    private $decorated;

    public function __construct(FactoryInterface $decoratedFactory)
    {
        $this->decorated = $decoratedFactory;
    }

    public function createNew()
    {
        return new Ride();
    }
}

Finally you shouldn't add anything into `sylius_resource` in config.yml.

суббота, 6 апреля 2019 г.

[Sylius] How to autowire AbstractResourceType

Use this in your class:

final class HomepageOrderType extends AbstractResourceType
{
    public function __construct(array $validationGroups = [])
    {
        parent::__construct(Order::class, $validationGroups);
    }
    ...

четверг, 28 марта 2019 г.

sylius grid 'sorting' doesnt work fix

make your needed field for sorting `sortable: true` in `fields:` definition, for example:

sylius_grid:
    grids:
        my_grid:
            driver:
                name: doctrine/orm
                options:
                    class: App\Document\Record
            sorting:
                datetime: desc
            fields:
                datetime:
                    type: datetime
                    sortable: true

четверг, 1 ноября 2018 г.

[sylius standalone bundles] "DataSource::__construct() must be an instance of Doctrine\ORM\QueryBuilder, null given" error fix

It means that your Grid repository method doesn't return QueryBuilder, maybe at now you return array/one entity objects with getResult() method inside Repository method.

Example of correct QueryBuilder repository method:

public function createPrivateListQueryBuilder(int $residentId): QueryBuilder{    return $this->createQueryBuilder('a')        ->leftJoin('a.user', 'user')        ->where('user.id = :id')        ->setParameter('id', $residentId);}

Notice that there is no getResult()/getOneOrNullResult()/getSingleResult().
Appears in versions Sylius 1.0 - 1.3, maybe earlier.

понедельник, 5 марта 2018 г.

четверг, 28 сентября 2017 г.

Sylius - The table with name 'sylius_order' already exists

1) be sure you have added your class' model parameter to config.yml, as described in Sylius documentation;

2) be sure you do not use old parent class somewhere else in config.yml - for example, this will cause error below. Do not forget to change it as new class:
sylius_resource:
    resources:
        sylius.accountant:
            classes:
                model: AppBundle\Entity\Order
        sylius.worker:
            classes:
                model: AppBundle\Entity\Order


понедельник, 18 сентября 2017 г.

Sylius Grid component - updatedAt field not found

You should to add needed field in Grid fields and make it sortable. For example, it should look like this:
sylius_grid:    grids:        sylius_admin_product:            fields:                updatedAt:                    type: datetime
                    label: sylius.ui.last_updated
                    options:                        format: d.m.Y H:i
                    sortable: ~

[sylius] cannot delete product, product in use

1. you should delete all orders, where contains product needs to delete.
2. remove all carts where, where remains this product. You can do it with php bin/console sylius:remove-expired-carts . If you need to remove all carts for all days, add parameter sylius_order.cart_expiration_period: to app/config/config.yml and rerun previous command again.

понедельник, 4 сентября 2017 г.

sylius "No locale has been set and current locale is undefined" error after generating slug for taxon

Replace in \Sylius\Bundle\AdminBundle\Resources\private\js\sylius-taxon-slug.js in function below

function updateSlug(element) {
    var slugInput = element.parents('.content').find('[name*="[slug]"]');
    var loadableParent = slugInput.parents('.field.loadable');

    if ('readonly' == slugInput.attr('readonly')) {
        return;
    }

    loadableParent.addClass('loading');

    var data;
    if ('' != slugInput.attr('data-parent') && undefined != slugInput.attr('data-parent')) {
        data = { name: element.val(), parentId: slugInput.attr('data-parent') };
    } else if ($('#sylius_taxon_parent').length > 0 && $('#sylius_taxon_parent').is(':visible') && '' != $('#sylius_taxon_parent').val()) {
        data = { name: element.val(), parentId: $('#sylius_taxon_parent').val() };
    } else {
        data = { name: element.val() };
    }


last else's data to:


data = { name: element.val(), locale: element.closest('[data-locale]').data('locale') };

And after that ajax will work.