0

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?

aa-Ahmed-aa
  • 323
  • 4
  • 13
  • how are you calling this code? this seems as a job for Symfony's Form validation – Ludo Oct 02 '19 at 16:31
  • I just need to add product with basic data (name, price, stock) then this code should(will) go in the service passing the dataParams – aa-Ahmed-aa Oct 02 '19 at 17:57
  • to me it just seems as a job for Validator https://symfony.com/doc/current/validation.html – Ludo Oct 03 '19 at 05:18

1 Answers1

0

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
}
Ludo
  • 474
  • 2
  • 8