UpdateOnStatusChange:AfterUpdateの実行:System.StringException:エラー

条件に基づいて別のオブジェクトにレコードを挿入するためのトリガー

コード

<���������������������������������������or(Object1__c o1: trigger.new)
{
    if(o1.Status__c == 'Closed')
    {
        for(Object1__c o12: [select name,country__c from Object1__c where Id =: o1.Id])
        {
            ListOfIds.add(new Object2__c(name=o12.name,
                                         country__c = o12.country__c));
        }
    }

    try
    {
        if(!ListOfIds.isEmpty() )
       insert ListOfIds;
    }
    catch(Exception e)
    {
        e.getMessage();
    }
}
</コード>

}

Getting the above error, can someone mention whats wrong in my
コード above and where i need to improve my coding skills… (Note)-
The above コード is not for bulk queries.

ベストアンサー

あなたのコーディングスキルを向上させるためのいくつかの指針:

  1. Do not ever write a query in a loop – there is always a better
    way!
  2. Do not catch and ignore exceptions. Catching the error and
    writing the message to the debug log is not beneficial to the user
    who experiences the problem.

    • Either do absolutely nothing and let the error surface, or
    • catch the exceptions and use the appropriate error handling
      techniques: .addError(),
      ApexPages.addMessages() etc. to display the
      problem.

Some good reading material on Apex Best Practices


トリガーコードのより簡単なバージョンは次のとおりです:

trigger UpdateOnStatusChange on Object1__c (after update) {

   //the list of items to be inserted
    List object2sToInsert = new List();

   //the queried list of items matching our criteria which were in this trigger collection
   //this list will never be null
    List closedObject1s = [SELECT Id
                                            , Name
                                            , Country__c
                                        FROM Object1__c
                                        WHERE Status__c = 'Closed' 
                                            AND Id IN Trigger.newMap.keyset()];

   //create a new record for each item in the result
    for (Object1__c closedObject1 : closedObject1s) {
        object2sToInsert.add(new Object2__c(Name = closedObject1.Name, Country__c = closedObject1.Country__c));
    }

   //do _not_ catch and ignore errors
    /* (catching and writing to the debug log is ignoring) */
    if (!object2sToInsert.isEmpty()) {
        insert object2sToInsert;
    }

}

コメントする

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です