• sandeep@Salesforce
  • PRO
  • 2649 Points
  • Member since 2011
  • Project Leader
  • Rsystems International


  • Chatter
    Feed
  • 66
    Best Answers
  • 5
    Likes Received
  • 5
    Likes Given
  • 44
    Questions
  • 1003
    Replies
I created the following class that updates the Websites field after a new website is added. It basically normalises it by removing 'http://', 'https://', and 'www'.

Here's the class:
 
trigger standardiseWebsitesTrigger on Account (after insert, after update ) {
    if(checkRecursive.runOnce()){
        
        Set<Id> AccIds = new Set<Id>();
        
        List<Account> acctsToUpdate = new List<Account>{};
            
            
            for (Account acc : Trigger.new){
                AccIds.add(acc.Id);
            }
        
        List<Account> accounts = [SELECT Id, Website FROM Account WHERE Id IN :AccIds];
        
        for (Account acc : accounts){
            string website = acc.Website;
            string hostDomain1 = 'http://';
            string hostDomain2 = 'https://';
            string justWWWAddress = 'www';       
            
            if (acc.Website.startsWith(hostDomain1) || acc.Website.startsWith(hostDomain2) && acctsToUpdate.isEmpty()){
                Url u = new Url(acc.Website);
                website = u.GetHost();
                acc.Website = u.getHost().replaceFirst('^(https?://www\\.|https?://|www\\.)','');
                acctsToUpdate.add(acc);
                
            }
            
            if(acc.Website.startsWith(justWWWAddress) && acctsToUpdate.isEmpty()){
                acc.website = website.substring(4);
                acctsToUpdate.add(acc);
                
            }
            
            update acctsToUpdate; 
            
        }
    }
    
    }

However when using the following test the assertion relating to removing the 'www.' component fails:
   
@isTest
    public class standardiseWebsitesTriggerTest {

    static testmethod void standardiseWebsiteTriggerHTTP() {
        testSetup('HTTP', 'http://I_AM_HTTP', true);
    }

    static testmethod void standardiseWebsitesTriggerWWW() {
        testSetup('WWW', 'WWW.I_AM_WWW', false);
    }

    public static void testSetup(String accName, String accWebsite, Boolean webProtocol) {
        Account acc = new Account(
            Name = accName,
            Website = accWebsite
        );
        insert acc;

        Account updatedAccount = [select Website from Account where id = :acc.Id];
        
        if(webProtocol) {
            Url u = new Url(acc.Website);
            System.assert(u.getHost() == updatedAccount.Website);
        } else {
            System.assert(updatedAccount.Website == acc.Website.substring(4));
        }
    }
    }

The error is:
 
>    Assertion failed
Class.standardiseWebsitesTriggerTest.testSetup: line 25, column 1
Class.standardiseWebsitesTriggerTest.standardiseWebsitesTriggerWWW: line 9, column 1

Any idea as to why this test may be failing?




 
Hello,

When i was deploying apex class with the profile i get below error on on of the profile "XYZ" like below:
Unknown user permission: LightningConsoleAllowedForUser
thanks for suggestion !
 
  • May 30, 2017
  • Like
  • 0
Hi. I am trying to use actionPoller to fetch data updated through a @future call (just the field being updated asyncronously, Future_Date__c), but it seems that the data in the StandardController is stuck in the original value, even though the fetch date is changed. Do you know how to trigger the standard controller to get the new data and refresh that part of the view?
<apex:page standardController="Case" cache="false" >
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:outputPanel id="blockToRerender" >
                <apex:form >
                    <apex:outputLabel value="Future Date: " />
                    <apex:actionStatus id="counterStatus" startText="Fetching…" stopText="Done!" rendered="{!ISBLANK(Case.Future_Date__c)}" />
                    <apex:outputText value="{!Case.Future_Date__c}" />
                    <br/><br/>
                    <apex:outputLabel value="Fetch Date: " />
                    <apex:outputText value="{!Now()}" />
                    <apex:actionPoller oncomplete="refreshJS();" interval="5" status="counterStatus" enabled="{!ISBLANK(Case.Future_Date__c)}" />
                    <apex:actionFunction name="refreshJS" reRender="blockToRerender" /> 
                </apex:form>
            </apex:outputPanel>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

 
Hello,

I'm very new to apex coding. I was informed that the proper way of creating trigger is to create a trigger then call apex class methods. Is that right?

I tried it on my end with a very simple trigger but I can't make it work.
Basically, what I want is that when I create Account, it will automatically create a Contact under the Account with Account is equal to Account id and contact last name is equal to account last name.

Attached is my trigger and class.

apex trigger 

Class
User-added image

Thank you
Marion
Hi All,

I am currently putting together an Apex script that would normalise all of the website addresses in our database by extracting the host addres and eliminating 'http', 'www' etc from the domain address. For this I am using a for loop. The problem that I am experiencing is that once the code runs (and it runs without errors and the debug produces the desired outcome) the website addresses don't get updated.

Here's the script so far:
public class Standardise_Websites {
    public Standardise_Websites(){
        list<Account> accts = [SELECT Website FROM Account];
               
        for (Account acct : accts){
            string website = acct.website;
            System.debug('Website is ---------->' +website);  
            website = website.replace('http://www.','');
            website = website.replace('https://www.','');
            website = website.replace('https://','');
            website = website.replace('http://','');
            website = website.replace('www.','');
            System.debug('Final website is ---------->' +website); 
            update acct;
            
        }
    update accts;
    }
}

               
    
I'm trying to update a custom field (Conversion_Type) from Lead to Contact, any ideas why it's not updating?
 
trigger LeadConvType on Lead (after insert) {     Map<Id,String> Conversion_Type = new Map<Id,String>(); // Map of the converted Contact ID and the Lead Status     for(Lead lead : Trigger.new) {         if (lead.IsConverted) {             Conversion_Type.put(lead.ConvertedContactId,lead.Conversion_Type__c);         }     }     List<Contact> conContacts = [select Id from Contact WHERE Contact.Id IN :Conversion_Type.keySet()];     for (Contact c : conContacts) {         c.Conversion_Type__c = Conversion_Type.get(c.Id);     }     update conContacts; }

 
Helllo,

I have a trigger and a test class in Sandbox PartielHRC.
the test coverage for trigger in Sandbox is around 80% but when i deploy it in Production it has 0%, i am not bale to find the reason

The following triggers have 0% code coverage. Each trigger must have at least 1% code coverage.

any sugggestions?
 
  • August 09, 2016
  • Like
  • 0
Can anybody help me solve this issue?
I want to check if the user selects duplicate value of the picklist when many records are displayed to edit and show the error message and stop if duplicate is found.
I wrote a apex method for the same. Now how to take the return value to check the condition to show the error message in javascript?
My apex method is :
public Integer getcheckDuplicate() {
       // RequestsList = new List<Reclassification_Request__c>();
        
        
        for(integer i=0 ; i<RequestsList.size();i++) {
             system.debug('Entering First For Loop');
            for( integer j=(i+1) ; j<RequestsList.size() ;j++) {
                Reclassification_Request__c reclassreqI = RequestsList.get(i);
                system.debug(reclassreqI);
                Reclassification_Request__c reclassreqJ = RequestsList.get(j);
                system.debug(reclassreqJ);
                if(reclassreqI.Request__c != 'Other') {
                    if(reclassreqI.Request__c == reclassreqJ.Request__c) {
                        system.debug('Duplicate Found');
                       // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Error:Priority may not be duplicated.'));         
                        ErrorCount =  ErrorCount+1; 
                                                 
                    } 
                }            
            }
        } 
        return ErrorCount;          
      }

I want the check the value of ErrorCount and show the error message. But the value is always 0. Why? Any help please...
I am trying to create a Closed Won amount custom formula field.  When the Stage = Closed Won, the fiield should display the Amount value if the 'Total Amount for Current FQ' is $.0.00 or 'Null' or the 'Total AMount for Current FQ' value. I am not sure how to write these formula. Here are the fields that would be in the formula:

StageName =  Closed Won
Total_Amount_for_Current_FQ__c
Amount

I appreciate the help!

Thanks!

System.QueryException: unexpected token: !=
Error is in expression '{!sear}' in component <apex:commandButton> in page listobjects: Class.listobjects.sear: line 57, column 1
Class.listobjects.sear: line 57, column 1

Please help me


public with sharing class listobjects {
    public String lisobj{get;set;}
    public String lisfields{get;set;}
    public string opira{get;set;}
    public String envalu{get;set;}
    public list<Sobject> accList{get;set;}
    public set<String> lisfiels{get;set;}
    public string query{get;set;}
    
    Public list<SelectOption> getobj(){
        List<SelectOption> opty=new List<SelectOption>();
        opty.add(new SelectOption('None','--none---'));
        opty.add(new selectoption('Account','Account'));
        opty.add(new selectoption('Lead','Lead'));
        opty.add(new selectoption('Contact','Contact'));
        opty.add(new selectoption('Opportunity','Opportunity'));
        opty.add(new selectoption('Reports','Reports'));
        opty.add(new selectoption('testA__c','testA__c'));
        return opty;
    }
    
    public listobjects(){
    
        lisfiels=new set<string>();
    }
    
    public list<SelectOption> getcall(){
    
        list<selectoption> losfils=new list<selectoption>();
        try{
            losfils.add(new SelectOption('None','--none---'));
            map<String,Schema.SObjectType> schemap = Schema.getGlobalDescribe();
            Schema.SObjectType ts=schemap.get(lisobj);
            Schema.DescribeSobjectResult dsobjresul=ts.getDescribe();
            Map<String,Schema.SObjectField> fildres=dsobjresul.Fields.getmap();
            for(Schema.SobjectField sts:fildres.values()){
                Schema.DescribeFieldResult dfc=sts.getDescribe();
                losfils.add(new SelectOption(dfc.getName(),dfc.getLabel()));
            }
        }catch(Exception e){}
        return losfils;
    }
    public list<Selectoption> getval(){
        list<Selectoption> opera=new list<Selectoption>();
        opera.add(new Selectoption('--None--','--None--'));
        opera.add(new Selectoption('%','Equal'));
        opera.add(new Selectoption('!=','NotEqual'));
        opera.add(new Selectoption('>:','Greaterthan'));
        return opera;
    }
    
    public void sear(){
        string query;
        Schema.SObjectType tt=Schema.getGlobalDescribe().get(lisobj);
                              
        query='Select id,Name from ' + tt   + 'where' + lisfields + '!=:' +envalu;
        list<Sobject> ss=database.query(query);
        system.debug('SSSSSSSSSSSSS'+query);
        
    }
    
}
<apex:page Controller="testctrl1">
    <apex:form >
    <apex:actionRegion >
        <apex:inputField value="{!updacc.Name}"/>
        <apex:inputField value="{!updacc.CustomerPriority__c}"/>
    </apex:actionRegion>
            <apex:commandButton action="{!customupdate}" value="Update" immediate="true"/>
    </apex:form>
</apex:page>



public class testctrl1{   
    public Account updacc{get; set;}
    public testctrl1() {
        updacc = [select Id, Name, CustomerPriority__c From Account where id = '001610000047HlW'];
    }
    public void customupdate(){
       update updacc;
    }
}

If the user change the input field value 'CustomerPriority__c' and click on Save. I need to update the record. How can I do that?

Thanks,
Vijay
how to send email to contact when a new case record is created using trigger?
Hello everyone,

When I am working with workflows, One question is roaming through my mind  i.e why don't we have time-dependent workflows actions when the evaluation criteria are "every time record is created and edited"


Thanks..........
  • February 03, 2016
  • Like
  • 1
I've been trough several posts / discussions but I'm still not clear on how do standard latitude and longitude fields on Account populate in Salesforce ? Do they automatically populate when I enter the account adress (it seems not...) ? Do I need to build a piece of code to retrive this data from Googe Maps (or oher provider) with an API ? Should I go for a specific geolocation app in the Appexchange ? The reason I need to populate this data is because I later need to export it and use it for account geolocation on a Website (store locator on Google Maps)
Many thanks for you advice !
 
Hi 
I am getting the below error.can any one suggest some solution
Aproblem with onclick  javascript for this button or link was encountered
this.style is null or not object.
Thanks
how to maintain the security level settings to different
departments[HR, Tech, Developer] which are not hierarchy.

I know there are many answers to the "too many" part of this question, and I understand the reason and the normally suggested solutions.  
But I believe I see this behavior change even running the same test on different occasions, i.e., with no code changes sometimes it will get this error, and sometimes not.

Does this seem possible?  Has anyone else experienced this?

And yes, I have (many times) tried most of the suggested solutions....  so this is more of a "is this really possible?" question.​
 

I have a very simple trigger to do an update to a field called CTS_Rep__c. It is on a custom object and the trigger updates the field from the account object. The code is below.
trigger TOR_Update_CTS_Rep on Trial_Order_Request__c (before update, before insert) {

    //This trigger updates the CTS_Rep__c field from the Account CTS_Rep__c Field.
    //The lookup to account is based on the TOR field called Consignee_Ship_To_Name__c.
    //Note: By using the "before" trigger to modify the Trigger.new objects, you don't need 
    // to explicitly perform an update DML statement. When the trigger ends, it will implicitly 
    // update the data as you have modified the values 

    For (Trial_Order_Request__c newTOR : Trigger.new)
    {
        Account acc = 
            [Select ID, CTS_Rep__c from Account Where ID =: newTOR.Consignee_Ship_To_Name__c Limit 1];
        newTOR.CTS_Rep__c = acc.CTS_Rep__c;
        System.debug('In Trigger new tor= ' + newTOR.CTS_Rep__c);              
    } //End for Loop
}  //End of trigger
The trigger works fine on inserts and updates but when I wrote my test and ran that I ran into some problems. I am not getting the CTS_Rep__c field filled in. The trigger does not seem to save the data. My test code is below.
@ISTest public class TOR_CTS_Rep_Test {

 testMethod private static void runtests(){
        //In order for this test to work the three users Finance, Test User, and SysAdmin
        //must be opened and saved in prod so agent will get those last modified!!!
        //Also, Finance user contact created must = true and marked as an inactive user. 
        //SysAdmin and Test User contact created field must = false and marked active.        
        
        //create users
        List<User> theusers = Create_Accts_Contacts_From_Users_Test.buildUsers();
        //Use user0 for the account owner
        User User0 = theusers[0];
     	//Use user2 for the CTS Rep
     	User User2 = theusers[2];
     
        //create Account
        Account testacct = NewObjFactory.buildTestAcct(0, 'ABC Company', User0.id);
     	testacct.CTS_Rep__c = user2.id;
     	System.debug('acct CTS Rep = ' + testacct.CTS_Rep__c);
        insert testacct;
     
  		String theTORID;
     Test.startTest();
        // Create the Trial Order Request to test the insert of a new TOR with CTS Rep
        Trial_Order_Request__c TOR = NewObjFactory.buildtestTOR(0, testacct.id);
     	insert TOR;
     	theTORID=TOR.id;
     Test.stopTest();
     
     System.debug('TOR CTS Rep = ' + TOR.CTS_Rep__c);
     	//check to see if cts rep was added
        Trial_Order_Request__c TOR1 = [Select id, name, CTS_Rep__c
                       from Trial_Order_Request__c where ID =: theTORID ];
     System.debug('TOR1                    = ' + TOR1.CTS_Rep__c);
     System.debug('TOR                     = ' + TOR.CTS_Rep__c);
     System.debug('TOR1 Name                    = ' + TOR1.Name);
     System.assertEquals(TOR1.CTS_Rep__c,TOR.CTS_Rep__c);
 } //End runtests
}  //End test
When I run debug does not show the CTS_Rep__c as having any data. Below is the debug log.
User-added image
As you can see by the debug log, the ID for the CTS_Rep__c  is null. It pulls the correct data in name field so I know on my select statement that I am getting the correct record but again the CTS_Rep__c is null. Can anyone explain to me what I am doing wrong and how to correct the problem. Thank you.
Hi, can we use javascript remoting without using visualforce page. I want to provide community login,forgot password, change password functionality  by using html and javscript only. anyone know how to do it??
<td>
                                <ui:inputcheckbox updateOn="change" change="{!c.SaveChanges}" text="{!item.Id}" value="{!item.CSopke1__Complete__c}"/>
                            </td>
                            <td>
                                <ui:inputDate  updateOn="change" change="{!c.searchChange}" value="{!item.CSopke1__Date__c}" displayDatePicker="true" />
                            </td>
                            <td>
                                <ui:inputText updateOn="change" change="{!c.searchChange}" value="{!item.CSopke1__Notes__c}"/>
                            </td>
Helper.js
SaveChanegHelper: function (cmp, event, helper) {
        var action = cmp.get('c.updateProcess');
        var processId = event.getSource().get("v.text");
        var iscompleted = event.getSource().get('v.value');
        var FieldLabel = ???
how I can get to know which field was changed so that I need to pass this fieldApi to further Apex controller toupdate record accordingly.
 
I have created an event monitoring app and can also delete it but I am unable to delete Event Monitoring App created by other users. what I did further is 
1. I made one creator as system administrator 
2. I have logged in with that creator.
3. Open Event Monitoring app created by that user.
4. Still I am not able to delete app. 
I have implemented a InlineEditing on a visualforce page. Issue that I am facing is if When user double click on any field, clear out field value and proceed to click on save then system shows expected error message to user which is exected because there is required validation for this field.
User-added image

when user click on undo icon and click on save still Error message appears.
User-added image
I deeply investigated and found that clicking on undo icon only shows it is reverting value but actually it does not properly revert value. so if user click on Save button Error occurs. Any Suggestion?


Thanks
Sandeep Singhal
We would like to get access token based on user name and password from Quickbook API in to salesforce apex class. 
Please provide bodyRequest structure , setheader 'Authorization' if possible. 
I have created a custom object with OWD private. Now I would like to sharing this record with a user X with 'Delete' permission.  What Accesslevel I need to use in order to create sharing record. 

Note: There is no Accesslevel called  'Delete'  exist. 
When I click on Account Tab it opens current window as nested is this feature or issue ?

User-added image
I am unable to delete some compoennts such Workflow,Rule, Field update, Email Alert & Approval process from production using DesctructiveChange.xml. It shows deployment succeeded. Any Idea why?

Although I am able to do it in my developer edition.
How can we generate EDI ( Electronic Data interchange) files of 270/271 format from apex. Any idea?
I need to generate ANSI files in apex. I could not find any useful api for this in apex itself.

Hi, 
I am integrating Salesforce with Linked in and getting below error while accessing linkedIn apis using accessToken. I am sure that access token is valid.
Here is my code 
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        string endPointValue = 'https://api.linkedin.com/v1/people/';
         //'https://api.linkedin.com/v1/people/~:(id,num-connections,picture-url)?format=json';//'https://api.linkedin.com/v1/people/~/shares?format=json';
        req.setendpoint(endPointValue );
        string bodyRequest = '{ "comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG", "visibility": {"code": "anyone"}}';
        req.setBody(bodyRequest);     
        System.debug(bodyRequest);
        req.setHeader('Authorization', 'Bearer ' + accessToken);
        req.setHeader('Content-length', string.ValueOf(bodyRequest.length())); 
        req.setHeader('Content-Type', 'application/json; charset=UTF-8');
        req.setMethod('GET');
        req.setTimeout(10000);
        HttpResponse res = h.send(req); 
        System.debug('===='+res.getBody());
Getting below Error: 
16:48:22.131 (1131126887)|CALLOUT_REQUEST|[46]|System.HttpRequest[Endpoint=https://api.linkedin.com/v1/people/, Method=GET] 16:48:22.958 (1958244094)|CALLOUT_RESPONSE|[46]|System.HttpResponse[Status=Method Not Allowed, StatusCode=405]
 
I have one junction Object "J" it is having primary Master Object Opportunity and secondary master Object "A" now when I go to detail page of "A" then Edit link of J's related list is not displaying but Del is displaying. but when I open this junction record separately I am able to see Edit and Delete both button.
Note: I have given CRUD permission to all users for this junction object "J". Please suggest what is te reason of this issue?
There is not java script applied to hide this in any home page component.
Hi All, 

I am facing the delivery failed parmanently error when I send any email to email address ( generated from Salesforce under an email service). It was working fine and it is not dependent to apex code we have written.
It is very strange that in my PRODUCTION and fullcopy sandbox when I go to any email Template folder and click on edit then I don't find option 
"This folder is accessible only by the following users" while it is coming in other sandboxes of that same production org. Any body has any idea ? it is very urgent.
I have a validation where I am comparing a rollup summary field ( sum of currency type field) with 0.00 but I am getting following error while evaluating validation rule on inserting record.
Here is Important blog for this 
http://www.codespokes.com/2014/02/quick-search-tool-for-apex.html
http://www.codespokes.com/2013/10/dmloption-usage-how-to-control-email.html
I need to migrate few items from UAT to PROD env using ANT tool so I need package.xml for below items.
1. Email Template
2. Field Updates
3. Email Alerts
4. Group
5. Queue
6. Approval Process

Note: Please do not use '*' sign because I need to migrate only few components not all.
I am using below link's code
http://salesforce.stackexchange.com/questions/14138/how-to-add-header-footer-in-vf-page-whose-content-type-is-word

Header and footer are getting displayed on each page of document as desired but my concern is that 
on converted word document Header's content displayed on first page and similarly footer's content displayed on last page why? and how to avoid it.

Recently a new option is added on VF Page compiler in salesforce what does it mean? 

<td>
                                <ui:inputcheckbox updateOn="change" change="{!c.SaveChanges}" text="{!item.Id}" value="{!item.CSopke1__Complete__c}"/>
                            </td>
                            <td>
                                <ui:inputDate  updateOn="change" change="{!c.searchChange}" value="{!item.CSopke1__Date__c}" displayDatePicker="true" />
                            </td>
                            <td>
                                <ui:inputText updateOn="change" change="{!c.searchChange}" value="{!item.CSopke1__Notes__c}"/>
                            </td>
Helper.js
SaveChanegHelper: function (cmp, event, helper) {
        var action = cmp.get('c.updateProcess');
        var processId = event.getSource().get("v.text");
        var iscompleted = event.getSource().get('v.value');
        var FieldLabel = ???
how I can get to know which field was changed so that I need to pass this fieldApi to further Apex controller toupdate record accordingly.
 
Actually using streaming api to display the changes on another user deatils page using Visual page.

Is it possible to display the changes or something using streaming API in home page or somewhere(if the user using or accessing the someother page in org).
 
Please help to achive my query. It would be greatly appreciated.


 
Hi all! I'm really new to apex code, trying to figure out how to get related records from Account. Any help is appreciated!

VF page:
<apex:page Controller="UseofRepeatOnEpudsController">
<apex:form >
    <apex:pageBlock title="Accounts with assoicated Contacts">
        <apex:repeat value="{!epudsList }" var="epd">
            <apex:pageBlockSection title="{!epd.name} - {!epd.Account1__r.Name}">
                <apex:pageBlockTable value="{!epudsList}" var="epd2">
                    <apex:column value="{!epd2.Absorbent_drum_1__c}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:repeat>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:
public class UseofRepeatOnEpudsController {
    public List<Logistic__c> epudsList{get;set;}
    public List<Account> AccountList{get;set;}
    public Id accId{get;set;}
    
    public UseofRepeatOnEpudsController() {
        accId = ApexPages.CurrentPage().getparameters().get('Id');
        epudsList = new List<Logistic__c>();
        epudsList = [SELECT id, Name ,  Account1__R.Name, Absorbent_drum_1__c From Logistic__c where Account1__c =:accId] ;
        accountList = [SELECT id, Name From Account];
    }

​Result:
I can't select VF page when setting up a button. My guess is that I need to use Standard controller="Account" and extention (My controller). I'm not sure how to set it correctly. Getting errors.

Also, epudsList is showing related custom object names which is fine, but PageBlockTable will show records not per custom object reocord - but all custom object records together.

So basically I'd like to press button on account and get related records separated. Accoont - > List of custom object records -> (Values related to one record)

Now its showing like: Account -> List of custom object records -> (Values related to multiple records) which is wrong.

Thanks for helping me out!
I created the following class that updates the Websites field after a new website is added. It basically normalises it by removing 'http://', 'https://', and 'www'.

Here's the class:
 
trigger standardiseWebsitesTrigger on Account (after insert, after update ) {
    if(checkRecursive.runOnce()){
        
        Set<Id> AccIds = new Set<Id>();
        
        List<Account> acctsToUpdate = new List<Account>{};
            
            
            for (Account acc : Trigger.new){
                AccIds.add(acc.Id);
            }
        
        List<Account> accounts = [SELECT Id, Website FROM Account WHERE Id IN :AccIds];
        
        for (Account acc : accounts){
            string website = acc.Website;
            string hostDomain1 = 'http://';
            string hostDomain2 = 'https://';
            string justWWWAddress = 'www';       
            
            if (acc.Website.startsWith(hostDomain1) || acc.Website.startsWith(hostDomain2) && acctsToUpdate.isEmpty()){
                Url u = new Url(acc.Website);
                website = u.GetHost();
                acc.Website = u.getHost().replaceFirst('^(https?://www\\.|https?://|www\\.)','');
                acctsToUpdate.add(acc);
                
            }
            
            if(acc.Website.startsWith(justWWWAddress) && acctsToUpdate.isEmpty()){
                acc.website = website.substring(4);
                acctsToUpdate.add(acc);
                
            }
            
            update acctsToUpdate; 
            
        }
    }
    
    }

However when using the following test the assertion relating to removing the 'www.' component fails:
   
@isTest
    public class standardiseWebsitesTriggerTest {

    static testmethod void standardiseWebsiteTriggerHTTP() {
        testSetup('HTTP', 'http://I_AM_HTTP', true);
    }

    static testmethod void standardiseWebsitesTriggerWWW() {
        testSetup('WWW', 'WWW.I_AM_WWW', false);
    }

    public static void testSetup(String accName, String accWebsite, Boolean webProtocol) {
        Account acc = new Account(
            Name = accName,
            Website = accWebsite
        );
        insert acc;

        Account updatedAccount = [select Website from Account where id = :acc.Id];
        
        if(webProtocol) {
            Url u = new Url(acc.Website);
            System.assert(u.getHost() == updatedAccount.Website);
        } else {
            System.assert(updatedAccount.Website == acc.Website.substring(4));
        }
    }
    }

The error is:
 
>    Assertion failed
Class.standardiseWebsitesTriggerTest.testSetup: line 25, column 1
Class.standardiseWebsitesTriggerTest.standardiseWebsitesTriggerWWW: line 9, column 1

Any idea as to why this test may be failing?




 
Hello,

When i was deploying apex class with the profile i get below error on on of the profile "XYZ" like below:
Unknown user permission: LightningConsoleAllowedForUser
thanks for suggestion !
 
  • May 30, 2017
  • Like
  • 0

I have two record types  A and B on case object

Now I want to display cases on related list of account page in the form of  two pageblock tables
1st pageblock table should be cases with record type A
2nd pageblock table should be  cases with record type B

 
Hi Friends,
I read in apex developer guide we can't deploy the email service address name. Can  any one help me how we deploy the email service address name?
Thank you
Hi. I am trying to use actionPoller to fetch data updated through a @future call (just the field being updated asyncronously, Future_Date__c), but it seems that the data in the StandardController is stuck in the original value, even though the fetch date is changed. Do you know how to trigger the standard controller to get the new data and refresh that part of the view?
<apex:page standardController="Case" cache="false" >
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:outputPanel id="blockToRerender" >
                <apex:form >
                    <apex:outputLabel value="Future Date: " />
                    <apex:actionStatus id="counterStatus" startText="Fetching…" stopText="Done!" rendered="{!ISBLANK(Case.Future_Date__c)}" />
                    <apex:outputText value="{!Case.Future_Date__c}" />
                    <br/><br/>
                    <apex:outputLabel value="Fetch Date: " />
                    <apex:outputText value="{!Now()}" />
                    <apex:actionPoller oncomplete="refreshJS();" interval="5" status="counterStatus" enabled="{!ISBLANK(Case.Future_Date__c)}" />
                    <apex:actionFunction name="refreshJS" reRender="blockToRerender" /> 
                </apex:form>
            </apex:outputPanel>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

 
Hello,

I'm very new to apex coding. I was informed that the proper way of creating trigger is to create a trigger then call apex class methods. Is that right?

I tried it on my end with a very simple trigger but I can't make it work.
Basically, what I want is that when I create Account, it will automatically create a Contact under the Account with Account is equal to Account id and contact last name is equal to account last name.

Attached is my trigger and class.

apex trigger 

Class
User-added image

Thank you
Marion
Hi All,

I am currently putting together an Apex script that would normalise all of the website addresses in our database by extracting the host addres and eliminating 'http', 'www' etc from the domain address. For this I am using a for loop. The problem that I am experiencing is that once the code runs (and it runs without errors and the debug produces the desired outcome) the website addresses don't get updated.

Here's the script so far:
public class Standardise_Websites {
    public Standardise_Websites(){
        list<Account> accts = [SELECT Website FROM Account];
               
        for (Account acct : accts){
            string website = acct.website;
            System.debug('Website is ---------->' +website);  
            website = website.replace('http://www.','');
            website = website.replace('https://www.','');
            website = website.replace('https://','');
            website = website.replace('http://','');
            website = website.replace('www.','');
            System.debug('Final website is ---------->' +website); 
            update acct;
            
        }
    update accts;
    }
}

               
    
Hi -

I am trying to navigate to a visual force page, while passing parameters through the URL. Here is what it is without javascript, using the Display in existing window without sidebar or header via URL option.
/apex/QuoteRequestDetailsPage?OpportunitySegmentId={!Opportunity_Segment__c.Id}

I'd like to put this into javascript and add criteria on WHEN we allow people to navigate to this visual force page.

Here's my best try but i'm getting an error:

string url = "/apex/RFPDetailsPage?OpportunitySegmentId="+{!Opportunity_Segment__c.Id}+"&
OpportunityId="+{!Opportunity_Segment__c.Opportunity_ID__c};

window.location.href=url;

 
Hi there!

I've been locked out of another Dev org of which I am the sole administrator. My org ID is 00D46000000YtOt and my username is jstone@visualantidote.com. If I can verify my identity, could I be granted access once again, please?
I have a process that based on checkboxes on the Account object when the Account is created, it will create a child account for the Parent account being created.  This will usually be done during the lead conversion process where the Account gets created and based on the checkboxes selected on the lead the approprate Child Accounts will be created.  Now here is my question.....When the lead conversion is successful and the opportunity is created for the parent account, I would like a trigger to based on the two check boxes on the Parent account (Anywhere or Complete) to create an Opportunity using the same field data from the opp created by the lead conversion for each child account created with a small tweak to the name field and re-pointing the Account ID on the new child opps to point to thier correct Child account again base don the proper checkbox selected and the trigger process.   Can this happen?   If so, can you give me a head start as I woudl like to get this automated and I know we can do this, but I have no idea. 

Please be my saving hero!!!!

Thanks in advance,

Shawn
Hi,

I want to call a Lightning Component event from a Visualforce page in a Community.

I've tried in this way
 
<div id="lightning" style=""></div>

<script>
$Lightning.use("c:TheApp", function() {
	$Lightning.createComponent("c:TheComponent", {},
		"lightning",
		function(cmp) {
			createdCmp = cmp;
			var myExternalEvent;
			myExternalEvent = $A.get("e.c:TheEvent");
			myExternalEvent.setParams({
				"p": 'p',
			});
		myExternalEvent.fire();
	});
});
</script>
It's working but it is not what I exactly want, because in this way the compnent is inserted in the page a runtime.

Is there a way to call the event without inserting the component a runtime, but inserting it in the page with the community builder ?

Thanks in advance.
Hi,
Is there a way I can change the VF page title with the value of item selected in the Lightning component included in the page? 

There is a dropdown in the lightning component and the selected value of the lightning dropdown menu must be reflected in the VF page title.

Thanks in advance,
Binaayo
I'm unable to get data in Kanban view on my custom objects. I  get the Kanban setting window and on save the same setting window reappears. How can I address this issue?
  • April 26, 2017
  • Like
  • 1

Hello,

InlineEditing allows us to show and hide buttons during and after editing inline.  However buttons I want hidden by default are displayed.

 

For instance, I have several buttons I want to show by default and hide when editing, plus a Save and Cancel button that I want hidden unless told to display by inline editing.  But when the page loads all of these buttons are displayed.  How am I supposed to make Save and Cancel hidden on page load, surely I dont have to use JS or CSS for that, it must be part of the inline editing capability surely?!

 

 

MORE INFO: Im not using a standard controller everything in the page is handled in a class.  Clicking the Save button (which calls a save method which updates the database, as you'd expect) doesnt save any changes made in inline editing.

I'm starting to think that inline editing will only work with a Standard Controller...

Hi,
in the Winter'09 release notes it says "Custom labels are custom text values, up to 1,000 characters in length, that can be accessed from Apex classes or Visualforce pages".
I could easily find how to access these labels from a visualforce page, but nowhere I can find how to access them from an apex class.
I need this because I have a class that dynamically generates labels for a certain table in a vf page. But I want to use Custom Labels (and the translation workbench) to get these translated in various languages.
Is there an object, something like Label with a static function like 'getLabel(String)'? Or is this not released in Winter '09?
  • September 30, 2008
  • Like
  • 0
I have something like this for a nice Title to my pageblock:

<apex:pageBlock id="appPageBlock" title="Application for : {!application.FirstName__c} {!application.MiddleName__c} {!application.LastName__c}">  

with some buttons like this one:
 <apex:pageBlockButtons>
            <apex:commandButton value="Save and Continue" style="...">
</apex:pageBlockButtons>
 
The only way i can change the font color on the Title is to use a facet for "header". However, when i do this, i lose my buttons....they just disappear.

Anyone have a trick as to how to change the font color without losing my buttons?
(I ONLY want to change the font color for my Title...nothing else on the page)

Thank you!

Hi everyone,

Does anyone know the different badges that can be achieved by contributing to this forum (newbie, smartie, etc) and how many points match each level?

Regards,
Fred
 

Today we’re excited to announce the new Salesforce Developers Discussion Forums. We’ve listened to your feedback on how we can improve the forums.  With Chatter Answers, built on the Salesforce1 Platform, we were able to implement an entirely new experience, integrated with the rest of the Salesforce Developers site.  By the way, it’s also mobile-friendly.

We’ve migrated all the existing data, including user accounts. You can use the same Salesforce account you’ve always used to login right away.  You’ll also have a great new user profile page that will highlight your community activity.  Kudos have been replaced by “liking” a post instead and you’ll now be able to filter solved vs unsolved posts.

This is, of course, only the beginning  and because it’s built on the Salesforce1 Platform, we’re going to be able to bring you more features faster than ever before.  Be sure to share any feedback, ideas, or questions you have on this forum post.

Hats off to our development team who has been working tirelessly over the past few months to bring this new experience to our community. And thanks to each of you for helping to build one of the most vibrant and collaborative developer communities ever.
 

Hi All,

during my work with apex, I had issue with searching data in maps of maps of maps... or combinations in lists. Sometimes I want to run a debug log and I want to see all values in fields. Salesforce put debug log into long string only, so it's hard to read. After time, I desided to create a new tool, which parse salesforce log into nice format for easy reading. Try it, and say if you like it. Feel free to request some improvements and ideas for implementing

 

 

http://www.cassacloud.com/nice-salesforce-debug/

 

enjoy!

 

PS: if you do not have any debug try this one:

16:55:49:253 USER_DEBUG [59]|DEBUG|{Best Case=(), Closed=(OppInfoTotal:[OppCategory=Closed, OppId=MyId, OppName=TestOPP1, OppProjectType=null, OppV2Practice=null, sumTotals=(sumQuarterRow:[RevenueType=Deposit, SumOfRow=null, month1=1.0, month2=0, month3=3.6], sumQuarterRow:[RevenueType=Milestone, SumOfRow=null, month1=3.0, month2=0, month3=0])]), Commit=(OppInfoTotal:[OppCategory=Commit, OppId=myId, OppName=TestOPP2, OppProjectType=null, OppV2Practice=null, sumTotals=(sumQuarterRow:[RevenueType=Final, SumOfRow=null, month1=1.0, month2=2.5, month3=1.9])]), Pipeline=()}

 

When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.  

 

That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it.