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


  • Chatter
    Feed
  • 54
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 454
    Replies
I have a visualforce page that I want to use a date field to rerender an output panel if the date is a certain month.

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

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

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

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

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

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


 
Hi,

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

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

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

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

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

and here is what I am getting
visualforce page preview

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

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

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

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

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

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

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

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

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

User-added image

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



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

    // Wrapper class
    public class PieWedgeData {

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

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

 

Hi all,

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

 

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

 

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

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

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

}

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

}

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

Any help would be appreciated.

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

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

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

Is there any posibility to do that ? 
  • March 28, 2019
  • Like
  • 1
I would like to know how I reference a custom field as part of this visual force page for Opportunity Line Items. The template is from this app, on the Appexchange form Salesforce labs: https://appexchange.salesforce.com/appxListingDetail?listingId=a0N300000016cYlEAI&modal=where_to_install_package

The error states that it is an invalid field, but it's a custom field on the product. 

Any help would be appreciated!
VF Error

Hi
I have created a Managed and Unmanaged packages and trying to access the URL provided while creating the packages and seeing the below issues

Managed Packages - When I am trying to access the URL and install the same package in a different account I am getting the below error
Package Not Found
The requested package doesn't yet exist or has been deleted. If this is a recently created package version, please try again in a few minutes or contact the package publisher. 

Unmanaged Packages
 - When I am trying to access the URL and install the same package in a different account I am getting the below error
This app can't be installed.
There are problems that prevent this package from being installed.

Package Not Found. User-added imageThe requested package doesn't yet exist or has been deleted. If this is a recently created package version, please try again in a few minutes or contact the package publisher.​​​​​​​

Your help would be really appreciated. .

Hi all, 

I'm having a problem related child objects using SOQL. In preparation for another object that has yet to be created, I made corrections to my custom object name, though now I can only query related child records using the old (wrong) name. My code here shows that now, the system recognizes both:


 
// Query child "Checklist_Item_Junctions__r" even though that is no longer the object's name
List<Checklist_Template__c> templateQuery = [Select Id, Machine_Series__c, (Select Id, Checklist_Template__c, Checklist_Template_Item__c From Checklist_Item_Junctions__r) From Checklist_Template__c];
        
        
        // separately query all "Checklist_Template_Item_Junction__c" records, (the new name of the object)
        List<Checklist_Template_Item_Junction__c> junctionQuery = [Select Id, Checklist_Template__c, Checklist_Template_Item__c From Checklist_Template_Item_Junction__c];
       

This saves successfully, and I have no idea why. There is no longer such an object as "Checklist_Item_Junction__c", but it's requiring that I call it that in my child relationship query.
 
Hi, 
I need to send an email alert to a couple of users every time a file is uploaded. 
I understand the workflows are not an option for files and I will need to write a trigger. 
I have never written anything like this and I would appreciate some quidance. 
All the best, 
 Aidel
I am displaying a list of account record with a checkbox
so when the user checks a record then I need the ID of that selected record in controller for further processing.

I am using actionsupport for this but I am unable to get the ID of the selected record in controller.

Please let me know where I am going wrong and if there is a better way of doing this.
 
public class ActionSupportParamDemoController
{

    public Id targetAccountId;
    
    public Id selectedAccountId { get; set; }
    
    public ActionSupportParamDemoController(ApexPages.StandardController controller) {

    }

  public List<Account> getAccounts()
  {
    return [select ID,Name,Active__c
            from Account
            order By name
            LIMIT 10];
  }

  public PageReference handleCheckBoxChange()
  {
      system.debug('target accountid ='+targetAccountId);
      
      selectedAccountId = targetAccountId;
      
       system.debug('target accountid ='+targetAccountId);
       system.debug('selected account ID ='+selectedAccountId);
      return null;
         
  }
  
  //own method
  public Id getTargetAccountId() {
        return targetAccountId;
    }
  
  public void setTargetAccountId(Id value) {
        targetAccountId = value;
    }
}

visualforce page
<apex:page standardController="Account"
           extensions="ActionSupportParamDemoController">
         
<apex:form>

 <apex:repeat value="{!Accounts}"
                var="accn">
                
       <apex:inputCheckbox value="{!accn.Active__c}">
       <br/>
       <apex:actionSupport event="onchange"
                           action="{!handleCheckBoxChange}">
                           
                    <apex:param id="account" 
                                name="accnId" 
                                value="{!accn.ID}"
                                assignTo="{!targetAccountId}"/>
                            
       </apex:actionSupport>
       
       </apex:inputCheckbox>
       {!accn.Name}
                 
 </apex:repeat>
 {!selectedAccountId}
</apex:form>


</apex:page>

thanks
sheila
 
Hi.

Happy about finally delivering option to get recordId by developer name, see relase info https://releasenotes.docs.salesforce.com/en-us/summer18/release-notes/rn_apex_developer_name.htm I wanted to use it. It works perfectly on Anonymous execution, however if used in apex class it is not possible to save due to method does not exists error.
Id devRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('PersonAccount').getRecordTypeId();
System.debug(devRecordTypeId);
In anonymous execution it returns a value in debug. Using in apex class gives an error:
Method does not exist or incorrect signature: void getRecordTypeInfosByDeveloperName() from the type Schema.DescribeSObjectResult
Do we have SF peoples here? Can you please fix it.
 
Hi all,
I am facing a familiar issue on Viewstates but not able to figure out what's causing it. 
Internal is holding 210KB
Internal is holding 210KB though my VF page has single Form. Below is the code.
<apex:page standardController="Account" extensions="AccountServiceControllerExtension2" readOnly="true" id="page">
    
    <style type="text/css">        
   
       .vfTableMainInfo {
            table-layout:fixed;
            word-wrap:break-word;
            overflow:hidden; 
            width: 50px;
                       
        }
        
        .vfTable {
            table-layout:fixed;
            word-wrap:break-word;
            overflow:hidden; 
            width: 50px;
}
        .expandFoldText{
            color: rgb(1,91,167);           
        }
        .expandFoldText1{
            color: rgb(1,91,167);           
        }       
        .expandFoldText2{
            color: rgb(1,91,167);    
            display: none;       
        }
       
    </style>
     
    <apex:form id="form">
   
    <apex:pageBlock id="main1" title="Service Data">    
              <apex:repeat id="repeat" value="{!allList}" var="innerList">
                       
        <apex:pageBlockTable id="subTable1" value="{!innerList}" var="item" styleClass="vfTable">        
                                   
             <apex:column >

                     <label id="plus{!innerList[0][14]}" class="expandFoldText1" onmouseover="componentColorMouseOver(this);"  onmouseout="componentColorMouseOut(this);" onclick="expandProudct1(this,{!innerList[0][14]});" >(+)</label>
                     <label id="minus{!innerList[0][14]}" class="expandFoldText2" onmouseover="componentColorMouseOver(this);"  onmouseout="componentColorMouseOut(this);" onclick="expandProudct2(this,{!innerList[0][14]});">(-) </label>

                     {!item[0]}
                    <apex:facet name="header">                        
                       <label>Product</label>
                    </apex:facet> 
             </apex:column>

             
             <apex:column value="{!item[1]}">

                    <apex:facet name="header">Status</apex:facet>
            
             </apex:column>
             <apex:column value="{!item[2]}">
                    <apex:facet name="header">Abstract</apex:facet>
             </apex:column>
             <apex:column value="{!item[3]}">
                    <apex:facet name="header">Date Open</apex:facet>
             </apex:column>
  
        </apex:pageBlockTable>     
        
        
        <div id="{!innerList[0][14]}" style="display:none">
                              
        <apex:pageBlockTable id="subTable2" value="{!innerList}" var="item" styleClass="vfTable">               
             <apex:column >
                    <apex:facet name="header"></apex:facet>
             </apex:column>       
             <apex:column value="{!item[4]}">
                    <apex:facet name="header">Name</apex:facet>
             </apex:column>
             <apex:column value="{!item[5]}">
                    <apex:facet name="header">SR Number</apex:facet>
             </apex:column>
             <apex:column value="{!item[6]}">
                    <apex:facet name="header">Date Closed</apex:facet>
             </apex:column>                           
        </apex:pageBlockTable>       
        
        <apex:pageBlockTable id="subTable3" value="{!innerList}" var="item" styleClass="vfTable">               
             <apex:column >
                    <apex:facet name="header"></apex:facet>
             </apex:column>       
             <apex:column value="{!item[7]}">
                    <apex:facet name="header">Resolution</apex:facet>
             </apex:column>
             <apex:column value="{!item[8]}">
                    <apex:facet name="header">Owner</apex:facet>
             </apex:column>
             <apex:column value="{!item[9]}">
                    <apex:facet name="header"></apex:facet>
             </apex:column>                           
        </apex:pageBlockTable> 
          
        </div>
        
        </apex:repeat>        
    </apex:pageBlock>

    </apex:form>
    
    <script>
  
          function hideAllHeader(){
            var headerList=document.getElementsByClassName("headerRow");
            tableList=document.getElementsByTagName("table");
            var aTable;                        
            var headers;
           
            var test=tableList[3];

                        
          for (var i = 0; i < tableList.length; i++) {
            if((tableList[i].id!=="page:form:main1:repeat:0:subTable1")&&(tableList[i].id.indexOf("page:form:main1:repeat:")===0)){           
                headers=tableList[i].getElementsByTagName("thead");                
                for(var j =0; j<headers.length; j++){
                    headers[j].style.display="none";  
                }
               }                                            
            }
         }
         
         hideAllHeader();      
                            
   </script>
    
    <script>
         window.onload = function(){
             hideAllHeader();               
         };   
    
         function componentColorMouseOver(component){
             //component.style.color="rgb(1,91,167)";
             component.style.color="red";
         }
         
         function componentColorMouseOut(component){
             //component.style.color="black";
             component.style.color="rgb(1,91,167)";
         }
         
                          
         function expandProudct1(t, div){
         
             var headerId=div.id.replace("pageBlockTable","page:form:main1:repeat:"); //page:form:main1:repeat:0:subTable1
             var headerId1=headerId+":subTable1";
             var headerId2=headerId+":subTable2";
             
             var headerId3=headerId+":subTable3";
                         
             var tableElem1=document.getElementById(headerId1);
             var headersElem1=tableElem1.getElementsByTagName("thead"); 
             var tableElem2=document.getElementById(headerId2);
             var headersElem2=tableElem2.getElementsByTagName("thead"); 
             var tableElem3=document.getElementById(headerId3);
             var headersElem3=tableElem3.getElementsByTagName("thead"); 
                          
             
             var curDisplay=String(div.style.display);
             if(curDisplay==='none'){             
                 //expand/fold table
                 div.style.display="inline";        
                 
                 t.style.display="none"; //hide/display plus and minus sine                 
                 document.getElementById(t.id.replace("plus","minus")).style.display="inline";    //hide/display plus and minus sine
                 
                 //expand/fold table header
                 if(headerId1.indexOf("page:form:main1:repeat:0:subTable1")===-1){
                     for(var x1 =0; x1<headersElem1.length; x1++){
                         headersElem1[x1].style.display="table-row-group";  
                     }
                 }    
                 for(var x2 =0; x2<headersElem1.length; x2++){
                     headersElem2[x2].style.display="table-row-group";  
                 }  
                 for(var x3 =0; x3<headersElem1.length; x3++){
                     headersElem3[x3].style.display="table-row-group";  
                 }  
                
             }    
                 
         }
         
                  
         function expandProudct2(t, div){
         
             var headerId=div.id.replace("pageBlockTable","page:form:main1:repeat:"); //page:form:main1:repeat:0:subTable1
             var headerId1=headerId+":subTable1";
             var headerId2=headerId+":subTable2";
             var headerId3=headerId+":subTable3";
                         
             var tableElem1=document.getElementById(headerId1);
             var headersElem1=tableElem1.getElementsByTagName("thead"); 
             var tableElem2=document.getElementById(headerId2);
             var headersElem2=tableElem2.getElementsByTagName("thead"); 
             var tableElem3=document.getElementById(headerId3);
             var headersElem3=tableElem3.getElementsByTagName("thead"); 
            
             var curDisplay=String(div.style.display);            
             if(curDisplay=='inline'){
                 div.style.display="none";
                 t.style.display="none"; 
                 document.getElementById(t.id.replace("minus","plus")).style.display="inline";   
             
 //expand/fold table header
                 
                 if(headerId1.indexOf("page:form:main1:repeat:0:subTable1")===-1){
                     for(var x1 =0; x1<headersElem1.length; x1++){
                         headersElem1[x1].style.display="none";  
                     }
                 }
                 for(var x2 =0; x2<headersElem1.length; x2++){
                     headersElem2[x2].style.display="none";  
                 }  
                 for(var x3 =0; x3<headersElem1.length; x3++){
                     headersElem3[x3].style.display="none";  
                 } 
                
             }      
             
         }
         function displayAllColumns(){
             document.getElementById("pageBlock1").style.display="none";    
             document.getElementById("pageBlock2").style.display="inline";    
         }
         
         function displayMainColumns(){
             document.getElementById("pageBlock2").style.display="none";    
             document.getElementById("pageBlock1").style.display="inline";    
         }
                  
    </script>
</apex:page>
Hello

Does anyone know how I could update a Contact Status field to the custom value of "Opportunity" when a new Opportunity is created then update the Status again when the Opportunity is closed?  Note, the Org is Professional Edition so I can't use Workflow Rules for this and I have no experience/knowledge of Triggers.

Any help would be appreciated!
I'm new to coding and trying to write a test trigger in my dev org.  The trigger needs to fire before insert and compare the name of the course being inserted inot my custom object against the existing courses.  If there is a duplicate course being inserted, throw an error.  Here is what I have so far that is not working.  It gives an error that the comparison if statement of "Variable does not exist: Course_Name__c".  Can someone point me in a direction?

=======TRIGGER CODE+++++

trigger testtr1 on Course__c (before insert) {

Public static void CheckDuplicates(List<Course__c> newCourse){             

      //Create a LIST of all existing courses
    List<Coures__c> ExistingCourses= [SELECT Id, Course_Name__c
                            FROM Course__c];

    
    // Create a SET of all incoming  course names to evaluate
  Set<String> Courses = new Set<String>();
    for (Courses__c s : Trigger.new) {
      Courses.add(s.Course_Name__c);
    } /*end for loop */
    
    //Compare SET values to LIST

      for(Courses__c s : Trigger.new)
            if(
                ExistingCourses.Course_Name__c = s.Course_Name__c)
                s.addError('DUPLICATE COURSE NAME');
  

}  /* end ChecDuplicates method */
}   /*end triggger begin */

 
public class CustomEmailComponentHandler {
    @AuraEnabled
    public static User getUserInfo() {
        try{
            User UserObj = [SELECT Name,Email 
                            FROM User 
                            WHERE Id = :UserInfo.getUserId()];
            return UserObj;
            
        }catch(Exception e){
            System.debug('Exception ::' + e.getMessage() + '==============Line Number ::' + e.getLineNumber());
        }
        return null;
    }
    
    @AuraEnabled
    public static  List<SearchResultWrapper> getSearchResult(String searchKeyword){
        try{
            String searchkey = '%'+ searchKeyword + '%';
            System.debug('searchkey ::'+searchkey);
            List<Lead> leadList = new List<Lead>();
            List<Contact> contactList = new List<Contact>();
            List<SearchResultWrapper> searchResultWrapperList = new List<SearchResultWrapper>();
            leadList = [SELECT Name,Email FROM Lead WHERE Email != Null AND Name != Null AND (Name Like :searchkey OR Email Like :searchkey) LIMIT 50000];
            System.debug('leadList ::'+leadList);
            contactList =[SELECT Name,Email FROM Contact WHERE Email != Null AND Name != Null AND (Name Like :searchkey OR Email Like :searchkey )LIMIT 4];
            System.debug('contactList ::'+contactList);
            if(leadList.size()>0 || contactList.size()>0){
                for(Lead Obj : leadList){
                    SearchResultWrapper searchResultWrapperObj = new SearchResultWrapper();
                    searchResultWrapperObj.Name = Obj.Name;
                    searchResultWrapperObj.Email = Obj.Email;
                    searchResultWrapperObj.ObjectName = 'Lead';
                    searchResultWrapperList.add(searchResultWrapperObj);
                }
                for(Contact Obj : contactList){
                    SearchResultWrapper searchResultWrapperObj = new SearchResultWrapper();
                    searchResultWrapperObj.Name = Obj.Name;
                    searchResultWrapperObj.Email = Obj.Email;
                    searchResultWrapperObj.ObjectName = 'Contact';
                    searchResultWrapperList.add(searchResultWrapperObj);
                }
                System.debug('searchResultWrapperList'+searchResultWrapperList);
            }
            return searchResultWrapperList;
            
            
        }catch(Exception e){
            System.debug('Exception ::' + e.getMessage() + '-----Line Number::' + e.getLineNumber());
        }
        return null;
    }
    
    @AuraEnabled
    public static String senMail_apex(String sendFrom, List<String> To, List<String> Cc, List<String> Bcc, String Subject, String Body, List<String> Attachments){
        try{
            List<ContentVersion> contentVersionList = new List<ContentVersion>();
            List<Messaging.EmailFileAttachment> attachmentList = new List<Messaging.EmailFileAttachment>();
            System.debug('sendFrom :' + sendFrom);
            Set<Id> documentId = new Set<Id>();
            if(Attachments.size()>0){
                for(String obj :Attachments){
                    documentId.add(obj);
                }  
            }
            if(documentId.size()>0){
                contentVersionList = [SELECT VersionData,Title,FileExtension FROM ContentVersion WHERE ContentDocumentId In :documentId AND IsLatest = true] ; 
            }
            if(contentVersionList.size()>0){
                for(ContentVersion fileobj : contentVersionList){
                    Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
                    attach.filename = fileobj.Title + '.' + fileobj.FileExtension;
                    attach.body = fileobj.VersionData;
                    attachmentList.add(attach);
                }
            }
            
            
            
            Messaging.SingleEmailMessage sendMail = new Messaging.SingleEmailMessage();
            
            sendMail.setSenderDisplayName(sendFrom);
            sendMail.setToAddresses(To); 
            sendMail.setBccAddresses(Bcc); 
            sendMail.setCcAddresses(Cc); 
            sendMail.setSubject(Subject); 
            sendMail.setHtmlBody(Body);
            sendMail.setFileAttachments(attachmentList);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {sendMail}) ; 
            
            return null;
        }catch(Exception e){
            System.debug('Exception ::' + e.getMessage() + '-----Line Number::' + e.getLineNumber());
        }
        return null;
        
    }
    
    @AuraEnabled
    public static  List<ContentDocument> getFiles(){
        try{
            List<ContentDocument>  contentDocumentList = [SELECT id,ContentSize,ContentModifiedDate,FileExtension,Title,FileType 
                                                          FROM ContentDocument
                                                          LIMIT 50000];
            return contentDocumentList;
            
        }catch(Exception e){
            System.debug('Exception ::' + e.getMessage() + '-----Line Number::' + e.getLineNumber());
        }
        return null;
        
    }
    
    @AuraEnabled
    public static  List<ContentDocument> searchFiles( String searchKeyword){
        try{
            String searchkey = '%'+ searchKeyword + '%';
            List<ContentDocument>  contentDocumentList = [SELECT id,ContentSize,ContentModifiedDate,FileExtension,Title,FileType 
                                                          FROM ContentDocument WHERE
                                                          Title LIKE :searchkey
                                                          LIMIT 50000];
            return contentDocumentList;
            
        }catch(Exception e){
            System.debug('Exception ::' + e.getMessage() + '-----Line Number::' + e.getLineNumber());
        }
        return null;
        
    }
    
    
    public class SearchResultWrapper {
        @AuraEnabled
        public String Name {get;set;}
        @AuraEnabled
        public String Email {get;set;}
        @AuraEnabled
        public String ObjectName {get;set;}
    }
}
Hello,
I have create a VF page to override the standard Quote Details page to be able to hide the Action column on related lists. This works great, but we want to use the Create PDF function to generate quote documents. When I click the Create PDF button, I see the popup window, but get the error: ".....salesforce.com refused to connect". When using the standard page, everything works fine.
Any suggestions?
Thanks!
I have a visualforce page that I want to use a date field to rerender an output panel if the date is a certain month.

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

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

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

I would like to do something like this below
{!IF(MONTH (et.Contract_Start_Date__c)  == 12  ,true,false))}
  • August 12, 2019
  • Like
  • 0
I was trying to solve a challenge from the topic Customize Compact Layouts and then i faced this problem. It has been a month or two  i am learning salesforce so not able to find where exactly problem lies. Please help me out

There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: LJOFHGKY
Hey, i've asked salesforce support if this is possible and they tell me it's not however I find it hard to believe.

If you have 3 cells with the following content:
Cell 1 - (2 characters) example: 01
Cell 2 - (3 characters) example: 123
Cell 3 - (3 characters) example: 345

They can be combined into one as 01123345

I'm looking for a text field with 8 characters to be split into 3 cells using the same format as above;

For example: 01123345

Cell 1 - (2 characters) example: 01
Cell 2 - (3 characters) example: 123
Cell 3 - (3 characters) example: 345

Does anyone have any suggestions
 
I want to add change owner button on opportunity list view page by using lightning componet  . i am  using below code but  can not see change owner button on my oppoty list page 
({
 doInit : function(component, event, helper) {
        var opportunityId = component.get("v.recordId");
        var action = component.get("c.changeOwnerMethod");
        action.setParams({
           opportunityId : opportunityId
        });
        action.setCallback(this, function(response) {
            if(response.getState() === "SUCCESS") {
                console.log("opportunity Owner Changed To Current login User");
             var rec = response.getReturnValue();
             console.log(rec.OwnerId);
            }
        });
        $A.enqueueAction(action);
        $A.get('e.force:refreshView').fire();
 }
})

<aura:component implements="force:hasRecordId,flexipage:availableForRecordHome,force:lightningQuickAction">
  <aura:attribute name="complete" type="Boolean" default="false" />
    <aura:attribute name="opportunityRecord" type="Object"/>
    <force:recordData mode="EDIT" aura:id="recordLoader"
                      recordId="{!v.recordId}"
                      fields="OpportunityNumber,OwnerId"
                      targetFields="{!v.opportunityRecord}" />
    <aura:if isTrue="{!v.opportunity.OwnerId != $SObjectType.CurrentUser.Id}">
    <aura:if isTrue="{!not(v.complete)}">
        <lightning:input type="toggle" messageToggleActive="" messageToggleInactive="" label="Are you sure to take the ownership on this Opportnity record?" name="input1" onchange="{!c.handleClick}"/>
    </aura:if>

    <aura:if isTrue="{!v.complete}">
        Opportunity is assigned to new Owner. 
    </aura:if>
    </aura:if>
    <aura:if isTrue="{!v.opportunityRecord.OwnerId == $SObjectType.CurrentUser.Id}">
        opportunity is already assigned to owner.
    </aura:if>
</aura:component>
I can see the utton via VF page implmentation but  my requirment is to display this via Lightning componet
Please  find my VF page code
 
<apex:page standardController="Opportunity" recordSetVar="opportunities" extensions="Workaround" showHeader="false"
 lightningStylesheets="true">
<script>
        function showToast() {
            sforce.one.showToast({
                "title": "Success!",
                "message": "{!mySelectedSize} record updated successfully.",
                "type": "success"
            });
        }
    </script>
    
    <apex:form id="muform">
        <apex:pageMessage summary="Selected Collection Size: {!mySelectedSize}" 
            severity="info"
                          id="mupms" />
  <apex:pageBlock >
      <apex:pageBlockSection >
      <apex:inputField value="{!Opportunity.OwnerId}" />
      </apex:pageBlockSection>
    <apex:pageBlockTable value="{!selected}" var="opp">
        <apex:column value="{!opp.Name}"/>    
      </apex:pageBlockTable>
      <apex:commandButton action="{!Save}" value="Save" onclick="showToast();" />
      <apex:commandButton value="Cancel" action="{!cancel}" />
    
    </apex:pageBlock>  
    
    </apex:form>    
</apex:page>
 
public class Workaround {
 ApexPages.StandardSetController setCon;

    public selectedSizeWorkaround(ApexPages.StandardSetController controller) {
        setCon = controller;
    }

    public integer getMySelectedSize() {
                return setCon.getSelected().size();
        }
       
    public integer getMyRecordsSize() {
        return setCon.getRecords().size();
    }

}


 
I want to change the default toast message displayed when I create a new opportunity record.
Requirement is that the the Toast message should display : 'Associated Account + Created Date' as the Opportunity name, if at all this is possible.
  • August 12, 2019
  • Like
  • 0
Hey guys , I am beginner to salesforce, my reqirement is I have to find the Second Maximum amount of oppurtunity using Soql query,, so what will be the query ??
Hi,

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

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


 
Hi,

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

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

trigger ContactTrigger on Contact (before insert,before update)
 {
   
  set<ID> accId = new set<ID>();
   list<string> ContactEmails=new list<string>();
    for(Contact conVar:trigger.new)
    {
        ContactEmails.add(conVar.email);
        accId.add(conVar.AccountId);
    }
    
    system.debug('ContactEmails ************' +ContactEmails);
    
    list<Contact> listOfDuplicateContacts=[select id,email,Account.ID from Contact where email in :ContactEmails AND AccountID IN : accId];
      system.debug('listOfDuplicateContacts ************' +listOfDuplicateContacts);
    
    for(Contact con:trigger.new)
    {
        if(trigger.isInsert){
        if(listOfDuplicateContacts.size()!=0)
        {
            con.addError('Contact email already exists with this name');
        }
        }
        if(trigger.isUpdate)
        {
           for(Contact oldContact :trigger.old)
           {
               if(con.Email!=oldContact.Email && listOfDuplicateContacts.size()!=0)
               {
                   con.addError('Contact email already exists with this name');
               }
           }
        }
    }
}
  • August 12, 2019
  • Like
  • 0
Hi Developers,

I am rendering a dynamic visualforce pdf having first and last page as image. I am able to set the full first page backgrounf image using @page:first but for last page I am stuck. I dont want any marigin Image should fit full size on last page.

I really need this help.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