简体   繁体   English

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

[英]Shopware 6 - Delete custom fields on plugin uninstall

I have created a custom service which creates custom fields in the customer form during plugin installation.我创建了一个自定义服务,它在插件安装期间在客户表单中创建自定义字段。 When activating the plugin, the service runs correctly and performs the required function.激活插件时,服务正常运行并执行所需的 function。

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

When uninstalling the plugin, I get the error message: You have requested a non-existent service "custom.service".卸载插件时,我收到错误消息:您请求了一个不存在的服务“custom.service”。

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

service.xml:服务.xml:

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

How can I call my own service within the uninstall function?如何在卸载 function 中调用我自己的服务?

Let me quickly show you an example of how we're doing it.让我快速向您展示我们如何做到这一点的示例。 The code should be self-explaining i guess:)我猜代码应该是不言自明的:)

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;
    }

You can't call it as before uninstall your plugin is deactivated.你不能像之前卸载你的插件被停用一样调用它。 As soon as it has been deactivated, all services from that plugin are deleted from the service container and can't be called.一旦它被停用,来自该插件的所有服务都会从服务容器中删除并且无法调用。 You can create an instance of your service directly in uninstall method.您可以直接在卸载方法中创建服务实例。 I think it is the best solution.我认为这是最好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM