• Ritesh Aswaney
  • PRO
  • 3633 Points
  • Member since 2011
  • Technical Solution Architect
  • salesforce.com


  • Chatter
    Feed
  • 137
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 795
    Replies

I've to write a Simple validation in my Custom VF/Apex code where a formula field (Grand Total which depends on 3 other fields) should not exceed a set number. If it does I would write a condition in my Apex code & add a error message to page. 

My Issue is that I think formula fields are only evaluated once the record is saved & when the page loads again & that's the reason I can't check for the modified Grand Total field in my apex code when User saves a record. 

 

Any workaround this , can this be achieved through After Trigger ?

Hello!

Don't judge me harshly - i'm newbie =).

For some hours i can't get over the error - "Expression cannot be assigned at line -1 column -1".

It appears every time i try to save the following APEX trigger -

 

trigger ItemAvailabilityChange on Item__c (before update) {

    if (Item__c.Items_Available__c == 0)
        Item__c.Availability__c = false;
    else 
        Item__c.Availability__c = true;
}

 Thanks in advance.

Here is the issue:

I have two lists that are being created by parsing two separate fields into plot point values. I need to loop through these lists simultaneously to create an X and a matching Y for a scatter graph. puting two for loops together will only create too many queries and not match the points correctly. How can I accomplish this goal?

 

My current code is below. It is producing the following error: Illegal Assignment from LIST<String> to string on Line 52

public with sharing class TestResultGraphConroller {

  
    public TestResultGraphConroller(ApexPages.StandardController stdController){
    }
    
    
    public String getTimeVolume(){
        return getTimeVolume(null);
    }
    
    public String getTimeVolume(List<Id> ids){
        GoogleViz gv = new GoogleViz();              
        gv.cols = new list<GoogleViz.col> { 
            new GoogleViz.Col('col2','Interval','number'),
            new GoogleViz.Col('col1','Channel Volume','number')
            };
        decimal interval = 0;
        for(Trial__c tv : [Select Id, Channel_Volume__c from Trial__c])
        {
        	Integer v;
        	List<String> channelvolumevalues = tv.Channel_Volume__c.split(' ');
        	for(String cv: channelvolumevalues)
        	{
            GoogleViz.row r = new GoogleViz.row();
            r.cells.add ( new GoogleViz.cell( interval));//interval
            r.cells.add ( new GoogleViz.cell( cv ));//X-Axis
            gv.addRow( r ); 
            interval = interval + .01;
            }
        }
        return gv.toJsonString();
    }  

    public String getFlowVolume(){
        return getFlowVolume(null);
    }
    
    public String getFlowVolume(List<Id> ids){
        GoogleViz gv = new GoogleViz();              
        gv.cols = new list<GoogleViz.col> { 
            new GoogleViz.Col('col1','Channel Volume','number'),
            new GoogleViz.col('col2','Channel Flow','number')    
            };              
               
        for(Trial__c tfv : [Select Id, Channel_Volume__c, Channel_Flow__c From Trial__c])
        {                                                          
            List<String> channelvolumevalues = tfv.Channel_Volume__c.split(' ');
            List<String> channelflowvalues = tfv.Channel_Flow__c.split(' ');
            for(String cv: channelvolumevalues)
            {
            	String cf = channelflowvalues;
            	GoogleViz.row r = new GoogleViz.row();
            	r.cells.add ( new GoogleViz.cell( cv ));//Y-Axis
            	r.cells.add ( new GoogleViz.cell( cf ));//X-Axis
            	gv.addRow( r ); 
            }
        }

        return gv.toJsonString();
    }  
}

 Can I get some assistance on the best way to do this? With the getTimeVolume it was much easier.

 

hi there,

 

Today, I managed to write yet another trigger and like always I think I have some errors. Please help:-

 

Trigger ChangeLeadOwner on Lead (after Insert)
{

    //First I will get list of LEAD Records where Pardot Score is less than 50 using a Query
    
    
    List<Lead> ParLead = [SELECT Id, Name FROM LEAD WHERE pi__score__c < 50];

    set<Id> LeadIds = new set<Id>();

    
    // Also get the list of Queues related to LEAD object and the specific queue where these leads should be assigned to.
    
    List<QueueSobject) PardotQueue = [SELECT Id, SobjectType, QueueId, Queue.Name, Queue.Email FROM QueueSobject WHERE Queue.Id=: 00GS00000016UFx AND SObjectType='Lead'];

    
    // Now, I should define a FOR loop which will search through the LEAD Records and look for the Pardot_Score field to be 50 or more than 50 then
    // reassign the LEAD to the Pardot Queue.

    for(Lead Leady1: Trigger.new)
    {
        if(pi__score__c >= '50')
        {
            newLead[0].Ownerid = PardotQueue[0].id;
        }
    }
}

 

My Goal is :-

 

On a LEAD when the field pi__score__c reached 50 or greater than 50 then it should be reassigned to a a specfic queue called - Pardot_Queue where the ID is = 00GS00000016UFx

 

 

Please help.

I have a VF page that shows a datatable with a master-child relationship join. I have an input field on the child objects but can not figure out how to save. Everything displays properly but will not save my changes to child objects.

 

VF Page:

   <apex:pageBlockButtons >
           <apex:commandButton action="{!save4}" id="saveButton" value="Save"/>
           <apex:commandButton onclick="resetInlineEdit()" id="cancelButton" value="Cancel"/>
    </apex:pageBlockButtons>
    <apex:pageblockTable value="{!acclist}" var="o">
        <apex:column width="10%" style="text-align:center;" headerValue="Name"><apex:outputField value="{!o.name}"/>  </apex:column>
          <apex:column headerValue="Line_Items">
                <apex:pageBlockTable value="{!o.Line_Items__r}" var="a">
                <apex:column width="4%" style="text-align:center;" headerValue="Pay Vendor"><apex:inputField value="{!a.Vendor_Paid__c}"/> </apex:column>
                <apex:column width="4%" style="text-align:center;" headerValue="InvRcd"><apex:outputField value="{!a.Invoiced_Received__c}"/> </apex:column>
                </apex:pageBlockTable>    
          </apex:column>
        </apex:column>
    </apex:pageblockTable>

 

Controller:

        acclist = [Select name, id, (SELECT Name,Invoiced_Received__c, Vendor_Paid__c, Service_Order__c from Line_Items__r) From Account where id IN (Select Vendor__c from Line_Item__c) ORDER BY name];\

     public PageReference save4() {
     update acclist;
return null;
}

 

  • October 18, 2012
  • Like
  • 0

Hello, I'm having some issues with a trigger I wrote to roll up all of the tasks on Account.  It works when I create or update the tasks, but it's failing to work when I delete a task.  It mentions the null object error, which I'm not sure how that makes sense because the task isn't null.  I am pretty sure I was accounting for it, but it keeps on throwing this error:

 

ctivity_Count: execution of AfterDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Activity_Count: line 9, column 1

 

 

trigger Activity_Count on Task (after insert, after update, after delete, after undelete) 
{
    List<Id> taskIds = new List<Id>();
    List<Id> accIds = new List<Id>();
    Map<Id,Account> accMap = new Map<Id,Account>();
    List<Account> updateList = new List<Account>(); 
    

    for(Task t : Trigger.new)    //line it's failing on
    {
        taskIds.add(t.Id);
        String str = t.whatId;
        if(str.startsWith('001'))     // Task belongs to Account
        {
            accIds.add(t.whatId);
        }
    }
    
    if(accIds.size() > 0)
    {
        for(Account ac : [SELECT Id, Activity_Count__c FROM Account WHERE Id in :accIds])
        {
            accMap.put(ac.Id,ac);
        }

        for(AggregateResult ar : [SELECT Count(Id) c, WhatId w FROM Task WHERE whatId IN :accIds and Subject Like 'Call' and CreatedDate = This_Month GROUP BY WhatId])
        {
            Account acc = new Account();
            
            string str = string.valueOf(ar.get('w'));
            
            acc = accMap.get(str);   // Edited   //
            acc.Activity_Count__c = Integer.valueOf(ar.get('c'));   // Edited
            
            updateList.add(acc);
        }
    }
    
    if(updateList.size() > 0)
    {
        update updateList;
    }
}

 

 

 

 

 

 

 

 

 

 

 

I need to run a trigger before insert, before update on leads.

 

I need to grab the value from a custom field in the lead record that was just updated/inserted.  Lead.customFieldValue

 

I then need to query the accounts table and find a match e.g.

 

Account[] accountId = [SELECT Id FROM Account WHERE Account.customField__c = Lead.customFieldValue];

 

I then need to take that account record ID that was a match to my lead record and place that value into the custom relationship field on the lead record called "Account".  

 

Basically I just took a lead, found an account record whose custom field value matched the lead's custom field value and linked the lead up to the Account record

 

 

I created a trigger to clone a custom object (service_order__c) if one of its fields called "recurring" is True. When I create/edit my custom object I get maximum trigger depth error. I can not figure out why I am getting that. Please help

 

Trigger:

trigger createRecurring on Service_Order__c(after update, after insert)
{  
    
    List<Service_Order__c> soInsert = new List<Service_Order__c>();
    for (Service_Order__c hr : [Select id,Recurring__c,Building__c, RecordTypeId from Service_Order__c where id in: Trigger.new])
    {
            if(hr.Recurring__c == True){
            Service_Order__c newSO = hr.clone(true);
            soInsert.add(newSO);      
            }
    }
    update soInsert;
}

  • October 16, 2012
  • Like
  • 0

Hello,

 

Dont understand why I am getting this error on the code below.  Isnt a (-) and a (+) an arithmetic expression LOL

 

any help as I am new to Appex.

 

trigger Peachtree_items_process on Peachtree_items__c (after update, after insert) {
    if (Peachtree_items__c.Stock_Minimum__c != null && Peachtree_items__c.Qty_On_Hand__c != null &&
            Peachtree_items__c.Qty_On_PO__c != null) {
            Peachtree_items__c.Stock_Reorder_Qty__c =
                Peachtree_items__c.Stock_Minimum__c -
                    (Peachtree_items__c.Qty_On_Hand__c + Peachtree_items__c.Qty_On_PO__c);
    }
}

Hi 

Actually I am able you install dataloader in windows OS system and aim scheduling the data its working fine 

 

But I am unable to install dataloader in Linux system inorder to schedule the data .

 

Earliest  reply will appreciated

 

Thanks 

  • October 16, 2012
  • Like
  • 0

Hello,

 

I have 2 triggers on the Account Object.  One is a before trigger that populates a field on the Account called Sales_Owner__c with the Account Owner ID.  The other is an After trigger that looks at 3 fields on the Account and then either populates or updates values in the Account Team section.  The triggers work as expected in both my sandbox and production environments for single updates, but when I try to dataload in multiple revisions I get the following error:

 

AccountTeamChanges: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0 with id 01M7000000e5rGpEAI; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Trigger.AccountTeamChanges: line 195, column 1

 

Has anyone else experienced this or know whay I am getting this?  Thanks for any assistance!  My triggers are below:

 

 

 

trigger ownerCopy on Account (before Insert, before Update) {

    // Update Sales Owner field with Account Owner
    for(Account x : Trigger.New){

            x.Sales_Owner__c = x.OwnerId;
}
}

 

=====================================================

 

trigger AccountTeamChanges on Account(after insert, after update)
{
    //list to hold new account team members
     List<AccountTeamMember> acctMembers = new List<AccountTeamMember>();
     
     //list to hold new account sharing rules
     List<AccountShare> acctSharingRules = new List<AccountShare>();
     
     //misc
     Set<String> rmMemberAccts = new Set<String>();
     Map<ID, ID> AccountTeamMap = new Map<ID, ID>();
    
     //iterate through records to find update processor values
     for(Account a : Trigger.new)
     {

        //new Account - Client Advisor
        if(Trigger.isInsert && a.Client_Advisor__c != null)
        {
            AccountTeamMember ca = new AccountTeamMember();
            ca.AccountId = a.Id;
            ca.TeamMemberRole = 'Client Advisor';
            ca.UserId = a.Client_Advisor__c;
            acctMembers.add(ca);
            
            AccountShare caSharingRule = new AccountShare();
            caSharingRule.AccountId = a.Id;
            caSharingRule.OpportunityAccessLevel = 'Read';
            caSharingRule.CaseAccessLevel = 'Read';
            caSharingRule.AccountAccessLevel = 'Edit';
            caSharingRule.UserOrGroupId = a.Client_Advisor__c;
            acctSharingRules.add(caSharingRule);
        }

        //new Account - Market Director
        if(Trigger.isInsert && a.Market_Director__c != null)
        {
            AccountTeamMember md = new AccountTeamMember();
            md.AccountId = a.Id;
            md.TeamMemberRole = 'Market Director';
            md.UserId = a.Market_Director__c;
            acctMembers.add(md);
            
            AccountShare mdSharingRule = new AccountShare();
            mdSharingRule.AccountId = a.Id;
            mdSharingRule.OpportunityAccessLevel = 'Read';
            mdSharingRule.CaseAccessLevel = 'Read';
            mdSharingRule.AccountAccessLevel = 'Edit';
            mdSharingRule.UserOrGroupId = a.Market_Director__c;
            acctSharingRules.add(mdSharingRule);
        }

        //new Account - Industry Manager
        if(Trigger.isInsert && a.Industry_Manager__c != null)
        {
            AccountTeamMember im = new AccountTeamMember();
            im.AccountId = a.Id;
            im.TeamMemberRole = 'Industry Manager';
            im.UserId = a.Industry_Manager__c;
            acctMembers.add(im);
            
            AccountShare imSharingRule = new AccountShare();
            imSharingRule.AccountId = a.Id;
            imSharingRule.OpportunityAccessLevel = 'Read';
            imSharingRule.CaseAccessLevel = 'Read';
            imSharingRule.AccountAccessLevel = 'Edit';
            imSharingRule.UserOrGroupId = a.Industry_Manager__c;
            acctSharingRules.add(imSharingRule);
        }

        //updated Account
        else if(Trigger.isUpdate)
        {
            //old Accoount record
            Account oldAcct = Trigger.oldMap.get(a.Id);
            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Client_Advisor__c != a.Client_Advisor__c && a.Client_Advisor__c != null)
            {
                //add old Client Advisor to remove list if one exists
                if(oldAcct.Client_Advisor__c != null)
                {
                    rmMemberAccts.add(oldAcct.Id);
                    AccountTeamMap.put(oldAcct.Id, oldAcct.Client_Advisor__c);
                }
                
                //add new processor to account team and update sharing rules
                AccountTeamMember ca = new AccountTeamMember();
                ca.AccountId = a.Id;
                ca.TeamMemberRole = 'Client Advisor';
                ca.UserId = a.Client_Advisor__c;
                acctMembers.add(ca);
                
                AccountShare caSharingRule = new AccountShare();
                caSharingRule.AccountId = a.Id;
                caSharingRule.OpportunityAccessLevel = 'Read';
                caSharingRule.CaseAccessLevel = 'Read';
                caSharingRule.AccountAccessLevel = 'Edit';
                caSharingRule.UserOrGroupId = a.Client_Advisor__c;
                acctSharingRules.add(caSharingRule);
            }
            else if(oldAcct.Client_Advisor__c != a.Client_Advisor__c && a.Client_Advisor__c == null)
            {
                rmMemberAccts.add(a.Id);
                AccountTeamMap.put(oldAcct.Id, oldAcct.Client_Advisor__c);
            }

            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Market_Director__c != a.Market_Director__c && a.Market_Director__c != null)
            {
                //add old Client Advisor to remove list if one exists
                if(oldAcct.Market_Director__c != null)
                {
                    rmMemberAccts.add(oldAcct.Id);
                    AccountTeamMap.put(oldAcct.Id, oldAcct.Market_Director__c);
                }
                
                //add new processor to account team and update sharing rules
                AccountTeamMember md = new AccountTeamMember();
                md.AccountId = a.Id;
                md.TeamMemberRole = 'Market Director';
                md.UserId = a.Market_Director__c;
                acctMembers.add(md);
                
                AccountShare mdSharingRule = new AccountShare();
                mdSharingRule.AccountId = a.Id;
                mdSharingRule.OpportunityAccessLevel = 'Read';
                mdSharingRule.CaseAccessLevel = 'Read';
                mdSharingRule.AccountAccessLevel = 'Edit';
                mdSharingRule.UserOrGroupId = a.Market_Director__c;
                acctSharingRules.add(mdSharingRule);
            }
            else if(oldAcct.Market_Director__c != a.Market_Director__c && a.Market_Director__c == null)
            {
                rmMemberAccts.add(a.Id);
                AccountTeamMap.put(oldAcct.Id, oldAcct.Market_Director__c);
            }

            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Industry_Manager__c != a.Industry_Manager__c && a.Industry_Manager__c != null)
            {
                //add old Client Advisor to remove list if one exists
                if(oldAcct.Industry_Manager__c != null)
                {
                    rmMemberAccts.add(oldAcct.Id);
                    AccountTeamMap.put(oldAcct.Id, oldAcct.Industry_Manager__c);
                }
                
                //add new processor to account team and update sharing rules
                AccountTeamMember im = new AccountTeamMember();
                im.AccountId = a.Id;
                im.TeamMemberRole = 'Industry Manager';
                im.UserId = a.Industry_Manager__c;
                acctMembers.add(im);
                
                AccountShare imSharingRule = new AccountShare();
                imSharingRule.AccountId = a.Id;
                imSharingRule.OpportunityAccessLevel = 'Read';
                imSharingRule.CaseAccessLevel = 'Read';
                imSharingRule.AccountAccessLevel = 'Edit';
                imSharingRule.UserOrGroupId = a.Industry_Manager__c;
                acctSharingRules.add(imSharingRule);
            }
            else if(oldAcct.Industry_Manager__c != a.Industry_Manager__c && a.Industry_Manager__c == null)
            {
                rmMemberAccts.add(a.Id);
                AccountTeamMap.put(oldAcct.Id, oldAcct.Industry_Manager__c);
            }

        }
        
        //DML OPERATIONS
        //remove team members from account team if any exist
        if(rmMemberAccts.size() > 0)
        {
            List<AccountTeamMember> removeTeam = new List<AccountTeamMember>();
            for(AccountTeamMember atm : [SELECT Id, UserId, AccountId
            FROM AccountTeamMember
            WHERE (TeamMemberRole='Client Advisor' OR TeamMemberRole='Market Director' OR TeamMemberRole='Industry Manager') AND AccountId IN :rmMemberAccts])
            {
                if(atm.UserId == AccountTeamMap.get(atm.AccountId))
                    removeTeam.add(atm);
            }
            
            delete removeTeam;
        }
        
        system.debug('-->ACCOUNT MEMBERS: ' + acctMembers);
        //insert the new account team members if any exist
        if(acctMembers.size() > 0)
            insert acctMembers; //LINE 100
        
        //insert account sharing rules if any exist
        if(acctSharingRules.size() > 0)
            insert acctSharingRules;
     }    
}

 

  • October 15, 2012
  • Like
  • 0

 

I received the following exception message after I moved the following code to production:

       System.LimitException: Too many SOQL queries: 101

 

I want to compare a value in the current record being saved against the top 5 values in the accounts table.  I should only be running ONE query per update - but somehow it's running a lot more.

 

It works fine when *testing* DEV and PRODUCTION, so I think some periodic process in Salesforce is sending a *batch* of records to the trigger instead of just one and it appears to be a lot of records at once.  Additionally, I only want the SOQL query to run if the user types a '?' in the custom field..

 

Anyone have any suggestions?  Perhaps if I move the SELECT statement into the IF statement.  I'm very familiar with queries in general - just not familiar with Apex syntax.

 

 

public static void checknumber(Account[] rur) {

 

for(Account m:rur) {
            

              Account[] acc = [Select inbr__c from Account where inbr__c > 35000 order by inbr__c desc limit 5

 

             if (myfield == '? ') {

                   //do_stuff_here

            }

 

}

 

Does anyone know if it is possible to perform a roll up sum of a cross object Quote Line Item formula field?  Here is my situation:

 

1) I have a custom Product number field named Watts

2) I have a custom Quote Line Item formula field named Total kW that is calculated as follows: quantity(from Quote Line Item) X kW(from Product) / 1000

3) I have a custom Quote number field named Total Order kW

4) I want the roll up sum of Quote Line Item Total kW to populate the Total Order kW when a quote or the line items are updated.

 

Please help...

 

Ben

970-619-5419

 

I am new to apex....i want to create Custom Picklist in whick i want all the fields of lead....Please tell me the code what should i write...Help will really be appreciated...!!!

  • January 24, 2012
  • Like
  • 0

I'm running into a baffling problem in my test class. I can't figure out why it keeps faiing the validation check on what should be relatively straightforward code.

 

It's got to be something simple I'm just not seeing.

 

 

Here's the relevant code:

 

        //create test contact
        testContact.Account = testAccount;
        testContact.LastName = 'Test Last Name';
        testContact.RecordType = [select Id from RecordType where Name = 'Team Contacts' and SobjectType = 'Contact'];       
        System.debug('Record type: '+testContact.RecordType);
        insert testContact;


        //create test time record
        testTimeClock.Start_Time__c = date.valueOf('2011-12-20T23:01:01Z');
        testTimeClock.End_Time__c = date.valueOf('2011-12-20T23:45:01Z');
        testTimeClock.Rate_My_Day__c = 'I had a great day!';
        testTimeClock.Team_Member_Employee__c = testContact.Id;
        insert testTimeClock;

 Now the testTimeClock.Team_Member_Employee__c field has a lookup filter that requires the contact record to of the Team Contacts record type.

 

Whenever I run this code, it fails on the insert testTimeClock; with the following message:

 

08:17:46.303 (303452000)|EXCEPTION_THROWN|[27]|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [Team_Member_Employee__c]
08:17:46.309 (309540000)|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [Team_Member_Employee__c]

 

If there's someone who can help me see the error of my way, i'd be v. appreciative.

 

 

Hey all,

 

I'm having a hard time figure out what I'm doing wrong.

 

I'm trying to have a lead get auto convertted if the lead source is of a specific type but, something is going wrong and I'm really not sure what it is.

 

If I try making a lead with the specified LeadSource and click save, the next page says that the lead was converted. The only problem is that there is no new Account and Contact object record related to that lead, and the lead also gets deleted.

 

Just ran apex tests in the sandbox and I'm not getting any errors.

 

Really would appreciate some guidance here... I've looked at like 5 tutorials and all of them have had essentially the same code, if not identical.

 

Thanks

 

 

if ( trigger.isAfter && trigger.isInsert)
    {
    	for( Lead l : trigger.new)
    	{
    		if( l.LeadSource == 'CustomPortal' && l.IsConverted == false)
            {
            	Database.Leadconvert lc = new Database.LeadConvert();
            	
            	lc.setLeadId(l.Id);
            	lc.setDoNotCreateOpportunity(true);
            	LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            	lc.setConvertedStatus(convertStatus.MasterLabel);
            	
            	Database.Leadconvertresult lcr = Database.convertLead(lc);
            	System.assert(lcr.isSuccess());
            	
            	Account newA = new Account( id = l.ConvertedAccountId, Primary_Contact__c = l.ConvertedContactId, Name = l.FirstName + ' ' + l.LastName);
            	//UpdateAccts.add(newA);
            	insert newA;
            }
    	}
    	//Insert UpdateAccts;
    }

 

  • December 15, 2011
  • Like
  • 0

Hi,

 

I work with Decimal values and after performing some calculations I alway end up with numbers like 1.235555555

 

I need to limit my Decimal to precision to only 2 decimal places after the decimal point.

 

I don't seem to find method that does that.

 

Any ideas, I am sure is simple :)

 

Forgot to mention: This is entirely in Apex code!

 

Thank you.

  • December 14, 2011
  • Like
  • 0

Hi everyone,  I am not a SFDC newbie but am new to writing triggers, etc.  Normally I would figure this out myself but I am in a bit of a time crunch :smileyindifferent:  So i created a trigger to count the number of contacts related to an account object, the code works without a problem.  However I now need to implement it and need to test the code to pass coverage requirements.  

 

I  need to create a class that creates a new contact.  Although my code for this class isn't throwing any errors, it is not creating the new contact record.  I realize this is small potatoes compared to some of the other requests here, but I'd appreciate the help.

 

@isTest
public class myClassTest {
static testMethod void myTest() {


Contact testContact = new Contact(recordtypeid='01280000000BcQiAAK',firstname='Bob',lastname='Dole',title='Teacher',AccountId='001V0000005D6cY');


insert testContact

;

}}

We had an outside consultant create a customization for our company and part of the customization included a custom Apex class.

 

Line 17 of this customization is written as

 

        for(OpportunityTeamMember ot:[select id,UserId,User.Name,Opportunity.OwnerId,Opportunity.Owner.Name from OpportunityTeamMember where OpportunityId=:lineItem.OpportunityId and User.Paid_on_Oppty_Sales_Credits__c=TRUE])

 

I need make an update that checks to see what the "Year" of the opporutnity close date is prior to running line 17 of this code.

 

I tried adding

 

IF(YEAR(Opporutnity.CloseDate) >= 2012) before line 17 but I get compile errors (because I know very little about APEX).

Error: Compile Error: Method does not exist or incorrect signature: YEAR(Schema.SObjectField)

 

What I would like to ulitmately do is add the following type of "if" statement to replace line 17 (the SOQL select statement is different depending on the outcome of the close date check).

 

IF(YEAR(Opporutnity.CloseDate) >= 2012)

        for(OpportunityTeamMember ot:[select id,UserId,User.Name,Opportunity.OwnerId,Opportunity.Owner.Name from OpportunityTeamMember where OpportunityId=:lineItem.OpportunityId and User.Paid_on_Oppty_Sales_Credits__c=TRUE])

IF(YEAR(Opporutnity.CloseDate) < 2012)

        for(OpportunityTeamMember ot:[select id,UserId,User.Name,Opportunity.OwnerId,Opportunity.Owner.Name from OpportunityTeamMember where OpportunityId=:lineItem.OpportunityId)

 

Can anybody recommend a solution to getting this added to our existing apex class.  Thank you in advance for any advice.

 

 

I've attached the relevant portion of the existing APEX class below.

 

public with sharing class ProductSalesCredits {
    public List<SalesCreditListItem> salesCredits {get; private set;}
    public OpportunityLineItem lineItem {get; private set;}
    public Opportunity currencyOpp {get; private set;}
    public List<SelectOption> userOptions {get; private set;}
    public Integer deleteIndex {get;set;}
    public Double revenueForecast {get; private set;}
    public Double bookingAmount {get; private set;}
    
    public static final String TYPE_PRIMARY = 'Primary';
    public static final String TYPE_ADDITIONAL = 'Additional';
    
    private List<Sales_Credit__c> creditsToDelete = new List<Sales_Credit__c>();
    
    private ProductSalesCredits(OpportunityLineItem lineItem, List<Sales_Credit__c> credits) {
        this.userOptions = new List<SelectOption>();
        for(OpportunityTeamMember ot:[select id,UserId,User.Name,Opportunity.OwnerId,Opportunity.Owner.Name from OpportunityTeamMember where OpportunityId=:lineItem.OpportunityId and User.Paid_on_Oppty_Sales_Credits__c=TRUE])
            this.userOptions.add(new SelectOption(ot.UserId,ot.User.Name));          
            
        Opportunity o=[select OwnerId,Owner.Name, CurrencyIsoCode from Opportunity where id=:lineItem.OpportunityId];
        currencyOpp = o;
        this.userOptions.add(new SelectOption(o.OwnerId,o.Owner.Name));
        this.lineItem = lineItem;
        this.salesCredits = new List<SalesCreditListItem>();
        for (Integer i=0;i<credits.size();i++) {
            this.salesCredits.add(new SalesCreditListItem(credits[i],i));
        }

 

 

I need to return a value of 0 if the field has 0, if the value is greater than 0 I need to divide by another field and return that value.

Here is the formula I have, it is giving me a syntax error saying incorrect paramaters expected 3 recieved 2

 

 

IF (Total_Event_Cost__c =0,0)  > 0  /  NumberOfWonOpportunities

 

Thank you!!!

When a full copy sandbox is refreshed from Production, I'm guessing people's private chatter messages are also copied across.

 

And if other folks can login as them on these full copy test environments - I'm guessing they will be able to access people's private chatter messages.

 

Is there a way to prevent this - other than I'm guessing physically delete all these private messages.

DISCLAIMER : JQuery Novice !

I have a beefy Visualforce Page with some Jquery - had a question about refreshing a div being used to render as a jquery dialog.

 

Here's a pseudo structure of my page

 

<Jquery Dialog Definition>

 

 

<apex:repeat>

iterate over a list of objects

Edit  Button on Click = invoke JS to launch the dialog, rerender=div

</apex:repeat>

 

<div display-none dialog>

displays details of the element on which the Edit button is clicked in the repeat above.

</div>

 

Now my question is how do I refresh this dialog to reflect the details of the element on which the Edit was clicked. Although my Edit Button onClick uses Javascript remoting to set the selected element id on the controller, the dialog box never refreshes to show this content. rerender doesnt seem to cut it. Anyone know how does one refresh a section which was originally rendered (not visible though) as part of the original page.

 

Trying to insert a Chatter Feed record as a User which is not the executing user 

 

FeedItem fi = new FeedItem(Body = 'Hello World', ParentId = '<ID OF USER>');

insert fi;

 

But this inserts it as a FeedItem from the executing User to the User whose Id is plugged into the FeedItem.

 

FeedItems seem to be created in the executing Users Chatter Stream.Wondering what I'm missing.

hi group,

 

                 In E-Mail to Case what are the mandatory values to be passed . And can any one explain to me in detail about E-mail to Case, In the sense where to be used and why ...

       

     Thanks for giving reply in (advance)

                    Thanks and Regards

                            Varma

 

                                     

I'm trying to write some tests for a Visualforce controller extension, however the tests are failing because a query in the controller is not retrieving related sObjects in a query. Outside of testing (in the sandbox), the related sObjects are retrieved without issue, but in testing the related sObjects are null.

 

Here is the query code in the controller:

private void queryRel ()
{
	for (Relationship__c r : [SELECT Id,Name,Primary_Client__r.Name,Owner.Id,Owner.Name,Owner.IsActive FROM Relationship__c WHERE Id = : relId FOR UPDATE])
		rel = r;
}

 In the test environment, Owner is null.

 

Here is the setup code for the test:

List<Relationship__c> rList = [SELECT Id,OwnerId,(SELECT Id FROM Accounts__r) FROM Relationship__c];
rList[2].OwnerId = [SELECT Id FROM User WHERE IsActive = TRUE AND Id != : UserInfo.getUserId() LIMIT 1].Id;
Database.update(rList[2]);

ApexPages.StandardController sc = new ApexPages.StandardController([SELECT Id FROM Relationship__c WHERE Id = : rList[0].Id]);
RelationshipAddController rac = new RelationshipAddController(sc);
System.AssertNotEquals('fatal',rac.pageMsgSeverity,rac.pageMsgBody + rac.rel);

 Currently that first assertion fails because an internal check to verify the Owner is active fails since Owner.IsActive is null.

 

Any suggestions would be greatly appreciated.

  • March 05, 2013
  • Like
  • 0

My controller has a method that returns a list.

Based on certain criteria I would like to hide the results from the DataBlockTable. For example if Revenue__c < 300.

 

I know this could be done by changing the SOQL query to filter the results so the list just does not contain the unwanted values. However I would prefer to keep the list as is and filter on the VisualForce side. Is there a syntax to use render  within a DataBlockTable so it will conditionally show the rows?

I have a trigger that does some work when the opportunity is closed with stage=close won. But my code also checks to make sure that if I am editing an opportunity that is saved with stage=close won (that is trigger.old has stage = close won) then it should not carry out the task.

 

Trigger createRenewalOpp on opportunity(after update){

    List<Opportunity> oppList = new List<Opportunity>();
    
    //making sure that the opportunity is not already closewon
    for(Opportunity p : trigger.old) {
          if(p.stageName !='Closed Won' ){

//execute code
}
}
}

 

The problem with above code is that if I create a new opportunity and close it starught away with stage = close won (meaning trigger.old has no value) then the code following the "if" statement does not execute.

 

How can I check to create an exception for such a scenario?

 

Thank you!

 

  • February 15, 2013
  • Like
  • 0

I've to write a Simple validation in my Custom VF/Apex code where a formula field (Grand Total which depends on 3 other fields) should not exceed a set number. If it does I would write a condition in my Apex code & add a error message to page. 

My Issue is that I think formula fields are only evaluated once the record is saved & when the page loads again & that's the reason I can't check for the modified Grand Total field in my apex code when User saves a record. 

 

Any workaround this , can this be achieved through After Trigger ?

hi i want to get distinct values from the list of values

 

i have a filed called brandcategory in this i have some data from this i want get distinct values in my visualforce page

example: in my filed i have this data

1

1

2

2

3

4

5

and i have to show result in my vf like this

1;2;3;4;5



 

how can we achive this

 

can any one help me

thanks for advance to all

 

 

Hi there,

 

I have a very unique sitatuon and possible a hard one to solve. I have this Validation Rule on the Contacts

 

 

AND(

OR(ISBLANK( LeadConverted2_ctc__c ),

AND(NOT(ISNEW()),

LeadConverted2_ctc__c =1

)

),

OR(

ISBLANK( Title ),

ISBLANK( Phone ),

ISBLANK( Email )

),

NOT(ISPICKVAL( LeadSource , "XYZ")))

 

 

We have data coming from the outside source which comes as a LEAD and in that external app we do not capture Title of the Lead. So this RULE should not kick in when the data is being fed from the external app as a LEAD.

I tried to solve the above by capturing the Lead Source. But here is another challenge that I am facing:-

 

If the LEAD that is being converted has a LEAD Source = XYZ and the Contact that is being attached to also has the same LEAD Source, then the Val Rule does not get ignored and gives the error message that Title, Phone and Email is required.

 

If the Contact's LEAD Source = SFDC then the Validation Rule is easily by passed.  I want this to happen at all lead conversion.

 

I want the Validation Rule not to kick in on the Lead Conversion.

 

Can I do this with Val Rule or is APEX the answer?

 

please help

 

 

 

 

 

Hello:

 

After creating a new product, I tried uploading it into a new opportunity and an apex trigger error appeared and wouldn't allow me to go any further.  No one has ever seen this error come up before.  It only happens when trying to upload a brand new product.  The error message is:

 

 

Apex trigger OpportunityDiscountCalculation caused an unexpected exception, contact your administrator: OpportunityDiscountCalculation: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.OpportunityDiscountCalculation: line 11, column 1

 

 

I tracked down this apex trigger that was developed by our previous system admin about 2 years ago.  There is no information about whether it was created from an app we got from the AppExchange. I don't know how to deactivate it.

 

Any suggestions?

 

I appreciate your consideration!

 

 

 

  • November 06, 2012
  • Like
  • 0

I feel like I'm very close to getting this to work.  What I'm trying to do it take the user to enter a Opportunity Contact Role page once they save the Opportunity.  To do so, I'm overriding the Opportunity View button.

 

I'm good with the redirct to the Opportunity Contact Role page but the standard Opportunity page is not coming up.  I get the following error:   

 

java.lang.IllegalArgumentException: Illegal view ID OpportunityRedirect?id=006M0000004ahc8. The ID must begin with /

 

Here's my code:

public with sharing class OpportunityRedirect {
	String oppId;

	public OpportunityRedirect(ApexPages.StandardController stdController) {
		//c = stdController;
		oppId = stdController.getId();
	}
        
	public PageReference redirect() {
		PageReference pageDetail = new PageReference ('/p/opp/ContactRoleEditUi/e?oppid=' + oppId + '&retURL=' + oppId);
		pageDetail.setRedirect(true);
		
		OpportunityContactRole[] ocr = [select ContactId, Role, isPrimary from OpportunityContactRole where OpportunityId = :oppId];
		system.debug('--------------------- ocr: ' + ocr);
		if (ocr.size() == 0) return pageDetail;
		
		//PageReference pageOpportunity = new PageReference('OpportunityRedirect/?id=' + oppId);
		PageReference pageOpportunity = new PageReference('OpportunityRedirect');
		pageOpportunity.getParameters().put('id',oppId);
		pageOpportunity.setRedirect(true);
		return pageOpportunity;
	}
}

 

<apex:page standardController="Opportunity" 
		extensions="OpportunityRedirect" action="{!redirect}">
	<apex:detail />
</apex:page>

 

 

 

When you are working with object X and before you can save a related object through lookup can not have a status of Y how do you write the test code across objects?

 

Thank you,

Steve

 

Hi Everyone

 

I have two custom objects Employee (Master) , submission (Detail).My rollup in Employee gives no of submissions made by each .I need to filter these submissions based on current month and for each employee... for this  i'm planning to write a trigger . here i created a count field on employee everytime if a record enter into submission object the count should be incremented.but i need employee wise submissions count on monthly basis could you please help me out.Every time the count should be reset to zero on next month. is it better to write a trigger or a class.

 

Thanks in advance

 

I created one object, which have fields like Start date, weeks etc.,. and also i created one custom button named as "Add". 

 

Coming to my requirement, if i give start date as 6/11/2012 and weeks as 3 then click on add button i want to show the pageblock table with below columns

 

startdate , weeks, 6/11/2012, 13/11/2012, 20/11/2012. and also these 3 week values will be in input form.

 

here my main intention is, how to create these type of columns dynamically? and also how to take the week values

 because if i take week value as 5 then i want to populate the coloumns 5 times dynamically. so here main thing is weeks  and startdate. based on weeks i want to populte the columns. if i give 5 weeks then i want first column as start date and remaining 4 columns will populate with further week values. And also another thing is, after giving these values where i want to store the values. For this waht i want to create???

 

So please give the solution to me ASAP. 

 

 

thanks

gani

Hi Guys,

 

I have created a simple vf page and placed and small jQuery script in the vf page (below code). I have added this vf page as an inline VF page in the Case detail page. In the jQuery I am trying to pick up the case number by passing the id of the div in which the case number is present and alerting the result. But I am getting a blank pop-up.

But when I try the same, by placing the jQuery in the sidebar, its working just fine.

 

<apex:page standardController="Case">
<script src="/resource/jQueryLatest" type="text/javascript"></script> <script type="text/javascript"> j$(document).ready(function(){ var caseNumber = j$("#cas2_ileinner").text(); alert(caseNumber); }); </script>
</apex:Page>

 Problem: not able to access the DOM elements of the standard detail page from a jQuery script which is placed in the inline vf page on the same page.

 

please help!

 

Regards

Sam

 

 

I encountered some unexpected behavior with the save() method on the standard controller and just curious as to the reasoning behind it.

 

I have an instance of a StandardController for a new custom object.  Calling the save() method successfully inserts a new record for the custom object.  If you call save() again, it inserts another new record instead of updating the existing one in the controller's context.

 

Here's the basic code:

 

MyObject__c o = new MyObject__c();
ApexPages.StandardController sc = new ApexPages.StandardController(o);

// this successfully inserts a new record...

sc.save();

// this successfully returns the Id of the new record
// doesn't this mean that the record is in the controller's current context?

Id myId = sc.getId();

// shouldn't this update the record that is in the current context?
// it does not; it inserts a new record

sc.save();

 

Why doesn't the second call to save() update the record that was inserted in the first call to save()?   It seems to be holding on to the reference of the object that was passed into the constructor.  This would kind of make sense to me if the call to getId() returned null.  At least it would appear that the context of the controller is consistent.

  • November 05, 2012
  • Like
  • 0

Hi all,

 

Does anyone know how to achieve the funtion like web-to-lead?

I have a html that contains a form where I upload a file of chatter. After I posted the form, is there any method to receive the post? 

 

Best Regards

  • November 05, 2012
  • Like
  • 0

How can I improve code coverage for my below class?

Lines which are in red are not covered,

 

Please, help me

 

 

global class My_InsertActual_Batch implements Database.Batchable<sObject> {
    
    Public String Query;
    List<User_Budget__c> ublst = new List<User_Budget__c>();
    List<User_Budget__c> ublst1 = new List<User_Budget__c>();
    List<Commission__c> comlst = new List<Commission__c>();
    List<Commission__c> comlst1 = new List<Commission__c>();
    Set<Id> ubid = new Set<Id>();
    Set<Id> comid = new Set<Id>();
    global Database.queryLocator start(Database.BatchableContext bc) {
        Query = 'SELECT Actual_Dirty__c,Actual__c,Channel__c,Month_Year__c,OwnerId FROM User_Budget__c WHERE Actual_Dirty__c = True LIMIT 20';
        return Database.getQueryLocator(Query);
    }
    
    global void execute(Database.BatchableContext bc, LIST<SObject> lst) {
        for(sObject s : lst) {
           User_Budget__c ub = (User_Budget__c)s; 
           ubid.add(ub.OwnerId);
           ublst.add(ub);
        }
        System.Debug('$$$$$$'+ubid);
        comlst = [select id,Sales_Team_Member__c,
        Total_My_SO_Sales_January__c, Total_My_SO_Sales_February__c,Total_My_SO_Sales_March__c,
        Total_My_SO_Sales_April__c,Total_My_SO_Sales_May__c,Total_My_SO_Sales_June__c,
        Total_My_SO_Sales_July__c,Total_My_SO_Sales_August__c,Total_My_SO_Sales_September__c,
        Total_My_SO_Sales_October__c,Total_My_SO_Sales_November__c,Total_My_SO_Sales_December__c,
        Total_Cash_Carry_Sales_January__c, Total_Cash_Carry_Sales_February__c,Total_Cash_Carry_Sales_March__c,
        Total_Cash_Carry_Sales_April__c,Total_Cash_Carry_Sales_May__c,Total_Cash_Carry_Sales_June__c,
        Total_Cash_Carry_Sales_July__c,Total_Cash_Carry_Sales_August__c,Total_Cash_Carry_Sales_September__c,
        Total_Cash_Carry_Sales_October__c,Total_Cash_Carry_Sales_November__c,Total_Cash_Carry_Sales_December__c 
        from Commission__c where Sales_Team_Member__c in :ubid];
        System.debug('@@@@@'+comlst);
        for(Commission__c com : comlst) {
            comid.add(com.id);
        }
        //ublst = [SELECT Actual_Dirty__c,Actual__c,Channel__c,Month_Year__c,OwnerId FROM User_Budget__c];
        System.debug('******'+ublst);
        for(User_Budget__c u: ublst) {               
           u.Actual__c = 0;
           for(Commission__c com : comlst) {               
               //SO Sales January
               if((u.OwnerId == com.Sales_Team_Member__c) &&
               (u.Actual_Dirty__c == True)) { 
                //u.Actual__c = 0;                   
                   if(u.Channel__c == 'Special Order') {
                       If(u.Month_Year__c.month() == 1) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_January__c;   
                       }                  
                       //SO Sales February
                       if(u.Month_Year__c.month() == 2) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_February__c;                                
                       }     
                       //SO Sales March
                       if(u.Month_Year__c.month() == 3) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_March__c;                                
                       }     
                       //SO Sales April
                       if(u.Month_Year__c.month() == 4) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_April__c;                                
                       }     
                       //SO Sales May
                       if(u.Month_Year__c.month() == 5) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_May__c;                                
                       }     
                       //SO Sales June
                       if(u.Month_Year__c.month() == 6) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_June__c;                                
                       }     
                       //SO Sales July
                       if(u.Month_Year__c.month() == 7) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_July__c;                                
                       }     
                       //SO Sales August
                       if(u.Month_Year__c.month() == 8) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_August__c;                                
                       }     
                       //SO Sales September
                       if(u.Month_Year__c.month() == 9) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_September__c;                                
                       }      
                       //SO Sales October
                       if(u.Month_Year__c.month() == 10) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_October__c;    
                            System.debug(com.Total_My_SO_Sales_October__c+'######'+u.Actual__c+u.Month_Year__c.month()); 
                            System.debug(u.Actual_Dirty__c+'!!!!!');             
                       }  
                       //SO Sales November
                       if(u.Month_Year__c.month() == 11) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_November__c;                                
                       }   
                       //SO Sales December
                       if(u.Month_Year__c.month() == 12) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_My_SO_Sales_December__c;                                
                       } 
                   }                
                   //CC Sales January
                   if(u.Channel__c == 'Cash & Carry') {
                       if(u.Month_Year__c.month() == 1) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_January__c; 
                           }                  
                       //CC Sales February
                       if(u.Month_Year__c.month() == 2) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_February__c;                                
                       }     
                       //CC Sales March
                       if(u.Month_Year__c.month() == 3) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_March__c;                                
                       }     
                       //CC Sales April
                       if(u.Month_Year__c.month() == 4) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_April__c;                                
                       }     
                       //CC Sales May
                       if(u.Month_Year__c.month() == 5) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_May__c;                                
                       }     
                       //CC Sales June
                       if(u.Month_Year__c.month() == 6) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_June__c;                                
                       }     
                       //CC Sales July
                       if(u.Month_Year__c.month() == 7) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_July__c;                                
                       }     
                       //CC Sales August
                       if(u.Month_Year__c.month() == 8) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_August__c;                                
                       }     
                       //CC Sales September
                       if(u.Month_Year__c.month() == 9) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_September__c;                                
                       }      
                       //CC Sales October
                       if(u.Month_Year__c.month() == 10) {
                            //u.Actual__c = 0;
                            u.Actual__c += com.Total_Cash_Carry_Sales_October__c;    
                            System.debug(com.Total_Cash_Carry_Sales_October__c+'######'+u.Actual__c+u.Month_Year__c.month()); 
                            System.debug(u.Actual_Dirty__c+'!!!!!');             
                       }  
                       //CC Sales November
                       if(u.Month_Year__c.month() == 11) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_November__c;                                
                       }   
                       //CC Sales December
                       if(u.Month_Year__c.month() == 12) {
                           //u.Actual__c = 0;
                           u.Actual__c += com.Total_Cash_Carry_Sales_December
__c;                                
                       } 
                   }
               }                  
           } 
           u.Actual_Dirty__c = False; 
           ublst1.add(u);
        }
        update ublst1;        
    }
    
    global void finish(Database.BatchableContext bc) {
         AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
         TotalJobItems, CreatedBy.Email
         FROM AsyncApexJob WHERE Id =:BC.getJobId()];
         If(a.Status == 'Completed') {
             My_scheduledActual_Batch bs = new My_scheduledActual_Batch();
             Datetime sysTime = System.now();
             sysTime = sysTime.addminutes(1);
             //String tStr = '0 05 * * * ? '; 
             String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' +
             sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();            
             System.schedule('Update Actual'+sysTime.getTime(),chron_exp, bs);
             
         }         
         If(a.Status != 'Completed') {
              // Send an email to the Apex job's submitter notifying of job completion. 
    
               Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               String[] toAddresses = new String[] {a.CreatedBy.Email,’mail@mail.com'};
               mail.setToAddresses(toAddresses);
               mail.setSubject('Apex Sharing Recalculation ' + a.Status);
               mail.setPlainTextBody
               ('The batch Apex job processed ' + a.TotalJobItems +
               ' batches with '+ a.NumberOfErrors + ' failures.');
               Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
               
               My_scheduledActual_Batch bs = new My_scheduledActual_Batch();
               Datetime sysTime = System.now();
               sysTime = sysTime.addminutes(6);
               //String tStr = '0 05 * * * ? '; 
               String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' +
               sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();            
               System.schedule('Update Actual'+sysTime.getTime(),chron_exp, bs);

         }
    }
}

 

 

 

Below is my test calss:

 

@isTest
private class Test_My_InsertActual_Batch {
    static testMethod void My_InsertActual_Batch(){
        
        User u1 = [SELECT Id,Name FROM User WHERE 
        Email = 'mail@mail.com' limit 1];  
        List <User_Budget__c> ublst = new List<User_Budget__c>();
        
        for(integer i = 0; i<200; i++) {
            Date sysDate = Date.parse('1/31/2012');
            sysDate = sysDate.adddays(i);
            User_Budget__c ub = new User_Budget__c(
            Channel__c = 'Cash & Carry',
            Actual__c = 0,
            Actual_Dirty__c = True,
            Budget_Currency__c = 500,
            Month_Year__c = sysDate,
            OwnerId = u1.id);
            ublst.add(ub);
        }
        insert ublst;
        
        Test.startTest();
            My_InsertActual_Batch insact = new My_InsertActual_Batch();
            ID batchprocessid = Database.executeBatch(insact);
            My_scheduledActual_Batch bs = new My_scheduledActual_Batch();
            Datetime sysTime = System.now();
            sysTime = sysTime.addminutes(1);              
            String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' +
            sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();            
            System.schedule('Update Actual'+sysTime.getTime(),chron_exp, bs);
        Test.stopTest();
    }
}

 

 

Hi,

 

I have a controller class and a VF page that display a list of records from which a user can select any number of records. Once a user check marks the records, they are displayed in second section of VF page.

 

Now again on second VF page (PDF page), I want to display the list again with extra information. But that list is not getting carried forward from one page to another.

 

Please suggest me as to what shall be done.

 

Thanks

Hi ,

 

I'm trying to create a custom OnClick JavaScript button that will update multiple records sterngth , weakness , opps .

 

can any one help me here

 

 {!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/25.0/apex.js")}
var recordTypeName = '{!Account.RecordType}';
var idArr = {!GetRecordIds($ObjectType.Business_Plan__c)}
var BPRecordId = '';
var queryPart = "'" + idArr.join("','") + "'"

if(recordTypeName == 'Channel'){
var result = sforce.connection.query("Select Id Strengths__c, Opportunities__c, Threats__c, Weakness__c From Business_Plan__C  where Id IN ("+queryPart+")") ;
BPRecordId = result.getArray("records")[0].Id;
}
else if(recordTypeName == 'Grower' || recordTypeName == 'Lawn and Garden'){
var result = sforce.connection.query("Select Id Strengths__c, Opportunities__c, Threats__c, Weakness__c From Business_Plan__C  where Id IN ("+queryPart+")") ;
BPRecordId = result.getArray("records")[0].Id;
}
else if(recordTypeName == 'Influencer'){
var result = sforce.connection.query("Select Id Strengths__c, Opportunities__c, Threats__c, Weakness__c From   Business_Plan__C  where Id IN ("+queryPart+")") ;
BPRecordId = result.getArray("records")[0].Id;
}
else{
alert('Invalid Operation. Please contact System Admin for details!!');
}

var BPDescription = sforce.connection.describeSObject("Business_Plan__c");
var BPUrlForNew = BPDescription.urlNew.split('com')[1];
var Strenght = '{!Business_Plan__c.Strengths__c}';
var CFID = 'CF'+'00NO0000000X9xI'; // this ID is differnect with the production,please chage it after deployment
var AccountName = '{!Account.Name}';
var aid='{!Account.Id}';
var Year = '{!Business_Plan__c.Name}';
 window.top.location=BPUrlForNew+'?'+CFID+'='+AccountName+'&'+CFID+'_lkid='+aid+'&RecordType='+BPRecordId+'&'+CFID+'='+Year;

  • November 03, 2012
  • Like
  • 0

just i want to retrive month from dateofbirth field ...please help me