현재 영역에 대한 삭제 작업이 금지되어 있습니다.
-
12-12-2019 - |
문제
sku를 통해 단순 제품에 대한 삭제 작업 명령을 생성하고 싶습니다.다음과 같은 오류가 발생합니다. 관리 영역을 설정하는 방법은 무엇입니까?
[Magento\Framework\Exception\LocalizedException]
현재 영역에 대한 삭제 작업이 금지되어 있습니다.
<?php
namespace Sivakumar\Sample\Console;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;
class DeleteSimpleProduct extends Command
{
protected $_product;
public function __construct(\Magento\Catalog\Model\Product $_product)
{
$this->_product =$_product;
parent::__construct();
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName('delete_simple_product')
->setDescription('Delete Simple Product')
->setDefinition($this->getOptionsList());
parent::configure();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$errors = $this->validate($input);
if ($errors) {
throw new \InvalidArgumentException(implode("\n", $errors));
}
$product_id = $this->_product->getIdBySku($input->getOption('sku'));
$product=$this->_product->load($product_id);
$product->delete();
$output->writeln('<info>product deleted ' . $input->getOption('sku') . '</info>');
}
public function getOptionsList()
{
return [
new InputOption('sku', null, InputOption::VALUE_REQUIRED, 'SKU'),
];
}
public function validate(InputInterface $input)
{
$errors = [];
$required =['sku',];
foreach ($required as $key) {
if (!$input->getOption($key)) {
$errors[] = 'Missing option ' . $key;
}
}
return $errors;
}
}
di.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Console\CommandList">
<arguments>
<argument name="commands" xsi:type="array">
<item name="delete_simple_product" xsi:type="object">Sivakumar\Sample\Console\DeleteSimpleProduct</item>
</argument>
</arguments>
</type>
</config>
해결책
다음을 사용해야 한다는 Max의 의견에 동의합니다. ProductRepositoryInterface::deleteById($sku)
, 하지만 삭제 권한을 얻으려면 추가 변경도 수행해야 합니다.
관리 영역에서는 다음 구성을 생성하여 이를 처리합니다. app/code/Magento/Backend/etc/adminhtml/di.xml
<preference for="Magento\Framework\Model\ActionValidator\RemoveAction" type="Magento\Framework\Model\ActionValidator\RemoveAction\Allowed" />
그만큼 Magento\Framework\Model\ActionValidator\RemoveAction\Allowed
클래스는 단순히 반환하여 권한 확인을 방지합니다. true
에서 isAllowed
방법.
위와 같이 di.xml을 변경하지 않으면 Magento\Framework\Model\ActionValidator\RemoveAction
클래스가 사용되므로 삭제 요청이 실패하게 됩니다. $this->registry->registry('isSecureArea')
true로 설정되어 있습니다.
일부 콘솔 명령을 생성하려고 하는 것 같은데 저는 아직 이에 대해 잘 알지 못합니다. 따라서 지금으로서는 삭제 작업을 허용하도록 레지스트리를 설정하고 나중에 더 깔끔한 솔루션이 발견되면 리팩터링하는 것이 가장 좋습니다.
$this->registry->register('isSecureArea', true)
다른 팁
최근 빈 카테고리를 삭제하는 콘솔 명령을 작성하는 동안 이 문제가 발생했습니다.
다른 답변에서 말했듯이 등록해야합니다 'isSecureArea'
사실로.
콘솔 명령에서 이 작업을 수행하려면 Magento\Framework egistry 클래스를 생성자에 전달해야 합니다.
내 경우에는 다음과 같이 했습니다.
public function __construct(CategoryManagementInterface $categoryManagementInterface, CategoryRepositoryInterface $categoryRepositoryInterface, Registry $registry)
{
$this->_categoryRepository = $categoryRepositoryInterface;
$this->_categoryManagement = $categoryManagementInterface;
$registry->register('isSecureArea', true);
parent::__construct();
}
그리고 그 다음에는 execute
실제 삭제를 수행하기 위해 저장소를 사용한 방법은 다음과 같습니다.
$this->_categoryRepository->deleteByIdentifier($category->getId());
스크립트를 사용하는 경우 아래 그림과 같이 레지스트리 개체를 만드십시오.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->get('Magento\Framework\Registry')->register('isSecureArea', true);
.
을 사용할 수 있습니다. 크리스 o'toole의 답변을 확장합니다.너무 여러 명령에서 실제로 명령에서 범주를 삭제해야합니다.처음에는
가 있습니다$oRegistry->register('isSecureArea', true);
.
하나의 명령에서 가 잘 작동했지만 (생성자에서) 여러 명령을 넣으면 컴파일하는 동안이 오류가 발생했습니다.
레지스트리 키 "issecurearea"가 이미 존재합니다
먼저 레지스트리 키의 존재 여부를 확인합니다
if($oRegistry->registry('isSecureArea') === null) {
$oRegistry->register('isSecureArea', true);
}
.
나는 생성자에 그것을 넣는 것이 나쁜 부분이 있는지 확실하지 않지만 그 이유는 오류가 발생하는 이유임을 가정합니다.또는 명령의 'execute
메소드에서 첫 번째 스 니펫을 실행하여 제거 할 수 있어야합니다.다시 말하지만, 나는 가장 좋은 방법으로 간주되는 것이 확실하지 않습니다 ...
제품을 사용하는 작업은 저장소를 사용해야합니다.
Magento\Catalog\Model\ProductRepository
. isSecureArea를 설정하는 대신 유형을 재정의하여 단일 유형의 객체를 제거하도록 허용할 수도 있습니다. RemoveAction
당신의 주장 di.xml
이와 같이:
<type name="Magento\Framework\Model\ActionValidator\RemoveAction">
<arguments>
<argument name="protectedModels" xsi:type="array">
<item name="salesOrder" xsi:type="null" /> <!--allow orders to be removed from front area-->
</argument>
</arguments>
</type>