Reputation: 113
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?
Upvotes: 3
Views: 1711
Reputation: 1361
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;
}
Upvotes: 7
Reputation: 905
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.
Upvotes: 1