• Subhash Garhwal
  • SMARTIE
  • 638 Points
  • Member since 2013
  • Technical Architect
  • Fexle Services


  • Chatter
    Feed
  • 20
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 103
    Replies
trigger trgset on contact (after insert)

{
    List<Contact> conToUpdate = new List<Contact>() ;
     for(Account acc : [Select Name,(Select id ,LastName from Contacts where id in: trigger.new ) from Account  ] )
     {
     for(Contact con : acc.Contacts)
     {
     con.LastName = acc.Name ;
     conToUpdate.add(con) ;
     }
    }
    if(conTOUpdate.size() > 0)
    {
       update conTOUpdate ;
    }
}


how can i restrict the code for a particular account only ...like if ther are 1000 account it will pick all ..how do i restrict it for a particular account ... in the suquery
is this right ??
for(Account acc : [Select Name,(Select id ,LastName from Contacts where id in: trigger.new ) from Account  wher account.id==contact.id] )
Hi all,

I written one trigger and test class getting this error. 
System.TypeException: Invalid id value for this SObject type

Trigger:-
----------

trigger EscalateCase on Escalation__c (after update) {
IF(Trigger.size > 1){return;}
IF(Trigger.new[0].Reason_For_Escalation__c == null || Trigger.new[0].Escalation_Comments__c == null || Trigger.new[0].Escalate_To_Management__c == false || Trigger.new[0].Case__c == null){return;}
Case c = new case(ID = trigger.new[0].Case__c, Escalate_To_Management__c = trigger.new[0].Escalate_To_Management__c, Reason_For_Escalation__c = trigger.new[0].Reason_For_Escalation__c, Escalation_Comments__c = trigger.new[0].Escalation_Comments__c);
update c;
}

Test class:-
--------------

@isTest
private class EscalateCaseTestClass{
@isTest static void Esc(){

Account a = new Account(Name='ContractBookingPeriodProcessingTest',Geography__c='TestGeography',
        Territory_Id__c='TestTerritory',
            Territory_Overlay__c='TestTerritoryOverlay',Renewals_Team__c='TestRenewalsTeam',
            Renewals_Account_Manager__c='TestRenewalsAccountManager');
        insert a;
        Contract c = new Contract(AccountId=a.id,Number_of_Booking_Periods_Records__c = 0, Number_of_Booking_Periods__c = 1,
                                    Status='Create', Finance_Charges__c ='0.5%',
                                    Contract_Term_Start_Date__c=date.valueOf('2013-01-01'),
                                    Contract_Term_End_Date__c=date.valueOf('2099-12-31')                    
                                    );
        insert c;

Case case1 = new case(Id=a.id,Escalate_To_Management__c =true,Reason_For_Escalation__c = 'TestReason' ,Escalation_Comments__c = 'TestEscalation' );
insert case1;

case1.Reason_For_Escalation__c = 'TestReasonForEscalation';
case1.Escalation_Comments__c = 'TestEscalationComments';
update case1;
}
}

Thanks
kumar
I am building a Visualforce page for the Opportunity custom console. I want to build a page with the basic contact information, how do I get the contact fields? I created a lookup(Contact) on the Opportunity
<apex:page standardController="Opportunity"  showheader="false" >
    <apex:form >
    <apex:pageBlock >
    
         <apex:pageBlockSection collapsible="false" columns="5">
             <apex:pageblocksectionItem >
             <apex:inputField value="{!Contact.Email}"/>
             </apex:pageblocksectionItem>
             
         </apex:pageBlockSection>  
         
    </apex:pageBlock>
    </apex:form>
        
</apex:page>
How can I modify this?

Thanks

Hello Everybody,
       I am new to the salesforce and I need to know about Visualforce page in salesforce so can anyone me the  give me the videos for visualforce 

Please Help
trigger copystreetaddress on Join_object__c(after insert)
{
list<contact> conlist=new list<contact>();    
    if(trigger.isUpdate)
    {
        Set<Id> accountId = new Set<Id>();
        Set<Id> contactId = new Set<Id>();
        for(Join_object__c tempJ : Trigger.new)
        {
            accountId.add(tempJ.Account__c);
            contactId.add(tempJ.Contact__c);
        }
       
        List<Account> AccountList = [Select id,Name,BillingStreet from Account where id in: accountId];
       
        List<Contact> ContactList = [Select id,Name,mailingStreet from Contact where id in: contactId];
       
        for(Join_object__c tempJ : Trigger.new)
        {
            for(Account tempAcc : AccountList)
            {
                if(tempJ.Account__c == tempAcc.Id)
                {
                    for(Contact tempCon : ContactList)
                    {
                        if(tempJ.Contact__c == tempCon.Id)
                        {
                            tempCon.mailingstreet = tempAcc.BillingStreet;
                            conlist.add(tempcon);
                        }                  
                   
                    }
               
                }
           
            }  
           
        }      
          
    }
     update ConList;  
}
This Trigger that I have written isn't working correctly.  What i am trying to do is get a list of the users that includes ID and Salesman Number.  Then I trying to update the account with the new user ID.  Currently nothing is changing, once I click edit and I don't know why.

thanks.

kevin

trigger AccountOwnerUpdateTrigger on Account (before insert, before update) {

    // this map will contain a list of Accounts with the same salesman #
    Map<String, List<Account>> AccountOwnerMap = new Map<String, List<Account>> ();
    for( Account Acc : trigger.new ) {
        // create the list if it doesn't already exist
        List<Account> AcctList = AccountOwnerMap.get( Acc.Ownerid );
        if( AcctList == null ) {
            AcctList = new List<Account>();
        }
        AcctList.add( Acc );
        AccountOwnerMap.put( Acc.OwnerID, AcctList );
    }

    // get list of CURRENTLY ACTIVE Users using the field Salesman_Number__c
   
    List<User> UserList = [
                        SELECT ID, Salesman_Number__c
                        FROM User
                        WHERE ID IN :AccountOwnerMap.keySet() AND IsActive = True ];
              
                                          
    // go through the User List and get a list of Accounts that have the same salesman
    for( User User : UserList ) {
        List<Account> AcctList = AccountOwnerMap.get( User.ID );

        // assign the Account Owner for each Account in the list
        for( Account Acc : AcctList )
        Acc.Ownerid = User.ID;
        }
}
Trying to create this VR on the record types shown in the code. 

The idea is for only these 3 record types to trigger the VR when the picklist "Stage equals Conversion" and if the field "Total_Annual_Sqft_Interior__c" is left blank, it wll not allow the user to save the record, unless there is a value in the "Total_Annual_Sqft_Interior__c" field. 

So, when I log in as a user, the validation rule seems to be triggered by any Opportunity Record type. 

Can someone help me tweak this?

Please note, the  "NOT($Profile.Name ="System Administrator")", is good on this VR, since I want to omit myself from this VR.

Thanks in advance!


RecordTypeId = "012d0000000WK8O" /*Interior Contractor*/ ||
RecordTypeId = "012d0000000We79" /*Interior Dealer/Distributor*/ ||
RecordTypeId = "012d0000000WWPM" /*Interior Quick Convert Opportunity*/
&&
ISPICKVAL(StageName, "Conversion")
&&
ISBLANK(Total_Annual_Sqft_Interior__c)
&&
NOT($Profile.Name ="System Administrator")


Hi Buddies,

I have a scenario based on the triigger, i.e, compare old and new values if it is changed send a mail to group of users.
It is not only for a single field, its for all fields i.e, mostly 200 fields.

So for this am using dynamic apex and comparing all fields, but I was not able to compare.

Map<String,Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
          Schema.SObjectType leadSchema = schemaMap.get('Order__c ');
          Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();

for (String fieldName: fieldMap.keySet()) {                    
                        for(Order__c w:Trigger.New){
                            string subject='';
                            string body='Changed Values for Record: '+w.name;  
                            if(Trigger.oldMap.get(w.id).fieldName!=Trigger.newMap.get(w.id).fieldName){ -->Error Line
                              body='<p>Hi,</p>';
                              body+='Your Record: '+w.name+' , Got changes value from <b>'+Trigger.oldMap.get(w.id).fieldName;
                              body+='</b> to <b>'+Trigger.newMap.get(w.id).fieldName;
                              mail.setHtmlBody(body);
                              mail.setSubject(subject);
                              allMails.add(mail);
                              Messaging.sendEmail(allMails);
                            }
                        }
                   }

Error is like : Error: Compile Error: Invalid field fieldName for SObject Order__c at line 69 column 76

its because, Trigger.oldMap.get(w.id).fieldName only. How can i pass this?
I need to map the Primary Contact's last name to a custom text field on the opporunity record. I found the below trigger in a forumn that seems to work -although it maps the contact's full name. Although it maps the name correctly, it now creates an error when converting a lead. Error message below. I'm not a developer and new to triggers so I'm hoping someone can help me with this issue.

1) Can I map just the last name only?
2) Can the lead conversion error be fixed?

Lead Conversion Error:
Error: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ContactRoleName: execution of BeforeUpdate caused by: System.QueryException: List has no rows for assignment to SObject Trigger.ContactRoleName: line 5, column 1: [] (System Code)

Trigger:
Trigger ContactRoleName on Opportunity(before update)
{OpportunityContactRole Roles = new OpportunityContactRole();
for(Opportunity o:Trigger.new)
{
Roles = [select Id,IsPrimary,Contact.Name, Contact.Email, Contact.Phone from OpportunityContactRole where opportunity.id=:o.Id];
o.Primary_Contact_Name__c = Roles.Contact.Name;
}
}
Hi,

Below given is my code and it is not the complete  .

I have Reservation object and invoice .When somebody registers with us ,Invoice for that customer should be automatically created as child object.

I have lookup relationship beyween invoice and Reservation.

I want to get all the invoices associate with the particular registration.Since reservation__ is the paretn object and invoice is the child,therefore,i am trying the following query in the code.However,I get the folowing error.

Compile Error: Didn't understand relationship 'reservation__r' in field path. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 166 column 49

Can somebody please help?


list<Reservation__c>pc=new List<Reservation__c>([select id,(select id from reservation__r.invoice__c)from reservation__c where reservation__c in:samp])



 


trigger  reservation on reservarion__c(before delete
{
Map<id,invoice__c>must=new Map<id,invoice__c>();
list<invoice__c>ok=new list<invoice__c>();
If(Trigger.IsBefore & Trigger.IsDelete)
{
//Map<id,invoice__c>must=new Map<id,invoice__c>();
//list<invoice__c>ok=new list<invoice__c>();
Set<id> samp=new set<id>();
For(reservation__c r:trigger.old)
{

samp.add(r.id);
System.debug('The values in the record of delete trigger of the samp is##########################'+samp);
}

list<Reservation__c>pc=new List<Reservation__c>([select id,(select id from reservation__r.invoice__c)from reservation__c where reservation__c in:samp])
}
hi,

  Can any one help me to pass the value in select option

Apex Class:

public class HousingOpportunity
{
    public Housing_Resource_Opportunity__c objHrsOpp {get; set;}
    //private String soql{get;set;}
    public HousingOpportunity()
    {
        objHrsOpp = new Housing_Resource_Opportunity__c();
   
    }
   
   public string selectBuildingname{get;set;} 

    public list<selectOption> getBuildingname()
    {
        list<selectOption> options = new list<selectOption>();
        options.add(new selectOption('','-None-'));
        list<Housing_Resource__c> houres= [Select Id,Name from Housing_Resource__c]; 
        Set<String> strUniq = new Set<String>();        
        for(Housing_Resource__c hr : houres)
        {
             if(strUniq.add(hr.Name.touppercase()))
             {
               options.add(new selectOption(hr.Name,hr.Name));
               system.debug('BuildingName--------------'+options);
             }
        }
       
        return options;
    }
 
     public string selectroomnameandnumber{get;set;}
     public List<selectOption> getroomnameandnumber()
     {
  
        List<selectOption> options = new List<selectOption>();
        options.add(new selectOption('','-None-'));
         system.debug('selectBuildingname@@@@@@@@@@@@@@@@@@@@@'+selectBuildingname);
        if(selectBuildingname != null)        // Its not covered from this line  value passing is null
        {

        String hrsSQL = 'Select Room_Name_and_Number__c from Housing_Resource__c  where Name=:selectBuildingname AND Room_Name_and_Number__c!=null';
            List<Housing_Resource__c> houres = Database.query(hrsSQL);
             //system.debug('roomnameupdown'+hrsSQL);
            for(Housing_Resource__c hr : houres)     
            {
                options.add(new selectOption(hr.Room_Name_and_Number__c,hr.Room_Name_and_Number__c ));  
            }
           
           
       } 
    
       return options;
     }
}


Test class:


@isTest
public class HousingOpportunityTestClass
{
    public static TestMethod void HousingOpportunityTestClass()
    {
         PageReference ref = Page.HousingOpportunity;
        Test.setCurrentPage(ref);
        system.debug('Test---------'+ref);

        Housing_Resource__c HousingResouce = new Housing_Resource__c(Name ='TestBuildName', Room_Name_and_Number__c = 'BN101');
        insert HousingResouce;
        
     
            ApexPages.currentPage().getParameters().put('selectBuildingname',HousingResouce.Name); 
           
            HousingOpportunity thehousopp = new HousingOpportunity();
        
      
         thehousopp.getBuildingname();
    
         thehousopp.getroomnameandnumber();

 }
 
}
  • March 21, 2014
  • Like
  • 0

 

Hi Developers , 

 

Can any one help me on this requirement .

 

i have a requirement , in an Account object i have 10000 records and picklist field with the values as 10,20,30,40 ,50.i would like to fetch the records for the picklist value as 10.how do u query on this?

 

Thanks In Advance

  • December 09, 2013
  • Like
  • 0

Hi All,

 

I have 4 batch class and execute one by one like

 

batch1,batch2,batch 3,Batch4 

 

my requirement is starting the  Batch1 class  after this one completed then I have to start next batch 2 then batch3 and batch 4.

 

How to handle this situtation in my batch class? Give me some scenario......

 

 

Thanks,

 

 

Vicky

 

 

I am trying to concatentate a text field with a date without including the time and am getting an error: Method does not exist or incorrect signature: [Date].format(String)

 

     Date NewDate = Camp.Startdate;

// Line below gives CampName2013-12-02 00:00:00
        NewCamp1.Name = camp.name + NewDate;


// Line below gives error: Method does not exist or incorrect signature: [Date].format(String)
       NewCamp1.Name = camp.name + NewDate.format('MM/dd/yyyy');

What am I doing wrong?

 

Thanks, Michele

Hi, 

 

I got the following class with testmethod that does not support service call out. 

I trying to change the testmethod to use mock responce but i must admin i'm quite new to apex... 

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

 

can someone please help ? 

thank you, 

Julien

 

/**
 * An apex page controller that exposes the site login functionality
 */
global with sharing class PortalLoginController 
{
  private User userRecord;
  
    global String OrgId            {get; private set;}
    global String CustomerPortalHostname {get; private set;}
    global String CustomerPortalId     {get; private set;}
    global String PartnerPortalHostname  {get; private set;}
    global String PartnerPortalId       {get; private set;}
    global String StartUrl         {get; private set;}    
    global Boolean IsPartner         {get; private set;}
  global String Username         {get; set;}
    global String Password         {get; set;}
    
    global PortalLoginController() 
    {
        this.OrgId = UserInfo.getOrganizationId(); 
        this.IsPartner = false;        
        
        loadPortalInfo();        
    }
    
    private void loadPortalInfo()
    {
      List<SitesToPortalsRedirectSettings__c> settings = SitesToPortalsRedirectSettings__c.getAll().values();
      
      if(settings.size() == 0 || settings.size() > 2)
      {
        if(settings.size() > 2)
        {
          throw new CustomException('Too many portals have been setup in the SitesToPortalsRedirectSettings custom setting.');
        }
        else
        {
          throw new CustomException('No portals have been setup in the SitesToPortalsRedirectSettings custom setting.');
        }  
      }
      
      Integer partnerPortalCount = 0;
      Integer customerPortalCount = 0;
      
      for(SitesToPortalsRedirectSettings__c setting : settings)
      {
        if(setting.Is_Partner_Portal__c == true)
        {
          partnerPortalCount++;
        }
        else
        {
          customerPortalCount++;
        }
      }
      
      if(partnerPortalCount > 1)
      {        
        throw new CustomException('Too many partner portals have been setup in the SitesToPortalsRedirectSettings custom setting.');      
      }
      
      if(customerPortalCount > 1)
      {        
        throw new CustomException('Too many customer portals have been setup in the SitesToPortalsRedirectSettings custom setting.');      
      }
      
      //If we get here, all checks above passed
      for(SitesToPortalsRedirectSettings__c setting : settings)
      {
        if(setting.Is_Partner_Portal__c == true)
        {
          this.PartnerPortalHostname = setting.Portal_Hostname__c;
            this.PartnerPortalId = setting.Portal_Id__c;
        }
        else
        {
          this.CustomerPortalHostname = setting.Portal_Hostname__c;
            this.CustomerPortalId = setting.Portal_Id__c;
        }
      }
    }
    
    private void LoadUserRecord()
    {
      List<User> userRecords = [select Id, UserType from User where Username = :Username];
      
      if(userRecords.size() != 1)
      {
        return;
      }
      
      this.userRecord = userRecords[0];
      
      if(userRecord == null)
      {
        throw new CustomException('No user was found for username: ' + Username);
      }
      
      if(userRecord.UserType != null && userRecord.UserType.trim().length() > 0)
      {
        if(userRecord.UserType.trim().equalsIgnoreCase('PowerPartner') == true)
        {
          this.IsPartner = true;
        }
        else
        {
          //Assume customer portal user
        }
      }
      else
      {
        //Should never see this but there just in case
        throw new CustomException('No UserType has been specified for the user with a username of ' + Username);
      }
    }     
    
    //This ensures we have a protocol and the trailing slash at the end of the hostname
    private String getCleanedHostname(String hostname)
    {
      if(hostname == null || hostname.trim().length() == 0)
      {
        throw new CustomException('getCleanedHostname - A hostname is required');
      }
      
      if(hostname.trim().startsWith('http://') == false || hostname.trim().startsWith('https://') == false)
      {
        //Assume SSL
        //hostname = 'https://' + hostname;
      }
      
      if(hostname.trim().endsWith('/') == false)
      {
        hostname = hostname + '/';
      }
      
      return hostname;
    }   

    global PageReference login() 
    {
      loadUserRecord();
        
        this.StartUrl = System.currentPageReference().getParameters().get('startURL');
        
        String hostname = null;
        String portalId = null;
        String urlString = null;
        
        if(StartUrl == null || StartUrl.trim().length() == 0)
        {
            List<String> values = new List<String>();
            
            if(IsPartner == true)
            {
              hostname = PartnerPortalHostname;
              portalId = PartnerPortalId;
              urlString = '{0}secur/login_portal.jsp?orgId={1}&portalId={2}&un={3}&pw={4}';
            }
            else
            {
              hostname = CustomerPortalHostname;
              portalId = CustomerPortalId;
              urlString = '{0}secur/login_portal.jsp?orgId={1}&portalId={2}&un={3}&pw={4}';
            }
            
            hostname = getCleanedHostname(hostname);
            
            values.add(hostname);
            values.add(orgId);
            values.add(portalId);
            values.add(username);
            values.add(password);                                                
            
            this.StartUrl = String.format(urlString, values);
        }
        
        System.debug('### START URL = ' + StartUrl);
        
        HttpRequest request = new HttpRequest();
        
        request.setEndpoint(StartUrl);
        request.setMethod('GET');
        
        /*      
        Blob headerValue = Blob.valueOf(username + ':' + password);
        
        String authorizationHeader = 'BASIC ' +
        
        EncodingUtil.base64Encode(headerValue);
        
        req.setHeader('Authorization', authorizationHeader);
        */
        
        Http http = new Http();
        
        HTTPResponse response = http.send(request);
     
        debugResponse(response);        
        
        if(response.getStatusCode() == 200)
        {                
            return new PageReference(hostname + 'home/home.jsp');
        }
        else if(response.getStatusCode() == 302)
        {                
            return new PageReference(response.getHeader('Location'));
        }
        else
        {
            return null;
        }
        
        //return Site.login(username, password, startUrl);
    }          
    
    private void debugResponse(HttpResponse response)
    {
      if(response == null)
      {
        return;
      }
      
      UDebug.printDebug('BODY = ' + response.getBody());      
      UDebug.printDebug('STATUS = ' + response.getStatus());
      UDebug.printDebug('STATUS CODE = ' + response.getStatusCode());
      
      for(String key : response.getHeaderKeys())
      {              
        if(key != null && key.trim().length() > 0)
        {
          String header = response.getHeader(key);
          
          UDebug.printDebug(key + ' = ' + header);
        }
      }
    } 
    
    public class CustomException extends Exception {}
        
    @IsTest(SeeAllData=true) 
    global static void testPortalLoginController () 
    {        
        Integer portalSettingsRowCount = [select count() from SitesToPortalsRedirectSettings__c];
        
        if(portalSettingsRowCount == 0)
        {
          SitesToPortalsRedirectSettings__c setting = (SitesToPortalsRedirectSettings__c) USObject.getCustomSetting('SitesToPortalsRedirectSettings__c');
          
          setting.Portal_Hostname__c = 'http://www.test.test';
          setting.Portal_Id__c = '123';
          
          insert setting;
        }
        
        PortalLoginController controller = new PortalLoginController ();
        controller.username = 'test@salesforce.com';
        controller.password = '123456'; 
                
        System.assertEquals(controller.login(),null);                           
    }       
}

 

 

Hi 

 

Can anyone help me in converting this trigger into calling a batch class.

 

As it is not sufficient for our bulk loading of 4 millions data.

 

Here is the trigger:

 

trigger createacc on Contact (after insert) {
list<Contact > con=[select id,firstname ,lastname from contact where id in:Trigger.newMap.keySet()];
list<account >acc =new list<account>();
list<contact>cc1 =new list<contact>();
for(contact c : con)
{
account a =new account ();

a.name =  c.FirstName != null ? c.FirstName + ' ' + c.LastName : c.LastName;
acc.add(a);

}
insert acc;
for(account a1:acc){
system.debug('---------------------this is id --------------------'+a1.id);
for(contact c : con){
c.accountid=a1.id;
cc1.add(c);
}
}
update cc1;
}

 

 

I have a format please update me exact correct code works for my scenario:

 

trigger insertAccount on Contact (after insert) {
Map<id, Contact> contacts = new Map<id, Contact>();
for (Integer i=0;i<Trigger.new.size();i++) {

contacts.put(Trigger.new[i].Id, Trigger.new[i]);

}
// You can execute batch apex using trigger using below codes
if (contacts.size() > 0) {
Database.executeBatch(new InsertAccounts(contacts));
}
}

 

global class InsertAccounts implements Database.Batchable<sObject> {
//map of contactid - contact
Map<Id, Contact> contactMap = new Map<Id, Contact>();
global InsertAccounts(Map<Id, Contact> contacts) {
ContactMap = contacts;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
return DataBase.getQueryLocator([SELECT Id,FirstName, LastName,AccountId FROM Contact WHERE accountID IN : contactMap.keySet()]);
}
global void execute(Database.BatchableContext BC,List<Account> scopeAcc) {

for (Integer i=0;i<scopeAcc.size();i++){
scopeAcc.get(i).Area__c=ownerMap.get(scopeAcc.get(i).OwnerId).Team__c;
}
update scopeAcc;
}
global void finish(Database.BatchableContext BC) {
//Send an email to the User after your batch completes
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'info@theblogreaders.com'};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job is done');
mail.setPlainTextBody('The batch Apex Job Processed Successfully');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

 

  • December 03, 2013
  • Like
  • 0

Hi,

 

       1. Is der any specific steps for writting trigger ? if it is ......please suggest me, because i am very confusing in this topic. Please help me out.

 

       2. How to write test class for trigger and If i write trigger logic in class, again i need to write a test class for that trigger.

 

 

Thank You,

Vivek.

 

global class getProductDetail
{

  
    
    WebService static List<string> getProductUpdate(List<Product2> lstPro)
    {
            List<string> lstProName = new List<string>();
            List<Product2> Productlist = new List<Product2>();
          //  List<Product2> prod=new  List<Product2>();
          Product2 pro = new  Product2();
            system.debug('---------------Name----------------'+lstPro);
             system.debug('---------------Name----------------'+lstPro[0].Name);
             system.debug('---------------strname__c----------------'+  lstPro[0].strOnhand__c);
             system.debug('---------------strname__c----------------'+  lstPro[0].QB_Available__c);
             
            for(Product2 p: lstPro)
            {
                try 
                {
            
                   pro =[Select Name,Family,ProductCode,QB_Available__c,QB_Next_due_date__c,QB_On_Hand__c,QB_On_order__c,QB_On_sales_order__c from Product2 where ProductCode=:p.Name and Family != 'Retail'];
                  
                  
                       system.debug('---------------Name----------------'+ pro.Name);
                       pro.QB_Available__c = Decimal.valueof(p.strAvailable__c);
                      system.debug('---------------Available----------------'+ pro.QB_Available__c);
                       pro.QB_On_Hand__c = Decimal.valueof(p.strOnhand__c);
                       pro.QB_On_order__c= Decimal.valueof(p.strOnOrder__c);
                       pro.QB_On_sales_order__c= Decimal.valueof(p.strOnOrderSales__c);
                       if(p.strNextDewDate__c != null)
                       pro.QB_Next_due_date__c= Date.valueof(p.strNextDewDate__c);
                     
                     
                      update pro;
                      string strname = 'Updated successfully:  '+p.Name;
                      lstProName.add(strname );
                  
               }
                catch(Exception e) 
                { 
                   System.debug('The following exception has occurred: '+p.Name + e.getMessage());
                   string pname = 'Update Failed -Error:' +p.Name+ e ;
                   lstProName.add(pname);
                } 
                  
             
            
            } 
            
          
           // Update Productlist;
            system.debug('---------------ProductUpdated----------------');
        
            return lstProName ;
    }
    
}

Hi 

help me out  for writing the test class for below trigger.

 

trigger createAllocationsForLead on Project__c (after insert) {

  for(Project__c newPro:Trigger.new)
  {
      
          Allocation__c all=new Allocation__c();
          all.Assigned_User__c=newPro.Project_Lead__c;
          all.Project__c=newPro.id;
          all.Start_Date__c=newPro.Actual_Start_Date__c;
          all.End_Date__c =newPro.Actual_End_Date__c;
          all.Location__c=newPro.Project_Type__c;   
          all.Role__c='Project Lead';
          insert all; 
          
      
  }
}

Hello All,

 

This is the data setup in object Child__c

 

http://imgur.com/50arUIy,AO95lex#0

 

 

 

This is what I wanted to achieve :

 

http://imgur.com/50arUIy,AO95lex#1

 

 

As you can see I am able to achieve my desired output (Grouping based on parent__r.id) using the above query.

 

But I am not able to understand the role played  "id" inside count().

 

What did "id" inside the count() operator do ?.

 

The same setup in a traditional SQL is straightforward as below.

 

SELECT Parent__r.id,count(*)

FROM Child__c

GROUP BY Parent__r.id

ORDER BY count(*) DESC

 

So can someone explain the role played "id" inside the SOQL statement ?

 

 

Is it possiable to use TypeSeript on visualforce page for angualrJS 2?
Hi All,

I need to create a report that show Average number of new opportunities created per week by a user.

Ex. 50 total opportunities created in this Month
    User A :- Creates 10 : 1 record in 1st week, 5 records in 2nd week, 4 records in 3rd week, 0 records in 4th week
    User A :- Creates 25 : 10 record in 1st week, 5 records in 2nd week, 5 records in 3rd week, 5 records in 4th week
    User A :- Creates 15 : 0 record in 1st week, 5 records in 2nd week, 5 records in 3rd week, 5 records in 4th week

    so,
    Average number of new opportunities created per week by User A : 2.5
    Average number of new opportunities created per week by User B : 6.25
    Average number of new opportunities created per week by User B : 3.75

Regards
Subhash


Create an Apex trigger for Account that matches Shipping Address Postal Code with Billing Address Postal Code based on a custom field.
I am writing following code:-

trigger AccountAddressTrigger on Account (before insert,before update)
{
    List <Account> act= [Select id,name from Account where BillingPostalCode != NULL and Match_Billing_Address__c='True' ];
        For(Account a:act)
       {
           a.ShippingPostalCode=BillingPostalCode;
            }
}

It gives error-Varibale Doesn't exist:BillingPostalCode. 

What I am missing here?
Note- In the challenge, it's given, ShippingPostalCode and BillingPostalCode are the API name, 
Hi Team,
 I need help in building test class for the below Apex Class

@RestResource(urlMapping='/Cortx/CancelOrderService/*')
global class CortxCancelOrderService {
   
    @HttpPost
    global static List<WebResponse> cancelOrders(List<OrderDetail> lstOrderDetail) {
   
        Integration_Log__c LogObj = new Integration_Log__c(Request__c = JSON.serialize(lstOrderDetail));
        insert LogObj;
        Set<String> set_OrderIds = new Set<String>();
        LogObj = [Select Id, Name, Response__c from Integration_Log__c WHERE Id=:LogObj.Id];
        try{
            List<WebResponse> Response = new List<WebResponse>();
            List<Order> lst_Order =  new List<Order>();
            Schema.DescribeSObjectResult r = Order.sObjectType.getDescribe();
            String keyPrefix = r.getKeyPrefix();
           
            for(OrderDetail var :  lstOrderDetail){       
                if(var.Order_Id != null && var.Order_Id.startsWith(keyPrefix) && (var.Order_Id.length() == 15 || var.Order_Id.length() == 18)){
                    set_OrderIds.add(var.Order_Id);
                }
            }  
            Map<Id, Order> map_Orders = new Map<Id, Order>([Select Id, Status, Cancel_Reason__c from Order Where Id IN:set_OrderIds]);
            List<Services_and_Equipment__c> lst_SE = [ Select Id, Order__c, Cortx_Service_Id__c from Services_and_Equipment__c WHERE Order__c  != null AND Order__c IN:map_Orders.keySet()];
            Map<Id, List<Services_and_Equipment__c>> map_Order2lstSE = new Map<Id, List<Services_and_Equipment__c>> ();
            for(Services_and_Equipment__c var : lst_SE ){
                if(map_Order2lstSE.containsKey(var.Order__c)){
                    map_Order2lstSE.get(var.order__c).add(var);
                }else{
                    List<Services_and_Equipment__c> lst_tmp = new List<Services_and_Equipment__c>{var};
                    map_Order2lstSE.put(var.order__c, lst_tmp);
                }
            }
            List<Services_and_Equipment__c> lst_SE_ToUpdate = new List<Services_and_Equipment__c>();
            Set<String> OrderIdsToUpdate = new Set<String>();
            for(OrderDetail var :  lstOrderDetail){       
                if(var.Order_Id != null && var.Order_Id.startsWith(keyPrefix)){
                    if(var.Order_Id.length() == 18 && map_Orders.containsKey(var.Order_Id)){
                        // Here We need to put data validation before update the Order status as Cancelled
                       
                       
                        if(var.CancelReason != null){
                            Order Order_Obj = new Order(Id=var.Order_Id, Cancel_Reason__c = var.CancelReason, status='Cancelled');
                            for(Services_and_Equipment__c se_var : map_Order2lstSE.get(var.Order_Id)){
                                se_var.Order__c = null;
                                se_var.Cortx_Service_Id__c = null;
                                lst_SE_ToUpdate.add(se_var);
                            }
                            OrderIdsToUpdate.add(var.Order_Id);
                            lst_Order.add(Order_Obj);
                        }else{
                            WebResponse Response_Obj = new WebResponse();
                            Response_Obj.Order_Id = var.Order_Id;
                            String ErrorMsg = 'CancelReaon is mandatory to cancel Order "'+ var.Order_Id ;
                            Response_Obj.Status = 'Failure';
                            Response_Obj.StatusDescription = ErrorMsg;
                            Response.add(Response_Obj);
                        }                    
                    }else{
                        WebResponse Response_Obj = new WebResponse();
                        Response_Obj.Order_Id = var.Order_Id;
                        String ErrorMsg = 'Order Record with Id "'+ var.Order_Id +'" not found in System';
                        Response_Obj.Status = 'Failure';
                        Response_Obj.StatusDescription = ErrorMsg;
                        Response.add(Response_Obj);
                    }
                }else{
                    WebResponse Response_Obj = new WebResponse();
                    Response_Obj.Order_Id = var.Order_Id;
                    String ErrorMsg = 'Order_Id field can not be null';
                    Response_Obj.Status = 'Failure';
                    Response_Obj.StatusDescription = ErrorMsg;
                    Response.add(Response_Obj);
                }
            }
            Database.SaveResult[] SR_OrderUpdate = Database.update(lst_Order, false);    
            Database.SaveResult[] SR_SE_Update = Database.update(lst_SE_ToUpdate, false);    
           
            for (Database.SaveResult sr : SR_OrderUpdate ) {
                WebResponse Response_Obj = new WebResponse();
                if (sr.isSuccess()) {
                    Response_Obj.Order_Id = sr.getId();
                    Response_Obj.Status = 'Success';
                    Response_Obj.StatusDescription = 'Order cancelled successfully. SFDC log number - '+ LogObj.Name;
                }
                else {                       
                    Response_Obj.Order_Id = sr.getId();
                    String ErrorMsg = 'The following error has occurred.';              
                    for(Database.Error err : sr.getErrors()) {
                        ErrorMsg = ErrorMsg +' '+ err.getStatusCode() + ': ' + err.getMessage();
                    }
                    Response_Obj.Status = 'Failure';
                    Response_Obj.StatusDescription = ErrorMsg + ' SFDC log number - '+ LogObj.Name;
                }
                Response.add(Response_Obj);
            }      
            LogObj.Response__c = JSON.serialize(Response);
            LogObj.Is_Success__c = true;
            update LogObj;
            System.debug('--------WebResponse---- '+ Response);
            return Response;
        }catch(Exception ex){
            WebResponse ExceptionResponse_Obj = new WebResponse();
            ExceptionResponse_Obj.Status = 'Failure';
            ExceptionResponse_Obj.StatusDescription = ex.getMessage();
            LogObj.Response__c = JSON.serialize(ExceptionResponse_Obj);
            LogObj.Is_Success__c = false;
            update LogObj;
            System.debug('--------WebResponse---- '+ ExceptionResponse_Obj);
            return new List<WebResponse>{ExceptionResponse_Obj};
        }
    }

    global class OrderDetail{
        global String Order_Id;          // SFDC Order Id 18 digit
        global String CancelReason;
        global OrderDetail(){}
    }
    global class WebResponse{
        global String Order_Id{get;set;}     // SFDC Order Id 18 digit
        global String Status{get;set;}             // Success or Failure
        global String StatusDescription{get;set;}  // Detail of Failure, In case of success it will have default value “Record Updated Successfully”
    }

}

 
  • February 12, 2016
  • Like
  • 0

I have created 2 block in my VF page. one for taking input and the other for displaying list of accounts.

I want edit and delete functionality for each Account record in the list.

I've successfully created everything except the delete functionality of the delete button. The controller and Markup code are below:

Controller: 

public class AccountCustom {
  public List<account> accountlist = new List<account>();
    public Account account{get; set;}
    
    ApexPages.StandardSetController ssc;
    
   public List<account> accdelete = new List<account>();
    public String accid{get; set;}
        
    
        //Constructor
        public AccountCustom()
        {
             accountQuerry();
        
        }
        
        //Method with the querry for the list
        public void accountQuerry()
        {
            
            accountlist = [SELECT Id, Name, Phone FROM Account];
            ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(accountlist);
        }
        
    
    
        //get Method being called from VF page to display list
        public List<account> getAccountList()
        {
            return accountlist;
        }
    
    
        //Save Method
        public void save()
        {
            account = new Account();
            insert account;
            accountQuerry();
        }

        //Method for deleting accounts from the list
        public void deleteAccount()
        {
            
            accdelete = [SELECT Id, Name, Phone FROM Account WHERE Id = :accid];
            
            if(accdelete.size() > 0)
            {
               if(accdelete[0].Id != '')
               {
                delete accdelete;
               }
            }
            accountQuerry();
        }
        
    
    
}





VF Page:


<apex:page controller="AccountCustom">
    <apex:form >
        <apex:pageBlock title="Create/Update Account">                                
            
            <apex:pageBlockSection > 
                
                <apex:inputField value="{!account.Name}"/>                                
                <apex:inputField value="{!account.Phone}"/>                            
                
            </apex:pageBlockSection>
            <apex:commandButton action="{!save}" value="Save" />                    
            
        </apex:pageBlock>

        <apex:pageBlock title="List Of Accounts">                                    
            
            <apex:pageBlockTable value="{!AccountList}" var="ac">                    
                
                <apex:column width="40">
                    <apex:outputLink value="/{!ac.id}/e?retURL=%2F{!ac.id}">
                    Edit
                    </apex:outputLink>
                
                </apex:column>
                <apex:column value="{!ac.Name}"/>
                <apex:column value="{!ac.Phone}"/>
                <apex:column value="{!ac.id}"/>
                <apex:column >
                    <apex:commandButton action="{!deleteAccount}" value="Delete" immediate="true">            
                   
                        <apex:param value="{!ac.id}" assignTo="{!accid}"/>
                    </apex:commandButton>                                                
                                   
                </apex:column>
                
            </apex:pageBlockTable>
        
        </apex:pageBlock>
    </apex:form>
</apex:page>

Hi Friends

I have created a email Template for my bussiness and i create a workflow with condition criteria.and set the Recipient Type is owner.but when i am creating record its sent a alert mails twice(2times).i want a single mail.can any body tell me how it is possible.
Hi all,

I have created a trigger that has 75% code coverage. I am unsure how to set an .adderror from my trigger. Dones anyone have a code sample of how this can be achieved?

Thanks

Trigger:
trigger PicklistLimitTrigger on Software_Assets__c(before insert,before update){
Integer count =[select count() from Software_Assets__c where Software_Product__c='Windows 7'];
for(Software_Assets__c a:trigger.new){
if(count==3&&a.Software_Product__c=='Windows 7'){
a.addError('Please chose some other pick-list Values');
}
}
}

Test Class:
@isTest
private class PickListLimitTriggerTest {
    static testMethod void PickListLimitTrigger() {
 Software_Assets__c sa = new Software_Assets__c(Asset_First_Recorded__c = date.today(), Asset_Status__c = 'Operational', Vendor__c = 'Microsoft', Software_Product__c = 'Windows 7');
 
 insert sa;
 
 }
}

 
what is batch apex and what are its uses?
HI Folks,

I have 2 objects   Policy , Interview. On interview record policy lookup is there.  If interview fields Contact name , Insured name matches with any  policy record's Contactname,Annuity name Then it should pull the policy on to the Interview record policy look up field.

I have writtened below code. But it was not works properly. There is no immediate update for the Policy look up field. Can any one correct below code ?


trigger Interview_PolicyUpdate on Interviews__c

(before insert,before update) {

set<id> cset = new set<id>();
set<string> Aset = new set<string>();

for(Interviews__c Intr : Trigger.new){

If(Intr.Contact__c != Null){
cset.add(Intr.Contact__c);
}

}
List<policy__c> po = [select Id,name,Contact__c,Type__c,Annuitiant_Name__c from
Policy__c where Contact__c in:cset ];
try{
for(Interviews__c Inr : Trigger.new){
for(Policy__c p : po){
//If(Inr.Annuitant_Name__c !=null){
if(p.Contact__c == Inr.Contact__c && Inr.Insured_Name__c == p.Annuitiant_Name__c){
Inr.Policy1__c = p.Id;
}
}
}
}
catch(Exception e){
System.Debug(e.getMessage());
}
}
  • July 21, 2014
  • Like
  • 0
trigger trgset on contact (after insert)

{
    List<Contact> conToUpdate = new List<Contact>() ;
     for(Account acc : [Select Name,(Select id ,LastName from Contacts where id in: trigger.new ) from Account  ] )
     {
     for(Contact con : acc.Contacts)
     {
     con.LastName = acc.Name ;
     conToUpdate.add(con) ;
     }
    }
    if(conTOUpdate.size() > 0)
    {
       update conTOUpdate ;
    }
}


how can i restrict the code for a particular account only ...like if ther are 1000 account it will pick all ..how do i restrict it for a particular account ... in the suquery
is this right ??
for(Account acc : [Select Name,(Select id ,LastName from Contacts where id in: trigger.new ) from Account  wher account.id==contact.id] )
Hi all,

I written one trigger and test class getting this error. 
System.TypeException: Invalid id value for this SObject type

Trigger:-
----------

trigger EscalateCase on Escalation__c (after update) {
IF(Trigger.size > 1){return;}
IF(Trigger.new[0].Reason_For_Escalation__c == null || Trigger.new[0].Escalation_Comments__c == null || Trigger.new[0].Escalate_To_Management__c == false || Trigger.new[0].Case__c == null){return;}
Case c = new case(ID = trigger.new[0].Case__c, Escalate_To_Management__c = trigger.new[0].Escalate_To_Management__c, Reason_For_Escalation__c = trigger.new[0].Reason_For_Escalation__c, Escalation_Comments__c = trigger.new[0].Escalation_Comments__c);
update c;
}

Test class:-
--------------

@isTest
private class EscalateCaseTestClass{
@isTest static void Esc(){

Account a = new Account(Name='ContractBookingPeriodProcessingTest',Geography__c='TestGeography',
        Territory_Id__c='TestTerritory',
            Territory_Overlay__c='TestTerritoryOverlay',Renewals_Team__c='TestRenewalsTeam',
            Renewals_Account_Manager__c='TestRenewalsAccountManager');
        insert a;
        Contract c = new Contract(AccountId=a.id,Number_of_Booking_Periods_Records__c = 0, Number_of_Booking_Periods__c = 1,
                                    Status='Create', Finance_Charges__c ='0.5%',
                                    Contract_Term_Start_Date__c=date.valueOf('2013-01-01'),
                                    Contract_Term_End_Date__c=date.valueOf('2099-12-31')                    
                                    );
        insert c;

Case case1 = new case(Id=a.id,Escalate_To_Management__c =true,Reason_For_Escalation__c = 'TestReason' ,Escalation_Comments__c = 'TestEscalation' );
insert case1;

case1.Reason_For_Escalation__c = 'TestReasonForEscalation';
case1.Escalation_Comments__c = 'TestEscalationComments';
update case1;
}
}

Thanks
kumar
I am building a Visualforce page for the Opportunity custom console. I want to build a page with the basic contact information, how do I get the contact fields? I created a lookup(Contact) on the Opportunity
<apex:page standardController="Opportunity"  showheader="false" >
    <apex:form >
    <apex:pageBlock >
    
         <apex:pageBlockSection collapsible="false" columns="5">
             <apex:pageblocksectionItem >
             <apex:inputField value="{!Contact.Email}"/>
             </apex:pageblocksectionItem>
             
         </apex:pageBlockSection>  
         
    </apex:pageBlock>
    </apex:form>
        
</apex:page>
How can I modify this?

Thanks