How to add one image to an entity?
This guide demonstrates how to add a one-to-one image association to an entity in Sylius 2.x. We'll use the PaymentMethod entity as an example, but the same approach applies to any other entity.
Prerequisites
Your project uses Sylius 2.x
LiipImagineBundle is installed and configured
Writable
public/media/image/directoryDoctrine migrations are enabled
Step 1: Create the Image Entity
<?php
// src/Entity/Payment/PaymentMethodImage.php
namespace App\Entity\Payment;
use Doctrine\ORM\Mapping as ORM;
use Sylius\Component\Core\Model\Image;
#[ORM\Entity]
#[ORM\Table(name: 'sylius_payment_method_image')]
class PaymentMethodImage extends Image
{
#[ORM\OneToOne(inversedBy: 'image', targetEntity: PaymentMethod::class)]
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
protected $owner;
public function __construct()
{
$this->type = 'default';
}
}Step 2: Update the Owner Entity
Step 3: Create the Image Form Type
Step 4: Register the Form Type
Step 5: Configure the Image Resource
Step 6: Extend the Owner Form Type
Register the form extension:
Step 7: Handle Image Upload with a Subscriber
Step 8: Customize the Payment Method twig hooks
Inspect the payment method form, let's assume you want to add new field to general section.

To add the image field in the general section of the Payment Method form using Twig hooks:
Create the template at
templates/admin/payment_method/form/sections/general/image.html.twig:
Update the Twig hooks configuration for the given
sylius_admin.payment_method.create.content.form.sections.generalhook:
Find out more about twig hooks here.
Step 9: (Optional) Add Validation Constraints
Step 10: Generate and Run Migrations
Step 11: Result

The Payment method has now image field 🎉!
Last updated
Was this helpful?
