How to add a custom model?

Extending Sylius with New Entities

In some cases, you may need to add custom models to extend Sylius to meet unique business requirements. Here, we’ll walk through the process of adding a Supplier entity, which could be useful for managing suppliers in your shop.

How to add a custom Entity to Sylius?

1. Define Your Requirements

For the Supplier entity, we’ll need three fields:

  • name: The supplier’s name

  • description: A description of the supplier

  • enabled: A flag indicating if the supplier is active

2. Generate the Entity

To simplify the entity generation, we can use Symfony’s SymfonyMakerBundle.

Run the following command to create the entity:

php bin/console make:entity

The generator will prompt you for the entity name and fields. Complete these fields to match your requirements.

If you encounter an error during entity generation, consider using the "force annotation fix" option in the Maker Bundle.

3. Update the Database with Migrations

Assuming your database is up-to-date, create a migration for the new entity:

Then, apply the migration to update your database schema:

4. Implement the ResourceInterface

To make your new entity compatible with Sylius resources, implement the ResourceInterface in your Supplier class.

In src/Entity/Supplier.php:

5. Extend the Repository from EntityRepository

In the generated repository file, extend EntityRepository to leverage Doctrine’s repository functionality, and remove any unnecessary constructors.

In src/Repository/SupplierRepository.php:

6. Register the Supplier Entity as a Sylius Resource

Create (or update) a sylius_resource.yaml file to register your new entity as a Sylius resource.

In config/packages/sylius_resource.yaml:

Verify the registration by running:

The output should display information related to the Supplier entity:

7. Configure a Grid for Supplier Management

To enable easy management of suppliers in the admin panel, configure a grid for the Supplier entity.

In config/packages/_sylius.yaml:

8. Define Routing for Supplier Administration

Define routes for managing the Supplier entity in the admin panel.

In config/routes.yaml:

9. Add Supplier to the Admin Menu

Add links to access the new Supplier entity management in the admin menu. See how to add items to the admin menu here.

10. Add translations

Add two entries to cover both the singular and plural translations of a new resource:

11. Check the Admin Panel

Navigate to https://localhost:8000/admin/suppliers/ to view and manage the Supplier entity in the Sylius admin panel.

Learn More

Last updated

Was this helpful?