• Everton CP7
  • NEWBIE
  • 50 Points
  • Member since 2013

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 44
    Replies

I'm trying to get the same ownerID from task "test 1" to task "test 3" when I complete the task "test 2".

 

trigger CriarTarefa_Impressao_e_Nova_separacao on Task (before update) {
      
  List<Id> ownerIds = new List<Id>();
  for (Task task : Trigger.new) {
    if (task.subject == 'test 1') {
      ownerIds.add(task.ownerId);
    }
  } 
    
    List<Task> owners = [SELECT Id, ownerId FROM Task WHERE ownerId IN :ownerIds];
  	Map<Id,String> ownerIdsTo = new Map<Id,String>();
  	for (Task owner : owners) {
    ownerIdsTo.put(owner.Id,owner.ownerID); 
  }
  
    List<Task> taskNova = new List<Task>();    
    for (Task task : Trigger.new)
    if (task.subject == 'test 2' && task.status == 'Completed'){
                taskNova.add (new Task(
                         Subject = 'test 3',
                         Status = 'Nenhum',
                         WhatID = task.WhatID,
                         Description = task.description,
                    	 Ownerid = ownerIdsTo.get(task.OwnerId),
                         ActivityDate = Date.today()));
    }

 

With this code the OwnerID returns null.

Hi there,
 
I have an object called "Turmas".
And most of my cases are related to "Turmas".


I have a lookup field in "Cases" to search for the name of my "Turmas" and I have hundreds of "Turmas".

In "Turmas" I have an text field called "PIT" it's my external ID.
I tried to modify some filter configurations to made the field "Turmas" in cases filtering by "PIT" too and bring me the name of my "Turma". But isn't possible, because "PIT" is an text field.


There is a way to made my field "Turmas" in cases filtered by "PIT" and bring me the "Turma" that I looking for?

Thanks !

I need notificiation email to owner's task when task still opens after 30 days.

 

I create a trigger and I think is correct.

But I don't know how to test this one.

 

I create a task with Activity Date 30 days before and I don't recieve any email.

And honestly I don't know if I messed up.

 

Here's my code using before update, before insert:

 

  List<Task> lst = [SELECT Id, ActivityDate FROM Task WHERE IsClosed = false AND ActivityDate >= :Date.today().addDays(+30)];
  for (Task task : Trigger.new) {

 

Thanks for help !

I'm trying to add an specific OwnerID to an specific task.

But I couldn't query my others tasks.

 

I'm trying to select the OwnerID from task "1X".

And put in the task "3X" when I complete the task "2X".

 

trigger CriarTarefa_Nova_separacao on Task (after update) {
    
    List<Id> creatorIds = new List<Id>();
  	for (Task task : Trigger.new) {
    if (task.Status == '1X') {
      creatorIds.add(task.CreatedById);
    }
  } 
    
    List<Task> creators = [Select Id, CreatedById from Task Where Id in :creatorIds];
  	Map<Id,String> creatorIdsTo = new Map<Id,String>();
  	for (Task creator : creators) {
    creatorIdsTo.put(creator.Id,creator.CreatedByID);
  }
    
    List<Task> taskNova = new List<Task>();
    for (Task tt : Trigger.new)
    if (tt.subject == '2X' && tt.status == 'Completed'){
                taskNova.add (new Task(
                         Subject = '3X',
                         Status = 'Nenhum',
                         WhatID = tt.WhatID,
                         Description = tt.description,
                    	 OwnerId = creatorIdsTo.get(tt.CreatedById),
                         ActivityDate = Date.today()));
    }
insert taskNova;
}

 My error is:

"Assigned to: Assigned to ID: owner can not be blank"

 

Thanks !

I have a WF that creates one task for me "Teste1".

I made one trigger creating task by task.

And I created another trigger to update one of this tasks with same owner's case.

 

It could be the same owner of the first task, cause in my WF is the same user that creates the case.

 

Code task by task:

 

trigger CriarTarefa_Nova_separacao on Task (after update) {
    
    List<Task> taskNova = new List<Task>();       
    for (Task tt: Trigger.New)
        if (tt.subject == 'Teste1' && tt.status == 'Concluído'){
                 taskNova.add (new Task(
                     Subject = 'Teste2',
                     Status = 'Nenhum',
                     WhatID = tt.WhatID,
                     Description = tt.description,
                     ActivityDate = Date.today(),
                     OwnerId = '005K00000015gHE'));
        }
        for (Task tt: Trigger.New)
        if (tt.subject == 'Teste2' && tt.status == 'Concluído){
            taskNova.add (new Task(
                     Subject = 'Teste3',
                     Status = 'Nenhum',
                     WhatID = tt.WhatID,
                     Description = tt.description,
                     ActivityDate = Date.today(),
                     OwnerId = '005K00000015gHE'));
            }
        for (Task t: Trigger.New)
            if (t.subject == 'Teste3' && t.status == 'Concluído'){
                taskNova.add (new Task(
                         Subject = 'Teste4',
                         Status = 'Nenhum',
                         WhatID = t.WhatID,
                         Description = t.description,
                         ActivityDate = Date.today()));
            }
    insert taskNova;
}

 

Code Update OwnerID:

 

trigger Impressao_de_album_task on Task (before insert) {
    
        Map<Id,Case> caseMap = new Map<Id,Case>();
        Set<id> Ids = new Set<id>();
        for (Task tk: Trigger.new) {
        Ids.add(tk.OwnerId);
        }
        
        Map<id,Case> caseMap2 = new Map<id,Case>([Select Id, CreatedbyID from Case Where Id in :Ids]);
        
        for (Task t: Trigger.new)
        if(t.Subject == 'Teste4')
        {
        Case c = caseMap2.get(t.OwnerId);
        
        caseMap.put(c.id,c);
        }
        update caseMap.values();
        
        }

 

My error when I will put "status = concluído" in my task "Teste 3" is:

 

CriarTarefa_Nova_separacao: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Impressao_de_album_task: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.Impressao_de_album_task: line 16, column 1: [] Trigger.CriarTarefa_Nova_separacao: line 33, column 1

 

Thanks !

I created a trigger to not let anyone close the case, unless you're the owner.

 

The problem is that some of my cases are created to queues.

 

How I add in my trigger the queues too?

 

trigger ProprietarioFechaChamado on Case (after update) {

    for(Case c : Trigger.new){
    if (c.Status == 'Fechado' && c.OwnerId <> UserInfo.getUserId()) {
      c.addError ('Erro');
}
    }
}

 

Thanks !

Hi there,

 

I made a code to create a task when another task have fotos_encontradas__c == 'NÃO'.

The code works fine, but whatid is not the same.

 

How I made my task open in same whatid?

 

 

trigger CriarTarefa_Pendencia_Duomind_Enviar_novamente_as_foto on Task (after update) {

    List<Task> task = new List<Task>();
    for (Task newTask: Trigger.New)
        if (newtask.fotos_encontradas__c == 'NÃO' && newtask.subject == 'Pendência Duomind' && newtask.status <> 'Concluído'){
                 task.add (new Task(
                     Subject = 'Pendência Duomind - Enviar novamente as fotos',
                     Status = 'Não iniciado',
                     ActivityDate = Date.today(),
                     OwnerId = '005U0000000EtIH'));   
         }
   insert task;
 }

Thanks ! 

Hi there,

 

I was trying create a trigger to send an email notification for another task owner when the first task is completed.

And they have a relation in the same case.

 

My code is getting error:

 

trigger EmailOwners on Task (before update) {
    static final String SUBJECT = 'TESTE';
    static final String BODY = 'Relativo a: {0}\nStatus: {1}\nAssunto: {2}\nComentário Enviado: {3}\nComentário de Conclusão: {4}';
    
    List<Id> ownerIds = new List<Id>();
  	for (Task task : Trigger.new) {
    if (task.Subject == 'Impressão - Preencher quantidade de fotos') {
      ownerIds.add(task.OwnerId);
    	}
    }
        
    List<User> owners = [Select Id, Email from User Where Id in :ownerIds];
  	Map<Id,String> ownerIdsToEmails = new Map<Id,String>();
  	for (User owner : owners) {
    	ownerIdsToEmails.put(owner.Id,owner.Email);
  							}
    
    Map< Id, Case > cases = new Map< Id, Case >( );
  	for(Task record: Trigger.new ) {
    if (record.WhatId != null && record.WhatId.getSObjectType( ) == case.SobjectType )  {
      cases.put( record.WhatId, null );
    }
    }
  
	for (Task task : Trigger.new) {
        if (task.Subject == 'Impressão - Formando tem fotos separadas?' && task.status == 'Conclúido'){
        if (new String[] {cases.put(task.whatid)})
    try {

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {ownerIdsToEmails.get(task.ownerId)});
        mail.setSubject(SUBJECT);
        
        String url = System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + task.WhatId;
        
        mail.setPlainTextBody(String.format(BODY,new String[]{
          url, task.Status,
          task.Subject, task.Description, task.Coment_rio_de_conclus_o_de_tarefa__c
        }));     
        
        Messaging.SendEmailResult[] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
        
        if (!result[0].isSuccess()) {
          System.debug(LoggingLevel.ERROR, 'Failed to send email'+result[0].getErrors()[0].getMessage());
        }
      
      } catch (System.EmailException ex) {
        System.debug(LoggingLevel.ERROR, 'Encountered EmailException');
      }
    }
}

When task with subject = "Impressão - Formando tem fotos separadas?" is completed.

The task owner with the subject = "Impressão - Preencher quantidade de fotos" will recieve an email notification.

Just send the email only when the whatID is the same.

Hi there,

 

I have workflow rules that open task for multiple users when someone create a case.

 

The problem here is when some user complete your task. Noone know about it.
So I need an email notification that send an email to the rest of owner's task in the same case.

 

I tried some codes and nothing.

 

Thanks for help !

 

 

 

Hi there,

 

I need a little help for this trigger.

 

trigger NaoFechaChamado on Case (after update) {
    
    Map<Id, Task> taskMap = new Map<Id, Task>();
    for(Task t : [SELECT Id, WhatId FROM Task WHERE IsClosed=false AND WhatId IN :trigger.newMap.keySet()])
    {
        taskMap.put(t.WhatId, t);
    }
    for(Case c : Trigger.new)
    {
        if(taskMap.containsKey(c.Id) && c.IsClosed && c.IsClosed != Trigger.oldMap.get(c.Id).IsClosed)
        c.addError('Você não pode fechar o chamado enquanto houver tarefas pendentes');
    }

}

I'm trying do this test class and keep getting me errors.

 

I'm brand new in Apex.

So, this little help will be a great help for me.

 

Thanks !

I'm trying to do a trigger that doesn't let anyone close the case if I have tasks opened in the case.

 

If you try to close the case an error will appear.

 

Code:

 

trigger ChamadoAbertoTarefaAberta on Case (after update) {

    {
        List <Task> statuslist = [SELECT id, Status FROM Task WHERE WhatId IN :trigger.new AND Status statuslist.add(t.WhatId, true)];
        MAP<id,string> statuslist= new LIST<Id,String>(); 
   		for(Task t : trigger.new) 
        }
            
            for(Case c : trigger.new()){
            if(map.get(c.Id) == true){
            c.addError(My error here); 
            }
            else{
            break; 
}
            }
}

 I don't know where I'm going wrong.

 

Thanks for help !

I'm brand new to Apex and need to test triggers to deploy to production.

I became reading some topics and I tried a lot do this test class for my trigger, but none doesn't work.

 

Anyone could help me with this test class?

 

Code:

 

trigger EmailTarefa on Task (after update) {
  static final String SUBJECT = 'Tarefa Concluída';
  static final String BODY = 'Atribuido Para: {0}\nRelativo a: {1}\nStatus: {2}\nAssunto: {3}\nComentário Enviado: {4}\nComentário de Conclusão: {5}';

  List<Id> creatorIds = new List<Id>();
  List<Id> ownerIds = new List<Id>();
  for (Task task : Trigger.new) {
    if (task.Status == 'Concluído') {
      creatorIds.add(task.CreatedById);
      ownerIds.add(task.OwnerId);  
    }
  } 

  List<User> creators = [Select Id, Email from User Where Id in :creatorIds];
  Map<Id,String> creatorIdsToEmails = new Map<Id,String>();
  for (User creator : creators) {
    creatorIdsToEmails.put(creator.Id,creator.Email);
  }
  
  List<User> owners = [Select Id, FirstName, LastName From User Where Id in :ownerIds];
  Map<Id,String> ownerIdsToNames = new Map<Id,String>();
  for (User owner : owners) {
    ownerIdsToNames.put(owner.Id,owner.FirstName + ' ' + owner.LastName);
  }
  
  for (Task task : Trigger.new) {
    if (task.Status == 'Concluído') {
      try {

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {creatorIdsToEmails.get(task.CreatedById)});
        mail.setSubject(SUBJECT);
        
        String url = System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + task.WhatId;
        
        mail.setPlainTextBody(String.format(BODY,new String[]{
          ownerIdsToNames.get(task.OwnerId), url, task.Status,
          task.Subject, task.Description, task.Coment_rio_de_conclus_o_de_tarefa__c
        }));     
        
        Messaging.SendEmailResult[] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
        
        if (!result[0].isSuccess()) {
          System.debug(LoggingLevel.ERROR, 'Failed to send email'+result[0].getErrors()[0].getMessage());
        }
      
      } catch (System.EmailException ex) {
        System.debug(LoggingLevel.ERROR, 'Encountered EmailException');
      }
    }
  }
}

 

Any help in this will be realy apreciated.

 

Thanks!

Hi there,

 

I created a VF page on task.

It works fine but when I will create a task related to a case and in this case have a "Personal Account" this error appears.

 

The ID in there, it's the ID from my personal account (WhoID).

 

Does anyone know about this error?

 

Thanks !

Hi there,

 

I'm trying do a column that will show me all the files that have been attached in all the tasks.

 

For example:
I created a task in the case, (the task is related to a case) I attached a file in there and I completed the task.
I created another task in the same case and I need to appear to me the file that have been attached in the first task.

And so on.

 

I put this code in my VF page.

It works if I'm in the same task I have attached the file.

 

<apex:pageBlockTable value="{!task.Attachments}" var="attach">
   <apex:column value="{!attach.name}"/>
   <apex:column value="{!task.subject}"/>
</apex:pageBlockTable>

 

Thanks!

Hi there,

 

I put the related list in my VF page.

The related list appears to me, but the button to attach the files don't.

 

<apex:relatedlist list="Attachments"/>

 

How I add the button?

 

I tried add the button, without the related list:

<apex:commandbutton value="Anexar arquivo" onclick="window.open('/p/attach/ActivityAttach?relatedListId={!task.Id}_RelatedActivityAttachmentList&retURL=%2F{!task.Id}%2Fe%3Fclose%3D1%26retURL%3D%252F500U0000001q9ik&pid={!task.Id}&type=00T')" /> 

With this code I open a window to attach the file.
But when I finished the process to attach the file. The file don't get attached into the task.

Hi there,

 

I create a VF page on case.

And the page don't read the assignment rules.

 

So, I tried to use trigger.

But giving me a huge error, I don't even know how to figure out.

 

trigger AtribuicaoDeCasoTr on Case (after insert) {
    
	Database.DMLOptions dmo = new Database.DMLOptions();
	dmo.assignmentRuleHeader.useDefaultRule= true;

Case newCase = new Case(Status ='new');
newCase.setOptions(dmo);
insert newCase;

}

SF accept the code.

But when I will create a case. This error appears to me:

 

"AtribuicaoDeCasoTr: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AtribuicaoDeCasoTr: maximum trigger depth exceeded Case trigger event AfterInsert for [500J0000001IUue] Case trigger event AfterInsert for [500J0000001IUuf] Case trigger event AfterInsert for [500J0000001IUug] Case trigger event AfterInsert for [500J0000001IUuh] Case trigger event AfterInsert for [500J0000001IUui] Case trigger event AfterInsert for [500J0000001IUuj] Case trigger event AfterInsert for [500J0000001IUuk] Case trigger event AfterInsert for [500J0000001IUul] Case trigger event AfterInsert for [500J0000001IUum] Case trigger event AfterInsert for [500J0000001IUun] Case trigger event AfterInsert for [500J0000001IUuo] Case trigger event AfterInsert for [500J0000001IUup] Case trigger event AfterInsert for [500J0000001IUuq] Case trigger event AfterInsert for [500J0000001IUur] Case trigger event AfterInsert for [500J0000001IUus] Case trigger event AfterInsert for [500J0000001IUut]: [] Trigger.AtribuicaoDeCasoTr: line 8, column 1"

 

Thanks,.

Everton.

Hi there,

 

I think my subject already told what I need.

I have a VF case and I need this checkbox appears to me.

I have assignment rules, but when I open a case SF don't read the rule.

 

Thanks,

Everton.

Hi there,

 

I created a half VF, cause I could't finish the page.

I have more than 500 lines and an error appears to me "String_too_long".

 

But I have to build this page and I was thinking in use <apex:include>. I created another page, put this code and I could create.

 

I tried this:

 

<apex:page standardcontroler= "case">
	<apex:include pageName="TESTE"/>
    	<apex:form>
            <apex:pageBlockSection columns="2" title="Dados do Formando" rendered="{!case.motivo__c == 'Impressão de foto'}">
                <apex:inputfield value="{!case.AccountID}" required="true"/>
                <apex:inputfield value="{!case.Descricao_da_foto__c}" required="true"/>
            </apex:pageBlockSection>
        </apex:form>
</apex:page>

 

No errors appears to me, but when I click in "Preview" I can't see my page.

 

Someone have any clue about this?

If I don't have to use <apex:include> don't have any problem, I just want to build my entire VF.

 

Thanks,

Everton Gomes

Hi there,

 

I have a pick list field "Motivo".

And depending the option that I choose some fields appears to me.

 

The page works perfectly when I made with just one option. But when I added another options my page doesn't render.

 

<apex:outputLabel value="Motivo">
   <apex:actionRegion >
        <apex:inputField value="{!case.motivo__c}">
           <apex:actionSupport event="onchange" reRender="orçamento"/>
           <apex:actionSupport event="onchange" reRender="prestadoradeserviços"/>
      	</apex:inputField>
   </apex:actionRegion>
</apex:outputLabel>
</apex:pageBlockSection>            
    
<apex:outputPanel id="orçamento">   	
   <apex:pageBlockSection columns="1" title="Orçamento de Eventos" rendered="{!case.motivo__c == 'Orçamento de eventos'}">
	<apex:inputfield value="{!case.Subject}"/>
        <apex:inputfield value="{!case.description}" style="width: 280px !important; height: 110px !important;"/>
   </apex:pageBlockSection>
</apex:outputPanel>
            
<apex:outputPanel id="prestadoradeserviços">   	
    <apex:pageBlockSection columns="1" title="Prestadora de Serviços" rendered="{!case.motivo__c == 'Prestadora de serviços'}">
        <apex:inputfield value="{!case.N_mero_de_Protocolo__c}"/>
	<apex:inputfield value="{!case.Subject}"/>
        <apex:inputfield value="{!case.description}" style="width: 280px !important; height: 110px !important;"/>
    </apex:pageBlockSection>
</apex:outputPanel>

 Thanks for help.

Hi there,

 

I created a page.

But when I click in the button to save. Tha page didn't save.

 

<apex:page standardController="case">
    <apex:form>
        <apex:sectionHeader title="Novo Chamado"/>
        <apex:pageBlock mode="edit">
<apex:pageBlockButtons location="bottom"> <apex:commandButton value="Criar Chamado" action="{!Save}"/> <apex:commandButton value="Cancelar" action="{!Cancel}" immediate="true"/> </apex:pageBlockButtons> <apex:pageBlockButtons location="top"> <apex:commandButton value="Criar Chamado" action="{!Save}"/> <apex:commandButton value="Cancelar" action="{!Cancel}" immediate="true"/> </apex:pageBlockButtons>
<apex:pageBlockSection columns="2" id="tipoderegistro" > <apex:pageBlockSectionItem > <apex:outputLabel value="Tipo de Registro"/> <apex:actionRegion > <apex:inputField value="{!case.RecordTypeId}"> <apex:actionSupport event="onchange" rerender="tipoderegistro"/> </apex:inputField> </apex:actionRegion> </apex:pageBlockSectionItem> <apex:outputLabel value="Motivo"> <apex:actionRegion > <apex:inputField value="{!case.motivo__c}"> <apex:actionSupport event="onchange" reRender="dados" /> </apex:inputField> </apex:actionRegion> </apex:outputLabel> </apex:pageBlockSection>
<apex:outputPanel id="dados"> <apex:pageBlockSection title="Cheque devolvido" rendered="{!case.motivo__c == 'Cheque devolvido'}"> <apex:inputfield value="{!case.dados_de_retorno__c}" required="true"/> </apex:pageBlockSection> </apex:outputPanel>
</apex:pageBlock> </apex:form> </apex:page>

 

I'm putting the entire code, cause I don't have any idea why my page didn't save.

If someone know how I do this, or a topic, a blog. Will be a great help for me.

 

Thanks,

I'm trying to get the same ownerID from task "test 1" to task "test 3" when I complete the task "test 2".

 

trigger CriarTarefa_Impressao_e_Nova_separacao on Task (before update) {
      
  List<Id> ownerIds = new List<Id>();
  for (Task task : Trigger.new) {
    if (task.subject == 'test 1') {
      ownerIds.add(task.ownerId);
    }
  } 
    
    List<Task> owners = [SELECT Id, ownerId FROM Task WHERE ownerId IN :ownerIds];
  	Map<Id,String> ownerIdsTo = new Map<Id,String>();
  	for (Task owner : owners) {
    ownerIdsTo.put(owner.Id,owner.ownerID); 
  }
  
    List<Task> taskNova = new List<Task>();    
    for (Task task : Trigger.new)
    if (task.subject == 'test 2' && task.status == 'Completed'){
                taskNova.add (new Task(
                         Subject = 'test 3',
                         Status = 'Nenhum',
                         WhatID = task.WhatID,
                         Description = task.description,
                    	 Ownerid = ownerIdsTo.get(task.OwnerId),
                         ActivityDate = Date.today()));
    }

 

With this code the OwnerID returns null.

I need notificiation email to owner's task when task still opens after 30 days.

 

I create a trigger and I think is correct.

But I don't know how to test this one.

 

I create a task with Activity Date 30 days before and I don't recieve any email.

And honestly I don't know if I messed up.

 

Here's my code using before update, before insert:

 

  List<Task> lst = [SELECT Id, ActivityDate FROM Task WHERE IsClosed = false AND ActivityDate >= :Date.today().addDays(+30)];
  for (Task task : Trigger.new) {

 

Thanks for help !

I'm trying to add an specific OwnerID to an specific task.

But I couldn't query my others tasks.

 

I'm trying to select the OwnerID from task "1X".

And put in the task "3X" when I complete the task "2X".

 

trigger CriarTarefa_Nova_separacao on Task (after update) {
    
    List<Id> creatorIds = new List<Id>();
  	for (Task task : Trigger.new) {
    if (task.Status == '1X') {
      creatorIds.add(task.CreatedById);
    }
  } 
    
    List<Task> creators = [Select Id, CreatedById from Task Where Id in :creatorIds];
  	Map<Id,String> creatorIdsTo = new Map<Id,String>();
  	for (Task creator : creators) {
    creatorIdsTo.put(creator.Id,creator.CreatedByID);
  }
    
    List<Task> taskNova = new List<Task>();
    for (Task tt : Trigger.new)
    if (tt.subject == '2X' && tt.status == 'Completed'){
                taskNova.add (new Task(
                         Subject = '3X',
                         Status = 'Nenhum',
                         WhatID = tt.WhatID,
                         Description = tt.description,
                    	 OwnerId = creatorIdsTo.get(tt.CreatedById),
                         ActivityDate = Date.today()));
    }
insert taskNova;
}

 My error is:

"Assigned to: Assigned to ID: owner can not be blank"

 

Thanks !

I have a WF that creates one task for me "Teste1".

I made one trigger creating task by task.

And I created another trigger to update one of this tasks with same owner's case.

 

It could be the same owner of the first task, cause in my WF is the same user that creates the case.

 

Code task by task:

 

trigger CriarTarefa_Nova_separacao on Task (after update) {
    
    List<Task> taskNova = new List<Task>();       
    for (Task tt: Trigger.New)
        if (tt.subject == 'Teste1' && tt.status == 'Concluído'){
                 taskNova.add (new Task(
                     Subject = 'Teste2',
                     Status = 'Nenhum',
                     WhatID = tt.WhatID,
                     Description = tt.description,
                     ActivityDate = Date.today(),
                     OwnerId = '005K00000015gHE'));
        }
        for (Task tt: Trigger.New)
        if (tt.subject == 'Teste2' && tt.status == 'Concluído){
            taskNova.add (new Task(
                     Subject = 'Teste3',
                     Status = 'Nenhum',
                     WhatID = tt.WhatID,
                     Description = tt.description,
                     ActivityDate = Date.today(),
                     OwnerId = '005K00000015gHE'));
            }
        for (Task t: Trigger.New)
            if (t.subject == 'Teste3' && t.status == 'Concluído'){
                taskNova.add (new Task(
                         Subject = 'Teste4',
                         Status = 'Nenhum',
                         WhatID = t.WhatID,
                         Description = t.description,
                         ActivityDate = Date.today()));
            }
    insert taskNova;
}

 

Code Update OwnerID:

 

trigger Impressao_de_album_task on Task (before insert) {
    
        Map<Id,Case> caseMap = new Map<Id,Case>();
        Set<id> Ids = new Set<id>();
        for (Task tk: Trigger.new) {
        Ids.add(tk.OwnerId);
        }
        
        Map<id,Case> caseMap2 = new Map<id,Case>([Select Id, CreatedbyID from Case Where Id in :Ids]);
        
        for (Task t: Trigger.new)
        if(t.Subject == 'Teste4')
        {
        Case c = caseMap2.get(t.OwnerId);
        
        caseMap.put(c.id,c);
        }
        update caseMap.values();
        
        }

 

My error when I will put "status = concluído" in my task "Teste 3" is:

 

CriarTarefa_Nova_separacao: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Impressao_de_album_task: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.Impressao_de_album_task: line 16, column 1: [] Trigger.CriarTarefa_Nova_separacao: line 33, column 1

 

Thanks !

I created a trigger to not let anyone close the case, unless you're the owner.

 

The problem is that some of my cases are created to queues.

 

How I add in my trigger the queues too?

 

trigger ProprietarioFechaChamado on Case (after update) {

    for(Case c : Trigger.new){
    if (c.Status == 'Fechado' && c.OwnerId <> UserInfo.getUserId()) {
      c.addError ('Erro');
}
    }
}

 

Thanks !

Hi there,

 

I made a code to create a task when another task have fotos_encontradas__c == 'NÃO'.

The code works fine, but whatid is not the same.

 

How I made my task open in same whatid?

 

 

trigger CriarTarefa_Pendencia_Duomind_Enviar_novamente_as_foto on Task (after update) {

    List<Task> task = new List<Task>();
    for (Task newTask: Trigger.New)
        if (newtask.fotos_encontradas__c == 'NÃO' && newtask.subject == 'Pendência Duomind' && newtask.status <> 'Concluído'){
                 task.add (new Task(
                     Subject = 'Pendência Duomind - Enviar novamente as fotos',
                     Status = 'Não iniciado',
                     ActivityDate = Date.today(),
                     OwnerId = '005U0000000EtIH'));   
         }
   insert task;
 }

Thanks ! 

Hi there,

 

I was trying create a trigger to send an email notification for another task owner when the first task is completed.

And they have a relation in the same case.

 

My code is getting error:

 

trigger EmailOwners on Task (before update) {
    static final String SUBJECT = 'TESTE';
    static final String BODY = 'Relativo a: {0}\nStatus: {1}\nAssunto: {2}\nComentário Enviado: {3}\nComentário de Conclusão: {4}';
    
    List<Id> ownerIds = new List<Id>();
  	for (Task task : Trigger.new) {
    if (task.Subject == 'Impressão - Preencher quantidade de fotos') {
      ownerIds.add(task.OwnerId);
    	}
    }
        
    List<User> owners = [Select Id, Email from User Where Id in :ownerIds];
  	Map<Id,String> ownerIdsToEmails = new Map<Id,String>();
  	for (User owner : owners) {
    	ownerIdsToEmails.put(owner.Id,owner.Email);
  							}
    
    Map< Id, Case > cases = new Map< Id, Case >( );
  	for(Task record: Trigger.new ) {
    if (record.WhatId != null && record.WhatId.getSObjectType( ) == case.SobjectType )  {
      cases.put( record.WhatId, null );
    }
    }
  
	for (Task task : Trigger.new) {
        if (task.Subject == 'Impressão - Formando tem fotos separadas?' && task.status == 'Conclúido'){
        if (new String[] {cases.put(task.whatid)})
    try {

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {ownerIdsToEmails.get(task.ownerId)});
        mail.setSubject(SUBJECT);
        
        String url = System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + task.WhatId;
        
        mail.setPlainTextBody(String.format(BODY,new String[]{
          url, task.Status,
          task.Subject, task.Description, task.Coment_rio_de_conclus_o_de_tarefa__c
        }));     
        
        Messaging.SendEmailResult[] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
        
        if (!result[0].isSuccess()) {
          System.debug(LoggingLevel.ERROR, 'Failed to send email'+result[0].getErrors()[0].getMessage());
        }
      
      } catch (System.EmailException ex) {
        System.debug(LoggingLevel.ERROR, 'Encountered EmailException');
      }
    }
}

When task with subject = "Impressão - Formando tem fotos separadas?" is completed.

The task owner with the subject = "Impressão - Preencher quantidade de fotos" will recieve an email notification.

Just send the email only when the whatID is the same.

Hi there,

 

I have workflow rules that open task for multiple users when someone create a case.

 

The problem here is when some user complete your task. Noone know about it.
So I need an email notification that send an email to the rest of owner's task in the same case.

 

I tried some codes and nothing.

 

Thanks for help !

 

 

 

Hi there,

 

I need a little help for this trigger.

 

trigger NaoFechaChamado on Case (after update) {
    
    Map<Id, Task> taskMap = new Map<Id, Task>();
    for(Task t : [SELECT Id, WhatId FROM Task WHERE IsClosed=false AND WhatId IN :trigger.newMap.keySet()])
    {
        taskMap.put(t.WhatId, t);
    }
    for(Case c : Trigger.new)
    {
        if(taskMap.containsKey(c.Id) && c.IsClosed && c.IsClosed != Trigger.oldMap.get(c.Id).IsClosed)
        c.addError('Você não pode fechar o chamado enquanto houver tarefas pendentes');
    }

}

I'm trying do this test class and keep getting me errors.

 

I'm brand new in Apex.

So, this little help will be a great help for me.

 

Thanks !

I'm trying to do a trigger that doesn't let anyone close the case if I have tasks opened in the case.

 

If you try to close the case an error will appear.

 

Code:

 

trigger ChamadoAbertoTarefaAberta on Case (after update) {

    {
        List <Task> statuslist = [SELECT id, Status FROM Task WHERE WhatId IN :trigger.new AND Status statuslist.add(t.WhatId, true)];
        MAP<id,string> statuslist= new LIST<Id,String>(); 
   		for(Task t : trigger.new) 
        }
            
            for(Case c : trigger.new()){
            if(map.get(c.Id) == true){
            c.addError(My error here); 
            }
            else{
            break; 
}
            }
}

 I don't know where I'm going wrong.

 

Thanks for help !

I'm brand new to Apex and need to test triggers to deploy to production.

I became reading some topics and I tried a lot do this test class for my trigger, but none doesn't work.

 

Anyone could help me with this test class?

 

Code:

 

trigger EmailTarefa on Task (after update) {
  static final String SUBJECT = 'Tarefa Concluída';
  static final String BODY = 'Atribuido Para: {0}\nRelativo a: {1}\nStatus: {2}\nAssunto: {3}\nComentário Enviado: {4}\nComentário de Conclusão: {5}';

  List<Id> creatorIds = new List<Id>();
  List<Id> ownerIds = new List<Id>();
  for (Task task : Trigger.new) {
    if (task.Status == 'Concluído') {
      creatorIds.add(task.CreatedById);
      ownerIds.add(task.OwnerId);  
    }
  } 

  List<User> creators = [Select Id, Email from User Where Id in :creatorIds];
  Map<Id,String> creatorIdsToEmails = new Map<Id,String>();
  for (User creator : creators) {
    creatorIdsToEmails.put(creator.Id,creator.Email);
  }
  
  List<User> owners = [Select Id, FirstName, LastName From User Where Id in :ownerIds];
  Map<Id,String> ownerIdsToNames = new Map<Id,String>();
  for (User owner : owners) {
    ownerIdsToNames.put(owner.Id,owner.FirstName + ' ' + owner.LastName);
  }
  
  for (Task task : Trigger.new) {
    if (task.Status == 'Concluído') {
      try {

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {creatorIdsToEmails.get(task.CreatedById)});
        mail.setSubject(SUBJECT);
        
        String url = System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + task.WhatId;
        
        mail.setPlainTextBody(String.format(BODY,new String[]{
          ownerIdsToNames.get(task.OwnerId), url, task.Status,
          task.Subject, task.Description, task.Coment_rio_de_conclus_o_de_tarefa__c
        }));     
        
        Messaging.SendEmailResult[] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
        
        if (!result[0].isSuccess()) {
          System.debug(LoggingLevel.ERROR, 'Failed to send email'+result[0].getErrors()[0].getMessage());
        }
      
      } catch (System.EmailException ex) {
        System.debug(LoggingLevel.ERROR, 'Encountered EmailException');
      }
    }
  }
}

 

Any help in this will be realy apreciated.

 

Thanks!