+ Start a Discussion
Arun ChaubeyArun Chaubey 
create an Apex class that inserts a new account named after an incoming parameter. If the account is successfully inserted, the method should return the account record. If a DML exception occurs, the method should return null?
The Apex class must be called 'AccountHandler' and be in the public scope.
The Apex class must have a public static method called 'insertNewAccount'.
The 'insertNewAccount' method must accept an incoming string as a parameter, name the account after the parameter, insert it into the system and then return the account record.
The 'insertNewAccount' method must also accept an empty string, catch the failed DML and return null.
Best Answer chosen by Arun Chaubey
NagaNaga (Salesforce Developers) 
Hi Arun,

Can you please let me know if the code below helps you


public class AccountHandler {
public static Account insertNewAccount(String name) {
Account a = new Account();
a.Name = name;
try
{
insert a;
} catch (Exception e) {
return null;
}
return a;
}
}
This method takes name string parameter and makes a new Account. Then it tries to insert it, but if insert fails then it returns null. If insert succeeds, it will return that account object.

Best Regards
Naga Kiran
 
Arundhati DebArundhati Deb 
Hi

I have a scenario where the account currency and opportunity currency can be different. The opportunity currency should be the same as opportunity owner currency. I have to write a trigger for it. Can anyone help me with it.
Highly appreciated.
Best Answer chosen by Arundhati Deb
Abdul KhatriAbdul Khatri
@Arundhati

I see some issues with your code so here is your code with some corrections.
 
public static void Opportunitycurrency (List<Opportunity> newOptyList) {
        
        List<Id> oppOwnerIds = new List<Id>();
        for(Opportunity opp: newOptyList)
        {
            if(opp.OwnerId != null)
            {  
                oppOwnerIds.add(opp.OwnerId); 
            }
        }
        
        Map<Id, User> userList = new Map<Id, User>([SELECT Id, Name, CurrencyIsoCode FROM User WHERE Id IN :oppOwnerIds]);
        
        for(Opportunity opp: newOptyList)
        {
            if(opp.type != 'Renewal')
            {
                opp.currencyisocode=userList.get(opp.OwnerId).currencyisocode;
            }
        }
    }

 
Anil Rao 17Anil Rao 17 
I have added few custom fields in the OP Object. When I look at a O, I want to view the custom fields in the OP associated to a O.

I get a list of the Products in the O page & when I click the link for the Product, it takes me to the Product page & there is no way that I amable to see the OP Records.

How can I see a list of all OP records associated to a O from the O Page?
 
Best Answer chosen by Anil Rao 17
Anil Rao 17Anil Rao 17
I was able to get this. I just had to change the page layout to add the desired columns
Nikhil kanth NayaniNikhil kanth Nayani 
Hi All,

Based on the Lead status I am trying to update the lead owner to a queue using the process builder. When my process builder has been pushed to different org I am getting error as below.
Error: The flow tried to update these records: null. This error occurred: INVALID_CROSS_REFERENCE_KEY: invalid cross reference id.

My Action field update is Lead owner(field) Queue(Type) xxx_Queue(Value)

 
Best Answer chosen by Nikhil kanth Nayani
Doug YoungerDoug Younger
I ran into a similar issue when deploying a process that posts to a chatter group. What seems to be happening is when you develop the process in a sandbox you are providing the name of the group or queue and the process builder links it to the internal ID behind the scenes. Unfortunately the IDs are typically different in your dev org and production org.

To fix this, after you deploy, you will need to modify the process (clone) in the production org and re-link the queue by name in the prod org so it gets the proper ID. When you activate the cloned version, it should work as expected.
nishwalnishwal 

 If @isTest(SeeAllData=false) working for anyone?

I have annotated the class as well as the method but the testmethod can see the existing data.

Here is simple code snippet. Assertion is getting failed for me...

@isTest(SeeAllData=false)
private class testAnnotationSeeAllData {

static testmethod void myUnitTest()
{
Test.startTest();
List<User> lstUsers = [Select Id, Name From User Where IsActive= true Limit 100];
System.assert(lstUsers.size() == 0);
Test.stopTest();
}
}

tried in api version 24 and 25 both. and Developer Org and Sandbox.


is there anyone who is experiencing the same problem?

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Users aren't considered data for this purpose.  The following doc page:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_data_access.htm

 

details which data will still be visible to your test - user is on that list.

imishraimishra 

Hi,

 

I want to autopopulate custom field values while converting lead to account, contact and opportunity.

I tried to map the lead fields, but is is getting mapped for only single object account or contact or opportunity.

 

Please let me know how i can populate the field values for all the three.

 

 

Thanks in advance.

Best Answer chosen by Admin (Salesforce Developers) 
imishraimishra

trigger LeadConvert on Lead (after update) {

  // no bulk processing; will only run from the UI
  if (Trigger.new.size() == 1) {

    if (Trigger.old[0].isConverted == false && Trigger.new[0].isConverted == true) {

      // if a new account was created
      if (Trigger.new[0].ConvertedAccountId != null) {

        // update the converted account with some text from the lead
        Account a = [Select a.Id, a.Type_of_Contact__c, a.Region__c,a.Country__c From Account a Where a.Id = :Trigger.new[0].ConvertedAccountId];
        a.Type_of_Contact__c = Trigger.new[0].Type_of_Contact__c;
        a.Please_specify_if_other__c = Trigger.new[0].Other__c;
        a.Region__c = Trigger.new[0].Region__c;
        a.Country__c = Trigger.new[0].Country__c;
        update a;

      }         

      // if a new contact was created
      if (Trigger.new[0].ConvertedContactId != null) {

        // update the converted contact with some text from the lead
        Contact c = [Select c.Id, c.Type_of_Contact__c, c.Region__c,c.Country__c From Contact c Where c.Id = :Trigger.new[0].ConvertedContactId];
        c.Type_of_Contact__c = Trigger.new[0].Type_of_Contact__c;
        c.Please_specify_if_other__c = Trigger.new[0].Other__c;       
        c.Region__c = Trigger.new[0].Region__c;
        c.Country__c = Trigger.new[0].Country__c;       
        update c;
      
        
      }

      // if a new opportunity was created
      if (Trigger.new[0].ConvertedOpportunityId != null) {

        // update the converted opportunity with some text from the lead
        Opportunity o = [Select o.Id, o.Opportunity__c,o.Region__c,o.Country__c from Opportunity o Where o.Id = :Trigger.new[0].ConvertedOpportunityId];
        o.Opportunity__c = Trigger.new[0].Type_of_Contact__c;
        o.Please_Speci_if_other__c = Trigger.new[0].Other__c;       
        o.Region__c = Trigger.new[0].Region__c;
        o.Country__c = Trigger.new[0].Country__c;       
        update o;

       
      }        

    }

  }    

}

Harry Smith 5Harry Smith 5 
Hi all,

I have a question - I created a object that will process new starters in our company and automatically created a user based on the new form.

I also need to send an email to certain people automatically once the form is filled in and created. I need any suggestions or instructions to do this, all will be greatly appreciated.
Best Answer chosen by Harry Smith 5
Murali MattaMurali Matta
Hi Harry,

You can Create a Workflow Rule 

1.  Select the Evaluation Criteria as "Created"
 User-added image

2. Make the Rule Criteria as "your object 18 - Character ID" does not contain Null 
User-added image

3. After saving select the Email Alert in the Workflow Rule.
User-added image

You can select the users  and select the Email Template.


Thanks,
Murali
Sindhu VmSindhu Vm 
Hi, I created a VF page and loaded Google GeoChart with static data and it worked fine. But then I wrote a controller to query the db as AggerateResult. Now my map does not work when I loop though the AggregateResult in VF page to populate the data for GeoChart.

I’m new to coding and not sure if I’m referencing the Aggregate Result properly in Vuisualforce page. Please help.

Here is the apex code:
public with sharing class testCon 
{
    Public AggregateResult[] myData{get; set;}
    Public Integer Count{get; set;}
   
    Public testCon()
    {     
       myData = [SELECT Collateral_State__c  State, Count(Name) NbrOfCollaterals FROM 
                        Collateral__c where Overall_Status__c = 'Active' and                                                              Collateral_State__c != null group by Collateral_State__c ];
       Count = Integer.valueOf(myData.size());
    }
  
    Public AggregateResult[] getmyData()
    {
       return myData;
    }
}

Here is the VF code:
<apex:page controller="testCon" readOnly="true">
    <apex:includeScript value="https://www.gstatic.com/charts/loader.js" />
    <apex:includeScript value="https://www.google.com/jsapi" />
    
    <script type="text/javascript">
        google.charts.load('current', {
        'packages':['geochart'],'mapsApiKey': 'MyKey'
      });
       
        var cnt = {!Count};
       
         google.charts.setOnLoadCallback(drawRegionsMap);
   
        function drawRegionsMap() {
   
            
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'State');
            data.addColumn('number', 'Number of Collaterals');
            
            data.addRow(['Illinois',1]); // Just a sample static data for illustration
           
            for(AggregateResult rs : {!myData})
            {
                data.addRow([rs.State,rs.NbrOfCollaterals]);
            }
            
            var options = {
            region: 'US',
            displayMode: 'markers',
            backgroundColor: '#75a3e7',
            datalessRegionColor: '#f2f2f2',
            colorAxis: {colors: ['green', 'blue']
      
            }
      };

  
     //Getting the GeoChart Div Container
       var chart = new 
       google.visualization.GeoChart(document.getElementById('chart_div'));
 
     //Drawing the GeoChart with Data and Options
       chart.draw(data, options);
  }
   
   </script>
   <div id="chart_div" style="width: 900px; height: 500px;"></div>
</apex:page>

The part of the VF code which is an issue is:
 
for(AggregateResult rs : {!myData})
 {
        data.addRow([rs.State,rs.NbrOfCollaterals]);
 }

 
Best Answer chosen by Sindhu Vm
karthikeyan perumalkarthikeyan perumal
Hello 

Try below Code.  that javascript looping is not the issue.  from controller to VF page MYDate was not parsing correctly.  here is the complate code. 

Class
public with sharing class testCon 
{
   Public AggregateResult[] myData{get; set;}
   public  Map<String,Integer > FinalData {get;set;}
   public String JsonMap{get;set;}  
     
    Public Integer Count{get; set;}
   
    Public testCon()
    { 
        FinalData= new Map<String,Integer >();
       myData = [SELECT Collateral_State__c  State, Count(Name) NbrOfCollaterals FROM 
                        Collateral__c where Overall_Status__c = 'Active' and                                                              Collateral_State__c != null group by Collateral_State__c ];
       Count = Integer.valueOf(myData.size());
       
       for ( AggregateResult ar : myData)
       {
         
        FinalData.put(string.valueof(ar.get('State')),integer.Valueof(ar.get('NbrOfCollaterals')));
         
                
       }
       
        JsonMap=JSON.serialize(FinalData); 
       
        
    }
  
     
}

VF page :
 
<apex:page controller="testCon" readOnly="true">
    <apex:includeScript value="https://www.gstatic.com/charts/loader.js" />
    <apex:includeScript value="https://www.google.com/jsapi" />
    
    <script type="text/javascript">
    
        google.charts.load('current', {'packages':['geochart'],'mapsApiKey': 'MyKey' });
       
        var cnt = {!Count};
       
         google.charts.setOnLoadCallback(drawRegionsMap);
         
        function drawRegionsMap() {
     
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'State');
            data.addColumn('number', 'Number of Collaterals');
            
            data.addRow(['Illinois',1]); // Just a sample static data for illustration
            
              
            var DataMap= JSON.parse('{!JsonMap}');
            
            alert(DataMap);
            
            for (var key in DataMap) {
           if (DataMap.hasOwnProperty(key)) {
           
           alert(key + " -> " + DataMap[key]);
           
           data.addRow([key ,DataMap[key]]);
           
           }
        }
           
            var options = {
            region: 'US',
            displayMode: 'markers',
            backgroundColor: '#75a3e7',
            datalessRegionColor: '#f2f2f2',
            colorAxis: {colors: ['green', 'blue']
      
            }
      };

       //Getting the GeoChart Div Container
       var chart = new 
       google.visualization.GeoChart(document.getElementById('chart_div'));
 
     //Drawing the GeoChart with Data and Options
       chart.draw(data, options);
  }
   
   </script>
   <div id="chart_div" style="width: 900px; height: 500px;"></div>
</apex:page>

NOTE: Remove alerts after you finished testing. 

Hope this will works for you.

Thanks
karthik
 
PACO_DPACO_D 
I am trying to save this component
<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable" access="global" >
    <c:auraMethod aura:id="child" />
    <aura:handler event="c:formsubmit" action="{!c.onFormSubmit}"/>
    
    
    
    <lightning:layout VerticalAlign="center">
        <lightning:layoutItem padding="around-small">
            <c:BoatSearchForm /> 
        </lightning:layoutItem>
    </lightning:layout>
    <lightning:layout VerticalAlign="center">
        <lightning:layoutItem padding="around-small">
            <c:BoatSearchResults />
        </lightning:layoutItem>
    </lightning:layout>
</aura:component>

 i have the error "No COMPONENT named markup://c:auraMethod found"

have you face this issue ?
 
Best Answer chosen by PACO_D
Manish  ChoudhariManish Choudhari
Hi Paco,

You are getting this error as there is no custom component named "auraMethod" in your org. If you do have this custom component, can you please paste the code here or may be give me more details about the scenario.

What I believe is you are trying to access standard aura method syntax, in that case please remove <c:auraMethod aura:id="child" /> line and use <aura:method , example code below:
 
<aura:method name="sampleMethod" action="{!c.doAction}" 
  description="Sample method with parameters"> 
    <aura:attribute name="param1" type="String" default="parameter 1"/> 
    <aura:attribute name="param2" type="Object" /> 
</aura:method>


More on <aura:method /> tag:  https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/ref_tag_method.htm


Please let me know if this answers your question and if you need further help on this.

Thanks,
Manish
Luciano RobertoLuciano Roberto 

Good Morning folks,

I have a component to inset case, but is experiencing an error of  log:
 

"first error: INVALID_FIELD, Cannot specify both an external ID reference Account and a salesforce id, AccountId: []"


Basically this code :
 

Component.cmp

 <aura:attribute name="caseObj" type="case" default="{'sobjectType': 'Case',
                         'AccountId': '',
                         'MSISDN__c': '',
                         'Status': ''
                    }"/>



<label>Montadora</label>
       <force:inputField aura:id="AccountId"  value="{!v.caseObj.AccountId}"/>
           
</div>
<div class="form-group">
            <label>MSISDN</label>
            <ui:inputText class="form-control" value="{!v.caseObj.MSISDN__c}"/>
</div>  
    
    
    <div class="form-group">
            <label>Status</label>
            <force:inputField aura:id="Status"  value="{!v.caseObj.Status}"/>
</div>   


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

controller.js

  create: function(component, event, helper)    {
        
        console.log('Create record');
    
        var caseObj = component.get("v.caseObj");
        
        
        var action = component.get("c.createRecord");
      
        
        action.setParams({
            caseObj : caseObj
        });



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

Class.apxc

 @AuraEnabled
    public static void createRecord (Case caseObj){
        
        try{
            System.debug('NovoCasoComponentController::createRecord::caseObj'+ caseObj);
            
            if(caseObj != null){
                insert caseObj;
            }
            
        } catch (Exception ex){
            
        }
        
    }    




Thanks

Best Answer chosen by Luciano Roberto
Khan AnasKhan Anas (Salesforce Developers) 
Hi Luciano,

Greetings to you!

Just add below line before inserting the Case in the Apex method.
 
caseObj.Account = null;

You can see in debug logs, it is already having AccountId in it, I nullified Account from the caseObj.

So, change your Apex method to:
@AuraEnabled
    public static void createRecord (Case caseObj){
        
        try{
            System.debug('NovoCasoComponentController::createRecord::caseObj'+ caseObj);
            
            if(caseObj != null){
                caseObj.Account = null;
                insert caseObj;
            }
            
        } catch (Exception ex){
            
        }
        
    }

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