aa-Ahmed-aa
aa-Ahmed-aa

Reputation: 382

Sylius - return validation messages on product save

when I use the sylius.factory.product here https://docs.sylius.com/en/1.6/book/products/products.html

Adding Product

/** @var ProductFactoryInterface $productFactory **/
$productFactory = $this->get('sylius.factory.product');

/** @var ProductInterface $product */
$product = $productFactory->createNew();
$product->setName('T-Shirt');
$product->setCode('00001');
$product->setSlug('t-shirt');

/** @var RepositoryInterface $productRepository */
$productRepository = $this->get('sylius.repository.product');

$productRepository->add($product);

and set the value of Code (has unique identifier) to a value already exists I get an exception I want to get the validation message "Product code must be unique." message provided by sylius
How to get this done?

Upvotes: 0

Views: 403

Answers (1)

Ludo
Ludo

Reputation: 512

Use Symfony Validation for this. Set the constraint on your entity:

# config/validator/validation.yaml
App\Entity\Product:
    constraints:
        - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
            fields: [code]
            message: 'Product code must be unique'

And then call validate() on Validator service:

public function productMethod(
    ProductFactoryInterface $productFactory, 
    ValidatorInterface $validator
) {
    /** @var ProductFactoryInterface $productFactory **/
    $productFactory = $this->get('sylius.factory.product');

    /** @var ProductInterface $product */
    $product = $productFactory->createNew();
    $product->setName('T-Shirt');
    $product->setCode('00001');
    $product->setSlug('t-shirt');

    $errors = $validator->validate($product);

    if (count($errors) > 0) {
        $errorsString = (string) $errors;
        return $errorsString;
    }

    // ...do something else
}

Upvotes: 0

Related Questions