• Lokeswara Reddy
  • NEWBIE
  • 340 Points
  • Member since 2015
  • TCS

  • Chatter
    Feed
  • 9
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 14
    Questions
  • 106
    Replies
Hi,
I'm trying to lookup an Account ID based on a text value.

Visitors who submit a form on our website can provide a "Dealer Name" value in a free text field. I want to use that value to search for an AccountID based on if the web visitor provided text is LIKE an Account.Trading_Name__c.

The code is as follows:
trigger Shopify_Set_Dealer_Account on Opportunity (before insert) {
    for(Opportunity o: trigger.new){
    
        /* 
            Only look up and set a Dealer_Account__c Id value if a Dealer Name text value is present, 
            this is a CUE Rental Opp and we haven't somehow set an Id before.
            Oppty_Dealer_Name__c is a Dealer Name text value provided in forms by visitors to SC websites
        */
        
        if((o.Oppty_Dealer_Name__c != NULL) && (o.Name.contains('CUE Rental') && (o.Dealer_Account__c == NULL))){
        
            // Construct SOQL query as a string variable first, as Apex doesn't make it easy to use LIKE %<variable>% syntax
            string Query = 'SELECT Id from Account WHERE Trading_Name__c LIKE' + '/%' + o.Oppty_Dealer_Name__c+ '/%' + 'LIMIT 1';
            
            // Execute the query
            Account[] DealerAccount = Database.query(Query); 
            
            /* 
                Only assign the found Dealer Account Id if we were able to match the website-provided Dealer Name value to a Dealer Account 
                Trading Name value, otherwise we'll get an error when we try to access the array element
            */
            if (DealerAccount.size() == 1) {
                o.Dealer_Account__c = DealerAccount[0].Id;
            }
            
        }
    }
}
However, I get the following error when this trigger is executed:
Shopify_Set_Dealer_Account: execution of BeforeInsert caused by: System.QueryException: line 1:49 no viable alternative at character '%' ().
I'm assuming this relates to lines 13 or 16.
I've searched online a lot for this problem and followed advice I'd seen about constructing the query first, but I'm having no joy.
Any advice?
Thanks,
Ross
 
I have the following code.  I would like to replace the CreatedBy.Name field with some text when it matches and automated account we have.

What would be the best way to replace this, send it to a list so I can then use that list in my pageBlockTable.
 
public my_Test_Apex(ApexPages.StandardController stdController)
{
       this.myCase = (Case)stdController.getRecord();
        
        //get case comments
        Case com = [select Id, CaseNumber,(select ParentId,CommentBody,CreatedDate,CreatedBy.Name from CaseComments ORDER BY CreatedDate DESC) from Case where Id =: ApexPages.CurrentPage().getParameters().get('Id') ];
        caseCommentList = new List<CaseComment>();
        for(CaseComment cs : com.CaseComments)
        {
           if(cs.CreatedBy.Name.contains('NameToReplace'))
           {
               //replace 'NameToReplace' with 'Support Representative'
           }
           else
           {
               caseCommentList.add(cs);
           }
            
        }       
}

Thanks.
Hey,

I'm currently working on implementing a time off booking system for our internal Salesforce org.
We have two different Business Hours records which reflect our two different working hours for employees - M2F - Monday to Friday, and M2T - Monday to Thursday.
We don't take holidays by the hour, we take them either in half days, or full days, so those business hours records are used purely for the holiday booking system, and to make things easier, are set to 24Hrs for each day worked in that particular record.

My idea was to use an APEX trigger to calculate the difference in business hours based on the particular users specified (at the User object level) business hours record - this works fine, however, if I try to create a 'Time Off' record that is 4 days in duration, the returned 'Number of Days' from my BusinessHours.diff calculation(s) is 3.96 days, not 4.

See my method here:
 
public static void calculateDays(List<Time_Off__c> timeOff){
        List<Time_Off__c> tu = new List<Time_Off__c>();
        for(Time_Off__c t:timeOff){
            Time_Off__c to = new Time_Off__c(Id=t.Id);
            String userBh = [SELECT Id, Business_Hours__c FROM User WHERE Id = :t.User__c LIMIT 1].Business_Hours__c;
            Id bhId = [SELECT Id, Name FROM BusinessHours WHERE Name =: userBh].Id;
            Long diffMs = BusinessHours.diff(bhId, t.Start_Date__c, t.End_Date__c);
            Double hours = diffMs/3600000;
            Double days = hours/24;
            to.Number_of_Days__c = days;
            tu.add(to);
                }
        update tu;
        
    }


Any help would be massively appreciated :)

Thanks,
Oli 

Hello,

I have the following error message:
Error: Illegal assignment from Schema.SObjectField to Id
when I try to update lookup field in apex.

Here is the method implementation:
public void addTaskCommentHistory(Task task) {
    if(task == Null) {
            return;
    }

    String newValue = task.Description;

    if(newValue != Null && !newValue.equals('')) {
        String taskId = task.Id;
        String fieldName = 'Comments';
        String oldValue = '';

        Task_History__c taskHistory = new Task_History__c();
        taskHistory.Task_ID__c = taskId;
        taskHistory.Field_Name__c = fieldName;
        taskHistory.Old_Value__c = oldValue;
        taskHistory.New_Value__c = newValue;


        String lastModifiedBy = task.LastModifiedById; 
        String userName = '';
        // the query will return no more than one row because the data is extracted by user id
        List<User> listOfUsers = [SELECT Name FROM User where Id = :lastModifiedBy];
        if(listOfUsers.size() > 0){
            User user = listOfUsers.get(0);
            userName = user.Name;
        }

        taskHistory.User__c = user.Name;

        insert taskHistory;
    }    
}

When I try to add
user.Name
to
taskHistory.User__c
in
taskHistory.User__c = user.Name;
I get the "Error: Illegal assignment from Schema.SObjectField to Id" message.

Please advise how to update the User__c lookup field without the error message?


 
Currently, we query for OpenEvents using a filter on the EventDate.  How can I also filter based on the date the email was sent to the subscriber?  For example, I want to query for OpenEvents from within the past week, but exclude any for emails that were sent over a month ago.
 
Hi ,

i am getting error from managed package apex trigger. So i am uanble to save my record. How to stop the trigger form managed package

Regards,
Vinothini
Hi, I am working for a client that wants to get documents uploaded to their SalesForce account via REST API and submit them to a seperate app using our platform. Is there a way to get to said uploaded document and "download" it through REST?
Hello,
When i m going to create a quote from opportunity the related Account Id is null in Lightning Experience 
But for the same use case the classic version has account Id.

I over come this issue by using the opportunity Id to fetch Account Id.

Is there any specific reason why its not comming in Lightining ?
I'm building an integration with a SOAP API v1.2, so I'm not able to use WSDL2Apex and I must create my own Request, and send it using Http.send(), storing the endpoint, user and password in a Named Credential.

​This SOAP API uses the standard PasswordDigest security in the XML header, and as this kind of authentication is not managed automaticaly by Salesforce (I do not understand why, it is an standard used frecuently), I must build the XML security header manually by encrypting the nonce + timestamp + password.

As salesforce merge the fields after the Http.send(), I need to obtain the password previously to encrypt it and build the XML header, so I'm not able to use '{!$Credential.Password}' and SOQL do not allows access to ii either.

So, how can I access the Named Credential password to build the XML security header node?
Does SandboxPostCopy Interface supports batch jobs?
How can we test this without deploying the code in production and refresh sandbox to do so?
I have one text fields 

input ::::Feeler - 62, Exciter - 58, Bottom-Liner - 58, Detailer - 54


and in a new field i only want to see output as :::Feeler - 62    how can i achieve using formula field?? 
I have to cover "sendEmailOnSubmission" method in my test class, please suggest how to cover this method.
class CableDealRequestTriggerHandler is handler class of a trigger.

public class CableDealRequestTriggerHandler{  
  //Method for sending Email to BA/DL 
    public void sendEmailOnSubmission(List<Cable_Deal_Request__c> cdrList,Map<id,Cable_Deal_Request__c> cdrOldMap,Map<Id,Deal_Request_Header__c> headerMap){
        
        try{
            
        //sending Email to BA/DL
        
        for(Cable_Deal_Request__c cdr : cdrList){
            system.debug('Cable Deal Request==>>>' + cdr);
            system.debug('If stateemnt==> ' + cdr.Cable_Deal_Status__c + '   ' + cdrOldMap.get(cdr.id).Cable_Deal_Status__c);
            if((cdr.Cable_Deal_Status__c == 'Submitted' || cdr.Cable_Deal_Status__c == 'Submitted to BA') && (cdrOldMap.get(cdr.id).Cable_Deal_Status__c=='Pending Finance Approval' || cdrOldMap.get(cdr.id).Cable_Deal_Status__c=='Open')){
                List<String>ccList = new List<String>();
                List<String>toList = new List<String>();
                system.debug('Enter after submitted');
                
                //toList.add(headerMap.get(cdr.Deal_Request_Header__c).user__r.email);
                
                if(headerMap.get(cdr.Deal_Request_Header__c).createdby.email != null)
                    ccList.add(headerMap.get(cdr.Deal_Request_Header__c).createdby.email);
                if(headerMap.get(cdr.Deal_Request_Header__c).Cable_Requested_By__r.email != null)
                    ccList.add(headerMap.get(cdr.Deal_Request_Header__c).Cable_Requested_By__r.email);
                for(Cable_Deal_Request_Creative_Executive__c cdre : headerMap.get(cdr.Deal_Request_Header__c).Cable_Deal_Request_Creative_Executives__r){
                    ccList.add(cdre.Creative_Executive__r.email);
                }
                
                if(cdr.Cable_Network_Platform__c.contains('Freeform')){
                    DisneyCableDls__c dsCable = DisneyCableDls__c.getInstance('Freeform DL');
                    toList.add(dsCable.DL_Email__c);

                }
                else{
                    DisneyCableDls__c dsCable = DisneyCableDls__c.getInstance('DCWW Dl');
                    toList.add(dsCable.DL_Email__c);
                }
                system.debug('List of reciepient==>> ' + ccList +'   ' + toList);
                
                contact tstCont = new Contact();
                tstCont.lastName='TEst';
                tstCont.email = 'test@test.com';
                insert tstCont;
                
                EmailTemplate templateId = [Select id from EmailTemplate where DeveloperName = 'Cable_Deal_Submitted_Email_Template' limit 1];
                
                List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setToAddresses(toList);
                mail.setTemplateID(templateId.Id); 
                mail.setccAddresses(ccList);
                mail.setTargetObjectId(tstCont.id);
                mail.setWhatId(cdr.id);
                mail.setSaveAsActivity(false);
                allmsg.add(mail);
                system.debug('Email Information ==>>' + mail);
                Messaging.sendEmail(allmsg); 
                delete tstCont;    
                
            }
        }
        }catch(Exception e){
            //string error = ExceptionLogger.createExceptionsRecord(e.getMessage(), 'CableDealRequestTriggerHandler', e.getStackTraceString());
            //throw new AuraHandledException(error);
           saveExceptionLogs(e.getMessage(),'CableDealRequestTriggerHandler',e.getStackTraceString());
        }
        
    }
}    
Hi Everyone,

I want to create Opportunity line item when I update Opportunity Stage to "Closed Won".

It works for when create new Opportunity but not works when I update an existing Opportunity.

It shows below error
FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry is in a different pricebook than the one assigned to the opportunity)
Thanks,
Vignesh

Hi,

Trying to create a trigger that will populate a field in the opportunity line items before save, however my trigger only populates the opportunity line item once saved. Both fields in the trigger are in the opportunity line item object, is that the issue? 

The reason to why I want to have the field populated before save is to be able to have a field dependency based on product information. If I could use "Product/PricebookEntry" as controlling field for my custom field Services__c that would solve my issue. But as that's not possible, I want to clone the product value to a picklist before save, and use that picklist for the field dependency. 

The oli.Product_Family__c field is a formula field referencing a field in the related product (formula field: TEXT (PricebookEntry.Product2.Family) ).


trigger OLIAUTOFILL on OpportunityLineItem (before insert, before update) {

for(OpportunityLineItem oli: Trigger.new)
    {
     // If you want this for update operation, then check update as well in the below if statement
     if(trigger.isBefore && trigger.isInsert)
     oli.Test_Type__c = oli.Product_Family__c;
    }
}

Hi, is there a way of accessing the data stored in Spring 15' Named Credentials from apex? For example the username, password and endpoint link?