• Middha
  • SMARTIE
  • 855 Points
  • Member since 2005
  • Make Positive

  • Chatter
    Feed
  • 30
    Best Answers
  • 3
    Likes Received
  • 0
    Likes Given
  • 105
    Questions
  • 232
    Replies

how can i check the line showProject4 = true in my test class?

public Boolean showProject4 {get;set;}
public void ProjButton3() { if(leave.Project_1__c != null && leave.Project_2__c != null && leave.Project_3__c != null) { showProject4 = true; } else { ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please select projects.'); ApexPages.addMessage(myMsg); showProject4 = false; } }

i have this in my test class: 

controller.ProjButton3();

but when i check it in the devconsole, line showProject4 = true isn't checked.

 

 

  • September 24, 2013
  • Like
  • 0

I wrote an Apex Web Service which is going to get called from a web site running on Cold Fusion. The web developer was saying that typically to call a service he would be given a URL to the WSDL and it would return an object with all the methods for that service.

 

I don't see how to do this in Salesforce. Should we take the WSDL and save it on the web server that's calling it? Also, he has the Enterprise WSDL so should he save that to the server too? He could then use that to login and get his session ID. Then supply the session ID to my Apex web service? I looked for documentation on how to call an Apex web service but I am only finding information about how to call out from Salesforce. 

 

Thanks,

Chris

Hi All ,

 

I am trying to create an apex trigger in which i have to manipulate some of the values that are being passed by the user on the VF page .

 

The scenario is , I've to book seats on a flight . Now the user will enter Travel Date and a flight no (unique) for object Flight__c . I am trying to fetch values for the no. of booked seats from another object Booking__c on the same date for the same flight that the user has entered . so I've written query in trigger

 

res=(List<Booking__c>)[select b.booked_seats__c from booking__c b where
               b.travel_date__c = flight.travel_date__c AND
               b.flight_no__c = flight.flight_no__c]

 

Here, as you can see I need Flight.travel_Date__c ( that is being passed by the user ) ! But im not being able to find a way .

 

FYI , My Booking and Flight have a look up relationship .

 

Please guide me thrugh this .

 

Let me know if this is perplexing or you need more info.

Hello,

Is anyone aware, why we can not fetch RecordType.Name on 'Contract' object.

 

list<Contract> lstContract = [Select RecordType.Name From Contract where AccountId =: AccountId];

system.debug('===== lstContract: '+lstContract);

 

RecordTypeName is working good for another objects but for 'Contract' it is just giving the recordtype Id.

Please suggest.

In overriding the new quoteentry page with a visualforce page, QuoteLineItems are not added to the Quote based on the OpportunityLineItems. To bring this functionality I am writing an after insert trigger to clone the OpportunityLineItems to the QuoteLineItems when a quote is created. I am receiving the following error:

 

Error: Compile Error: SObject constructor must use name=value pairs at line 18 column 30

 

Here is my apex code:

 

trigger NewQuoteLineItems on Quote (After Insert) {

    Set<Id> qid = new Set<Id>();
    for(Quote q : Trigger.new){
        System.debug('**** 0 q id : '+q.Opportunityid); 
        qid.add(q.opportunityid);
    }
    System.debug('****1 : q Id size '+ qId.size());
    
    List<QuoteLineItem> qli = new List<QuoteLineItem>();

    List<OpportunityLineItem> oli = new List<OpportunityLineItem>([select id, opportunityid, pricebookentryid,
        Quantity, TotalPrice
        from OpportunityLineItem where opportunityid = :qid]);
   
    for(Quote quote : System.Trigger.new){

        QuoteLineItem item = new QuoteLineItem (
        
            qli[0].pricebookentryid = oli.pricebookentryid);
            
            qli.add(item);
    }
    insert qli;
}

 

I believe my trigger should generate a list of products attadched to the related opportunity and then create the same products on the quote record using a for loop. Is this the correct way? The above code is my start to the trigger.

 

Thank you,

ckellie

I'm hitting "Maximum view state size limit (135KB) exceeded" errors when certain actions are performed on my page.  When I look at the View State, about 95% of the content comes from Internal.  I have tried adding "transient" to the few variables that could potentially get large, though right now I'm only dealing with data from 63 records in just a few fields (no blobs or long text fields even).  Any tips on what I can do to reduce that View State, or track down what's causing it?

 

Hi All,

 

I have two questions.

 

  1. I want to find whether the object is in our organization or not. I want to do this in APEX controller. Is there any method to do that?
  2. After find the object I want to retrieve the fields name of that object. This also want to perform in APEX controller. Is there any method to do that? 

Thanks in Advance!

 

 

I have a very strange situation.  I am using a custom Job object with a custom creation page.  When I input a value into one of my fields (Long Text Area) it shows up on the job page, but when going to edit the value does not repopulate to be edited and must be entered all over again.  What is really strange is that I have other fields of the exact same type setup the exact same way that work.  Any ideas?

 

 

 

<apex:form id="NewJob">
    <apex:pageBlock id="Job" title="Edit Job">
            <apex:pageBlockButtons >   
                     <apex:commandButton value="Save" action="{!JobSaved}" rerender="msgPanel,NewJob"/>
                     <apex:commandButton value="Save & New" action="{!SaveNew}" rerender="msgPanel,NewJob"/>
                     <apex:commandButton value="Cancel" action="{!cancel}" />
            </apex:pageBlockButtons>            
            <apex:pageBlockSection title="Information" columns="2"> 
                <apex:outputField id="name" value="{!Job.name}" />      
                <apex:outputField value="{!Job.Job_Events_Status__c}" />  
                <apex:inputField value="{!Job.Job_Description__c}"/>  
                <apex:inputField value="{!Job.Account__c}" required="true">     
                    <apex:param id="AcctId" value="document.getElementById('{!$Component.mypage:NewJob:Job:j_id5:j_id8_lkid}').value" assignTo="{!AcctId}"/>
                 </apex:inputField>                          
                <apex:inputField value="{!Job.Job_Name_Subject__c}" required="true"/>
                <apex:pageBlockSectionItem id="ContLookup" >
                 <apex:outputLabel >Contact</apex:outputLabel>  
                    <apex:outputPanel >
                    <apex:define name="requiredInputDiv"><div class="requiredInput">
                    <apex:define name="requiredInputDiv"><div class="requiredBlock"/></apex:define>
                    <apex:inputtext id="CName" value="{!ContName}"  size="20" />
                        <apex:commandlink onclick="popup('/apex/LookupContact'); return false;" target="Lookup" immediate="true"  title="Lookup Contact">
                                 <apex:image url="{!$Resource.Lookup}" width="20" height="20"/>
                        </apex:commandlink> 
                    </div></apex:define>
                          <apex:outputPanel id="msgPanel" > 
                            <apex:outputPanel id="msg" rendered="{!If(OR(IsError,IsSaved),true,false)}">
                             <apex:outputtext value="Contact: You must enter a value" style="color:#ff0000;"  />
                        </apex:outputPanel>
                    </apex:outputPanel> 
                   </apex:outputPanel>
                </apex:pageBlockSectionItem> 
                <apex:inputField value="{!Job.Client_Ref__c}"/> 
                <apex:pageBlockSectionItem id="OppLookup">    
                    <apex:outputLabel >Opportunity</apex:outputLabel>
                         <apex:outputPanel >
                        <apex:inputtext Id="theOpp" value="{!OppName}"/>
                            <apex:commandlink onclick="popup('/apex/LookupOpportunity'); return false;" target="Lookup" immediate="true"  title="Lookup Opportunity" >
                                 <apex:image url="{!$Resource.Lookup}" width="20" height="20"/>
                            </apex:commandlink>    
                        </apex:outputPanel> 
                </apex:pageBlockSectionItem>       
                <apex:inputField value="{!Job.Job_Start_Date__c}" required="true"/>
                <apex:inputField value="{!Job.Respondent_Type__c}"/>
                <apex:inputField value="{!Job.Job_End_Date__c}" required="true"/>
                <apex:inputField value="{!Job.Job_Category__c}" />
                <apex:inputField value="{!Job.Other_Date__c}" />
                <apex:inputField value="{!Job.Job_Sub_Category__c}"/>
                <apex:inputField value="{!Job.End_Client__c}"/> 
                <apex:inputField value="{!Job.Job_Status__c}" Id="JobStatus" required="true">
                    <script>document.getElementById('{!$Component.JobStatus}').disabled = {!IF(Status,true,false)}; </script>
                </apex:inputField>  
                <apex:inputField value="{!Job.Other_Location__c}" Id="JobLoc" required="true">
                    <script>document.getElementById('{!$Component.JobLoc}').disabled = {!IF(Status,true,false)}; </script>
                </apex:inputField>  
                <apex:inputField value="{!Job.Job_Qualification__c}" required="true"/>
                <apex:inputField value="{!Job.Moderator_Name__c}"/>
                <apex:inputField value="{!Job.Job_Type__c}" required="true"/>
                <apex:inputField value="{!Job.PM__c}" required="true" />
                <apex:inputField value="{!Job.Recruitment_Method__c}" required="true"/>
                <apex:inputField value="{!Job.Booked_By__c}" required="true"/>
                <apex:inputField value="{!Job.Required_Number_of_Participants__c}" required="true" />
                <apex:pageBlockSectionItem />  
                <apex:pageBlockSectionItem />   
                <apex:inputField value="{!Job.Exclude_from_Calendar__c}" />  
                <apex:pageBlockSectionItem />      
                <apex:inputField value="{!Job.TDI_Job__c}" />
                <apex:pageBlockSectionItem /> 
                <apex:inputField value="{!Job.GMS_Job__c}" />
                <apex:inputHidden id="ContName" value="{!Job.Contact__c}"/>
                <apex:inputHidden id="Oppty" value="{!Job.Opportunity__c}"/>         
            </apex:pageBlockSection>             
            <apex:pageBlockSection title="Additional Information" columns="2"> 
            <apex:inputField value="{!Job.Actual_Number_of_Participants__c}" />
            <apex:inputField value="{!Job.Project_Received_Date__c}" />
            <apex:inputField value="{!Job.Recruit_Start_Date__c}" />
            <apex:inputField value="{!Job.Incentive_Amounts__c}" />
            <apex:inputField value="{!Job.Referral_Fee__c}" />
            <apex:inputField value="{!Job.Basic_Specs__c}" />  
            <apex:inputField value="{!Job.Facility_Special_Requirement__c}" />
            <apex:inputField value="{!Job.Basic_Specification__c}" />   
            <apex:inputField value="{!Job.Invoice_Number__c}" />            
            <apex:inputField value="{!Job.Additional_Notes__c}" />       
                        
            </apex:pageBlockSection> 
            
            <apex:pageBlockSection title="Ratings" columns="2"> 
            <apex:inputField value="{!Job.Recruitment__c}" />
            <apex:inputField value="{!Job.Project_Management__c}" />
            <apex:inputField value="{!Job.Facility_Staff_Service__c}" />
            <apex:inputField value="{!Job.Facility_Rating__c}" />
            <apex:inputField value="{!Job.Rating_Comments__c}" />
                        
            </apex:pageBlockSection> 
            
            <apex:pageBlockSection title="Comments" columns="1"> 
             <apex:inputField value="{!Job.PO_Number__c}" />
            <apex:inputField value="{!Job.Special_Needs__c}" style="width:90%" />          
            <apex:inputField value="{!Job.Comments__c}" style="width:90%" />
            <apex:inputField value="{!Job.Client_Service_Manager_Notes__c}" style="width:90%" />
            <apex:inputField value="{!Job.QA_Feedback__c}" style="width:90%" /> 
                        
            </apex:pageBlockSection> 
             
    </apex:pageBlock>
</apex:form>

 



 

 

I created this trigger to update and populate some fields in a task record. I was wondering if anyone could see a way that I could optimize the code so that it runs more efficiently. Thanks.

 

 

Trigger:

rigger Task_Update_Trigger on Task (before update) {
    
    List<Task> newTask = trigger.new;
    List<Task> oldTask = trigger.old;
    List<User> userList = new List<User>();
    List<Contact> contactList = new List<Contact>();
    DateTime dt = system.now();
    Date day = system.now().date();
    Date EndofWeek = system.today().toStartOfWeek() + 5;
    String str = dt.format('MM/dd');
    userList = [SELECT Name, Id, Alias FROM User WHERE Id =: newTask[0].OwnerId];
    contactList = [SELECT Name, Id FROM Contact WHERE Id =: newTask[0].WhoId];
    
    for(Task T : newTask){
        for(Task O : oldTask){
            for(User U : userList){
                for(Contact C : contactList){
                    if(T.OwnerId == U.Id && T.Type == 'TAP' && T.TAP_Result__c == 'No Connection' && T.WhoId == C.Id){
                        if(T.TAP_Stage__c == 'Called/1st VM Left' && O.TAP_Stage__c != 'Called/1st VM Left'){
                            if(day == EndofWeek){
                                T.ActivityDate = system.today() + 3;
                            }
                            else
                            {
                                T.ActivityDate = system.today() + 1;
                            }
                            if(T.Description == '' || T.Description == null){
                                T.Description = str + ' ' + U.Alias + ' - Called and left a vm (1) for ' + C.Name;
                            }
                            else{
                                T.Description = str + ' ' + U.Alias + ' - Called and left a vm (1) for ' + C.Name + '\n\n' + T.Description;
                            }
                            T.CallDisposition = 'Called and left a vm';
                            T.Activity_Classification__c = 'Voice Message';
                        }
                        if(T.TAP_Stage__c == 'Called/No VM (1)' && O.TAP_Stage__c != 'Called/No VM (1)'){
                            if(day == EndofWeek){
                                T.ActivityDate += 3;
                            }
                            else
                            {
                                T.ActivityDate += 1;
                            }
                            T.Description = str + ' ' + U.Alias + ' - Called and did not leave a vm (1) for ' + C.Name + '\n\n' + T.Description;
                            T.CallDisposition = 'Called and did not leave a vm';
                            T.Activity_Classification__c = 'Call Attempt';
                        }
                        if(T.TAP_Stage__c == 'Email (1)' && O.TAP_Stage__c != 'Email (1)'){
                            if(day == EndofWeek){
                                T.ActivityDate += 3;
                            }
                            else
                            {
                                T.ActivityDate += 1;
                            }
                            T.Description = str + ' ' + U.Alias + ' - Sent Email(1) to ' + C.Name + '\n\n' + T.Description;
                            T.CallDisposition = 'Sent Email(1)';
                            T.Activity_Classification__c = 'Email';
                
                        }
                        if(T.TAP_Stage__c == 'Called/2nd VM Left' && O.TAP_Stage__c != 'Called/2nd VM Left'){
                            if(day == EndofWeek){
                                T.ActivityDate += 3;
                            }
                            else
                            {
                                T.ActivityDate += 1;
                            }
                            T.Description = str + ' ' + U.Alias + ' - Called and left a vm (2) for ' + C.Name + '\n\n' + T.Description;
                            T.CallDisposition = 'Called and left a vm';
                            T.Activity_Classification__c = 'Voice Message';
                        }
                        if(T.TAP_Stage__c == 'Called/No VM (2)' && O.TAP_Stage__c != 'Called/No VM (2)'){
                            if(day == EndofWeek){
                                T.ActivityDate += 3;
                            }
                            else
                            {
                                T.ActivityDate += 1;
                            }
                            T.Description = str + ' ' + U.Alias + ' - Called and did not leave a vm (2) for ' + C.Name + '\n\n' + T.Description;
                            T.CallDisposition = 'Called and did not leave a vm';
                            T.Activity_Classification__c = 'Call Attempt';
                        }
                        if(T.TAP_Stage__c == 'Email (2)' && O.TAP_Stage__c != 'Email (2)'){
                            if(day == EndofWeek){
                                T.ActivityDate += 3;
                            }
                            else
                            {
                                T.ActivityDate += 1;
                            }
                            T.Description = str + ' ' + U.Alias + ' - Sent Email(2) to ' + C.Name + '\n\n' + T.Description;
                            T.CallDisposition = 'Sent Email(2)';
                            T.Activity_Classification__c = 'Email';
                        }
                        if(T.TAP_Stage__c == 'Called/3rd VM Left' && O.TAP_Stage__c != 'Called/3rd VM Left'){
                            if(day == EndofWeek){
                                T.ActivityDate += 3;
                            }
                            else
                            {
                                T.ActivityDate += 1;
                            }
                            T.Description = str + ' ' + U.Alias + ' - Called and left a vm (3) for ' + C.Name + '\n\n' + T.Description;
                            T.CallDisposition = 'Called and left a vm';
                            T.Activity_Classification__c = 'Voice Message';
                        }
                        if(T.TAP_Stage__c == 'Called/No VM (3)' && O.TAP_Stage__c != 'Callec/No VM (3)'){
                            if(day == EndofWeek){
                                T.ActivityDate += 3;
                            }
                            else
                            {
                                T.ActivityDate += 1;
                            }
                            T.Description = str + ' ' + U.Alias + ' - Called and did not leave a vm (3) for ' + C.Name + '\n\n' + T.Description;
                            T.CallDisposition = 'Called and did not leave a vm';
                            T.Activity_Classification__c = 'Call Attempt';
                        }
                        if(T.TAP_Stage__c == 'Email (3)' && O.TAP_Stage__c != 'Email (3)'){
                            if(day == EndofWeek){
                                T.ActivityDate += 3;
                            }
                            else
                            {
                                T.ActivityDate += 1;
                            }
                            T.Description = str + ' ' + U.Alias + ' - Sent Email(3) to ' + C.Name + '\n\n' + T.Description;
                            T.CallDisposition = 'Sent Email(3)';
                            T.Activity_Classification__c = 'Email';
                        }   
                        if(T.TAP_Stage__c == 'Final VM/Email' && O.TAP_Stage__c != 'Final VM/Email'){
                            T.Description = str + ' ' + U.Alias + ' - Final VM and Email completed\n\n' + T.Description;
                            T.CallDisposition = 'Called and left a vm / emailed';
                            T.Activity_Classification__c = 'Voice Message';
                        }
                    }
                }
            }   
        }
    }
}

 

Hi !

 

I need some help...

 

In apex, I want to get email address from a contact linked to the account concerned by the request on which the trigger started :

 

I try to explain better :                                                                                                           Contact(Object)

                                                                                                                                                 Email

                                                                                                                                                 (I want to get this...)

 

                                                                       Account (Object)

                                                                       Field_service_manager_contact__c (lookup to contact)

 

Request__c (Object)                                                                                                           

Entity__c (lookup to Account)                                                                                             

(I am here)                                                                                                                             

 

Is it clear ?

I don't know how to code this in my class.....

 

Thanks a lot to help me !

Marie

 

 

 

 

  • March 23, 2011
  • Like
  • 0

I have added a simple trigger and it works great.

 

 

trigger AddConversionUponAccountCustomer on Account (after insert, after update) {
    Conversions__c[] cList = new Conversions__c[]{};
    for(Account a : trigger.new)
    {
        if(a.Type == 'Customer')
        cList.add(new Conversions__c (Name = a.name, phone__c = a.Phone, email__c = a.Email__c, Account__c = a.Id));
        }
        insert cList;
 

 

As you can see, the way the trigger works is when the Type under an Account is marked 'Customer', I am adding a new custom object, Conversions__c.  

 

The problem lies in the fact that I want to be be able to transfer the Contacts that are associated with the Account over to the new Conversions__c custom object that is created.

 

From my very small amount of exerpience that I have, I am thinking I need to use a List to query the Account.Contacts, grab the Contact.ID, and then map this over to Conversions__c.Contacts__r.  Is this the proper thinking?

I have the following extremely basic code written in my sandbox:

 

trigger SubUpdate on Subscriber__c (before insert) {
list<Fiber_Qualified_Address__c> gpon = [select id,name, street_address__c, loc__c, zip_code__c from Fiber_Qualified_Address__c where street_address__c=:Trigger.new[0].street_address__c
and loc__c=:Trigger.new[0].loc__c
and zip_code__c=:Trigger.new[0].zip_code__c
];

if(gpon.size()>0)

{

Trigger.new[0].fiber_address__c = gpon[0].id;
}}

 

The issue I am having is that when I insert new records, I use the Apex Data Loader and am sometimes inserting hundreds or thousands of records at a time. What am I missing here so that the trigger fires on all records and not just the first record in the batch? I am still fairly green on code writing.


Any help is appreciated.

 

Matt

Hi, I created my first ever trigger, see below. However, I've really struggled the last two days trying to Unit Test it.  I've failed miserably so far. I wonder can anyone here help me?  Here is my trigger:

 

trigger UserStatusBefore on User (before update) {
    
/**********************************************************************
*                                                                        
* This code fires *ONLY* when a user updates status on homepage. If user posts     *
* URL or file along with status, then FeedItemAfter trigger fires. FeedItemAfter   *
* trigger also fires when a user posts to another user's feed.                     *
*                                                                                  *
************************************************************************************/ 
    
    for (User f : trigger.new)
    {
        Datetime thisDT = System.now();
        String itemCreatedDate = thisDT.format('yyyy-MM-dd HH:mm:ss');
        String tiBod;       
           
        for (Id theId : trigger.oldMap.keySet())
           {
                User oldUsr=trigger.oldMap.get(theId);
                User newUsr=trigger.newMap.get(theId);
                String oldStatus=oldUsr.CurrentStatus;
                String newStatus=newUsr.CurrentStatus;
                String UserId1 = f.id;
                
                if (oldStatus != newStatus && null != newStatus)
                {
                    //UserProfileFeed up = [SELECT Id, Body, CommentCount, ContentData, ContentDescription, ContentFileName, ContentSize, ContentType, CreatedDate, InsertedByID, IsDeleted, LastModifiedDate, LikeCount, LinkUrl, ParentId, Title, Type FROM UserProfileFeed WITH UserId = :UserId1 LIMIT 1];
                    User u = [select id, name, email from user where id = :f.Id];                                    
                    tiBod = 'Posted Against: User Home Page' + '\n' + 'Message: ' + f.CurrentStatus + '\n' + 'Created by: ' + u.name + ' - ' + u.email + '\n' + 'Created On: ' + itemCreatedDate;
        
                    //Compile and send email message 
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    String[] toAddresses = new String[] {System.Label.ChatterArchiveExternalEmailAddress};
                    mail.setToAddresses(toAddresses);
                    mail.setSubject('New UserStatus Update');
                    mail.setSaveAsActivity(false);
                    mail.setPlainTextBody(tiBod);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
                }
                else
                {    
                    //do nothing
                } 
           }          
    }    
}

 

 

 

 

Can someone show me what the Unit Test for this trigger looks like? thanks

  • March 19, 2011
  • Like
  • 0

 

I get an error when i execute the below code.
object Dispute_New__c and Document_ID__c are related (lookup)

trigger UpdateCaseStausonDoc on Dispute_New__c (after update) {
  List<Document_ID__c> openlineitems =
  [SELECT j.id FROM Document_ID__c j 
  WHERE j.Dispute_Case_Rela__r.id IN:Trigger.new
  FOR UPDATE];
  for (Document_ID__c li:openlineitems){
 /** Update field Reference_Key2__c  in all cases except null value of
  /** picklist Dispute_Case_Rela__r.status__c 
  if(li.Dispute_Case_Rela__r.Status__c !=''){
  li.Reference_Key2__c = li.Dispute_Case_Rela__r.status__c;
  }
 
}
Thanks for your help

 

I'm writing some code to take an unkonown custom object and create a sharing record for it.  I'm able to grab the object name using the DescribeSObjectResult object,  work out the sharing object name and then create an instance of it using newSobject and assign it to a sObject.  However,  when I attempt to add data to the object's fields,  I get a "Field expression not allowed for generic SObject" error.  Typically,  I'd get around this by casting the sObject to the object that I want to use,  but,  I can't do that here because I don't want to hardcode the object type (this code could be used to provide sharing for a range of records).

 

Here's the code to quickly get to where I am.

 

sObject objToShare = new CustomObject__c();

Schema.SObjectType objObjectType;
DescribeSObjectResult objDescribeResult;
string strObjectName;
string strShareObjectName;
Map<String, Schema.SObjectType> mapAllSobjects = Schema.getGlobalDescribe();
Sobject objShareRecord;


//What object are we dealing with?
objObjectType = objToShare.getSObjectType();
system.debug('1***  objObjectType: ' + objObjectType);

//Get the name of the object
objDescribeResult = objObjectType.getDescribe();
strObjectName = objDescribeResult.getName();

//Get the name of the sharing object associated with it
strShareObjectName = strObjectName.substring(0, strObjectName.lastIndexOf('__c')) + '__Share';
system.debug('2***  strShareObjectName: ' + strShareObjectName);

//Get an instance of the object
objObjectType = mapAllSobjects.get(strShareObjectName);
objShareRecord = objObjectType.newSobject();
system.debug('3***  objShareRecord: ' + objShareRecord);

//Populate the record
objShareRecord.AccessLevel = 'edit'; //!***   ERROR   ***!//

 

I've tried a couple of things to resolve this without any success and I'm sure that this problem must be encountered fairly regularly,  does anyone have a way to sucessfully cast the sObject?

 

How do you format the output of a date field in Visualforce? I want to evalute the date in a series of if else statements, but I am  recieving a long number such as 1299542400000 when the querry runs. How can I format the output to be usefull?? Thanks in advance.

 

 

List<Opportunity> Opptys2 = [SELECT LastActivityDate, Activity_Status__c FROM Opportunity ORDER BY LastActivityDate DESC];	

List<OpportunityFeed> Opptys = [SELECT id, (SELECT CreatedDate FROM FeedComments ORDER BY CreatedDate DESC) FROM OpportunityFeed];

 

 

 

Chris

Hi

 

Can anyone tell me how to construct the query to obtain the account hierarchy for a given account?

 

select Id, ParentId from Account where Id=123

 

this gives the parentid for this account.

 

How do I go from here?

 

Any help is appreciated.

 

Thanks.

 

 

I am having the following Apex code in my class:

 

public List<SelectOption> getItems() {
                List<SelectOption> options = new List<SelectOption>();
                options.add(new SelectOption('US','US'));
                options.add(new SelectOption('CANADA','Canada'));
                options.add(new SelectOption('MEXICO','Mexico'));
                return options;
        }

The visual force page code which fetches all information is as below:

 

<apex:selectList size="1" id="countryList" onChange="setCountry(this.value);">
    <apex:selectOptions value="{!items}"/>
    </apex:selectList>

 

 

The default value that we get after executing this visual force page is US, but I want it to be suppose Canada, How can i do it.

Please Help.

 

Regards,

Lakshman

 

~Share Knowledge, grow more~

Is Recursion possible in apex code, if so please give some example.

  • December 20, 2010
  • Like
  • 0

Hello!

 

In relation to my previous post, here's another request. I have refreshed my sandbox recently, so cant refresh again to populate all my users accordingly.

 

Now, I have one user account (in LIVE) that I want to also open in Sandbox - but I dont want to wait for another 30 days for a refresh of Sandbox.

 

Is there any way of creating the same user in Sandbox (with the same ID)?

 

Best,

Pranav

I am using SingleEmailMessage to send emails to Salesforce users by setting setTargetId.

As per Salesforce document "If you use SingleEmailMessage to email your organization’s internal users, specifying the user’s ID in setTargetObjectId means the email doesn’t count toward the daily limit. However, specifying internal users’ email addresseses in setToAddresses means the email does count toward the limit."

For some reason, this stops working after few emails. I do receiece some emails but then it stops and starts working again next day, Seems like it is consuming some daily limit which is reset next day.

On checking logs, it still shows "Success" and there is not error: Messaging.SendEmailResult[getErrors=();isSuccess=true;])

Any solution to this?
Hi,

I am trying to login as a community user using Partner WSDL (Java) but with no success. Can anyone please help me understand what the endpoint should be to make this work? Here is a sample code I am trying.
ConnectorConfig config = new ConnectorConfig();
config.setUsername("user@mycommunity.com");
config.setPassword("*******");
config.setAuthEndpoint("https://testcomm-developer-edition.ap*.force.com/services/Soap/u/30.0/");
                
PartnerConnection connection = new PartnerConnection(config);  //Connector.newConnection(config);
   
//    LoginScopeHeader_element __header = new LoginScopeHeader_element();
//       __header.setOrganizationId("00D90000000ql00000");
//       __header.setPortalId("0DB90000000Gn00000");
        connection.__setLoginScopeHeader(__header);
        
System.out.println("Connection Successful = " + connection.getUserInfo());
Even adding LoginScopeHeader did'nt work.

Hi , 

We have a third party IDP setup with Salesforce as SP and are using IDP initiated flow to authenticate the user which works well from browser. We need the Salesforce session Id using IDP credentials via code. Is there any way we can do that?

Though we can generate a SMAL assertion and post it to Salesforce directly but we need to sign that assertion with IDP key which IDP does not shares. Any other options?

After Summer 13 updates, I am not able to see the 'Publish' button on Connected Apps. It was there before the update as I was using it.

 

(I have a namespace set for my Org.)

Hi,

 

I had a method which was fetching the access token for another Salesforce Org, using JWT assertion. It was working well till the Summer 13 update happened. Now I am getting "invalid client credentials" error, a bad request. Anyone else having the same issue, any workarounds?

 

Here is the code:

 

String username = 'abc@abc.com';
Long rightNow = (dateTime.now().getTime()/1000)+1;
String claimSet = '{"iss": "' + CSetting.getSettingValue('Consumer Key', '') + '", '; 
       claimSet = claimSet + '"prn": "' + username + '", '; 
       claimSet = claimSet + '"aud": "https://login.salesforce.com", ';  
       claimSet = claimSet + '"exp": "'+ (rightNow + 300) + '"}';
		
		 
String header = '{"alg":"HS256"}';
String signatureInput = base64URLencode(blob.valueOf(header))+'.'+base64URLencode(blob.valueOf(claimSet));
		    
String privateKey = CSetting.getSettingValue('Consumer Secret', '');
		
Blob signature = Crypto.generateMac('hmacSHA256',blob.valueof(signatureInput),blob.valueof(privateKey));
		    
String jwt = signatureInput + '.' + base64URLencode(signature);	    
String body = 'grant_type=' + encodingUtil.urlEncode('urn:ietf:params:oauth:grant-type:jwt-bearer','UTF-8')+'&assertion='+jwt;
		    	    
HttpRequest req = new HttpRequest();				            
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
req.setHeader('Content-type', 'application/x-www-form-urlencoded');
req.setBody(body);
Http http = new Http();				  
HTTPResponse res = http.send(req);
		    
		    
	    
	 

 

Hi All,

 

Can we create and publish connected apps from a production Org??  

 

The page from where we create connected apps says it can only be published from a dveeloper org with namespace.

Hi,

 

I am trying to sign an input within APEX. Can anyone help me with the correct way of signing an input with a private key? I have the certificate (.crt) file and provate key (jks) file. 

 

1. How can i get the pkcs8 format key, do I need to create a new certificate along with the new key?

 

2. Once i get the key, How can i use the pirvate key to sign an input string within APEX, do i put that in a String, what about the new line characters we get in the key file?

Can we create a profile using CRID based Metadata API call i.e. "create"??

I am fetching profiles and deploying them using Metadata API. All is working well except Administrative Permissions (API enabled etc).

Thought about using permission sets but they cannot be assigned at Profile level. Any way we can add/update these System permissions while deploying profiles?

Hi,

 

After Spring release also, we have many old Orgs where Connected apps are not available. We cannot create new connected apps from these Orgs, which is not a problem though.

 

The problem is that in these Orgs, if we install a connected app, our outside application cannot connect to Salesforce using this app. We get 'Not approved' error on the user login history. After installation we opted for "Admin approved user" and added the profiles as well. Looking at these profiles we do not see the "Connected Apps" section and the app name in which we have added this profile.

 

The Orgs which are created in last one month or so are working fine and as expected. 

 

Is there any way we can install and use connected apps in all our SFDC Orgs??

  • February 22, 2013
  • Like
  • 0

Hi ,

 

Do we have any way in APEX, to know the relationship that is shown on chatter via "Originally Posted By". I can see the share post as a FeedItem but no clues where it stores the linkage to original feed. I am open to APEX/SOAP/REST API or any other way.

  • February 04, 2013
  • Like
  • 0

Hi,

 

Is there any way that i can search for any text in a class/page while working in Developer Console. I have a long class with thousand lines of code and need to find some specific text in that class. Browsers 'Ctr + F' does not works. It only shows me the search results from the few lines of code that is visible on the page.

 

Does DC provides any search text box which i am missing which i can use to search the text from my code?

  • September 14, 2012
  • Like
  • 1

Hi All,

 

I am trying to access values of a map in my class on the VF page using Dynamic Binding. 

 

{!mymap['firstname']}

 

This works fine but now if I try to pass this as an attribute in one of the custom VF components it throws an error:

 

<c:mycomp fname="{!mymap['firstname']}"/>

 

Error thrown: Unknown property 'MapValue.firstname'.

 

any thoughts?

Hi,

 

Background: I have Account OWD set to private and number of sharing rules defined which gave number if users access to Account records. I have a checkbox called "Inactive" on Account. 

 

Requirement: I want that if an Account is marked as inactive, the account (and related records) should not come in any search results, for any user other then System Administrator.

 

Solution that I can think of is if I can update the Account owner to System Admin and remove any kind of sharing it has. But i can only delete any manual sharing. Rule based sharing cannot be deleted from APEX.

 

Can anyone suggest any other solution?

 

Thank you.

  • January 30, 2012
  • Like
  • 0

I am following a cusom object record but i dont get any notification if any other user posts anything on that record. I have enabled all the options in Chatter Email Settings and also enabled the Feed Tracker on that object.

 

Do i need to make any post so that i can get notifications on all subsiquent posts? Doesnt following that record is enough? Please let me know if i am missing anything.

  • November 09, 2011
  • Like
  • 0

Hi All,

 

I am trying to set current users chatter status message by updating the UserStatus field on user object. It works fine for the first time but if i try to set the same status again, it doesnt works. 

 

While we can do this from the Chatter tab UI. Any suggestions how we can do this from code as well?

 

Thanks.

  • January 06, 2011
  • Like
  • 0

Visualforce Document states that

 

"Data that's used across several Visualforce pages must be defined within the first page, even if that page isn't using the data. For example, if a field is necessary on pages two and three of a three-step process, page one must also contain the field. You can hide this field from the user by setting the rendered attribute of the field to false."


I dont think this is true, as i have created many wizards where i have not listed fields on page 1, used in my other pages. Please confrim.

  • January 04, 2011
  • Like
  • 0

Hi All,

 

I am using custom settings in a class which is working fine if i call that method on click of a button. But when i schedule the same method, custom settings throws null pointer exception.

 

Can anyone give some pointer to this issue?

 

Thanks in advance.

  • December 01, 2010
  • Like
  • 0

Hi All, I have a webservice written in APEX which returns a complex object. This complext object is a List of Object which itself has another list of object. we can say 2D arrays.

 

While i am trying to consume it from a Java client it throws this error: 

 

"Circular Object Graph detected during serialization, you can not have circular object references in an Apex WebService response."

 

My class is: 

 

 

global class SampleService
{
    global class  ObjectFieldInformation
    {
        WebService Integer fieldSerialNumber;
    }
	
    global class  ObjectInformation
    {
        WebService List<ObjectFieldInformation> objectFieldInformationList;
    }
   
    
    global class CallsResponse
    {
        WebService List<ObjectInformation> callList;
        WebService String something;
    }

    WebService static CallsResponse getComplexObjects()
    {
    	FindCallsResponse  response = new FindCallsResponse();
        
        List<ObjectInformation> responseCallList =  new List<ObjectInformation>();
        ObjectFieldInformation objResultFieldInfo;
        ObjectInformation objCallInfo = new ObjectInformation();
        
        for(Integer i=0;i<5;i++)
        {	
               	List<ObjectFieldInformation> callData = new List<ObjectFieldInformation>();
		        for(Integer j=0;j<5;j++)
		        {	
	        		objResultFieldInfo = new ObjectFieldInformation();
		                callData.add(objResultFieldInfo);
		    	}
		    	
	        objCallInfo.objectFieldInformationList = callData;
	        responseCallList.add(objCallInfo);
        }	
    	 response.callList = responseCallList;
    	 return response;
    }
}

Please advise.

/G

 

 

Hi , I am trying to figure out the name of user who commented on a feed but unfortunately i am not able to make a query:

 

"Select u.Id,u.Parent.Name,  (Select ParentId From FeedComments) From UserFeed u" WORKS but when it does not allows me to create a parent relationship in inner query but it works on parent query.

 

"Select u.Id,u.Parent.Name, (Select ParentId,Parent.Name From FeedComments) From UserFeed u" gives an error.

 

Is there anything wrong in this query? I donot want to collect the Parent Ids and fetch names from User object in another query.

 

Any solutions please?

Hi , 

We have a third party IDP setup with Salesforce as SP and are using IDP initiated flow to authenticate the user which works well from browser. We need the Salesforce session Id using IDP credentials via code. Is there any way we can do that?

Though we can generate a SMAL assertion and post it to Salesforce directly but we need to sign that assertion with IDP key which IDP does not shares. Any other options?

Hi,

 

Is there any way that i can search for any text in a class/page while working in Developer Console. I have a long class with thousand lines of code and need to find some specific text in that class. Browsers 'Ctr + F' does not works. It only shows me the search results from the few lines of code that is visible on the page.

 

Does DC provides any search text box which i am missing which i can use to search the text from my code?

  • September 14, 2012
  • Like
  • 1
Hi,

I am having a problem while crating a scontrol.

I want to assign the value of {!Account_FullBillingAddress} to a javascript variable,
when i do that

var test = "{!Account_FullBillingAddress}";

It gives an error "Unterminated string constant" ,(whenever there is a new line charachter inserted by user in account street).

Is there any way to assign this address to a variable.
Please reply.

Thanks
  • December 02, 2005
  • Like
  • 1
I'm looking for a salesforce partner that has experience in cloning salesforce instances. Currently, we have 1 organization with 3 users. We want to split the organization into 3 different organizations and one user per organization but maintain all custom objects, fields etc. 

The manner in which we would decide which Data goes with which organization is easy enough as we have an ownerid to tie the object/contact/account/company to the user. 

I would consider doing this myself but unsure of the process. 

Any ideas/suggestions?
Thanks
Hi,

There is an standard object called File. If i want to import and export files in the file object using data loader i cannot do it because File object is not there in the list in Data Loader. Please tell me how to export and import files.
I am using SingleEmailMessage to send emails to Salesforce users by setting setTargetId.

As per Salesforce document "If you use SingleEmailMessage to email your organization’s internal users, specifying the user’s ID in setTargetObjectId means the email doesn’t count toward the daily limit. However, specifying internal users’ email addresseses in setToAddresses means the email does count toward the limit."

For some reason, this stops working after few emails. I do receiece some emails but then it stops and starts working again next day, Seems like it is consuming some daily limit which is reset next day.

On checking logs, it still shows "Success" and there is not error: Messaging.SendEmailResult[getErrors=();isSuccess=true;])

Any solution to this?
Hi,

how to get available related lists names for any object?


Thanks,
N.J
Hi,

I am trying to login as a community user using Partner WSDL (Java) but with no success. Can anyone please help me understand what the endpoint should be to make this work? Here is a sample code I am trying.
ConnectorConfig config = new ConnectorConfig();
config.setUsername("user@mycommunity.com");
config.setPassword("*******");
config.setAuthEndpoint("https://testcomm-developer-edition.ap*.force.com/services/Soap/u/30.0/");
                
PartnerConnection connection = new PartnerConnection(config);  //Connector.newConnection(config);
   
//    LoginScopeHeader_element __header = new LoginScopeHeader_element();
//       __header.setOrganizationId("00D90000000ql00000");
//       __header.setPortalId("0DB90000000Gn00000");
        connection.__setLoginScopeHeader(__header);
        
System.out.println("Connection Successful = " + connection.getUserInfo());
Even adding LoginScopeHeader did'nt work.

Hello everybody ,

 

  I am having a Situation to get the object level permissions(like modify ,delete ,etc) of a standard user on custom objects in controller , can anybody have the idea how to acheive this?

  • November 25, 2013
  • Like
  • 0

how can i check the line showProject4 = true in my test class?

public Boolean showProject4 {get;set;}
public void ProjButton3() { if(leave.Project_1__c != null && leave.Project_2__c != null && leave.Project_3__c != null) { showProject4 = true; } else { ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please select projects.'); ApexPages.addMessage(myMsg); showProject4 = false; } }

i have this in my test class: 

controller.ProjButton3();

but when i check it in the devconsole, line showProject4 = true isn't checked.

 

 

  • September 24, 2013
  • Like
  • 0

Working on a trigger to update the lead object. The field displays a count of activities completed within 30 days from the Lead record's CreatedDate.

 

I can't find a clean way to limit my SOQL subquery based on the parent object's CreatedDate field.

 

Any ideas?

 

    public static String ldPrefix =  Lead.sObjectType.getDescribe().getKeyPrefix();
    public static void updateLeadCounts30days(Set<ID> leadIds) {

        List<Lead> Leads = [SELECT ID, CreatedDate, TP_First_30_Days__c, (SELECT ID, ActivityDate FROM Tasks), (SELECT ID, ActivityDate FROM Events) FROM Lead WHERE ID IN :leadIds];
        List<Lead> updateLeads = new List<Lead>();

        for (Lead l : Leads) {

		Date InitDate = l.CreatedDate;
		Date InitDate30 = l.CreatedDate + 30;

		Integer ThirtyTaskCount = [SELECT COUNT() FROM Tasks WHERE ActivityDate <= :InitDate30];            	
		Integer ThirtyEventCount = [SELECT COUNT() FROM Events WHERE ActivityDate <= :InitDate30];
		Integer FirstThirtyDays = ThirtyTaskCount + ThirtyEventCount;

		if (l.TP_First_30_Days__c != FirstThirtyDays) {
			l.TP_First_30_Days__c = FirstThirtyDays;
		}	
		updateLeads.add(l);
	}

 

After Summer 13 updates, I am not able to see the 'Publish' button on Connected Apps. It was there before the update as I was using it.

 

(I have a namespace set for my Org.)

Hi - I get a client posting what appears to be a valid SAML2 Bearer grant to a Salesforce access token endpoint. The error is

"user hasn't approved this consumer".

 

I guess "the consumer" is identified by a client_id of the registered Remote/Connected application. When I build a SAML2 assertion I use that "client_id" as an issuer and my own login name as "subject name".

 

So I have this application with my Salesforce account view, but how do I get this connected application 'approved' ?

Hi,

 

I had a method which was fetching the access token for another Salesforce Org, using JWT assertion. It was working well till the Summer 13 update happened. Now I am getting "invalid client credentials" error, a bad request. Anyone else having the same issue, any workarounds?

 

Here is the code:

 

String username = 'abc@abc.com';
Long rightNow = (dateTime.now().getTime()/1000)+1;
String claimSet = '{"iss": "' + CSetting.getSettingValue('Consumer Key', '') + '", '; 
       claimSet = claimSet + '"prn": "' + username + '", '; 
       claimSet = claimSet + '"aud": "https://login.salesforce.com", ';  
       claimSet = claimSet + '"exp": "'+ (rightNow + 300) + '"}';
		
		 
String header = '{"alg":"HS256"}';
String signatureInput = base64URLencode(blob.valueOf(header))+'.'+base64URLencode(blob.valueOf(claimSet));
		    
String privateKey = CSetting.getSettingValue('Consumer Secret', '');
		
Blob signature = Crypto.generateMac('hmacSHA256',blob.valueof(signatureInput),blob.valueof(privateKey));
		    
String jwt = signatureInput + '.' + base64URLencode(signature);	    
String body = 'grant_type=' + encodingUtil.urlEncode('urn:ietf:params:oauth:grant-type:jwt-bearer','UTF-8')+'&assertion='+jwt;
		    	    
HttpRequest req = new HttpRequest();				            
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
req.setHeader('Content-type', 'application/x-www-form-urlencoded');
req.setBody(body);
Http http = new Http();				  
HTTPResponse res = http.send(req);
		    
		    
	    
	 

 

Hi All,

 

Can we create and publish connected apps from a production Org??  

 

The page from where we create connected apps says it can only be published from a dveeloper org with namespace.

Hi,

 

I have created a new sandbox from a enterprise org and I am trying to schedule a job using the following code in the sandbox.

 

String actJobId = System.schedule('ActScheduler', system.now().addSeconds(30).format('ss mm HH dd MM ? yyyy'), new ActivitiesJob2Scheduler());

 

But it throws the following exception though there is no job for this which is showing under scheduled jobs. 

 

System.AsyncException: The Apex job named "ActScheduler" is already scheduled for execution.

Does anyone has any idea why this is happening like this and why it is not able to schedule the job.

 

Regards

Kamal Ranjan

Hi,

 

Is there any way that i can search for any text in a class/page while working in Developer Console. I have a long class with thousand lines of code and need to find some specific text in that class. Browsers 'Ctr + F' does not works. It only shows me the search results from the few lines of code that is visible on the page.

 

Does DC provides any search text box which i am missing which i can use to search the text from my code?

  • September 14, 2012
  • Like
  • 1

Hello,

 

I have two custom lookup fields in my Case object:  User_Contact__c (User lookup)  and Opportunity_Name__c (Opportunity lookup).  I wrote a trigger to update the User_Contact__c to the Opportunity owner ID from the  Opportunity_Name__c field.  Below is my trigger code:

 

trigger Case_OpptyAttached on Case (before insert, before update) {
    
    for (case c : trigger.new) {
    
        if (c.User_Contact__c != c.Opportunity_Name__r.OwnerId) {
        
            c.User_Contact__c = c.Opportunity_Name__r.OwnerId;
        }
    }
}

 

 

When I update the case record, the custom User lookup field is blank.  Is my apex syntax incorrect?

 

Thank you so much.

 

David

  • September 13, 2012
  • Like
  • 0

I wrote an Apex Web Service which is going to get called from a web site running on Cold Fusion. The web developer was saying that typically to call a service he would be given a URL to the WSDL and it would return an object with all the methods for that service.

 

I don't see how to do this in Salesforce. Should we take the WSDL and save it on the web server that's calling it? Also, he has the Enterprise WSDL so should he save that to the server too? He could then use that to login and get his session ID. Then supply the session ID to my Apex web service? I looked for documentation on how to call an Apex web service but I am only finding information about how to call out from Salesforce. 

 

Thanks,

Chris

I'm trying to write a Trigger that will automatically populate a lookup field with the Partner User's account when the partner creates a new record in a custom object. The Trigger I tried is thus:

 

trigger UpdateAccountName on Change_Request__c (after update) {
    for(Change_Request__c a : Trigger.old)
{a.Customer_Name__c = a.CreatedBy.Contact.AccountID; }
}

 I've tried various combinations of "old" and "new" and "before", "after", "update" and "insert", but I either get the error message below, when attempting to actually utilise the Trigger (there are no compiling errors), or the Trigger simply does nothing, but with no error message. Can anyone offer any guidance? Thanks!

 

Apex trigger UpdateAccountName caused an unexpected exception, contact your administrator: UpdateAccountName: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.UpdateAccountName: line 8, column 1