• Dushyant Sonwar
  • PRO
  • 3965 Points
  • Member since 2014
  • Senior Salesforce Developer


  • Chatter
    Feed
  • 89
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 667
    Replies
@AuraEnabled
    public static List<String> getPicklistvalues(String objectName, String field_apiname,Boolean nullRequired){
        List<String> optionlist = new List<String>();       
        Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
        Map<String, Schema.SObjectField> field_map = gd.get(objectName.toLowerCase()).getDescribe().fields.getMap();        
        List<Schema.PicklistEntry> picklistValues = field_map.get(field_apiname).getDescribe().getPickListValues();       
        if(nullRequired == true){
            optionlist.add('--None--');
        }       
        for (Schema.PicklistEntry pv : picklistValues) {
            optionlist.add(pv.getValue());
        }
        return optionlist;
    }
Dear. 
This seems an easy question with easy solution, but I don't find a technical solution after look in google, developer salesforce, etc.

This is what I want: I need to perform a set of validations in a lot of custom field values of the Opportunity. After see different options (process builder, validation rules, formulas, etc) the best approach if to use a VisualForce page. In that VisualForce page I want to show a text custom field, with a custom error message that can change via visualforce/javascript code.

This is my issue: I am not able to change the text custom field value. I have no erros. Just no changes on the text value. Below is the code I used in the VisualForce page.

Do you have any suggestion?
 
<apex:page standardcontroller="Opportunity">

    <apex:form id="formId">
        <apex:pageblock id="pb">
        
            <apex:pageBlockSection id="Block1" title="Opportunity Information" columns="2">
        
                <apex:inputField id="Warning_message" value="{!Opportunity.Warning_message__c}" />
                
            </apex:pageBlockSection>

        
        </apex:pageblock>
    </apex:form>
               
           
    <script type="text/javascript">
    
        function myFunction() 
        {
            document.getElementById('{!Opportunity.Warning_message__c}').value = "This will not change the value";
            document.getElementById('{!Opportunity.Warning_message__c}').innerHTML= "This will not change the value";
            document.getElementById('Warning_message').value = "This will not change the value";
            document.getElementById('Warning_message').innerHTML= "This will not change the value";            
            document.getElementById('{!$Component.formId.pb.Block1.Warning_message}').value = "This will not change the value";            
        }    
                            
        var msgObj= document.getElementById('{!Opportunity.Warning_message__c}');
        msgObj.value = "This will not change the value";            
        msgObj.innerHTML= "This will not change the value";            

    </script>
    
</apex:page>

Many thanks.
 
Hi all,

Newbie here.

I've got the following VF code that generates a Word doc when an action button is pressed on a custom object (Contract_Work_Order__c).

I'm trying to retrieve a contact's full name based on its id.  The field below is returning the Contact ID.  

{!Contract_Work_Order__c.Contractor__c}

I essentially need to write the following select statement and return the value.
Select name from contacts where Id ={!Contract_Work_Order__c.Contractor__c}

Here's the current VF page:
 
<apex:page standardController="Contract_Work_Order__c" contentType="application/msword#MSA_{!Contract_Work_Order__c.Id}.doc" sidebar="false" standardStylesheets="false" applyBodyTag="false">

<div style="font-family:sans-serif;"> 
<center>
<h4>MASTER SUB-CONSULTANT AGREEMENT</h4>
</center>
</div>
 
<div style="font-family:sans-serif;text-align:left;font-size:10pt;">
<p>This MASTER SUB-CONSULTANT AGREEMENT ("Agreement") is made and entered into as of <apex:outputText value=" {!TODAY()}"/> (“Effective Date”), 
by and between XYZ, and <apex:outputText value=" {!Contract_Work_Order__c.Contractor__c}"/> ("Sub-Consultant”), each individually sometimes referred to as a “Party” and collectively as “Parties”.</p>
 
<p>Your account details are:</p>
 
<table>
<tr><th>Opportunity Name</th>
    <td><apex:outputText value="{!Contract_Work_Order__c.Opportunity__c}"/></td>
    </tr>
<tr><th>Account Rep</th>
    <td><apex:outputText value="{!Contract_Work_Order__c.Account_Rep__c}"/></td>
    </tr>
<tr><th>Customer Since</th>
    <td><apex:outputText value="{0,date,long}">
        <apex:param value="{!Contract_Work_Order__c.CreatedDate}"/>
        </apex:outputText></td>
    </tr>
</table>
    
<p>It's a pleasure to have you on board.  Please do not hesitate to contact us should you have any questions or concerns.</p>
    
<p>Sincerely,</p>
    
<p><apex:outputText value="{!Contract_Work_Order__c.CreatedById}"/></p>
</div>
    
</apex:page>

I'm stuck and would appreciate your pointers!

Thank you.

 
======================
Main Class
======================

global class ScheduleInvoice implements Schedulable {
    public static String CRON_EXP = '0 0 0 1 * ? *';
    global static String scheduleIt() {
        ScheduleInvoice sm = new ScheduleInvoice();
        return System.schedule('Monthly Reconciliation', CRON_EXP, sm);
    }
    global void execute(SchedulableContext sc) {Id AccountEIDrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('EID').getRecordTypeId();
        Id AccountPVCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('PVC').getRecordTypeId();
        Id AccountPMCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('PMC').getRecordTypeId();
        Id AccountVMCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('VMC').getRecordTypeId();
        Id InvoiceVRCrecordTypeId = Schema.getGlobalDescribe().get('Invoice__c').getDescribe().getRecordTypeInfosByName().get('VRC').getRecordTypeId();
        
        set<ID> recordIds = new Set<ID>();
        recordIds.add(AccountEIDrecordTypeId);
        recordIds.add(AccountPVCrecordTypeId);
        recordIds.add(AccountPMCrecordTypeId);
        recordIds.add(AccountVMCrecordTypeId);
        
        List<Invoice__c> invoiceList = new List<Invoice__c>();
        List<Invoice__c> invList = new List<Invoice__c>();
        Integer m = Date.Today().Month();
        Date firstDayOfMonth = System.today().toStartOfMonth();
        Date lastDayOfMonth = firstDayOfMonth.addDays(Date.daysInMonth(firstDayOfMonth.year(), firstDayOfMonth.month()) - 1);
        Date invDesDate = system.Today().addMonths(1);
        Integer invMonth = invDesDate.Month();
        Integer invYear = invDesDate.year();
        String MonthName;
      
        for (Account acct: [
            select Id, Active__c RecordTypeId
            from Account
            where RecordTypeId IN: recordIds and Active__c = true
        ]) {
                Invoice__c inv = new Invoice__c();
                inv.Account__c = acct.Id;
                inv.Status__c = 'Accepted';
                inv.Date__c = system.Today();
                switch on m {
                    when 1 {        
                        invoiceDate__c = 'Jan 1 to Jan 31';
                    }    
                    when 2 {        
                        invoiceDate__c = 'Feb 1 to Feb 28';
                    }
                    when 3 {
                        invoiceDate__c = 'Mar 1 to Mar 31';
                    }
                    when 4 {          
                        invoiceDate__c = 'Apr 1 to Apr 30';
                    }
                     when 5 {        
                        invoiceDate__c = 'May 1 to May 31';
                    }    
                    when 6 {        
                        invoiceDate__c = 'Jun 1 to Jun 30';
                    }
                    when 7 {
                        invoiceDate__c = 'Jul 1 to Jul 31';
                    }
                    when 8 {          
                        invoiceDate__c = 'Aug 1 to Aug 31';
                    }
                    when 9 {        
                        invoiceDate__c = 'Sep 1 to Sep 30';
                    }    
                    when 10 {        
                        invoiceDate__c = 'Oct 1 to Oct 31';
                    }
                    when 11 {
                        invoiceDate__c = 'Nov 1 to Nov 30';
                    }
                    when 12 {          
                        invoiceDate__c = 'Dec 1 to Dec 31';
                    }
                }                                                                                                                
                   inv.Payment_Due_Date__c =  lastDayOfMonth; 
                switch on invMonth {
                    when 1 {        
                        MonthName = 'January';
                    }    
                    when 2 {        
                        MonthName = 'February';
                    }
                    when 3 {
                        MonthName = 'March';
                    }
                    when 4 {          
                        MonthName = 'April';
                    }
                     when 5 {        
                        MonthName = 'May';
                    }    
                    when 6 {        
                        MonthName = 'June';
                    }
                    when 7 {
                        MonthName = 'July';
                    }
                    when 8 {          
                        MonthName = 'August';
                    }
                    when 9 {        
                        MonthName = 'September';
                    }    
                    when 10 {        
                        MonthName = 'October';
                    }
                    when 11 {
                        MonthName = 'November';
                    }
                    when 12 {          
                        MonthName = 'December';
                    }
                }
            inv.RecordTypeId = InvoiceVRCrecordTypeId;
                inv.Description__c = MonthName + ' ' + String.valueof(invYear) + ' ' + 'TMC';
                
               invList.add(inv);
        }
          
        if (!invList.isEmpty()) {
            insert invList; 
        }   
    }
}

===========================
Test Class
===========================
@isTest
public class CreatingInvoice_Test {
    @isTest static void executeTest(){
        
        Test.startTest();
        
        Id AccountPVCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('PVC').getRecordTypeId();
        Id AccountPMCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('PMC').getRecordTypeId();
        Id AccountVMCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('VMC').getRecordTypeId();
        Id InvoiceVRCrecordTypeId = Schema.getGlobalDescribe().get('Invoice__c').getDescribe().getRecordTypeInfosByName().get('VRC').getRecordTypeId();
        
        SchedulableContext sc = null;
        ScheduleInvoice CI = new ScheduleInvoice();
        CI.execute(sc);
        
        account a = new account();
        a.Name = 'Test Account';
        a.Active__c = true;
        a.RecordTypeId = AccountVMCrecordTypeId;
        
        insert a;
        
        ScheduleInvoice CI1 = new ScheduleInvoice();
        String sch1 = '0 0 0 1 * ? *'; 
        system.schedule('ScheduleInvoice', sch1, CI1);
        
        Test.stopTest();
    }
}
display get response data in vf page, json response please help 

VF page :

<apex:page controller="RESTAPIJSONResponseController">
    <apex:form >
        <apex:pageBlock >            
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Fetch" action="{!fetchAPI}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
        
        <apex:pageblock >
            <apex:pageBlockSection >
                <apex:pageBlockTable value="{!listWrapper}" var="obj">
                    <apex:column value="{!obj.rates}" headerValue="Id"/>
                    <apex:column value="{!obj.base}" headerValue="Login"/>
                    

 

                    
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>

Controller: 
public with sharing class RESTAPIJSONResponseController {

    public List < JSONWrapper > listWrapper {get;set;}
    
    public RESTAPIJSONResponseController() {
        listWrapper = new List < JSONWrapper >();
    }
    
    public void fetchAPI() {
        HTTP h = new HTTP();
        HTTPRequest req = new HTTPRequest();
        req.setEndPoint('https://theforexapi.com/api/latest?HTTP/2');
        req.setMethod('GET');
        HTTPResponse res = h.send(req);  
        JSONParser parser = JSON.createParser(res.getBody());
        listWrapper = (List < JSONWrapper >) JSON.deSerialize(res.getBody(), List < JSONWrapper >.class);
        system.debug(''+res.getBody() );
        /*
           If the response contains only one value instead list, then you can use the below code
           JSONWrapper obj = (JSONWrapper) JSON.deSerialize(res.getBody(), JSONWrapper.class); 
           listWrapper.add(obj);
        */
    }
    
    public class JSONWrapper {
        
        public String base {get;set;}
        public String rates {get;set;}
        
    }
    
}

JSON Response :  in system.debug
"{\"date\":\"2021-07-07\",\"base\":\"EUR\",\"rates\":{\"USD\":\"1.1831\",\"JPY\":\"130.86\",\"BGN\":\"1.9558\",\"CZK\":\"25.688\",\"DKK\":\"7.4361\",\"GBP\":\"0.85500\",\"HUF\":\"355.57\",\"PLN\":\"4.5192\",\"RON\":\"4.9268\",\"SEK\":\"10.1813\",\"CHF\":\"1.0917\",\"ISK\":\"146.30\",\"NOK\":\"10.2475\",\"HRK\":\"7.4867\",\"RUB\":\"87.8009\",\"TRY\":\"10.2566\",\"AUD\":\"1.5711\",\"BRL\":\"6.1224\",\"CAD\":\"1.4708\",\"CNY\":\"7.6478\",\"HKD\":\"9.1900\",\"IDR\":\"17146.47\",\"INR\":\"88.2825\",\"KRW\":\"1344.89\",\"MXN\":\"23.5724\",\"MYR\":\"4.9241\",\"NZD\":\"1.6760\",\"PHP\":\"58.960\",\"SGD\":\"1.5924\",\"THB\":\"38.173\",\"ZAR\":\"16.8666\"}}"

Visualforce Error:
System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set
Error is in expression '{!fetchAPI}' in component <apex:commandButton> in page forexconv: Class.System.JSON.deserialize: line 15, column 1
Class.RESTAPIJSONResponseController.fetchAPI: line 16, column 1

Need to display This format :
Need to display this format
To This  Type : 
User-added image

Please Help With this Issue,
Thanks in Advance.




 
I'm creating a simple VFP to render as PDF and I would like to get some picklist fields. The problem is that I'm getting the API Name and not the label value. There's a way to do it using only VFP?

Example of how I'm doing:
Status: <br/>{!CPRMinutes__c.Status__c}
User-added imageHi Team,

I want to display error mesg when we select 'Other-Explain'.
<apex:page showHeader="false" action="{!InitMethod}" cache="false" controller="AH_HN_PhysicianAcceptnReject_CLS" tabStyle="Case">
    <apex:includeScript value="/soap/ajax/36.0/connection.js"/>
    <apex:includeScript value="/soap/ajax/36.0/apex.js"/>
    <apex:includeLightning />
    <apex:Pagemessages />
    
    <head>
        <apex:slds />
        <div class="slds-align_absolute-center">
            <apex:image url="{!$Resource.AH_Physician_Expert_Template_Logo}" />
        </div>
    </head>
    
    <apex:form >
        <div class="slds-align_absolute-center">
            
            <apex:outputText rendered="{!ThanksmsgAccpt}">
                <span style="font-size:20px;font-weight:bold;" class="slds-m-top_xx-large">Thank you for accepting, the case has now been added to your dashboard.  Please log into the physician portal to begin your review.</span>
            </apex:outputText> 
            
            <!--
<apex:outputText rendered="{!ThanksmsgRejec}">
<span style="font-size:20px;font-weight:bold;" class="slds-m-top_xx-large">Thank you for rejecting the case.<br/> </span>
</apex:outputText>
-->
            
            
            <apex:outputText rendered="true">
                <apex:pageBlock >
                    <!-- span style="font-size:20px;font-weight:bold;" class="slds-m-top_xx-large">Thank you for rejecting the case.<br/><br/> </span -->
                    
                    <p>Please select the reason:</p>
                    <apex:actionRegion >
                    <apex:selectList id="Pleaseselectthereason" size="1" label="caseRejectReason"  value="{!caseRejectReason}">
                        <apex:selectoption itemLabel="Out of office-cannot complete due to existing workload" itemValue="Out of office-cannot complete due to existing workload"></apex:selectoption>
                        <apex:selectoption itemLabel="I recommend another physician more suitable for this case.Enter Name in Free Text Box" itemValue="I recommend another physician more suitable for this case.Enter Name in Free Text Box"></apex:selectoption>
                        <apex:selectoption itemLabel="Other - explain" itemValue="Other - explain"></apex:selectoption>
                        <!--<apex:actionSupport event="onchange" reRender="comments" />-->
                    </apex:selectList>
                    </apex:actionRegion>
    
                    <br/>
                    
                    <p>Comments:</p>
                    <apex:inputTextarea label="Comments" style="width:550px;height:100px" id="comments" value="{!caseRejectComment}"/> 
                    
                    <br/><br/>
                    
                    <div align="center" draggable="false" >
                        <apex:commandButton action="{!saveRejectInfo}" value="Save"/>
                    </div>
                    
                </apex:pageBlock>
            </apex:outputText>
            
            <apex:outputText rendered="{!rejectreasonmessage}">
                <span style="font-size:20px;font-weight:bold;" class="slds-m-top_xx-large">Thank you for rejecting the case.</span>
            </apex:outputText>
            
            
            
            
            <apex:outputText rendered="{!Assignedtoothers}">
                <span style="font-size:20px;font-weight:bold;" class="slds-m-top_xx-large">This case has already been assigned to some other physician.</span>
            </apex:outputText>
            <apex:outputText rendered="{!AlreadyAccepted}">
                <span style="font-size:20px;font-weight:bold;" class="slds-m-top_xx-large">You have already accepted the case.</span>
            </apex:outputText>
            <apex:outputText rendered="{!AlreadyRejected}">
                <span style="font-size:20px;font-weight:bold;" class="slds-m-top_xx-large">You have already rejected the case.</span>
            </apex:outputText>
        </div>   
        
        
    </apex:form>
</apex:page>
                                        
Regards,
Isha
global with sharing class products {
    @AuraEnabled
    public static List<PricebookEntry> getproduct() {

   List<PricebookEntry> prod= [SELECT Product2.Name, Unitprice FROM PricebookEntry];
  return prod;

    }
}

component--
<aura:component controller="products" > 
<aura:attribute name="productname" type="PricebookEntry[]"/>
<aura:attribute name="cols" type="List"/>  
     
    <aura:handler name="init" value="{!this}" action="{!c.doinit}"/>
   
    <lightning:datatable
            data="{!v.productname}"
            columns="{!v.cols}"
            keyField="Id"
            onrowaction="{!c.onRowAction}"/>
   
       
</aura:component>

controller---
({
	doinit : function(component) {
       component.set( 'v.cols' , [
            {
                'label': 'Name',
                'fieldName': 'Name',
                'type': 'text'
            },
{label': 'Price',
                'fieldName': 'Price',
                'type': 'Currency'
},
            {
                'label': 'Action',
                'type': 'button',
                'typeAttributes': {
                    'label': 'Add to Cart',
                    'name': 'view_details'
                }
            },
            {
                'label': 'Action',
                'type': 'button',
                'typeAttributes': {
                    'label': 'Buy',
                    'name': 'view_details'
                }
            }
            ]);
        
  var action = component.get("c.getproduct"); 
        // var self = this;
        action.setCallback(this, function(actionResult) {
            var state = actionResult.getState();
        if (state === "SUCCESS") {
          component.set("v.productname", actionResult.getReturnValue());
            component.set("v.productprice",actionResult.getReturnValue());
        }
            });
          $A.enqueueAction(action);
    },
		
	
})

Name and price of the products is not showing in datatable, but soql is executing successfully. What to do?
<div class="col-md-7">
    <apex:inputSecret value="{!newPassword}" styleClass="form-control newPass formControl" />
</div>
<!--New Addition-->
<div class="panel conditionPanel" rendered="{!ISBLANK(newPassword)}">
    <ul class="list-unstyled font-12">
        <h5 class="font-12"><span class="glyphicon glyphicon-info-sign" /><strong>{!$Label.passwordmanage}</strong> </h5>
    </ul>
</div>

I wanted show next div only when user type something in new password
I have a command button that creates a record and when it is saving it freezes for a few seconds whilst it is executing. I cannot figure a way to display that it is saving so people dont just reclicking the button. Ive seen people display a gif whilst saving but im unable to find a way to replicate this function or even display in text that it is saving
 
<apex:form style="margin: 10px; color:#322c4f">
                                    <span style="font-size:1.25em">Request callback</span>    
                                    <table style="color:#322c4f">
                                    <tr>
                                        <td colspan="2" style="color:#322c4f">
                                            User:
                                        </td>
                                        <td style="color:#322c4f">
                                            {!$User.FirstName} {!$User.LastName}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" style="color:#322c4f">
                                            Date &#038; Time: 
                                        </td>
                                        <td style="color:#322c4f">
                                            <apex:outputText value="{0,date,dd/MM/yyyy HH:mm}"><apex:param value="{!NOW()}" /></apex:outputText>
                                        </td>
                                    </tr>
                                    <tr>
                                    </tr>
                                    <tr>
                                    <td colspan="2" style="color:#322c4f">
                                    Interested In:
                                    </td>
                                    <td style="color:#322c4f">
                                    DashCams
                                    </td>
                                    </tr>
                                    </table>
                                    <br/>
                                     <span style="padding-left: 1px">Contact:
                                    <apex:selectList multiselect="false" value="{!selectedContact}" size="1">
                                    <apex:selectOptions value="{!contacts}">
                                    </apex:selectOptions>
                                    </apex:selectList><br/>
                                
                                    Notes:<br/>
                                    <apex:inputTextarea value="{!Notes}" rows="3" style="width:50%; border: 1px solid #322c4f; color: #322c4f; margin-left:2px" /></span>
                                    <apex:commandButton styleClass="logger" value="Save" action="{!save}" style="width:25%;float: right; margin-top:40px;border: 1px solid #322c4f; color:white; padding: 10px 5px"/>
                                </apex:form>

 
Hi guys,
Been working on this for a while but unable to fugure out. 
i want to render the table only based on the click of the buttons i.e,
if i click the open cases the table should  filter and load all the open cases and 
if i click the closed cases the table should filter and load all the closed cases and like that.
but iam not able to comprehend this. 
can anyone please help me figure this out.
User-added image

---------------------------------apex controller----------------------------
public class portalCases {
    @AuraEnabled
    public static list <Case> fetchCase() {
        Return [SELECT CaseNumber,Category__c,Case_Sub_Category__c,Subject,CreatedDate FROM Case];
        
    }
}
----------------------------------component------------------------------
<aura:component controller="portalCases" implements="force:appHostable,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global">
        
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
    
    <aura:attribute name="lstAllCase" type="Case[]"/>
    
    <div class="slds-m-around_xx-large, slds-align_absolute-center" id="myDIV">
        &nbsp;&nbsp;&nbsp;&nbsp;
        <button class="btn active" onclick="{!c.myAction}">Open Cases</button>&nbsp;&nbsp;&nbsp;&nbsp;
        <button class="btn" onclick="{!c.myAction}">Closed Cases</button>&nbsp;&nbsp;&nbsp;&nbsp;
        <button class="btn" onclick="{!c.myAction}">All Cases</button>&nbsp;&nbsp;&nbsp;&nbsp;
    </div>
    
    <div class="slds-m-around_medium">
        <table id="tableId" class="slds-table slds-table_bordered slds-table_cell-buffer" cellspacing="0" width="100%" >
            <thead>
                <tr>
                    <th>Case Number</th>
                    <th>Category</th>
                    <th>Sub Category</th>
                    <th>Subject</th>
                    <th>Created Date</th> 
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.lstAllCase}" var="cas">
                    <tr>
                        <td>{!cas.CaseNumber}</td>
                        <td>{!cas.Category__c}</td>
                        <td>{!cas.Case_Sub_Category__c}</td>
                        <td>{!cas.Subject}</td>
                        <td>{!cas.CreatedDate}</td>
                    </tr>
                </aura:iteration>  
            </tbody>
        </table>
    </div>
    
</aura:component>

----------------------------------JScontroller-------------------------------------
({    
    doInit : function(component,event,helper){
        //call apex class method
        var action = component.get('c.fetchCase');
        action.setCallback(this, function(response) {
            //store state of response
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.lstAllCase', response.getReturnValue());          
            }
        });
        $A.enqueueAction(action); 
    },
    
    myAction : function(component, event, helper) {
        // Get the container element
        var btnContainer = document.getElementById("myDIV");
        
        // Get all buttons with class="btn" inside the container
        var btns = btnContainer.getElementsByClassName("btn");
        
        // Loop through the buttons and add the active class to the current/clicked button
        for (var i = 0; i < btns.length; i++) {
            btns[i].addEventListener("click", function() {
                var current = document.getElementsByClassName("active");
                current[0].className = current[0].className.replace(" active", "");
                this.className += " active";
            });
        }
    },
})
----------------------------CSS---------------------------
.THIS {
}

.THIS .btn {
    border: none;
    outline: none;
    padding: 10px 16px;
    border-radius: 8px;
    background-color: #f1f1f1;
    cursor: pointer;
}

/* Style the active class (and buttons on mouse-over) */
.THIS .active, .THIS .btn:hover {
    background-color: #1f0663;
    color: white;
}
Dear Pals,

I need to  Fire ShowNavigateToList After ShowToast On Single Save Function Of JS file,somehow only ShowToast working and not the ShowNavigateToList,Here is  what i have written for Save button,basically after the record is Upserted i want the page to move to ListView,what change is needed below
 
onConfirm:function(component, event, helper){
        var picklist=component.find('ddLevel1');
        var picklistvalue=picklist.get('v.value');
        var picklistdep=component.find('ddLevel2');
        var picklistvaluedep2=picklistdep.get('v.value');
        var picklistoldL1=component.get('v.oldL1');
        var picklistoldL2=component.get('v.oldL2');
        var picklistoldL3=component.get('v.oldL3');
        var ertrecordGuid=component.get('v.ertGUID');
        var picklistdep3=component.find('ddLevel3');
        var picklistvaluedep3=picklistdep3.get('v.value');
        var action = component.get("c.savecasetype");
       
        action.setParams({  'level1' : picklistvalue,
                          'level2' : component.get('v.secondlevelselected'),
                          'level3' : picklistvaluedep3,
                          'oldlevel1' : picklistoldL1,
                          'oldlevel2' : picklistoldL2,
                          'oldlevel3' : picklistoldL3,
                          'guid':ertrecordGuid,
                          'id' : component.get("v.recordId")});
        
        
        var toastEvent = $A.get("e.force:showToast");
        action.setCallback(this, function(e) {
            if(e.getState()=='SUCCESS'){
                var result=e.getReturnValue();
                        
                
                if(result==='successfull'){
                    toastEvent.setParams({
                        "title": "Success!",
                        "message": "The record has been Upserted  successfully."
                         
                    });
                    
                    toastEvent.fire();
                   
                }else{
                   
                    toastEvent.setParams({
                        "title": "Error",
                        "message": "The record has not been Upserted  successfully."
                    });
                    toastEvent.fire();
                }
            }
            
            
          
             $A.get('e.force:refreshView').fire(); 
             
        });
        
           var action = component.get("c.getListViews");
    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === "SUCCESS") {
            var listviews = response.getReturnValue();
            var navEvent = $A.get("e.force:navigateToList");
            navEvent.setParams({
                "listViewId": listviews.Id,
                "listViewName": null,
                "scope": "Case"
            });
            navEvent.fire();
        }
    });
        $A.enqueueAction(action);
        
          
        
    }

Here is ListView controller
 
@AuraEnabled 

public static List<ListView> getListViews() { 

    List<ListView> listviews = 

        [SELECT Id, Name FROM ListView WHERE SobjectType = 'Case' and Name='Recently Viewed Cases']; 

  

   

    return listviews; 

}



Your help is needed and appreciated
Regards,
Fiona​​​​​​​

 
Hi Everyone, 

I'm working on a pdf export for Opportunities using a Visualforce page. I am able to grab all the data I need but I can't figure out how to display my lookup data fields properly in the export. 

Here is the instance of the lookup field being used:
User-added image

It is pulling data from Contacts:
User-added image

and in the export it displays as the ID and not the name:
User-added image
I have tried using ".name" in my code: <apex:outputText value="{!Opportunity.Designer_Name__c.Name}"/>

but I get this error: Error: Unknown property 'String.Name'

Any help would be greatly appreciated, thank you!
Hello,

I created a visual force page (and a custom button) which updates the account ownership from a list view. I would like to add inline editing to the below. Could you please assist me?

<apex:page standardController="Account" recordSetVar="accounts" tabStyle="Account" sidebar="false" lightningStylesheets="true">
    <apex:form >
        <apex:pageBlock title="Edit Accounts" mode="edit">
            <apex:pageMessages />
            <apex:pageblockButtons location="top">
                <apex:commandButton value="Save" action="{!Save}" />
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>
        <apex:pageBlockTable value="{!selected}" var="A">
            <apex:column headerValue="Name">
                <apex:outputField value="{!A.name}"/>
            </apex:column> 
            <apex:column headerValue="Owner">
                <apex:inputField value="{!A.OwnerId}"/>
            </apex:column>
       </apex:pageBlockTable>         
    </apex:pageBlock>
  </apex:form>
</apex:page>
I am using apex:chart tag on visualforce page, to display a chart to community users having a "Customer Community Login" license.

I've added the VF component on builder, enabled the respective VF page and controller class. But when I publish the changes, those changes don't reflect on the community for users.

What is the problem here? How should I resolve it?
 
Hi and appreciate any insight on this.

My save button no longer works.  It was a VS button.  I made a new List View button calling VFP/ APEX  Not sure what went wrong here.  

Button
 
User-added image

VFP.
<apex:page standardController="Case" recordSetVar="cases" lightningStylesheets="true" extensions="setQuickCaseExtensionController"> 
    <apex:form >
        <apex:pageBlock title="Quick Case Entry" mode="edit">
            <apex:pageMessages id="showmsg"></apex:pageMessages>
            
            <apex:pageBlockSection title="Case Details" columns="1">                 
                                
              <apex:inputField label="Source Type" required="true" value="{!case.Source_Type__c}" /> 
              <apex:inputField label="Origin" required="true" value="{!case.Origin}"/>  
              <apex:inputField label="Contact" value="{!case.ContactId}"/> 
              <apex:inputField label="Subject" required="true" value="{!case.Subject}"/> 
              <apex:inputTextArea style="width:300px;height:100px" required="true" label="Description (Min 10 chars)"  value="{!case.Description}"/>
              <apex:inputField label="Category" required="true" value="{!case.Category__c}"/> 
              <apex:inputField label="Sub-Catagory 1" required="true" value="{!case.Sub_Catagory_1__c}"/>  
              <apex:inputField label="Sub-Catagory 2" required="true" value="{!case.Sub_Category_2__c}"/>  
              <apex:inputField label="Sub-Catagory 3" required="true" value="{!case.Sub_Category_3__c}"/>              
              <apex:inputField value="{!case.Related_Account__c}" label="Account"/>          
              <apex:inputField value="{!case.Incident_Occurence_Date__c}" label="Incident Occurrence Date"/>
              <apex:inputField value="{!case.Incident_Occurrence_Time__c}" label="Incident Occurrence Time"/>  
             </apex:pageBlockSection>   
            
            <apex:pageBlockButtons > 
                <apex:commandButton value="Save & Close Quick Case" action="{!save}"/> 
                <apex:commandButton value="Cancel" action="{!cancel}"/> 
            </apex:pageBlockButtons> 
                       
          
        </apex:pageBlock> 
    </apex:form>
</apex:page>

APEX Class

public class setQuickCaseExtensionController {
   private Case QC; 
   public ApexPages.StandardSetController stdController; 
   public setQuickCaseExtensionController(ApexPages.StandardSetController controller){
        controller.setPageSize(10);
        this.QC = (Case)controller.getRecord(); 
        RecordType RecId = new RecordType();
        RecId=[SELECT Id FROM RecordType where Name='Customer First' LIMIT 1];
        QC.RecordTypeId=RecId.Id;
        QC.Quick_Case__c = True;
        QC.Origin = 'Phone';
        QC.Source_Type__c = 'Consumer';
        QC.Description='Quick Case';
        QC.Quick_Case_Closed__c = True;
        QC.Subject='New Quick Case';
        stdcontroller=controller;        
    }

}
I have a visualforce page where a user inputs serial numbers for an asset (New_Asset_Install_LOC_Serial_Number__c), I need this serial number input field to update the main serial number field on the asset Object (SerialNumber). Currently the New_Asset_Install_LOC_Serial_Number__c field is being updated on the asset, but I also need this value to populate the SerialNumber field on the asset.

Here is my visualforce code:
<apex:page docType="html-5.0" standardController="Case" extensions="installTicketUpdateAssetClass" id="thePage"> 
   
    
    <style>
    .installSerialNumber{
        }
    .setupSerialNumber {
        }
    .setupModel {
        }
    .setupModelForId {
        }
    .verify{
        }
    .update{
        }
    .autoSerialCheck{
        }
    .idNumber{
        }
    .ipAddress{
        }
    .locationRemarks{
        }
    .installNotes{
        }
    .serialDoesntMatch{
        }
    .serialDoesntMatchCheckBoxOnAsset{
        }
   
    </style>
    <p></p>


    <apex:form id="theForm"> 
        <apex:pageblock id="Assets">

            <apex:pageBlockSection id="pbs" columns="1"> <!-- to allow the apex:input to show the label -->
                
                <apex:pageBlockTable rows="1" id="pbt3" value="{!Case.Assets__r}" var="asset">
                
                    <apex:column style="width:12%;" headerValue="Product Code"><!-- to take the label dynamically -->
                         <apex:inputText style="width:80%;" disabled="true" styleClass="setupModelForId" value="{!asset.Product_Code_for_Paperless_Install_Docs__c}"  />
                    </apex:column>
                    
            		<apex:column style="width:11%;" headerValue="ID Number"><!-- to take the label dynamically -->
                        <apex:inputText required="true" style="width:80%;" styleClass="idNumber" value="{!asset.New_Asset_Install_LOC_ID_Number__c}"  />
                    </apex:column>
                    
                    <apex:column style="width:10%;" headerValue="B/W Starting Meter"><!-- to take the label dynamically -->
                        <apex:inputText required="true" styleClass="bwMeter" style="width:80%;" value="{!asset.New_Asset_Install_B_W_Meter__c}"  />
                    </apex:column>
                
               		<apex:column style="width:10%;" headerValue="Color Starting Meter"><!-- to take the label dynamically -->
                        <apex:inputText styleClass="colorMeter" style="width:80%;" value="{!asset.New_Asset_Install_Color_Meter__c}"  />
                    </apex:column>
                
                <apex:column style="width:10%;" headerValue="I.P. Address"><!-- to take the label dynamically -->
                        <apex:inputText styleClass="ipAddress" style="width:90%;" value="{!asset.New_Asset_Install_Equipment_IP_Address__c}"  />
                    </apex:column>
                    
                    <apex:column style="width:.01%;" headerValue=""><!-- to take the label dynamically -->
                        <apex:inputText disabled="true" style="width:.01%;" styleClass="setupIdNumber" value="{!asset.New_Asset_Setup_LOC_ID__c}"  />
                    </apex:column>
                
            </apex:pageBlockTable>
                
                <apex:pageBlockTable id="pbt" value="{!Case.Assets__r}" var="asset">
                                 
                    <apex:column style="width:12%;" headerValue="Product Code"><!-- to take the label dynamically -->
                         <apex:inputText style="width:80%;" disabled="true" styleClass="setupModel" value="{!asset.Product_Code_for_Paperless_Install_Docs__c}"  />
                    </apex:column>
                    
                    <apex:column style="width:12%;" headerValue="Serial Number Install"><!-- to take the label dynamically -->
                        <apex:inputText style="width:80%;" disabled="" styleClass="installSerialNumber" value="{!asset.New_Asset_Install_LOC_Serial_Number__c}"  />
                    </apex:column>
                    
                    <apex:column style="width:6%; text-align:center;" value="{!asset.Serialized__c}"/>
                    
                    <apex:column style="width:13%;" headerValue="I Verified the Serial Number"><!-- to take the label dynamically -->
                        <apex:inputCheckbox styleClass="serialDoesntMatchCheckBoxOnAsset" value="{!asset.I_Verify_the_Serial_Number_is_Correct__c}"/>
                    </apex:column>
                    
                    <apex:column style="width:.01%;" headerValue=""><!-- to take the label dynamically -->
                        <apex:inputText style="width:.01%;" disabled="true" id="pbi" styleClass="setupSerialNumber" value="{!asset.Serial_Number_Service_Setup__c}"  />
                    </apex:column>
                    
                </apex:pageBlockTable>
                </apex:pageBlockSection>
            
            
            
            <apex:pageBlockTable rows="1" id="pbt2" value="{!Case.Assets__r}" var="asset">
                
            		<apex:column style="" headerValue="Location Remarks"><!-- to take the label dynamically -->
                        <apex:inputTextarea styleClass="locationRemarks" style="width:99.45%;" value="{!asset.New_Asset_Install_Equipment_Location__c}"  />
                    </apex:column>
                    
                    <apex:column style="" headerValue="Install Notes"><!-- to take the label dynamically -->
                        <apex:inputTextarea styleClass="installNotes" style="width:99.45%;" value="{!asset.Install_Notes__c}"  />
                    </apex:column>
                
               		<apex:column headerValue="Customer DocuSign Link" >
                        <apex:outputLink target="_blank" style="width:99.45%;" value="{!case.Customer_DocuSign_Link__c}">
                            Customer DocuSign Link
                        </apex:outputLink>
                	</apex:column>
                
            </apex:pageBlockTable>
            
            <apex:pageBlockSection id="pbs2" columns="2">
                <apex:inputField id="cheaterOnSite" onchange="cheaterLeftOnSite(); return false;" value="{!case.Cheater_Left_On_Sight__c}"/>
                <apex:inputCheckbox styleClass="autoSerialCheck" onchange="" id="serialNumberVerified" disabled="" value="{!Case.Serial_Numbers_Verified__c}"/>
                <apex:inputText id="cheaterId" value="{!case.Cheater_ID__c}"/>
				<apex:inputCheckbox onchange="enableUpdateButton(); return false;" id="manualSerialNumberVerification" disabled="" value="{!Case.Manual_Serial_Number_Verification__c}"/>
                <apex:inputCheckbox id="cheaterCheckBox" value="{!case.Cheater_was_used_at_install__c}"/>
                <apex:inputCheckbox id="install" value="{!Case.Install_Complete__c}"/>
                
              
                
            </apex:pageBlockSection>
            <p class="serialDoesntMatch">
                <apex:inputCheckbox id="serialDoesntMatchCheckBox" value="{!Case.Asset.I_Verify_the_Serial_Number_is_Correct__c}"/> 
                The above serial number(s) have been verified by <strong>{!$User.FirstName} {!$User.LastName}.</strong>
                <br/>
                <strong>{!$User.FirstName} {!$User.LastName}</strong> has uploaded a document that verifies the correct serial number
               
            </p>
            <apex:pageBlockButtons location="bottom">  
                 <apex:commandButton styleClass="verify" id="verify" onclick="verifySerialNumbers(); return false;" value="Verify" />
                <apex:commandButton oncomplete="congrats(); return false;" styleClass="update" id="update" disabled="" value="Update" action="{!saveSerialIdNumber}" />
            </apex:pageBlockButtons>
        </apex:pageblock>
    </apex:form>

</apex:page>

And here is my apex class:
public class installTicketUpdateAssetClass {
    private ApexPages.StandardController controller;

    //Constructor 
    public installTicketUpdateAssetClass(ApexPages.StandardController controller) {
        this.controller = controller;
    }

    public void saveSerialIdNumber() {
        // here we use the standard controller's capability of fetching related records to update them ourselves 
        // (Casting is needed because YourChildRelationshipName__r is specific to your case object)
        update ((Case) controller.getRecord()).Assets__r;
        // here we call the standard controller's "update"
        controller.save();
    }
}

​​​​​​​Any help would be greatly appreciated

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.

I have a class which filters query on SystemModStamp < Yesterday.

I want to cover this query in test class by creating record in test class whose SystemModStamp is older than yesterday.

I have tried on Json.deserialize method and Test.LoadData method both do not work well for systemModStamp. 

Hi folks !!

I want something like,  From date - To date. User can select the dates, and I will show the results between the dates.
I can do something like this :User-added image
Date from_date = Date.newInstance(2021,10,10);
Date to_date = Date.newInstance(2019,3,20);
list<contact> a = [select name from contact where
(CreatedDate >=: from_date) AND CreatedDate <=: to_date) ];

Here, I put the values of the dates manually. I want to know that, when I will click on the submit button, how can I get the values from the date pickers and put them into a variable manually?

[ In PHP I did something like this task, I am new in Salesforce. I collected the values of the variables from the date picker using jquery. In Salesforce, don't know how to do it?]

Thanks in advance.
@AuraEnabled
    public static List<String> getPicklistvalues(String objectName, String field_apiname,Boolean nullRequired){
        List<String> optionlist = new List<String>();       
        Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
        Map<String, Schema.SObjectField> field_map = gd.get(objectName.toLowerCase()).getDescribe().fields.getMap();        
        List<Schema.PicklistEntry> picklistValues = field_map.get(field_apiname).getDescribe().getPickListValues();       
        if(nullRequired == true){
            optionlist.add('--None--');
        }       
        for (Schema.PicklistEntry pv : picklistValues) {
            optionlist.add(pv.getValue());
        }
        return optionlist;
    }
Hi,
 I want to style my pdf. I want to get the record fields in a box and with good appearence.please help me in this.

User-added image

Below is my code...

========
ShowContactDetail.vfp

<apex:page controller="UpdateContactDetail">
 <style type="text/css">
  #title {
  font-size: 150%;
  margin-left: 30%;
  }
 </style>
  
  <h2 id="title">Contact</h2><br/><br/>
    <apex:form >
     <apex:pageBlock >
        <apex:pageBlockTable value="{!con}" var="b">
             <apex:column headervalue="Title">
                <apex:OutputText value="{!b.Title}" /> 
            </apex:column>   
            <apex:column headervalue="First Name">
                <apex:OutputText value="{!b.FirstName}" /> 
            </apex:column>            
            <apex:column headervalue="Last Name">
                <apex:OutputText value="{!b.LastName}" />
            </apex:column>
            <apex:column headervalue="Email">
                <apex:inputText value="{!b.Email}" />
            </apex:column>
            <apex:column headervalue="Phone">
                <apex:inputText value="{!b.Phone}" />
            </apex:column>
            
            <apex:column >
                <apex:commandLink action="{!updateRecord}" value="Update"/>                            
            </apex:column>                                                                                   
    </apex:pageBlockTable>
    </apex:pageBlock>
    </apex:form> 
         
</apex:page>

===============
UpdateContactDetail.apxc

public class UpdateContactDetail {

  public Contact con {get;set;}
  public Id recId;

    public UpdateContactDetail ()
    {
      recId = ApexPages.CurrentPage().getparameters().get('recordId');
        getRecord();
    }
   public void getRecord() {
   
      con = [select Id, Name,FirstName, LastName, Title, Email, Phone from contact where id =:recId];   

   }    
    
    public PageReference updateRecord(){      
        try{ 
            update con;
            
        }
        catch(DmlException ex){
            ApexPages.addMessages(ex);
        }
        return null;
    }
}

=============
GeneratePDFOfContactTrigger


trigger GeneratePDFOfContactTrigger on Contact (after update) {
    
    GeneratePDFController.generateContactPDF(Trigger.new);
    
}

==============
GeneratePDFController.apxc


public class GeneratePDFController{ 
    public static final String FORM_HTML_START = '<HTML><BODY>';
    public static final String FORM_HTML_END = '</BODY></HTML>';
    
    public static void generateContactPDF(list<contact> contactList){
        String pdfContent = '' + FORM_HTML_START;
        for(contact con : contactList){
            try
            {
                pdfContent = '' + FORM_HTML_START;
                pdfContent = pdfContent + '<H2>Contact Information</H2>';
                
                //Dynamically grab all the fields to store in the PDF
                Map<String, Schema.SObjectType> sobjectSchemaMap = Schema.getGlobalDescribe();
                Schema.DescribeSObjectResult objDescribe = sobjectSchemaMap.get('Contact').getDescribe();
                Map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
                
                //Append each Field to the PDF
                
                for(Schema.SObjectField fieldDef : fieldMap.values()){
                    Schema.Describefieldresult fieldDescResult = fieldDef.getDescribe();
                    String name = fieldDescResult.getName();
                    if(name == 'Title' || name == 'FirstName' || name == 'LastName' || name == 'Email' || name == 'Phone'){
                        pdfContent = pdfContent + '<P>' + name + ': ' + con.get(name) + '</P>';
                    }
                }
                pdfContent = pdfContent + FORM_HTML_END;
            }catch(Exception e){
                pdfContent = '' + FORM_HTML_START;
                pdfContent = pdfContent + '<P>THERE WAS AN ERROR GENERATING PDF: ' + e.getMessage() + '</P>';
                pdfContent = pdfContent + FORM_HTML_END;
            }
            attachPDF(con,pdfContent);
        }
    }
    
    public static void attachPDF(Contact con, String pdfContent){
        try{
            Attachment attachmentPDF = new Attachment();
            attachmentPDF.parentId = con.Id;
            attachmentPDF.Name = con.FirstName+' '+con.LastName+ '.pdf';
            attachmentPDF.body = Blob.toPDF(pdfContent); //This creates the PDF content
            insert attachmentPDF;
        }catch(Exception e){
            con.addError(e.getMessage());
        }
    }
    
}

Thank you in advance 
Kindly help me out with below code
Except Error message functionality all working

//VFP
<apex:page controller="NumberClassErrorMessage" wizard="true">
    <apex:form >
        <apex:pageBlock title="Number Calculations">
            <apex:pageMessages id="showmsg"></apex:pageMessages>
            
            <apex:pageBlockSection title="Calculator" >
                <font color="#E70E38">
                Enter Number 1: <apex:inputText value="{!Num1}" />
                Enter Number 2: <apex:inputText value="{!Num2}"/>
                    </font>
                <apex:commandButton value="Calculate" action="{!calculator}" reRender="xyz" />
                <apex:outputLabel id="xyz" value="{!SUBSTITUTE(JSENCODE(message), '\\n', '<br/>')}" escape="false" />       
            </apex:pageBlockSection>    
        </apex:pageBlock>
    </apex:form>    
</apex:page>

//APEX
public class NumberClassErrorMessage {
    
    public integer Num1 {set; get;}
    public integer Num2 {set; get;}
    public string message {set; get;}
    public void calculator()
    {
        integer add,sub,mul,div ;
        
        //if(acc.AccountNumber == '' || acc.AccountNumber == null)
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter Account number'));
        /*if(NumberA < 0){
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'First number is negative!'));
}
*/      
        if(Num1 == null || Num1 < 0){
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Kindly Enter Valid Amount in Number 1'));
            
        }
        if(Num2 == null || Num2 < 0){
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Kindly Enter Valid Amount in Number 2'));
        }
        
        add = Num1+Num2;
        sub = Num1-Num2;
        mul = Num1*Num2;
        // div = Num1/Num2;
        
        message = 'Addition of Numbers :' +add + '\n' + 
            'Substraction of Numbers :' +sub +  '\n' +
            'Multiplication of Numbers :' +mul +  '\n' +
            'Division of Numbers :'  ; // +div
    }
}
Dear. 
This seems an easy question with easy solution, but I don't find a technical solution after look in google, developer salesforce, etc.

This is what I want: I need to perform a set of validations in a lot of custom field values of the Opportunity. After see different options (process builder, validation rules, formulas, etc) the best approach if to use a VisualForce page. In that VisualForce page I want to show a text custom field, with a custom error message that can change via visualforce/javascript code.

This is my issue: I am not able to change the text custom field value. I have no erros. Just no changes on the text value. Below is the code I used in the VisualForce page.

Do you have any suggestion?
 
<apex:page standardcontroller="Opportunity">

    <apex:form id="formId">
        <apex:pageblock id="pb">
        
            <apex:pageBlockSection id="Block1" title="Opportunity Information" columns="2">
        
                <apex:inputField id="Warning_message" value="{!Opportunity.Warning_message__c}" />
                
            </apex:pageBlockSection>

        
        </apex:pageblock>
    </apex:form>
               
           
    <script type="text/javascript">
    
        function myFunction() 
        {
            document.getElementById('{!Opportunity.Warning_message__c}').value = "This will not change the value";
            document.getElementById('{!Opportunity.Warning_message__c}').innerHTML= "This will not change the value";
            document.getElementById('Warning_message').value = "This will not change the value";
            document.getElementById('Warning_message').innerHTML= "This will not change the value";            
            document.getElementById('{!$Component.formId.pb.Block1.Warning_message}').value = "This will not change the value";            
        }    
                            
        var msgObj= document.getElementById('{!Opportunity.Warning_message__c}');
        msgObj.value = "This will not change the value";            
        msgObj.innerHTML= "This will not change the value";            

    </script>
    
</apex:page>

Many thanks.
 
Hi all,

Newbie here.

I've got the following VF code that generates a Word doc when an action button is pressed on a custom object (Contract_Work_Order__c).

I'm trying to retrieve a contact's full name based on its id.  The field below is returning the Contact ID.  

{!Contract_Work_Order__c.Contractor__c}

I essentially need to write the following select statement and return the value.
Select name from contacts where Id ={!Contract_Work_Order__c.Contractor__c}

Here's the current VF page:
 
<apex:page standardController="Contract_Work_Order__c" contentType="application/msword#MSA_{!Contract_Work_Order__c.Id}.doc" sidebar="false" standardStylesheets="false" applyBodyTag="false">

<div style="font-family:sans-serif;"> 
<center>
<h4>MASTER SUB-CONSULTANT AGREEMENT</h4>
</center>
</div>
 
<div style="font-family:sans-serif;text-align:left;font-size:10pt;">
<p>This MASTER SUB-CONSULTANT AGREEMENT ("Agreement") is made and entered into as of <apex:outputText value=" {!TODAY()}"/> (“Effective Date”), 
by and between XYZ, and <apex:outputText value=" {!Contract_Work_Order__c.Contractor__c}"/> ("Sub-Consultant”), each individually sometimes referred to as a “Party” and collectively as “Parties”.</p>
 
<p>Your account details are:</p>
 
<table>
<tr><th>Opportunity Name</th>
    <td><apex:outputText value="{!Contract_Work_Order__c.Opportunity__c}"/></td>
    </tr>
<tr><th>Account Rep</th>
    <td><apex:outputText value="{!Contract_Work_Order__c.Account_Rep__c}"/></td>
    </tr>
<tr><th>Customer Since</th>
    <td><apex:outputText value="{0,date,long}">
        <apex:param value="{!Contract_Work_Order__c.CreatedDate}"/>
        </apex:outputText></td>
    </tr>
</table>
    
<p>It's a pleasure to have you on board.  Please do not hesitate to contact us should you have any questions or concerns.</p>
    
<p>Sincerely,</p>
    
<p><apex:outputText value="{!Contract_Work_Order__c.CreatedById}"/></p>
</div>
    
</apex:page>

I'm stuck and would appreciate your pointers!

Thank you.

 
I have the following:

<apex:outputText value="{0, number, currency}"><li>{!$ObjectType.Trips_Meetings__c.fields.Budget__c.Label}: <apex:param value="{!relatedTo.Budget__c}"/></li></apex:outputText>

Budget__c is already a currency field type, but I had to add 
value="{0, number, currency}"
in order to display the value with currency symbol and comma.

However, <apex:param/> is getting rendered w/ the <span> automatically.

This is what the result currently looks like:
  • Client Matter #: 55604
  • Estimated Cost:
           $55,604.00
  • Proposed Dates: test
But the goal is to have it displayed as:
  • Client Matter #: 55604
  • Estimated Cost: $55,604.00
  • Proposed Dates: test
I've tried using <apex:variable> and <apex:outputpanel>, but that did not do anything. How do I prevent the child of <apex:outputText>, <apex:param>, getting rendered w/ the <span>.

 
Hello, I made a validation rule in Content Version that blocks the changing of document details that have the value "Vertragsdokument" etc. in the field Dokumentenklasse which is a picklist in Content Version. Now I created a Profile which I named "Document Deleter"
I want my validation rule to work for every profile except this one. Could you tell me how to change my code to make this possible?

My Trigger:

AND(
 
       NOT(ISNEW()),
OR(
       Text( PRIORVALUE(Dokumentenklasse__c)) = "Geschäftsbrief",
       Text( PRIORVALUE(Dokumentenklasse__c)) = "Vertragsdokument",
       Text( PRIORVALUE(Dokumentenklasse__c)) =  "Wichtige Dokumentation oder Entscheidung",
 Text( PRIORVALUE(Dokumentenklasse__c)) =  "Druckstück"
)
)
Newbie dev here. Does anyone know why inline editing was disabled when I added the script below? The only reason I added it is because every time the page loads, the cursor moves to a specific field in the page, even though that was not last position of the cursor
 
<script>
    window.onload = function(){
        window.scrollTo(0,0);
    };
</script>

Not sure if you wanna see my Visualforce page since it's so long. I realize there is a similar question but it was not enough for me to resolve the issue.
======================
Main Class
======================

global class ScheduleInvoice implements Schedulable {
    public static String CRON_EXP = '0 0 0 1 * ? *';
    global static String scheduleIt() {
        ScheduleInvoice sm = new ScheduleInvoice();
        return System.schedule('Monthly Reconciliation', CRON_EXP, sm);
    }
    global void execute(SchedulableContext sc) {Id AccountEIDrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('EID').getRecordTypeId();
        Id AccountPVCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('PVC').getRecordTypeId();
        Id AccountPMCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('PMC').getRecordTypeId();
        Id AccountVMCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('VMC').getRecordTypeId();
        Id InvoiceVRCrecordTypeId = Schema.getGlobalDescribe().get('Invoice__c').getDescribe().getRecordTypeInfosByName().get('VRC').getRecordTypeId();
        
        set<ID> recordIds = new Set<ID>();
        recordIds.add(AccountEIDrecordTypeId);
        recordIds.add(AccountPVCrecordTypeId);
        recordIds.add(AccountPMCrecordTypeId);
        recordIds.add(AccountVMCrecordTypeId);
        
        List<Invoice__c> invoiceList = new List<Invoice__c>();
        List<Invoice__c> invList = new List<Invoice__c>();
        Integer m = Date.Today().Month();
        Date firstDayOfMonth = System.today().toStartOfMonth();
        Date lastDayOfMonth = firstDayOfMonth.addDays(Date.daysInMonth(firstDayOfMonth.year(), firstDayOfMonth.month()) - 1);
        Date invDesDate = system.Today().addMonths(1);
        Integer invMonth = invDesDate.Month();
        Integer invYear = invDesDate.year();
        String MonthName;
      
        for (Account acct: [
            select Id, Active__c RecordTypeId
            from Account
            where RecordTypeId IN: recordIds and Active__c = true
        ]) {
                Invoice__c inv = new Invoice__c();
                inv.Account__c = acct.Id;
                inv.Status__c = 'Accepted';
                inv.Date__c = system.Today();
                switch on m {
                    when 1 {        
                        invoiceDate__c = 'Jan 1 to Jan 31';
                    }    
                    when 2 {        
                        invoiceDate__c = 'Feb 1 to Feb 28';
                    }
                    when 3 {
                        invoiceDate__c = 'Mar 1 to Mar 31';
                    }
                    when 4 {          
                        invoiceDate__c = 'Apr 1 to Apr 30';
                    }
                     when 5 {        
                        invoiceDate__c = 'May 1 to May 31';
                    }    
                    when 6 {        
                        invoiceDate__c = 'Jun 1 to Jun 30';
                    }
                    when 7 {
                        invoiceDate__c = 'Jul 1 to Jul 31';
                    }
                    when 8 {          
                        invoiceDate__c = 'Aug 1 to Aug 31';
                    }
                    when 9 {        
                        invoiceDate__c = 'Sep 1 to Sep 30';
                    }    
                    when 10 {        
                        invoiceDate__c = 'Oct 1 to Oct 31';
                    }
                    when 11 {
                        invoiceDate__c = 'Nov 1 to Nov 30';
                    }
                    when 12 {          
                        invoiceDate__c = 'Dec 1 to Dec 31';
                    }
                }                                                                                                                
                   inv.Payment_Due_Date__c =  lastDayOfMonth; 
                switch on invMonth {
                    when 1 {        
                        MonthName = 'January';
                    }    
                    when 2 {        
                        MonthName = 'February';
                    }
                    when 3 {
                        MonthName = 'March';
                    }
                    when 4 {          
                        MonthName = 'April';
                    }
                     when 5 {        
                        MonthName = 'May';
                    }    
                    when 6 {        
                        MonthName = 'June';
                    }
                    when 7 {
                        MonthName = 'July';
                    }
                    when 8 {          
                        MonthName = 'August';
                    }
                    when 9 {        
                        MonthName = 'September';
                    }    
                    when 10 {        
                        MonthName = 'October';
                    }
                    when 11 {
                        MonthName = 'November';
                    }
                    when 12 {          
                        MonthName = 'December';
                    }
                }
            inv.RecordTypeId = InvoiceVRCrecordTypeId;
                inv.Description__c = MonthName + ' ' + String.valueof(invYear) + ' ' + 'TMC';
                
               invList.add(inv);
        }
          
        if (!invList.isEmpty()) {
            insert invList; 
        }   
    }
}

===========================
Test Class
===========================
@isTest
public class CreatingInvoice_Test {
    @isTest static void executeTest(){
        
        Test.startTest();
        
        Id AccountPVCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('PVC').getRecordTypeId();
        Id AccountPMCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('PMC').getRecordTypeId();
        Id AccountVMCrecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('VMC').getRecordTypeId();
        Id InvoiceVRCrecordTypeId = Schema.getGlobalDescribe().get('Invoice__c').getDescribe().getRecordTypeInfosByName().get('VRC').getRecordTypeId();
        
        SchedulableContext sc = null;
        ScheduleInvoice CI = new ScheduleInvoice();
        CI.execute(sc);
        
        account a = new account();
        a.Name = 'Test Account';
        a.Active__c = true;
        a.RecordTypeId = AccountVMCrecordTypeId;
        
        insert a;
        
        ScheduleInvoice CI1 = new ScheduleInvoice();
        String sch1 = '0 0 0 1 * ? *'; 
        system.schedule('ScheduleInvoice', sch1, CI1);
        
        Test.stopTest();
    }
}
Hello, How do I adjust the margins of my VF page? I have tried different things but none seem to work. the text starts all the way to the left side of the page and I want it to be indented, and I want the right margin also to stick out more. 

<apex:page standardcontroller="Lead" extensions="FinancialChecklistPageExtension" lightningStylesheets="true" action="{!firstScreen}">
    <style>
           .One
             {
            margin-left:30px;
            margin-right:30px;
            padding-left:30px;
            padding-right:30px;
        font-size:15px;
             }
    </style>
        <script type="text/javascript">
           function disableOnSubmit(input) {
            var btn = input;
            setTimeout(function(){ 
                btn.disabled = 'disabled';
               
                btn.className = 'btnDisabled';
                btn.value = "Processing..."; 
            }, 50);
        }
           function disableOnSubmit2(input) {
            var btn = input;
            setTimeout(function(){ 
                btn.disabled = 'disabled';
             
                btn.className = 'btnDisabled';
                btn.value = "Saving..."; 
            }, 50);
        }
    </script>
   
   
    <apex:form id="theForm" >
       
       <div align="center" draggable="false">
        <apex:outputPanel style="text-align:center;" rendered="{!IF(kansasSelected =false && njselected = false && nyselected = false && riselected = false,true,false)}">
          
            <br/><br/><br/><br/>
       <b>Which region is this for?<br/><br/></b> &nbsp;     <apex:selectList style="align:center;text-align:center" value="{!region}" multiselect="false" size="1">
                            <apex:selectOption itemValue="" itemLabel="--- Please Select ---"/>
                            <apex:selectOption itemValue="Kansas" itemLabel="Kansas"/>
                            <apex:selectOption itemValue="New Jersey" itemLabel="New Jersey"/>
                            <apex:selectOption itemValue="New York" itemLabel="New York"/>
                            <apex:selectOption itemValue="Rhode Island" itemLabel="Rhode Island"/>
                        </apex:selectList><br/><br/>    
            
                    <div align="center"  draggable="false" >
                        <apex:commandButton value="Next" action="{!showForm}" onclick="disableOnSubmit(this);" reRender="theForm" />
                    </div> 
        
            </apex:outputPanel> 
        </div>

         
 <!-- KANSAS -->    
        <apex:outputPanel styleClass="One" rendered="{!kansasSelected}" > 
                        <div style="text-align:center; font-size:18px">
                             <b><u>Kansas Finance Check List</u></b><br/> 
                        </div> 
                    <apex:repeat value="{!financialChecklistTemp}" var="fc">
                        
                        <div style="text-align:center;">
                            Created Date: <apex:inputField value="{!fc.CreatedDate}" /><br/><br/>
                        </div>
                        
                        <b>*All of these elements factor in whether or not the facility will get the Medicaid eligibility necessary</b>
                        <br/><br/>
                        
                        1. Is the patient alert and oriented?  If not, is there a POA, guardian, attorney or responsible family member to assist with Medicaid process?    
                        <apex:inputField value="{!fc.KS_Is_the_patient_alert_and_oriented__c}" /><br/>
                        2. Does patient/family have access to documents? (Birth Certificate, SS Card, ID’s, Insurance Cards, Marriage Cert, Divorce or Death Decrees, etc.)    
                        <apex:inputField value="{!fc.KS_Does_patient_have_access_to_docs__c}" /><br/>
                        3. <b><u>For patients under 65</u></b> – does the patient receive disability or is the patient in the process of applying? 
                        This would be necessary to obtain LTC Medicaid benefits. <b><u>If the patient is under 65 and does not have disability refer to finance for review.</u></b>
                        <apex:inputField value="{!fc.KS_For_patients_under_65__c}" /><br/>
                        4.    Is resident single, separated or married?  If married and or separated, is legal spouse willing and able to participate with Medicaid process? 
                        <apex:inputField value="{!fc.KS_IS_resident_single_separated__c}" /><br/>
                         5.    What is patient’s income and resources? (Pensions, Social Security, Checking, Savings, Residential Property, IRA’s, 
                         Stocks, Bonds, etc.) – <b><u>If income or assets exceed $2,000 refer to finance for review</u></b>
                        <apex:inputField value="{!fc.KS_What_is_patient_s_income__c}" /><br/>
                         6.    Does patient understand and agree that <B>ALL</B> income must be turned over to the facility on a monthly basis, with the exception of $62 Personal Need’s Allowance?
                        <apex:inputField value="{!fc.KS_Does_patient_understand_and_agree__c}" /><br/>
                         7.    Has patient transferred any assets in the last five years? This includes any gifts or loans that remain unpaid.  
                         If so, this will result in a period of Medicaid ineligibility and <b><u>should be referred to finance.</u></b>   
                        <apex:inputField value="{!fc.KS_Has_patient_transferred_any_assets__c}" /><br/>
                        8.    All admissions regardless of payer need the “less than 30” from the hospital (unless the patient has an existing care assessment)  
                        <apex:inputField value="{!fc.KS_All_admissions_regardless__c}" /><br/>
                        <br/><br/>    
                        
                        General information: When running eligibility “medical necessity or QMB only” means it needs a new Medicaid application (not just a conversion to LTC). Those are typically more challenging. 
                        <br/><br/>
                    <div align="center"  draggable="false" >
                        <apex:commandButton value="Save" action="{!savetasks}" onclick="disableOnSubmit2(this);" reRender="theForm" />
                        </div> <br/><br/>
                    <div align="center"  draggable="false" >
                        <apex:commandButton value="Attach to Referral" action="{!generatePdf}" onclick="disableOnSubmit2(this);" reRender="theForm" />
                    </div> 
                        </apex:repeat>
                    </apex:outputPanel> 

        
        </apex:form> 
         
</apex:page>
Hi, I am working on the Account VisualForce page, and on that page I have a custom field that is from a different object. I am able to display that field from the different object but right now it is in a table. Is there a way to output the field value without a table, but just a single line of text? Below is what I have now, but only want the output to be a line of text, not in a table or anything else. The line below is already within an ouputPanel.Thanks.
 
<apex:pageBlockTable width="100%" cellpadding="1" cellspacing="1" 
                     value="{!contactList}" var="con" border="0" 
                     frame="none" id="table1">
    <apex:column>
        <apex:outputField value="{!con.CustomField__c}"
            rendered="{!con.CustomField__c != NULL}" 
        />
    </apex:column>
</apex:pageBlockTable>

 
Hi All !

I am trying to create a wrapper class , but in the VF page Iam getting error Unknown property 'String.DCode'. Any advice on this 


<apex:page controller="wrapperclass">
<apex:form>

<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockTable value="{!lstwrapperstring}" var="wrap">
<apex:column headerValue="Action">
<apex:inputCheckbox/>
</apex:column>

<apex:column headerValue="Deal Code"/>
{!wrap.DCode}

<apex:column headerValue="Course"/>
{!wrap.C}

<apex:column headerValue="Trainer First Name"/>
{!wrap.TFirstName}

<apex:column headerValue="Trainer Last Name"/>
{!wrap.TLastName}

<apex:column headerValue="Trainer Education"/>
{!wrap.TEducation}


</apex:pageBlockTable>



</apex:pageBlockSection>

</apex:pageBlock>

</apex:form>

</apex:page>


 
Hello All

Please find the below,   controller and a part of VF Page. Here the refresh not working when User clicks on Verify Asset button, the new one , which User has to enter is populating 3 Fields (Location, Warranty, Date) with the Previous entered Values. Please someone help in change of code or where have to change to get empty of those 3 fields on addition of new?

Thanks in Advance!
TrialHead Aspirant

VF Page:
========

 <apex:outputPanel rendered="{!renderAddAsset}">
                
                Model Number:<apex:inputText value="{!modelNumber}"/> 
                Serial Number:<apex:inputText value="{!serialNumber}"/>
                Install Date:<apex:input value="{!installDate}" 
                    html-placeholder="Install Date" 
                                              type="date"/>
                <apex:selectList label="Fields" value="{!selectedLocationId}" multiselect="false" size="1" >
                     <apex:selectOptions value="{!LocationSelections}" />
                </apex:selectList>
                In Warranty?<apex:selectList id="WarrantyStatusId" value="{!WarrantyStatus}" size="1">
                    <apex:selectOption itemValue="true" itemLabel="Yes"/>
                    <apex:selectOption itemValue="false" itemLabel="No"/>
                </apex:selectList> 
                 <apex:commandButton action="{!verifyAsset}" value="Verify Asset" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
                 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <apex:commandButton action="{!cancelAddAsset}" value="Cancel" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
            </apex:outputPanel>

Controller:
============
public PageReference verifyAsset(){
        resetError();
        Boolean hasErrors = false;
       
        
        if(modelNumber == '' || modelNumber == null){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please enter model number.')); 
            hasErrors = true;
        }
        if(selectedLocationId == 'Select service location' ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please select a location.')); 
            hasErrors = true;
        }
        if(!string.isBlank(modelNumber)  && !modelNumber.isAlphanumeric() ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Model Number can only contain alphanumeric characters.')); 
            hasErrors = true;
        }
        if(hasErrors){
            assetError = true;
            return null;
        }
        User-added image
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