# Remove a custom field via a Plugin

**URL:** https://forum.mautic.org/t/remove-a-custom-field-via-a-plugin/32749
**Category:** Product Support
**Created:** [July 14, 2024, 1:49am UTC](https://forum.mautic.org/t/remove-a-custom-field-via-a-plugin/32749 "2024-07-14T01:49:51Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![rcarabelli](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.mautic.org/rcarabelli/32/6807_2.png) [@rcarabelli](https://forum.mautic.org/u/rcarabelli)
#### Post date: [July 14, 2024, 1:49am UTC](https://forum.mautic.org/t/remove-a-custom-field-via-a-plugin/32749/1 "2024-07-14T01:49:51Z")

</div>

**Your software**  
My Mautic version is: 5.1  
My PHP version is:8.2  
My Database type and version is: MySQL 8

**Your problem**  
My problem is: I am trying to delete a custom field after a plugin upgrade but it seems not possible with the documentation (that I am probably understanding wrong).  
So, to put it in context.  
Version 1.1.0 of the plugin creates many custom fields  
Version 1.1.1 should remove some of those fields and add others

I can create all I want on plugin update or install but can’t remove any on a plugin update.  
This is the code:

```auto
> <?php
> 
> namespace MauticPlugin\MauticZenderBundle\EventListener;
> 
> use Mautic\PluginBundle\Event\PluginInstallEvent;
> use Mautic\PluginBundle\Event\PluginUpdateEvent;
> use Mautic\PluginBundle\PluginEvents;
> use Symfony\Component\EventDispatcher\EventSubscriberInterface;
> use Doctrine\ORM\EntityManagerInterface;
> use Psr\Log\LoggerInterface;
> 
> class PluginInstallUpdateEventListener implements EventSubscriberInterface
> {
> private $entityManager;
> private $logger;
> 
> public function __construct(EntityManagerInterface $entityManager, LoggerInterface $logger)
> {
> $this->entityManager = $entityManager;
> $this->logger = $logger;
> }
> 
> public static function getSubscribedEvents()
> {
> return [
> PluginEvents::ON_PLUGIN_INSTALL => ['onPluginInstallOrUpdate', 0],
> PluginEvents::ON_PLUGIN_UPDATE => ['onPluginInstallOrUpdate', 0],
> ];
> }
> 
> public function onPluginInstallOrUpdate($event)
> {
> if ($event->getPlugin()->getName() === 'Zender') {
> $this->logger->info('Zender plugin installation/update detected.');
> 
> $this->createOrUpdateField('id_whatsapp_in_zender', 'ID WhatsApp in Zender');
> $this->createOrUpdateField('pruebas_de_zender_mautic', 'Pruebas de Zender Mautic');
> $this->createOrUpdateField('nuevo_campo', 'Nuevo Campo');
> 
> $this->createControlTable();
> 
> if ($event instanceof PluginUpdateEvent) {
> $this->removeFields();
> }
> }
> }
> 
> private function createOrUpdateField($alias, $name)
> {
> $existingField = $this->entityManager->getRepository(\Mautic\LeadBundle\Entity\LeadField::class)->findOneBy(['alias' => $alias]);
> if (!$existingField) {
> $field = new \Mautic\LeadBundle\Entity\LeadField();
> $field->setName($name);
> $field->setAlias($alias);
> $field->setType('text');
> $field->setGroup('core');
> $field->setObject('lead');
> $field->setIsPublished(true);
> 
> $this->entityManager->persist($field);
> $this->entityManager->flush();
> $this->logger->info("Custom field '{$name}' created.");
> } else {
> $this->logger->info("Custom field '{$name}' already exists.");
> }
> }
> 
> private function createControlTable()
> {
> $this->logger->info('Starting control table creation process.');
> 
> try {
> $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager);
> $this->logger->info('SchemaTool instantiated.');
> 
> $classes = [$this->entityManager->getClassMetadata(\MauticPlugin\MauticZenderBundle\Entity\ApiZenderControlLog::class)];
> $this->logger->info('Class metadata loaded.', ['classes' => $classes]);
> 
> $this->logger->info('Beginning schema update.');
> $schemaTool->updateSchema($classes, true);
> $this->logger->info('Control table "api_zender_control_log" created successfully.');
> } catch (\Exception $e) {
> $this->logger->error('Error creating control table "api_zender_control_log": ' . $e->getMessage());
> }
> }
> 
> private function removeFields()
> {
> $this->logger->info('Removing custom fields "nuevo_campo" and "pruebas_de_zender_mautic".');
>         
> try {
> $connection = $this->entityManager->getConnection();
> $connection->executeQuery('ALTER TABLE leads DROP COLUMN nuevo_campo');
> $connection->executeQuery('ALTER TABLE leads DROP COLUMN pruebas_de_zender_mautic');
> $this->logger->info('Custom fields "nuevo_campo" and "pruebas_de_zender_mautic" removed successfully.');
> } catch (\Exception $e) {
> $this->logger->error('Error removing custom fields: ' . $e->getMessage());
> }
> }
> }

```

These errors are showing in the log: No errors, it just won’t remove, but will add all I want

Steps I have tried to fix the problem:

---

<div class="post-metadata">

### Author: ![rcarabelli](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.mautic.org/rcarabelli/32/6807_2.png) [@rcarabelli](https://forum.mautic.org/u/rcarabelli)
#### Post date: [July 14, 2024, 2:02am UTC](https://forum.mautic.org/t/remove-a-custom-field-via-a-plugin/32749/2 "2024-07-14T02:02:09Z")

</div>

> [@rcarabelli](#):
>
> `removeFields`

Was my mistake, was removing the DB table columns but not the custom fields.

This is the correct example code for removing a complete field via a plugin update

```auto
    private function removeFields()
    {
        $this->logger->info('Removing custom fields "nuevo_campo" and "pruebas_de_zender_mautic".');

        try {
            $fieldAliases = ['nuevo_campo', 'pruebas_de_zender_mautic'];
            foreach ($fieldAliases as $alias) {
                $field = $this->fieldModel->getRepository()->findOneByAlias($alias);
                if ($field) {
                    $this->fieldModel->deleteEntity($field);
                    $this->logger->info("Custom field '{$alias}' removed successfully.");
                }
            }
        } catch (\Exception $e) {
            $this->logger->error('Error removing custom fields: ' . $e->getMessage());
        }
    }

```

> Blockquote

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/flex020/uploads/mautic/original/1X/43c63600fe51440378769136903f1fa2a9a34102.png) [@system](https://forum.mautic.org/u/system)
#### Post date: [July 15, 2024, 2:02pm UTC](https://forum.mautic.org/t/remove-a-custom-field-via-a-plugin/32749/3 "2024-07-15T14:02:43Z")

</div>

This topic was automatically closed 36 hours after the last reply. New replies are no longer allowed.
