### Run Web Server and Environment Setup Source: https://stack.sylius.com/getting-started Sets the application secret in the environment file and starts the local web server using Docker and Symfony CLI. ```dotenv APP_SECRET=UseYourOwnSecretPlease ``` ```bash docker compose up -d symfony serve -d ``` -------------------------------- ### Initialize New Sylius Stack Project Source: https://stack.sylius.com/getting-started Commands to create a new Symfony project with the necessary webapp dependencies using either Composer or the Symfony CLI. ```bash # With Composer: composer create-project symfony/skeleton:"8.0.*" my_project_directory cd my_project_directory composer require webapp # Or with Symfony CLI: symfony new my_project_directory --version="8.0.*" --webapp cd my_project_directory ``` -------------------------------- ### Install Sylius Bootstrap Admin UI package Source: https://stack.sylius.com/bootstrap-admin-ui/getting-started Use Composer to install the package into your Symfony project. ```bash composer require sylius/bootstrap-admin-ui ``` -------------------------------- ### Initialize Stimulus App Source: https://stack.sylius.com/getting-started Manual initialization of the Stimulus application for custom asset management. ```javascript // assets/bootstrap.js import { startStimulusApp } from '@symfony/stimulus-bundle'; const app = startStimulusApp(); // assets/app.js import './bootstrap.js'; ``` -------------------------------- ### Configure Symfony Flex and Dependencies Source: https://stack.sylius.com/getting-started Enables contrib recipes for Symfony Flex and installs the required Sylius Stack packages and Doctrine dependencies. ```bash composer config extra.symfony.allow-contrib true composer require -W \ doctrine/orm \ doctrine/doctrine-bundle \ pagerfanta/doctrine-orm-adapter \ symfony/asset-mapper \ sylius/bootstrap-admin-ui \ sylius/ui-translations ``` -------------------------------- ### Define Sylius Grid Configuration Source: https://stack.sylius.com/grid/index/your_first_grid This section demonstrates how to define a Sylius grid for the 'Supplier' entity. It includes examples for configuring grid fields like 'name' and 'enabled' using PHP (recommended and config file) and YAML. The PHP examples utilize the GridBuilderInterface, while the YAML approach uses the sylius_grid configuration. ```php withFields( StringField::create('name') ->setLabel('app.ui.name'), TwigField::create('enabled', '@SyliusBootstrapAdminUi/shared/grid/field/boolean.html.twig') ->setLabel('app.ui.enabled'), ) ; } } ``` ```php addGrid(GridBuilder::create('app_admin_supplier', Supplier::class) ->withFields( StringField::create('name') ->setLabel('app.ui.name'), TwigField::create('enabled', '@SyliusBootstrapAdminUi/shared/grid/field/boolean.html.twig') ->setLabel('app.ui.enabled'), ) ) }; ``` ```yaml sylius_grid: grids: app_admin_supplier: driver: name: doctrine/orm options: class: App\Entity\Supplier fields: name: type: string label: app.ui.name enabled: type: twig label: app.ui.enabled options: template: '@SyliusBootstrapAdminUi/shared/grid/field/boolean.html.twig' # This will be a checkbox field ``` -------------------------------- ### Full Resource Configuration Reference Source: https://stack.sylius.com/resource/index/index/show_resource Provides a comprehensive example of resource configuration including templates, criteria, serialization groups, and versions. ```yaml app_book_show: path: /books/{author} methods: [GET] defaults: _controller: app.controller.book::showAction _sylius: template: Book/show.html.twig repository: method: findOneNewestByAuthor arguments: [$author] criteria: enabled: true serialization_groups: [Custom, Details] serialization_version: 1.0.2 ``` ```php use Sylius\Resource\Annotation\SyliusRoute; #[SyliusRoute( name: 'app_book_show', path: '/books/{author}', methods: ['GET'], controller: 'app.controller.book::showAction', repository: [ 'method' => 'findOneNewestByAuthor', 'arguments' => ['$author'], ], criteria: [ 'enabled' => true, ], serializationGroups: ['Custom', 'Details'], serializationVersion: '1.0.2', )] ``` -------------------------------- ### Install Sylius Admin UI with Composer Source: https://stack.sylius.com/admin-ui/getting-started Installs the Sylius Admin UI package using Composer. This is the primary method for adding the package to a Symfony project. ```bash composer require sylius/admin-ui ``` -------------------------------- ### Configure Sylius Resource with Admin UI Templates Source: https://stack.sylius.com/admin-ui/getting-started Demonstrates how to configure a Sylius Resource entity to use the Admin UI's CRUD templates. This involves annotating the entity with `#[AsResource]` and specifying the `templatesDir`. ```php namespace App\Entity; use Sylius\Resource\Metadata\AsResource; use Sylius\Resource\Model\ResourceInterface; #[AsResource( templatesDir: '@SyliusAdminUi/crud', )] class Speaker implements ResourceInterface { // ... } ``` -------------------------------- ### Install Sylius Resource Bundle with Composer Source: https://stack.sylius.com/resource/index/installation Installs the Sylius Resource Bundle using Composer. This command adds the bundle to your composer.json file and downloads the package. It assumes Composer is installed globally or provides instructions for local installation. ```bash composer require sylius/resource-bundle ``` ```bash curl -sS https://getcomposer.org/installer | php php composer.phar require sylius/resource-bundle ``` -------------------------------- ### Configure Resource Creation Route in YAML Source: https://stack.sylius.com/resource/index/index/create_resource Defines the basic route configuration for a resource creation action using the Sylius ResourceController. This setup maps a URL path to the controller's createAction, allowing for both GET and POST requests. ```yaml app_book_create: path: /books/new methods: [GET, POST] defaults: _controller: app.controller.book::createAction ``` -------------------------------- ### Install Sylius Grid Bundle with Composer Source: https://stack.sylius.com/grid/index/installation Use Composer to add the Sylius Grid Bundle to your project's dependencies. This command fetches the package and updates your composer.json file. Ensure Composer is installed globally or use the .phar file. ```bash composer require sylius/grid-bundle ``` ```bash curl -sS https://getcomposer.org/installer | php php composer.phar require sylius/grid-bundle ``` -------------------------------- ### Configure String Filters in Sylius Grid Source: https://stack.sylius.com/grid/index/filters Demonstrates how to apply string filters to a grid using either the fluent PHP GridBuilder interface or YAML configuration. The examples show both explicit filter creation and the simplified StringFilter helper. ```php withFilters( Filter::create('username', 'string') ->setFormOptions([ 'type' => 'contains', ]) ) ->withFilters( StringFilter::create('username', null, 'contains') ) ; } } ``` ```yaml sylius_grid: grids: app_user: filters: username: type: string form_options: type: contains ``` ```php addGrid(GridBuilder::create('app_user', '%app.model.user.class%') ->withFilters( Filter::create('username', 'string') ->setFormOptions([ 'type' => 'contains', ]) ) ->withFilters( StringFilter::create('username', null, 'contains') ) ); }; ``` -------------------------------- ### Customize Admin Panel Asset Initialization Source: https://stack.sylius.com/getting-started Disables default Stimulus and Symfony UX stylesheets to allow custom initialization. Provides configuration in YAML or PHP and the corresponding Twig template. ```yaml sylius_twig_hooks: hooks: 'sylius_admin.base#stylesheets': symfony_ux: enabled: false 'sylius_admin.base#javascripts': app: priority: 200 template: 'base/javascripts/app.html.twig' symfony_ux: enabled: false ``` ```php use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return static function (ContainerConfigurator $containerConfigurator): void { $containerConfigurator->extension('sylius_twig_hooks', [ 'hooks' => [ 'sylius_admin.base#stylesheets' => [ 'symfony_ux' => [ 'enabled' => false, ], ], 'sylius_admin.base#javascripts' => [ 'app' => [ 'priority' => 200, 'template' => 'base/javascripts/app.html.twig', ], 'symfony_ux' => [ 'enabled' => false, ], ], ], ]); }; ``` ```twig {{ importmap('app') }} ``` -------------------------------- ### Configure Sylius Resource entity templates Source: https://stack.sylius.com/bootstrap-admin-ui/getting-started Apply the AsResource attribute to your entity to point the templates directory to the Sylius Bootstrap Admin UI CRUD templates. ```php namespace App\Entity; use Sylius\Resource\Metadata\AsResource; use Sylius\Resource\Model\ResourceInterface; #[AsResource( // We still use the Sylius admin ui templates dir. templatesDir: '@SyliusAdminUi/crud', )] class Speaker implements ResourceInterface { // ... } ``` -------------------------------- ### Install Sylius Twig Extra using Composer Source: https://stack.sylius.com/twig-extra/getting-started Installs the sylius/twig-extra package using Composer and Symfony Flex. This is the initial step to enable the provided Twig extensions. ```bash composer require sylius/twig-extra ``` -------------------------------- ### Comprehensive Resource Controller Configuration Source: https://stack.sylius.com/resource/index/index/create_resource Provides a full example of configuring a Sylius resource route, including custom templates, form types, event names, factory methods, and criteria filtering. ```yaml app_genre_book_add: path: /{genreName}/books/add methods: [GET, POST] defaults: _controller: app.controller.book::createAction _sylius: template: Book/addToGenre.html.twig form: App\Form\BookType event: book_create factory: method: createForGenre arguments: [$genreName] criteria: group.name: $genreName redirect: route: app_book_show parameters: { title: resource.title } ``` -------------------------------- ### Configure Custom Redirects in Sylius Routes Source: https://stack.sylius.com/resource/index/index/create_resource Demonstrates how to override the default post-creation redirect behavior in Sylius. Includes examples for simple route redirection, parameterized redirects using request variables, and accessing created resource properties. ```yaml app_book_create: path: /books/new methods: [GET, POST] defaults: _controller: app.controller.book::createAction _sylius: redirect: app_book_index ``` ```yaml app_book_create: path: /genre/{genreId}/books/new methods: [GET, POST] defaults: _controller: app.controller.book::createAction _sylius: redirect: route: app_genre_show parameters: { id: $genreId } ``` ```yaml app_book_create: path: /books/new methods: [GET, POST] defaults: _controller: app.controller.book::createAction _sylius: redirect: route: app_book_show parameters: { title: resource.title } ``` -------------------------------- ### Enable Sylius Grid Bundle in Kernel Source: https://stack.sylius.com/grid/index/installation Register the Sylius Grid Bundle within your application's kernel configuration file (config/bundles.php). This step is necessary to activate the bundle's functionalities after installation. ```php ['all' => true], ]; ``` -------------------------------- ### Comprehensive Deletion Configuration Reference Source: https://stack.sylius.com/resource/index/index/delete_resource This comprehensive example demonstrates various configuration options for resource deletion, including custom event names, repository method calls with arguments, overriding criteria, and setting custom redirects. It showcases the flexibility of Sylius's resource controller. ```yaml app_genre_book_remove: path: /{genreName}/books/{id}/remove methods: [DELETE] defaults: _controller: app.controller.book::deleteAction _sylius: event: book_delete repository: method: findByGenreNameAndId arguments: [$genreName, $id] criteria: genre.name: $genreName id: $id redirect: route: app_genre_show parameters: { genreName: $genreName } ``` -------------------------------- ### State Machine Operation (Publish) Source: https://stack.sylius.com/resource/index/configure_your_operations Enables applying a state machine transition to a resource item. This example demonstrates a 'publish' transition for a book resource. ```APIDOC ## GET /books/{id}/publish ### Description Applies a 'publish' state machine transition to a specific book resource. ### Method GET ### Endpoint /books/{id}/publish ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the book to publish. ### Response #### Success Response (200) - **book** (object) - The updated book resource after the transition. - **id** (integer) - The ID of the book. - **title** (string) - The title of the book. - **state** (string) - The current state of the book. #### Error Response (404) - **message** (string) - Book not found. ``` -------------------------------- ### Complex Redirect with Parameters in Sylius Annotations Source: https://stack.sylius.com/resource/index/index/update_resource Configure a redirect with route parameters using PHP annotations. This example redirects to 'app_genre_show' and includes 'genreId' in the parameters. ```php use Sylius\Resource\Annotation\SyliusRoute; #[SyliusRoute( name: 'app_book_update', path: '/genre/{genreId}/books/{id}/edit', methods: ['GET', 'PUT'], controller: 'app.controller.book::updateAction', redirect: [ 'route' => 'app_genre_show', 'parameters' => ['id' => '$genreId'], ], )] ``` -------------------------------- ### GET /books (Index Operation) Source: https://stack.sylius.com/resource/index/configure_your_operations The Index operation provides a grid-based view of resources. It can be configured using the grid FQCN or a grid name. ```APIDOC ## GET /books ### Description Retrieves a paginated grid view of books. The grid configuration is linked via the `Index` operation metadata. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **criteria** (array) - Optional - Filtering criteria for the grid. ### Response #### Success Response (200) - **resources** (ResourceGridView) - The grid view object containing the collection data. - **books** (ResourceGridView) - Alias for the resources collection. ### Response Example { "books": { "data": [...], "pagination": { "total": 10, "page": 1 } } } ``` -------------------------------- ### Configure Resource Mapping Paths Source: https://stack.sylius.com/resource/index/installation Configures the mapping paths for resources within the Sylius Resource Bundle. This YAML configuration tells the bundle where to find your entity definitions, typically within the src/Entity directory of your project. ```yaml sylius_resource: mapping: paths: - '%kernel.project_dir%/src/Entity' ``` -------------------------------- ### Debug Sylius Resource Configuration Source: https://stack.sylius.com/resource/index/configure_your_resource Verifies the correct configuration of a Sylius resource by running a console command. This command outputs detailed metadata about the registered resource, including its alias, class, and other configuration options. It's a crucial step for troubleshooting resource setup. ```shell $ bin/console sylius:debug:resource 'App\Entity\Book' ``` -------------------------------- ### Configure Resource for Creation Operation Source: https://stack.sylius.com/cookbook/admin_panel/basic_operations This PHP code configures a resource entity, `Book`, to support the 'create' operation. It uses the `#[AsResource]` attribute to define metadata such as the admin section, route prefix, template directory, and the associated form type. The `Create()` operation is explicitly added to enable resource creation. ```php namespace App\Entity; use App\Form\BookType; use Sylius\Resource\Metadata\AsResource; use Sylius\Resource\Metadata\Create; use Sylius\Resource\Model\ResourceInterface; #[AsResource( section: 'admin', // This will influence the route name routePrefix: '/admin', templatesDir: '@SyliusAdminUi/crud', // This directory contains the generic templates formType: BookType::class, // The form type you have generated in previous step operations: [ // ... new Create(), // This operation will add "create" operation for the book resource ], )] class Book implements ResourceInterface { //... } ``` -------------------------------- ### Configure Show operation for resource details Source: https://stack.sylius.com/resource/index/configure_your_operations Configures a show operation to display individual resource details. This setup automatically generates the corresponding GET route and makes the resource entity available in Twig templates. ```php #[AsResource( operations: [ new Show(), ], ) class Book implements ResourceInterface { } ``` ```php return (new ResourceMetadata()) ->withClass(Book::class) ->withOperations( new Operations([ new Show(), ]) ); ``` -------------------------------- ### Create Book Processor Implementation (PHP) Source: https://stack.sylius.com/cookbook/ddd_architecture/basic_operations Implements the `CreateBookProcessorInterface` to handle the creation of a book resource. This processor takes a `BookResource` object, validates its properties, creates a `CreateBookCommand` from the data, and dispatches it using a command bus. It then converts the resulting model back into a `BookResource`. ```php declare(strict_types=1); namespace App\BookStore\Infrastructure\Sylius\State\Processor; use App\BookStore\Application\Command\CreateBookCommand; use App\BookStore\Domain\ValueObject\Author; use App\BookStore\Domain\ValueObject\BookContent; use App\BookStore\Domain\ValueObject\BookDescription; use App\BookStore\Domain\ValueObject\BookName; use App\BookStore\Domain\ValueObject\Price; use App\BookStore\Infrastructure\Sylius\Resource\BookResource; use App\Shared\Application\Command\CommandBusInterface; use Sylius\Resource\Context\Context; use Sylius\Resource\Metadata\Operation; use Sylius\Resource\State\ProcessorInterface; use Webmozart\Assert\Assert; /** * @implements ProcessorInterface */ final readonly class CreateBookProcessor implements ProcessorInterface { public function __construct( private CommandBusInterface $commandBus, ) { } public function process(mixed $data, Operation $operation, Context $context): BookResource { Assert::isInstanceOf($data, BookResource::class); Assert::notNull($data->name); Assert::notNull($data->description); Assert::notNull($data->author); Assert::notNull($data->content); Assert::notNull($data->price); $command = new CreateBookCommand( new BookName($data->name), new BookDescription($data->description), new Author($data->author), new BookContent($data->content), new Price($data->price), ); $model = $this->commandBus->dispatch($command); return BookResource::fromModel($model); } } ``` -------------------------------- ### Registering a Grid in a Sylius Resource Entity Source: https://stack.sylius.com/grid/index/your_first_grid Demonstrates how to attach a grid to a resource entity using the #[AsResource] attribute. This enables the index operation for the entity by specifying the grid class or name. ```php namespace App\Entity; use App\Grid\AdminSupplierGrid; use Sylius\Resource\Metadata\AsResource; use Sylius\Resource\Metadata\Index; use Sylius\Resource\Model\ResourceInterface; #[AsResource( section: 'admin', routePrefix: '/admin', templatesDir: '@SyliusAdminUi/crud', operations: [ new Index(grid: AdminSupplierGrid::class), new Index(grid: 'app_admin_supplier') ], )] class Supplier implements ResourceInterface { // ... } ``` -------------------------------- ### Use Custom Factory Service Source: https://stack.sylius.com/resource/index/index/create_resource Demonstrates how to integrate a custom service as a factory for resource creation. This uses expressions to reference a service container ID and a specific method to instantiate the resource. ```yaml app_book_create: path: /{authorId}/books/new methods: [GET, POST] defaults: _controller: app.controller.book::createAction _sylius: factory: method: ["expr:service('app.factory.custom_book_factory')", "createNewByAuthorId"] arguments: $authorId ``` -------------------------------- ### Install Sylius Twig Hooks using Composer Source: https://stack.sylius.com/twig-hooks/getting-started This command installs the Sylius Twig Hooks package using Composer and Symfony Flex. It's the first step to integrating the package into your project. ```bash composer require sylius/twig-hooks ``` -------------------------------- ### Create Book Command Definition (PHP) Source: https://stack.sylius.com/cookbook/ddd_architecture/basic_operations Defines the `CreateBookCommand` class, which encapsulates the data required to create a new book. It includes properties for name, description, author, content, and price, utilizing specific value objects for type safety. This command is intended to be dispatched via a command bus. ```php declare(strict_types=1); namespace App\BookStore\Application\Command; use App\BookStore\Domain\Model\Book; use App\BookStore\Domain\ValueObject\Author; use App\BookStore\Domain\ValueObject\BookContent; use App\BookStore\Domain\ValueObject\BookDescription; use App\BookStore\Domain\ValueObject\BookName; use App\BookStore\Domain\ValueObject\Price; use App\Shared\Application\Command\CommandInterface; /** * @implements CommandInterface */ final readonly class CreateBookCommand implements CommandInterface { public function __construct( public BookName $name, public BookDescription $description, public Author $author, public BookContent $content, public Price $price, ) { } } ``` -------------------------------- ### Enable Sylius Resource Bundle and Dependencies in Kernel Source: https://stack.sylius.com/resource/index/installation Enables the Sylius Resource Bundle and its required dependencies (BabDevPagerfantaBundle) within the application's kernel configuration. This is a necessary step after installing the bundles via Composer. ```php return [ new Sylius\Bundle\ResourceBundle\SyliusResourceBundle(), new BabDev\PagerfantaBundle\BabDevPagerfantaBundle(), ]; ``` -------------------------------- ### Defining Grid Filters Source: https://stack.sylius.com/grid/index/your_first_grid Shows how to implement search filters on a grid using different configuration styles. Options include the recommended PHP class-based builder, a PHP configuration function, or YAML configuration files. ```php withFilters( StringFilter::create('name') ->setLabel('Name'), BooleanFilter::create('enabled') ->setLabel('Enabled'), ); } } ``` ```php addGrid(GridBuilder::create('app_admin_supplier', Supplier::class) ->withFilters( StringFilter::create('name') ->setLabel('Name'), BooleanFilter::create('enabled') ->setLabel('Enabled'), ) ); }; ``` ```yaml sylius_grid: grids: app_admin_supplier: filters: name: type: string label: Name enabled: type: boolean label: Enabled ``` -------------------------------- ### Configure Resource Show Operation in PHP Source: https://stack.sylius.com/cookbook/admin_panel/basic_operations Defines a 'Book' resource with the 'show' operation enabled using the #[AsResource] attribute. This configuration influences route generation and template directories within the Sylius admin panel. It requires the Sylius Resource component. ```php namespace App\Entity; use App\Form\BookType; use Sylius\Resource\Metadata\AsResource; use Sylius\Resource\Metadata\Show; use Sylius\Resource\Model\ResourceInterface; #[AsResource( section: 'admin', // This will influence the route name routePrefix: '/admin', templatesDir: '@SyliusAdminUi/crud', // This directory contains the generic templates operations: [ // ... new Show(), // This operation will add "show" operation for the book resource ], )] class Book implements ResourceInterface { //... } ``` -------------------------------- ### GET /books/{title} Source: https://stack.sylius.com/resource/index/index/show_resource Retrieves a book resource by title with additional filtering criteria applied. ```APIDOC ## GET /books/{title} ### Description Retrieves a book by its title, applying a filter to ensure only enabled books are returned. ### Method GET ### Endpoint /books/{title} ### Parameters #### Path Parameters - **title** (string) - Required - The title of the book to search for. ### Response #### Success Response (200) - **book** (object) - The book entity matching the title and enabled status. ``` -------------------------------- ### Configure Resource for Update Operation Source: https://stack.sylius.com/cookbook/admin_panel/basic_operations This PHP code configures a resource entity, `Book`, to support the 'update' operation. Similar to the creation configuration, it uses the `#[AsResource]` attribute for metadata and explicitly adds the `Update()` operation. This enables editing existing resources. ```php namespace App\Entity; use App\Form\BookType; use Sylius\Resource\Metadata\AsResource; use Sylius\Resource\Metadata\Update; use Sylius\Resource\Model\ResourceInterface; #[AsResource( section: 'admin', // This will influence the route name routePrefix: '/admin', templatesDir: '@SyliusAdminUi/crud', // This directory contains the generic templates formType: BookType::class, // The form type you have generated in previous chapter operations: [ // ... new Update(), // This operation will add "update" operation for the book resource ], )] class Book implements ResourceInterface { //... } ``` -------------------------------- ### GET /admin/books/{id} Source: https://stack.sylius.com/resource/index/index/show_resource Retrieves a single book resource using a custom template for the administrative view. ```APIDOC ## GET /admin/books/{id} ### Description Retrieves a book resource and renders it using a specified custom template for administrative purposes. ### Method GET ### Endpoint /admin/books/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the book. ### Response #### Success Response (200) - **book** (object) - The requested book entity rendered via `Admin/Book/show.html.twig`. ``` -------------------------------- ### Submit Resource Form in HTML Source: https://stack.sylius.com/resource/index/index/create_resource Demonstrates how to link a standard HTML form to the defined resource creation route. The form uses the POST method to trigger the controller's persistence logic. ```html
``` -------------------------------- ### GET /books/{id} (Show Operation) Source: https://stack.sylius.com/resource/index/configure_your_operations The Show operation retrieves the details of a specific resource item identified by its ID. ```APIDOC ## GET /books/{id} ### Description Fetches the details of a single book resource by its unique identifier. ### Method GET ### Endpoint /books/{id} ### Parameters #### Path Parameters - **id** (mixed) - Required - The unique identifier of the book. ### Response #### Success Response (200) - **book** (App\Entity\Book) - The requested book entity. ### Response Example { "book": { "id": 1, "title": "Example Book", "author": "Author Name" } } ``` -------------------------------- ### Index Operation Source: https://stack.sylius.com/resource/index/configure_your_operations The Index operation allows you to browse all items of your resource. It typically maps to a GET request on a collection endpoint. ```APIDOC ## GET /books ### Description Retrieves a list of all resources. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **page** (int) - Optional - The page number for pagination. - **limit** (int) - Optional - The number of items per page. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **resources** (Pagerfanta\Pagerfanta) - A paginated list of resources. - **books** (Pagerfanta\Pagerfanta) - An alias for the resources variable. - **operation** (Sylius\Resource\Metadata\Index) - The index operation metadata. - **resource_metadata** (Sylius\Resource\Metadata\ResourceMetadata) - The metadata for the resource. - **app** (Symfony\Bridge\Twig\AppVariable) - The Twig application variable. #### Response Example ```json { "resources": { ... }, "books": { ... }, "operation": { ... }, "resource_metadata": { ... }, "app": { ... } } ``` ``` -------------------------------- ### GET /books/{id} Source: https://stack.sylius.com/resource/index/index/show_resource Retrieves a single book resource by its unique identifier. This endpoint uses the default ResourceController showAction. ```APIDOC ## GET /books/{id} ### Description Fetches a single book resource from the repository based on the provided ID. If the resource is not found, a 404 error is returned. ### Method GET ### Endpoint /books/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the book. ### Response #### Success Response (200) - **book** (object) - The requested book entity rendered via the default template `App:Book:show.html.twig`. ``` -------------------------------- ### Complex Redirect with Parameters in Sylius Routes Source: https://stack.sylius.com/resource/index/index/update_resource Define a redirect with specific route parameters. This example redirects to 'app_genre_show' and passes the 'genreId' as a parameter. ```yaml app_book_update: path: /genre/{genreId}/books/{id}/edit methods: [GET, PUT] defaults: _controller: app.controller.book::updateAction _sylius: redirect: route: app_genre_show parameters: { id: $genreId } ``` -------------------------------- ### Configure Grid Actions Source: https://stack.sylius.com/grid/index/your_first_grid Implements grid actions to enable user interaction with resources. Supports main actions (global) and item actions (per-row) using PHP classes or YAML configuration. ```php final class AdminSupplierGrid extends AbstractGrid { public function __invoke(GridBuilderInterface $gridBuilder): void { $gridBuilder ->addActionGroup( MainActionGroup::create( CreateAction::create() ) ) ->addActionGroup( ItemActionGroup::create( UpdateAction::create(), DeleteAction::create() ) ); } } ``` ```php return static function (GridConfig $grid) { $grid->addGrid(GridBuilder::create('app_admin_supplier', Supplier::class) ->addActionGroup( MainActionGroup::create( CreateAction::create() ) ) ->addActionGroup( ItemActionGroup::create( UpdateAction::create(), DeleteAction::create() ) ) ); }; ``` ```yaml sylius_grid: grids: app_admin_supplier: actions: main: create: type: create item: update: type: update delete: type: delete ``` -------------------------------- ### Custom Redirect After Update in Sylius Routes Source: https://stack.sylius.com/resource/index/index/update_resource Configure a custom redirect route after a successful resource update. This example redirects to the 'app_book_index' route. ```yaml app_book_update: path: /books/{id}/edit methods: [GET, PUT] defaults: _controller: app.controller.book::updateAction _sylius: redirect: app_book_index ``` -------------------------------- ### Implement Custom Factory Methods and Resource Metadata Source: https://stack.sylius.com/resource/index/resource_factories Demonstrates adding custom methods to a factory and referencing them within the resource metadata configuration to handle specific creation logic. ```php declare(strict_types=1); namespace App\Factory; use App\Entity\Book; use Sylius\Resource\Factory\FactoryInterface; use Symfony\Component\Security\Core\Security; final class BookFactory implements FactoryInterface { public function __construct(private Security $security) { } public function createNew(): Book { return new Book(); } public function createWithCreator(): Book { $book = $this->createNew(); $book->setCreator($this->security->getUser()); return $book; } } ``` ```php #[AsResource( operations: [ new Create( path: 'authors/{authorId}/books', factoryMethod: 'createWithCreator', ), ], ) class Book implements ResourceInterface { } ``` -------------------------------- ### Implement BookItemProvider for Resource Retrieval Source: https://stack.sylius.com/cookbook/ddd_architecture/basic_operations Creates a custom provider that fetches a book entity using a query bus. It extracts the ID from the request context and returns a mapped BookResource. ```php final readonly class BookItemProvider implements ProviderInterface { public function __construct(private QueryBusInterface $queryBus) {} public function provide(Operation $operation, Context $context): object|array|null { $id = $context->get(RequestOption::class)?->request()->attributes->getString('id'); $model = $this->queryBus->ask(new FindBookQuery(new BookId(Uuid::fromString($id)))); return BookResource::fromModel($model); } } ``` -------------------------------- ### Override Update Criteria in Sylius Annotations Source: https://stack.sylius.com/resource/index/index/update_resource Achieve the same customization as the YAML example but using PHP annotations. This defines the 'title' as the lookup criteria for the update action. ```php use Sylius\Resource\Annotation\SyliusRoute; #[SyliusRoute( name: 'app_book_update', path: '/books/{id}/edit', methods: ['GET', 'PUT'], controller: 'app.controller.book::updateAction', criteria: [ 'title' => '$title', ], )] ``` -------------------------------- ### Configure Talk Grid Fields and Actions (PHP) Source: https://stack.sylius.com/cookbook/admin_panel/grids Defines the 'app_talk' grid for the Talk resource. It configures visible fields like 'title' and 'startsAt', and sets up main, item, and bulk actions including create, update, and delete. ```php withFields( StringField::create('title') ->setLabel('Title') ->setSortable(true), DateTimeField::create('startsAt') ->setLabel('StartsAt'), ) ->addActionGroup( MainActionGroup::create( CreateAction::create(), ) ) ->addActionGroup( ItemActionGroup::create( // ShowAction::create(), UpdateAction::create(), DeleteAction::create() ) ) ->addActionGroup( BulkActionGroup::create( DeleteAction::create() ) ) ; } } ``` -------------------------------- ### Configure Multiple Doctrine Drivers and Resources (YAML) Source: https://stack.sylius.com/resource/index/index/configuration This configuration demonstrates setting up multiple Doctrine drivers (ORM and PHPCR-ODM) and defining resources for both. It includes configurations for 'app.book' using ORM and 'app.article' using PHPCR-ODM. ```yaml sylius_resource: drivers: - doctrine/orm - doctrine/phpcr-odm resources: app.book: classes: model: App\Entity\Book app.article: driver: doctrine/phpcr-odm classes: model: App\Document\ArticleDocument ``` -------------------------------- ### Register FormType as a Service in YAML Source: https://stack.sylius.com/resource/index/index/forms Registers a custom FormType class as a service in Symfony's configuration. This is typically needed when extending AbstractResourceType or when the form has custom constructor dependencies. This is a YAML example. ```yaml app.book.form.type: class: App\Form\Type\BookType tags: - { name: form.type } arguments: ['%app.model.book.class%', '%app.book.form.type.validation_groups%'] ``` -------------------------------- ### Define and Configure Custom Resource Factory Source: https://stack.sylius.com/resource/index/resource_factories Shows how to implement a custom factory by implementing FactoryInterface and registering it in the Symfony service container to decorate the default factory. ```php declare(strict_types=1); namespace App\Factory; use App\Entity\Book; use Sylius\Resource\Factory\FactoryInterface; final class BookFactory implements FactoryInterface { public function createNew(): Book { $book = new Book(); $book->setCreatedAt(new \DateTimeImmutable()); return $book; } } ``` ```yaml services: App\Factory\BookFactory: decorates: 'app.factory.book' ``` -------------------------------- ### Configure Custom Create Customer Processor (PHP) Source: https://stack.sylius.com/resource/index/processors This PHP code configures a custom processor, `CreateCustomerProcessor`, for the 'create' operation of a Customer resource. It uses attribute-based routing with `#[AsResource]` and specifies the custom processor class for the `Create` operation. ```php namespace App\Entity\Customer; use App\Sylius\State\Processor\CreateCustomerProcessor; use Sylius\Resource\Metadata\AsResource; use Sylius\Resource\Metadata\Create; use Sylius\Resource\Model\ResourceInterface; #[AsResource( operations: [ new Create( processor: CreateCustomerProcessor::class, ), ], ) final class BoardGameResource implements ResourceInterface ``` -------------------------------- ### Override Update Criteria in Sylius Routes Source: https://stack.sylius.com/resource/index/index/update_resource Customize the criteria used to find a resource during an update operation. This example shows how to use a route parameter 'title' to identify the book instead of the default 'id'. ```yaml app_book_update: path: /books/{title}/edit methods: [GET, PUT] defaults: _controller: app.controller.book::updateAction _sylius: criteria: { title: $title } ``` -------------------------------- ### Custom Event Name for Update in Sylius Annotations Source: https://stack.sylius.com/resource/index/index/update_resource Define a custom event name for resource updates using PHP annotations. This example sets the event name to 'customer_update', enabling listeners for 'app.book.pre_customer_update' and 'app.book.post_customer_update'. ```php use Sylius\Resource\Annotation\SyliusRoute; #[SyliusRoute( name: 'app_book_customer_update', path: '/customer/book-update/{id}', methods: ['GET', 'PUT'], controller: 'app.controller.book::updateAction', event: 'customer_update', )] ``` -------------------------------- ### Use Callable as Factory Source: https://stack.sylius.com/resource/index/resource_factories Shows how to use a static method as a factory for a resource by passing a callable array to the factory attribute. ```php declare(strict_types=1); namespace AppFactory; use AppEntityBook; final class BookFactory { public static function create(): Book { return new Book(); } } ``` ```php declare(strict_types=1); namespace AppEntityBook; use AppFactoryBookFactory; use SyliusResourceMetadataAsResource; use SyliusResourceMetadataCreate; use SyliusResourceModelResourceInterface; #[AsResource( operations: [ new Create( factory: [BookFactory::class, 'create'], ), ], ) class Book implements ResourceInterface { } ``` -------------------------------- ### Configure Create Operation for Book Resource (External PHP File) Source: https://stack.sylius.com/resource/index/configure_your_operations This snippet shows how to configure the 'Create' operation for a Book resource using an external PHP configuration file. It defines the Book entity and its associated operations, including 'Create', within the Sylius resource metadata. ```php withClass(Book::class) ->withOperations( new Operations([ new Create(), ]) ) ; ``` -------------------------------- ### Configure a Hookable to Render a Twig Template Source: https://stack.sylius.com/twig-hooks/getting-started This YAML configuration defines a hookable named 'some_block' for the 'my_first_hook'. It specifies that the 'some_block.html.twig' template should be rendered when the hook is triggered. This is a basic setup for extending Twig templates. ```yaml sylius_twig_hooks: hooks: 'my_first_hook': some_block: template: 'some_block.html.twig' ``` -------------------------------- ### Configure Sylius Resource Routing Source: https://stack.sylius.com/resource/index/installation Sets up the routing for the Sylius Resource Bundle. This configuration utilizes a service loader to manage resource-related routes, enabling the bundle's routing capabilities within your Symfony application. ```yaml sylius_resource_routes: resource: 'sylius.symfony.routing.loader.resource' type: service ``` -------------------------------- ### Configure Custom Repository Method for Resources Source: https://stack.sylius.com/resource/index/index/show_resource Demonstrates how to specify a custom repository method in the resource configuration. This allows for complex queries or joins instead of the default findOneBy method. ```yaml app_book_show: path: /books/{author} methods: [GET] defaults: _controller: app.controller.book::showAction _sylius: repository: method: findOneNewestByAuthor arguments: [$author] ``` ```php use Sylius\Resource\Annotation\SyliusRoute; #[SyliusRoute( name: 'app_book_show', path: '/books/{author}', methods: ['GET'], controller: 'app.controller.book::showAction', repository: [ 'method' => 'findOneNewestByAuthor', 'arguments' => ['$author'], ], )] ``` -------------------------------- ### Autoprefixing Example: 'content' Hook Source: https://stack.sylius.com/twig-hooks/autoprefixing-feature Demonstrates how autoprefixing simplifies hook calls. When autoprefixing is enabled, calling {% hook 'content' %} within the 'index/content.html.twig' template, which is hooked into 'app.index', is equivalent to calling {% hook 'app.index.content' %}. ```twig {% hook 'app.index' %} {# index.html.twig is an entry template, so it is not an hookable #} ``` ```twig {% hook 'content' %} {# this template is an hookable, and is hooked into app.index #} {# # so {% hook 'content' %} this is a shorter form of {% hook 'app.index.content' %} # when autoprefixing is turned on #} ``` ```twig ```