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


  • Chatter
    Feed
  • 63
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 521
    Replies
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>


 
Hi,

I have a an object called payment_plan__c which is parent and child payment_detail__c is child.. I want to create a vf page in another object called Bookin__c which has a lookup (Payment_Plan__c) .Need to fetch child record(i.e) Payment_Details_c  Based on the lookup value in booking object on a button click in booking object

Thanks in advance,
Shyam.
I have a requirement that for an account there should be unique email id for every related contact. But in my code it is not working as per the requirement, it is checking all the contacts irrespective of Account. 
But I need to check only Account related contacts email id's.Here is my code please help me where I am doing wrong.

trigger ContactTrigger on Contact (before insert,before update)
 {
   
  set<ID> accId = new set<ID>();
   list<string> ContactEmails=new list<string>();
    for(Contact conVar:trigger.new)
    {
        ContactEmails.add(conVar.email);
        accId.add(conVar.AccountId);
    }
    
    system.debug('ContactEmails ************' +ContactEmails);
    
    list<Contact> listOfDuplicateContacts=[select id,email,Account.ID from Contact where email in :ContactEmails AND AccountID IN : accId];
      system.debug('listOfDuplicateContacts ************' +listOfDuplicateContacts);
    
    for(Contact con:trigger.new)
    {
        if(trigger.isInsert){
        if(listOfDuplicateContacts.size()!=0)
        {
            con.addError('Contact email already exists with this name');
        }
        }
        if(trigger.isUpdate)
        {
           for(Contact oldContact :trigger.old)
           {
               if(con.Email!=oldContact.Email && listOfDuplicateContacts.size()!=0)
               {
                   con.addError('Contact email already exists with this name');
               }
           }
        }
    }
}
  • August 12, 2019
  • Like
  • 0
I have a repeat in a visualforce page that displays the fieds in a fieldset. I want the fields to display in two columns (like the standard detail pages), but they would only display all in one cell when using apex:pageBlockSection. 

I tried to add a span to wrap the repeat to add style of width: 50% and display:inline.
It is displaying in two columns, but there seems to be a line break after each field.

Here is the code
<apex:pageBlockSection title="Information" columns="2">
                <apex:inputField value="{!Projects__c.Name}" label="Project Name" required="true"/>
                <apex:outputField value="{!Projects__c.OwnerId}" />
                <span style="display:inline; width:50%;">                
                    <apex:repeat value="{!$ObjectType.Projects__c.FieldSets.projectFieldSet}" var="f"> 
                        <span style="display:inline; width:50%;">
                            <apex:inputField value="{!Projects__c[f.fieldPath]}" label="{!f.Label}" required="{!OR(f.required, f.dbrequired)}"/>
                        </span>
                    </apex:repeat> 
                </span>                                             
            </apex:pageBlockSection>

and here is what I am getting
visualforce page preview

I want to get rid of all the vertical spaces in between the fields. Any ideas?
Hi i have a custom visual force page , in this i was unable to use onchange event
My VF Page has Account Lookup and salesDistrict lookup ,when user chnage the account  value i have to populate the accout's sales value in sales lookup field. Folowing is my code

<apex:pageBlockSectionItem helpText=" The End User’s physical location" >
Account Name:
<apex:inputField id="oppAccountId" value="{!thisOpp.AccountId}" required="true">
<apex:actionSupport action="{!populatesalesdistrict}" event="onchange" reRender="salesDistrict" status="pageStatus"/> </apex:inputField>
</apex:pageBlockSectionItem>

<apex:pageBlockSectionItem helpText="Auto populated from Account; Enter if blank">
Sales District :
<apex:inputField value="{!thisOpp.Sales_District_lkup__c}" id="salesDistrict" required="true"/>
</apex:pageBlockSectionItem>
 controller: Mrthod:
  Public void populatesalesdistrict(){
       Account thisAcc = [SELECT Id, Sales_District__c,SoldTo__c from Account where ID =: thisOpp.AccountId];
       thisOpp.Sales_District_lkup__c = thisAcc.Sales_District__c;
}
What is alternate if onchange will not work for lookup fields.?
Hey all!
I have a visualforce page using an apex:tabpanel element wrapped in an outputPanel. When I rerender the outputpanel, the formatting of the tabpanel breaks down, showing the content of all tabs stacked on the page instead of only the content of the selected tab. For the tabpanel, I'm using switchtype="client" because I think it's a smoother user experience.

If I had to guess, I would say the tabpanel element is probably using jquery to handle its tab transitions, and when the element is rerendered it's scrubbing some of the script and breaking down the display a little. I've seen some comments around HTML5 elements being scrubbed unless you specify it in the doctype, but I have specified the html-5.0 doctype and it didn't help here.

The best workaround I can think of would be to re-render only all the individual elements within the tabpanel instead of the tabpanel itself, but that would be quite a laborious implementation.

Has anyone faced anything similar or know of a better workaround to rerender a tabpanel without messing up the display format?
Why does my chart has month names on wedges but the sample example doesn't ? 

In my sandbox I  copied and pasted exact code from the salesforce documentation as shown here https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_charting_overview_simple_example.htm

Created a Apex Controller, Created a Wrapper Class, Created a VFP.
 
The output as shown in this example doesn't have month names on the wedges. However the output I get has month names on the wedges. This example doesn't uses rendererFn property. I am wondering why i see month names and the example shown does'nt?

This is my output 
User-added imageHowever I was expecting to see this 

User-added image

Here the Code exactly as copied from the documentation 
 
<apex:page controller="PieChartController" title="Pie Chart">
    <apex:chart height="350" width="450" data="{!pieData}">
        <apex:pieSeries dataField="data" labelField="name"/>
        <apex:legend position="right"/>
    </apex:chart>
</apex:page>



public class PieChartController {
    public List<PieWedgeData> getPieData() {
        List<PieWedgeData> data = new List<PieWedgeData>();
        data.add(new PieWedgeData('Jan', 30));
        data.add(new PieWedgeData('Feb', 15));
        data.add(new PieWedgeData('Mar', 10));
        data.add(new PieWedgeData('Apr', 20));
        data.add(new PieWedgeData('May', 20));
        data.add(new PieWedgeData('Jun', 5));
        return data;
    }

    // Wrapper class
    public class PieWedgeData {

        public String name { get; set; }
        public Integer data { get; set; }

        public PieWedgeData(String name, Integer data) {
            this.name = name;
            this.data = data;
        }
    }
}

 

Hi all,

There are probably steps I can look into to further optimize my visualforce page, but before I start into that, I'm wondering if it's not some sort of browser issue.

 

When I look at my view state size in the developer window it says 79KB. When my field tech tries to open it, it says that the view state has exceeded the limit of 170KB, and is 194KB instead. Why would it be more than 100KB larger when another viewer tries to access it? 

 

I am working on a trail for future method, my method finds the number of contacts on account and updates the "Number of Contacts" field on the Account.

Everyhting is working as expected but in the test class while asserting the output, the SOQL is not pulling this field.

Future Method:
public class AccountProcessor {
    
	@future
    public static void countContacts(List<Id> AccIds){
        
    List<Account> acctsContacts = new List<Account>();
        
    //List<Contact> noOfContacts = new List<Contact>();
        
        //integer noOfContacts;
        
    for(ID accn: AccIds){
            
     //contactsID = [Select ID from Contact where Account.ID = :accn];
            
     //noOfContacts = [Select COUNT() from Contact where Account.ID = :accn];
          
     	acctsContacts =  [Select Name, (Select Firstname, Lastname FROM Contacts)
                          FROM Account
                          WHERE ID =:accn]; 
         
            for(Account accns: acctsContacts){
                
            	integer noOfContacts = accns.Contacts.size();
                System.debug('Number of Contacts' +noOfContacts);
                    
                accns.Number_of_Contacts__c = noOfContacts;                 
                
            	}                        
       
       }        
        
    }

}

Test Method:
 
@isTest
public class AccountProcessorTest {
    
    @isTest
    public static void testcountContacts(){
        
        //Test Data Preparation - Create new accounts
        ID testAccID;
        List<ID> testAccIdsList = new List<ID>();
        List<Account> testAccount = new List<Account>{
            
            new Account(Name ='TestAccount 1'),
            new Account(Name = 'TestAccount 2'),
            new Account(Name = 'TestAccount 3'),
            new Account(Name = 'TestAccount 4')
        };
            
            insert testAccount;  
        
        //Create 2 contact for each Account
        List<Contact>consList = new List<Contact>();
        for (Account eachAccount:testAccount){
            
            for(integer i=0; i<2; i++){
                
               // List<Contact>consList = new List<Contact>{
                    
                  Contact cons = new Contact(Firstname ='Contact'+i, Lastname = 'Test'+i, AccountId = eachAccount.Id);
                  consList.add(cons);
            }
            
        }
        
        insert conslist;
        
        System.debug('Number of Contacts'+conslist.size());
        
        System.debug('Contacts'+conslist);
        
            //Getting the IDs of the Accounts
            for(Account testaccn:testAccount){
                
                //testAccId = [Select ID from Account 
                             //WHERE Account.ID =:testaccn.Id];
                    
                testAccIdsList.add(testaccn.ID);
                
            }
        
        //Test Starts 
        Test.startTest();
         
        AccountProcessor.countContacts(testAccIdsList);
            
        Test.stopTest();
        
           List<Account>accContactPresent = new list<Account>();
        
           System.debug('List of IDs'+testAccIdsList);
           
           for(Id eachaccID :testAccIdsList){
           
                // This SOQL is not pulling the Number_of_Contacts field
                
                Account contactCount = [Select Match_Billing_Address__c, Number_of_Contacts__c from Account 
                                   		WHERE ID= :eachaccID];
               
           		accContactPresent.add(contactCount);
           
           }  
           for(Account foreachContact :accContactPresent){
               
            	System.debug('Contacts Present'+accContactPresent);
            
            	System.assertEquals(2, foreachContact.Number_of_Contacts__c);
               
         }
        
           
    }

}

Log
At line 73: is wehre, I am not able to pull the Number_Of_Contacts field from Account. It is pulling the ID and Match Billing Address field.

Any help would be appreciated.

 
I want to display around 40k markers on the map. I tried like this but maximum is 10 (i read in documentation this is some sort of a limitation).

Here is my code: 
<apex:page standardController="Account" recordSetVar="accounts" >

  <apex:map width="1200px" height="1000px" mapType="roadmap"
    center="42.23  42.23">
        <apex:repeat value="{! accounts }" var="acc">
        <apex:mapMarker title="{! acc.Name }" position="{!acc.BillingLatitude}, {!acc.BillingLongitude},{!acc.BillingCity}, {!acc.Billing_Zip_Postal_Code__c}" />
        </apex:repeat>
  </apex:map>
  </apex:page>

Is there any posibility to do that ? 
  • March 28, 2019
  • Like
  • 1
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!'));  
    }
}

​​​​​​​​​​​​​​
We have a validation rule on our opportunities relating to the close date. this causes errors when converting a lead and creating an opportunity. is there a way to change the default close date and stage used when converting a lead?
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';
    } */

}


 
trigger SpamControllerTrigger on Case (before insert) {
    
    /*===================================================hhjjf====================================*/
    List<String> lstBasedOnDesc=new  List<String>();  
    for(Keywords__c ks:[Select name from Keywords__c])
    {
        lstBasedOnDesc.add(ks.name);
    }
    
    List<String>LstSpamkeyword=new List<String>();
    /*===================================================hhjjf====================================*/
    for(Trigger_Control__c tc:Trigger_Control__c.getAll().values())
    {
        if( tc.Enable_Spam_Controller_Trigger__c==true)
        {
            for(case cs:Trigger.new)
            {
                if(userinfo.getName()=='Automated Workflow') 
                { 
                    if(lstBasedOnDesc.size()>0)
                    {
                        for(String s:lstBasedOnDesc)
                        {
                            if(cs.Description!=null && ( cs.Description).Contains(s))
                            {
                                cs.ownerId='00Gd00000027kH7';
                                cs.Spam_criteria__c='Based on Description';
                                cs.Possible_Spam__c=true;
                                cs.Identified_Keyword__c=s; 
                            } 
                            else if(cs.Subject!=null && (cs.Subject).Contains(s))
                            {
                                cs.ownerId='00Gd00000027kH7';cs.Spam_criteria__c='Based on Subject'; 
                                cs.Possible_Spam__c=true;cs.Identified_Keyword__c=s;
                            }
                            else if((cs.SuppliedEmail).Contains(s))
                            {
                                cs.ownerId='00Gd00000027kH7';
                                cs.Spam_criteria__c='Based on Webmail';
                                cs.Possible_Spam__c=true;
                                cs.Identified_Keyword__c=s;
                            }   
                            if(cs.Subject==null || cs.Description==null)
                            {
                                cs.ownerId='00Gd00000027kH7'; 
                                cs.Spam_criteria__c='Blank Description / Subject';  
                                cs.Possible_Spam__c=true; 
                                cs.Identified_Keyword__c='Blank Subject or Description'; 
                            } 
                            
                        }
                    }
                }
            }
        }
    }
}
Hi All, 

We are getting only 33% code coverage . And rest of lines is showing in red color that not cover. 
my test class is here-
 
@isTest
public class SpamControllerTriggerTest {
    @isTest
    public Static void SpamTestmethod()
    { 
         Profile pf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        
        User tuser = new User(lastName = 'Automated Workflow',
                              email = 'AutomatedWorkflow@test.org',
                              Username = 'AutomatedWorkflow@test123.org',
                              EmailEncodingKey = 'ISO-8859-1',
                              Alias = 'AW',
                              TimeZoneSidKey = 'America/Los_Angeles',
                              LocaleSidKey = 'en_US',
                              LanguageLocaleKey = 'en_US',
                              ProfileId = pf.Id);
        insert tuser;
        
        system.runAs(tuser){
        
        Account acc = new Account(Name='MassBay');
        insert acc;
        
        Contact con = new Contact(AccountId=acc.Id,LastName='test',Email='desd.red@test.tst');
        insert con;
        Trigger_Control__c tc=new Trigger_Control__c();
       tc.Enable_Spam_Controller_Trigger__c=true;
        tc.Name='test tc';
        insert tc;
     
        
     List<case>lstcase=new List<case>();
       List<RecordType> listRecType = [select Id from RecordType where sObjectType = 'Case' And Name = 'MassBayCC_Ticket'];     
    
            Case cs = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id);
          cs.Spam_criteria__c='Based on Description';
        cs.Subject='tesr';
        cs.Description='Test Description1';
        cs.SuppliedEmail='shr.jdd@test.com';
        cs.Possible_Spam__c=true;
        cs.Identified_Keyword__c='s';
          lstcase.add(cs);
          Case cs1 = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id);
          cs1.Spam_criteria__c='Based on Webmail';
        cs1.Subject='tesr';
        cs1.Description='Test Description 2';
        cs1.SuppliedEmail='shr.jdd@test.com';
        cs1.Possible_Spam__c=true;
        cs1.Identified_Keyword__c='s';
          lstcase.add(cs1);
          Case cs2 = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id);
          cs2.Spam_criteria__c='Based on Subject';
        cs2.Subject='tesr';
        cs2.Description='Test Description 3';
        cs2.SuppliedEmail='shr.jdd@test.com';
        cs2.Possible_Spam__c=true;
        cs2.Identified_Keyword__c='s';
        
        lstcase.add(cs2);
          insert lstcase;
          
       
    }
}
}





 
I have created a visualforce page that displays a chatter group. We are using this chatter group mainly to mention records, which require rich text and this visualforce page doesn't seem to have it. 

<apex:page lightningStylesheets="True"   >
  <chatter:feed entityId="0F90v0000008zhtCAA"/>
</apex:page>

This is the code I have. Is there anything I can do to make this rich text or just completely duplicate the chatter group page.
We have a Create New Work Order page in Field Service Lightning (FSL), as a Visualforce page.  One of the fields is a Work Type (picklist), but the order of the picklist is crazy, and I would like it to be in alphabetical order.  I have no idea if this is even possible or what order it is even pulling in.  Below are the only 2 parts of the code that contain Work Order Type.  I am not a developer, so any help is GREATLY appreciated!

  <tr>
                                    <td>
                                        <div class="slds-form-element">
                                            <label class="slds-form-element__label">Work Type *</label>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="slds-form-element__control">
                                            <select id="work-type" class="slds-input" data-api="WorkTypeId">
                                                <option value=""></option>
                                            </select>
                                        </div>
                                    </td>
                                </tr>
_________________________________________________________________________________
var getPicklistOptions = function() {
Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.Kappus_NewWorkOrderButtonController.getWorkTypes}',
            function(workTypes, event) {
                if (event.statusCode === 200) {                   Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.Kappus_NewWorkOrderButtonController.getOptions}',
                    function(options, event) {
                        if (event.statusCode === 200) {
                            var options1 = '',
                                options2 = '',
                                options3 = '';
                            workTypes.forEach(function(workType) {
                                options1 += '<option value="' + workType['Id'] + '">' + workType['Name'] + '</option>';
                            });


 
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.:


 
Hi All !

I am currently generating an excel output with formula in the table: <td>=ROUNDUP(C{!rowNum}*D{!rowNum}/100,0)</td>
The output generated comes in the format:
800000
I actually want the output in the format:
$800,000

How do I achieve this?

Thanks!
Anuj
I'm a new admin and took over for our previous admin. I have very limited knowledge of code and today I changed the email address associated with the account that created these Apex classes and Visual Force pages. I don't understand what is causing this and I don't know how to fix it. Any help is GREATLY appreciated. 


Apex script unhandled exception by user/organization: 0050P000007vNqx/00DU0000000HGNG

Visualforce Page: /apex/QVP_Opp_Details



caused by: NoCustomerNumberException: There is no CRM record associated with this Account

Class.SalesForceWS_Controller_QVP_Opp.<init>: line 29, column 1
 
I am assuming that what I trying to do is pretty basic, I am just fairly new to visual force

I would like an alert to show if a certain condition is met. In this alert I would like to have input fields that can be saved to the record. 

I created this visual force page, but it is not an alert. 
How can I make it into an alert?

<apex:page standardController="Comment__c" rendered="{!if(Comment__c.Care_Management_Related2__c==true,true,false)}">
<apex:form >
        <apex:pageBlock title="Enter Care Management Call Details">
            <apex:pageBlockSection title="Next Suggested Call" columns="1">
                <apex:inputField value="{!Comment__c.Next_Suggested_Call_Date__c}"
                label="next suggested call date"/>
                <apex:inputText value="{!Comment__c.Next_Suggested_Call_Description__c}"
                    label="Next Suggested Call Description"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>
I have a list button from the account record that called up this VF page. The works perfectrly in classic but the page doesn not load in lighteing. Why?
<apex:page standardController="Account"    extensions="UploadAttachmentController">

 <apex:sectionHeader title="{!Account.Name}" subtitle="Attach File"/>
 
 <apex:form id="form_Upload">
 <apex:pageBlock >

 <apex:pageBlockButtons >
   <apex:commandButton action="{!back}" value="Back to {!Account.Name}"/>
   <apex:commandButton action="{!back}" value="Cancel"/>
 </apex:pageBlockButtons>
 <apex:pageMessages />
 
  <apex:pageBlockSection columns="1">
  
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File" for="file_File"/>
      <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/>
    </apex:pageBlockSectionItem>
  
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Type" for="type"/>
      <apex:selectList value="{!selectedType}" size="1" id="type"> 
        <apex:selectOption itemValue="MSA" itemLabel="MSA"/>
        <apex:selectOption itemValue="NDA" itemLabel="NDA"/>

      </apex:selectList>
    </apex:pageBlockSectionItem>
    
   
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Description" for="description"/> 
      <apex:inputTextarea id="description" value="{!description}" rows="4" cols="50"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="" for="uploadBtn"/> 
      <apex:commandButton id="uploadBtn" value="Attach File" action="{!processUpload}" />
    </apex:pageBlockSectionItem>    
    
  </apex:pageBlockSection>
 
 </apex:pageBlock>


 </apex:form>

</apex:page>
I want to import bulk contact records to insert from csv file using vf page.
I am able to insert around 1000 records but if there are than 1000 records, i get an error of 'time limit exceeded'.

Here is my VF Page:
<apex:page controller="UploadCSVController">
    <h1 style="font-size:30px"><center>CSV Uplaod Page</center></h1><br/><br/>

    <apex:form id="idForm">
        <apex:pageMessages /><br/><br/>

        <apex:pageBlock tabStyle="Contact" id="idInputBlock">
            <p style="height:13px; font-size:13px"><b>Set the first column of the CSV file as LastName Field:</b></p><br/>
            <apex:inputFile value="{! fileBody}" fileSize="{! fileSize}" fileName="{! fileName}" accept=".csv" contentType="text/csv" id="idInputFile"></apex:inputFile>                 <!-- Input File -->
            <apex:commandButton value="Upload File" action="{! ReadFromFile}" onclick="document.getElementById('actionStatusUP').style.display = 'inline';" />  <!-- Upload Button to upload file -->
            <img src="/img/loading.gif" style="display:none" id="actionStatusUP" />                    
            <apex:pageBlockButtons location="bottom" >                                                                                                          <!-- Save Button to insert the records -->
                <apex:commandButton value="Save" action="{! save}" rendered="{! reVariableSave}" onclick="document.getElementById('imageSV').style.display = 'inline';" />
                <img src="/img/loading.gif" style="display:none" id="imageSV" />
            </apex:pageBlockButtons>
        </apex:pageBlock>

        <apex:pageBlock rendered="{! reVariableBlock}" id="idTable">
            <apex:pageBlockSection collapsible="false" columns="2" >
                <p><b>Total Records in CSV File:&nbsp;</b></p>
                <apex:outputText value="{! totalRecords}" style="color:black" />
                <p><b>Number of Records Successfully inserted:&nbsp;</b></p>
                <apex:outputText value="{! insertedRecords}" style="color:green" />
                <p><b>Number of Failed Records:&nbsp;</b></p>
                <apex:outputText value="{! failedRecords}" style="color:red" />
            </apex:pageBlockSection><br/>
            <center><p style="color:dodgerblue;font-size:25px"><b>Details of the inserted records</b></p></center><br/><br/>
            <apex:pageBlockTable value="{! contactsList}" rendered="{! reVariable}" var="con" >                                                           <!-- Table to display details of inserted records -->
                <apex:repeat value="{! fieldNamesList}" var="fld" >
                    <apex:column value="{! con[fld]}" />
                </apex:repeat>
            </apex:pageBlockTable>
        </apex:pageBlock>
        
    </apex:form>
</apex:page>
Here is my controller code:
public with sharing class UploadCSVController {

    //Public Variables----------------------------------------------------------------------------------------------------------------------------------------------
    public transient Blob    fileBody{ get; set; }                              //fileBody
    public transient Integer fileSize{ get; set; }                              //fileSize
    public transient String  fileName{ get; set; }                              //fileName
    public List<Contact>     contactsList{ get; set; }                          //List of inserted contacts
    public List<String>      fieldNamesList{ get; set; }                        //List of fields in Contact Object's fields which are avaiable in CSV
    public Boolean           reVariableSave{ get; set; }                        //Variable to render Save Button
    public Boolean           reVariableBlock{ get; set; }                       //Variable to render PageBlock with inserted record details
    public Boolean           reVariable{ get; set; }                            //Variable to render Record Details Table    
    public Integer           totalRecords{ get; set; }                          //Total number of records in CSV File
    public Integer           insertedRecords{ get; set; }                       //Number of records successfully inserted
    public Integer           failedRecords{ get; set; }                         //Number of failed records

    //Private Variables----------------------------------------------------------------------------------------------------------------------------------------------
    String fileBodyAsString = '';                                               //String value of file Body
    String header           = '';

    //Constructor----------------------------------------------------------------------------------------------------------------------------------------------------
    public UploadCSVController(){
        contactsList        = new List<SObject>();
        fieldNamesList      = new List<String>();
        reVariableSave      = false;
        reVariableBlock     = false;
        reVariable          = false;
        totalRecords        = 0;
        insertedRecords     = 0;
        failedRecords       = 0;    
    }

    //Method to check file size and whether the file body is readable------------------------------------------------------------------------------------------------
    public void ReadFromFile(){
        reVariableBlock = false;
		if(fileSize < 3280760 && fileName.substringAfterLast('.').equalsIgnoreCase('csv')){
            try{
                fileBodyAsString = fileBody.toString();
                ReadCSVFile();
            }
            catch(exception e){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error reading CSV file'));
            }
        }
        else{
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'No File Chosen or,'));
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'File Size greater than 50 KB or,'));
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'File is not of CSV type'));
        }
    }

    //Method to read the file and create a contact list which will be inserted and check exceptions in CSV file------------------------------------------------------
    private void ReadCSVFile(){
        if(fileBodyAsString.length() > 100000){
            header = fileBodyAsString.substring(0, 2000).split('\n')[0];
        }
        else{
            header = fileBodyAsString.split('\n')[0];
        }
        fileBodyAsString = fileBodyAsString.substringAfter('\n');

        contactsList.clear();
        fieldNamesList.clear();
        for(String str : header.split('\n')[0].split(',')){
            fieldNamesList.add(str.trim());
        }
        String                      contactDetails      = '';
        Map<string, SObjectField>   fieldNamesMap       = Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap();

        if(fieldNamesList[0].equalsIgnoreCase('LastName')){
            Contact con             = new Contact();
            Integer flag            = 0; 
            while( !String.isEmpty(fileBodyAsString)){                                                                 //Itereation over each contact
                if(fileBodyAsString.length() > 100000){
                    contactDetails = fileBodyAsString.substring(0, 100000).split('\n')[0];
                }
                else{
                    contactDetails = fileBodyAsString.split('\n')[0];
                }
                fileBodyAsString = fileBodyAsString.substringAfter('\n');
                String lastnameValue = contactDetails.substringBefore(',').trim();
                for(Integer j=0; j<fieldNamesList.size(); j++){                                                                 //Iterating over the fields & assigning value to them for each contact 
                    Schema.DisplayType fieldType = fieldNamesMap.get(fieldNamesList[j]).getDescribe().getType();
                    if( fieldType == Schema.DisplayType.DATE ){              //Setting value of fields which are of Date Type
                        try{
                            con.put(fieldNamesList[j].trim(), Date.valueOf(contactDetails.substringBefore(',').trim()));
                        }
                        catch(Exception e){
                            flag = 1;
                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Empty ' + fieldNamesList[j].trim() + ' field or Date is not in format \"YYYY-MM-DD\" for record with LastName = ' + lastnameValue));
                        }
                    }
                    else if( fieldType == Schema.DisplayType.DATETIME ){ //Setting value of fields which are of DateTime Type
                        try{
                            con.put(fieldNamesList[j].trim(), Datetime.valueOf(contactDetails.substringBefore(',').trim()));
                        }
                        catch(Exception e){
                            flag = 1;
                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Empty ' + fieldNamesList[j].trim() + ' field or DateTime is not in format \"YYYY-MM-DD HH:MM:SS\" for record with LastName = ' + lastnameValue));
                        }
                    }
                    else if( fieldType == Schema.DisplayType.BOOLEAN ){  //Setting value of fields which are of Boolean Type
                        if(contactDetails.substringBefore(',').trim().equalsIgnoreCase('true') || contactDetails.substringBefore(',').trim().equalsIgnoreCase('false') || contactDetails.substringBefore(',').trim() == ''){
                            con.put(fieldNamesList[j].trim(), Boolean.valueOf(contactDetails.substringBefore(',').trim()));
                        }
                        else{
                            flag = 1;
                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,  'Acceptable value for ' + fieldNamesList[j].trim() + ' field is \"TRUE/FALSE\" for record with LastName = ' + lastnameValue));
                        }
                    }
                    else if( fieldType == Schema.DisplayType.TEXTAREA ){ //Setting value of fields which are of TextArea Type
                        if(contactDetails.left(1) != '\"'){                                                                 //Setting value of fields which are of TextArea Type with comma
                            con.put(fieldNamesList[j].trim(), contactDetails.substringBefore(',').trim());
                        }
                        else{                                                                                               //Setting value of fields which are of TextArea Type without comma
                            con.put(fieldNamesList[j].trim(), contactDetails.substringBetween('\"', '\"') .trim());
                            contactDetails = contactDetails.substringAfter('\"').substringAfter('\"');
                        }
                    }
                    else{                                                                                                   //Setting value of all other type of fields
                        try{
                            con.put(fieldNamesList[j].trim(), contactDetails.substringBefore(',').trim());
                        }
                        catch(Exception e){
                            flag = 1;
                        }
                    }
                    contactDetails = contactDetails.substringAfter(',');
                }
                contactsList.add(con);
                con = new Contact();
            }                  
            if(flag != 1){                                                                                                  //If there is no exception, show Save button
                reVariableSave = true;
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,  'Click Save Button to insert the Records '));
            }
        }
        else{
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,  'First Column in CSV file is not LastName. Set the first column in CSV file as LastName'));
        }
    }

    //Save method to insert the Contact Recods and counting inserted records and failed records----------------------------------------------------------------------
    public Pagereference save(){
        reVariableBlock = true;
        Database.SaveResult[] srList = Database.insert(contactsList, false);
        contactsList.clear();
        Set<Id> savedContactIdSet = new Set<Id>();
        totalRecords    = 0;
        insertedRecords = 0;
        failedRecords   = 0;
        for (Database.SaveResult sr : srList) {
            ++totalRecords;
            if (!sr.isSuccess()) {
                ++failedRecords;               
                for(Database.Error err : sr.getErrors()) {
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,  err.getStatusCode() + ': ' + err.getMessage() + ' for Record at Line Number: ' + (totalRecords + 1)));
                }
            }
            else{
                ++insertedRecords;
                savedContactIdSet.add(sr.getId());
            }
        }
        contactsList = Database.query('SELECT ' + header + ' FROM Contact WHERE Id in :savedContactIdSet');
        if(contactsList.size() > 0 && contactsList.size()<400){
            reVariable = true;
        }
        return null;
    }
}
Please help me with the solution on how to insert more than 10,000 reocrds without hitting the time limit exceed limt.
 
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