Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon OnContentAfterDelete usage example


OnContentAfterDelete usage example


Here is an example of how to use the onContentAfterDelete event in a Joomla content plugin to delete related data from a custom SQL table when an article is deleted:

Registering the Event in the Plugin XML File

In the plugin XML file, register the onContentAfterDelete event under the events section:

xml
<events>
  <event name="onContentAfterDelete" group="content" />
</events>

Implementing the Event Handler in the Plugin PHP File

In the plugin PHP file, create a function to handle the onContentAfterDelete event:

php
public function onContentAfterDelete($context, $data)
{
  // Check if the event is for article deletion
  if ($context == 'com_content.article')
  {
    // Get the deleted article ID
    $articleId = $data->id;

    // Connect to the database
    $db = JFactory::getDbo();

    // Prepare the SQL query to delete related data
    $query = $db->getQuery(true)
      ->delete($db->quoteName('#__my_custom_table'))
      ->where($db->quoteName('article_id') . ' = ' . $articleId);

    // Execute the query to delete the related data
    $db->setQuery($query)->execute();
  }

  // Return true to allow deletion to proceed
  return true;
}

This code does the following:

1. Checks if the event context matches article deletion (com_content.article)
2. Retrieves the deleted article ID from the $data object
3. Connects to the database using JFactory::getDbo()
4. Prepares a SQL query to delete the related data from the custom table using the article ID
5. Executes the query to delete the related data
6. Returns true to allow the article deletion to proceed

When an article is deleted, this plugin will automatically delete any related data from the custom SQL table #__my_custom_table based on the deleted article's ID[1][2][5].

Citations:
[1] https://docs.joomla.org/Plugin/Events/Content
[2] https://docs.joomla.org/J3.x:Creating_a_content_plugin/en
[3] https://github.com/joomla/joomla-cms-examples/blob/master/plugins/content/example/example.php
[4] https://www.joomlatools.com/extensions/logman/developer/plugins/joomla-framework
[5] https://joomla.stackexchange.com/questions/23398/delete-row-from-custom-made-sql-when-deleting-article-in-joomla