0

I am working on a visualforce page where on click of a button i am passing some parameters in URL and fetching that in controller using ApexPages.currentPage().getParameters().get() method.

But I am not able to get the city parameter in the below URL.

what am I doing wrong?

URL:https://c.cs51.visual.force.com/apex/emailClient?streetAdd=2711+Avenue+X+&leadID=00Q4B000003KWwcUAG#5G&City=Brooklyn

public with sharing class SendEmailController {

    public String addlRecipients {get; set;}
    public Lead   ourLead {get; set;}
    public EmailMessage emailMsg {get; private set;}
    public String FromAddress {get;set;}
    public string StreetAddress {get;set;}
    public string cityName {get;set;}



    public SendEmailController() {

        //Getting all the parameters from the URL.
        String streetAdd = ApexPages.currentPage().getParameters().get('streetAdd');
        if(streetAdd != null){
            StreetAddress = streetAdd;
        }

        string city = ApexPages.currentPage().getParameters().get('City');
          system.debug('city city'+city);
        if(city !=null){          
            cityName = city;    
        }
        system.debug('city param'+cityName);
        String leadID = ApexPAges.currentPage().getParameters().get('leadID');
        if(leadID != null)
            ourLead = [select id,name,Email from lead where id =:leadID];
        FromAddress = 'Sample@movoto.com';
        emailMsg = new EmailMessage();


    }

    public Attachment attachment {
        get {
            if (attachment==null) {
                System.debug('==========> creating new empty Attachment.');
                attachment = new Attachment();
            }
            return attachment;
        }
        set;
    }

    // send email message per the attributes specified by a user.
    public PageReference send() {
        try {
            // now create our SingleEmailMessage to send out.
            Messaging.SingleEmailMessage singleEmailMsg = new Messaging.SingleEmailMessage();

            // concatenate all Bcc Addresses
            if (emailMsg.BccAddress != null && emailMsg.BccAddress != '') {
                singleEmailMsg.setBccAddresses(emailMsg.BccAddress.split(';'));
            }

            // concatenate all CC Addresses
            if (emailMsg.CcAddress != null && emailMsg.CcAddress != '') {
                singleEmailMsg.setCcAddresses(emailMsg.CcAddress.split(';'));
            }

            singleEmailMsg.setSubject(emailMsg.Subject);
            singleEmailMsg.setPlainTextBody(emailMsg.TextBody);
            singleEmailMsg.setTargetObjectId(ourLead.id);
            singleEmailMsg.setSaveAsActivity(true); // Save this email as an acitvity in activity history.

            // now add additional recipients
            String[] addlToAddresses = null;
            if (addlRecipients != null && addlRecipients != '') {
                addlToAddresses = addlRecipients.split(';');
            }
            // now lets add any additional recipients to our list of recipients.
            List<String> lstToAddresses = null;
            if (addlToAddresses != null) {
                // now append these to our main recipient.
                lstToAddresses = new List<String>(addlToAddresses);
            } else {
                lstToAddresses = new List<String>();
            }
            lstToAddresses.add(emailMsg.ToAddress);
            singleEmailMsg.setToAddresses(lstToAddresses); 

            // now we need to reset the ToAddress for our EmailMessage.
            emailMsg.ToAddress += (addlRecipients != null ? ';' + addlRecipients : '');

            if (attachment.Body != null) {
                Messaging.EmailFileAttachment emailAttachment = new Messaging.EmailFileAttachment();
                emailAttachment.setBody(attachment.Body);
                emailAttachment.setFileName(attachment.Name);
                singleEmailMsg.setFileAttachments(new List<Messaging.EmailFileAttachment> {emailAttachment});
            }
            List<Messaging.SendEmailResult> results =  Messaging.sendEmail(
                new List<Messaging.SingleEmailMessage> {singleEmailMsg});

            // now parse  our results

            if (results[0].success) {

                if (attachment.Body != null) {
                    attachment.parentId=emailMsg.Id;
                    insert attachment;
                }

                PageReference pgRef = new PageReference('/' + ourLead.Id);
                pgRef.setRedirect(true);
                return pgRef;
            } else {
                // on failure, display error message on existing page so return null to return there.
                String errorMsg = 'Error sending Email Message. Details = ' + results.get(0).getErrors()[0].getMessage();
                System.debug('==========> ' + errorMsg);
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, errorMsg));
                return null;
            }
        }
        catch (Exception e) {
            // on failure, display error message on existing page so return null to return there.
            String errorMsg = 'Exception thrown trying to send Email Message. Details = ' + e;
            System.debug('==========> ' + errorMsg);
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, errorMsg));
            return null;
        }

        return null;
    }

    // cancel creation of emailMessage. 
    public PageReference cancel() {
        // no need to do anything - just return to calling page.
        PageReference pgRef = new PageReference('/' + ourLead.Id);
        pgRef.setRedirect(true);
        return pgRef;
    }


    public PageReference populateTemplate() {
        // we need to perform the merge for this email template before displaying to end-user.

        EmailTemplate emailTemplate = [select Body, HtmlValue, Subject, DeveloperName, BrandTemplateId 
                                       from EmailTemplate where DeveloperName='Brokerage_email_template' limit 1];

        // construct dummy email to have Salesforce merge BrandTemplate (HTML letterhead) with our email
        Messaging.SingleEmailMessage dummyEmailMsg = new Messaging.SingleEmailMessage();
        dummyEmailMsg.setTemplateId(emailTemplate.Id);
        // This ensures that sending this email is not saved as an activity for the targetObjectId. 
        dummyEmailMsg.setSaveAsActivity(false);

        // send dummy email to populate HTML letterhead in our EmailMessage object's HTML body.
        String[] toAddresses = new String[]{FromAddress};
            dummyEmailMsg.setToAddresses(toAddresses);

        Savepoint sp = Database.setSavepoint();

        Account dummyAcct = new Account(Name='dummy account');
        insert dummyAcct;

        Contact dummyContact        = new Contact(AccountId=dummyAcct.Id);
        dummyContact.FirstName      = 'First';
        dummyContact.LastName       = 'Last';
        dummyContact.Email          = 'nobody@nowhere.com';
        insert dummyContact;

        dummyEmailMsg.setTargetObjectId(dummyContact.Id);
        dummyEmailMsg.setWhatId(ourLead.Id);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {dummyEmailMsg});
        // now rollback our changes.
        Database.rollback(sp);

        String body = dummyEmailMsg.getPlainTextBody();

          system.debug('cityy::'+cityName);
           system.debug('stdd::'+StreetAddress);

        if(!String.isBlank(StreetAddress) && StreetAddress!= 'null')
            body = body.replace('ADDR ', StreetAddress);
         else{
              body = body.replace('ADDR ', ' ');
         } 
          if(cityName!=null && cityName != 'null') { 
           body = body.replace('CITYR', cityName);
            }
            else
            {
                 body = body.replace('CITYR', ' ');
            }
            body = body.replace('ClientName', ourLead.name);



        // now populate our fields with values from SingleEmailMessage.
        emailMsg.BccAddress  = UserInfo.getUserEmail();
        emailMsg.Subject     = dummyEmailMsg.getSubject();
        emailMsg.TextBody    = body;
        emailMsg.ToAddress   = ourLead.email;
        emailMsg.FromAddress = fromAddress; 
        emailMsg.CcAddress   = '';

        return null;
    }
}
  • 4
    Remove #5G before City parameter in url and try. – Reshma May 10 '17 at 5:51
  • It works after removing #5G from the URL parameter. Is there any reason for appending that in URL? – Rohit Mourya May 10 '17 at 5:53
  • URL accept certain valid character in query parameters, always good to encode them before redirection. – Raul May 10 '17 at 6:07
  • 1
    There are no salesforce limits for no of characters passed as parameters. But you should aware of browser URL length limits. If #5G is part of streetAdd param then how its coming after leadId param? Please ensure url parameters are encoded properly to make it works fine. – Reshma May 10 '17 at 6:16
  • 1
    Anything after the # in the URL is not sent to server by the browser that's why you are not getting value for the City parameter; – itzmukeshy7 May 10 '17 at 8:56
1

If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in ApexPages.currentPage().getParameters().get()). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter or remove this and add to the main URL.

Credit: sfussenegger

| improve this answer | |
0

We can do it via javascript-

        function getParameterByName(name, url) {
            if (!url) url = window.location.href;
             name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
            if (!results) 
                return null;
            if (!results[2]) 
                return '';

            return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Call this function - For eg: If you are passing a variable by the name of id we can get it by using

JavaScrprit

var GetIdFromUrl = getParameterByName('id');
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.