I try to make some pages with 404 status and ouptut 404 page but with current url.
I do it in observer.
This is my events.xml
<event name="catalog_category_load_after">
<observer name="empty_to_404" instance="ProviderModuleObserverCatalogEmptyTo404" shared="false"/>
</event>
This is a class of Observer
/** @var ResponseFactory */
protected $responseFactory;
/** @var UrlInterface */
protected $url;
protected $registry;
public function __construct(
ResponseFactory $responseFactory,
UrlInterface $url,
Registry $registry,
Http $http
) {
$this->http = $http;
$this->responseFactory = $responseFactory;
$this->url = $url;
$this->registry = $registry;
}
/**
* @param Observer $observer
* @return void
*/
public function execute(Observer $observer)
{
/** @var MagentoCatalogModelCategory */
$category = $observer->getData('category');
$fullActionName = $this->http->getFullActionName();
$productsCount = $category->getProductCount();
if ($fullActionName == 'catalog_category_view' && !$productsCount) {
// Do page 404 status
$redirectionUrl = $this->url->getUrl('cms/noroute');
/** @var ResponseHttp $response */
$response = $this->responseFactory->create();
$response->setRedirect($redirectionUrl, 404)->sendResponse();
return $this;
}
}
I’v got a redirect to 404 page and to 404 url.
What is the right way to do it? Also, what event name will be prefer?