• karthikeyan perumal
  • PRO
  • 3506 Points
  • Member since 2015

  • Chatter
    Feed
  • 99
    Best Answers
  • 0
    Likes Received
  • 4
    Likes Given
  • 1
    Questions
  • 632
    Replies
I'm creating a visualforce page that displays data for confirmation when changes are made to a record and I wanted an email to be triggered when the changes are confirmed/ submitted. I added a picklist to the object and reference it in the page using

<td><apex:inputField value="{!RMA__c.Changes_have_been_review__c}"/>        
            </td>

It shows up fine and has the values from the picklist field but whenever you select your value and hit submit it doesn't update the objects field. 

Any help would be appreciated.

-Tyler
I am using equals and hashcode methods. I am unable to include hashcode method in test class.
public class WrapperClassWrapperClass
{
    public string lastName;
    public string email;
    public string phone;
    public string company;
    public string ownerid;
    public WrapperClassWrapperClass(string leadName , string leadEmail, string leadphone , string leadcompany, string leadOwnerId){
            this.lastName = leadName != null ? leadName:null;
            this.email = leadEmail !=null ? leadEmail:null;
        	this.phone = leadphone != null ? leadphone:null;
        	this.company = leadcompany != null ? leadcompany:null;
        	this.ownerid = leadOwnerId != null ? leadOwnerId:null;
        }
    public Boolean equals(Object obj) {
        if (obj instanceof WrapperClassWrapperClass) {
            WrapperClassWrapperClass p = (WrapperClassWrapperClass)obj;
            return ((((lastName==p.lastName) && (email==p.email) && (phone==p.phone) && (company==p.company))||
                    (((lastName==p.lastName) &&  (company==p.company)) &&
                     ((email==p.email) || (phone==p.phone))))&& ownerid==p.ownerid);
        }
        return false;
    }
    public Integer hashCode() {
        return !test.isRunningTest() ? (1 * (lastName.hashCode() + phone.hashCode() + company.hashCode() + ownerid.hashCode())) ^ email.hashCode() : 123456;     
    }
}

I am calling using this wrapper class in a trigger.
 
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]);
 }

 
what settings can be transferred threw metadata api
          web to case 
          web to lead
          case settings
          lead conversion
Please let me know the answer for the above question?
<!-- Subscription Table -->
<div class="slds-scrollable_y" style="height: 30rem;">
	<table class="slds-table slds-table_bordered">
		<tbody>
			<aura:iteration items="{!v.subscriptions}" var="sub">
				<tr class="slds-hint-parent">
					<td>
						<div class="slds-grid">
							<div class="slds-col slds-size_1-of-8 slds-p-left_small" ondblclick="{!c.editOn}">
								<aura:if isTrue="{!v.edit}">
									<ui:inputCheckbox value="{!sub.subscribed}"/>
									<aura:set attribute="else">
										<ui:outputCheckbox value="{!sub.subscribed}"/>
									</aura:set>
								</aura:if>
							</div>
							<div class="slds-col slds-size_7-of-8 slds-text-align_left slds-has-flexi-truncate">
								<p class="slds-truncate" title="{!sub.productName}">
									{!sub.productName}
								</p>
							</div>
						</div>
					</td>
				</tr>
			</aura:iteration>
		</tbody>
	</table>
</div>
<!-- Subscription Table -->
User-added image
I'm developing a component that allows users to mass subscribe customers to Product email alerts. I want the listed product names to truncate once the length reaches the width of the component. However, the names are currently extending past the component and not truncating as expected. I've attached the portion of my markup in question and the resulting component. Any and all help is appreciated.

Thanks
Hi,
I'm trying to test a class wher I get current User Ip
@AuraEnabled    
public static String GetUserIPAddress() {
string ReturnValue = Auth.SessionManagement.getCurrentSession().get('SourceIp');

return ReturnValue;
} // GetUserIPAddress



Test class:

 public static testmethod void Test1()
 {System.runAs(new User(Id = UserInfo.getUserId())){
     
     String ip = siteLeadForm.GetUserIPAddress();}
       
        

    }

In sandbox it is ok, but in production I receive this error:
System.UnexpectedException: Current session unavailable 
Stack Trace: Class.Auth.SessionManagement.getCurrentSession: line 5, column 1 Class.siteLeadForm.GetUserIPAddress: line 18, column 1 Class.siteLeadFormTEST.Test1: line 17, column 1


Any Ideas?
thankyou in advance

Hi guys, I'm wondering of how I am going to write a Test Class for Apex Class and a Trigger. This is just a simple Class and a Trigger please see below exact codes I am using.

trigger LeadUpdateListener on Lead (after update) {

    for ( Lead updatedLead : Trigger.New ) {
        CalloutExternal.pipelineConnect(updatedLead.Id);
	}
    
}
public class CalloutExternal {

    @future(callout=true)
    
    public static void pipelineConnect (String id) {
        
        String token = 'xxxxxxxxx';
        
        HttpRequest request = new HttpRequest();
        String endpoint = 'https://xxx.xxxxxxx.com/trigger/'+ token + '/' + id;
        request.setEndpoint(endpoint);
        request.setMethod('GET');
               
        HttpResponse response = new HTTP().send(request);
        
        System.debug('xxxx Response...' + response);
    }

}
I tried creating a Test Class but it doesn't let me through. If anyone who could show me here that would be much appreciated. Thank you!
global class CsvFileExporter implements System.Schedulable {
   global void execute(SchedulableContext sc) {
List<Account> accList = [Select Id,Name, AccountNumber, Industry, CreatedDate,LastModifiedDate,Phone from Account where CreatedDate=TODAY];
       List<Account> latestModiaccList = [Select Id,Name, AccountNumber, Industry, CreatedDate,LastModifiedDate,Phone from Account where LastModifiedDate=TODAY AND CreatedDate !=TODAY];

       String header = '\bAccounts inserted Today\b\r\n'+ '\bId, Name, Account Number, Industry,Phone\b\r\n';
       String header1 ='\r\n\bAccounts Modified Today\b\r\n'+ '\bId, Name, Account Number, Industry,Phone\b\r\n';
String generatedCSVFile = header+'';
List<String> queryFields = new List<String>{'Id','Name','AccountNumber','Industry','Phone'};
       String fileRow = '';
for(Account a: accList){            
fileRow = '';
fileRow = fileRow +','+ a.Id;
fileRow = fileRow +','+ a.Name;
       fileRow = fileRow +','+ a.AccountNumber;
fileRow = fileRow +','+ a.Industry;
       fileRow = fileRow +','+ a.Phone;
fileRow = fileRow.replaceFirst(',','');
generatedCSVFile = generatedCSVFile + fileRow + '\n';
}
       generatedCSVFile = generatedCSVFile+header1+'';
       for(Account ac: latestModiaccList){
fileRow = fileRow +','+ ac.Id;
fileRow = fileRow +','+ ac.Name;
        fileRow = fileRow +','+ ac.AccountNumber;
fileRow = fileRow +','+ ac.Industry;
        fileRow = fileRow +','+ ac.Phone;
           fileRow = fileRow.replaceFirst(',','');
           generatedCSVFile = generatedCSVFile + fileRow + '\n';
       }
       system.debug('File:'+generatedCSVFile);
Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
Blob csvBlob = blob.valueOf(generatedCSVFile);
String csvName = 'Accounts data inserted and modified Today.csv';
csvAttachment.setFileName(csvName);
csvAttachment.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{'ranga.vangalapudi@gmail.com'};
String subject = 'Accounts data inserted and modified Today';
email.setSubject(subject);
email.setToAddresses(toAddresses);
I want to use 2 constructors within my Controller class, one for a VF component and another for VF page.is it possible to have the same SOQL within 2 constructors.Please give an example
Hello, I've just started to learn about Apex and I'm having difficulty writing a test class for the following Apex class. 

The following Apex class has code to retrieve Account records and logic to iterate over a list of Account records and update the Description field.  I learned this Apex class through Trailhead and wanted to write a test class for it but couldn't figure out how.
public class OlderAccountsUtility {
    public static void updateOlderAccounts() {
      // Get the 5 oldest accounts
      Account[] oldAccounts = [SELECT Id, Description FROM Account ORDER BY CreatedDate ASC LIMIT 5];
      // loop through them and update the Description field
      for (Account acct : oldAccounts) {
          acct.Description = 'Heritage Account';
      }
      // save the change you made
      update oldAccounts;
    }
}
This is what I have written.  Can anyone show me how to fix this Apex test unit so it works?  Any help would be much appreciated!
@isTest
private class OlderAccountsUtilityTest {
    
    @isTest static void createAccount() {
    
    List <Account> accts = new List<Account>();
      for(integer i = 0; i<200; i++) {
         Account a = new Account(Name='testAccount'+'i');
         accts.add(a);
    }
        
   	insert accts;

    Test.StartTest();	
        
        List<Account> accList = [SELECT Id, Description FROM Account ORDER BY CreatedDate ASC LIMIT 5];
     
 		for (Account acct : accList) {
        acct.Description = 'Heritage Account';
        }

    Test.StopTest();

	System.AssertEquals(
    
    	database.countquery('SELECT COUNT() FROM Account WHERE Description' = 'Heritage Account'), 5);
             
    }
}

 
Hello,
I have a batch job which runs to populate two objects.. Monthly Activity(MonAct) and URL Individual monthly Activity (URLIndMonAct)...
The problem with the response is that I am quering for MonAct records and I am getting back 5 of them . And each of those MonAct records contains with it thousands of URLIndMonAct records...

I have limited my query to just 2 records per batch but I am still getting DML Rows : 10001 error ..
If I redice the size to 1 record, the batch is running for too long...

Can any one please guide me, how can I modify my code to prevent this error and not lose any records while processing...
Any help is appreciated.

Thanks!
global class BatchToUpdateGARecords implements Database.Batchable<sObject>, Database.Stateful, Schedulable, Database.AllowsCallouts{

    private List<String> EMAIL_BATCH_RESULTS = new List<String>{System.Label.Email_List};  
    global  IndividualMonthlyGARecords.BatchResponse runningBatchResponse;
    private String query;
    private Integer queryYear;
    private Integer queryMonth;

    global BatchToUpdateGARecords(Integer year, Integer month){
        runningBatchResponse = new IndividualMonthlyGARecords.BatchResponse();

        // Validate user input, if request to run batch is not for todays date
        if(month != null && year != null && month >= 0 && month <= 12 && year > 1950){
            this.queryYear  = year;
            this.queryMonth = month;
        }
        else{
            Date yesterdaysDate = Date.today().addDays(-1);

            this.queryYear  = yesterdaysDate.year();
            this.queryMonth = yesterdaysDate.month();
        }

        this.query  = 'SELECT Id, GID__c ';
        this.query += 'FROM Monthly_Activity__c ';
        this.query += 'WHERE Year__c = ' + queryYear + ' ';
        this.query += 'AND Month__c = ' + queryMonth + ' ';
        this.query += 'AND GID__c <> null ';
        this.query += 'AND GID__c > 0 ';
        
    }

    global BatchToUpdateGARecords(){
        this(null, null);
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Monthly_Activity__c> currentBatchRecords){
	
        List<Monthly_Activity__c> MonthlyActivities = [
            SELECT Id, GID__c, Month__c, Year__c
            FROM Monthly_Activity__c 
            WHERE Year__c =: queryYear
            AND Month__c =: queryMonth
            AND GID__c IN: Pluck.decimals('GID__c', currentBatchRecords)
        ];        

        List<URL_Individual_Monthly_Activity__c> urlIndividualMonthlyActivities = [
            SELECT Id, GID__c, URL__c, Month__c, Year__c
            FROM URL_Individual_Monthly_Activity__c 
            WHERE Year__c =: queryYear
            AND Month__c =: queryMonth
            AND GID__c IN: Pluck.decimals('GID__c', currentBatchRecords)
        ];        
         
        if(MonthlyActivities.isEmpty()){
            return;
        }
    
        try{           
            IndividualMonthlyGARecords.batchHandlerToUpdateRecords(
                runningBatchResponse,
                MonthlyActivities,
                urlIndividualMonthlyActivities,
                queryYear,
                queryMonth
            );
        
       }catch(exception ex){
            system.debug('exception call :'+ ex.getMessage());
            system.debug('exception call line :'+ ex.getStackTraceString());
        }
        if(runningBatchResponse != null && !runningBatchResponse.getSuccessRecords().isEmpty()){
            List<Database.SaveResult> updateResults =
                Database.update(runningBatchResponse.getSuccessRecords(), false);

            for(Database.SaveResult updateResult : updateResults){
              if(!updateResult.isSuccess()){
                for(Database.Error err : updateResult.getErrors()){
                  runningBatchResponse.addDatabaseError(err.getMessage());
                }
              }
            }
        }

        runningBatchResponse.clearSuccessRecords();
    
        if(runningBatchResponse != null && !runningBatchResponse.getSuccessRecordsIMA().isEmpty()){

            List<Database.SaveResult> updateResults1 =
                Database.update(runningBatchResponse.getSuccessRecordsIMA(), false);

            for(Database.SaveResult updateResult1 : updateResults1){
              if(!updateResult1.isSuccess()){
                for(Database.Error err : updateResult1.getErrors()){
                  runningBatchResponse.addDatabaseError(err.getMessage());
                }
              }
            }
        }

        runningBatchResponse.clearSuccessRecords();
  
    }

    global void execute(SchedulableContext SC){
        Database.executeBatch(new BatchToUpdateGARecords(), 2);                            //Changed from 5    }
    
    global void finish(Database.BatchableContext BC){
        AsyncApexJob apexBatchResult = [
            SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id =: BC.getJobId()
        ];
    
        // Generate email body
        String emailBody = 'Apex Batch to Update PageviewSessions processed '
            + apexBatchResult.TotalJobItems + ' batches with '+ apexBatchResult.NumberOfErrors + ' failures.\n\n'
            + 'Database errors (if any): ' + JSON.serialize(runningBatchResponse.getDatabaseErrors()) + '\n';
        
        // Extract error string from batch response
        //emailBody += runningBatchResponse.generateErrorString();

        // Send email
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(EMAIL_BATCH_RESULTS);
        mail.setSenderDisplayName('About.com Experts - Batch Results');
        mail.setSubject('About.com - Batch to Update PageviewSessions - status: ' + apexBatchResult.Status);
        mail.setPlainTextBody('Batch Process has completed\n\n' + emailBody);

        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{mail});
    }
}

 
I am trying to write a trigger on my Lead Object that will not allow a user to click Convert unless a boolean field is True. I need help with some sample code to get started. 

I plan to create an Approval Process on the lead record, then with the final Approver action have a field update to have my custom checkbox (Approved) set to True. 

Once this happens I want the user to be able to click Convert, but only once the checkbox is set to true. If it has not gone through the approval process, the user shoudnt be able to click convert. 

I should also note I would only want this for a specific record type of my lead object.
Can you send data (via SOAP) out from Sandbox to another System (not Salesforce)?
#newbie
Do requests with the If-None-Match header, that return a 304 response, count towards my API limit?
So I have an issue with a flow.  When I did a test it worked but now its not and I have no idea why.  The error message makes very little sense to me but appears to be an issue with the student field?

Can anyone help me with this:
Error element myRule_1_A1 (FlowRecordCreate).
This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: Meal_Transaction_AIAIAD: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0 Trigger.Meal_Transaction_AIAIAD: line 24, column 1. For details, see API Exceptions.
This report lists the elements that the flow interview executed. The report is a beta feature.
We welcome your feedback on IdeaExchange.
Flow Details
Flow Name: Payment_Meals_Update_Ver_3
Type: Workflow
Version: 1
Status: Active
Flow Interview Details
Interview Label: Payment_Meals_Update_Ver_3-1_InterviewLabel
Current User: Scott Walker (00XX000000#XXXXXXX)
Start time: 4/3/2017 4:46 PM
Duration: 0 seconds
How the Interview Started
Scott Walker (00X0000000000) started the flow interview.
Some of this flow's variables were set when the interview started.
myVariable_old = null
myVariable_current = a00000000aa0000008
ASSIGNMENT: myVariable_waitStartTimeAssignment
{!myVariable_waitStartTimeVariable} Equals {!Flow.CurrentDateTime}
Result
{!myVariable_waitStartTimeVariable} = "4/3/2017 4:46 PM"
DECISION: myDecision
Executed this outcome: myRule_1
Outcome conditions: and
1. {!myVariable_current.Payment_for__c} (Lunch Billing) Equals Lunch Billing
Logic: All conditions must be true (AND)
RECORD CREATE: myRule_1_A1
Create one Meal_Transaction__c record where:
Student__c = {!myVariable_current.Student__c} (null)
Transaction_Amount__c = {!myVariable_current.Amount_Paid__c} (1)
Transaction_Date__c = {!myVariable_current.CreatedDate} (4/3/2017 4:46 PM)
Transaction_Type__c = Credit
Result
Failed to create record.

Error Occurred: This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: Meal_Transaction_AIAIAD: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0 Trigger.Meal_Transaction_AIAIAD: line 24, column 1. For details, see API Exceptions.

I have mapped the fields and I believe they are correct, as follows:

User-added image

the fields on the right are:

Student__c
Amount_Paid__c
CreatedDate


Any help really appreciated I really need to get this to work
 
We have users in both Classic and Lightning using the standard "New" button on leads.  I need to override the standard "New" button and redirect the user to a lightning app.  I created a VF page action that will redirect the user to the lightning app.  Everything works great however for lightning users, the redirect opens a new tab in the browser.  How do I keep the redirect on the same browser window in lightning?  Do I need to create a VF page pulling in a lightning component?
My salesforce for outlook account was automatically logged out but when I click to log back in and enter my credentials I get this message: 
User-added image
 
//BlockContentLinkTrigger
trigger BlockContentLinkTrigger on ContentDocumentLink (before insert) {  
    for(ContentDocumentLink  contDocL : Trigger.new) {
      if (CDLHelper.isSharingAllowed(contDocL)) {  
          contDocL.addError('Pièce joint bloquée depuis objet ContentDocumentLink');
     } 
   }  
}

//CDLHelper
public class CDLHelper {
    public static boolean isSharingAllowed(ContentDocumentLink cdl) {
        //String docId = cdl.ContentDocumentId;        
        ContentVersion version = [select PublishStatus, FileExtension from ContentVersion
                                  where ContentDocumentId =: cdl.ContentDocumentId limit 5];              
        if (version.PublishStatus.equals('P') && (version.FileExtension != 'null')) {
            return false;
        }
        return true;
    }
}

 
Hi,
I need update the fields when I create a new register and when I update the same.
I created a trigger that execute a method that make this update.

When I create a new register This method works, and when I try update occurs a error.

Can you evaluate my code and see if I did the right way, and what is wrong?

Trigger code:
Trigger INSERT
trigger CalcularTudoTrigger on Item_de_oportunidade__c (after insert) {
    
    Item_de_oportunidade__c item = new Item_de_oportunidade__c();
    item = [SELECT Id, Name, Margin__c, Sales_Type__c, nome_oportunidade__c, Category__c, Extra_Expenses__c
            FROM Item_de_oportunidade__c
               WHERE Id IN : Trigger.newMap.keyset() limit 1];
    
    Opportunity op = new Opportunity();
    op = [SELECT Id FROM Opportunity WHERE Id = : item.nome_oportunidade__c];

    if(trigger.isAfter){
         if(trigger.isInsert){
            AutomatizaCalculos.inserirCalculoMVS(item.Id, op.Id, item.Sales_Type__c, item.Category__c, item.Margin__c, item.Extra_Expenses__c);
         }
    }
}

Trigger UPDATE
trigger CalcularAtualizacao on Item_de_oportunidade__c (before update) {
    
    Item_de_oportunidade__c item = new Item_de_oportunidade__c();
    item = [SELECT Id, Name, Margin__c, Sales_Type__c, nome_oportunidade__c, Category__c, Extra_Expenses__c
            FROM Item_de_oportunidade__c
               WHERE Id IN : Trigger.newMap.keyset() limit 1];
    
    Opportunity op = new Opportunity();
    op = [SELECT Id FROM Opportunity WHERE Id = : item.nome_oportunidade__c];

    if(trigger.isBefore){
         if(trigger.isUpdate){
            AutomatizaCalculos.inserirCalculoMVS(item.Id, op.Id, item.Sales_Type__c, item.Category__c, item.Margin__c, item.Extra_Expenses__c);
         }
    }

}

APEX CODE:

global class AutomatizaCalculos {
    
    public static void inserirCalculoMVS(String id_item, String regional, String tipoVenda, String categoria, Decimal margem, Decimal gastos){
        Item_de_oportunidade__c item = new Item_de_oportunidade__c();
        item = [SELECT Id, Name, Sales_Type__c, Category__c, Margin__c, Extra_Expenses__c FROM Item_de_oportunidade__c WHERE Id = : id_item];
        
        if(regional == 'AR'){
            if(tipoVenda == 'FEE'){
                item.MVS__c = (margem * 0.956) - gastos;
                inserirCalculoComissao(item.MVS__c, item.Id, categoria);
            }else{
                item.MVS__c = margem - gastos;
                inserirCalculoComissao(item.MVS__c, item.Id, categoria);
            }
            
        }else if(regional == 'CL' || regional == 'US'){
                item.MVS__c = margem - gastos;
            inserirCalculoComissao(item.MVS__c, item.Id, categoria);
        }else{
            if(tipoVenda == 'FEE'){
                item.MVS__c = (margem * 0.8725)-gastos;
                inserirCalculoComissao(item.MVS__c, item.Id, categoria);
            }else{
                item.MVS__c = margem - gastos;
                inserirCalculoComissao(item.MVS__c, item.Id, categoria);
            }  
        }
    update item;
    }
    public static void inserirCalculoComissao(Decimal mvs, String item_id, String categoria){
        Item_de_oportunidade__c item = new Item_de_oportunidade__c();
        item = [SELECT Id, Name, Margin__c, MVS__c, MS_Customer__c, Category__c FROM Item_de_oportunidade__c WHERE Id = : item_id];
        if(categoria == 'IT SERVICES' || categoria == 'MANAGED SERVICES'){
            if(item.MS_Customer__c == true){
                item.Fee_Pre_Sales__c = mvs *0.015;
                item.Fee_Pre_Manager__c = mvs * 0.075;
                item.Fee_Pre_Rep__c = mvs * 0.03;
            }else{
                item.Fee_Pre_Sales__c = mvs *0.03;
                item.Fee_Pre_Manager__c = mvs * 0.015;
                item.Fee_Pre_Rep__c = mvs * 0.06;
            }
            
        }else{
            if(item.MS_Customer__c == true){
                item.Fee_Pre_Sales__c = mvs *0.015;
                item.Fee_Pre_Manager__c = mvs * 0.075;
                item.Fee_Pre_Rep__c = mvs * 0.03;
            }else{
                item.Fee_Pre_Sales__c = mvs *0.02;
                item.Fee_Pre_Manager__c = mvs * 0.01;
                item.Fee_Pre_Rep__c = mvs * 0.04;
            } 
        }
        
        update item;
    }
}

Thanks
Rafael
I have a custom object called Service Contract. The object contains the following fields Effective Date (date) and Calls Per Year (number) End Contract (checkbox). 

When a user sets up the service contract for a customers machine the customer will decide how many times per year they want the machine serviced.

For example: Starting April 1,2017 I want my machine serviced 2 times per year.
I need the event/reminder to tell the user on October 1 and April 1 to create a work order untill End Contract is checked. 
I have no idea how to work this out. My expirence with Apex is null, I do have other programing expirience and want to learn how to do this just really need some help. 

I had been advised previously to create a custom setting which I have but do not know how to proceed. 
I'm creating a visualforce page that displays data for confirmation when changes are made to a record and I wanted an email to be triggered when the changes are confirmed/ submitted. I added a picklist to the object and reference it in the page using

<td><apex:inputField value="{!RMA__c.Changes_have_been_review__c}"/>        
            </td>

It shows up fine and has the values from the picklist field but whenever you select your value and hit submit it doesn't update the objects field. 

Any help would be appreciated.

-Tyler
I am using equals and hashcode methods. I am unable to include hashcode method in test class.
public class WrapperClassWrapperClass
{
    public string lastName;
    public string email;
    public string phone;
    public string company;
    public string ownerid;
    public WrapperClassWrapperClass(string leadName , string leadEmail, string leadphone , string leadcompany, string leadOwnerId){
            this.lastName = leadName != null ? leadName:null;
            this.email = leadEmail !=null ? leadEmail:null;
        	this.phone = leadphone != null ? leadphone:null;
        	this.company = leadcompany != null ? leadcompany:null;
        	this.ownerid = leadOwnerId != null ? leadOwnerId:null;
        }
    public Boolean equals(Object obj) {
        if (obj instanceof WrapperClassWrapperClass) {
            WrapperClassWrapperClass p = (WrapperClassWrapperClass)obj;
            return ((((lastName==p.lastName) && (email==p.email) && (phone==p.phone) && (company==p.company))||
                    (((lastName==p.lastName) &&  (company==p.company)) &&
                     ((email==p.email) || (phone==p.phone))))&& ownerid==p.ownerid);
        }
        return false;
    }
    public Integer hashCode() {
        return !test.isRunningTest() ? (1 * (lastName.hashCode() + phone.hashCode() + company.hashCode() + ownerid.hashCode())) ^ email.hashCode() : 123456;     
    }
}

I am calling using this wrapper class in a trigger.
 
My requirement is to display Account and its related contacts using accordion and accordion section.

I am able to display account and when I expand account it will show Rating and Phone but Under each account I want a separate accordion to show contact firstname and contact lastname.

Here's my code
public with sharing class MyController {

    @AuraEnabled
    public static List<Account> showAccountsForAccordion()
    {
        List<Account> accList = [select Id,Name,Rating,Phone,(select firstname,lastname from contacts)
                                 FROM 
                                 Account
                                 Order By name LIMIT 4];
        return accList;
    }
}

<aura:component implements="flexipage:availableForAllPageTypes" 
                controller="MyController"
                access="global" >
	
    <aura:attribute name="accnList"
                    type="List"/>
    
    <aura:handler name="init"
                  value="{!this}"
                  action="{!c.doInit}"/>
    
    <div class="demo-only slds-grid" style="height: 150px; width: 300px; padding: 2rem;">
    <div class="slds-is-fixed">
    <div style="position: absolute; top: 1rem; left: 1rem; border: 1px solid red; background: rgb(244, 246, 249);">
    
    <lightning:accordion>
          <aura:iteration items="{!v.accnList}" 
                          var="acc">
              
              <lightning:accordionSection name="{!acc.Name}" 
                                          label="{!acc.Name}">
                  
                   <aura:set attribute="body">
                       
                        <p>Rating : {!acc.Rating}</p>
                        <p>Phone : {!acc.Phone}</p>
                      
                    </aura:set>
                  
                  </lightning:accordionSection>
              
              <aura:iteration items="{!v.accnList.contacts}" 
                                  var="con">
                  <lightning:accordionSection name="{!con.Name}" 
                                              label="{!con.Name}">
                  
                   <aura:set attribute="body">
                       
                        <p>FirstName : {!con.FirstName}</p>
                        <p>LastNamePhone : {!con.LastName}</p>
                      
                    </aura:set>
                   </lightning:accordionSection>
                       </aura:iteration>
      </aura:iteration>
      </lightning:accordion>
  </div>
</div>
         </div>
</aura:component>


({
	doInit : function(component, event, helper) {
		
        debugger;
        var action=component.get('c.showAccountsForAccordion');
        
        action.setCallback(this,function(response){
            
            debugger;
            var state = response.getState();
            console.log('state ='+state);
            if (component.isValid() && state === "SUCCESS") {
               
                component.set("v.accnList", response.getReturnValue());
                console.log('v.accnList='+response.getReturnValue());
              }
        });$A.enqueueAction(action);
        
	}
})

Please tell me how to achieve this.

thanks
sheila
Is there a way to darken the selections, or increase the font size in Lightning. The options appear to be "Greyed Out" and are hard to see.
I apologize in advance, I am very new at Apex development and am just starting out down the SFDC Dev path, however I do have quite a bit of coding background. My question is, I'm embedding an iframe into a VF page that will show an Account creation page from our own backend and if possible, I'd like to pass through a few field values from the Account Record that the VF page lives on (Account Name, Phone number, etc) to the backend site that the iframe is showing.

Is it possible to pass through these values and if so, how best to go about that in Apex? Thank you so much!
Hi can anyone please help me with this test class .I was able to create content version but not content document link 

Apex class:

public class ContentVersionTriggerHelper {
    public static void linkContentVersion (List<contentversion> contentversionList) {
        try{
            //To store the taxonomy name
            Set <string>taxonomySet = new set <string>(); 
            //To store Taxonomy name and ID - Name is the Key
            map <string, string> taxonomyMap = new map <string,string>();
            list<contentversion> contentversionCaseList = new list<contentversion> ();
            for (contentversion objCV: contentversionList){
                system.debug('$$$objCV'+objCV.ContentDocumentId);
                // check if Taxonomy exists
                if(objCV.Taxonomy_Reference__c!=null && objCV.CurrentUserProfile__c  == 'Integration User'){ 
                    taxonomySet.add(objCV.Taxonomy_Reference__c);
                //check if case Id exist
                }else if(objCV.Case_Reference__c!=null && objCV.CurrentUserProfile__c == 'Integration User'){ 
                    contentversionCaseList.add(objCV);
                }
            }
            if(!taxonomySet.isEmpty()){
                for(Document_Type__c objDT : [select Id,name from Document_Type__c where name=:taxonomySet]){
                    taxonomyMap.put(objDT.name,objDT.Id);
                }
                //create case documents and link files
                insertCaseDocumentandLink(contentversionList,taxonomyMap); 
            }
            if(!contentversionCaseList.isEmpty()){ 
                // Directly link files to case
                insertContentDocumentLink(contentversionCaseList);
            }
        }catch (exception ex){
            system.debug('Exception occured in ContentVersionTriggerHelperClass' + ex.getLineNumber()  +ex.getMessage());         
            insert new Error_Framework__c(
                Error_Message__c=ex.getStackTraceString(), 
                Event_Category__c='Contentversion After Insert', 
                Description__c='Exception Occured in linkContentVersion Method', 
                User__c=UserInfo.getUserId(), 
                Object_Name__c='ContentDocumentLink/CaseDocument', 
                Source_Code_Location__c='ContentVersionTriggerHelper'
            );
        }
        return;
    }
   
   
    public static void insertCaseDocumentandLink(List<contentversion> contentversionList, map <string, string> taxonomyMap ) {
        system.debug('$$$insertCaseDocumentandLink'+contentversionList +' '+ taxonomyMap);
        //To store the  Case_Documents__c to be inserted
        list <Case_Documents__c> insertCaseDocumentList = new list <Case_Documents__c>();
        //To store the  ContentDocumentLink to be inserted
        list <ContentDocumentLink> insertContentDocumentLinkList = new list <ContentDocumentLink>();
            for (contentversion objCV: contentversionList){
                if(taxonomyMap.containskey(objCV.Taxonomy_Reference__c)){//checking if taxnomy exists
                    Case_Documents__c newDocument = new Case_Documents__c();
                    newDocument.Document_Status__c='Draft'; 
                    newDocument.Document_Type__c=taxonomyMap.get(objCV.Taxonomy_Reference__c);
                    newDocument.Effective_Date__c=system.today();
                    newDocument.Number_Of_Files__c=0;
                    newDocument.Case_Number__c = objCV.Case_Reference__c;
                    newDocument.Send_to_Oneview__c = false;
                    system.debug('$$$ContentDocumentId'+objCV.ContentDocumentId);
                    newDocument.Content_Document_Reference__c = objCV.ContentDocumentId;
                    insertCaseDocumentList.add(newDocument);
                }
                
            } 
            if(!insertCaseDocumentList.isEmpty()){
                insert insertCaseDocumentList;
                for (Case_Documents__c objCD: insertCaseDocumentList){
                    ContentDocumentLink caseDocLink = new ContentDocumentLink();
                    caseDocLink.LinkedEntityId = objCD.Id;
                    caseDocLink.contentDocumentId = objCD.Content_Document_Reference__c; 
                    //Viewer permission. The user can explicitly view but not edit the shared file.
                    caseDocLink.ShareType = 'V'; 
                    insertContentDocumentLinkList.add(caseDocLink);
                }
                if(!insertContentDocumentLinkList.isEmpty()){
                    insert insertContentDocumentLinkList;
                }
            }
            return;
    }
  //  This is not covered in Test class .
    public static void insertContentDocumentLink (List<contentversion> contentversionList){
        system.debug('$$$insertContentDocumentLink'+contentversionList);
        //To store the  ContentDocumentLink to be inserted
        list <ContentDocumentLink> insertContentDocumentLinkList = new list <ContentDocumentLink>();
        for (contentversion objCV: contentversionList){
                ContentDocumentLink caseDocLink = new ContentDocumentLink();
                caseDocLink.LinkedEntityId = objCV.Case_Reference__c;
                caseDocLink.contentDocumentId = objCV.ContentDocumentId; 
                //Viewer permission. The user can explicitly view but not edit the shared file.
                caseDocLink.ShareType = 'V'; 
                insertContentDocumentLinkList.add(caseDocLink);
        }
         if(!insertContentDocumentLinkList.isEmpty()){
                insert insertContentDocumentLinkList;
           }
        return;
    }
}
===========================================================================

Test class

@isTest
public class Test_ContentVersionInsertAction {
    /*************************************************************************************************************
* Apex Class Name     : ContentVersionInsertAction 
* Version             : 1.0 
* Created Date        : 12/02/2018
* Function            : Test class for ContentVersionInsertAction
* Modification Log    :
* Developer           :             Date                    Description
* ----------------------------------------------------------------------------                 
* Priyanka Indurthi            12/02/2018                   Original Version
************************************************************************************************************/
    
    static testmethod void testmethod1(){
        Test.startTest();
        Service_Mapping_Utility__c smu = new Service_Mapping_Utility__c(Case_Record_Type__c='Wires', 
                                                                        Case_Product_Name__c='Domestic Implementations',
                                                                        Case_Action__c='Drawdown Setup',
                                                                        Is_Auth__c=true,
                                                                        Hand_Off__c=true,
                                                                        Authentication_Required__c='High');
        insert smu;
        
        case newCase = new case(SelectProduct__c= smu.id,
                                Case_Type__c = 'Domestic Implementations',
                                Case_Received_Date__c = system.today());
        insert newCase;
        
        Document_Type__c docType = new Document_Type__c(LOB__c = 'Commercial Bank',
                                                        External_Id__c = 'Commercial BankEntityFinancial StatementsInterim Financial Statements',
                                                        Category__c = 'Entity');
        insert docType;
        
        
        profile pr = [select id from profile where name = 'Integration User'];
        user intgUser = new user(firstname = 'testFirstName',
                                 lastname = 'testLastName',
                                 profileid = pr.id,
                                 email = 'testuser@testclass.com',
                                 Username = 'testfirst.lastname@testclass.com',
                                 Alias = 'TfTl',
                                 CommunityNickname = 'test' ,
                                 TimeZoneSidKey = 'America/New_York', 
                                 LocaleSidKey = 'en_US', 
                                 EmailEncodingKey = 'UTF-8',
                                 LanguageLocaleKey = 'en_US'
                                );
        insert intgUser;
        system.runAs(intgUser){ 
            ContentVersion cv = new ContentVersion(
                Title = 'Test',
                PathOnClient = 'Test.jpg',
                VersionData = blob.valueof('Test Content Data'),
                IsMajorVersion = true,
                Case_Reference__c = newcase.id,
                Taxonomy_Reference__c = [select id,name from Document_Type__c where id =:docType.id][0].name
            );
            insert cv;
            
            ContentVersion contentVersionSelect = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id LIMIT 1];
            List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
            System.assertEquals(documents.size(), 1);
        }
       
         Test.stopTest();
    }   
}
I am trying to de-activate an apex trigger in production but it keeps failling. I have tried 2 different methods:

1. De-activating in sandbox and pushing to production
2. Using force.com IDE to delete. I am able to delete in my sandbox environment but I keep receiving an error when I try to deploy it to production.

Here is the error:

User-added image 
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]);
 }

 
Relationships: User -->Service Appointments ---> Work Orders -->Cases
   
Service Appointment (Parent) - Work Order(Child) - Cases(Parent to Work order)

i need to retrieve the coordinates from address and show them into a map

this is my code i want to be able to show coordinates in the map markers.

<apex:page standardController="Cuenta__c">

  <apex:pageBlock >
      


    
  <apex:map width="600px" height="400px" mapType="roadmap"
    center="{!Cuenta__c.Billing_Address__c},{!Cuenta__c.Billing_City__c},{!Cuenta__c.Billing_State__c}">

<apex:mapMarker title="Billing Address"
       position="{!Cuenta__c.Billing_Address__c},{!Cuenta__c.Billing_City__c},{!Cuenta__c.Billing_State__c}"
                >
      <apex:mapInfoWindow >
            <apex:outputPanel layout="block" style="font-weight: bold;">
              <apex:outputText >{!Cuenta__c.Billing_Address__c}</apex:outputText>
            </apex:outputPanel>

            <apex:outputPanel layout="block">
              <apex:outputText >{!Cuenta__C.Billing_City__C }</apex:outputText>
            </apex:outputPanel>               

            <apex:outputPanel layout="block">
              <apex:outputText >{!Cuenta__c.Billing_State__c}</apex:outputText>
            </apex:outputPanel> 
          

           
          </apex:mapInfoWindow>
      
      </apex:mapMarker>
                  <apex:mapMarker title="Fiscal Address"
       position="{!Cuenta__c.Fiscal_Address__c},{!Cuenta__c.Fiscal_City__c},{!Cuenta__c.Fiscal_State__c}"
    >
                      <apex:mapInfoWindow >
            <apex:outputPanel layout="block" style="font-weight: bold;">
              <apex:outputText >{!Cuenta__c.Fiscal_Address__c}</apex:outputText>
            </apex:outputPanel>

            <apex:outputPanel layout="block">
              <apex:outputText >{!Cuenta__C.Fiscal_City__C }</apex:outputText>
            </apex:outputPanel>               

            <apex:outputPanel layout="block">
              <apex:outputText >{!Cuenta__c.Fiscal_State__c}</apex:outputText>
            </apex:outputPanel>               

           
          </apex:mapInfoWindow>
      
      </apex:mapMarker>
      <apex:mapMarker title="Shipping Address"
       position="{!Cuenta__c.Shipping_Address__c},{!Cuenta__c.Shipping_City__c},{!Cuenta__c.Shipping_State__c}"
    >
                                <apex:mapInfoWindow >
            <apex:outputPanel layout="block" style="font-weight: bold;">
              <apex:outputText >{!Cuenta__c.Shipping_Address__c}</apex:outputText>
            </apex:outputPanel>

            <apex:outputPanel layout="block">
              <apex:outputText >{!Cuenta__C.Shipping_City__C }</apex:outputText>
            </apex:outputPanel>               

            <apex:outputPanel layout="block">
              <apex:outputText >{!Cuenta__c.Shipping_State__c}</apex:outputText>
            </apex:outputPanel>               

           
          </apex:mapInfoWindow>
      
      </apex:mapMarker>

      
      </apex:map>
  </apex:pageBlock>

</apex:page>

what settings can be transferred threw metadata api
          web to case 
          web to lead
          case settings
          lead conversion
Please let me know the answer for the above question?

I created an object called Dados_Utiliza_o__c which contains about 50 fields, which are populated with .csv, among these fields there is a called Nome_do_Paciente__C that contains the name of an account, where my intention is to create a trigger before inserting, where:
1. Check if there is an account (patient in my case) with the CPF (document of unique registration of person in Brazil, similar to Social Security Card) registered in the system;
2. If it does not exist it starts the process of registering
3. As .csv sends the full name in the field, then it breaks the name to enter in the salesforce, first name and last name.
4. Register or update the account if it is already on the system.
5. If the registered account name is the same as the Nome_do_Segurado__c field (another field and something that can occur in .csv), it lists this created or updated account, otherwise it just inserts in text form in the unrelated field

this is my trigger currently, I'm not finding what's wrong or if something is missing:

trigger PacienteUtilizacao on Dados_Utiliza_o__c (before insert) {
    
	Account paciente;
    Account segurado;
    String firstSplit;
    String restSplits; 
   
    RecordType personAccountRecordType =  [SELECT Id FROM RecordType WHERE Name = 'Paciente' AND SObjectType = 'Account'];
    
    //verifica se existe um account com o preenchido
    for(Dados_Utiliza_o__c utilizacao : Trigger.new)
    {
    	try {
            paciente = [
                SELECT
                	FirstName,
                	LastName,
                    Sexo__pc,
                    Birthdate__c,
                    CPF__pc
                FROM Account
                WHERE CPF__pc = :utilizacao.CPF_CGC_do_Referenciado__c
                LIMIT 1
            ];
        //se não encontrar ele cadastra
		} catch (Exception e) {
       		paciente = new Account();         
		}
        
        //Quebra o nome do paciente em First Name e Last Name
		if(utilizacao.Nome_do_Paciente__r.Name != null){
            String input = utilizacao.Nome_do_Paciente__r.Name;
            firstSplit = input.substringBefore(' ');
            restSplits = input.substringAfter(' ');
        }
        
        //Quando não encontrar o paciente no try de cima ele então cadastra
        try {             
        	paciente.RecordTypeId = personAccountRecordType.Id;
            paciente.FirstName = firstSplit;
            paciente.LastName = restSplits;
            paciente.Sexo__pc = utilizacao.Sexo__c;
            paciente.Birthdate__c = utilizacao.Data_de_Nascimento_Y2K__c;
            paciente.CPF__pc = utilizacao.CPF_CGC_do_Referenciado__c;
            upsert paciente;
        } catch (Exception e) {
            System.debug(e.getMessage());
        }
          
        IF (paciente.Name == utilizacao.Nome_do_Segurado__c){
			utilizacao.Nome_do_Segurado__c = paciente.Id;
			// se for, entao o id do segurado é o id que achamos para o paciente    
        } ELSE{
             // se nao for, vamos tentar buscar o segurado pelo nome.
			try {
            	segurado = [
                	SELECT
                    FirstName,
                    LastName,
                    Sexo__pc,
                    Birthdate__c,
                    CPF__pc
                    FROM Account
                    WHERE CPF__pc = :utilizacao.Nome_do_Segurado__c
                    LIMIT 1
                ];
                // se acharmos, entao vamos bucsar o ID no registro de utilizacao que estamos criando.
                utilizacao.Nome_do_Segurado__c = segurado.Id;
            } catch (Exception e) {
            	System.debug(e.getMessage());        
            }
        }
    }
}
I am new to Salesforce and trying to create Big object first on sandbox. We are archiving the records from a Custom object to Big Object. The custom object has all kind of fields such as 
- Date/Time
- Picklist
- Number
- Formula
- Checkbox
- URL
- Lookup
- Percent
- Master-Detail and more... 

Does Big object supports all the mentioned data types? I went through some documentation avaialble to deploy the Big object but was not able to find the answer to this Question.
Thank you
Hi All,

I am working JSON Parsing which is very new to me. I am getting the response and deserialized by using below method.
Map<String, Object> deSer = (Map<String, Object>) JSON.deserializeUntyped(resp.getbody());
Response Body is below:
{
	value = ({
		group_name =  *******,
		groupid = 1,
		sub_customer = [{
			"CustomerId": "9488490",
			"CustomerName": "*******",
			"Street": "*******,"
			City ":"
			KINGSWOOD ","
			PostalCode ":"
			******* ","
			Country ": Australia",
			"Assetcnt": "0"
		}, {
			"CustomerId": "9488491",
			"CustomerName": "*******",
			"Street": "*******,"
			City ":"
			PENRITH ","
			PostalCode ":"
			******* ","
			Country ": Australia",
			"Assetcnt": "0"
		}, {
			"CustomerId": "94106344",
			"CustomerName": "*******",
			"Street": "*******,"
			City ":"
			KINGSWOOD ","
			PostalCode ":"
			******* ","
			Country ": Australia",
			"Assetcnt": "0"
		}, {
			"CustomerId": "94126502",
			"CustomerName": "*******",
			"Street": "DERBY STREET,"
			City ":"
			KINGSWOOD ","
			PostalCode ":"
			******* ","
			Country ": Australia",
			"Assetcnt": "0"
		}, {
			"CustomerId": "94106486",
			"CustomerName": "*******",
			"Street": "*******,"
			City ":"
			KINGSWOOD ","
			PostalCode ":"
			******* ","
			Country ": Australia",
			"Assetcnt": "0"
		}, {
			"CustomerId": "9488489",
			"CustomerName": "*******",
			"Street": "*******,"
			City ":"
			PENRITH ","
			PostalCode ":"
			******* ","
			Country ": Australia",
			"Assetcnt": "0"
		}]
	})
}

I would like to get a list of Sub_Customers by using below method which is getting NULL Values.
 
List<Object> lstObj = (List<Object>) deSer.get('sub_customer');

Once I get the list<Object> I need to pass to Lightning: Datatable to display as a tree Grid view.

Regards,
VSK98
 
  • December 03, 2018
  • Like
  • 0
execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.emailmatchdatacontact: line  29,column 1

trigger emailmatchdatacontact on ContactRelationship__c (before insert,before update) 
{
    List<ContactRelationship__c> con= new List<ContactRelationship__c>();
    List<Contact> conlist=new List<Contact>();
    Set<String> valtocheck=new Set<String>();
    Map<String,Contact> valfound=new Map<String,Contact>();
    for(ContactRelationship__c cr:trigger.new)
    {
      if(!string.isBlank(cr.EmailId__c)) valToCheck.add(cr.EmailId__c);
    }
    system.debug(valToCheck);
    Map<String, boolean> contactRelationCheckMap = new Map<String, boolean>();
    if(valtocheck != null)
    {
    List<Contact> conrelList = new List<Contact>();
    conrelList = [select id,Email from Contact where Email IN:valtocheck];
    if(conrelList.size()>0)
    {
    for(Contact c:conrelList)
    {   
        contactRelationCheckMap.put(c.Email, true);
    }
        for(ContactRelationship__c cr:trigger.new) 
        {  
            for(Contact c:conrelList)
            {
            if(cr.EmailId__c !=null)
            {
            if(contactRelationCheckMap.get(cr.EmailId__c))
            {  
                
                contact connn=new contact();
                connn.Opt_out_status__c=true; 
                connn.opt_out_transaction__c=system.today();
                connn.id=c.Id;
                conlist.add(connn);
                system.debug(c);
                system.debug(connn);
                system.debug('data available');
                system.debug(contactRelationCheckMap);
                } 
            }
            }
        }
         system.debug('conlistconlistconlistconlist');
         system.debug(conlist);
        // valfound.put(cr.Email,cr);
    } 
     // update conlist;
      //System.debug(conlist);
      
    }
    
    try
   {
    system.debug('data available');
    system.debug(conlist);
    update conlist;
    }
    catch(system.NullPointerException e)
    {
        system.debug('data not available');
    }  
}    

 
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]);
 }

 

I have multiple communities in my org.

User-added image

When I purposely try to show an error in the community it show different URL in the error message.
Community that being access is "Trial3", but the error is show as another community ("Trial").
User-added image

Why is this happening?

How to overcome this issue?

Unable to login  @ Dev Org. dectivate a flow assicated with login flow for system admin. unable to login  thrown error message while login " no active flow"
Hi,
I am new in salesforce. I have question about relationships. Is it possible to generate dynamically a generic link between objects? My scenario is to have a custom object with fields like object_id,object_name, field_id, field_name. I would like to build  links between my custom object and other objects.