<p><strong><a href="https://craftcms.stackexchange.com/a/798/45">Brad's answer</a> is totally correct.</strong></p>

<p>As the question was posed by the original asker, Brad provided an example of an event listener which would be triggered when an entry is deleted. He also mentions the CASCADE DELETE capabilities of a Record.</p>

<p>In my opinion, the absolute best way to achieve what you're doing is by <strong>properly setting up your Record.</strong> In your <a href="http://buildwithcraft.com/docs/plugins/records#defining-relations" rel="nofollow noreferrer">defineRelations</a> method, you can create a proper relationship between your table and the main elements table...</p>

<pre><code>class MyPlugin_MyRecord extends BaseRecord
{

    // ...

    public function defineRelations()
    {
        return array(
            'element' =&gt; array(static::BELONGS_TO, 'ElementRecord', 'required' =&gt; true, 'onDelete' =&gt; static::CASCADE),
        );
    }

}
</code></pre>

CC BY-SA 3.0
2014-07-08T06:42:17.780Z
Also remember that a user might not want your data deleted when they delete the entry, so a database level cascade delete might not always be the best place to put the business rule. Using the event listener allows you to decide whether or not to delete the record.
Luke Holder
CC BY-SA 3.0
2014-07-08T06:44:38.053Z
For example what if the related record is a product that has orders against it? Deleting the entry might delete the product entry but you will still want to link to the historic product from order history. In that case I would pace a field on the record called 'deleted' as boolean. Anyways point is be careful with cascade delete logic on the db layer.
Luke Holder
CC BY-SA 3.0
2014-07-08T16:55:39.400Z
My plugin has two records both created when the entry my plugin's custom input type is associated with is saved. Both records use the entry's id as keys for their entries.  Record (A) has a one to one relationship to the entry id.  Record (B) has a one to many relationship with entry id.  I am unclear with the information above how to setup the relation so 'onDelete' works.
a-am
CC BY-SA 3.0
2014-07-08T17:14:54.407Z
It sounds like you'd just need to define that relationship in both of your records, nearly identical to the example code. Despite the fact that they are one-to-one VS one-to-many, I think they will both use `BELONGS_TO` because they are both the **child tables** of the main elements table. Check out this page on [Yii relationship terms...](http://www.yiiframework.com/wiki/181/relations-belongs_to-versus-has_one/)
Lindsey D
CC BY-SA 3.0
2014-07-08T17:19:00.760Z
I'm speculating a bit because I don't know exactly what your plugin does, but I'd say there's a good chance that you'd be better off relating your Records to **elements**, rather than directly to entries. Entries are a _type of_ element (as are assets, users, etc). This would allow your field type to be associated with any element type, not just limited to entries. _Disclaimer: I may be completely wrong here... You may have a valid reason for wanting to link your field type with entries exclusively._
Lindsey D
CC BY-SA 3.0
2014-07-08T22:03:25.813Z
Do I need to reinstall the plugin for the updated relations to take?
a-am
CC BY-SA 3.0
2014-07-08T22:04:36.780Z
Yes. The table (and its relationships) are created when the plugin is installed.
Lindsey D
CC BY-SA 3.0
2014-07-08T22:07:48.797Z
So to keep data intact I will need to setup a migration?
a-am
CC BY-SA 3.0
2014-07-08T22:09:28.470Z
Indeed... And migrations are a whole other ballgame! If you've got any migration issues, I'd suggest opening up a new SE question.
Lindsey D
CC BY-SA 3.0
2014-07-08T22:14:23.587Z
You are very welcome! :)
Lindsey D
CC BY-SA 3.0
2014-07-08T04:40:21.480Z
2014-07-08T04:40:21.480Z
2017-04-13T12:51:00.253Z
Lindsey D
<p>You can add something like this to your plugin's <code>init()</code> method:</p>

<pre><code>craft()-&gt;on('entries.onDeleteEntry', function(Event $event) {
    // Do your custom logic here.
    // Note that you can access the entry that was just deleted via $event-&gt;params['entry']
});
</code></pre>

<p>Or, better yet, from your custom table, make sure the foreign key that you've created on your entryId column back to the entries table has a CASCADE DELETE setup on it so that when Craft deletes the entry, it will cascade down and delete it from your table as well.</p>

CC BY-SA 3.0
2014-07-08T04:36:05.117Z
Is the CASCADE DELETE added to the defineRelations return array in the Record file?
a-am
CC BY-SA 3.0
2014-07-08T04:38:06.203Z
Yeah... check out craft/app/records for examples: 'element' => array(static::BELONGS_TO, 'ElementRecord', 'id', 'required' => true, 'onDelete' => static::CASCADE),
Brad Bell
CC BY-SA 3.0
2014-07-08T04:41:51.923Z
Or just see Lindsey's answer for an actual example. :)
Brad Bell
CC BY-SA 3.0
2014-07-08T04:45:20.097Z
Sorry, I felt compelled to include a more elaborate example (and note my opinion on which method was best). But Brad's answer is definitely the right one, because it lists **both ways** of achieving this goal... including the event listener technique, which was originally mentioned by @aran.
Lindsey D
CC BY-SA 3.0
2014-07-08T04:47:23.697Z
It's also worth noting that the event listener technique has some drawbacks... The example above is only listening for the deletion of an **entry**. And while that directly answers the original question, if your data were ever linked to an element other than an entry, that listener would be useless.
Lindsey D
CC BY-SA 3.0
2014-07-08T02:54:55.100Z
2014-07-08T02:54:55.100Z
Brad Bell
<p>When an entry is created with my plugin's field type, data is saved to a separate table with entries id for reference. I need to delete that data if the entry that is associated with the data is deleted.  How and where should I listen for entry delete event to execute a method to delete this separate data?</p>

<plugin-development><entries><plugins>
Where and how should you listen for entry delete in plugin?
# Where and how should you listen for entry delete in plugin?

(Asked by: username_0 on 2014-07-08)

When an entry is created with my plugin's field type, data is saved to a separate table with entries id for reference. I need to delete that data if the entry that is associated with the data is deleted. How and where should I listen for entry delete event to execute a method to delete this separate data?

**Tags:** plugin-development, entries, plugins

---

## 2 answers

### Answer by username_3 on 2014-07-08. Score: 4 | Accepted answer

You can add something like this to your plugin's init() method:
craft()->on('entries.onDeleteEntry', function(Event $event) {
    // Do your custom logic here.
    // Note that you can access the entry that was just deleted via $event->params['entry']
});

Or, better yet, from your custom table, make sure the foreign key that you've created on your entryId column back to the entries table has a CASCADE DELETE setup on it so that when Craft deletes the entry, it will cascade down and delete it from your table as well.

> **Comments:**
> **username_0**: Is the CASCADE DELETE added to the defineRelations return array in the Record file?  
> **username_3**: Yeah... check out craft/app/records for examples: 'element' => array(static::BELONGS_TO, 'ElementRecord', 'id', 'required' => true, 'onDelete' => static::CASCADE),  
> **username_3**: Or just see Lindsey's answer for an actual example. :)  
> **username_1**: Sorry, I felt compelled to include a more elaborate example (and note my opinion on which method was best). But Brad's answer is definitely the right one, because it lists **both ways** of achieving this goal... including the event listener technique, which was originally mentioned by @aran.  
> **username_1**: It's also worth noting that the event listener technique has some drawbacks... The example above is only listening for the deletion of an **entry**. And while that directly answers the original question, if your data were ever linked to an element other than an entry, that listener would be useless.  

---

### Answer by username_1 on 2014-07-08. Score: 1

Brad's answer is totally correct.
As the question was posed by the original asker, Brad provided an example of an event listener which would be triggered when an entry is deleted. He also mentions the CASCADE DELETE capabilities of a Record.
In my opinion, the absolute best way to achieve what you're doing is by properly setting up your Record. In your defineRelations method, you can create a proper relationship between your table and the main elements table...
class MyPlugin_MyRecord extends BaseRecord
{

    // ...

    public function defineRelations()
    {
        return array(
            'element' => array(static::BELONGS_TO, 'ElementRecord', 'required' => true, 'onDelete' => static::CASCADE),
        );
    }

}

> **Comments:**
> **username_2**: Also remember that a user might not want your data deleted when they delete the entry, so a database level cascade delete might not always be the best place to put the business rule. Using the event listener allows you to decide whether or not to delete the record.  
> **username_2**: For example what if the related record is a product that has orders against it? Deleting the entry might delete the product entry but you will still want to link to the historic product from order history. In that case I would pace a field on the record called 'deleted' as boolean. Anyways point is be careful with cascade delete logic on the db layer.  
> **username_0**: My plugin has two records both created when the entry my plugin's custom input type is associated with is saved. Both records use the entry's id as keys for their entries.  Record (A) has a one to one relationship to the entry id.  Record (B) has a one to many relationship with entry id.  I am unclear with the information above how to setup the relation so 'onDelete' works.  
> **username_1**: It sounds like you'd just need to define that relationship in both of your records, nearly identical to the example code. Despite the fact that they are one-to-one VS one-to-many, I think they will both use `BELONGS_TO` because they are both the **child tables** of the main elements table. Check out this page on [Yii relationship terms...](http://www.yiiframework.com/wiki/181/relations-belongs_to-versus-has_one/)  
> **username_1**: I'm speculating a bit because I don't know exactly what your plugin does, but I'd say there's a good chance that you'd be better off relating your Records to **elements**, rather than directly to entries. Entries are a _type of_ element (as are assets, users, etc). This would allow your field type to be associated with any element type, not just limited to entries. _Disclaimer: I may be completely wrong here... You may have a valid reason for wanting to link your field type with entries exclusively._  
> **username_0**: Do I need to reinstall the plugin for the updated relations to take?  
> **username_1**: Yes. The table (and its relationships) are created when the plugin is installed.  
> **username_0**: So to keep data intact I will need to setup a migration?  
> **username_1**: Indeed... And migrations are a whole other ballgame! If you've got any migration issues, I'd suggest opening up a new SE question.  
> **username_1**: You are very welcome! :)  

---

