How to add multiple images to an entity?
This guide explains how to associate multiple images with a single entity in Sylius 2.x using a one-to-many relationship. We'll use the ShippingMethod entity as an example, but this applies to any entity.
Prerequisites
Sylius 2.x is installed
LiipImagineBundle is configured
Doctrine is configured with migrations
The media path (
public/media/image/) is writable
Step 1: Create the Image Entity
<?php
// src/Entity/Shipping/ShippingMethodImage.php
namespace App\Entity\Shipping;
use Sylius\Component\Core\Model\Image;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ORM\Table(name: 'app_shipping_method_image')]
class ShippingMethodImage extends Image
{
#[ORM\ManyToOne(
targetEntity: ShippingMethod::class,
inversedBy: 'images'
)]
#[ORM\JoinColumn(
name: 'owner_id',
referencedColumnName: 'id',
nullable: false,
onDelete: 'CASCADE'
)]
protected $owner = null;
}Step 2: Extend the Owner Entity
Step 3: Configure Resources
Step 4: Create the Image Form Type
Register the form type if necessary:
Step 5: Extend the Form for Shipping Method
Register the extension:
Step 6: Enable Image Upload via Listener
Step 7: (Optional) Add Validation Constraints
Step 8: Customize the Shipping Method twig hooks
Inspect the shipping method form, let's assume you want to add new new section Images that is between the general and configuration.

Configure hooks for your new images section
Create templates for your hooks
Step 9: Generate and Run Migrations
Step 10: Result

The Shipping method has now collection of images 🎉!
Last updated
Was this helpful?
