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


  • Chatter
    Feed
  • 90
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 676
    Replies
Hi,

I need to create a Custom Button with a Content Source as Visualforce Page. I have created a Visualforce page for this.

The problem is that when I choose Visualforce Page in the Content Source of the Custom Button setup, the Content list remains empty. It doesn't show my Visualforce page there, despite it is already created and ready for use.
How can I put my Visualforce page in the Content of the Custom Button?

User-added image

User-added image
@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();
    }
}
  • August 06, 2021
  • Like
  • 0
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.

I'm looking out to remove all the special characters from the string without removing Chinese or any other langaguge characters in Apex.

String strText = 'Welcome - to! % $sale&sforcecode # crack %  东莞可达薄有限公司';

Excepted O/P : Welcometosalesforcecodecrack东莞市可达薄膜科技有限公司
 


I don't want to use for loop, any regex compartiable for apex?

Hello all. I've created a custom component to show the Case status path. And it is working as expected. But now they want to change the color of the "Mark current status" button. So far the documentation i found only applies if i use standart HTML to build it from scratch, and not if i use <lightning:path \>. Or i could hack the DOM redered by salesforce, and force CSS in there, but  i believe i run the risk of in an API change, of that not working (Don't i?) My code:

Component

<aura:component implements="forceCommunity:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" controller="CST_pathComponent">
    <aura:attribute name="variant" type="String" default="linear"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="hideUpdateButton" type="Boolean" default="false"/>
    <lightning:path aura:id="path" recordId="{!v.recordId}"
        variant="{!v.variant}"
        hideUpdateButton="{!v.hideUpdateButton}"
       	onselect="{!c.handleSelect}"
    />
</aura:component>

JS

({
    doInit: function (component, event) {
        var action = component.get("c.getUserInfo");
        action.setCallback(this, function (response) {
            
            var state = response.getState();
            console.log('response: ' + response);
            console.log('state: ' + state);
            console.log('CST_pathComponent response 1:  ' + response.getReturnValue());
            if (state === 'SUCCESS') {
                var hideBtn = response.getReturnValue();
«                component.set('v.hideUpdateButton', hideBtn);
            }
        });
        
        $A.enqueueAction(action);
	},
    handleSelect: function(component, event){
        console.log('select');
    }
})
Any ideas?


Lightning Component:

<aura:component controller="LC_Lst_Acnt_tile">
    <aura:attribute name="acco" type="Account[]"/>
     <aura:attribute name="Srchacc" type="string"/>
   
    <lightning:layout  multipleRows="True">
      <lightning:layoutItem size="4">
        <lightning:card title="Search Accounts">
           
            <aura:set attribute="actions">
               <lightning:button label="search" onClick="{!c.searchme}"/>
            </aura:set>
           
            <lightning:input label="Enter the Text" value="{!v.Srchacc}"/>
            </lightning:card>
          </lightning:layoutItem>
               
         <lightning:layout>
        <lightning:card title="Tile view">
             <aura:iteration items="{!v.acco}" var="sd"/>
            <lightning:layoutItem size="4">
                Name:{!sd.Name} <p/>
                Phone:{!sd.Phone}<p/>
                Fax:{!sd.Fax}<p/>
            </lightning:layoutItem>
           
          </lightning:card>
        </lightning:layout>
       
    </lightning:layout>
</aura:component>

-------------------------------------------------------------------------------------------------------

Controller:


({
searchme : function(component, event, helper) {
var aa= component.get("v.Srchacc");
        var action=component.get("c.TileAccount");
        action.setParams({"st":aa});
        action.setCallback(this,function(response){
           
            var state=response.getState();
            var res=response.getReturnvalue();
            component.set("v.acco",res);
        });
        $A.enqueueAction(action);
}
})


-------------------------------------------------------------------------------

Apex Class:



public class LC_Lst_Acnt_tile {

    @AuraEnabled
    public static List<Account> TileAccount(string st)
    {
        string query='select Name,Phone,Fax from Account where Name like \'%'+st+'%\'';
        List<Account> acc= Database.query(query);
        system.debug(acc);
        return acc;
    }
}


------------------------------------------------------------------------------------------

Lightning Application:

<aura:application extends="force.slds">
    <c:Lc_List_Account_tile/>
</aura:application>


--------------------------------------------------------------------------------------------


Error Message:



This page has an error. You might just need to refresh it.
Assertion Failed!: Unable to get value for key 'sd.Name'. No value provider was found for 'sd'. : false
Failing descriptor: {c:Lc_List_Account_tile}


-------------------------------------------------------------------------

Hi All,

Can any one correct me where iam Wrong
Hi,

I need to create a Custom Button with a Content Source as Visualforce Page. I have created a Visualforce page for this.

The problem is that when I choose Visualforce Page in the Content Source of the Custom Button setup, the Content list remains empty. It doesn't show my Visualforce page there, despite it is already created and ready for use.
How can I put my Visualforce page in the Content of the Custom Button?

User-added image

User-added image
Hi experts!
I have a little problem with a simple force.com site that I'm building.
I want to see a list of contacts with basic info, one of these info is a picklist field, but when I render the page, this picklist show the first value of list instead of the current value of the record.
Here's my VF Code of the picklist:
VF
<apex:pageBlockSectionItem >
                                    <apex:outputLabel value="{!$ObjectType.Contact.fields.type__c.label}" />
                                    <apex:selectList styleClass="slds-input"  value="{!statusOptions}"   size="1">
                                        <apex:selectOptions value="{!ItemsList}" rendered="true"/>
                                    </apex:selectList>
                                </apex:pageBlockSectionItem>
And the method of the controller:

public List<Selectoption> getItemsList(){
        List<SelectOption> options = new List<SelectOption>(); 
        List<Schema.Picklistentry> fieldResult = Schema.Contact.type__c.getDescribe().getPicklistValues();
        //options.add(new SelectOption());
        for(Schema.PicklistEntry f : fieldResult) {
            options.add(new SelectOption(f.getValue(), f.getLabel()));
        }
        return options;
    }

Any help will be very appreciated! Thanks in advance.
Hello,
I have an aura component to show / hide field depending on checkbox values. What I'm trying to do is to when the checkbox for the current user is checked, to show the field on the component. But if the current user profile name is different from the record owner, to make the field on the component disabled.
The problem is that 2 fields on my component is showing when I only want to display one.

aura markup
How do I change my markup to apply the logic on the same lightning textarea so only 1 is shown
 
<aura:component controller="ActionDescriptionFieldShowHideController" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    
    <aura:attribute name="recordId" type="String"/>
    <aura:attribute name="actionRec" type="Action__c" default="{'sObjectType':'Action__c'}"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <lightning:spinner alternativeText="Loading" size="large" aura:id="spinner" class="slds-hide" />
    
    <aura:attribute name="CurrentUser" type="Object"/>
    <force:recordData recordId="{!$SObjectType.CurrentUser.Id}"
                      fields="Profile.Name"
                      targetFields="{!v.CurrentUser}"/>
    
    
    <form class="slds-form_stacked">
    
        
    <aura:if isTrue="{!and(v.actionRec.Commercial__c == true, v.CurrentUser.Profile.Name == 'Sales')}">
        <lightning:textarea label="Description" name="desc" value="{!v.actionRec.Description__c }"/>  
        <aura:set attribute="else">
            <aura:if isTrue="{!and(v.actionRec.Commercial__c == true, v.CurrentUser.Profile.Name != 'Sales')}">
                <lightning:textarea label="Description" name="desc" disabled="true" value="{!v.actionRec.Description__c }"/> 
            </aura:if>
        </aura:set>  
    </aura:if>
        
    <footer class="slds-modal__footer">
        <lightning:button variant="brand"
                          label="Save"
                          title="Save"
                          onclick="{! c.actionSave}" />
    </footer>
    </form>
</aura:component>

 
Hi everyone,below is the trigger and testclass which i have written.ablw to cover 70% can some one plz help me to increase the code coverage.
trigger:
trigger updateoppstage on Account (after update) {
set<id> accountId=new set<id>();
    
   
    for(Account a:trigger.new){
        accountId.add(a.id);
    }
    //query the account related opp
    List<opportunity>opp=new list<opportunity>();
   List<opportunity>opplist=[select id,name,stageName,createdDate,Accountid from opportunity where Accountid=:accountid];
    for(opportunity o:opplist){
        if(o.stageName!='ClosedWon'&&  o.CreatedDate<system.today()){
            o.stageName='ClosedLost';
        }
        opp.add(o);
    }
    update opp;
}
testclass:
@isTest
public class Testupdateoppstage {
@isTest
    static void call(){
        Account a=new Account();
        a.name='testacc';
         insert a;
        opportunity o=new opportunity();
        o.name='testopp';
        o.StageName='needanalysis';
        o.CloseDate=system.today();
        //o.CreatedDate=2-2-2021;
        o.AccountId=a.id;
       
        Test.startTest();
       List<opportunity>opp=[select id,accountId,stageName,name,closeDate,createdDate from opportunity where accountid=:a.id];
       
        update a;
         o.stageName='ClosedLost';
        update opp;
        //system.assertEquals(o.stageName, 'ClosedLost');
        Test.stopTest();
        
    }
}

Thanks in advance
  • November 05, 2021
  • Like
  • 0
Hello, I want to build a datatable component that shows all files of the records in the custom object "Mediathek. for now I wanted to make a datatable that shows the records on Mediathek where Typ = 'Printmaterial'. Could you show me how to fix my component to achive it?
When saving I do get this error:
Failed to save PrintmaterialDatatableController.js: c.PrintmaterialDatatable: Failed to parse CONTROLLER for js://c.PrintmaterialDatatable: org.auraframework.util.json.JsonStreamReader$JsonStreamParseException: Expected ',' or '}', got FUNCTION_ARGS_END [25, 2]: 'function(component, event, helper) { component.set('v.mycolumns', [ {label: 'Thema', fieldName: 'Beschreibung__c', type: 'url', typeAttributes: {label: { fieldName: 'Beschreibung__c' }, target: '_blank'}}, {label: 'Thema__c', fieldName: 'Thema__c', type: 'picklist', fixedWidth: 160 }, ]); var action = component.get("c.loadMedia"); action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS") { var records =response.getReturnValue(); records.forEach(function(record){ }); component.set("v.media", records); } }); $A.enqueueAction(action); }': Source

COMPONENT
<aura:component controller="MediaController" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" >
    
    <aura:attribute name="recordId" type="Id" />    
    <aura:attribute name="mediathekList" type="List" default="Mediathek[]"/>
                                              
   
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>   
    <aura:attribute name="mycolumns" type="List"/>
  
        <div>
            <aura:if isTrue="{!not(empty(v.media))}">
                <lightning:datatable data="{!v.mediathekList }" 
                         columns="{!v.mycolumns }" 
                         keyField="Id"
                         hideCheckboxColumn="true"
                         />
                <aura:set attribute="else">
                    <div Style="text-align : center"> Keine Aufgaben</div>
                </aura:set>
            </aura:if>
        </div>
        
</aura:component>


JS
({
    doInit: function(component, event, helper) {
    
      
        	component.set('v.mycolumns', [
            {label: 'Thema', fieldName: 'Beschreibung__c', type: 'url',
            typeAttributes: {label: { fieldName: 'Beschreibung__c' }, target: '_blank'}},
                {label: 'Thema__c', fieldName: 'Thema__c', type: 'picklist', fixedWidth: 160 },
        ]);
        var action = component.get("c.loadMedia");
            action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var records =response.getReturnValue();
                records.forEach(function(record){
                 
                });
                component.set("v.media", records);
            }
        });
        $A.enqueueAction(action);
            
       

})


APEX
public class MediaController {

       
//ÜBERFÄLLIG - Abfrage Tasks, wo das Activity Date abgelaufen und der Status "Not Completed" ist//
@AuraEnabled
public static List<Mediatheken> loadmedia(Id recordId){
    string userId = UserInfo.getUserId();
    return[SELECT Thema__c, Bezeichnung__c FROM Mediathek__c WHERE Typ__c = 'Printmaterial'];
}
}

 

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.

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