Shopware 6 - 在插件卸载时删除自定义字段

Shopware 6 - Delete custom fields on plugin uninstall

我创建了一个自定义服务,它在插件安装期间在客户表单中创建自定义字段。激活插件时,服务正常运行并执行所需功能。

public function activate(ActivateContext $context): void
{
  ../
  $customFieldSetService = $this->container->get('custom.service');
  $customFieldSetService->extendCustomerFields();
  /..
}

卸载插件时,我收到错误消息:您请求了一个不存在的服务“custom.service”。

public function uninstall(UninstallContext $context): void
{
 ../
  $customFieldSetService = $this->container->get('custom.service');
  $customFieldSetService->deleteCustomerFields();
 /..
}

service.xml:

<service id="custom.service" class="MyPlugin\Service\CustomFieldSetService" public="true" />

如何在卸载函数中调用自己的服务?

您不能像卸载前那样调用它,您的插件已停用。一旦停用,该插件的所有服务都会从服务容器中删除并且无法调用。您可以直接在卸载方法中创建服务实例。我认为这是最好的解决方案。

让我快速向您展示我们如何做的一个例子。 我猜代码应该是不言自明的:)

public function uninstall(UninstallContext $uninstallContext): void
    {
        if ($uninstallContext->keepUserData()) {
            parent::uninstall($uninstallContext);

            return;
        }

        $this->removeCustomField($uninstallContext);

        parent::uninstall($uninstallContext);
    }

private function removeCustomField(UninstallContext $uninstallContext)
    {
        $customFieldSetRepository = $this->container->get('custom_field_set.repository');

        $fieldIds = $this->customFieldsExist($uninstallContext->getContext());

        if ($fieldIds) {
            $customFieldSetRepository->delete(array_values($fieldIds->getData()), $uninstallContext->getContext());
        }
    }

private function customFieldsExist(Context $context): ?IdSearchResult
    {
        $customFieldSetRepository = $this->container->get('custom_field_set.repository');

        $criteria = new Criteria();
        $criteria->addFilter(new EqualsAnyFilter('name', ['your_custom_fieldset']));

        $ids = $customFieldSetRepository->searchIds($criteria, $context);

        return $ids->getTotal() > 0 ? $ids : null;
    }