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

  • Chatter
    Feed
  • 9
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 14
    Questions
  • 106
    Replies
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?


 
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
Our organizations with work multi-level hierarchies of Account.
I was wondering if anyone knows how one can create a script Or SOQL to find out the "Ultimate Parent" and store the result in a field.

Thanks
1) There is a multiselect picklist field 'BU_Specialty_Name__c' with values "A","B","C" & "R". The condition is that, If user selects any value along with "R", an error should occur saying that 'R should be selected alone'. For this I have implemented a Validation rule as below: 
IF(OR(AND(INCLUDES(BU_Specialty_Name__c,"R"),INCLUDES( BU_Specialty_Name__c,"A")),
      AND(INCLUDES(BU_Specialty_Name__c,"R"),INCLUDES( BU_Specialty_Name__c,"B")),
      AND(INCLUDES(BU_Specialty_Name__c,"R"),INCLUDES( BU_Specialty_Name__c,"C"))
      ),
  true, false)
It is working fine for the environment(Sandbox) which has "A","B","C"&"R" values for 'BU_Specialty_Name__c'.
2) But now, the requirment is that, For the other environment(Prod),  'BU_Specialty_Name__c' has few more values "A","B","C","D", "E" & "R". 
    Here also same condition should be given that is, If user selects any value along with "R", an error should occur.
   And we cannot overwrite Validation rule depending upon environment always.

  So,Is there any alternative to throw an error When user selects any value along with "R", instead of calling all the values as I did above?
 The idea should work for all environments independant on other multiselect picklist values.

Any kind of suggestion is accepted. Thanks in advance!
Hi,
I am tring to redirect users to Opportunity tab after saving the record. Wanted to construct the generic URL instead of hard coding the value, let me know what the generic URL should be so that it wroks in produciton too.
HI All,

Depending on country field i want to update manager field on account object.
I have maintain country name and manager detains in custom setting object.

Now i want to get the data from custom setting. 

I have completed this task through trigger , using  "before insert and before update" event.

But i want to complete this task through trigger , using "after insert and after update" event

I have tried this way  :

trigger StateManager1 on Account(after insert, after update)
 {
     Map<String ,StateManager__c> mp=StateManager__c.getAll();
     Set<String> bcKeySet = new Set<String>();
     bcKeySet = mp.keyset();
     Set<Id> setIds=new Set<Id>();
     List<Account> lisAcc=[select id ,name ,Manager__c ,Country__c  from Account where id In : trigger.newMap.keyset()];
     List<Account> acc=new List<Account>();
     for(Account a : lisAcc)
     {
         if(bcKeySet.contains(a.Country__c ))
         {
       
             if(Trigger.isupdate && mp.get(a.Country__c).ManagerName__c!=a.Country__c)
             {
                 a.Manager__c =mp.get(a.Country__c).ManagerName__c;
                 acc.add(a);
             }
             if(Trigger.isinsert)
             {
                 a.Manager__c =mp.get(a.Country__c).ManagerName__c;
                 acc.add(a);
             }
         }
     }
     Update acc;
     
 }
 
 
But i am getting below error :

Error:Apex trigger StateManager1 caused an unexpected exception, contact your administrator: StateManager1: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0012800000R91HiAAJ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, StateManager1: maximum trigger depth exceeded Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi] Account trigger event AfterUpdate for [0012800000R91Hi]: []: Trigger.StateManager1: line 26, column 1

Please help me how will complete by using after events

Thanks
​Satheesh
I'm new to Salesforce and I was wondering why do I get the following error for my code. if you can please write me back code would be greatfully aprreciated.

API class 
public class CheckbookAPI {
    
    // DigitalCheck__APIConfig__c is a custom setting object that stores the API Keys
    public static DigitalCheck__APIConfig__c Config = DigitalCheck__APIConfig__c.getOrgDefaults();

    public CheckbookAPI()
    {
    }

    public static String getChecks() {
        HttpRequest req = CheckbookAPI.getHttpRequest('GET', '/transactions');
        return CheckbookAPI.getHttpResponse(req);
    }    
    public static String createCheck(String email, Decimal amount, String firstName, String lastName, String semail, String description) {
        HttpRequest req = CheckbookAPI.getHttpRequest('POST', '/send_check');

        Map<String,Object> mapParams = new Map<String,Object>();
        mapParams.put('email', email);
        mapParams.put('amount', amount);
        mapParams.put('first_name', firstName);
        mapParams.put('last_name', lastName);
        mapParams.put('sender_email', semail);
        mapParams.put('description', description);
        req.setBody(JSON.serialize(mapParams));
        return CheckbookAPI.getHttpResponse(req);
    }
    

    private static String getHttpResponse(HttpRequest req) {
        Http http = new Http();
        HTTPResponse response = http.send(req);
        return response.getBody();
    }
    
    private static HttpRequest getHttpRequest(String Method, String Path) {
        // Initialize the request
        HttpRequest req = new HttpRequest();
        
        // Build the selected elements
        String SelectedElements = '';
        
        
        // Set the method
        req.setMethod(Method);
        SelectedElements += Method;
        
        // Set the Content-Type header
        if (Method == 'POST') {
            SelectedElements += 'application/json';
            req.setHeader('Content-Type', 'application/json');
        }
        
        // Set the endpoint
        String CompletePath = '/' + CheckbookAPI.Config.DigitalCheck__VersionAPI__c + Path;
        SelectedElements += CompletePath;
        req.setEndpoint(CheckbookAPI.Config.DigitalCheck__ServerURL__c + CompletePath);

        return req;
    }
    


}

API CALL class
 
global with sharing class DigitalChecksChargeController {

    public DigitalChecksChargeController(ApexPages.StandardController stdController)
    {

    }    
    
    @RemoteAction
    public static String processCharge() {
        return '200'; // Simulate the status code of the <charge> request
    }
    
    @RemoteAction
    public static String createCheck(String email, Decimal amount, String firstName, String lastName, String semail, String description) {    
        return CheckbookAPI.createCheck(email, amount, firstName, lastName, semail, description);
    }    
}

TEST class
@isTest
public class CheckbookAPI_UsingStaticResources {
    public testmethod static void testWS() {
        String testBody = 'This is a test :-)';
 
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('Test_WS');
        mock.setStatusCode(200);
        Test.setMock(HttpCalloutMock.class, mock);
 
        CheckbookAPI  callout = new CheckbookAPI ();
        HttpResponse resp = callout.getChecks();  // <== GETTING ERROR : Static methods cannot be invoked through an object instance: getChecks()
        
        //System.assertEquals(200, resp.getStatusCode());        
        //System.assertEquals(resp.getBody(), testBody);
    }
}


So I'm getting 
Static methods cannot be invoked through an object instance: getChecks()

 
Their is one custom field  NAME on lead object consist of two string (first and last name) seperated by space . Their are two standard field on lead object
1. First Name, 2. Last Name.  
I am updating first string of NAME field(Custom field) in the Last Name standard field and second string of NAME field in First Name of Standard Field, using workflow+ field update.
 User-added image
 
Update Last Name using Formula: LEFT( Name__c ,FIND(" ", Name__c ))
Updat First Name using Formula : MID( Name__c , FIND(" ", Name__c ), LEN(Name__c ) )
 
Now My Question is If second string in NAME string is absent then  first name field should be updated to blank because it optional field. How i can use the formula; Please Suggest
 
Note: In custom name field i'm inserting data from web to lead.
Hello, 

I have a custom object (ObjectA__c) and want add a custom field which will populate with a checkbox if true if IsActive  is checked on the standard User object. 

When I attempt to create a custom text formula field in ObjectA__c named ActiveUser__c with the following syntax in the Formula Option field, I receive the below error message, any ideas? 
$User.IsActive

Error: Formula result is data type (Boolean), incompatible with expected data type (Text).
Is it possible to have Toast message  on Opportunity wheneve new product with quanitty more than 1000 is added or edited. The ask is to show the warning message only once when product is updated or added.
I have seen toast messages which appears every time the record is accessed, if conditions met. But how can we just show the toast message on child record DML operations.
As per my understanding, there won't be any DML operations on Opportunity when line items are edited or updated.
Any thoughts.. 
Hi All,

Any best practices around handling CPU time out error for test classes?
The error from the deployment really doesn't give any clue on why it is taking too long for test class execution.

Regards
Lokesh
Hi All,

We are trying to integrate with external system, there is a complex type defined to pas name-value pair as part of tag
               
<Organization>
      <Unit Type="Legal Entity">XYZ1</Unit>
</Organization>
Apex generated label "Type" where we can pass avlue as "Legal Entity", but how to pass XYZ1 while invoking the service.

I believe the structure should be somethign similar to          
<Organization>
       <Unit Type="Legal Entity" Value="XYZ1" />
</Organization>
When tested via SOAPUI, request is success but the value is not being updated in the target system.

Any clue on how to solve this issue?

Thanks in advance
Any clue why I don't see new formula field when I run report? but can see while customizing the report?
- add new fields and set FLS
- update custom report type to add this new field and change the display name
- customize the report to include new field and save it
- run report, field is not visible

note that the object belongs to managed app
Does SandboxPostCopy Interface supports batch jobs?
How can we test this without deploying the code in production and refresh sandbox to do so?
Hi All,

There a VF page to search on Accounts, the page has 'Search' and 'Cancle' buttons, after filling data in search field and if you click 'Enter' button it won't work, the user has to click manually on 'Search' button, when clicked it reloads the page and shows progress bar till the resulsts displayed. 
Now there is a new requirement to have a new button 'Create New Account' in the VF page to redirect to new Account edit page by copying the data from search fields, Every thing works fine, but if user clicks 'Enter' button after filling search fields by defaults it takes the user to New account page!
Is there any way that we can controle this? on 'Enter' click it should invoke 'Search' button else NO action,

<apex:commandButton action="{!search}" value="Search" id="SearchBt" status="processingStatus" reRender="resultPanel,errorPanel"/>
<!--  <apex:commandButton action="{!search}" value="Search"/> -->
<apex:commandButton action="{!reset}" value="Reset" status="processingStatus" reRender="resultPanel,errorPanel,searchPanel"/>
<apex:commandButton action="{!redirectToNewAccountPG}" value="Create New Account"/>

I have tried Line#2, the Enter button has invoked 'Search' button, but it did not show the search bar and more over it reloads entier page and not just the search results.

Any thoughts on this? Thanks in advanc

Lokesh...



 
Hi All,

I'm under impression that Queueable class, when invoked from trigger, will be treated as a seperate transaction, similar to @future method.
Am I under wrong impression?

I have Queueable class, that will be enqued from Account trigger, where it invokes external webservice and updates few fields in Account.

It works fine when I invoke the Queueable from Trigger.isBefore update context, but it fails when invoked from Trigger.isAfter update !.
Error message : FATAL_ERROR|System.FinalException: Record is read-only

Can some one throw some light on this !?
Hi All,

I'm working on showing error message if the user try to create an accunt which already exists in the system. 

for(Account acc:duplicateAccounts){
   String recordLink = URL.getSalesforceBaseUrl().toExternalForm() + '/' + acc.Id;
   currentAccount.addError('im an html error with a <a href="http://google.com">link</a>', FALSE);
}

This is how it displayes

Need help in displaying the Link alone in the error message, any help is much appreciated !

Is this the same issue which Salesforce mentioned the issue is fixed?
https://success.salesforce.com/issues_view?id=a1p30000000T4PjAAK
 
If opportunity stage value meets the criteria then trigger fires and invokes handler code which inturn calls external webservcie, if the response from webservcie is success then update a field in Account object. 
The plan is to secure this field and there is a validation rule to prevent any user (except system admin and interface user) from updating on this field,  ( the field can not be hidden from the PG layout and there are users with permission sets to update if the field is read only on PG layout)

I was under impression that the validation rules will by pass as the field update is happending in Apex, , but it is not.

-> User updates opportunity stage value,
-> the trigger fires and invokes webservcie,
-> webservice returns success
-> Apex tries to update field on Account , this step failed as there is a validation rule to prevent user from updating the field
Any thoughts on how to resolve this?
Hi,

Need help in aligning the VF page set to window, when I try to reduce the coulmns width I do not see any change in the page width.
vf page

VF page code, 

<apex:page controller="ProductSearch" action="{!loadData}" tabstyle="Opportunity" docType="html-5.0">
 <apex:form >
 
      <apex:sectionHeader title="Choose Price Book for" subtitle="{!OptyName}" rendered="{!showPB}">
         Select a price book for this opportunity. You can add products only from a single price book. Changing a selected price book will delete all existing products from this opportunity.
         <p>Choose a price book that contains products with the same currency as the opportunity. If no products are available for the chosen currency, ask your administrator to create them.</p>
     </apex:sectionHeader>
     
     
     <apex:pageblock id="CP" title="Choose Price Book for: {!OptyName}" rendered="{!showPB}">
         <apex:pageBlockSection collapsible="false">
         <apex:selectList title="Price Book" label="Price Book" value="{!selectedPB}" size="1"> 
             <apex:selectOptions value="{!PBList}"/>
         </apex:selectList>
         
         </apex:pageBlockSection>
               <apex:pageBlockButtons location="bottom">
                 <apex:commandButton value="Save" style="width:50px" action="{!savePB}"/>
                 <apex:commandButton value="Cancel" style="width:50px" action="{!cancel}"/>
               </apex:pageBlockButtons>  
     </apex:pageblock>

 
     <apex:pageBlock title="Product Search" id="PS1" rendered="{!showSearhBlock}">
         <apex:pageBlockSection >
             
             <apex:selectList label="Product Group:" value="{!selectedPG}" multiselect="false" size="1">
                 <apex:actionsupport event="onchange" action="{!getProductGroup}" reRender="PS1, SR, WM"/>
             <apex:selectOptions value="{!BGList}" />
             </apex:selectList>

             <!--<apex:selectList label="Product Name:" value="{!selectedName}" multiselect="false" size="1">
                 <apex:actionsupport event="onchange" action="{!getProductName}" reRender="PS1, SR, WM"/>
             <apex:selectOptions value="{!NameList}" />
             </apex:selectList> -->

             <apex:selectList label="Item Type:" value="{!selectedItemType}" multiselect="false" size="1">
                 <apex:actionsupport event="onchange" action="{!getItemType}" reRender="PS1, SR, WM"/>
             <apex:selectOptions value="{!itemTypeList}" />
             </apex:selectList> 

             <apex:selectList label="Model Series:" value="{!selectedmodel}" multiselect="false" size="1">
                 <apex:actionsupport event="onchange" action="{!getModelSeries}" reRender="PS1, SR, WM"/>
             <apex:selectOptions value="{!modelSeriesList}" />
             </apex:selectList>
             
             <!--<apex:selectList label="Product Description:" value="{!selectedDes}" multiselect="false" size="1">
             <apex:selectOptions value="{!DesList}" />
             </apex:selectList> -->                                      

           <!--  <apex:selectList label="Life Cycle:" value="{!selectedLC}" multiselect="true" size="3">
             <apex:actionsupport event="onchange" action="{!getLieCycle}" reRender="PS1, SR, WM"/>
             <apex:selectOptions value="{!LCList }" />
             </apex:selectList> -->
                 
            <apex:selectCheckboxes value="{!selectedLC1}" label="Life Cycle:">
             <apex:actionsupport event="onchange" action="{!getLieCycle}" reRender="PS1, SR, WM"/>
               <apex:selectOptions value="{!LCList1}"/>
            </apex:selectCheckboxes>            
             
             <apex:inputText label="Full Product Search" value="{!productSearch}" size="75"/>
             <apex:actionregion >
                 <apex:commandButton title="Search on Search" value="Search Within Results" action="{!SearchOnSearch}" style="width:130px"/>
                 <apex:commandButton title="Search" value="Full Search" action="{!FullProductSearch}" style="width:100px"/>
             </apex:actionregion>

         </apex:pageBlockSection>
     </apex:pageBlock>
     <apex:pageBlock rendered="{!showSearchPB}" id="SR">
             <!--
             <apex:pageBlockButtons >
                 <apex:commandButton value="Select" style="width:75px" action="{!getSelectedRows}"/>
                 <apex:commandButton value="Cancel" style="width:75px" action="{!cancel}"/>
             </apex:pageBlockButtons> -->
         <apex:pageBlockSection title="Search Results">
             <apex:dataTable value="{!products}" var="wrapper" cellpadding="4" border="1" style="width:1250px">

                <apex:column style="width:20px">
               <!-- <apex:facet name="header"> <apex:inputCheckbox >
                <apex:actionSupport event="onclick" action="{!GetSelected}" onsubmit="checkAll(this)"/>
                </apex:inputCheckbox></apex:facet> -->
                <apex:inputCheckbox id="checkedone" value="{!wrapper.selected}">
                <apex:actionSupport event="onclick" action="{!GetSelected}" rerender="SP"/>
                </apex:inputCheckbox></apex:column>
             
                 <apex:column headerValue="Product Name" value="{!wrapper.prod.Model_Description_Formula__c}" style="width:290px"/>
                 <apex:column headerValue="Product Code" value="{!wrapper.prod.ProductCode}" style="width:115px"/>
                 <apex:column headerValue="Model Series" value="{!wrapper.prod.Model_Series__c}" style="width:115px"/>
                 <apex:column headerValue="Product Group" value="{!wrapper.prod.Family}" style="width:140px"/>
                 <apex:column headerValue="Item Type" value="{!wrapper.prod.CBS_Item_Type_Description__c}" style="width:140px"/>
             
             </apex:dataTable>
         </apex:pageBlockSection>
     </apex:pageBlock>


     <apex:pageBlock rendered="{!showSearchPB}" id="SP">
             <apex:pageBlockButtons rendered="{!showButtons}">
                 <apex:commandButton value="Select" style="width:75px" action="{!getSelectedRows}"/>
                 <apex:commandButton value="Cancel" style="width:75px" action="{!cancel}"/>
             </apex:pageBlockButtons>
         <apex:variable value="{!0}" var="rowNum"/>    
         <apex:pageBlockSection title="Selected Products">
             <apex:dataTable value="{!selectedSearchProducts}" var="wrapper" cellpadding="4" border="1" style="width:1250px">

                <apex:column style="width:20px">
               <!-- <apex:facet name="header"> <apex:inputCheckbox >
                <apex:actionSupport event="onclick" action="{!GetSelected}" onsubmit="checkAll(this)"/>
                </apex:inputCheckbox></apex:facet> -->
                <apex:commandLink value="Remove" style="color:blue" action="{!RemoveSelected}" reRender="SP">
                    <apex:param value="{!rowNum}" name="rowToRemove" assignTo="{!rowToRemove}"/>
                </apex:commandLink>
                <apex:variable var="rowNum" value="{!rowNum + 1}"/>    
                <!-- <apex:inputCheckbox id="checkedone" value="{!wrapper.selected}">
                </apex:inputCheckbox> --> </apex:column>
             
                 <apex:column headerValue="Product Name" value="{!wrapper.productName}" style="width:290px"/>
                 <apex:column headerValue="Product Code" value="{!wrapper.productCode}" style="width:115px"/>
                 <apex:column headerValue="Model Series" value="{!wrapper.modelSeries}" style="width:115px"/>
                 <apex:column headerValue="Product Group" value="{!wrapper.productGroup}" style="width:140px"/>
                 <apex:column headerValue="Item Type" value="{!wrapper.itemType}" style="width:140px"/>
             
             </apex:dataTable>
         </apex:pageBlockSection>
     </apex:pageBlock>


     
     <apex:pageBlock id="WM" rendered="{!isWarning}">
         <apex:outputText value="No Products found with the search criteria"></apex:outputText>
         
     </apex:pageBlock>

     <apex:sectionHeader title="Add Products to" subtitle="{!OptyName}" rendered="{!showResultPB}">
         Add products to this opportunity from <strong>{!PricebookName}</strong> price book
     </apex:sectionHeader>
 
     <apex:pageblock id="IB" rendered="{!showResultPB}">

             <apex:pageBlockButtons >
                 <apex:commandButton value="Save" style="width:75px" action="{!save}"/>
                 <apex:commandButton value="Cancel" style="width:75px" action="{!cancel}"/>
             </apex:pageBlockButtons>     

         <apex:dataTable value="{!selectedProducts}" var="wrapper" cellpadding="4" border="0" style="width:1250px">
            <apex:column headerValue="Product Name">
                <apex:outputText value="{!wrapper.productDescription}"/>
            </apex:column>    
            <apex:column headerValue="Line Description">
                <apex:inputText value="{!wrapper.lineDescription}"/>
            </apex:column>
            <apex:column headerValue="Sales Price">
                <apex:inputText value="{!wrapper.salesPrice}"/>
            </apex:column>
            <apex:column headerValue="Quantity">
                <apex:inputText value="{!wrapper.quantity}"/>
            </apex:column>

            <apex:column headerValue="Gross Margin Amount ">
                <apex:inputText value="{!wrapper.grossMarginAmount}"/>
            </apex:column>            
            <apex:column headerValue="Requested Delivery Date">
                <apex:input type="date" value="{!wrapper.dateValue}"/>
            </apex:column>

            <apex:column headerValue="Second Hand / Contract Renew">
                <apex:inputCheckbox value="{!wrapper.isSecondHand}"/>
            </apex:column>
         </apex:dataTable>

     
     
     </apex:pageblock>
     
 </apex:form>
</apex:page>
 
I'm working on custom product search, which is a replacement for standard product search from Opportunity (Add Product from the related list). The VF page will have couple of Select options, if you select one value from first select option then it should filter the possible values in other select options and it should display the available products as well.
I have to filter values based on pricebook entry and account currency. I'm passing these two values in the url while invoking the vf page from the search button.

The issue:
The dynamic query works when there is only one condition in the where clasuse, I'm trying to add two filter conditions in the where clause then the query returns no rows, no error/exception thrown.

Filter 1:
        String QUERY_STRING = 'select Name, ProductCode, CBS_Segment__c, Description, Family, CBS_Item_Type_Description__c, Model_Series__c, Life_Cycle_Status__c FROM Product2 ';
        String WHERE_CLAUSE = 'WHERE Id IN (SELECT Product2Id FROM PricebookEntry where Pricebook2Id =: pb2Id and CurrencyIsoCode =: currencyCode)';
QUERY_STRING += WHERE_CLAUSE;
Database.query(QUERY_STRING);


This returned values as expected

Filter 2:
        String QUERY_STRING = 'select Name, ProductCode, CBS_Segment__c, Description, Family, CBS_Item_Type_Description__c, Model_Series__c, Life_Cycle_Status__c FROM Product2 ';
        String WHERE_CLAUSE = ' WHERE Family =: selectedPG' ;
QUERY_STRING += WHERE_CLAUSE;
Database.query(QUERY_STRING);


This also returned values

When I combine both the conditions then it does not return any values.

        String QUERY_STRING = 'select Name, ProductCode, CBS_Segment__c, Description, Family, CBS_Item_Type_Description__c, Model_Series__c, Life_Cycle_Status__c FROM Product2 ';
        String WHERE_CLAUSE = 'WHERE  Id IN (SELECT Product2Id FROM PricebookEntry where Pricebook2Id =: pb2Id and CurrencyIsoCode =: currencyCode)';
WHERE_CLAUSE += ' AND Family =: selectedPG' ;
QUERY_STRING += WHERE_CLAUSE;
Database.query(QUERY_STRING);


I have tried different approaches like combiting both the conditions in the single variable and then adding to the query string, no use.

Can some one through light why this is not working? do we have any limitations on having filter condtions in dynyamic query.
Please note that the binding variables are in scope with the method and when used alone it is working, but with combination not working.
Hi,

Problem description: On click of a button on Opportunity, a request goes to third party (SOAP API), couple of fields will get updated based on the response,
When the user click on the button, a popup window will open which auto refreshes every five seconds till we gets the response and render new button, when clicked on this button it redirects to the third paty. the requiement is to show some progress till the button gets visible. I have used actionfunction feature but it is not working for me.
Any help is much appreciated.

Regards
Lokesh
Hi,
Need help in udnerstanding the error type and resolving the same.​
System.CalloutException: IO Exception: Unable to tunnel through proxy. Proxy returns "HTTP/1.0 403 Forbidden

We are trying to integrate with Perlchain CPQ machine, There is no provision for passing the user name and password in the wsdl provided by CPQ. I have followed the link and tweaked to pass these two as part of header.
http://blog.dacology.com/callouts-from-salesforce-adding-soap-headers-for-wsse-security/

I'm still getting the error, 
System.CalloutException: IO Exception: Unable to tunnel through proxy. Proxy returns "HTTP/1.0 403 Forbidden

Need help in resolving this.

//Generated by wsdl2apex

public class xsServicesOp {

        public class Security {
            public UsernameToken usernameToken;
            private String[] usernameToken_type_info = new String[]{'UsernameToken','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','UsernameToken','0','1','true'};
            private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
            private String[] field_order_type_info = new String[]{'usernameToken'};
        }
        public class UsernameToken {
            public String username;
            public String password;
            private String[] username_type_info = new String[]{'Username','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','string','0','1','true'};
            private String[] password_type_info = new String[]{'Password','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','string','1','1','true'};
            private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
            private String[] field_order_type_info = new String[]{'username','password'};
        }  
    public class CreateOpportunityPortType {
        public String endpoint_x = //'http://localhost:8010/CreateOpptyMed/1';
           (I have replace endpoint with the correct url)
                                    
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
            //instantiate the header
            public UsernameToken userToken;
            public Security Header;
            private String Header_hns = 'Security=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
            //end
        private String[] ns_map_type_info = new String[]{'http://www.test.machine/messages/opportunity/1', 'CdmMessagesOpport', 'http://www.test.machine/opportunity/1', 'CdmOpportunity', 'http://www.test.machine/services/opportunity/1', 'CdmServicesOpport', 'http://www.test.machine/common/1', 'CdmCommon', 'urn:codelist:ISO639-2-2002', 'CdmCodelist', 'http://www.test.machine/customer/1', 'CdmCustomer'};
        public CdmMessagesOpport.CreateOpportunityResponseMessageType CreateOpportunity(CdmOpportunity.OpportunityType Opportunity,CdmOpportunity.AccountType Account,CdmOpportunity.ProductsType[] Products) {
            CdmMessagesOpport.CreateOpportunityRequestMessageType request_x = new CdmMessagesOpport.CreateOpportunityRequestMessageType();
            request_x.Opportunity = Opportunity;
            request_x.Account = Account;
            request_x.Products = Products;
            CdmMessagesOpport.CreateOpportunityResponseMessageType response_x;
            Map<String, CdmMessagesOpport.CreateOpportunityResponseMessageType> response_map_x = new Map<String, CdmMessagesOpport.CreateOpportunityResponseMessageType>();
            response_map_x.put('response_x', response_x);
            
            userToken = new UsernameToken();
            userToken.username = 'onecanon';
            userToken.password = 'password';


            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              '',
              'http://www.test.machine/services/opportunity/1',
              'CreateOpportunityRequestMessage',
              'http://www.test.machine/services/opportunity/1',
              'CreateOpportunityResponseMessage',
              'CdmMessagesOpport.CreateOpportunityResponseMessageType'}
            );
            response_x = response_map_x.get('response_x');
            return response_x;
        }
    }
}

 
Need help on achieving inbound integration from IBM MQ to SFDC, the requirement is some thing like there should be sfdc listener in MQ which notifies/sends the data to sfdc whenever new records comes into Q.
I did not find any useful document on integration from MQ to SFDC.
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?
We are looking for a SalesForce Developer able to create an API between SalesForce and a custom built PHP platform using SQL databases. The desired solution will simply push data fields between the 2 applications as they are updated, and allow for pre-population of forms with the external database. We have already built the PHP platform, and can handle our side of the programming, we just need a SalesForce developer to handle the API. Feel free to email me at gwcarrara@cognizion.com