+ Start a Discussion
vickySFDCvickySFDC 

Hi All,

This two VF tags I am really confusing

Can anyone give examples <apex:actionsupport> and <apex:actionfunction> tags and give some examples?

 

 

Thanks,

 

Vicky

Best Answer chosen by Admin (Salesforce Developers) 
asish1989asish1989

HI

A component that provides support for invoking controller action methods directly from JavaScript code using an AJAX request. An <apex:actionFunction> component must be a child of an<apex:form> component.

 

Used when we need to perform similar action on varioud events. Een though you can use it in place of actionSupport as well where only event is related to only one control.

Example

<!-- Page: -->
	<apex:page controller="exampleCon">
	<apex:form>
		<!-- Define the JavaScript function sayHello-->
		<apex:actionFunction name="sayHello" action="{!sayHello}" rerender="out"
		status="myStatus"/>
	</apex:form>
	
	<apex:outputPanel id="out">
		<apex:outputText value="Hello "/>
		<apex:actionStatus startText="requesting..." id="myStatus">
		<apex:facet name="stop">{!username}</apex:facet>
		</apex:actionStatus>
	</apex:outputPanel>
	
	<!-- Call the sayHello JavaScript function using a script element-->
	<script>window.setTimeout(sayHello,2000)</script>
	<p><apex:outputText value="Clicked? {!state}" id="showstate" /></p>
	<!-- Add the onclick event listener to a panel. When clicked, the panel triggers
	the methodOneInJavascript actionFunction with a param -->
	<apex:outputPanel onclick="methodOneInJavascript('Yes!')" styleClass="btn">
		Click Me
	</apex:outputPanel>
	
	<apex:form>
		<apex:actionFunction action="{!methodOne}" name="methodOneInJavascript"
		rerender="showstate">
			<apex:param name="firstParam" assignTo="{!state}" value="" />
		</apex:actionFunction>
	</apex:form>
</apex:page>

/*** Controller ***/
public class exampleCon {
	String uname;
	public String getUsername() {
		return uname;
	}
	public PageReference sayHello() {
		uname = UserInfo.getName();
		return null;
	}
	public void setState(String n) {
		state = n;
	}
	public String getState() {
		return state;
	}
	public PageReference methodOne() {
		return null;
	}
	private String state = 'no';
}

 

.ActionSupport : A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by theserver when a particular event occurs, such as a button click or mouseover.

 

Used when we want to perform an action on a perticular eventof any control like onchange of any text box or picklist.

 

Example

<apex:page controller="exampleCon">
	<apex:form>
		<apex:outputpanel id="counter">
			<apex:outputText value="Click Me!: {!count}"/>
				<apex:actionSupport event="onclick"
				action="{!incrementCounter}"
			rerender="counter" status="counterStatus"/>
		</apex:outputpanel>
		
		<apex:actionStatus id="counterStatus"
			startText=" (incrementing...)"
			stopText=" (done)"/>
	</apex:form>
</apex:page>


/*** Controller: ***/
public class exampleCon {
	Integer count = 0;
	public PageReference incrementCounter() {
		count++;
		return null;
	}
	public Integer getCount() {
		return count;
	}
}

 If this post answers your questions please mark it as solved and hit kudos button if it helps you

 

Thanks

 

PronowPronow 

Hello there,

 

In my project, on an object I have two fields. One is an auto-update and other is a formula field. Auto-update field contains 'Current Date' value ( 'TODAY()' ). Formula field is number type, calculating difference in days between a custom DATE field and above auto-update DATE field.

 

I am trying to trigger, a workflow rule that will fire when value of formula field would be 30 or 60.

 

Please help me out as the workflow is not getting triggered when the above formula evaluates to true.

 

Thank you in advance.

Best Answer chosen by Admin (Salesforce Developers) 
PronowPronow

Thank you for your response.

 

However, I guess you did not get the actual problem that I faced. The workflow is supposed to fire when the auto-update field i.e. Current date will change. The other field is formula field calculating No. of days between two dates. One is Cutom date field and other is Current date.

 

Even if I try to fire a workflow to update either Current date or No. of days, you need to update that particular record.

 

So, as a conclusion I found a solution to write a Schedular that will fire everyday, and it will calculate no. of days and update it. This will cause all dependent workflows to fire.

 

I implemented this solution in my project, and its working fine and uninterrupted now.

 

Thank you for your knowledge sharing.

Basil DobekBasil Dobek 
Hi, I'm trying to create a new empty project using the Salesforce CLI and I receive the message "ERROR running force:project:create  Cannot read property 'create' of undefined".    Does anyone know what might be causing this or how to further troubleshoot it? 

The command I'm entering in the terminal is "sfdx force:project:create --projectname VSCodeQuickStart".   I've tried "sfdx force:project:create --projectname VSCodeQuickStart --manifest" as well.


Thank you


 
Best Answer chosen by Basil Dobek
Khan AnasKhan Anas (Salesforce Developers) 
Hi Basil,

Greetings to you!

Please make sure you are using the latest version of salesforcedx. Try to update the CLI
sfdx update

If the problem still persists, uninstall the salesforcedx and reinstall it.

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
RarLopzRarLopz 
Can someone please assist, how do i get around this exception of 'Too many query Rows 5001'

 
list<Id> accId = new list<Id>();

list<Contact> conDSA = [Select Id, Name, DSA__c, AccountID from Contact 
                        Where DSA__c = true AND AccountID!=null ];

system.debug('Number of Contacts that are DSA ' +conDSA.size());
for (Contact c: conDSA){
system.debug('>>> ' +c.Name + c.AccountId);
    accId.add(c.AccountId);

}

list<AccountContactRelation> acr = [SELECT Id, isDSA__c,AccountId, ContactId 
                                    FROM AccountContactRelation 
                                    Where AccountId IN :accId ];

system.debug('Number of records in ACR are: ' +acr.size());

for (AccountContactRelation a: acr){
    	a.isDSA__c = true;
}
update acr;

 
Best Answer chosen by RarLopz
Raj VakatiRaj Vakati
Looks like you are calling this code from the developer console so you are getting the  all the record so can you try like this

 
list<Id> accId = new list<Id>();

list<Contact> conDSA = [Select Id, Name, DSA__c, AccountID from Contact 
                        Where DSA__c = true AND AccountID!=null Limit 500];

system.debug('Number of Contacts that are DSA ' +conDSA.size());
for (Contact c: conDSA){
system.debug('>>> ' +c.Name + c.AccountId);
    accId.add(c.AccountId);

}

list<AccountContactRelation> acr = [SELECT Id, isDSA__c,AccountId, ContactId 
                                    FROM AccountContactRelation 
                                    Where AccountId IN :accId Limit 9999];

system.debug('Number of records in ACR are: ' +acr.size());

for (AccountContactRelation a: acr){
    	a.isDSA__c = true;
}
update acr;

https://help.salesforce.com/articleView?id=000181404&language=en_US&type=1
RupBRupB 

Hi,

 

- Sorry to bother, but I found no answer to this wuestion either on the web, or in the dev forum, or in the Apex documentation - 

 

I have a trigger, which detects error conditions and feeds errors to the class or field.

This gives a nice result interactively, in the GUI.

But how do I write test code to catch these errors ?  Is there a System.AssertException(), or the equivalent ? 

 

trigger createOrder on Asset (after insert, after update) {[...] if (price.get(a.Product2Id) == NULL) { System.debug(' error : no active price'); a.Product2Id.addError('no active price on the Product'); }[...]}

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdccoder1sfdccoder1

Hi RupB,

 

I worked out a solution for a similar case I had where addError() was used for a record and not for a field.

I  believe though it should work for your case too.

 

The idea is to:

 

a. Write code in the test class that will cause the trigger to 'addError()'.

b. Surround the above test class code with try - catch.

cAssert that an exception is thrown and that the exception message is the same one you created with 'addError()'.

 

Here's an example (partly pseudo) code from both trigger and test class:

 

Trigger: 

 

if(myRecord.MyField == some value)

myRecord.addError('My Error Message');

 

 

Test Class: 

 

try

{

MyRecord.MyField = a value that will cause an error

update MyRocord;

throw new MyException('An exception should have been thrown by the trigger but was not.'); // 1. If we get to this line it means an error was not added and the test class should throw an exception here. 2MyException class extends Exception.

}

catch(Exception e)

{

Boolean expectedExceptionThrown =  e.getMessage().contains('My Error Message')) ? true : false;

System.AssertEquals(expectedExceptionThrown, true);

 

 

Let me know if this did the work

 

 

Message Edited by sfdccoder1 on 09-01-2009 01:32 AM
Richard Rodriguez 1Richard Rodriguez 1 
I'm trying to create an Apex Class that checks all Account records on a daily basis and sends an email to the email field on ones that have a review due on that date.

For example:
Vendor ABC Pty Ltd has opted in for reviews (Vendor Review: Reminders = true), has an annual review date set in their record (Vendor Review: Date = 17/02/2019), and an email address set in their record (Vendor Review: Email = abc@test.com).

Here is my code:
global class VendorReviewCronJob implements Schedulable{ 
    
        global void execute(SchedulableContext SC) {
            sendmail();
        }

        public List<Id> getVendorReviewEmailAddresses(Integer Month, Integer Day) 
        { 
            List<Id> mailToIds = new List<Id>();
             
            Account[] a = [SELECT Id, Vendor_Review_Email__c, Vendor_Review_Date__c, Vendor_Review_Reminders__c
                            FROM Account 
                            WHERE DAY_IN_MONTH(Vendor_Review_Date__c) = : Day 
                            AND CALENDAR_MONTH(Vendor_Review_Date__c) = : Month   
                            ];
        
            for(Account recipient : a) {
                    
                    System.Debug('\n*******Found VendorReview Recipient');
                                        
                    if (recipient.Vendor_Review_Reminders__c == true)
                    {
                        mailToIds.add(recipient.Id);
                        System.Debug('\n*******Recipient: '+ recipient.Vendor_Review_Email__c);
                         
                    } else {
                        System.Debug('\n*******NO Recipient');
                    }
                
            }

            return mailToIds;
        }




        public void sendMail() 
        {
      
            String debugAddress = 'eyewell@salesforce.com';
            String VendorReviewEmailTemplateName = 'User_Vendor_Review_Required';       
            String debugMessage;
            String[] toAddresses;

            Integer DayOfEvent   = date.today().day();
            Integer MonthOfEvent = date.today().month();

            List<Id> VendorReviewIdsList = getVendorReviewEmailAddresses(MonthOfEvent,DayOfEvent);

            EmailTemplate VendorReviewTemplate = [select Id,Name,Subject,body from EmailTemplate where DeveloperName = :VendorReviewEmailTemplateName];
 
            if(VendorReviewTemplate != null && VendorReviewIdsList.isEmpty() == false)
            {

                Messaging.MassEmailMessage VendorReviewMail = new Messaging.MassEmailMessage();
    
                VendorReviewMail.setTargetObjectIds(VendorReviewIdsList);
                VendorReviewMail.setTemplateId(VendorReviewTemplate.Id);
                VendorReviewMail.setUseSignature(false);
                VendorReviewMail.setSaveAsActivity(true);

                try {
                    Messaging.sendEmail(new Messaging.MassEmailMessage[] { VendorReviewMail });
                }catch(Exception e)
                {
                    System.Debug(e);
                }
           
            }
            else
            {
                System.Debug('VendorReviewCronJob:sendMail(): Either an email template could not be found, or no Account has a Vendor Review today');
            }

                
        }

    
}
I've scheduled the apex class to run daily, but although it's showing that it has run, the emails for the reviews due that day haven't sent, and I also haven't received the confirmation email of how many were sent.

Admittedly, I got the base of the code from a mailer that was checking for birthdays on a Contact object, but I felt the same principles still applied.

Can anybody see where I've gone wrong?
Best Answer chosen by Richard Rodriguez 1
SarvaniSarvani
Hello Richard,

I see there is no problem in your code. It worked for me, when I tested on "contact" object but NOT  for "Account" object. It gave me error "Only Users, Contacts, Leads, and Person objects are allowed for targetObjectIds.: []."  Try using SingleEmailMessage method and use setToAddresses attribute to set the email receiver.

Hope it helps,

Thanks,
Sarvani
Brian Chipman 4Brian Chipman 4 
Would like to create a class to POST some data on an endpoint provided by an outside vendor.  Am modeling it on the "Mighty Moose" Trailhead example (https://trailhead.salesforce.com/en/content/learn/modules/apex_integration_services/apex_integration_rest_callouts) and the only difference seems to be the endpoint, the existence of an "api_key" (which the vendor says should be part of the url), and am passing more than one field.  Looks simple, but I have never done this type of thing before.  

Am testing in the "Open Execute Anonymous Window" of the developer console.  The trailhead example works fine but I am always getting a 400 Bad Request error for the real call out.  I do have a Remote Site setting.

Anything in the code below you can see (some data changed for security reasons)?
Any code you think might work better?
Any questions or details I should ask the vendor?
The vendor says I should be getting an explanatory message, but in the debug log I only see '400 Bad Request' and some other seemingly unrelated stuff.
 
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://my.domain.com/icon/send_eligible_offers?api_key=abcd-1234');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');

// Set the body as a JSON object
request.setBody('{"product_sku":"NTL07007", "serial_number":"1234343434", "user_email":"user.name@gmail.com", "sales_person_email":"agent@mail.com"}');

HttpResponse response = http.send(request);

// Parse the JSON response
if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
} else {
    System.debug(response.getBody());
}

 
Best Answer chosen by Brian Chipman 4
Egor Gerasimenko 9Egor Gerasimenko 9
400 Bad Request is the response from the endpoint you are trying to hit, and typically indicates that you are sending some bad data. Perhaps you are missing a header or your JSON doesn't match the expected schema. You can try to send the same request using a REST tool like Postman to confirm that the problem is not with the Apex code. 
Sammy7Sammy7 
Hi, 
 Im getting the following error and cannot figure out why: 

System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: null: [toAddresses, null]

Class.email_class.send: line 48, column 1
Class.TestquoteEmailclass.sendEmailTestMethod: line 47, column 1

Below is my test class: 
@isTest
public class TestquoteEmailclass {
    @isTest static void sendEmailTestMethod(){
    
        Product2 prod = new Product2(Name = 'SLA: Bronze', IsActive = true);
        insert prod;
        PricebookEntry pbe=new PricebookEntry(unitprice=0.01,Product2Id=prod.Id, Pricebook2Id=Test.getStandardPricebookId(), IsActive= true); 
        insert pbe; 
        Account acc = new Account (name='Acme');
        insert acc;
        Opportunity opp= new Opportunity (name='Testopp', Accountid=acc.id, CloseDate= date.today(), StageName='Closed Won', Pricebook2id=Test.getStandardPricebookId());
        insert opp; 
        OpportunityLineItem oppLine = new OpportunityLineItem( pricebookentryid=pbe.Id,TotalPrice=2000, Quantity = 2,Opportunityid = opp.Id);
        insert oppLine;       
        Quote q= new Quote (Name='Testq', Opportunityid=opp.id, QuotetoInvoice__c= True,  Pricebook2id=Test.getStandardPricebookId());
        insert q;
    
     System.currentPagereference().getParameters().put('id',q.id);
     Attachment objAtt = new Attachment();
     objAtt.Name = 'Test';
     objAtt.body = Blob.valueof('string');
     objAtt.ParentId = q.Id;
     insert objAtt;

         ApexPages.StandardController sc =new ApexPages.StandardController(q); 
        email_class ec=new email_class (sc);
        ec.ToAddresses='test@gmail.com';
         ec.CCAddresses='test2@gmail.com';
        ec.emailCC= 'test3@gmail.com';
        ec.email_body='test1111111';
        ec.subject='test22222';
        
         Messaging.InboundEmail email = new Messaging.InboundEmail();  
         Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        email.plainTextBody = 'This should become a note';
        email.fromAddress ='test@test.com';
        String contactEmail = 'jsmith@salesforce.com';
        email.ccAddresses = new String[] {'Jon Smith <' + contactEmail + '>'};
        email.subject = 'Dummy Account Name 123';

        ec.send();

}
}

And my controller:
public class email_class{
        
    Public string ToAddresses {get;set;}
    Public string CCAddresses {get;set;}
    Public string quoteId {get;set;}
    Public string subject {get;set;}
    public string email_body {get;set;}
    public string emailTo {get;set;}
    public string emailCC {get;set;}
     public  string [] ccaddress;   
              
        
        
        public email_class(ApexPages.StandardController controller) {
                quoteId = ApexPages.currentPage().getParameters().get('id');
    }
        
    Public PageReference send(){

                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // set the to address
                mail.setToAddresses(new String[] {emailTo}); 
               // mail.setCCAddresses(new String[] {emailCC});   //set the cc address
                   
        if(emailCC != null && emailCC.trim() != '')
        {
        ccaddress = emailCC.split(',',0);
        mail.setCCAddresses(ccaddress);}
                                                              
   
                mail.setSubject(subject);
                mail.setBccSender(false);
                mail.setUseSignature(false);
                mail.setPlainTextBody(email_body);
               

                List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();

                for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :quoteId]){  // Add to attachment file list  
                        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();  
                        efa.setFileName(a.Name); 
                        efa.setBody(a.Body); 
                        fileAttachments.add(efa);
                }
                mail.setFileAttachments(fileAttachments);// Send email
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                return null;
        }
}

Any help is appreciated !
Best Answer chosen by Sammy7
Sammy7Sammy7
Forgot to pass "emailTo" DOH !
Neeraj Sharma 103Neeraj Sharma 103 
Hi 

I am new in Salesforce Begineer

My Question is:

How to validate Phone field of Account Object with Use of Apex Class and the validation is ONly 10 Digit is input by user no sepcial character no characters Only digits and digit will be 10 
and if user input digit according the condition then the record will be save and user not input 10digit then error will be show on the Phone field "Please Provide Valid Number"  on Custom Visual force Page
Please help me ASAP


Thanks 
Neeraj Sharma
 
Best Answer chosen by Neeraj Sharma 103
Khan AnasKhan Anas (Salesforce Developers) 
Hi Neeraj,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Visualforce:
<apex:page id="pg" controller="PhoneValidationC" >
    <apex:form id="fm">
        
        <script >
        function show()
        {
            var phn=document.getElementById("{!$Component.pg.fm.pgb.pbs.one}");
            var pattern=/^\d{10}$/;
            if(!pattern.test(phn.value))
            {
                alert("Please Provide Valid Number");
                phn.focus();
                return false;
            }  
            else{
                alert("Apex Method");
                CallApexMethod();
                return true;
            }
        }
        </script>
        
        <apex:actionFunction name="CallApexMethod" action="{!insertIt}" reRender="fm"/>
        <apex:pageBlock id="pgb" title="Account Phone Validation">
            <apex:pageBlockSection columns="1" id="pbs">
                <apex:inputField value="{!acc.Name}" />
                <apex:inputField value="{!acc.Phone}" id="one" />               
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="Bottom">
                <apex:commandButton value="Validate" onclick="show();" />
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:
public class PhoneValidationC {
    
    public Account acc {get;set;}
    
    public PhoneValidationC(){
        acc = new Account();
    }
    
    public pageReference insertIt(){
        System.debug('Apex Method');
        INSERT acc;   
        return null;
    }    
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Patrick BulaczPatrick Bulacz 

Hi All,

 

Just wondering if anyone has had any experience with working around the 100000 char limit on Strings in Apex.

 

Basically am producing a large text file that needs to then be attached to a record via notes and attachments.

 

I've got a few workarounds but wondering if there are any other ideas out there.

 

Ideally I'd like to check the length of the string and if it's 'nearing' the limit convert it to a blob and add it to a list of blobs and then run a loop and add all the blobs together to create 1 large file and then attach that via notes and attachments. Obviously that can't be done because you can't just simply add blobs but that's the basic dilemma so if anyone has any suggestions please let me know.

 

My other solutions are to generate the output to a visualforce page then scrape the visualforce page but I get the ugly <Html> and </Html> tags at the beginning and the formatting is a little off (would be good to just be able to 'renderAs=text' but oh well.

 

Anyway any help is much appreciated.

 

Cheers,

 

Patrick

Best Answer chosen by Admin (Salesforce Developers) 
wesnoltewesnolte

Hey

 

What about this:

 

 

Blob myBIGblob;
for(Blob thisB:myBlobs){
// unfortunately can't do the following with binary types like you can
// with strings :(
myBIGblob.valueOf(myBIGblob.toString() + thisB.toString());
}