We understand Taxons in Sylius as you would normally define categories. Sylius gives you a possibility to categorize your products in a very flexible way, which is one of the most vital functionalities of the modern e-commerce systems. The Taxons system in Sylius works in a hierarchical way. Let’s see exemplary categories trees:

 |\__ Clothes
 |         \_ T-Shirts
 |          \_ Shirts
 |           \_ Dresses
 |            \_ Shoes
 \__ Books
         \_ Fantasy
          \_ Romance
           \_ Adventure
            \_ Other

 \_ Male
  \_ Female

How to create a Taxon?

As always with Sylius resources, to create a new object you need a factory. If you want to create a single, not nested category:

/** @var FactoryInterface $taxonFactory */
$taxonFactory = $this->get('sylius.factory.taxon');

/** @var TaxonInterface $taxon */
$taxon = $taxonFactory->createNew();


But if you want to have a tree of categories, create another taxon and add it as a child to the previously created one.

/** @var TaxonInterface $childTaxon */
$childTaxon = $taxonFactory->createNew();



Finally the parent taxon has to be added to the system using a repository, all its child taxons will be added with it.

/** @var TaxonRepositoryInterface $taxonRepository */
$taxonRepository = $this->get('sylius.repository.taxon');


How to assign a Taxon to a Product?

In order to categorize products you will need to assign your taxons to them - via the addProductTaxon() method on Product.

/** @var ProductInterface $product */
$product = $this->container->get('sylius.factory.product')->createNew();

/** @var TaxonInterface $taxon */
$taxon = $this->container->get('sylius.factory.taxon')->createNew();

/** @var RepositoryInterface $taxonRepository */
$taxonRepository = $this->container->get('sylius.repository.taxon');

/** @var ProductTaxonInterface $productTaxon */
$productTaxon = $this->container->get('sylius.factory.product_taxon')->createNew();


/** @var EntityManagerInterface $productManager */
$productManager = $this->container->get('sylius.manager.product');


What is the mainTaxon of a Product?

The product entity in Sylius core has a field mainTaxon. This field is used, for instance, for breadcrumbs generation. But you can also use it for your own logic, like for instance links generation.

To set it on your product you need to use the setMainTaxon() method.