• Shivdeep Kumar
  • NEWBIE
  • 434 Points
  • Member since 2014
  • Accenture Solutions Pvt Ltd

  • Chatter
    Feed
  • 14
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 2
    Questions
  • 108
    Replies
Hi All,
I  am facing errror when execute this class through vf page  and also it is showing one record instead of more record .
it is show error "List has more than 1 row for assignment to SObject
Error is in expression '{!getData}' in component <apex:commandButton> in page cpqvf: Class.ProductEntry.getData: line 13, column 1
An unexpected error has occurred. Your development organization has been notified.

"
Please help .

public class ProductEntry{ 
    public List<sObjectWrapper> wrappers{get;set;} 
Public string selectedname{get;set;}
 public List<PricebookEntry> PriceEntry{get;set;}
    public  ProductEntry()
    {
    PriceEntry=new List<PricebookEntry>();
    } 
 public void getData()
 {
     List<sObjectWrapper> wrapper=new List<sObjectWrapper>();
     
    product2 productList=[select id,name,Units_of_Measure__c from product2 where Bundle_Type__c=:selectedname];
     PriceBook2 pricebook=[select id from pricebook2 where name In('BlackBeltHelp V2')];
    PriceEntry=[SELECT id,Name,Pricebook2Id,Product2Id,ProductCode,UnitPrice,UseStandardPrice FROM PricebookEntry WHERE Pricebook2Id=:pricebook.id and product2Id=:productList.id];
    }     
    Public List<string> optionList=new List<String>{'Basic','Advance','Primium'};
        Public List<Selectoption> getselectedaccnamefields(){
            List<Selectoption> lstnamesel = new List<selectoption>();
            lstnamesel.add(new selectOption('', '- None -'));
            for(String s :optionList){
            lstnamesel.add(new selectoption(s,s));
            }
            return lstnamesel; 
        }
}
and my viasulforce page is 

<apex:page controller="ProductEntry">
    <apex:form >
        <apex:pageBlock title="Select Product List">
            <apex:pageBlockSection columns="1">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Bundle Type"/>
                    <apex:selectList size="1" value="{!selectedname}"> 
        <apex:selectOptions value="{!selectedaccnamefields}"/>  
    </apex:selectList>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
            <apex:pageBlockTable value="{!PriceEntry}" var="a">
                <apex:column value="{!a.id}"/>
                <apex:column value="{!a.name}"/>
                <apex:column value="{!a.Pricebook2Id}"/>
            <apex:column value="{!a.UnitPrice}"/>
                <apex:column value="{!a.ProductCode}"/>
                <apex:column value="{!a.UseStandardPrice}"/>
            </apex:pageBlockTable>
            <apex:pageBlockButtons >
                <apex:commandButton value="GetData" action="{!getData}"/>
            </apex:pageBlockButtons>
            
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
Hello! I am working on preparing my org to roll over to Lightning and I have seven custom buttons I need to update. My custom buttons are showing in Lightning but not workin as they should. Typically these buttons open and an email in a new tab and gather information up into a template. Here's an example of one: 

/_ui/core/email/author/EmailAuthor?rtype=003&p3_lkid={!GIS_New_Account_Set_Up__c.Id}&retURL=%2F{!GIS_New_Account_Set_Up__c.Id}&p5={!$User.Email}&p24="smorgan@geninfo.com,rmercado@geninfo.com,amoore@geninfo.com,skeele@geninfo.com,scausey@geninfo.com,jdailey@geninfo.com,jsowell@geninfo.com,nprabhakaran@geninfo.com,cvodila@geninfo.com,implogging@geninfo.com,impcontract@geninfo.com&template_id=00X500000015TvQ

Could anyone tell me what I need to change? I've read a few resources and I think I need to create an action but it's not clicking for me. I do not see how I can have the same result which is clicking the action and an email popping up in a new window with all of the information needed from Salesforce (based on an email template I have in place), all the email addresses needed are populated in and all the sales person has to do is click send.

Thank you!
Hello
I am trying to understand how to use base utility helper method in lighting component.
Base.cmp
--------
<aura:component abstract="true">
	{!v.body}
</aura:component>


BaseHelper.js
--------------
({
    callServer : function(component,method,callback,params) {
        var action = component.get(method);
        if (params) {
            action.setParams(params);
        }
       
        action.setCallback(this,function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                // pass returned value to callback function
                callback.call(this,response.getReturnValue());  
            } else if (state === "ERROR") {
                // generic error handler
                var errors = response.getError();
                if (errors) {
                    console.log("Errors", errors);
                    if (errors[0] && errors[0].message) {
                        throw new Error("Error" + errors[0].message);
                    }
                } else {
                    throw new Error("Unknown Error");
                }
            }
        });
       
        $A.enqueueAction(action);
    }
})


ApexController.axpc
-------------------
public with sharing class ApexController {
    @AuraEnabled
    public static List<Contact> getContacts() {
        List<Contact> contacts = [select Id, Name, MailingStreet, Phone, Email FROM Contact];
        return contacts;
    }
}


CallApexClassCmpBase.cmp
------------------------

<aura:component controller="ApexController">
	
    <lightning:card title="Bring Contact data">
       
          <aura:set attribute="actions">
       
              <lightning:button label="Contact Data" onclick="{!c.Condata}" />
          </aura:set> 
   
    </lightning:card>
    
</aura:component>


In the controller.js of the above component

({
 Condata : function(component,event,helper) {
 helper.callServer(
            component,
            "c.getContacts",
            function(response) { 
               console.log('Contacts data'+JSON.stringify(response));
            }
        );
      
    }
})



<aura:application extends="force:slds">

    <c:CallApexClassCmpBase/>
     
 </aura:application>
when I preview this I am getting an error as below:

This page has an error. You might just need to refresh it. Action failed: etaPrime:CallApexclassCmpBase$controller$Condata [helper.callServer is not a function] Failing descriptor: {etaPrime:CallApexclassCmpBase$controller$Condata}

I am not able to figure out what is causing the issue,

Please help.

smita
I have a checkbox field on my Campaign Member records called Campaign_IsActive__c.  Using a trigger, I'd like when my Campaign IsActive = FALSE, to update the Campagin_IsActive__c on my Campaign Member records.

I've been working on a trigger for a few days and continue to run into roadblocks.  I'm currently facing an error stating: Variable Does Not Exist: 'CampaignMember'.

Can anyone please point me in the right direction?  Once I can get the list, I'll be able to update the field.  But I have had the hardest time simply getting a list of CampaignMembers from Campaigns.
 
trigger deactivateCampaignMember on Campaign (after insert) {
    if(Trigger.isAfter){
        if(Trigger.isInsert){
        Map<id, list<CampaignMember>> campaignMemberMap = new Map<Id, List<CampaignMember>>();
        for(campaign camp : [SELECT Id, (SELECT LeadId,ContactId FROM CampaignMembers) FROM Campaign])
        
            {
            list<CampaignMember> campMemebersList = camp.CampaignMember;
            
            if(campMemebersList!= null)
                {
                campaignMemberMap.put(camp.Id, campMemebersList);
                }
            }

        }
    }
}



 

Hi Guys,

My scenario is I need a process that creates a case when a new record called "Change Request" is approved.
However, I cannot find any option under 'approval process' to create a record upon approval. I am unsure of this is actually possible. I hope you can help me.

Thank you,
 

Roberto

public class AccountOwnerUpdate{
    public Boolean isSelected{get;set;}
    public Account accounts{get;set;}
    public List<Account> selectedAccounts{get;set;}
   // public Boolean sendEmail{get;set;}
    public AccountOwnerUpdate(ApexPages.StandardSetController standardController)
    {   
        if(standardController.getSelected().size() == 0){
            isSelected = false;
            ApexPages.Message msg = new ApexPages.message(ApexPages.Severity.ERROR,'No Account Selected');
            ApexPages.addMessage(msg);
        }else{
            isSelected = true;
            selectedAccounts=  [SELECT id,name,ownerid from Account where id=:standardController.getSelected()];
           accounts = selectedAccounts[0]; 
           // accounts.ownerid = null; 
       }       
    }
    public PageReference updateAccount()
    {   
        for(Account a: selectedAccounts){
            a.ownerid = accounts.ownerid;
        }
        update selectedAccounts;
        return new Pagereference('/001/o');
    }

}
Hi All,

I have requirement where i have to update a field in an object using flow. please help me with procedure for the same. below is the exact requirement

in my org i have a object obj with fields FF(formula field), textField i have to update the value of the FF into textField using flow. can you please help me with step by step procedure for the same. Thanks

Best Regrads,
Mohammad Yaseen.
Hi Developers,
I am Facing strange issue. My class has 94% code coverage, i checked in eclipse as well. but while deploying this class it shows code coverage failure, only  61% code coverage, Even though i used RUN specified tests option.

Any help on this will be appriciated.
Hi
I want to bring the New Case creation button in the opp object. i used as per below,
Its working OK, while creating a new case, But its neither returning to the Opportunity object after case creation nor in the Case object Opportunity lookup , its showing the related Opp ID. Can you plz suggest on my below URL how to achieve it?. Thanks
https://cs6.salesforce.com/500/e?retURL=%2F{!Opportunity.Id}&save_new_url={!Opportunity.Name}


User-added image
Hello,

do you have any trigger to force Case Assignment Rule to run when a User edit with inline editing?
I know that there are some ideas to correct this and the only workaround is to use a trigger.

I'm using this code but is not triggering any Rule:
 
trigger CaseAssignmentTrigger on Case (before update) {
  
  for (Case theCase:trigger.new) {
      Database.DMLOptions dmo = new Database.DMLOptions();
      dmo.assignmentRuleHeader.useDefaultRule = true;
      theCase.setOptions(dmo);
      
      System.debug ('working');
  }
    
        
}



Thank you.
Hi Folks,

I am having an apex class which is having AuraEnabled method which returns list of accounts to <aura:iteration >. I am not able to display the list in component.Code is very simple nothing complicated.
  
Need help ASAP.


<aura:component controller="Accounts">
    <aura:attribute name="Acc" type="Account[]" default="{'sObjectType':'Account',
                                                                         'Name':'',
                                                         'Id':''}"/>
    <aura:iteration items="{!v.Acc}" var="acc">
    <p>{!acc.Name}</p>
    </aura:iteration>
</aura:component>

//Server side controller
public with sharing class Accounts {
    @AuraEnabled
    Public Static List<Account> getAccount(){
  return  [Select Name,id from Account LIMIT 2];
      
    
}
}

 
Hello, 

I am stuggling with this trigger to count the number of open tasks on a lead. I am receiving the following error: 

UpdateContactClosedTasks: execution of AfterDelete caused by: System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop: External entry point

Here is the trigger: 

trigger UpdateLeadOpenTasks on Task (after insert, after undelete,
after update, after delete) {

// Declare the variables

public set<Id> LeadIDs = new Set<Id>();
public list<Lead> LeadsToUpdate = new List<Lead>();

// Build the list of Leads and Contacts to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
    for(Task t: Trigger.new){
     if(t.WhoId<>null){
    if(string.valueOf(t.WhoId).startsWith('00Q'))
    LeadIDs.add(t.WhoId);
   }
  } 
}

if(Trigger.isDelete || Trigger.isUpdate){
    for(Task t: Trigger.old){
     if(t.WhoId<>null){
    if(string.valueOf(t.WhoId).startsWith('00Q'))
    LeadIDs.add(t.WhoId);
   }
  } 
}

// Update the Leads

if(LeadIDs.size()>0){
for(Lead l: [Select l.Id, l.Open_Activities__c,
(Select Id From Tasks where IsClosed = False)
From Lead l where Id in :LeadIDs])
LeadsToUpdate.add(new Lead(Id=l.Id, Open_Activities__c = l.Tasks.size()));
update LeadsToUpdate;
}
if(LeadstoUpdate != null && !LeadsToUpdate.isEmpty())
Database.update(LeadsToUpdate);
}

Any help would be greatly appreciated. 
Here is the code snippit:
trigger WorkOrderJobRollUp on Work_Order__c (before update, after insert, after delete, after undelete) {
    
    // Check to make sure work order is not being deleted
    IF (trigger.isdelete == FALSE)
    {
        // Run trigger for all situations with the exception of the AFE Approval process
        For(Work_Order__c wo : Trigger.New)
        {
            try
            {
                Work_Order__c beforeUpdate = Trigger.oldMap.get(wo.ID);
                system.debug('Work Order ID New: ' + wo.ID);
                system.debug('Work Order ID Old: ' + beforeUpdate.ID);
                
                string oldstatus = beforeUpdate.Work_Order_Status__c;
                
                system.debug('New WO Status: ' + wo.Work_Order_Status__c);
                system.debug('Old WO Status: ' + beforeUpdate.Work_Order_Status__c);
                system.debug('Old WO Status: ' + trigger.oldmap.get(wo.ID).Work_Order_Status__c);
                system.debug('Old WO Status: ' + oldstatus);
                   
                   IF (wo.Work_Order_Status__c == 'Approved' && beforeUpdate.Work_Order_Status__c == 'Pending Approval') return;
            }
            catch(exception e){}
        }
    }

Here is a snippit of the debug log:
14:09:14.853 (9285875790)|USER_DEBUG|[12]|DEBUG|Work Order ID New: a270j0000009ASKAA2 14:09:14.853 (9285880579)|STATEMENT_EXECUTE|[13] 14:09:14.853 (9285889523)|HEAP_ALLOCATE|[13]|Bytes:18 14:09:14.853 (9285894991)|HEAP_ALLOCATE|[13]|Bytes:37 14:09:14.853 (9285898897)|USER_DEBUG|[13]|DEBUG|Work Order ID Old: a270j0000009ASKAA2 14:09:14.853 (9285901596)|STATEMENT_EXECUTE|[15] 14:09:14.853 (9285907986)|VARIABLE_SCOPE_BEGIN|[15]|oldstatus|String|false|false 14:09:14.853 (9285914795)|VARIABLE_ASSIGNMENT|[15]|oldstatus|"Approved" 14:09:14.853 (9285916837)|STATEMENT_EXECUTE|[17] 14:09:14.853 (9285920997)|HEAP_ALLOCATE|[17]|Bytes:23 14:09:14.853 (9285925680)|USER_DEBUG|[17]|DEBUG|New WO Status: Approved 14:09:14.853 (9285928468)|STATEMENT_EXECUTE|[18] 14:09:14.853 (9285932040)|HEAP_ALLOCATE|[18]|Bytes:23 14:09:14.853 (9285935598)|USER_DEBUG|[18]|DEBUG|Old WO Status: Approved 14:09:14.853 (9285938221)|STATEMENT_EXECUTE|[19] 14:09:14.853 (9285964009)|HEAP_ALLOCATE|[19]|Bytes:23 14:09:14.853 (9285968749)|USER_DEBUG|[19]|DEBUG|Old WO Status: Approved 14:09:14.853 (9285971863)|STATEMENT_EXECUTE|[20] 14:09:14.853 (9285974149)|HEAP_ALLOCATE|[20]|Bytes:23 14:09:14.853 (9285978158)|USER_DEBUG|[20]|DEBUG|Old WO Status: Approved

The value of the Work Order Status field is changing from Pending Approval to Approved and I don't want the body of the trigger to fire off when this happens.  How does the Trigger.newmap and trigger.oldmap values equal each other?
Can anyone Please help me out for this Apex Class to create a test class......


public with sharing class ListContactDetailOnCallController {     
public List<Contact> contacts {get;set;}       
public Integer contactsCount {get;set;}     
public List<Case> cases {get;set;}      
public string cPhone {get;set;}
         
Public ListContactDetailOnCallController(){         
cphone=ApexPages.currentPage().getParameters().get('phone');         
String orderId=ApexPages.currentPage().getParameters().get('orderId');         cases = [Select Id, Order_Id__c, SuppliedPhone From Case where Order_Id__c =:orderId];         
if(cphone!='' && cphone!=null){            
contacts = [Select  Name, mobilephone, ( Select Id, Order_Id__c, SuppliedPhone From Cases where Order_Id__c =:orderId  ) , Email,customer_id__c,birthdate,phone,title,ownerid,source__c                 from contact where phone like :('%' + cphone + '%')  OR MobilePhone like :('%' + cphone + '%') ORDER BY lastModifieddate]; 
                                        if(contacts.size()==0){  
               contactsCount=0;                           
 }else if(contacts.size()==1){   
              contactsCount=1;           
  }        
 }else{  
           contactsCount=0;      
   }    
 }         

 public PageReference redirPage(){     
    PageReference pR;        
 if(contactsCount==0){          
  pR=new PageReference('/003/e?retURL=%2F003%2Fo&con12='+cPhone);        
      return pR;      
   }if(contactsCount==1){          
   pR= new PageReference('/'+contacts[0].Id);          
   return pR;      
   }else{           
  return null;       
  }    
 }     
     }
 
We have two object say A and B. 
A has a lookup on B. 
A has two text field Type and year.
B has one text field Type and year
I want to populate the lookup field of A by matching Type and Year field of A with type and Year field of B. Trigger code should be bulkified. Need help, its urgent. Thank you

I have set up email to case and it works fine. As an admin i can send emails from within a Case from the email which i have set up as the email to case address, responses are threaded back to the case and everything looks fine. However, other users can send email from a case ONLY from their own email address and they do not have the ability to select the generic Support email. As a result responses are not threaded to the case and they are sent only to their personal email.

Any idea why? How can i allow all users to send email from a case using the email to case address?

This is my apex method that is returning a list:
@AuraEnabled(cacheable=true)
    public static List<String> getTypePicklistValuesMethod(){
        List<String> pickListValuesList= new List<String>();
         Schema.DescribeFieldResult fieldResult = Task.Type.getDescribe();
         List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
         for( Schema.PicklistEntry pickListVal : ple){
             pickListValuesList.add(pickListVal.getLabel());
         }    
         return pickListValuesList;
    }

and this is my JS file:
import { LightningElement, wire} from 'lwc';
import picklistValues from '@salesforce/apex/TaskCreator.getTypePicklistValuesMethod';

export default class ListToMapPractice extends LightningElement
{
    @wire(picklistValues)
    typeValues;
}

So can this "typeValues" be directly used as an array or is there something more to it that i don't know yet.
i want to upload a csv using vf page that would contain parent accounts with corresponding child accounts, and i want to merge them using batch instead of doing this manually but i am getting error " List has more than 1 row for assignment to SObject on line: 35" on my batch, 
my vf page is 
<apex:page controller="MergeChildAccountsController">
    <apex:form enctype="multipart/form-data">
        <apex:inputFile value="{!csvFile}" />
        <apex:commandButton action="{!processCsv}" value="Process CSV" />
    </apex:form>
</apex:page>
============================================
my controler is 
public class MergeChildAccountsController {
    public Blob csvFile { get; set; }
    
    public void processCsv() {
        String[] filelines = csvFile.toString().split('\n');
        List<Account> childAccounts = new List<Account>();
        Map<String, String> parentMap = new Map<String, String>();
        
        for (Integer i = 1; i < filelines.size(); i++) {
            String[] fields = filelines[i].split(',');
            String accountName = fields[0].trim();
            String parentName = fields[1].trim();
            
            Account child = new Account(Name = accountName);
            childAccounts.add(child);
            parentMap.put(accountName, parentName);
        }
        
        Database.executeBatch(new MergeChildAccountsBatch(childAccounts, parentMap));
    }
}
====================================

my batch is 
public class MergeChildAccountsBatch implements Database.Batchable<Account> {
    List<Account> childAccounts;
    Map<String, String> parentMap;
    
    public MergeChildAccountsBatch(List<Account> childAccounts, Map<String, String> parentMap) {
        this.childAccounts = childAccounts;
        this.parentMap = parentMap;
    }
    
    public Iterable<Account> start(Database.BatchableContext bc) {
        return [SELECT Id, Name, ParentId FROM Account WHERE Name IN :parentMap.keySet() OR Id IN :childAccounts];
    }
    
    public void execute(Database.BatchableContext bc, List<Account> parentAccounts) {
        try {
            Map<String, Account> nameToAccountMap = new Map<String, Account>();
            
            for (Account account : parentAccounts) {
                nameToAccountMap.put(account.Name, account);
            }
            
            Set<Account> accountsToMerge = new Set<Account>();
            for (Account child : childAccounts) {
                String parentName = parentMap.get(child.Name);
                if (parentName != null) {
                    List<Account> parentList = [SELECT Id, Name, ParentId FROM Account WHERE Name = :parentName];
                    accountsToMerge.addAll(parentList);
                }
            }
            
            Database.MergeResult[] mergeResults = Database.merge(nameToAccountMap.values(), new List<Account>(accountsToMerge), false);
           system.debug('mergeResults' +mergeResults);
            
            
           /* for (Database.MergeResult result : mergeResults) {
                if (result.isSuccess()) {
                    // do something with the merged account
                } else {
                    // handle the merge failure
                }
            } */
        } catch (Exception e) {
            System.debug('Error: ' + e.getMessage() + ' on line: ' + e.getLineNumber());
        }
    }
    
    public void finish(Database.BatchableContext bc) {
        // do nothing
    }
}

Hi there,
I have the following apex email handler which pourpose is to update de priority of a case create from email-to-case according to the priority that is informed on the subject of the email that originated the case:


global with sharing class EmailToCasePriorityHandler implements Messaging.InboundEmailHandler{
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        System.debug('get in the email class');
        // Parse the email to extract the priority
        String subject = email.subject;
        Pattern pattern = Pattern.compile('(Case #(\\d+) - Priority (\\d)');
        Matcher matcher = pattern.matcher(subject);
        System.debug('subject' + subject);
        if (!matcher.matches()) {
            System.debug('does not match' );
            result.message = 'Email subject is not in the right format.';
            return result;
        }
        String priority = matcher.group(2);
        // Retrieve the case and update the priority
        Case theCase = [SELECT Id, Priority, CaseNumber FROM Case WHERE Subject = : subject LIMIT 1];
        if (theCase == null) {
            result.message = 'Case not found.';
            return result;
        }
        theCase.Priority = priority;
        update theCase;
        // Set the response message and status
        result.message = 'Case ' + theCase.Id + ' priority updated to ' + priority;
        result.success = true;
        return result;
    }
}


I have set up the email-to-case and it is working fine.

I have also configured the Email Services to this apex class.

But for some reason when a case is create from email-to-case this class is not being called.

What can it be?

And is there a better way to implement this custom email handler? Because I am using the subject of the email to retrieve the correct case to update.

Thanks!

  • February 24, 2023
  • Like
  • 0

Hi, Could you please help me written validation rule.

I'm having object 'Vehicle' which is having field 'Lock'. And there is another object name as 'CLIN' having lookup relationship to Vehicle, also there is self relationship between CLIN object.

Validation is written on 'CLIN' object. If 'Vehicle' record is locked , can not create/Update CLIN record.

Also After trigger is working on 'CLIN' object, which rollups fields to the same parent record.
Currently, I'm creating CLIN selecting self lookup relationship field and that selected CLIN's Vehicle is locked. So, when I'm creating this record I am getting validation error.

I need a validation that checks only Current CLIN's Vehicle is locked excluding the self lookup CLIN's Vehicle record is either locked or not.

Thanks in advance

Hi,
I am sending an email through apex class to users. Email is going from (noreply@salesforce.com; on behalf of; XXX <xxx@xxx.com>.) But this is not working for only one profile.
public class BMCRF_NewUserCreation 
{
       public static string description = '';
       public static string firstName = '';
       public static string Alias = '';
       public static string Email = '';
       public static string UserName = '';
       public static string lastName = '';
       public static string WorkerType = '';
       public static string EmployeeType = '';
       public static string Position = '';
       public static string Manager = '';
       public static string EmployeeID = '';
       public static string Company = '';
       public static string Division = '';
       public static string Location = '';    
       public static string Department = '';
       public static ID userManagerId;  
       public static list<user> usercreationList = new list<user>();
       public static list<id> taskIDList = new list<id>();
       public static Profile prof = [SELECT Id FROM Profile WHERE Name = 'ServiceDesk Client'limit 1];
       public static ID profileId = prof.id;
//===========================================================================================================================================================
    public static ID getManagerId(string mName)
    {
        user uName = [SELECT Id,name FROM User where name =: mName limit 1];
        return uName.id;
    }
        
//===========================================================================================================================================================
  @invocableMethod
    public static void createUser(list<ID> IDList)
    {
        taskIDList.addAll(IDList);
        BMCRF_NewUserCreation.setUserInfo();
    }
    
//===========================================================================================================================================================
    public static void setUserInfo()
   {
             
            //list<BMCServiceDesk__Task__c> tskList = [Select BMCServiceDesk__taskDescription__c from BMCServiceDesk__Task__c where id IN: taskIDList];
            list<BMCServiceDesk__Task__c> tskList = [Select BMCServiceDesk__taskDescription__c from BMCServiceDesk__Task__c where Name = '00076155'];
           for(BMCServiceDesk__Task__c tsk : tskList)
           {
                description = tsk.BMCServiceDesk__taskDescription__c;
                User newUser = new User();
               
                if(description.contains(firstName))
                {
                   firstName = description.substringAfter('First Name:');
                   firstName = firstName.substringBefore('\n');
                   firstName.trim();
                   newUser.FirstName = firstName;
                }
                if(description.contains(lastName))
                {
                    lastName = description.substringAfter('Last Name:');
                    lastName = lastName.substringBefore('\n');
                    lastName.trim();
                    newUser.LastName = lastName;
                }
                UserName = firstName+'.';
                UserName = UserName+lastName.trim();
                Email = UserName +'@starrcompanies.com';
                UserName = UserName+'@starrcompanies.com';
                Alias = firstName.substring(1,2)+lastName.substring(1,5);
                newUser.Alias = Alias;
                    
                if(description.contains(WorkerType))
                {
                    WorkerType = description.substringAfter('Worker Type:');
                    WorkerType = WorkerType.substringBefore('\n');
                    WorkerType.trim();
                    newUser.Title = WorkerType;
                    newUser.Worker_Type__c = WorkerType;
                }
                if(description.contains(EmployeeType))
                {
                   EmployeeType = description.substringAfter('Employee Type:');
                   EmployeeType = EmployeeType.substringBefore('\n'); 
                   EmployeeType.trim();
                   newUser.Employee_CW_Type__c = EmployeeType;
                }
                if(description.contains(Position))
                {
                    Position = description.substringAfter('Position:');
                    Position = Position.substringBefore('\n');
                    Position.trim();
                }
                if(description.contains(Manager))
                {
                    Manager = description.substringAfter('Manager:');
                    Manager = Manager.substringBefore('\n');
                    Manager.trim();
                    userManagerId = getManagerId(Manager);
                    newUser.ManagerId = userManagerId;
                }
                if(description.contains(EmployeeID))
                {
                    EmployeeID = description.substringAfter('Employee ID:');
                    EmployeeID = EmployeeID.substringBefore('\n');
                    EmployeeID.trim();
                    newUser.BMCRF_Employee_Id__c = EmployeeID;
                }
                if(description.contains(Company))
                {
                    Company = description.substringAfter('Company:');
                    Company = Company.substringBefore('\n');
                    Company.trim();
                    newUser.CompanyName = Company;
                }
                if(description.contains(Division))
                {
                    Division = description.substringAfter('Division:');
                    Division = Division.substringBefore('\n');
                    Division.trim();
                    newUser.Division = Division;
                }
                if(description.contains(Department))
                {
                    Department = description.substringAfter('Cost Center:');
                    Department = Department.substringBefore('\n'); 
                    Department.trim();
                    newUser.Department = Department;
                }
                if(description.contains(Location))
                {
                    Location = description.substringAfter('Location:');
                    Location = Location.substringBefore('\n'); 
                    Location.trim();
                    newUser.City = Location;
                }          
                  newUser.Email = Email;
                  newUser.EmailEncodingKey = 'UTF-8';
                  newUser.LanguageLocaleKey = 'en_US';
                  newUser.LocaleSidKey = 'en_US';
                  newUser.TimeZoneSidKey='America/New_York';
                  newUser.ProfileId = profileId;
                  newUser.Username = UserName; 
                  newUser.CommunityNickname = firstName+'.'+lastName;
                  newUser.IsActive=true;
                  newUser.FederationIdentifier = firstName+'.'+lastName;
                  
                  usercreationList.add(newUser);
               }
       
                try
                {   
                    //insert usercreationList;
                    Database.SaveResult[] results = Database.insert(usercreationList, false);
            for(Database.SaveResult result : results) 
            {
                if(result.isSuccess()) 
                {
                    System.debug('Successfully inserted User : ' + result.getId());
                } 
                else 
                {
                    for(Database.Error error : result.getErrors()) 
                    {
                        System.debug('Error Status : ' + error.getStatusCode() + ' : ' + 'Error Fields : ' + error.getFields());
                    }
                }
            }
                    system.debug('User is created....');
                    assignPermissionSet();
                }
                catch(DmlException e)
                { 
                    System.debug('The following exception has occurred: ' + e.getMessage()); 
                }

       DisplayInfo();
       assignPermissionSet();
   } 
//============================================================================================================================================================
//@future(callout=true)
    public static void assignPermissionSet()
  {
//========================================================Permission Set License Assign===================================================================
    
     list<PermissionSetLicenseAssign> PermissionSetLicenseList = new list<PermissionSetLicenseAssign>();
      
      PermissionSetLicense PermissionSetLicense = [SELECT id, MasterLabel FROM PermissionSetLicense where MasterLabel = 'Identity Connect'];
      for(user userId : usercreationList)
      {
          PermissionSetLicenseAssign PermissionSetLicenseAssign = new PermissionSetLicenseAssign();
          PermissionSetLicenseAssign.AssigneeId = userID.id;
          PermissionSetLicenseAssign.PermissionSetLicenseId = PermissionSetLicense.id;
          PermissionSetLicenseList.add(PermissionSetLicenseAssign);
      }
       //insert PermissionSetLicenseList;
                try
                {   
                    //insert usercreationList;
                    Database.SaveResult[] results = Database.insert(PermissionSetLicenseList, false);
                    for(Database.SaveResult result : results) 
                    {
                        if(result.isSuccess()) 
                        {
                            System.debug('Successfully inserted User : ' + result.getId());
                        } 
                        else 
                        {
                            for(Database.Error error : result.getErrors()) 
                            {
                                System.debug('Error Status : ' + error.getStatusCode() + ' : ' + 'Error Fields : ' + error.getFields());
                            }
                        }
                    }
                }
      catch(DmlException e)
        {
             System.debug('The following exception has occurred: ' + e.getMessage()); 
        }
      
      
//========================================================Permission set Assignment===================================================================
     
      string IdentityConnect = 'IdentityConnect';
      string MobileDeviceFormAccess = 'Mobile_Device_Form_Access';
      string ServiceDeskClient = 'ServiceDesk_Client';
      string ServiceDeskClientMobile = 'ServiceDesk_Client_Mobile';
      
      list<PermissionSet> permissions = [SELECT Id, Name FROM PermissionSet WHERE Name =: IdentityConnect OR Name =: MobileDeviceFormAccess OR Name =: ServiceDeskClient  OR Name =: ServiceDeskClientMobile];
      List<PermissionSetAssignment> permissionSetAssignmentsList = new List<PermissionSetAssignment>();
      
      system.debug('permissions : '+ permissions);
   for(User user: usercreationList)
   {
      for(PermissionSet permission: permissions)
      {
          system.debug('permissions : '+ permissions);
          PermissionSetAssignment permissionSetAssignment = new PermissionSetAssignment();

            if(permission.name ==  IdentityConnect)
            {
                permissionSetAssignment.PermissionSetId = permission.Id;
                system.debug('IdentityConnect : '+ permission.Id);
            }
          else if(permission.name == MobileDeviceFormAccess)
          {
                permissionSetAssignment.PermissionSetId = permission.Id;
                system.debug('MobileDeviceFormAccess : '+ MobileDeviceFormAccess);
            }
          else if(permission.name == ServiceDeskClient)
          {
                permissionSetAssignment.PermissionSetId = permission.Id;
                system.debug('ServiceDeskClient : '+ permission.Id);
            }
          else if(permission.name == ServiceDeskClientMobile)
          {
                permissionSetAssignment.PermissionSetId = permission.Id;
                system.debug('ServiceDeskClientMobile : '+ permission.Id);
            }
          permissionSetAssignment.AssigneeId = user.ID;
          permissionSetAssignmentsList.add(permissionSetAssignment);
      }
   }
          //insert permissionSetAssignmentsList;
           try
                {   
                    Database.SaveResult[] results = Database.insert(permissionSetAssignmentsList, false);
                    for(Database.SaveResult result : results) 
                        {    
                            if(result.isSuccess()) 
                            {
                                System.debug('Successfully inserted User : ' + result.getId());
                            } 
                            else 
                            {
                                for(Database.Error error : result.getErrors()) 
                                {
                                    System.debug('Error Status : ' + error.getStatusCode() + ' : ' + 'Error Fields : ' + error.getFields());
                                }
                            }
                         }
                }
      catch(DmlException e)
        {
             System.debug('The following exception has occurred: ' + e.getMessage()); 
        }
  }
//============================================================================================================================================================    
  
    public static void DisplayInfo()
    {      
             System.debug('firstName : '+ firstName);
            System.debug('lastName : '+ lastName);
            System.debug('WorkerType : '+ WorkerType);
            System.debug('EmployeeType : '+ EmployeeType);
            System.debug('Position : '+ Position);
            System.debug('Manager : '+ Manager);
            System.debug('ManagerID : '+ userManagerId);
            System.debug('EmployeeID : '+ EmployeeID);
            System.debug('Company : '+ Company);
            System.debug('Division : '+ Division);
            System.debug('Location : '+ Location);
            System.debug('Department : '+ Department);
            System.debug('Email : '+ Email);
            System.debug('Alias : '+ Alias);
            System.debug('UserName : '+ UserName);
    }

}

getting this error while navigating to record page throug view action. "This page has an error. You might just need to refresh it. First, would you give us some details? (We're reporting this as error ID: 1773372238)"

Can you please help me to find the bug

.js:-


import { LightningElement, track, api } from 'lwc';
import getplayer from '@salesforce/apex/playerdemo.getplayer';
import assignclubcaptain from '@salesforce/apex/playerdemo.assignclubcaptain';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import {NavigationMixin} from 'lightning/navigation';
const actions=[
                 {label:'Assign',name:'assign'},
                 {label:'View',name:'view'},
]
const columns=[
                 {label:'Player Name',fieldName:'Name'},
                 {label:'Player Id',fieldName:'Id'},
                 {
                    type:'action',
                    typeAttributes : {rowActions:actions},
                },
]
export default class Datatablewithrawaction extends LightningElement {
   @track data=[];
   @track columns=columns;
   @track buttonvalue='Show';
   @track cardvisible=false;
   @api recordId;
   @track playerdata=[];
   
   
   connectedCallback(){
    getplayer({fid:this.recordId})
    .then(result=>{
        this.data=result;
    })
    .catch(error=>{
    })
   }
   
   handleclick(event){
       const lab=event.target.label;
       if(lab==='Show'){
        this.cardvisible=true;
        this.buttonvalue='Hide';
       }
       else if(lab==='Hide'){
        this.cardvisible=false;
        this.buttonvalue='Show';
       }
   }
   handleRowAction(event){
    const actionName=event.detail.action.name;
    const row=event.detail.row;
    switch(actionName){
        case'assign':this.assignCaptain(row);
        break;
        case'view' :this.navigateToPlayerRecordPage(row);
        break;
        default:
    }
   }
   assignCaptain(currentRow){
     const selectedRow= currentRow;
     assignclubcaptain({lwcrowid:selectedRow.Id})
     .then(result=>{
        this.playerdata=result;
     })
     this.showSuccessToast();
     window.location.reload;
   }
   showSuccessToast(){
         const event= new ShowToastEvent({
            label:'Record Updated',
            message:'Captain assignment successfully',
            variant:'success',
            mode:'dismissable'
         });
         this.dispatchEvent(event);
   }
   navigateToPlayerRecordPage(rowData){
      const player= rowData;
      this[NavigationMixin.Navigate]({
        type: 'standard_recordPage',
        attribute:{
                  recordId:player.Id,
                  actionName:'view'
        }
      })
   }
}
===============================================================
.html:-

<template>
    <lightning-button variant="brand" label={buttonvalue} onclick={handleclick}></lightning-button>
    <template if:true={cardvisible}>
           <lightning-card title="Players Name">
                  <lightning-datatable  key-field="id"
                                        data={data}
                                        columns={columns}
                                        onrowaction={handleRowAction}
                                        hide-checkbox-column></lightning-datatable>
           </lightning-card>
    </template>
</template>

CONTROLLER:
public class actual {
   ID myID {get;set;}
   public List<Account> getAccounts() {    
        List<Account> results = Database.query(
            'SELECT Id, Name,AccountNumber, AnnualRevenue,value__c FROM Account');
        return results;
   }
   public void opp(){
        Id IdOfMember = this.myID;
        System.debug(IdOfMember);
   }
}
VF PAGE:
<apex:page controller="actual" docType="html-5.0" extensions="actual">
    <apex:form >
    <apex:pageBlock >
    <apex:pageBlockTable value="{! accounts }" var="acc" >
        <apex:column >
            <apex:actionSupport action="{!opp}">
                  <apex:param assignTo="{!myID}" value="{!acc.ID}" />
               </apex:actionSupport>
            <apex:commandButton action="{!opp}" reRender="" value="create opp">
            </apex:commandButton>
        </apex:column>
        <apex:column value="{! acc.id }"/>
        <apex:column value="{! acc.AccountNumber }"/>
    </apex:pageBlockTable>
    </apex:pageBlock>
    </apex:form>
</apex:page>

clicking the add opportunity is error. system debugs' null. its sending ID as null from vf page always and not the id i link.
<apex:actionSupport> and <apex:param> are not linking dynamic parameters in table.
HELP!!!

Below is my program :- 

@RestResource(URLMapping='/SendEmailForOTP/*')
global class WordpressIntegrationForEmail {
    
    @HTTPPOST
    global static FinalReturnWrapper SendEmailMsg(string email , string otp,string mob,boolean send_otp_if_exists)
    {
        
        FinalReturnWrapper returnResponse = new FinalReturnWrapper(); 
        cls_data objData = new cls_data();
        contact_data cobjData = new contact_data();
        string failed = 'Email not exist';   //Need to create custom label
        string success = 'Email successfully sent to email address' ;//Need to create custom label
        list<contact> conList = [Select id,Do_Not_Mail__c,Email_Verification_Status__c, Email_Verification_Status_Date__c from contact where email =: email Limit 1];
        
        if(conList.size() > 0 )  // If the email id is exist then ...
        {
            objData.contact_exists = true;
            
            for(contact c : conList)
            {
                objData.contact_id =c.id;
                cobjData.name=c.Name;
                if(c.Do_Not_Mail__c == false && c.Email_Verification_Status__c == null && c.Email_Verification_Status_Date__c == null)
                {
                    
                    OtpViaEmail.sendEmail(email,otp);
                    objData.otp_sms_sent = true; 
                    objData.otp_email_sent = true;
                    
                }
                
            }
            returnResponse.obj = objData;
            returnResponse.cobj= cobjData ;
            return returnResponse;
            
        }
        else    // If the email id not exist then...
        {
            if(send_otp_if_exists ==false )
            {
                OtpViaEmail.sendEmail(email,otp);
                objData.otp_sms_sent = true; 
                objData.otp_email_sent = true;
                
                
                return returnResponse;
            }
            
            
        }
        
    }
    
    global class FinalReturnWrapper {
        
        public cls_data obj ;
        public contact_data cobj;
        
    }
    public class cls_data {
        
        public boolean contact_exists;
        public boolean otp_sms_sent;
        public boolean otp_email_sent;
        public string contact_id;
        
    }
    
    public class contact_data {
        public string name;
        
        
    }
    
    
}


See here i need to return FinalReturnWrapper but when i called this from postman so getting error as parser error.

So can someone please let me know how can I change the response to json file. Please guid me the code.

Request sample body :
 "email": "email@email.email",
    "firstName": "test",
    "lastName": "test",
 

Can someone please help? to implement this api.
  • November 24, 2022
  • Like
  • 0
I am trying to Pull up List of Service Appointments related to accounts however unable to get result as I keep geeting error .

Here is what I have Tried :-

A) SELECT ID , Name, (SELECT FSL__Service_Appointment__r.AppointmentNumber, FSL__Service_Appointment__r.SchedStartTime FROM FSL__Service_Appointment__r WHERE Status = 'Scheduled'  ORDER BY SchedStartTime ) FROM Account GROUP BY ID

B) SELECT ID , Name, (SELECT AppointmentNumber, SchedStartTime FROM ServiceAppointment WHERE Status = 'Scheduled'  ORDER BY SchedStartTime ) FROM Account GROUP BY ID

Both throws an Error Unable to Undertand the relationship. 
Hi All,

I am trying to get the object prefix of Parent objects from child object.
In Case, I have the lookup to Opportunity and 2 custom objects. Here In my scenario, I am trying to create 2 records if an email is sent out to the customer. So, If an email is sent related to Opportunity object, my custom object field need to populate only opportunity id. Similarly with other objects should populate the caseid and that objectid.
I have written my code something like this.
 for(Case cs : Trigger.New){
        
        if(cs.Email_Template__c != Null && cs.Email_Template__c != ''){
            
            e = new EmailNotifications();
            e.CaseId= cs.id;
            e.OpporunityId = cs.Opportunity__c;
            e.EngagementId = cs.Engagement_ID__c;
            e.SessionId = cs.Session_ID__c;
            EmailList.add(e);            
        } 
        
    }
        if(EmailList.size()>0){
            CaseHandler.sendEmail(EmailList,MapEmailTemplate);
        }
public static void sendEmail(List <EmailNotifications> EmailList ,Map <String , CaseEN__c > MapParentEmailTemplate){
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        List<Email_Notification__c> reminderNotification = new List<Email_Notification__c>();
        List<Email_Notification__c> updatereminderNotification = new List<Email_Notification__c>();
Map<Id, Id> map_Formfields = new Map<Id, Id>();
        
        for(EmailNotifications en:Emaillist){
           
            string myIdPrefix;
            myIdPrefix = String.valueOf(en.CaseId).substring(0,3);
            if(myIdPrefix == '006'){
            map_Formfields.put(en.CaseId,en.OpporunityId);
            }
            if(myIdPrefix == 'a00'){
                map_Formfields.put(en.CaseId,en.EngagementId);
            }
            if(myIdPrefix == 'a05'){
                map_Formfields.put(en.CaseId,en.SessionId);
            }
            Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {'abc@abc.com'};
                system.debug('toAddresses' +toAddresses);
            mail.setToAddresses(toAddresses);
            mail.setSubject('Hi');
            system.debug('hi');
            mail.setSenderDisplayName('Hi');
            system.debug('xyz');
           
            String body = 'Dear ' + cas.ContactEmail + ', ';
            body += 'First mail';
            system.debug('body'+body);
            mail.setHtmlBody(body);
            mail.setWhatId(cas.Id);
            mails.add(mail);
           
            List<Messaging.SendEmailResult> list_mr =Messaging.sendEmail(mails);
             Integer i=0;
            for(Messaging.SendEmailResult ser : list_mr){
                if(ser.isSuccess()){
                    Messaging.SingleEmailMessage maill = mails[i];
                    Id caseId = maill.getwhatId();
                    system.debug('caseId'+caseId);
                    Id ObjId = map_Formfields.get(caseId);
                   ManageEmailNotification( etname , myIdPrefix , ObjId,caseId,Emaillist);
                }
            }
             public static void ManageEmailNotification(String EmailTemplateName , String ObjectType , String ObjectId , Id caseId,List <EmailNotifications> EmailList){
                   list<Email_Notification__c> notificationlist = new list<Email_Notification__c>();
                List<Email_Notification__c> reminderNotification = new List<Email_Notification__c>();
                List<Email_Notification__c> updatereminderNotification = new List<Email_Notification__c>();
                for(EmailNotifications en : EmailList){
                    if (ObjectType == '006') 
                {
                     en.OpporunityId = ObjectId;  
                } 
               if (ObjectType == 'a00') 
                {
                     en.EngagementId= ObjectId;  
                } 
                if (ObjectType == 'a05')
                {
                    system.debug('ObjectType'+ObjectType);
                    en.SessionId = ObjectId; 
                    system.debug('ObjectId'+ObjectId);
                   system.debug('ObjectId'+en.SessionId); 
                }
            /*After Sending the Scheduled Email , Details will be updated to  Email Notification Object*/ 
            Email_Notification__c em= new Email_Notification__c();
            if(en.ScheduledFlag == False){
                system.debug('scheduled flag'+en.ScheduledFlag);
                if(en.OpporunityId != null)
                             {
                                 em.opportunity__c = en.OpporunityId;
                             }
                             else if (en.SessionId != NUll){
                                 em.Session__c = en.SessionId;
                             }
                             else if (en.EngagementId != NULL){
                                 em.Engagement__c = en.EngagementId;
                             }
                em.Case__c = en.CaseId; 
                em.Status__c = 'Sent';
               
                em.Email_Template__c = en.EmailName;
                notificationlist.add(em);    
            }
            /*After Sending the Scheduled Email , Details will be updated to  Email Notification Object*/  
            system.debug('Scheduled Flag boolean'+en.ScheduledFlag);
            system.debug('EmailTemplateName'+en.EmailTemplateName);
            
            if(en.ScheduledFlag == True){
                system.debug('update ');
                Email_Notification__c updatelist = new Email_Notification__c();
                system.debug('opp id'+en.OpporunityId);
                system.debug('Email_Template__c :::'+ en.EmailName );
                
                updatelist = [select id,status__c,Sent_Date__c from Email_Notification__c where   Opportunity__c = :en.OpporunityId ];
               
                updatelist.Status__c = 'Sent';
                
                updatereminderNotification.add(updatelist);
                break;
                
            }
           
            /*Check if the any remainder emails need scheduled*/
            if(en.ParentEmail == em.Email_Template__c ){
                
                Email_Notification__c em1 = new Email_Notification__c();
                if(en.OpporunityId != null)
                             {
                                 em1.opportunity__c = en.OpporunityId;
                             }
                             else if (en.SessionId != NUll){
                                 em1.Session__c = en.SessionId;
                             }
                             else if (en.EngagementId != NULL){
                                 em1.Engagement__c = en.EngagementId;
                             }
                em1.Case__c = en.CaseId;
               
                em1.Status__c = 'Scheduled';
                system.debug('em1'+em1.Status__c);
               
                system.debug('em1'+em1.Scheduled_Date__c);
                em1.Email_Template__c = en.getParentname(en.ParentEmail).Name;
                system.debug('em1'+em1.Email_Template__c);
                
               
                reminderNotification.add(em1); 
                
                
            }
        }
        if(notificationlist.size()>0){
           
            insert notificationlist;
        }
        if(updatereminderNotification.size()>0){
           
            Update updatereminderNotification;
        }
        if(reminderNotification.size()>0){
           
            
            insert reminderNotification;
        }
    }

1) How to dynamically I pass the object Id for that particular case?
2) Is there any way I can pass the object name and get the Opportunity prefix or other custom objects?
3) How to avoid writing code multiple times?
4) How to pass id dynamically in Update query 
select id,status__c,Sent_Date__c from Email_Notification__c where   Opportunity__c = :en.OpporunityId

Please anyone help me on this?
Any help will be greatly appreciated.

Thanks,
Sirisha         
I have a batch class and I'm trying to write a test class for that batch class but the test class is not covering the execute method. Could someone please help me on this. 
global class ACMContactDocumentExpiration implements Database.Batchable<sObject>,database.stateful {

   public List<Aircraft_Training__c> AirTrn = new List<Aircraft_Training__c>();
    public List<Crew_Staff__c> Crewlist=new List<Crew_Staff__c>();
    public List<Experience__c> Exp = new List<Experience__c>();
    public List<Training__c> Trn = new List<Training__c>();
    public List<Contact> Con = new List<Contact>();
    global Database.QueryLocator start(Database.BatchableContext BC)
   {
        AirTrn = [Select Id, Name, Experience__c,Experience__r.Name, Aircraft_Rating__c, PPC_Expiration_Date__c, PPC_Date__c, Training_Date__c FROM Aircraft_Training__c WHERE PPC_Expiration_Date__c =: Date.today()+Integer.valueOf(System.label.AL_PPC_Expiration_Days)];
        Set<String> AirTrnIds = new Set<String>();
        for(Aircraft_Training__c a: AirTrn)
            {
                AirTrnIds.add(a.Experience__r.Name);
            }
            system.debug('----------'+AirTrnIds.size()); 
        
        Exp = [Select Id, Name, Contact__c, Contact__r.Id, Last_Recurrent_Date__c FROM Experience__c WHERE Name IN: AirTrnIds AND (Last_Recurrent_Date__c =: Date.today()-Integer.valueOf(System.label.Exp_Last_Recurrent_Days) OR Last_Recurrent_Date__c != null OR Last_Recurrent_Date__c =: null)];
        Set<String> ExpIds = new Set<String>();
        for(Experience__c e: Exp)
            {
                ExpIds.add(e.Contact__r.Id);
            }
            system.debug('----------'+ExpIds.size());
            
        Trn = [Select Id, Name, Contact__c, Contact__r.Id, Expiration_Date__c, Exam_Date__c, Training_Type__c FROM  Training__c WHERE Expiration_Date__c =: Date.today()+Integer.valueOf(System.label.Training_Expiration_Days) AND (Training_Type__c =: System.label.Training_Type_Intl_Procedures OR Training_Type__c =: System.label.Training_Type_RVSM)];
        Set<String> TrnIds = new Set<String>();
        for(Training__c t: Trn)
            {
                TrnIds.add(t.Contact__r.Id);
            }
            system.debug('----------'+TrnIds.size()); 
            
        Con = [Select Id, Email FROM Contact WHERE ID IN: ExpIds OR ID IN: TrnIds]; 
        Set<String> ConIds = new Set<String>();
        for(Contact c: Con)
            {
                ConIds.add(c.Id);
            }
            system.debug('----------'+ConIds.size());
        
        string query= 'Select Id, Contact__c, Contact__r.Name, Active_License__r.License_Type__c, Active_Medical__r.Medical_Type__c,  Mandate_Record_Type__c,  Contact_Record_Type__c, License_Expiration_Date__c, Medical_Expiration_Date__c,Training_Expiration_Date__c, Crew_Email__c from Crew_Staff__c WHERE Contact__r.Id IN : ConIds';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Crew_Staff__c> scope) {
        List<Crew_Staff__c> newCrew = new List<Crew_Staff__c>();
        Set<Id> newCrewIds = new Set<Id>();
        for(Crew_Staff__c crew:scope) {               
        if(
            
            ((crew.Contact_Record_Type__c == 'Pilot') &&
            (crew.Mandate_Record_Type__c == 'ACM') &&
            (crew.Crew_Email__c != null)) ||
            (date.valueof(crew.License_Expiration_Date__c) == System.today()+Integer.valueOf(System.label.Date_2)) ||
            (date.valueof(crew.Medical_Expiration_Date__c) == System.today()+Integer.valueof(System.label.Medical_Expiration_Days))
          
          ) {        
            Crewlist.add(crew);
            }
            newCrewIds.add(crew.Id);
        }
          system.debug('----------'+Crewlist.size());
         
      
    }
    
    global void finish(Database.BatchableContext BC) {    
    system.debug('------>'+Crewlist.size());
 
    List<Messaging.SingleEmailMessage> maillist  = new List<Messaging.SingleEmailMessage>();
        
        if(Crewlist.size()>0) {       
            for(Crew_Staff__c crewrec:Crewlist)
            {
                // Query on OrgWideEmailAddress would set "FROM address" in the email
                OrgWideEmailAddress[] owea = [Select Id From OrgWideEmailAddress where Address = 'test@test.com'];
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                if (owea.size()>0) {
                    mail.setOrgWideEmailAddressId(owea.get(0).Id);
                }
                mail.setSubject('Pilot Documents Expiring Soon');
                mail.setToAddresses(new String[]{crewrec.Crew_Email__c});              
                mail.setReplyTo('flightops@acass.ca');
                string htmlBody;
              
                htmlBody =  '<p><span style=font-family:calibri, monospace> Dear  '+ crewrec.Contact__r.Name +', </span> </p>' +
               '<p><span style=font-family:calibri, monospace> This is a friendly reminder that you have the following documents coming due for renewal: </span></br>';
              
                          
                  String lType = crewrec.Active_License__r.License_Type__c;
                  Date lExpDate = date.newInstance(crewrec.License_Expiration_Date__c.year(), crewrec.License_Expiration_Date__c.month(), crewrec.License_Expiration_Date__c.day() );
                  String mType = crewrec.Active_Medical__r.Medical_Type__c;
                  Date mExpDate = crewrec.Medical_Expiration_Date__c;
                  htmlBody += +lType+ ' license will expire on ' +lExpDate+'</br>';
                  htmlBody += +mType+ ' medical will expire on ' +mExpDate+'</br>';
          
              for(Training__c t: Trn)
              {
                  String tType = t.Training_Type__c;
                  Date tExpDate = t.Expiration_Date__c;
                  htmlBody += +tType+' training will expire on ' +tExpDate +'</br>';
              }
              
              for(Aircraft_Training__c a1: AirTrn)
              {
                  String aName = a1.Aircraft_Rating__c;
                  Date aPPCexp = a1.PPC_Expiration_Date__c;
                  htmlBody += +aName+' aircraft training will expire on ' + aPPCexp +'</br>'; 
              }              
              
            
              htmlBody += '<p><span style=font-family:calibri, monospace> Please send clear, colour photos/scans the renewed document  prior to the expiration date. </span></p>'+
              '<p><span style=font-family:calibri, monospace>Kindest regards,</span></br>'+
              '<span style=font-family:calibri, monospace>Flight Operations </span></p>';
              mail.setHtmlBody(htmlBody);
               maillist.add(mail);         
            
            }
            Messaging.sendEmail(maillist);
        }
     }
 
@isTest
public class SendEmailToCrewJobscheduledtest {

public static testmethod void myUnitTest() {


List<Contact> con = new List<Contact>();
Contact c = new Contact(
Accident_Note__c = 'Test',FirstName = 'Test',LastName = 'test');
con.add(c);
insert con;

Test.startTest();


String CRON_EXP = '0 0 0 3 9 ? 2022';
String jobId = System.schedule('SendEmailToCrewJobscheduledtest', CRON_EXP, new SendEmailToCrewJobscheduled());
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId]; 
System.assertEquals(0, ct.TimesTriggered); 
System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime)); 


ACMContactDocumentExpiration b = new ACMContactDocumentExpiration();
Database.QueryLocator q1 = b.start(null);
Database.executeBatch(b, 200);

Test.stopTest();
}
}

 
what exactly it means..when ever i quered 
SELECT Id, MasterLabel
 FROM LeadStatus WHERE IsConverted=true,
result is only one record:

SELECT Id, MasterLabel
 FROM LeadStatus WHERE IsConverted=false:
result is 3 records:

is it like only 4 master lables we have in leadstatus
  • November 15, 2018
  • Like
  • 0

I need to share a public calandar with Comminity users. So that it will share just my avaialbility and NOT details of events with community users. It should allow community user to add time on my calandar.

Is there a paid/free app or any other solution?

Facebook is seeking a Senior Application Developer to join the Salesforce Developer team and participate in the development, integration and maintenance of Force.com applications.  Facebook has a very creative, fast-paced, innovative culture, and we like to have fun developing cool stuff!  

 

Send your resume or contact me at: 

Shawn Cook

shawn@fb.com

 

Facebook is currently building large scalable architecture and using Salesforce as our primary productivity platform.  The Salesforce Developer team works with the most state of the art technology.  At Facebook, we are passionate about the emerging Salesforce technology and offer first-hand access to the latest features and development tools!

 

This is a full-time permanent position based in our main office in Palo Alto.  Facebook offers full relocation assistance for this role and many other perks.

 

  • Technical design, configuration, development and testing of Force.com custom applications, interfaces and reports
  • Model, analyze and develop or extend persistent database structures which are non-intrusive to the base application code and which effectively and efficiently implement business requirements
  • Integrate Force.com applications to other Facebook external or internal Business Applications and tools
  • Develop UI and ACL tailored to Facebook employees and suppliers
  • Apply sound release management and configuration management principles to ensure the stability of production environments