• Dushyant Sonwar
  • PRO
  • 3425 Points
  • Member since 2014
  • Salesforce Developer


  • Chatter
    Feed
  • 72
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 576
    Replies

Hello, I have been a bit perplexed by this issue and could use some help.  I have a method in before update trigger that is writing the changes of a changed field ( the field name, the oldvalue, and the newvalue) of a field changed within a fieldset.  

 

The output is just the first line which is "These fields are changed and need approval: " and then nothing else prints.  Also, debugging I find that I have this in a try/catch and I am seeing the "Error:  String validation Exception on name ID" which has me very confused as well. 

 

Here is the code 

 

public static void getChangedFieldValues(Map<Id, Account> newMap, Map<Id, Account> oldMap) {

        List<Schema.FieldSetMember> approvalFields = Util.getAddressApprovalFields();

        for (Account newAcc : newMap.values()) {
            Account oldAcc = oldMap.get(newAcc.Id);

            for (FieldSetMember fsm : approvalFields ) {
                String field = fsm.getFieldPath();
                try {
                    System.debug('newAcc.get(Field) ====== ' + newAcc.get(field));
                    System.debug('oldAcc.get(Field) ====== ' + oldAcc.get(field));
                    if (newAcc.get(field) != oldAcc.get(field)) {
                        newAcc.Start_Address_Approval_Description__c = 'These address fields are changed and need approval:\n';
                        newAcc.Start_Address_Approval_Description__c += fsm.getLabel() + ' changed from: ' + oldMap.get(fsm.getFieldPath()) + ' to: ' +
                                newAcc.get(fsm.getFieldPath()) + '\n';
                    }
                } catch (Exception e) {
                    System.debug('Address Error: ' + e);
                }
            }
}


Like i said, it is updating the Description field with the first line, "These address fields are changed and need approval" , but then nothing else is getting added to the field, and at the same time I am also seeing that weird error:

Error: System.StringException: Invalid id: Name

 

Any help on why the rest is not being printed or the error would help immensely.  

Hello, all

I have added a percentage 'yearly increase' field to my Opp Product.

I am looking for a way to calculate the lifetime total of the product after x years (x being the 'term' field) if the price is increased by 'yearly increase' every year and how to track each year's price. This needs to work for any given term

for example.
  • product price = $100
  • yearly increase = 3%
  • term = 5​​​​​​​
    • year 1 price = 100
    • year 2 price = 103
    • year 3 price = 106.09
    • year 4 price = 109.27
    • year 5 price = 112.55
    • lifetime total = 530.91
If I could use a for loop in the formula editor I could calculate the lifetime total, but I can't figure out how to do that in the formula editor. Is there a way to do that or to write the for loop in an apex class and use that to populate the lifetime total field? I have no clue how to track each year's price espically when the term will vary.

Thank you for your time and help.
<id,Sobject> map1 = <id, Sobject>();
<id,Sobject> map2 = <id, Sobject>();

if map1 and map2 contain same key with different values.
how to add map2 values to map1 without deleting map1 values.
Hi,

I have a requriment to create list view from VF page.

Is there any way to create listview from apex
trigger for updating a value depending on another object field.
A very simple trigger.
I want to update by incrementing the total_applicant(Type:Number, object: Job__c) field by 1, which is to be done only after a record is inserted or updated in the Candidate__c object.
I can't figure out why line 7 is always red(errorneous) which leads to no change in the databse.
A little help would be appreciated. A newbiew here by the way.
I want to be able to create a Case and when the Case is created automatically link a File or Attachment.

I have a word document that I want attached to cases when they are created.

What is the best way to achieve this? Presumably it will require Apex code? Will I need to make a copy of the Word document from somewhere then create the required File records to attach it to the Case?
 
  • May 15, 2020
  • Like
  • 0
I am learning Apex and am trying to get my controller to query for Resource_List__c records where the Survey_Form__c field = :RecordId (the current Survery_Form__c record I am viewing)

VF Page
<apex:page Controller="ResourceListController">
    <apex:form>
    <apex:pageBlock>
<apex:pageBlockTable value="{! ResourceList }" var="RL">
    <apex:column value="{! RL.Id }"/>
    
</apex:pageBlockTable>
    </apex:pageBlock>
        </apex:form>
</apex:page>

Class
public class ResourceListController {
   public Id RecordId {get;set;}    
public List<Resource_List__c> getResourceList() {
    
    List<Resource_List__c> results = Database.query(
        'SELECT Id, Account__c, Distance__c, type__c ' +
        'FROM Resource_List__c ' + 
        'Where Survey_Form__c = :RecordId '
    );
    return results;
}
}

VF Page Output when on the Lightning page
User-added image
but when I put the query into the query editor and hard code the record Id there are values in this table

User-added image

Is there any way to pass the record id into the VF page without invoking aura or LWC? I just want to learn the fundamentals before I step into those new languages
hi,
I have used <apex:image> in Visualforce email template.
the image is showing fine in Outlook app but image is not coming in outlook.com
Is there a way to allow the user to single click to open the select, and then single click to select a value?

I have a table with a "Pay?" column that is a select list field that uses inline-edit on dbl click, which works, but I would like it to work on a single click. Unfortunately, when I change the event to onclick, it will open up the select box but toggle off and on when I try to select a value because I am using a single click on the cell.

Is there a way to allow the user to single click to open the select, and then single click to select a value?

Page:
<apex:page controller="DTTestPageController" lightningStylesheets="true">
    <apex:pageMessages />

 <apex:form id="form">  
    
    <apex:pageBlock mode="inlineEdit" id="pageblock1">  
        <div id="header" class="headerborder">
            <p id="title">DT Worksheet</p>

            <p id="select">
            <apex:selectList size="1" id="filter" value="{!pickValue}">
                <apex:actionSupport event="onchange"  action="{!GetMedicals}" rerender="table1"/>
                <apex:selectOption itemLabel="All" itemValue="All" ></apex:selectOption>
                    <apex:selectOption itemLabel="Needs Review" itemValue="Review" ></apex:selectOption>
                    <apex:selectOption itemLabel="Pay" itemValue="Pay"></apex:selectOption>
                    <apex:selectOption itemLabel="Don't Pay" itemValue="Dont Pay"></apex:selectOption>
            </apex:selectList>
            <apex:commandButton id="alert" value="Alert" rerender="" action="{!alertUser}"/>
        </p>

        </div>
        <apex:pageBlockButtons location="bottom">  
               <apex:commandButton id="saveButton" value="Save" rerender="" action="{!saveme}"/>  
               <apex:commandButton id="cancelButton" value="Cancel" rerender="table1"/>  
        </apex:pageBlockButtons> 
    
        

        <div class="tableborder" id="border">
    <apex:pageBlockTable value="{!lstMedicals}" var="med" id="table1">
        
        <apex:column headerValue="Medical Bill Number" headerClass="headerStyle">
                <apex:actionRegion >
                      <apex:outputLink value="/{!med.Id}" styleClass="link">
                            {!med.Name}
                      </apex:outputLink>
                </apex:actionRegion>  
        </apex:column>

            <apex:column headerValue="Provider" headerClass="headerStyle">
                <apex:actionRegion >
                      <apex:outputField value="{!med.Provider_Name__c}">
                      </apex:outputField>
                </apex:actionRegion>  
        </apex:column>

        <apex:column headerValue="Pay?" headerClass="headerStyle" id="column1">
            
            
                <apex:actionRegion id="actionRegion1">
                      <apex:outputField value="{!med.Disburse__c}" id="pay">
                              <apex:inlineEditSupport event="onClick" showOnEdit="saveButton,cancelButton"/>
                      </apex:outputField>
                </apex:actionRegion>  
        </apex:column>

        <apex:column headerValue="Notes" headerClass="headerStyle">
                <apex:actionRegion >
                      <apex:outputField value="{!med.Disbursement_Note__c}">
                              <apex:inlineEditSupport event="ondblClick" showOnEdit="saveButton,cancelButton" id="note"/>
                      </apex:outputField>
                </apex:actionRegion> 
        </apex:column>
    </apex:pageBlockTable>
</div>
 </apex:pageBlock>  
</apex:form>

Controller:
public class DTTestPageController {
    /* private String sortOrder = 'LastName'; */
    public string pickValue{get; set;}
    public litify_pm__Matter__c matterId{get; set;}
    public Id recordTypeId = Schema.SObjectType.Medical_Bill__c.getRecordTypeInfosByName().get('Medical').getRecordTypeId();
    public list<Medical_Bill__c> lstMedicals{get; set;}

    public DTTestPageController(){
        pickValue = 'All';
        GetMedicals();
    }

    public void GetMedicals() {
        
        matterId = [SELECT Id, litify_pm__Principal_Attorney__c, Litigation_Attorney__c  FROM litify_pm__Matter__c WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
        

        


        if (pickValue == 'All') {
            lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c from Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId];
            
        }
        else if (pickValue == 'Review') {
            lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c From Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId AND Disburse__c = null];
        }
        else if (pickValue == 'Pay') {
            lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c From Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId AND Disburse__c = 'Yes'];
        }
        else if (pickValue == 'Dont Pay') {
            lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c From Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId AND Disburse__c = 'No'];
        }
        else {
             lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c from Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId];
        }
        
    }

    public pagereference saveme()
    {
    try
    {
        System.debug(lstMedicals);
        update lstMedicals;
         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Medical Bill List Updated!'));
    }   
    catch(DmlException ex)
    {
        ApexPages.addMessages(ex);

    }
    return NULL;
    }   

  /*   public void sortByFirstName() {
        this.sortOrder = 'LastName';
    } */

    public void alertUser() {
        Id profileId=userinfo.getProfileId();
        String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
        Id ownerId;
        String assignedRole;
        String subject;

        if (profileName == 'Disbursements Team' || profileName == 'Disbursements Team Lead') {

            if (matterId.Litigation_Attorney__c == null) {
                ownerId = matterId.litify_pm__Principal_Attorney__c;
            }
            else {
                ownerId = matterId.Litigation_Attorney__c;
            }

            assignedRole = 'Attorney';
            subject = 'Verify The List Of Medical Bills We Are Paying Is Correct';

        }
        else {
            ownerId = '0056A000000mKxc';
            assignedRole = 'Disbursements';
            subject = 'The Attorny Has Reviewed The List of Medical Bills';
        }

        Task taskRecord = new Task();
        taskRecord.OwnerId = ownerId;
        taskRecord.Assigned_Role__c = assignedRole;
        taskRecord.Subject = subject;
        taskRecord.WhatId = matterId.Id;
        taskRecord.litify_pm__Matter__c = matterId.Id;
        taskRecord.ActivityDate = System.today();
        taskRecord.Priority = 'Normal';

        insert taskRecord;
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Alert Sent!'));  
    }
}

​​​​​​​​​​​​​​
I have a Visualforce table that isn't populating on page load. It will populate after I select a picklist value from #filter, but not until then. How can I make the data populate automatically on page load?

Page:
<apex:page controller="DTTestPageController" tabStyle="Lead" lightningStylesheets="true">
    <apex:messages/>
    <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

<apex:form id="form">  
    
    <apex:pageBlock mode="inlineEdit" id="pageblock1">  
        <div id="header" class="headerborder">
            <p id="title">DT Worksheet</p>

            <p id="select">
            <apex:selectList size="1" id="filter" value="{!pickValue}">
                <apex:actionSupport event="onchange"  action="{!GetMedicals}" rerender="table1"/>
                <apex:selectOption itemLabel="All" itemValue="All" ></apex:selectOption>
                    <apex:selectOption itemLabel="Needs Review" itemValue="Review" ></apex:selectOption>
                    <apex:selectOption itemLabel="Pay" itemValue="Pay"></apex:selectOption>
                    <apex:selectOption itemLabel="Don't Pay" itemValue="Dont Pay"></apex:selectOption>
            </apex:selectList>
            <apex:commandButton id="alert" value="Alert" rerender=""/>
        </p>

        </div>
        <apex:pageBlockButtons location="bottom">  
               <apex:commandButton id="saveButton" value="Save" rerender="" action="{!saveme}"/>  
               <apex:commandButton id="cancelButton" value="Cancel" rerender=""/>  
        </apex:pageBlockButtons> 
    
        

        <div class="tableborder" id="border">
    <apex:pageBlockTable value="{!lstMedicals}" var="med" id="table1">
        
        <apex:column headerValue="Medical Bill Number" headerClass="headerStyle">
                <apex:actionRegion >
                      <apex:outputLink value="/{!med.Id}" styleClass="link">
                            {!med.Name}
                      </apex:outputLink>
                </apex:actionRegion>  
        </apex:column>

            <apex:column headerValue="Provider" headerClass="headerStyle">
                <apex:actionRegion >
                      <apex:outputField value="{!med.Provider_Name__c}">
                      </apex:outputField>
                </apex:actionRegion>  
        </apex:column>

        <apex:column headerValue="Pay?" headerClass="headerStyle" id="column1">
            

            

            <apex:facet name="header">
               <!--  <apex:commandLink action="{! sortByFirstName }" 
                    reRender="contacts_list">Pay
                </apex:commandLink> -->
            </apex:facet>
            
                <apex:actionRegion id="actionRegion1">
                      <apex:outputField value="{!med.Disburse__c}" id="pay">
                              <apex:inlineEditSupport event="ondblClick" showOnEdit="saveButton,cancelButton"/>
                      </apex:outputField>
                </apex:actionRegion>  
        </apex:column>

        <apex:column headerValue="Notes" headerClass="headerStyle">
                <apex:actionRegion >
                      <apex:outputField value="{!med.Disbursement_Note__c}">
                              <apex:inlineEditSupport event="ondblClick" showOnEdit="saveButton,cancelButton" id="note"/>
                      </apex:outputField>
                </apex:actionRegion> 
        </apex:column>
    </apex:pageBlockTable>
</div>
 </apex:pageBlock>  
</apex:form>  

    </html>

</apex:page>
Controller:
public class DTTestPageController {
    private String sortOrder = 'LastName';
    public string pickValue{get; set;}
    public litify_pm__Matter__c matterId{get; set;}
    public Id recordTypeId = Schema.SObjectType.Medical_Bill__c.getRecordTypeInfosByName().get('Medical').getRecordTypeId();
    public list<Medical_Bill__c> lstMedicals{get; set;}
    public void GetMedicals() {

        System.debug(pickValue);

    
        if (pickValue == 'All') {
            lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c from Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId];
            
        }
        else if (pickValue == 'Review') {
            lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c From Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId AND Disburse__c = null];
        }
        else if (pickValue == 'Pay') {
            lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c From Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId AND Disburse__c = 'Yes'];
        }
        else if (pickValue == 'Dont Pay') {
            lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c From Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId AND Disburse__c = 'No'];
        }
        else {
             lstMedicals = [Select Id, Name, Provider_Name__c, Disburse__c, Disbursement_Note__c from Medical_Bill__c WHERE Matter__c =: matterId.Id AND RecordTypeId =: recordTypeId];
        }
        
    }

    public pagereference saveme()
    {
    try
    {
        System.debug(lstMedicals);
        update lstMedicals;
        
    }   
    catch(DmlException ex)
    {
        ApexPages.addMessages(ex);

    }
    return NULL;
    }   

  /*   public void sortByFirstName() {
        this.sortOrder = 'LastName';
    } */

}


 
Hi all and Happy new year.

I had this task to create a custom Related list on the Account Page Layout with Visualforce and it all works fine. I've got all the records that i need and all the required fields and of course "New Project" button.

New Project button

However the only issue is that when i added the "New BD Project" button, when the new page is opened and the user change his mind and press "Cancel" it returns to the Visualforce page only, not to the Account Page Layout.

Cancel

I tried different solution, but i could not make it work.
Here is the commandlink button
<div style="margin-left: 30%;">
<apex:commandLink value="New BD Project" action="       {!URLFOR($Action.BD_Project__c.New)}" target="_parent"     styleClass="btn" style="text-      decoration:none;padding:4px;"/>
</div>

I found the whole Visualforce page and Controller in another solution which was for Contact Related list and i modified it to fit my requirements. The only change is that in the working Contact solution(where when you press cancel it returns you to the previous page) is that the code for the New Object is in the Controler:
 
public pageReference newContact()
{
pageReference pageRef = new pageReference(URL.getSalesforceBaseUrl().toExternalForm() + '/003/e?&retURL=' + accounts.id);
return pageRef;
}

Did any of you guys had a similar issue and found a solution.

Kind regards,
Dimitar
 

Here is the controller and the Visualforce that i'm using.:


 
I'm going to override the standard controller for my object .  Do insertion a new record  ( record in base still there is no).  Page

<apex:page standardController="CallReportHosp__c" extensions="CtrlCallHospEdit" >
<apex:outputPanel rendered="{!IF($CurrentPage.parameters.theType = 'app', false, true)}" >
            <apex:pageBlockSection columns="2">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="{!$ObjectType.CallReportHosp__c.fields.AccountID__c.label}" for="organisation"/>
                    <apex:inputField value="{!CallReportHosp__c.AccountID__c}" id="organisation" >
                         <apex:actionSupport event="onchange"  reRender="pblock" status="status" action="{!SelectService}" />
                    </apex:inputField>
                </apex:pageBlockSectionItem>
Controller
public with sharing class CtrlCallHospEdit {


public Boolean booleanValue {get;set;}
pablic CallReportHosp__c rep;

 public CtrlCallHospEdit(ApexPages.StandardController controller)
    {
       this.booleanValue=false;
       rep = (CallReportHosp__c)controller.getRecord();

       System.debug(' bool= '+booleanValue);
       SelectService();      
    }
 
 
    
public void SelectService(){
system.debug('selectservice=');
        if(rep.AccountID__c !=null)
           { booleanValue = true; System.debug('acc= '+rep.AccountID__c); }
           else {booleanValue=false; System.debug('acc= '+rep.AccountID__c); }
    }     
}
I changed value in field AccountID__c in page, but i don't have its value in controller ( i have rep.AccountID__c = null).
I remind you that I need to get the value of the field BEFORE saving the record in the database (before the call Save).
Tell me what I'm doing wrong
 
Hi there,

I have created an Apex trigger for my organization and deployed it to production and it seems to be conflicting with my attempts to update a bunch of records in Data Loader.

We have a custom object that governs a special form, which I will call Forms__c (it is not actually named Form), and we have put on this object a trigger to prevent duplicates from being created. On create or update, the trigger checks the name of a given record, which will always be a 4-digit number, and returns an error if the number/name is already in use.
 
trigger FormNumberDuplicate on Form__c (before insert, before update) {
    list<id> formId = new list<id>();
    list<string> formNumber = new list<string>();
    
    if (Trigger.isInsert || Trigger.isUpdate) {
        for (Form__c t : Trigger.New) {
            System.debug(t);
            formId.add(t.Id);
            formNumber.add(t.Name);
        }
        
        List<Form__c> allForms = [SELECT Id, Name FROM Form__c WHERE IsDeleted = false];
        Integer flag = 0;
        for(Form__c t : allForms) {
            System.debug(t);
            if(!formId.contains(t.Id)) {
                if(formNumber.contains(t.Name)) {
                   flag = flag+1; 
                }
            }
        }
        System.debug(flag);
        if(flag > 0) {
            for(Form__c t : Trigger.New) {
                t.Name.addError('This Form number is already in use.');
            }
        }    
    }
    
    
}

The trigger works as intended: if a user tries to create a Form and uses the same number, it prevents them from entering a duplicate of the form and it tells them the form number is already in use.

However, I was trying to bulk update these Form__c records today with data from an external source, and ran into the issue where every single Form__c record would not update and threw the error in this trigger.

What am I missing here?

Thanks.
 

Hi all,

I'm trying to create a validation rule via trigger when two multiselect picklist values are the same then the validation to fire.

trigger differentValues on User (before insert) {

    for(User u : Trigger.New) {
        if(u.Restrict_access_by_Country__c =='DE' && u.TestMultiSelectCountry__c== 'DE' ) {
        u.addError('Values cannot be the same');
    }
    }
}

This trigger it's not firing.. I'm confused why not?
Hey there, I'm new to development and APEX classes, so apologies if this is easy. But basically we have Zuora package (for billing) and I'm updating one of the classes for default values when creating a quote. Most of the code works, except when I add in a reference to Billing Country on the Account it says it doesn't exist. My code for that particular part is below, and full code below that.

Error: 
Error: Compile Error: Variable does not exist: billingcountry at line 23 column 20
// Retrieve the account ID from the quote
      Id accountId = (Id) record.get('zqu__Account__c');
      
      List<Account>accounts = [SELECT Id, BillingCountry FROM Account WHERE Account.ID = :accountID];
      
      if (accounts.billingcountry == 'Canada')
      {
      record.put('zqu__PaymentGateway__c', 'Standard');
      } else {
      record.put('zqu__PaymentGateway__c', 'USD2');
      }
Full code:
global class ZuoraDefaultValues extends zqu.CreateQuoteController.PopulateDefaultFieldValuePlugin{  
   global override void populateDefaultFieldValue
(SObject record, zqu.PropertyComponentController.ParentController pcc)
   {    
      super.populateDefaultFieldValue(record, pcc);  
      
      //Populate default values in the quote header  
      Id OpptId = (Id) record.get('zqu__Opportunity__c');    
      List<Opportunity> Opportunity= [SELECT Id, Name FROM Opportunity WHERE Opportunity.Id = :OpptId ]; 
       
      record.put('Name', 'Quote For ' + Opportunity[0].Name + ' ' + Date.today().format());
      record.put('zqu__InitialTerm__c', 12);    
      record.put('zqu__RenewalTerm__c', 12);    
      record.put('zqu__ValidUntil__c', Date.today().addDays(30));    
      record.put('zqu__StartDate__c', Date.today());
      record.put('zqu__PaymentMethod__c', 'Credit Card');  
      
      // Retrieve the account ID from the quote
      Id accountId = (Id) record.get('zqu__Account__c');
      
      List<Account>accounts = [SELECT Id, BillingCountry FROM Account WHERE Account.ID = :accountID];
      
      if (accounts.billingcountry == 'Canada')
      {
      record.put('zqu__PaymentGateway__c', 'Standard');
      } else {
      record.put('zqu__PaymentGateway__c', 'USD2');
      }
    

      // Find the contacts associated with the account         
      List<Contact>contacts = [SELECT Id, Name FROM Contact WHERE Account.Id = :accountId];
      
      // Assuming the contacts are present set the billTo and soldTo to the first contact
      if  (contacts.size() > 0) {
         // System.debug('mp: about to add ' + contacts[0].Id + ' as a contact ID');
         record.put('zqu__BillToContact__c', contacts[0].Id);
         record.put('zqu__SoldToContact__c', contacts[0].Id);

         // Beforeretrieving  the lookup  options, needs to populate the map first
         super.setLookupOptions(pcc);
      
         // Now retrieve the lookup component options
         zqu.LookupComponentOptions billToOptions = super.getLookupOption('zqu__BillToContact__c');
         billToOptions.targetId = contacts[0].Id;
         billToOptions.targetName = contacts[0].Name;
         zqu.LookupComponentOptions soldToOptions  = super.getLookupOption('zqu__SoldToContact__c');
         soldToOptions.targetId = contacts[0].Id;
         soldToOptions.targetName = contacts[0].Name;
      }
   }
}

 
I am trying to write test coverage for a method and receiving the error "Attempt to de-reference a null object" when I run the test.  Below is my test class, can anyone guide me in the right direction with this?

Test class:

static testmethod void getselectOptionsTest(){
        Id RecordTypeIdPropAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Franchisee').getRecordTypeId();
        
        Account fAcct = new Account(Name = 'Test', RecordTypeId=RecordTypeIdPropAccount);
        insert fAcct;
        sObject objObject = [SELECT Id, Name FROM Account WHERE Name = 'Test' LIMIT 1];
        String fld = 'RetailerCategory';
        
        Test.startTest();
        multiPicklistCtrl.getselectOptions(objObject, fld);
        Test.stopTest();
        
    }

Original method:

@AuraEnabled
    public static List <String> getselectOptions(sObject objObject, string fld) {
          system.debug('objObject --->' + objObject);
          system.debug('fld --->' + fld);
          List < String > allCats = new list < String > ();
          // Get the object type of the SObject.
          Schema.sObjectType objType = objObject.getSObjectType();
        
        // Describe the SObject using its object type.
          Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
 
          // Get a map of fields for the SObject
          map < String, Schema.SObjectField > fieldMap = objDescribe.fields.getMap();

          // Get the list of picklist values for this field.
          list < Schema.PicklistEntry > values =
           fieldMap.get(fld).getDescribe().getPickListValues();

          // Add these values to the selectoption list.
          for (Schema.PicklistEntry a: values) {
           allCats.add(a.getValue());
          }
          system.debug('allCats ---->' + allCats);
          allCats.sort();
          return allCats;    
        }
New to coding and would really appreciate any help that can be provided.

I am trying to write a test class for a function I have written that creates Opportunities for each account in a list.  On compile I am receiving the error 'Method does not exist or incorrect signture: void CreateOpptys(Id, List) from the type multiPicklistCtrl.  Can someone please tell me what I am doing wrong?

This is my test class:

static testmethod void CreateOpptysTest(){
        Id RecordTypeIdPropAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Property').getRecordTypeId();
        
        Account pAcct = new Account(Name = 'Test Property account', RecordTypeId=RecordTypeIdPropAccount);
        insert pAcct;
        
        PropertySpace__c pSpace = new PropertySpace__c(Name='Test Property Space', Property__c = pAcct.Id, SquareFootage__c = 2000);
        insert pSpace;

        List<Account> accts = new List<Account>();
        for (Integer i=0; i<20; i++) {
            accts.add(new Account(Name = 'Test Account -' +i, RecordTypeId=RecordTypeIdPropAccount));
        }
        insert accts;
        
        accts = [Select Id from Account];
        
        Test.startTest();
          multiPicklistCtrl.CreateOpptys(pSpace.id,accts);
          Test.stopTest();
    }

Here is the function I am trying to write the test for:

@AuraEnabled
    public static void CreateOpptys(Id propertyId, List<Id> selectedAccts){
        system.debug('From Create Oppty propertyId1>>>'+propertyId);
        system.debug('From Create Oppty selectedAccts>>>'+selectedAccts);
        //Need to search through existing Opportunities and if there is an active Opty created for the Account and Property, do not create another Oppty.
        PropertySpace__c propSpace = new PropertySpace__c();
        Id propSpaceId;
        if(string.valueof(propertyId).startsWith('006')){
            opportunity opp= [SELECT PropertySpace__c FROM Opportunity WHERE Id = :propertyId];
               propSpace= getProp(opp.PropertySpace__c);
            propSpaceId = opp.PropertySpace__c;
        }
        else{
            propSpace = [SELECT Name,SquareFootage__c, Property__c FROM PropertySpace__c WHERE Id = :propertyId];
            propSpaceId = propertyId; 
        }
            
        Id recTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Vacancy Fill').getRecordTypeId();
        
         
        list<Opportunity> lstOpptys = new List<Opportunity>();
        for(integer i=0; i< selectedAccts.size(); i++){
            Opportunity o = new Opportunity(Name = propSpace.Name +i,
                                            CloseDate = date.today().addDays(90),
                                            StageName = 'Prospect',
                                            RecordTypeId = recTypeId,
                                            AccountId = selectedAccts[i]);

        lstOpptys.add(o);
        }    
        insert lstOpptys;
        
            
    }

 
Here is my code:
PassQuery is a string which contains the record ids
<apex:pageBlockTable value="{! retrieveRecords }" var="row">
               
                <apex:column id="checkboxcolumn" >
                    <apex:facet name="header">
                        <apex:inputCheckbox id="headerCheckbox" value="{! checked}" >
                            <apex:actionSupport event="onchange" action="{! headerCheckboxMethod}" reRender="pgblock"/>
                        </apex:inputCheckbox>
                    </apex:facet>
                    <apex:inputCheckbox value="{!If(contains(passQuery, row.Id),true,false)}" id="childCheckBox" >
                        <apex:actionSupport event="onchange" action="{! checkboxStateMethod}" reRender="headerCheckbox">
                            <apex:param name="checkboxId" value="{! row.Id}" assignTo="{! recordId}" />
                        </apex:actionSupport>
                    </apex:inputCheckbox>
                </apex:column>
                
                <apex:column headerValue="Action" title="Action">
                    <apex:outputLink title="Edit Record" value="/{! row.Id}/e?retURL=/apex/DescribeCallAssignment" >Edit</apex:outputLink>|&nbsp;
                    <apex:commandLink title="Delete Record" action="{! deleteRecord}"  reRender="pgblock">Del
                        <apex:param name="recordToBeDeleted"  value="{! row.Id}" assignTo="{! RecordToDelete}" />
                    </apex:commandLink>
                </apex:column>
                <apex:repeat value="{! retrieveColumns}" var="col">
                    <apex:column value="{! row[col]}" />
                </apex:repeat>
            </apex:pageBlockTable>
I have a visualforce page that I want to use a date field to rerender an output panel if the date is a certain month.

Currently I'm using a number field for this section but i would like to use a date field called Contract_Start_Date__c.

I'm not sure how to format the formula to check for what month it is from the Contract Start date. .  

<apex:outputPanel layout="none" rendered="{!IF(et.Number_of_Months__c >= 12  ,true,false)}">

I would like to do something like this below
{!IF(MONTH (et.Contract_Start_Date__c)  == 12  ,true,false))}
  • August 12, 2019
  • Like
  • 0
Hi,

If particular product not added in quote, I don't want print the specific sentence in the quote PDF.

<p><strong>display:{!if(!QLI.weli.Product_Description__c=XXXXXXXX,'','none')},"><b>Along with the above mentioned XXXXXXX we also have complete range of XXXXXXXXX</b></strong>, Should you have any other clarifications / details please do feel free to contact us.</p>


 

Hey there, 

Is there a way to programmactically set these properties in my .page file? User-added image

 

For example I want to auto-enable `Show scrollbars` when someone adds this page. Or I want this page to always be 700px. etc

 

my .page file looks like the following format

 

<apex:page sidebar="false" standardController="something" showHeader="false" standardStyleSheets="false" extensions="more something">
    <div id="root"/>
        <apex:includeScript loadOnReady="true" value="{!$somethingscript}"/>
</apex:page>
Hi, I need to create a validation rule for record type to restrict the user from creating with 2 conditions, one when the email is blank and another when (screening pick value is unscreened and Territory Lookup is blank), following is something I tried but it works for first condition but not the second. 

AND( 
$RecordType.Name = "Partner", 
ISBLANK(Email),
OR($RecordType.Name = "Partner", 
ISPICKVAL(Screening__c, "Unscreened"),
ISBLANK(Sales_Territory__c))))

Hello, I have been a bit perplexed by this issue and could use some help.  I have a method in before update trigger that is writing the changes of a changed field ( the field name, the oldvalue, and the newvalue) of a field changed within a fieldset.  

 

The output is just the first line which is "These fields are changed and need approval: " and then nothing else prints.  Also, debugging I find that I have this in a try/catch and I am seeing the "Error:  String validation Exception on name ID" which has me very confused as well. 

 

Here is the code 

 

public static void getChangedFieldValues(Map<Id, Account> newMap, Map<Id, Account> oldMap) {

        List<Schema.FieldSetMember> approvalFields = Util.getAddressApprovalFields();

        for (Account newAcc : newMap.values()) {
            Account oldAcc = oldMap.get(newAcc.Id);

            for (FieldSetMember fsm : approvalFields ) {
                String field = fsm.getFieldPath();
                try {
                    System.debug('newAcc.get(Field) ====== ' + newAcc.get(field));
                    System.debug('oldAcc.get(Field) ====== ' + oldAcc.get(field));
                    if (newAcc.get(field) != oldAcc.get(field)) {
                        newAcc.Start_Address_Approval_Description__c = 'These address fields are changed and need approval:\n';
                        newAcc.Start_Address_Approval_Description__c += fsm.getLabel() + ' changed from: ' + oldMap.get(fsm.getFieldPath()) + ' to: ' +
                                newAcc.get(fsm.getFieldPath()) + '\n';
                    }
                } catch (Exception e) {
                    System.debug('Address Error: ' + e);
                }
            }
}


Like i said, it is updating the Description field with the first line, "These address fields are changed and need approval" , but then nothing else is getting added to the field, and at the same time I am also seeing that weird error:

Error: System.StringException: Invalid id: Name

 

Any help on why the rest is not being printed or the error would help immensely.  

Trying to have a method that counts and then updates fields on the Lead object with the notes have been created by ouur API service. We have two fields on the lead for Tour Count and Web Submission count but no matter what I try I keep getting this error. Am I calling the SOQL wrong here? 

Error: Didn't understand relationship 'Note__r' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.

as well as Variable does not exist: Note__r
 
public class Notefunctions {     
    
    public static void countofNotesInLead(List<Note> Nte){
        
        Set<Id> parentIds = new Set<Id>();

		for(Note n :Nte) {
			parentIds.add(n.ParentId);
		}
        
        if(!parentIds.isEmpty()){
            List<Lead> leadList = [Select Id,Count_of_Tour_Requests__c,Count_of_Web_Submissions__c, 
                                   (Select Body,Id,ParentId,Title from Note__r 
                                    WHERE Title LIKE '%Web Submission%' 
                                    AND CreatedBy.Username LIKE '%web.integrations@%') 
                                   	from Lead where Id IN:parentIds FOR UPDATE];
            
            Map<Id, Integer> tourNoteMap = new Map<Id, Integer>();
            for(Lead lead: leadList){
                Integer count = 0;
                for(Note note: lead.Note__r){
                    if(note.Body.containsIgnoreCase('In Person Tour') || note.Body.containsIgnoreCase('Virtual Tour')){
                        count++;
                    }
                }
                if(count != 0){
                    tourNoteMap.put(lead.Id, count);
                }
            }
            
            List<Lead> leadUpdateList = new List<Lead>();
            for(Lead l : leadList){
                Boolean isHaveRecs = l.Note__r.size() > 0 ? True : False;
                if(isHaveRecs){
                    l.Count_of_Web_Submissions__c = l.Note__r.size();
                    
                    if(tourNoteMap.containsKey(l.Id)){
                        l.Count_of_Tour_Requests__c = tourNoteMap.get(l.Id);
                    }
                    
                    leadUpdateList.add(l);
                }
            }
            
            if(!leadUpdateList.isEmpty())    update leadUpdateList;
            
        }
    }
}

 
Hello everyone,

I'm have a table which shows the list of Opportunities. I want to show an inner table whenever an opportunity row is clicked. Similar to the following. However, i'm unable to achieve this & not sure what i might be missing. Please share your inputs. Thanks in advance!
<table>
                        <thead >
                            <tr>
                                <th>Opportunity</th>
                                <th>Type</th>
                                <th>Start</th>
                                <th>End</th>
                                <th>Budget</th>
                                <th>More ($)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <apex:repeat value="{!wrap}">
                                <tr>
                                    <td>{!wrap.a}</td>
                                    <td>{!wrap.b}</td>
                                    <td>{!wrap.c}</td>
                                    <td>{!wrap.d}</td>
                                    <td>{!wrap.e}</td>
                                    <td>{!wrap.f}</td>
                                </tr>
                                
                                <!--Inner Table-->
                                <tr>
                                    <div>
                                    <table id="newtable">
                                        <thead id="newth">
                                            <tr>
                                                <th colspan="1">Jan</th>
                                                <th colspan="1">Feb</th>
                                                <th colspan="1">Mar</th>
                                                <th colspan="1">Apr</th>
                                                <th colspan="1">May</th>
                                                <th colspan="1">Jun</th>
                                                <th colspan="1">Jul</th>
                                                <th colspan="1">Aug</th>
                                                <th colspan="1">Sep</th>
                                                <th colspan="1">Oct</th>
                                                <th colspan="1">Nov</th>
                                                <th colspan="1">Dec</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                
                                        </tbody>
                                    </table>
                                    </div>
                                </tr>                                    
                            </apex:repeat>
                        </tbody>
                    </table>

I'm trying to something similar & even tried the following example which didnt work. 
https://www.soliantconsulting.com/blog/multi-tiered-tables-in-visualforce/?unapproved=382305&moderation-hash=7a67877d361da32c66a3507d496a06c3#comment-382305
I am exporting a VF page as Excel document. While I export excel file, Image cell contains blank data. Below is my VF page code. It is working fine if I am using static url (<img alt="Image" src="https://myorgurl/resource/DefaultProfileImage" />) instead of dynamic Image url.
<apex:page controller="Users_Profile" contentType="application/vnd.ms-excel#Users.xls">
        <table border="0" cellspacing="0" cellpadding="0" style="width:100%;">
            <thead>
                <tr>
                    <th>Profile Image</th>
                    <th>Name</th>
                    <th>City</th>
                    <th>State</th>
                </tr>
            </thead>
            <tbody>
                <apex:repeat value="{!lstUsers}" var="user">
                    <tr>
    					<td>
    						<image alt="Image" src="{!BaseUrl}{!URLFOR($Resource.DefaultProfileImage)}" />
    					</td>
                        <td>{!user.Name}</td>
                        <td>{!user.City__c}</td>
                        <td>{!user.State__c}</td>
                    </tr>
                </apex:repeat>
            </tbody>
        </table>
    </apex:page>
I have tried XML structure instead of HTML tags in VF page to get this resolved but it is not working. I referred following answered questions but did not get solution for this.
  1. Exporting image on Excel Sheet from visualforce page.. (https://developer.salesforce.com/forums?id=906F000000097OtIAI)
  2. Visualforce page : Export Results to Excel or CSV (https://developer.salesforce.com/forums/?id=906F00000009UQnIAM)
APEX code:

public with sharing class InnerSOQLQuery {
    
    
    public List<Invoice__c> invList {get;set;}
    
   public List<Item_Detail__c> itemDetail {get;set;}
    
    public  void getRelatedRecords(){
   
     itemDetail = new List<Item_Detail__c>();
            
 invList = [SELECT Invoice_Number_c, Product_Detailsc, (SELECT Name, Quantityc, Ratec FROM Item_Detailsr LIMIT 7) FROM Invoice_c WHERE Id = 'a015w00001FG4gz'];
      
        for(Invoice__c Invs:invList){
            
            for( Item_Detail_c itm:Invs.Item_Details_r){
                itemDetail.add(itm);
                system.debug('Item Name-->'+ itm.Name+ '-->Rate-->'+itm.Rate_c + '-->Quantity-->'+itm.Quantity_c);
            }
        }  
        system.debug('Item Name-->'+ itemDetail);
       
    }
}

VF Code>

<apex:page controller="InnerSOQLQuery"   docType="html-5.0" standardStylesheets="false" applyBodyTag="false" applyHtmlTag="true">

  <apex:pageBlock title="My Content">
    <apex:repeat value="{!invList}" var="acct">
        <apex:outputText value="{!acct.Product_Details__c}"/>
        
        <apex:repeat value="{!acct.Item_Details__r}" var="obj2">
            <apex:outputText value="{!obj2.Name}"/>
        </apex:repeat>
    </apex:repeat>
</apex:pageBlock>
</apex:page>

Result:

User-added image

But my Controller shows proper Output while executing via Anonymous window:

It fetches Child records
I'm trying to override the standard new action for the Product object with a visualforce page. I create the page, and made sure to override the action in "Button, Links, and Action". However, when I click the new button on my Product detail page, which also is a visualforce page that overrides the view action, it still shows the default new action page and not my visualforce one. 

Here is where I overrided the actions with visualforce pages:

User-added image
Here is my visualforce page for the detail view:
User-added imageAnd here is my visualforce page which is supposed to override the new action:
User-added image
 
Hello developers,
I need help.
If InputField in not null then enable InputFile apex tag on VF page.
How to do it.
Please help me.
Thanks in advance
Regards,
Anita sodhi
Hi,

I have a requriment to create list view from VF page.

Is there any way to create listview from apex
Hi there, 
Salesforce Support sent me to this forum since they were unable to help me. I am trying to add two text fields to the front page of a Lightning Opportunity page. See mockup image attachedUser-added image. How do I go about that?

Thanks!
 
Hi ,

Can any one help to get URL for   activities in lightining. 


Thanks in advance.
Hi guys,
i want to share with you a solution I come up with, to wrap long url when rendering a VF page.
Basically the problem was this:
A customer pasted a very long URL (more than 400 chars) in a Rich Text Area. When rendering the page as PDF, to print it, the URL overflow the page margin, so it wasn't visible at all.

This is the code i come up with
private String addWhiteSpaceInUrlTooLong(String text) {
        // Step 1 - Search anchor links
        Pattern ptn = Pattern.compile('<a[^>]*(>.*?)</a>'); // WATCH OUT! This regex doesn't match nested anchor
        Matcher mch = ptn.matcher(text);
        Integer charPerLine = 50; // A whitespace is inserted each charPerLine chars
        while (mch.find()) {
            String toReplace = mch.group(1);
            String substitute = '';
            Integer len = toReplace.length();

            if (len < charPerLine) //No need to replace
                continue;

            Integer elems; // White space to insert

            if (len / charPerLine == 0)
                elems = len / charPerLine;
            else
                elems = len / charPerLine + 1;

            // Insert white spaces
            for (Integer i = 1; i <= elems; i++) {
                if ((charPerLine * i) < len)
                    substitute += toReplace.substring(charPerLine * (i - 1), charPerLine * i) + ' ';
                else
                    substitute += toReplace.substring(charPerLine * (i - 1), len) + ' ';
            }

            text = text.replace(toReplace, substitute);            
        }

        // Step 2 - Search pasted links
        ptn = Pattern.compile('\\b\\s(https?://\\S.*?)(\\s|$)');
        mch = ptn.matcher(text);
        charPerLine = 60;

        while(mch.find()) {
            String toReplace = mch.group();
            String substitute = '';
            Integer len = toReplace.length();

            if (len < charPerLine)
                continue;

            Integer elems;

            if (len / charPerLine == 0)
                elems = len / charPerLine;
            else
                elems = len / charPerLine + 1;

            // Insert white spaces
            for (Integer i = 1; i <= elems; i++) {
                if ((charPerLine * i) < len)
                    substitute += toReplace.substring(charPerLine * (i - 1), charPerLine * i) + ' ';
                else
                    substitute += toReplace.substring(charPerLine * (i - 1), len) + ' ';
            }

            text = text.replace(toReplace, substitute);
        }

        return text;
    }

You could use like this:
MyCustomObject.richText = addWhiteSpaceInUrlTooLOng(MyCustomObject.richText);
Hope it will be useful ;)
 
Hi.

In the VF I used the date format as YYYY-MM-dd in the 
<apex:outputText value="{0,date,YYYY/MM/dd}">
Before the last week of the year it was OK. When the new year falls in the  last week of Decemeber comes the issue.
For example
2014:
S   M  T  W Th F Sat
28 29 30 31 1   2 3

In the above calendar 1st Jan of 2015 falls in the Thurusday.So when I viewd the records of 28,29,30 of December 2014 It showed as
2015-12-28
2015-12-29
2015-12-30
2015-12-31

After that I came to know that
@"YYYY" is week-based calendar year.
@"yyyy" is ordinary calendar year.
http://realmacsoftware.com/blog/working-with-date-and-time

cheers
suresh