• MIKE_DAY
  • NEWBIE
  • 80 Points
  • Member since 2011

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 12
    Replies

Hi Guys,

 

I have started using Chatter for Mobile and, in many cases, this allows me to attach images to records and have them appear as attachements against the record.  This is not supported however when uploading Chatter files to Tasks as the image will stay in the chatter feed but not the Attachment Related List.

 

Does anyone have an example of a trigger that will take a Task's Chatter feed (files only) when created and insert it as a Task Attachment?

 

If not, could you point me in the right direction please?

 

Many thanks

 

Mike

Hi Guys,

 

I have created an Apex page which, using Javascript, can query the Task Object from a UserId (Task Owner) and Date (Activity Date) entered on the Apex page. When a Commandbutton is clicked the Javascript function will bring back all the Tasks found and all the related Account information.  This will then produce a google route map of the users completed tasks that day, starting and ending at the Users Home address (User Postcode).

 

All of the below works fine and the map is produced, but only after I click the command button twice as the first click will not recognise the data a user has entered on the page. By the second click it has cached the entry somehow and the data can be passed to the function.

 

Does anyone know how I can get the field entries to pass to the function first time? 

 

CODE:

 

<apex:page standardController="Task" sidebar="false" showHeader="false">
<apex:includeScript value="/soap/ajax/20.0/connection.js" />
<script type="text/javascript">
var previousOnload = window.onload;
window.onload = function()
{
if (previousOnload)
{
previousOnload;
}
init();
}

function init()
{
sforce.connection.sessionId = '{!$Api.Session_ID}';
}


function Tracker(U,D){
var Uid = "'"+U+"'";
var maps;
var gurl = "http://maps.google.com/maps?q=from:";
var day= D.slice(0,2);
var month=D.slice(3,5);
var year=D.slice(6,10);
var newdate = year+"-"+month+"-"+day;
alert("User ID:"+Uid+"Date: "+D);

 

var Acc= sforce.connection.query("Select Account.Name, Account.BillingPostalCode, Time_On__c, Time_Off__c from Task where OwnerId = "+Uid+" AND ActivityDate = "+ newdate +" AND Status = 'Closed' ORDER BY LastModifiedDate ");
var ex = Acc.getArray("records");
   if (ex.length < 1) { alert("There are no Tasks to be Mapped");
   } else {

var usrq= sforce.connection.query("Select User.Postalcode from User where User.Id = "+Uid+" ");
var usr = usrq.getArray("records"); 

var maps = usr[0].PostalCode+" (Home)"+"+to:+";
for (var a=0; a < ex.length; a++) { //for all records   
maps = maps+ex[a].Account.BillingPostalCode+" ("+ ex[a].Account.Name + " "+ ex[a].Time_On__c +" - " + ex[a].Time_Off__c +") "+"+to:+";
    }
maps = maps + usr[0].PostalCode + " (Home)";
window.open(gurl+maps,"frame","menubar=1,resizable=1,scrollbars=1,width=900,height=600");
  }
}
</script>

<apex:outputPanel id="Track">
<apex:form id="thisForm">
<apex:pageBlock title="Field Tracker" mode="edit">
<apex:pageBlockButtons >
<apex:commandButton value="Start Tracking" onClick="Tracker('{!Task.OwnerId}','{!Task.ActivityDate}') "/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Please enter a User and Date:" columns="2">
<apex:inputField label="User" id="UserID" value="{!Task.OwnerId}" />
<apex:inputField label="Date" id="Date" value="{!Task.ActivityDate}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:outputPanel>

</apex:page>

 

There are 2 custom fields Time_On__c and Time_Off__C which are pretty self explanitory but if you need any more details on this please let me know.

 

PS: If anyone can help me get the map into an iframe on the page instead of a new window that would be a bonus.

 

Thanks as always

 

Mike

Hi All,

This is driving me round the bend and I think i need a new perspective on it if at all possible?

My trigger has been designed to catpure very high level product information from a custom object and create an opportuntiy invoice with an associated price book and line items.

The trigger works every time on the sandbox and I really have put it through its paces hower I simply cannot get my Test Class to run

Trigger Code:

trigger insertNewOpportunity on Items_Used__c (before insert) {
// Create Variables
List<Opportunity> listOppor = new List<Opportunity>();
List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
Set<Id> SetAccId = new Set<Id>();
 
// Create Opportunity If required
if(trigger.New[0].RelatedTo__c != null) {
  Opportunity[] exOppo = [SELECT Id from Opportunity where Customer_Ref__c = :Trigger.New[0].RelatedTo__c]; // Find an Opportunity with the same Customer Reference as the product being inserted
  
    if(exOppo.IsEmpty()){ // If no Opportunity exisits for this record
      for(Items_used__c item : Trigger.new){      
        if(item.Account__c != null){ 
          Opportunity OppNew = new Opportunity(Customer_Ref__c = item.RelatedTo__c,AccountId = item.Account__c,StageName = 'Closed Won',CloseDate = System.today(),Type = 'Existing Business',Name = 'Invoice for Visit' +' '+ item.RelatedTo__c, RecordTypeID = '01220000000UWCK',Division__c = item.Division__c,Amount = 0.00,Quote_Due_By__c = System.today(),Referred_By__c = item.ReferredBy__c,LeadSource = 'Technician Sale');
         listOppor.add(OppNew);          
        }
       insert listOppor;  // Create Opportunity 
      }
    }
}
// Insert Opportunity Line Items
 for(Items_used__c lineitem : Trigger.new){ // For all the items being inserted
  List<PriceBook2> pbook = new List<PriceBook2>();
  if((lineitem.Account__c != null) && (lineitem.RelatedTo__c != null)){
  SetAccId.add(lineitem.Account__c);
   Map<Id, Account> MapAccount = new Map<Id, Account>([select Division__c, Price_Band__c from Account where Id IN :SetAccId]);
   if(MapAccount.get(lineitem.Account__c).Price_Band__c != null){ // If the Price Band picklist for the Account is not Empty
    pbook = [Select Id from PriceBook2 where Name = :MapAccount.get(lineitem.Account__c).Price_Band__c]; 
   } // Else if the Division picklist for the Account is one of the following:
   else if(lineitem.Division__c == 'Pest'){ pbook = [Select Id from PriceBook2 where Id = '01s20000000PuSW'];} // Select the Pest Division Standard Price Book
   else if(lineitem.Division__c == 'Fire') { pbook = [Select Id from PriceBook2 where Id = '01s20000000Pz7tAAC'];} // Select the Fire Division Standard Price Book
   else if(lineitem.Division__c == 'Water') { pbook = [Select Id from PriceBook2 where Id = '01s20000000PvJCAA0'];} // Select the Pest Division Standard Price Book
   List<PriceBookEntry> pbe = new List<PriceBookEntry>(); // Get the Price Book Id
   pbe = [select Id, Pricebook2Id, UnitPrice from PriceBookEntry where Name = :lineitem.Item_Used__c AND PriceBook2Id = :pbook[0].Id];
   List<Opportunity> Opp = New List<Opportunity>(); // Get the related Opportunity Record
   Opp = [Select Id from Opportunity where Customer_ref__c = :lineitem.RelatedTo__c];
   Double q = Double.valueOf( lineitem.Quantity__c ); // Change the QTY Picklist to a numeric
   // Add all the Line item information to the List
   OpportunityLineItem oli = new OpportunityLineItem (OpportunityId = Opp[0].Id,PricebookEntryId = pbe[0].Id,Quantity = q, UnitPrice = pbe[0].UnitPrice);
   oliList.add(oli);
   insert oliList; // Insert the Line Item
   }  
 } 
}

Test Code:

@istest
private class testItemsUsed{
static testMethod void testItemsUsed1(){
 Account a1 = new Account(Name = 'Test Account', Division__c = 'Fire', Price_Band__c ='Fire Division Band C', Phone = '029208622998', RecordTypeId = '01220000000UVOw', Status__c='Active', Type = 'Customer');
 insert a1;
 Items_used__c i1 = new Items_Used__c(Quantity__c = '1', RelatedTo__c = 'A', Division__c = 'Fire', Account__c = a1.Id, ReferredBy__c='TEST USER', Item_Used__c = '1 Kg Powder Extinguisher');
 insert i1;
}
static testMethod void testItemsUsed2(){
 Account a2 = new Account(Name = 'Test Account', Division__c = 'Water', Phone = '029208622998', RecordTypeId = '01220000000UVOw', Status__c='Active', Type = 'Customer');
 insert a2;
 Items_used__c i2 = new Items_Used__c(Quantity__c = '1', RelatedTo__c = 'B', Account__c = a2.Id, Division__c = 'Water', ReferredBy__c='TEST USER', Item_Used__c = 'MISC');
 insert i2;
 Items_used__c i3 = new Items_Used__c(Quantity__c = '2', RelatedTo__c = 'B', Account__c = a2.Id, Division__c = 'Water', ReferredBy__c='TEST USER', Item_Used__c = 'MISC');
 insert i3;
}

}

Failure Warning:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, insertNewOpportunity: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0 Trigger.insertNewOpportunity: line 34, column 1: []

I have run the query that pulls through the records that should populate in line 34 throught eh developer console (Select Id from PriceBook2 where Id = '01s20000000PuSW' and also Select Id from PriceBook2 where Name = 'Fire Division Band A') and it brings back records.

I have tested and tested but cannot get this List index out of bounds issue to resolve itself

PLEASE HELP!!!!!

Thanks

Mike

Help??!!

 

Hi, I have been attempting to develop an Apex page that will do the following from a button click on an opportunity but after several attempts got lost:

 

Display Current Opportunity details in a page block (I can do this part)

 Start a loop{

  Display Related Quotation Details in a block

    Start a Loop{

     Display Quotation Related Products within a block

    End the loop}

 End the loop}

Save as PDF and Email

 

The finished page should look something like this:

 

---- Opportunity Details ----

 

Opportunity Name: TestOppo1

Account: TestCompany

 

---- Quote1 Details ---

 

Quote Name: Quote1

Value: £1000.00

 

--- Quote 1 Line Items ---

 

Product Name: Product 1

QTY: 1

Price: 500

Product Name: Product 2

QTY 1

Price: 500

 

---- Quote2 Details ---

 

Quote Name: Quote2

Value: £1000.00

 

--- Quote 2 Line Items ---

 

Product Name: Product 1

QTY: 1

Price: 500

Product Name: Product 2

QTY 1

Price: 500

 

-- Opportunity Detail --

 

Value: £2000

Tax: 20%

Grand Total: £2400

 

If this makes sense to anyone and you have done this is a roundabout way with another object PLEASE let me know as I

am new to APEX and this will be my first page.

 

Please let me know if I haven't provided enough detail.

 

Mike

Thinking of enabling #Communities for your customer? Then be aware of the current #Gotcha that the default Apex Classes that are created when you enable your first Community do not ALL have code coverage >75%.

What this means:
You can enable Communities in Production, however as soon as you attempt to migrate anything from a sandbox into Production that triggers all tests to be run (doesn't have to be just code), your migration will fail as three of the classes only have 33%, 20% and 21%.

Let me repeat that, you might only be migrating a bunch of new custom fields and page layouts and the Change Set (or Eclipse/ANT) will fail.

I hit this problem this week in a go-live deployment so had to update Apex Classes to achieve average total code coverage >75% in order to proceed with our deployment.

The PM of Communities knows about the problem and advises he is looking at a fix, but in the meantime here are the four Apex Classes that need to be updated.

 

CommunitiesLandingControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that takes the user to the right start page based on credentials or lack thereof
 */
@IsTest public with sharing class CommunitiesLandingControllerTest {
  @IsTest(SeeAllData=true) public static void testCommunitiesLandingController() {
    // Instantiate a new controller with all parameters in the page
    CommunitiesLandingController controller = new CommunitiesLandingController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToStartPage();
  }
}

 

CommunitiesLoginControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that exposes the site login functionality
 */
@IsTest global with sharing class CommunitiesLoginControllerTest {
  @IsTest(SeeAllData=true) 
  global static void testCommunitiesLoginController () {
    CommunitiesLoginController controller = new CommunitiesLoginController ();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToAuthPage();
  }  
}

 

CommunitiesSelfRegControllerTest.cls

A few controller variables to set prior to calling the controller method for the original test method, followed by a couple of additional test methods for further coverage.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
@IsTest public with sharing class CommunitiesSelfRegControllerTest {
  @IsTest(SeeAllData=true) 
  public static void testCommunitiesSelfRegController() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = '8yhMsHDN&ituQgO$WO';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testInvalidPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = 'not the same';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testNullPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
}

 

CommunitiesSelfRegController.cls

A few additions to this class to set the Profile and Account Ids for portal user creation. Update the ProfileId value based on the "portal" license(s) (e.g., Customer Portal, Customer Community, etc) and set the AccountId to that of the Account you wish to use for self-registration. Note: this needs to be set even if you're not using self-registration so the class can be tested.

Plus some debug statements so I could see what was happening and needed to be tested.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
public with sharing class CommunitiesSelfRegController {

  public String firstName {get; set;}
  public String lastName {get; set;}
  public String email {get; set;}
  public String password {get; set {password = value == null ? value : value.trim(); } }
  public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
  public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
  
  public CommunitiesSelfRegController() {}
  
  private boolean isValidPassword() {
    return password == confirmPassword;
  }

  public PageReference registerUser() {
  
    // it's okay if password is null - we'll send the user a random password in that case
    if (!isValidPassword()) {
      System.debug(System.LoggingLevel.DEBUG, '## DEBUG: Password is invalid - returning null');
      ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
      ApexPages.addMessage(msg);
      return null;
    }  

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    //String profileId = ''; // To be filled in by customer.
    //String roleEnum = ''; // To be filled in by customer.
    //String accountId = ''; // To be filled in by customer.

    // Set this to your main Communities Profile API Name
    String profileApiName = 'PowerCustomerSuccess';
    String profileId = [SELECT Id FROM Profile WHERE UserType = :profileApiName LIMIT 1].Id;
    List<Account> accounts = [SELECT Id FROM Account LIMIT 1];
    System.assert(!accounts.isEmpty(), 'There must be at least one account in this environment!');
    String accountId = accounts[0].Id;
    
    String userName = email;

    User u = new User();
    u.Username = userName;
    u.Email = email;
    u.FirstName = firstName;
    u.LastName = lastName;
    u.CommunityNickname = communityNickname;
    u.ProfileId = profileId;
    
    String userId = Site.createPortalUser(u, accountId, password);
   
    if (userId != null) { 
      if (password != null && password.length() > 1) {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful and password ok - returning site.login');
        return Site.login(userName, password, null);
      }
      else {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful but password not ok - redirecting to self reg confirmation');
        PageReference page = System.Page.CommunitiesSelfRegConfirm;
        page.setRedirect(true);
        return page;
      }
    }
    System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation not successful - returning null');
    return null;
  }
}

 

 

Hi Guys,

 

I have started using Chatter for Mobile and, in many cases, this allows me to attach images to records and have them appear as attachements against the record.  This is not supported however when uploading Chatter files to Tasks as the image will stay in the chatter feed but not the Attachment Related List.

 

Does anyone have an example of a trigger that will take a Task's Chatter feed (files only) when created and insert it as a Task Attachment?

 

If not, could you point me in the right direction please?

 

Many thanks

 

Mike

Hi Guys,

 

I have created an Apex page which, using Javascript, can query the Task Object from a UserId (Task Owner) and Date (Activity Date) entered on the Apex page. When a Commandbutton is clicked the Javascript function will bring back all the Tasks found and all the related Account information.  This will then produce a google route map of the users completed tasks that day, starting and ending at the Users Home address (User Postcode).

 

All of the below works fine and the map is produced, but only after I click the command button twice as the first click will not recognise the data a user has entered on the page. By the second click it has cached the entry somehow and the data can be passed to the function.

 

Does anyone know how I can get the field entries to pass to the function first time? 

 

CODE:

 

<apex:page standardController="Task" sidebar="false" showHeader="false">
<apex:includeScript value="/soap/ajax/20.0/connection.js" />
<script type="text/javascript">
var previousOnload = window.onload;
window.onload = function()
{
if (previousOnload)
{
previousOnload;
}
init();
}

function init()
{
sforce.connection.sessionId = '{!$Api.Session_ID}';
}


function Tracker(U,D){
var Uid = "'"+U+"'";
var maps;
var gurl = "http://maps.google.com/maps?q=from:";
var day= D.slice(0,2);
var month=D.slice(3,5);
var year=D.slice(6,10);
var newdate = year+"-"+month+"-"+day;
alert("User ID:"+Uid+"Date: "+D);

 

var Acc= sforce.connection.query("Select Account.Name, Account.BillingPostalCode, Time_On__c, Time_Off__c from Task where OwnerId = "+Uid+" AND ActivityDate = "+ newdate +" AND Status = 'Closed' ORDER BY LastModifiedDate ");
var ex = Acc.getArray("records");
   if (ex.length < 1) { alert("There are no Tasks to be Mapped");
   } else {

var usrq= sforce.connection.query("Select User.Postalcode from User where User.Id = "+Uid+" ");
var usr = usrq.getArray("records"); 

var maps = usr[0].PostalCode+" (Home)"+"+to:+";
for (var a=0; a < ex.length; a++) { //for all records   
maps = maps+ex[a].Account.BillingPostalCode+" ("+ ex[a].Account.Name + " "+ ex[a].Time_On__c +" - " + ex[a].Time_Off__c +") "+"+to:+";
    }
maps = maps + usr[0].PostalCode + " (Home)";
window.open(gurl+maps,"frame","menubar=1,resizable=1,scrollbars=1,width=900,height=600");
  }
}
</script>

<apex:outputPanel id="Track">
<apex:form id="thisForm">
<apex:pageBlock title="Field Tracker" mode="edit">
<apex:pageBlockButtons >
<apex:commandButton value="Start Tracking" onClick="Tracker('{!Task.OwnerId}','{!Task.ActivityDate}') "/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Please enter a User and Date:" columns="2">
<apex:inputField label="User" id="UserID" value="{!Task.OwnerId}" />
<apex:inputField label="Date" id="Date" value="{!Task.ActivityDate}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:outputPanel>

</apex:page>

 

There are 2 custom fields Time_On__c and Time_Off__C which are pretty self explanitory but if you need any more details on this please let me know.

 

PS: If anyone can help me get the map into an iframe on the page instead of a new window that would be a bonus.

 

Thanks as always

 

Mike

Hi All,

This is driving me round the bend and I think i need a new perspective on it if at all possible?

My trigger has been designed to catpure very high level product information from a custom object and create an opportuntiy invoice with an associated price book and line items.

The trigger works every time on the sandbox and I really have put it through its paces hower I simply cannot get my Test Class to run

Trigger Code:

trigger insertNewOpportunity on Items_Used__c (before insert) {
// Create Variables
List<Opportunity> listOppor = new List<Opportunity>();
List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
Set<Id> SetAccId = new Set<Id>();
 
// Create Opportunity If required
if(trigger.New[0].RelatedTo__c != null) {
  Opportunity[] exOppo = [SELECT Id from Opportunity where Customer_Ref__c = :Trigger.New[0].RelatedTo__c]; // Find an Opportunity with the same Customer Reference as the product being inserted
  
    if(exOppo.IsEmpty()){ // If no Opportunity exisits for this record
      for(Items_used__c item : Trigger.new){      
        if(item.Account__c != null){ 
          Opportunity OppNew = new Opportunity(Customer_Ref__c = item.RelatedTo__c,AccountId = item.Account__c,StageName = 'Closed Won',CloseDate = System.today(),Type = 'Existing Business',Name = 'Invoice for Visit' +' '+ item.RelatedTo__c, RecordTypeID = '01220000000UWCK',Division__c = item.Division__c,Amount = 0.00,Quote_Due_By__c = System.today(),Referred_By__c = item.ReferredBy__c,LeadSource = 'Technician Sale');
         listOppor.add(OppNew);          
        }
       insert listOppor;  // Create Opportunity 
      }
    }
}
// Insert Opportunity Line Items
 for(Items_used__c lineitem : Trigger.new){ // For all the items being inserted
  List<PriceBook2> pbook = new List<PriceBook2>();
  if((lineitem.Account__c != null) && (lineitem.RelatedTo__c != null)){
  SetAccId.add(lineitem.Account__c);
   Map<Id, Account> MapAccount = new Map<Id, Account>([select Division__c, Price_Band__c from Account where Id IN :SetAccId]);
   if(MapAccount.get(lineitem.Account__c).Price_Band__c != null){ // If the Price Band picklist for the Account is not Empty
    pbook = [Select Id from PriceBook2 where Name = :MapAccount.get(lineitem.Account__c).Price_Band__c]; 
   } // Else if the Division picklist for the Account is one of the following:
   else if(lineitem.Division__c == 'Pest'){ pbook = [Select Id from PriceBook2 where Id = '01s20000000PuSW'];} // Select the Pest Division Standard Price Book
   else if(lineitem.Division__c == 'Fire') { pbook = [Select Id from PriceBook2 where Id = '01s20000000Pz7tAAC'];} // Select the Fire Division Standard Price Book
   else if(lineitem.Division__c == 'Water') { pbook = [Select Id from PriceBook2 where Id = '01s20000000PvJCAA0'];} // Select the Pest Division Standard Price Book
   List<PriceBookEntry> pbe = new List<PriceBookEntry>(); // Get the Price Book Id
   pbe = [select Id, Pricebook2Id, UnitPrice from PriceBookEntry where Name = :lineitem.Item_Used__c AND PriceBook2Id = :pbook[0].Id];
   List<Opportunity> Opp = New List<Opportunity>(); // Get the related Opportunity Record
   Opp = [Select Id from Opportunity where Customer_ref__c = :lineitem.RelatedTo__c];
   Double q = Double.valueOf( lineitem.Quantity__c ); // Change the QTY Picklist to a numeric
   // Add all the Line item information to the List
   OpportunityLineItem oli = new OpportunityLineItem (OpportunityId = Opp[0].Id,PricebookEntryId = pbe[0].Id,Quantity = q, UnitPrice = pbe[0].UnitPrice);
   oliList.add(oli);
   insert oliList; // Insert the Line Item
   }  
 } 
}

Test Code:

@istest
private class testItemsUsed{
static testMethod void testItemsUsed1(){
 Account a1 = new Account(Name = 'Test Account', Division__c = 'Fire', Price_Band__c ='Fire Division Band C', Phone = '029208622998', RecordTypeId = '01220000000UVOw', Status__c='Active', Type = 'Customer');
 insert a1;
 Items_used__c i1 = new Items_Used__c(Quantity__c = '1', RelatedTo__c = 'A', Division__c = 'Fire', Account__c = a1.Id, ReferredBy__c='TEST USER', Item_Used__c = '1 Kg Powder Extinguisher');
 insert i1;
}
static testMethod void testItemsUsed2(){
 Account a2 = new Account(Name = 'Test Account', Division__c = 'Water', Phone = '029208622998', RecordTypeId = '01220000000UVOw', Status__c='Active', Type = 'Customer');
 insert a2;
 Items_used__c i2 = new Items_Used__c(Quantity__c = '1', RelatedTo__c = 'B', Account__c = a2.Id, Division__c = 'Water', ReferredBy__c='TEST USER', Item_Used__c = 'MISC');
 insert i2;
 Items_used__c i3 = new Items_Used__c(Quantity__c = '2', RelatedTo__c = 'B', Account__c = a2.Id, Division__c = 'Water', ReferredBy__c='TEST USER', Item_Used__c = 'MISC');
 insert i3;
}

}

Failure Warning:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, insertNewOpportunity: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0 Trigger.insertNewOpportunity: line 34, column 1: []

I have run the query that pulls through the records that should populate in line 34 throught eh developer console (Select Id from PriceBook2 where Id = '01s20000000PuSW' and also Select Id from PriceBook2 where Name = 'Fire Division Band A') and it brings back records.

I have tested and tested but cannot get this List index out of bounds issue to resolve itself

PLEASE HELP!!!!!

Thanks

Mike

Help??!!

 

Hi, I have been attempting to develop an Apex page that will do the following from a button click on an opportunity but after several attempts got lost:

 

Display Current Opportunity details in a page block (I can do this part)

 Start a loop{

  Display Related Quotation Details in a block

    Start a Loop{

     Display Quotation Related Products within a block

    End the loop}

 End the loop}

Save as PDF and Email

 

The finished page should look something like this:

 

---- Opportunity Details ----

 

Opportunity Name: TestOppo1

Account: TestCompany

 

---- Quote1 Details ---

 

Quote Name: Quote1

Value: £1000.00

 

--- Quote 1 Line Items ---

 

Product Name: Product 1

QTY: 1

Price: 500

Product Name: Product 2

QTY 1

Price: 500

 

---- Quote2 Details ---

 

Quote Name: Quote2

Value: £1000.00

 

--- Quote 2 Line Items ---

 

Product Name: Product 1

QTY: 1

Price: 500

Product Name: Product 2

QTY 1

Price: 500

 

-- Opportunity Detail --

 

Value: £2000

Tax: 20%

Grand Total: £2400

 

If this makes sense to anyone and you have done this is a roundabout way with another object PLEASE let me know as I

am new to APEX and this will be my first page.

 

Please let me know if I haven't provided enough detail.

 

Mike

Hello,

 

I developed a VF Page to mass edit records from UI using the standard controller and this is a list button. Here is my VF Page 

<apex:page standardController="Tier_Pricing__c" recordSetVar="unused" tabstyle="Tier_Pricing__c" sidebar="false">
    <apex:includeScript value="{!$Resource.UtilJS}" />
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages />            
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Return" action="{!cancel}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockTable value="{!Selected}" var="a" id="table">
                <apex:column headerValue="Name">
                    <apex:outputField value="{!a.name}"/>
                </apex:column>
                <apex:column headerValue="Price break Type">
                    <apex:outputField value="{!a.Price_Break_Type__c}"/>
                </apex:column>                
                <apex:column headerValue="Tier Number">
                    <apex:outputField value="{!a.Tier_Number__c}"/>
                </apex:column> 
                <apex:column headerValue="Value From">
                    <apex:outputField value="{!a.Value_From__c}"/>
                </apex:column>
                <apex:column headerValue="Value To">
                    <apex:outputField value="{!a.Value_To__c}"/>
                </apex:column> 
                <apex:column headerValue="Agreement Price">
                    <apex:inputField value="{!a.Agreement_Price__c}"/>
                </apex:column>                               
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

 

 

This VF page works fine and  I can able to mass edit records at a time. But, when I select records and click the list button, the records are not sorted. So I want to sort the records by Tier Number in the page.

 

 

How can I implement this? 

 

Thanks in advance

 

VPrakash

 

Hi

Is it possible to write a formula that essentially breaks the shipping address down into the individual lines?

We have an external system that needs to receive the address fields for a child object to an Account in three separate fields.

I figure if I can identify a new line character, then this should be pretty straight forward, but I can't figure out how to do this.
Any ideas?

thanks
Nick
I am trying to create tasks through the webservice API. I have code that looks something like this:

List<sObject> objs = new List<sObject>;
foreach ... {
  Task task = new Task();
  task.AccountId = accountID;
  task.WhatId = opportunityID;
  task.Subject = subject;
  task.Description = description;
  task.ActivityDate = date;
  task.IsClosed = isComplete;
  task.Priority = "Normal";
  task.Status = (isComplete) ? "Completed" : "In Progress";
  objs.Add(task);
}

sObject[] objArray = objs.ToArray();
SaveResult[] resArray = new SaveResult[objs.Count];
DebuggingInfo debInfo = binding.create(sessionHeader, new AssignmentRuleHeader(), new MruHeader(), new DebuggingHeader(), new EmailHeader(), objArray, out resArray);


The accountIds and opportunityIds were retrieved earlier in the code through the API. I have confirmed that they are valid IDs, referring to the correct accounts and opportunities that already exist in the DB.

For each task that I try to inset, I receive the following error message:
Error code is: INVALID_FIELD_FOR_INSERT_UPDATE
Error message: Unable to create/update fields: AccountId. Please check the security settings of this field and verify that it is read/write for your profile.
The error code and message seem to imply that I cannot create a task with an accountId. This seems strange, as I want to relate the task to the accountId.

Any idea on what the error message means, and how I can fix this so that I can insert tasks into the DB through the API? (And regarding the instruction to check the security settings of this field, etc, I have done some poking around in my account and I could not find where to do this, if this would indeed solve my problem).

Thanks!


Message Edited by yaakov on 03-04-2008 11:26 PM
  • March 05, 2008
  • Like
  • 0