Hi,
I need to see if a category exists, I *MUST* (I know it's not the right way, but in this case I'm forced) use object manager and I only have the url_key. How can I do this in magento 2.2?
Many thanks
Solved! Go to Solution.
Hi @agiorgini,
Maybe you can try something like this (I've used a shell class for the PoC).
private $category;
public function __construct(
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
$name = null
) {
$this->category = $categoryFactory;
parent::__construct($name);
}
protected function configure()
{
$this->setName('test:category');
$this->setDescription('Your shell class description.');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$categories = $this->category->create()
->getCollection()
->addAttributeToFilter('url_key','your-category-url-to-search')
->addAttributeToSelect(['entity_id']);
$output->writeln($categories->getFirstItem()->getEntityId());
}
And the ouput was the category id.
Hi @agiorgini,
Maybe you can try something like this (I've used a shell class for the PoC).
private $category;
public function __construct(
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
$name = null
) {
$this->category = $categoryFactory;
parent::__construct($name);
}
protected function configure()
{
$this->setName('test:category');
$this->setDescription('Your shell class description.');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$categories = $this->category->create()
->getCollection()
->addAttributeToFilter('url_key','your-category-url-to-search')
->addAttributeToSelect(['entity_id']);
$output->writeln($categories->getFirstItem()->getEntityId());
}
And the ouput was the category id.
thanks a lot!