简体   繁体   中英

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.

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".

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" />

How can I call my own service within the uninstall 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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