+ Start a Discussion
Apex code.ax1542Apex code.ax1542 

I am getting an error while saving a note .

I am getting an error while saving a note as i want to change the Title of the Note with Body content upto 77 alphabhets.

 

Error-   INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call

 

Here is my code:-

trigger NotesTitleBeforeInsert on Note (after insert,after update){

List<Note> allTitles = new List<Note>();
if(trigger.isInsert || trigger.isUpdate){
for(Note nT: Trigger.new){
List<Note> ntList = [select ID,Title,Body,ParentId,Parent.Id from Note where Id =:nT.Id];
String titleValue;
for(Note n1 : ntList){
titleValue = n1.Title.substring(0, 6);
system.debug(titleValue);
Boolean TitleTest = Pattern.matches('[0-9]', titleValue);
//Pattern titlePattern = Pattern.Compile('[0-9]{10}');
//Matcher NoteTitle = titlePattern.matcher(n1.Title);
system.debug(TitleTest);

if(TitleTest == true){
n1.Title = n1.Body.substring(0, 76);
}
//update n1;
allTitles.add(n1);
}


}
}
if(allTitles.size() > 0 ){
insert allTitles ;
}
}

Best Answer chosen by Admin (Salesforce Developers) 
vishal@forcevishal@force

Try the below code:

 

trigger NotesTitleBeforeInsert on Note (before insert,before update)

{
     for(Note nT: Trigger.new)

    {
          titleValue = nT.Title.substring(0, 6);
          Boolean TitleTest = Pattern.matches('[0-9]', titleValue);

          if(TitleTest)
               nT.Title = nT.Body.substring(0, 76);
    }


}

 

Let me know if you face any issues with this.

All Answers

Devendra@SFDCDevendra@SFDC

Hi,

 

You need to use before insert here.

 

And assign the value to the field which you want to control via trigger. You dont have to write update and insert statement for the same record in a trigger.

 

Hope this helps :)

 

Thanks,

Devendra

Apex code.ax1542Apex code.ax1542
Thanks for replying but i am still not able to find out my solution.
vishal@forcevishal@force

Try the below code:

 

trigger NotesTitleBeforeInsert on Note (before insert,before update)

{
     for(Note nT: Trigger.new)

    {
          titleValue = nT.Title.substring(0, 6);
          Boolean TitleTest = Pattern.matches('[0-9]', titleValue);

          if(TitleTest)
               nT.Title = nT.Body.substring(0, 76);
    }


}

 

Let me know if you face any issues with this.

This was selected as the best answer
Apex code.ax1542Apex code.ax1542

After adding this line 

 

Boolean TitleTest = Pattern.matches('[0-9]{6}', n1.Title);

 

in your code. its working fine.Thanks alot for your time.