• Hemant_Jain
  • SMARTIE
  • 588 Points
  • Member since 2015

  • Chatter
    Feed
  • 15
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 6
    Questions
  • 85
    Replies
Is there any way to remove hyperlink for Frorm  Address?
User-added image
<apex:column value="{!email.FromAddress}" headerValue=" From Address"/>
Thanks in Advance,
Deepak
 
hi,
I have a favourite button which fetches the items which has been ordered more than twice.
This is my controller

    Public List<Menu__c> favmenu {get;set;}
     favmenu = [select id, name,Category__c,Description__c,Image__c,ImageURL__c,Dish_Name__c,Price__c,
                 Special_Dish__c,Status__c,SubCategory__c,veg_non_veg__c,remarks__c from Menu__c where id IN : menuIdList]; 
           
           if(favmenu.size()>0)
               nofavourites = 'Choose from your favourites';
           else
                nofavourites='No favourites yet';

When i m testing for favmenu.size()>0 ..... it is working fine....but for the else part, when the soql query is not fetching any item, it is showing the error
Attempt to de-reference a null object 
An unexpected error has occurred. Your development organization has been notified.
  • September 21, 2017
  • Like
  • 1
Hi , im trying to update Account.fax = contact.fax if account.type == prospect.
Then i used helper class , but not working give me solution please. And tell how can i write test class for trigger and helper class. I am learning Apex programming...
Trigger :trigger newSupportinClassForContact on Contact (before insert, after insert, before update, after update) {
    
        supportClassForContactUpdateAccount.AccountContactCreation(trigger.new);
        

Error: Method does not exist or incorrect signature: void AccountContactCreation(List<Contact>) from the type supportClassForContactUpdateAccount
Helper Class:
public class supportClassForContactUpdateAccount {
     public static void AccountContactCreation(){
     //list<contact>  cons = new list<contact>();
         contact[]  cons;
         cons = trigger.new;
         list<id> accountIdList = new list<id>();
         for(contact newCons:cons){
             if(newCons.fax != null && newCons.AccountId !=null ){
                 accountIdList.add(newCons.Accountid);
             }
         Map<ID, account> accToUpdate = new Map<ID, account> (
    [select Id, name, fax from account
    where Id in :accountIdList]);
  
List<account> accUpd = new List<account>{};
        for(account newAcc:accToUpdate.values()){
            if(newAcc.Type=='Prospect'){
            newAcc.Fax=newCons.Fax;
            accUpd.add(newAcc);
            }
        }
 if (accUpd != null && !accUpd.isEmpty())
Database.update(accUpd);
         }
}
}
public class DuplicateLeads {
    public List<Lead> leadsList {set;get;}
    public List<String> emailList {set;get;}
    public Integer count=0;
    public DuplicateLeads(){
        leadsList=[select email,name from lead];
    }
    public void BasedOnEmail(){
        List<aggregateResult> results=[select count(id)cou,email from lead group by email];
        for(AggregateResult ar:results){
            count=(Integer)ar.get('cou');
            System.debug(count);
            if(count>2){
                emailList.add((String)ar.get('email'));//values are not added to the list
                System.debug(emailList);
            }
        }
    } 
}
Hi Guys, I have already this validation rule in place: 

Debit_Authorization__c &&  ISBLANK(IBAN__c)

now we added an extra field which can be filled instead of the IBAN__c field. So if Debit_Authorization__c, IBAN__c or extra field have to be filled. How can I solve this in one validation? 
Hi All,

I am trying to invoke Apex code from custom button on a custom object (Trainee__c) page layout. I am getting error : Unexpected Identifier when I am passing the name field of the custom object in he parameter to Apex method. Following is the code:
 
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

sforce.apex.execute("PopulateTraineeModule","PopulateTraineeModuleData",
{TraineeName:{!Trainee__c.Name});

alert('Module Data for {!Trainee__c.Name} refreshed');
If I replace  {!Trainee__c.Name} with a hard coded value.. Say 'Atticus Finch' the logic is working fine.
I am also able to see the correct alert message with {!Trainee__c.Name}

Not sure where the problem is.
Following is my Apex Class and method
global class PopulateTraineeModule {

    
    webservice static void PopulateTraineeModuleData (String TraineeName )
    {
...
     }
}




alert('Module Data for {!Trainee__c.Name} refreshed');


 
Hi All,

I am getting System.NullPointerException: Attempt to de-reference a null object error in salesforce test class.

Apex Class:
global class planvisitcontroller {
 public String RequestorEmployee { get; set; }
    public id leadid{get;set;}
    public string userid{get;set;}
    public string SelectedProduct{get;set;}
    public boolean showReqPopup { get; set; }
    public list<lead> leadlist{get;set;}
    
    public boolean serachdone{get;set;}
    public list<user> userList{get;set;}
    public String routeAccMap { get; set; }
    
    public String taskSubject{get;set;}
    public DateTime startDateTime {get;set;}
    public DateTime endDateTime {get;set;}
    public String errorMessage {get;set;}
    
     public list<Account> lstAccount {get;set;} 
    public boolean isError { get; set; }
    public List<WrapperLead> wrappers {get; set;} 
    public List<String> selectedDays {get;set;}
    public String recordName { get; set; }
    
    public List<SelectOption> days { get; set; }
    public Set<String> plannedDays;
    public String currentMonth { get; set; }

   public planvisitcontroller () {
        showReqPopup = false;
        wrappers = new List<WrapperLead>();
        SelectedDays = new List<String>();
        days = new List<SelectOption>();
       mapUsersByID = new Map<Id, User>([SELECT Id, Name From User 
                                         WHERE Manager.Id=:UserInfo.getUserId() AND UserRole.Name='Sales Executive']);
        
        leadlist=[select id, name, Status, Requested_Visit_Time__c,OwnerId,Sales_Executive__c,Address,city 
                 from lead WHERE OwnerID=:mapUsersByID.keySet()  and isConverted=false and Sales_Executive__c!=null 
                 order by Requested_Visit_Time__c];
         
        for(Lead l : leadlist){
            wrappers.add(new WrapperLead(l, new List<Integer>{1,2})); 
        } 
            
        lstAccount = [SELECT Id, Name, Onboarding_Status__c, BillingCity, OwnerId,Sales_Executive__c From Account 
                      WHERE Sales_Executive__c=:mapUsersByID.keySet()];
    }
    
    
    public PageReference closetable() {
        showReqPopup=false;
        return null;
    }


    public PageReference SelectedEmployee() {
        return null;
    }
    
    
    public PageReference closePopup() {
        PageReference ref = new PageReference('/apex/D2R_PlanVisit');
        ref.setRedirect(true);    
        return ref;      
    }
    
    public void FilterEmployee() {
        userList=mapUsersByID.values();
        serachdone=true; 
        openpopup();   
        //return null;
    }
    
    
    public PageReference CloseWindow() {
        showReqPopup=false;
        selectedDays = new List<String>();
        plannedDays = new Set<String>();
        taskSubject = '';
        
        return null;
    }


    public PageReference openpopup() {
         showReqPopup=true;
        String recordId = leadid;
        List<Task> existingTasks = new List<Task>();
        plannedDays = new Set<String>();
       
        if(recordId.startsWith('00Q')) {
            Lead l = [SELECT Sales_Executive__r.name FROM Lead WHERE Id=:recordId];
            
            if(RequestorEmployee=='' || RequestorEmployee == null)
                RequestorEmployee = l.Sales_Executive__r.name;
            
            existingTasks = [Select Id, subject, ActivityDate from Task Where WhoId=:recordId AND Type='Visit'];
            
        }else {
            Account a = [Select Sales_Executive__r.name From Account Where id=:recordId];
            if(RequestorEmployee=='' || RequestorEmployee == null)
                RequestorEmployee  = a.Sales_Executive__r.name;
            
            existingTasks = [Select Id, subject, ActivityDate from Task Where WhatId=:recordId AND Type='Visit'];
        }
       
        days = getDaysOfCurrentMonth();
        
        for (Task t : existingTasks){
            String taskDay = String.valueOf(t.ActivityDate);
        }
       
        selectedDays = new List<String>();
        
        for (Task t : existingTasks){
            
            String taskDay = String.valueOf(t.ActivityDate);
            System.debug('!!: ' + taskDay);
            
            if(String.isNotBlank(taskDay) ){
                List<String> i = taskDay.split('-');
                
                if(Date.Today().Year() == Integer.valueOf(i[0]) &&  Date.Today().Month() == Integer.valueOf(i[1]))
                    if(!plannedDays.contains(''+i[2])) {
                        selectedDays.add(''+Integer.valueOf(i[2]));
                        plannedDays.add(''+Integer.valueOf(i[2]));
                    }
            }
            
        }   
         System.debug(' selectedDays !!: ' + selectedDays);
         System.debug('plannedDays !!: ' + plannedDays);
        
        return null;
    }


    public PageReference saveplaning() {
        
        showReqPopup=false;
        String recordId = leadid;
        Lead leadplan = new Lead();
        Account acc = new Account();
        List<Task> tasksToInsert = new List<Task>();
        
        System.debug('selected Days: ' + selectedDays );
        
        if(recordId.startsWith('00Q')){
            leadplan = [select id, Requested_Visit_Time__c, Plan__c, Name, OwnerId, Sales_Executive__c from Lead where id = :recordId ];
        
        } else {
            acc = [SELECT Id, Name, BillingCity, OwnerId,Sales_Executive__c From Account 
                   WHERE Id=:recordId];
        }
        
       
        for(String str : selectedDays) {
        
            system.debug('Loop for : ' + str);
            Id visitRT = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Plan-Visit Task').getRecordTypeId();
            
            if(!plannedDays.contains(str)) {
            
                system.debug('task to be inserted for : ' + str);
                Integer day = Integer.valueOf(str);
                Date dueDate = date.newInstance(Date.Today().Year(), Date.Today().Month(), day);
                
                Task task = new Task();
                task.subject = taskSubject;
                
                if(String.isNotBlank(userid)){
                     task.OwnerId = userid;
                } else {
                    if(recordId.startsWith('00Q'))
                        task.OwnerId = leadplan.Sales_Executive__c;
                    else
                        task.OwnerId = acc.Sales_Executive__c;
                }
                              
                if(recordId.startsWith('00Q')) {
                    task.whoId = recordId;
                } else {
                    task.whatId = recordId;    
                }
                
                task.ActivityDate = dueDate;
                task.RecordTypeId = visitRT;
                task.Type = 'Visit';
                
                tasksToInsert.add(task);
              }
          }
          
          if(tasksToInsert.size()>0) {
              insert tasksToInsert;
          }
          
          PageReference ref = new PageReference('/apex/D2R_PlanVisit');
          ref.setRedirect(true);
        
          return ref;      
    }
    
     public List<SelectOption> getDaysOfCurrentMonth() {
    
          Map<Integer,String> mapMonthsByIndex = new Map<Integer,String>{ 1 => 'January', 2 => 'February'};
        currentMonth = mapMonthsByIndex.get(Date.Today().Month()) + ' , ' + Date.Today().Year();
        
        Date firstDayOfMonth = System.today().toStartOfMonth();
        Date lastDayOfMonth = firstDayOfMonth.addDays(Date.daysInMonth(firstDayOfMonth.year(), firstDayOfMonth.month()) - 1);
        
        System.debug('!!!!: ' + lastDayOfMonth);
        List<String> days = new List<String>();
        
        for(Integer i=1; i<=lastDayOfMonth.day() ; i++ ){
            days.add('' + i);
            System.debug('!!!!: ' +i);
        }
            
        List<SelectOption> Options = new List<SelectOption>();
        
        for(String str : days){
            Options.add(new SelectOption(str,str));
        }
        
        return Options;
    }
    }

Test Class
@isTest
private class planvisitcontrollerTest
{

    @testSetup 
 static void setup() 
 {
      Profile p = [SELECT Id FROM Profile WHERE Name='Sales Executive'];
      User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
      insert u2;
        
      Lead l = new Lead();
      l.LastName = 'Salesforce.com';
      l.Company = 'KPMG';
      l.Status = 'New';
      l.Email = 'abc@gmail.com';
      l.Phone = '8938493';
      l.Industry = 'Web';
      l.City=' bangalore';
      l.PostalCode ='788889';
      l.State = 'Karnataka';
      l.Country = 'India';
      insert l;
      
      Task t = new Task();
      t.Subject= 'test task';
      t.ActivityDate = System.Today();
      t.WhoId = l.Id;
      t.Type = 'Visit';
      insert t;
  
       l = [SELECT Id FROM Lead WHERE Id = :l.Id];
 }

     @isTest 
 static void testMethod1() 
 {
 
    
     planvisitcontroller pc = new planvisitcontroller();
      Test.startTest();
      pc.SelectedEmployee();
      pc.closePopup();
    
       pc.FilterEmployee();
      pc.CloseWindow();
      
      pc.saveplaning();
      pc.getDaysOfCurrentMonth();
      Test.stopTest();
   
      System.assertNotEquals(null,    pc.openpopup());

     
      
 }

}

Getting error in openpopup() method in Apex class. Because passing the recordId.startsWith('00Q') in openpopup. Not getting how to pass in Test class. Could any one help on this. 

Thanks in Advance.
Does anyone know how to convert an ID into a name value in Apex (not a formula)?  Thanks 
Hi all,

I am trying to use this JSON parsing in a trigger.
The purpose of the trigger is to insert latitude and longtitude data to custom object "Branch__c" once data like address, city etc. are inserted so geolocation details are inserted automatically after the trigger is fired.
The point is to gather address details from Branch__c custom object and construct a String to be put in "endPointString" variable.
I am doing this by using a formula field where I want to concatenate all necessary details. 
In order to test whether the callout works in a trigger at all I chose to make an "in between steps trigger" just to test the functionality, therefore in all newly inserted rows would be put the same longtitude and latitude details as these the "endPointString" variable would have a fixed String value for the moment.
The thing is that when I use below trigger which uses above "parsing classes" and try to insert test data, I get a different error :)

Can you please help?
Appreciate your help,
Milan


The error: Line: 36, Column: 1
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, updGPStest: execution of BeforeInsert caused by: System.CalloutException: Callout from triggers are currently not supported. Class.getGPS.getGPSdata: line 23, column 1 Trigger.updGPStest: line 11, column 1: []​

Data to insert:
-----------------------------
List<Branch__c> brList = new List<Branch__c> {
    new Branch__c(Account__c = '0010Y00000EhCbzQAF', City__c='Kladno', Name__c='Kladno_BULK_TEST1', Postal_Code__c='272 01', Street__c='Vrchlického', Street_No1__c='2409', Street_No2__c='9'),
    new Branch__c(Account__c = '0010Y00000EhCbzQAF', City__c='Kladno', Name__c='Kladno_BULK_TEST2', Postal_Code__c='272 01', Street__c='Vrchlického', Street_No1__c='2409', Street_No2__c='9'),
    new Branch__c(Account__c = '0010Y00000EhCbzQAF', City__c='Kladno', Name__c='Kladno_BULK_TEST3', Postal_Code__c='272 01', Street__c='Vrchlického', Street_No1__c='2409', Street_No2__c='9')
};
// Bulk insert all contacts with one DML call

insert brList;

My current trigger:
-------------------------------

 trigger updGPStest on Branch__c (before insert, before update) {
     
    List<Branch__c> addrString = new List<Branch__c>();
    getGPS gps = new getGPS();
    
    for(Branch__c br1 : Trigger.New) {
    

        addrString = [SELECT Concatenate_Address__c FROM Branch__c WHERE Id IN :Trigger.New];
        
        gps.getGPSdata();

        
        
        br1.Location_GPS__latitude__s = gps.getLat();
        br1.Location_GPS__longitude__s = gps.getLng();
        
        
         //gps.setEndPointStr('&addrString&');
        //gps.setEndPointStr('http://maps.googleapis.com/maps/api/geocode/json?address=Černokostelecká /, Říčany, 251 01');
        //br1.Test_Column__c = br1.Concatenate_Address__c;
        

    }
}


web callout classes used:

//class no.1
--------------------
public class getGPS {
    
    String endPointString = 'https://maps.googleapis.com/maps/api/geocode/json?address=Žerotínova 1664/57, Praha, 130 00&key=AIzaSyDpkHWwId9J1mMCqu9mirXPEwpM3XTs0GU';
    double lng;
    double lat;
    
    public double getLng() {
        return lng;
        }
    
    public double getLat() {
        return lat;
        }
    
  

      public void getGPSdata() {
          Http httpProtocol = new Http();
          HttpRequest request = new HttpRequest();
          String endpoint = endPointString;
          request.setEndPoint(endpoint);
          request.setMethod('GET');
          HttpResponse response = httpProtocol.send(request); 
          String jsonString = response.getBody();
          googleAddress addr = googleAddress.parse(jsonString);
          
googleAddress.Location loc = addr.firstLoc;
double lng = loc.lng;
double lat = loc.lat;
          
          this.lng=lng;
          this.lat=lat;

      }
    
                       
}

//class no.2
--------------------

public class googleAddress {

    public class Address_components {
        public String long_name;
        public String short_name;
        public List<String> types;
    }

    public class Geometry {
        public Location location;
        public String location_type;
        public Viewport viewport;
    }

    public List<Results> results;
    public String status;
    public Location firstLoc;

    public class Results {
        public List<Address_components> address_components;
        public String formatted_address;
        public Geometry geometry;
        public Boolean partial_match;
        public String place_id;
        public List<String> types;
    }

    public class Viewport {
        public Location northeast;
        public Location southwest;
    }

    public class Location {
        public Double lat;
        public Double lng;
    }

    
    public static googleAddress parse(String json) {
        
        googleAddress returnAddr;
        
        returnAddr = (googleAddress) System.JSON.deserialize(json, googleAddress.class);
        if (!returnAddr.results.isEmpty()){
            returnAddr.firstLoc = returnAddr.results[0].geometry.location;
        }
        return returnAddr; 
        
        
    }
}
 
Hello, 
I'm a newbie and working on apex classes in order to extract data into csv files (I don't want to use dataloader, reports or another thing, juste apex code). 
I have problem with the Address field : all the others fields are in one column when I generate the csv (like : "data1","data2","data3" etc). But I have this when the Address field is coming : (I've hidden the first colum which is ok until Address)

Address field : csv format problem

I'm not able to target the field :
- my  "if (fieldMap.keySet().contains('address')) " doesn't work and I don't know how to proceed
- if (fieldMap.keySet() == 'address')    doesn't work too (Tells me : Comparison arguments must be compatible types : Set <String>, String)
And I don't know how to separate the country, the countryCode etc...

My code : 
 
public class DataExtractUser {

    public static void extractUsers() {

        String csv = '';
        String query = 'SELECT ';

        // Getting User object fields
        Schema.DescribeSObjectResult objectDescribe  = User.SObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = objectDescribe.fields.getMap();


        // Building csv's header and inserting required fields in the SOQL request 
        for( String fieldName : fieldMap.keySet() ) {
            // This if doesn't work actually
            if (fieldMap.keySet().contains('address')) {
                // Treatment
            } else {
                csv += '"' + fieldName + '",';
                query += fieldName + ',';
            }

        }

        // Deleting last comma
        query = query.substring(0, query.length()-1);
        query += '\n FROM User';
        csv = csv.substring(0, csv.length()-1);
        csv += '\n';

        List<User> users = Database.query(query);

        // Building csv
        for (User user : users) {
            for ( String fieldName : fieldMap.keySet() ) {
                csv += '"' + user.get(fieldName) + '",';
            }
            csv = csv.substring(0, csv.length());
            csv += '\n';
        }

        //Deleting last \n
        csv = csv.substring(0, csv.length()-1);

        // Generating csv file and recording in Chatter files
        try {
            ContentVersion file = new ContentVersion(
                    title = 'users.csv',
                    versionData = Blob.valueOf(csv),
                    pathOnClient = '/users.csv'
            );
            insert file;
        } catch (Exception e) {
            System.debug('error' + e);
        }
    }

}

Thanks for help, 
Julie.
trigger updateProjectTeammember on opportunityTeamMember(after insert, after update, after delete){
        if(trigger.isInsert || trigger.isUpdate){
        
        Map<String,String> OppOtmfieldMap=new Map<String,String>();
               OppOtmfieldMap.put('Sr. Client Insights Manager','CEM_Assigned__c');
               OppOtmfieldMap.put('Client Insights Manager','CEM_2nd__c');
               OppOtmfieldMap.put('Data Manager','Ops_Owner__c');
               OppOtmfieldMap.put('Lead Consultant','Consultant_assigned__c');
               OppOtmfieldMap.put('Support Consultant','Consultant_2nd__c');
               OppOtmfieldMap.put('Analysis Support','Analysis_Support__c');
               OppOtmfieldMap.put('BD/Development Partner','BD_Development_Partner__c');
        
        Map<String,String> projOtmfieldMap=new Map<String,String>();
               projOtmfieldMap.put('Sr. Client Insights Manager','Sr_Client_Insights_Manager__c');
               projOtmfieldMap.put('Client Insights Manager','Client_Insights_Manager__c');
               projOtmfieldMap.put('Data Manager','Ops_Manager__c');
               projOtmfieldMap.put('Lead Consultant','Lead_Consultant__c');
               projOtmfieldMap.put('Support Consultant','Support_Consultant__c');
               projOtmfieldMap.put('Analysis Support','Analysis_Support__c');
               projOtmfieldMap.put('BD/Development Partner','BD_Development_Partner__c');
        
            list<id> oppoIdList = new list<id>();
            map<id, id> oppoOtmMap = new map<id, id>();
            list<id> proMemList = new list<id>();
            map<id, id> oppIdProIdMap = new map<id, id>();
            list<id> proId = new list<id>();
            Map<Id,Opportunity> oppIdMap = new Map<Id,Opportunity>();
            Map<id, id> oppIdAccIdMap = new Map<id, id> ();
            Set<id> accId=new Set<Id>();
            
        for(OpportunityTeamMember otm : trigger.new){
                        OppoIdList.add(otm.OpportunityId);
                        oppoOtmMap.put(otm.Id, otm.OpportunityId);
            }
        
        map<id, list<Project__c>> oppIdProjectListMap = new map<id, list<Project__c>>();
        list<Opportunity> oppoList = [select Id, accountId, Project__c, (Select Id, Name from Project__r) From opportunity Where Id In: oppoIdList];
        system.debug('--oppoIdList--' +oppoIdList);
        for(Opportunity op : oppoList){
            proId.add(op.id);
            oppIdMap.put(op.id,op);
            accId.add(op.accountId);
            oppIdAccIdMap.put(op.id, op.accountId);
           // oppIdProIdMap.put(op.id, op.Project__c);
            oppIdProjectListMap.put(op.id, op.Project__r);
            }
                
        list<Project_Team__c> ptmListForInsert = new list<Project_Team__c>();
        system.debug('--proId--' +proId);
        system.debug('--accId--' +accId);
        system.debug('--oppIdProIdMap--' +oppIdProIdMap);
        system.debug('--oppIdAccIdMap--' +oppIdAccIdMap); 
        
        list<Project_Team__c> ptmList = [Select id, Account__c, Project__c, Member_Role__c, Team_Member__c From Project_Team__c Where Id In: proId];
        map<id, list<Project_Team__c>> proPtmMap = new map<id, list<Project_Team__c>>();
        
        for(project_Team__c ptm : ptmList){
        
            list<project_Team__c> tempList = proPtmMap.get(ptm.Project__c);
            
            if(templist!= null && templist.Size()>0){
                tempList.add(ptm);
                }else{
                        tempList = new list<project_Team__c>();
                        tempList.add(ptm);
                }
                proPtmMap.put(ptm.Project__c, tempList);
            }
        
        for(OpportunityTeamMember otm : trigger.new){
        
            Boolean flag = false;
           
            List<project__c> listOfProj = oppIdProjectListMap.get(otm.OpportunityId);
            
            for(Project__c pro : listOfProj){
            List<project_team__c> listOfPrjTm = proPtmMap.get(pro.id);
            
            
            if(listOfPrjTm!= null){
                for(Project_Team__c ptm : listOfPrjTm){
                    if(otm.userId == ptm.Team_Member__c){
                        flag =true;
                        }
                    }
                }
                if(flag ==true){
                }else{
                    Project_Team__c ptm1 = new Project_Team__c();
                    ptm1.Team_Member__c= otm.userId;
                    ptm1.Member_Role__c = otm.TeamMemberRole;
                    ptm1.Account__c = oppIdAccIdMap.get(otm.OpportunityId);
                    ptm1.Project__c = proPtmMap.get(otm.OpportunityId);
                    ptmListForInsert.add(ptm1);
                    system.debug('--ptm1--' +ptm1);
                    }
            }}
        if(ptmListForInsert.size()>0){

        insert ptmListForInsert;
            }
            
  }
}
User-added image

Component code:

<apex:component >
<h1>Address</h1>
<p>First Name: {!$User.FirstName}</p>
<p>Last Name: {!$User.LastName}</p>
<p>Phone: {!$User.Phone}</p>
<p>Email: {!$User.Email}</p>
<p>Address:{!$User.Address}</p>
</apex:component>

Visualforce Page:

<apex:page standardController="sobject">
<center>
<c:componentname ></c:componentname>
</center>
</apex:page>
Hi,

I am a Trainee in VF development. Stucked in between one assignement. Please suggest me solution to fulfill below requirement. 

Requriment: User should be able to select an Account, based on the selected Account, show Account’s Name, Industry and Type in new section.
 
<apex:page controller="AccountDetails">

<script type="text/javascript">
    function getRemoteAccount(){
        alert(document.getElementById("form1.accName"));//Unable to access selected value
    }

</script>
 <apex:form id="form1">
 <apex:pageblock >
     <apex:pageblockSection >
         <apex:inputField value="{!acc.AccountId}" id="accName" onchange="getRemoteAccount()"/>
     </apex:pageblockSection>
     <apex:pageBlockSection >
     <span id="span1" />
     </apex:pageBlockSection>
 </apex:pageblock>
 </apex:form>
</apex:page>
 
/************Controller*********************/

public class AccountDetails {

    public contact acc { get; set; }
}

 
Hello,

I have added a css like below on a input field like below
 
<apex:inputField value="{!caseObj.AccountId}" styleClass="CSS_required"/>

.CSS_required{border-left: 3px solid red;}


it is dispplayed like:

User-added image
How can i move the red bar to the left ?
  • December 29, 2016
  • Like
  • 0
Hello,

I want to know is there a way to expire refresh tokens manually through apex code. If yes, how to to do it?
Can someone help me with showing notifications like success/error/warning on lightning modal by firing toastevent
Hello,

I have a requirement to embed the standard home page into my custom Lightning App(Coded). Can this be done. If yes, how?
Hi,

I have to display records to users as per territory hierarchy.

For example,
I have Object A - OWD is set to private.
Below is the type of Territory hierarchy

Territory 1(T1) -- > Territory 2(T2) -- > Territory 3(T3) --Territory 4(T4)

Here, Territory 2 is child of Territory1 , Territory 3 is child of Territory 2 and so on

Now, I wand the records created by  Territory 4 to be accessible to T1, T2 and T3.
Records created by T3, should be accessible to the users belonging to T1 and T2 and so on.

I am able to achieve this by creating sharing rules for the object, but here i need to create separate sharing rules for to share records with each of the territories above in the hierarchy.

Can we not achieve this as we do in role hierarchy?.

Inside each territory record, we have sharing groups: Territory,Territory, Territory and Subordinates. Can these be used some how to achieve this?

 
Create a validation rule to check that a contact is in the zip code of its account.
To complete this challenge, add a validation rule which will block the insertion of a contact if the contact is related to an account and has a mailing postal code (which has the API Name MailingPostalCode) different from the account's shipping postal code (which has the API Name ShippingPostalCode).
Name the validation rule 'Contact must be in Account ZIP Code'.
A contact with a MailingPostalCode that has an account and does not match the associated Account ShippingPostalCode should return with a validation error and not be inserted.
The validation rule should ONLY apply to contact records with an associated account. Contact records with no associated parent account can be added with any MailingPostalCode value. (Hint: you can use the ISBLANK function for this check)
Is there any way to remove hyperlink for Frorm  Address?
User-added image
<apex:column value="{!email.FromAddress}" headerValue=" From Address"/>
Thanks in Advance,
Deepak
 
In such case will a Manager be able to see records of a object on which OWD is Private and he does not own those records.
Dropbox is only syncing all the existing information in salesforce. Upon creation of a new opportunity the folders under dropbox in SF are no longer auto creating and not connecting to the dropbox. Certain projects only a few of the required folders are being populated. Folder is not creating in dropbox either. Would this be more of Salesforce issue or Dropbox? 
m trying to callout thru schedulable and batch class...m stuck in  Too many callouts: 101 ...plz help
public class SchedulerForPostApex implements Schedulable{
    public void execute(SchedulableContext sc){
        system.debug('*******Going to call future method ');
        Postbatchclass  batchapex = new Postbatchclass();
        id batchprocessid = Database.executebatch(batchapex,1);
system.debug('Process ID: ' + batchprocessid);
  
        
    }
}

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

global class Postbatchclass implements Database.Batchable<sObject>,Database.AllowsCallouts {

Public String query;
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        query = 'select id, Name, SOCi_Id__c FROM Account where SOCi_Id__c != null'; //need to define query
        return Database.getQueryLocator(query);

  
    }
     global void execute(Database.BatchableContext BC, List<Account> scope) {
     
         FOR(Account sr : scope){
           PostsRequest.getpostsCalloutResponseContents(sr);
       }
         
      }
      global void finish(Database.BatchableContext BC){
      }
}

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

public class PostsRequest { 
    
    private static final String API_KEY = 'apikeyy';     
    
    //@future(callout=true)
    public static void getpostsCalloutResponseContents(Account ac) {  
    Http h;
    HttpRequest req;
    HttpResponse res;

    //String finalResult = '';
    Map<String, List<PostClass>> WrapperPostMap = new Map<String, List<PostClass>>();
    List<Account> alist = [select id, Name, SOCi_Id__c FROM Account where SOCi_Id__c != null];  
    List<PostClass> WrapperPostList = new List<PostClass>(); 
    for (Account a : alist) {
        String result = null;                        
        h=new Http();
        req=new HttpRequest();
        req.setEndpoint('endpoint' + a.SOCi_Id__c + '/get?since=2011-01-01&api_key=' + API_KEY);
        req.setMethod('GET');
        res = h.send(req);
        if(res.getStatusCode() == 200){
            result = res.getBody();
          }        
      
            
        List<Object> resultList = (List<Object>) JSON.deserializeUntyped(res.getBody());              
      
        if(resultList != null){
          for (Object entry : resultList) {
                 WrapperPostList.add((PostClass)(JSON.deserialize(JSON.serialize(entry),PostClass.class)));
            }
          }
                WrapperPostMap.put(a.id, WrapperPostList);
          
                System.debug('The WrapperPostListid List value size is: ' + WrapperPostList.size()); 
      h=null;
        req=null;
        res=null;    
    
      } 
        
         System.debug('The WrapperPostListid List value is: ' + WrapperPostList);
         System.debug('The WrapperPostListid List value size is: ' + WrapperPostList.size());
        
        for (Account a : alist) {                
              makeCallout(WrapperPostMap.get(a.Id), a.id);
          }
        
    }    
  
    public static void makeCallout(List<PostClass> WrapperPostList, String aid) {
        String result = null;       
                  
       
      
             System.debug('The WrapperPostList list is: ' + WrapperPostList); 
        Set<String> postIds = new Set<String>();
        for (PostClass f : WrapperPostList) {
            postIds.add(f.id);
        }

        Map<String, Post__c> posts = new Map<String, Post__c>();
        Map<String, Post__c> newposts = new Map<String, Post__c>();
        for (Post__c p : [
                select Id, Name, SOCi_Post_Id__c
                from Post__c
                where SOCi_Post_Id__c in :postIds
                ]) {
            posts.put(p.SOCi_Post_Id__c, p);
        }


        for (PostClass f : WrapperPostList) {
            Post__c p;
            if (posts.containsKey(f.id)) {
             
            } else {
                
                p = new Post__c(SOCi_Post_Id__c = f.id, Account__c = aid);
                p.Name = f.network +' '+ 'Post';
                p.Date_Scheduled__c = Date.valueOf(f.created_at);
                p.Created_By__c = f.created_by_name;
                p.Post_Date__c = Date.valueOf(f.schedule);
              //  p.Channel__c=f.remote_network_id;
              //  p.Channel__c = [SELECT id from Channel__c where Account__r.SOCi_Id__c =: f.project_id and Type_of_Channel__c =: f.network LIMIT 1].id;
        newposts.put(f.id, p);
            }
            
          
        }

     insert newposts.values();
                     
  }
  
   
    class PostClass {
        public String id;
        public String project_id;
        public String network;
        public String created_by_name;
        public String schedule;
        public String created_at;
       // public String remote_network_id;
        
    }


 
}
  • September 28, 2017
  • Like
  • 0
HI 

Please help me to integrate from saleforce to twitter using Rest API.
I have created Twitter app and ganerated consumer key and secretkey.

I have follow the below link:-
https://developer.salesforce.com/forums?id=906F00000005KOwIAM

1) In the we have class please explain the what is "code" here .
2) PageReference pg = new PageReference('https:// Please_PUT HERE TwitterAuthorizeURL ?response_type=code&client_id=Put client id&redirect_uri=YOUR CALL BACK URL') ;
tell me how to replace the bold values, please give me clarity.
same thing for below line :-
String tokenuri = 'https://PLEASE PRovide api hit url of twitter?grant_type=authorization_code&code='+code+'&redirect_uri=YOUR CALL BACK URL';  


Thanks
Satheesh k
This is a standard component of activity But I want to make same component as a custom component with different tabs? If Any Help, it would be greatly appreciated. Thanks in Advance. 
My code looks like this:

component
<lightning:select label="SalesUnit" variant="label-hidden" aura:id="SalesUnit__c" value="{!v.item.SalesUnit__c}" class="LIGHTNING_SELECT_SIZE">
                    <aura:iteration items="{!v.SalesUnit__c}" var="opt">
                        <option value="{!opt.text}" >{!opt.label}</option>
                    </aura:iteration>
                </lightning:select>

serverside
for(UOM__c uom : uomList){
            SelectOption so = new SelectOption(uom.UOM_UOM__c, uom.Id);
                 optionList.add(so);
        }


I want to change default value 'MT' to 'KG'. How can I do??
User-added image
 
hi,
I have a favourite button which fetches the items which has been ordered more than twice.
This is my controller

    Public List<Menu__c> favmenu {get;set;}
     favmenu = [select id, name,Category__c,Description__c,Image__c,ImageURL__c,Dish_Name__c,Price__c,
                 Special_Dish__c,Status__c,SubCategory__c,veg_non_veg__c,remarks__c from Menu__c where id IN : menuIdList]; 
           
           if(favmenu.size()>0)
               nofavourites = 'Choose from your favourites';
           else
                nofavourites='No favourites yet';

When i m testing for favmenu.size()>0 ..... it is working fine....but for the else part, when the soql query is not fetching any item, it is showing the error
Attempt to de-reference a null object 
An unexpected error has occurred. Your development organization has been notified.
  • September 21, 2017
  • Like
  • 1
Can someone help me with showing notifications like success/error/warning on lightning modal by firing toastevent
how to raise ticket in salesforce 
window.open('/apex/QuoteTemplate?id={!Quote.Id}','_blank','height=600,width=800,Window Position=center');
how to use window position??
I would like to show them a video from lead to closure showing features and how to do?

I am not happy so far it’s even difficult to find a category to post.

Thanks

Mike
Hi everyone
scenario
suppose we have two objects 1.item and 2.bill
object item has 4 fields
field1-name
field2-quantity
field3-price
field4-bill(look up relationship with custom object bill).
now bill is another custom object with fields
customer name and
total amount
now i need to write trigger to calculate total amount in the bill object

example we buy 2 soaps of $10
and 2 shirts of $100
so total amount would be 20 + 200 =220

anyone plz help..

Hi All,
I am trying to download csv file when i click on button. But when i click button i am getting like this in csv file.

{"index":93 name:"HideProfileElvVideo" value:false}. Below is my code

VF Page:

<apex:page controller="MyCustomListViewController" contentType="application/vnd.ms-excel#filename.csv">{!header}
<!-- <apex:pageBlock >
<apex:pageBlockTable value="{!Contacts}" var="contact" id="pbt"> 
<apex:column >
<apex:outputField value="{!contact.con.Name}"/>
</apex:column>

<apex:column >
<apex:outputField value="{!contact.con.Account.name}"/> 
</apex:column>
<apex:column >
<apex:outputField value="{!contact.con.Phone}"/>
</apex:column> 
<apex:column >
<apex:outputField value="{!contact.con.Email}"/>
</apex:column> 
</apex:pageBlockTable> 
</apex:pageBlock> -->
<!-- <apex:repeat value="{!Contacts}" var="contact" >
{!contact.con.Name},{!contact.con.Account.name},{!contact.con.Phone},{!contact.con.Email}
</apex:repeat> -->

<apex:pageBlock >
<apex:pageBlockTable value="{!Contacts}" var="contact" id="pbt"> 
{!contact.con.Name},{!contact.con.Account.name},{!contact.con.Phone},{!contact.con.Email}

</apex:pageBlockTable> 
</apex:pageBlock> 
</apex:page>

@RestResource(urlMapping='/listRevenueProfile/*')

global with sharing class RESTRevenueprofileController {

@HttpGet
  global static List<Revenue_Profile__c> fetchRevenue()
  {    
     list<Revenue_Profile__c>lst1=new list<Revenue_Profile__c>();
   
   lst1=[Select Aug_17__c,Apr_17__c,January_2020_Sales_Updated__c,January_2021_Sales_Updated__c,July_2016_Sales_updated__c,July_2017_Sales_Updated__c,July_2018_Sales_Updated__c,July_2019_Sales_Updated__c,July_2020_Sales_Updated__c,June_2017_Sales_Updated__c,June_2018_Sales_Updated__c,June_2019_Sales_Updated__c,June_2020_Sales_Updated__c,June_2021_Sales_Updated__c,March_2017_Sales_Updated__c,March_2018_Sales_Updated__c ,
        March_2019_Sales_Updated__c,March_2020_Sales_Updated__c,March_2021_Sales_Updated__c,May_2017_Sales_Updated__c,May_2018_Sales_Updated__c,May_2019_Sales_Updated__c,May_2020_Sales_Updated__c,May_2021_Sales_Updated__c,November_2016_Sales_Updated__c,November_2017_Sales_Updated__c,November_2018__c,November_2019_Sales_Updated__c,November_2020_Sales_Updated__c,October_2016_Sales_Updated__c,October_2017_Sales_Updated__c,
        October_2018_Sales_Updated__c,Jun_19__c,Jun_20__c,Jun_21__c,Mar_17__c,Mar_18__c,Mar_19__c,Mar_20__c,Mar_21__c,May_17__c,May_18__c,May_19__c,May_20__c,May_21__c,Nov_16__c,Nov_17__c,Nov_18__c,Nov_19__c,Nov_20__c,Oct_16__c,Oct_17__c,Oct_18__c,Oct_19__c,Oct_20__c,Sep_16__c,Sep_17__c,Sep_18__c,Sep_19__c,Sep_20__c from Revenue_Profile__c WHERE CreatedDate >=2015-07-01T00:00:00Z];
    System.debug('----lst1----'+lst1);
    
    return lst1;
    
     list<Revenue_Profile__c>lst=new list<Revenue_Profile__c>();
   lst=[Select Opportunity_id__c,X18_Digit_Opportunity_ID__c,April_2017_Sales_Updated__c,April_2018_Sales_Updated__c,April_2019_Sales_Updated__c,April_2020_Sales_Updated__c,April_2021_Sales_Updated__c,August_2016_Sales_Updated__c,August_2017_Sales_Updated__c,August_2018_Sales_Updated__c,August_2019_Sales_Updated__c,August_2020_Sales_Updated__c,
        December_2016_Sales_Updated__c,December_2017_Sales_Updated__c,October_2019_Sales_Updated__c,October_2020_Sales_Updated__c,September_2016_Sales__c,September_2017_Sales_Updated__c,September_2018_Sales_Updated__c,September_2019_Sales_Updated__c,September_2020_Sales_Updated__c,Apr_18__c,Apr_19__c,Apr_20__c,Apr_21__c,Aug_16__c,Aug_18__c,Aug_19__c,Aug_20__c,Dec_16__c,Dec_17__c,Dec_18__c,Dec_19__c,Dec_20__c,Feb_17__c,Feb_18__c,     
        Feb_19__c,Feb_20__c,Feb_21__c,Jan_17__c,Jan_18__c,Jan_19__c,Jan_20__c,Jan_21__c,Jul_16__c,Jul_17__c,Jul_18__c,Jul_19__c,Jul_20__c,Jun_17__c,Jun_18__c,December_2018_Sales_Updated__c,December_2019_Sales_Updated__c,December_2020_Sales_Updated__c,February__c,February_2018_Sales_Updated__c,February_2019_Sales_Updated__c,February_2020_Sales_Updated__c,February_2021_Sales_Updated__c,January_2017_Sales_Updated__c,January_2018_Sales_Updated__c,January_2019_Sales_Updated__c from Revenue_Profile__c WHERE CreatedDate >=2015-07-01T00:00:00Z];
      System.debug('----lst----'+lst);
    return lst;
   
 } 
}
https://help.salesforce.com/articleView?id=000176969&type=1 (not work for me)