+ Start a Discussion
Cesar Ramirez Vasquez005391619375684564Cesar Ramirez Vasquez005391619375684564 

Is possible to create a trigger that checks if a Master-Detail Relationship exist, and if it doesn't exist create a new one ?

Hi guys ! Lately im having some seriuos troubles inserting Factura__c records because they have a master-detail relationship with accounts (called Empresa_Cliente__c) and sometimes the account doesnt exist and the insert fail. So i was building a trigger that checks if the account exist and if it dont create a new one with the field Codigo_NAF__c of Factura__c object. The problem is that trigger isnt working, it doesnt fire; do you guys now where maybe the issue ? Is that possible ?
Account has a custome field called Codigo_NAF__c just for info and the trigger is already active; but when i create a new record of type Factura__c and try to enter an Account that doesnt exist the trigger doesnt fire and i just receive the validation error that says: Please insert a valid account (something like that).

This is my trigger:
trigger insertAcc on Factura__c (before insert) {

System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__c) ; 
List<Account> a = [select name, Codigo_NAF__c from account where Codigo_NAF__c = :trigger.New[0].Empresa_Cliente__c];
System.debug(Logginglevel.ERROR , ' ::::::: List :::::::::::::' + a) ; 
if (a == null){
Account acc = new Account();
acc.Name = trigger.New[0].Empresa_Cliente__c;
acc.Codigo_NAF__c = trigger.New[0].Empresa_Cliente__c;

insert (acc);


System.debug(Logginglevel.ERROR , ' ::::::: acc :::::::::::::' + acc) ;
}

}

I hope someone can help me ! Thanks in advance !

 

pradeep naredlapradeep naredla
Hi ceser,
         There is no problem with ur trigger but u have to keep in mind that If a trigger is ececuted and a account record is inserted but the account is not yet commited to the database with out commiting how can u retrive the account from the database thats why ur getting that error.

Regards,
pradeep.
kiranmutturukiranmutturu
what you are getting here
 System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__c) ;
pradeep naredlapradeep naredla
Hi ceser,
       I have written this code and its working properly for me but while entering the record we have to enter the account record otherwise it will through validation error as required field missing.

regards,
pradeep.
trigger first1 on check__c (before insert)
 {
 set<id> set1= new set<id>();
 set<id> set2= new set<id>();
 for(check__c c: trigger.new)
 {
 if(c.account__c==null)
 {
account acc= new account();
acc.name='pradeep';
insert acc;
}
 list<account> acc1= [select id,name from account where name='pradeep' ];
c.account__c =acc1[0].id;
}
}

Cesar Ramirez Vasquez005391619375684564Cesar Ramirez Vasquez005391619375684564
Hi pradeep thank you for your answer i will try; but the main issue im having is that when i hit save record, sales force validation comes out and doesnt let fire the trigger; im really stuck with this one.
@kiran_mutturu that exactly the problem the trigger is not even fired so i cant see the debug logs. The problem is that sales force checks if the master relationship exist before commiting the action so trigger is not even fired; i need to bypass the validation or do something more clever haha i hope you guys can help.
pradeep naredlapradeep naredla
hi ceser,
        Thats what i said the validation will first execute in the order of execution so if u want to overcome that may be it is not possible.

Regards,
pradeep.
Cesar Ramirez Vasquez005391619375684564Cesar Ramirez Vasquez005391619375684564
Oh i didnt understand before, well thanks for your reply i will keep trying, if i find a solution, i will post it, if someone have an idea please let me know !
Thanks
kiranmutturukiranmutturu
Oops...
How I missed that.... lol..

Yeah you can't get it done until you filled some value in the Master field.. If that is the case then there is no point of this trigger.  I hope this is a deadlock case...
kiranmutturukiranmutturu
I hope in your case u can convert this Master detail field in to look up. Your trigger will always check whether you have a value in the field or not , if not you will create one and assign the same. So there will no case where there is record with out the Parent. Here some more cases things that we need to keep in mind are when you are deleting tha parent we need to write a trigger on the parent object to delte the associated records and also when ever you are creating a child record we should assign the owner from parent record. If we made these changes then it will work as it is Master detail and supports your business case....This is just my thought may be you may have lots of dependencies or may not be possible to change the realatioship type.
Cesar Ramirez Vasquez005391619375684564Cesar Ramirez Vasquez005391619375684564
@kiran_mutturu The field of the master relationship is always filled but sometimes it dont exist in the account object ,i want to create a new account when that happens with the value that that the user fill.
Thank you for your answer !
Carolina Ruiz MedinaCarolina Ruiz Medina
Hola Cesar, 
De nuevo yo :) 

Si el campo es master-detail no puedes dejarlo en blanco, con lo que nunca pasaras esa validacion. Por codigo or por UI debes rellenarlo. 

Por UI nunca se lanzara el trigger porque nunca llegaras al trigger, la propia validacion de Salesforce para campos Master - Detail the obliga a poner un valor y que ese valor exista.

Por codigo para crear un registro de tipo factura debes ponerle un Account ( Empresa_Cliente) que exista sino la propia validacion de Salesforce no te deja seguir.

No se lanza ningun trigger en ninguno de los casos ya que no estas cumpliendo los requisitos para llegar a ese trigger.

Master - detail es un tipo de campo : Maestro - detalle , padre- hijo, Un hijo no puede existir sin un padre, y este padre debe existir antes que el hijo. 

Si lo que tu quieres es que por codigo se cree un Account si no se cumple el criterio, y que luego esta companñia se le asigne a tu objeto ( un poco lioso pero posible, ten cuidado con los limites ) debes de usar un Lookup field.

Posiblemente algo que tambien te pueda ayudar antes de escribir codigo es mirar como funcionan los Workflows y en caso quizas un workflow trigger. 
Aunque si al final tras definir las necesidades de tu negocio/ bussines requirements/ tener todas las validaciones en un mismo sitio..  sigues necesitando un trigger ve a por ello.

Piensa siempre que la plataforma te da muchas cosas antes de que necesites escibir codigo, y aun asi si decides escribir codigo ten en cuenta las guias de Apex y los limites que puedes encontrar.

Espero que te ayude :) 

Salu2,
Carolina.