Zombie email records being created in database

This seems like a bug to me but I would also like to know if I am doing this correctly.

When I create a contact I have a “before_save” logic hook that checks for duplicate emails. If a contact is being input with an email that belongs to someone else then I will cancel the contact save and show the user an error. It looks something like this.

if ($emailCount >= 1) {

            SugarApplication::appendErrorMessage('Sorry, the email address <strong>' . $emailArray['email_address'] . '</strong> is already in the system <br>');

            SugarApplication::redirect("index.php?module=Contacts&action=EditView&record=" . "$bean->id");

        }

However, when saving a contact the email address is saved and inserted into the database before the “before_save” logic hook is hit. The record is insert into the email_addr_bean_rel table.

In the save() function in Person.php the saveEmail() function is called, inserting the email into the database with the bean id. However, if I cancel out of the save in my logic hook, that bean id is never created as a contact record, but the email record is already in the database.

This causes issues for me since there are email records in the database for contacts that don’t exist.

Am I doing this correctly?
Is this a bug that needs an issue on github?

Hey wiatrp,
Interesting, I also wouldn’t expect the email address to be saved in this situation

My suggestion would be, since Email addresses are saved alike relationships on another table, you could perhaps try the “before_relationship_add” hook, rather than the “before_save” hook?

If this fails, I’d agree with raising on github as an issue, it sounds like it would need further investigation!

As an aside, you could perhaps take a slightly different approach to this.
Maybe a custom save button, that fires off similar logic, and only continues onto saving if no duplicate emails are found?