• Alex Kirby
  • NEWBIE
  • 105 Points
  • Member since 2014

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 26
    Replies
Hi, 

This is definitely a beginner level question, but I can't find the answer.

In my email I want to display the name of an account, not the ID.

The catch is that the vf email template references a custom object's related object that is AN account (the agency account), but not THE account the the object belongs to. 

Other solutions I found say to use Account.Name but that doesn't work in this case because it isn't the record's account I'm referencing. 

The visualforce code I'm using is: {!relatedTo.Agency2__c} 

I hope that question makes some sense. I'd be grateful for any help you can offer.

​Nichelle
Is anyone else getting the following errors in the Progress tab in their DC sandboxes?
They show up before anything is opened, prior to that there was an error about Metadata failing to return the correct amount of lines. The prior error corrected itself after 10 days.

Getting all queued deployments for container=undefined
Creating deployment for containerId undefined Save=true runTests=false
Creating or Updating containerMember for containerId=undefined
public class cloneM {
    
    private final Opportunity o;    
    public CloneM (ApexPages.StandardController 
                       stdController) {
                           this.o = (Opportunity)stdController.getrecord();
                       }
    
    Public opportunity newOpp{get; set;}
    
        
    public void cloneOpp(){
        
        list<es__c> esList = [select id from es__c where opportunity_name__c =: o.id];

        
        String soql = cloneUtil.getCreatableFieldsSOQL('opportunity','id=\''+o.id+'\'');
        
        opportunity opp = (opportunity)Database.query(soql);
        opportunity newOpp = opp.clone(false, true);
        newOpp.stageName = 'Not Worked';
        insert newOpp;
        
        if(esList.size() >0){             
                        
            for(es__c es : esList){
                String soql2 = cloneUtil.getCreatableFieldsSOQL('es__c','id=\''+ es.id + '\'');
                es__c oldEs = (es_mpan__c)Database.query(soql2);
                es__c newEs = oldEs.clone(false,false);
                insert newEs;
            }	
        }
    }
}

Here is my class, I am trying to create a custom button to clone a parent record and all child records associated to it. The issue is I hit a govenor limit on the when looping through the esList as I am querying all the fields for each record. I knew this would happen but I am sruggling to solve the issue around looping through a list to retrieve all fields for each record prior to insert?
 
if(esList.size() >0){             
                        
            for(es__c es : esList){
                String soql2 = cloneUtil.getCreatableFieldsSOQL('es__c','id=\''+ es.id + '\'');
                es__c oldEs = (es__c)Database.query(soql2);
                es__c newEs = oldEs.clone(false,false);
                insert newEs;
            }	
        }

This is my issue, I am calling a utility to dynamically pull all field information for each record:

Having this is the loop is the offending line..
es__c oldEs = (es__c)Database.query(soql2);
Does anyone have any ideas on how I can resolve this without having everyfield in the class? 

Thanks in advance.
 
HI All,

I have put a small schedulable class together to run in the evenings to identify accounts with inactive owners and change them to a holding owner until they are ready to be allocated again.

The reason they need to be with an active owner is due to us pushing in data from external systems over night to keep out accounts update.

Here is the class:
 
global class inactiveAccountOwnerChange implements schedulable {
    
    global void execute(SchedulableContext SC) {
        id SFUser;
        List <Account> accountToUpdate = [Select Id, owner.Isactive from Account where owner.isactive = False];
        List <User> SFU = [Select id from user where name = 'Salesforce Unallocated'];
        
        SFUser = string.valueof(SFU[0].get('id'));
        
        for(Account a : accountToUpdate){  
            
            a.ownerid = SFUser;         
            
            update a;
        }
    }
}

This seems to work fine the issue I am having is I am only able to cover 75% of the class due to the "inactive" owner...

Here is my test class:
 
@isTest
public class test_inactiveAccountOwnerChange {
    
    static id usr;  
    
    Private Static Void Init(){  
        
        Profile p = [SELECT Id FROM Profile WHERE Name='ACM (Business Movers)']; 
        
        User u = new User(
            Alias = 'standt34', 
            Email='standarduser12234@testorg.com', 
            EmailEncodingKey='UTF-8', 
            LastName='Testing', 
            LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', 
            ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles',
            UserName='standarduser123451@testorg.com');
        
        insert u;
        usr = u.id;
        
        account a = new account();
        a.Name = 'Test';
        a.REG_ADD_LINE_1__c = 'Line 1';
        a.REG_ADD_LINE_2__c = 'Line 2';
        a.REG_ADD_LINE_3__c = 'Line 3';
        a.REG_ADD_LINE_4__c = 'Line 4';
        a.REG_ADD_TOWN__c = 'Town';
        a.REG_ADD_POSTCODE__c = 'B63 02H';
        a.Company_Type__c = 'Limited';
        a.OwnerId = u.id;
        
        Insert a;  
    }
    
    
    
    static testMethod void inactiveOwners() {   
        
        Test.startTest();
        
        init();
        
        String CRON_EXP = '0 0 0 1 1 ? 2025';  
        String jobId = System.schedule('testScheduledApex', CRON_EXP, new inactiveAccountOwnerChange() );
        CronTrigger ct = [select id, CronExpression, TimesTriggered, NextFireTime from CronTrigger where id = :jobId];
        
        System.assertEquals(CRON_EXP, ct.CronExpression); 
        System.assertEquals(0, ct.TimesTriggered);
        System.assertEquals('2025-01-01 00:00:00', String.valueOf(ct.NextFireTime));
        
        Test.stopTest();       
    }
}
I insert a test user as active, insert the account with the active user.. I am unable to set this user to inactive at this point which in turn does not cover the final part of my class lines 12 and 14..

Any ideas on how I can get round this ?

Thanks


 
Hi all, I am really struggling with creating a testclass for the below:
 
public with sharing class myCampaigns {

	public string selectedValue { get;set; }
    public List<SelectOption> statusOptions { get;set; }
    Public Integer noOfRecords{get; set;}
    Public Integer size{get;set;}    
    public string inputText1{get;set;}
            
    string queryString;
    id uId;  
    public ApexPages.StandardSetController setCon {
    
        get{
            if(setCon == null){ 
                uId = UserInfo.getUserID();
                size = 30;
                if(selectedValue == 'All' || selectedValue == null){
                queryString = 'Select id, Company, Name, Campaign_Code__c, Ownerid, LeadSource, Status, Opportunity_Start_Date__c, Opportunity_End_Date__c, Opportunity_Close_Date__c, Opportunity_Type__c From Lead where OwnerId = :uId';    
                }else{
                queryString = 'Select id, Company, Name, Campaign_Code__c, Ownerid, LeadSource, Status, Opportunity_Start_Date__c, Opportunity_End_Date__c, Opportunity_Close_Date__c, Opportunity_Type__c From Lead where OwnerId = :uId and campaign_code__c =: selectedValue';
                }
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
                setCon.setPageSize(size);
                noOfRecords = setCon.getResultSize();
            }
            return setCon;
           
        }set;  
    }
   
    Public List<Lead> getLeads(){
        List<Lead> leadList = new List<Lead>();
        for(Lead l : (List<Lead>)setCon.getRecords())
            leadList.add(L);
        return leadList;
    }
     
    public pageReference refresh() {
        setCon = null;
        getleads();
        setCon.setPageNumber(1);
        return null;
    }
     
    public Boolean hasNext {
        get {
            return setCon.getHasNext();
        }
        set;
    }
    public Boolean hasPrevious {
        get {
            return setCon.getHasPrevious();
        }
        set;
    }
  
    public Integer pageNumber {
        get {
            return setCon.getPageNumber();
        }
        set;
    }
  
    public void first() {
        setCon.first();
    }
  
    public void last() {
        setCon.last();
    }
  
    public void previous() {
        setCon.previous();
    }
  
    public void next() {
        setCon.next();
    }

    public void autoRun()
    {
        Schema.DescribeFieldResult statusFieldDescription = Lead.Campaign_code__c.getDescribe();
        statusOptions = new list<SelectOption>();
        
        for (Schema.Picklistentry picklistEntry : statusFieldDescription.getPicklistValues())
        {
            statusOptions.add(new SelectOption(pickListEntry.getValue(),pickListEntry.getLabel()));
        }
    }
}

I don't know why, I have tried many variations and still can't even get it to initialize the controller, just remains at 0%..
This is what I have so far and would of thought it would of at least shown something?
@isTest
public class test_myCampaigns {
    
    static testMethod void myCampaignsTest(){
        
        Lead l = new lead();
        l.firstName = 'Test';
        l.lastname = 'User';
        l.Company = 'Test Company';
        insert l;
        
        List <Lead> ld = [Select id from Lead];
        
        Test.startTest();
        
        Test.setCurrentPage(Page.myCampaigns);
        
        ApexPages.StandardSetController con = new ApexPages.StandardSetController(ld);
        myCampaigns ext = new myCampaigns(con);
        ext.getLeads();
        Test.stopTest();
        
    }
}

Help is always appreciated.
Hi All,

I am trying to create a visualforce page to display as a homepage component. I have created a test page with some random characters in and created a component to add to the page layout.. All of this I have done before but for some reason the VF page comes up blank when it is added to the home page layout (wide side).

I have other dev orgs weith this working but for some reason I can't get my head around why it isn't showing?!!

Help please!
Hi all,

I have a controller and a vf page to upload documents to a folder in our community. The file uploads successfully but the file extension is not captured in the process causing issues when trying to open the file.

VF:
 
<apex:pageBlock >
    
    
    <apex:pageBlockSection showHeader="false" columns="2" id="block1">

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File Name" for="fileName"/>
          <apex:inputText value="{!document.name}" id="fileName"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File" for="file"/>
          <apex:inputFile value="{!document.body}" filename="{!document.name}"  id="file"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Description" for="description"/>
          <apex:inputTextarea value="{!document.description}" id="description"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Keywords" for="keywords"/>
          <apex:inputText value="{!document.keywords}" id="keywords"/>
        </apex:pageBlockSectionItem>

      </apex:pageBlockSection>

Controller: 
 
public with sharing class qmtDocuments {

    List<Folder> fld = [Select id from Folder where DeveloperName ='qmtDocumentsFolder' limit 1];

    public List<Document> getDocuments() {
        return [select id, Name, Description, ContentType from Document Where FolderId =:fld];
    }
    
 
  public Document document {
    get {
      if (document == null)
        document = new Document();
      return document;
    }
    set;
  }
 
  public PageReference upload() {
    
    document.AuthorId = UserInfo.getUserId();
    document.FolderId = string.valueof(fld[0].get('id')); // put it in running user's folder
    document.name = document.name;
    	
    try {
      insert document;
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading file'));
      return null;
    } finally {
      document.body = null; // clears the viewstate
      document = new Document();
   
    }
 
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'File uploaded successfully'));
    return null;
  }
 
}

Result:

User-added image

The top file I entered using standard salesforce in the backend as a test.

Any help is appreciated, cheers.
Hi All,

I would like to pass a variable to myu apex class to filter the list view returned:

I would like to add a field called category on to the visualforce page and have the SOQL where clause filter by the users selection i.e. if they select 'billing' I would want the query to be Select id, CaseNumber, ContactId, Subject, Status, Priority, CreatedDate from Case where category__c = billing'

Help is always appreciated, thanks

Class:
 
public with sharing class Pagination {


    Public Integer noOfRecords{get; set;}
    Public Integer size{get;set;}    
    
    public ApexPages.StandardSetController setCon {
        get{
            if(setCon == null){
                size = 20;
                string queryString = 'Select id, CaseNumber, ContactId, Subject, Status, Priority, CreatedDate from Case';
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
                setCon.setPageSize(size);
                noOfRecords = setCon.getResultSize();
            }
            return setCon;
        }set;  
    }


    Public List<Case> getCases(){
        List<Case> caseList = new List<Case>();
        for(Case C : (List<Case>)setCon.getRecords())
            caseList.add(C);
        return caseList;
    }
     
    public pageReference refresh() {
        setCon = null;
        getCases();
        setCon.setPageNumber(1);
        return null;
    }
     
    public Boolean hasNext {
        get {
            return setCon.getHasNext();
        }
        set;
    }
    public Boolean hasPrevious {
        get {
            return setCon.getHasPrevious();
        }
        set;
    }
  
    public Integer pageNumber {
        get {
            return setCon.getPageNumber();
        }
        set;
    }
  
    public void first() {
        setCon.first();
    }
  
    public void last() {
        setCon.last();
    }
  
    public void previous() {
        setCon.previous();
    }
  
    public void next() {
        setCon.next();
    }
}
VF:
<apex:page controller="Pagination" showHeader="false">
        <apex:pageBlock id="pb" mode="maindetail">
            <apex:pageBlockTable value="{!Cases}" var="a" >
                <apex:column headerValue="Case Number">
                <apex:outputlink value="/qmt_CaseDetail?id={!a.id}">{!a.CaseNumber}</apex:outputlink>
                </apex:column>
                <apex:column value="{!a.ContactId}"/>
                <apex:column value="{!a.Subject}"/>
                <apex:column value="{!a.Status}"/>
                <apex:column value="{!a.Priority}"/>
                <apex:column value="{!a.CreatedDate}"/>
            </apex:pageBlockTable>
            <apex:panelGrid columns="7">
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value="|<" action="{!first}" disabled="{!!hasPrevious}" title="First Page"/>
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value="<" action="{!previous}" disabled="{!!hasPrevious}" title="Previous Page"/>
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value=">" action="{!next}" disabled="{!!hasNext}" title="Next Page"/>
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value=">|" action="{!last}" disabled="{!!hasNext}" title="Last Page"/>
                <apex:outputText >{!(pageNumber * size)+1-size}-{!IF((pageNumber * size)>noOfRecords, noOfRecords,(pageNumber * size))} of {!noOfRecords}</apex:outputText>
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value="Refresh" action="{!refresh}" title="Refresh Page"/>
                <apex:outputPanel style="color:#4AA02C;font-weight:bold;" >
                    <apex:actionStatus id="fetchStatus" startText="Fetching..." stopText=""/>
                </apex:outputPanel>
            </apex:panelGrid>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Hi All,

I have recently started using maps in SF and I am struggling to work out test coverage. I managed to complete the same operation using SOQL but I waned to reduce the amount used in the org.

Here is my trigger:
 
trigger Net_Mar_Ini on Net_Margin_Calculation__c (before insert) {
    
    string index;
     Map<String, Double> mapIndexToCost = new Map<String, Double>(); 
	 set<String> setcollected  = new Set<String>();
   
    for(Net_Margin_Calculation__c NM : Trigger.new){
     index = nm.index__c;   
    }
    
    setcollected.add(index + 'Acquire');
    setcollected.add(index + 'Bad Debt');
    setcollected.add(index + 'Debt Admin');
    setcollected.add(index + 'Lose');
    setcollected.add(index + 'Meter');
    setcollected.add(index + 'Other');
    setcollected.add(index + 'Register');
    setcollected.add(index + 'Renew');
    setcollected.add(index + 'Serve');
    setcollected.add(index + 'Support');
    
    for(Cost__c objCost : [select Index__C, Value__c FROM Cost__c WHERE Index__c IN : setcollected]){
            mapIndexToCost.put(objCost.Index__c, double.valueof(objCost.Value__c));}
    
    for(Net_Margin_Calculation__c NM : Trigger.new){

        if(mapIndexToCost.containskey(nm.index__c + 'Acquire')){
       	 NM.Acquire_MPAN__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Acquire'));}
	       
        if(mapIndexToCost.containskey(nm.index__c + 'Bad Debt')){
        NM.Bad_Debt_MWh__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Bad Debt'));}
                      
        if(mapIndexToCost.containskey(nm.index__c + 'Debt Admin')){
        NM.Debt_Admin_MWh__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Debt Admin'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Lose')){
        NM.Lose_MPAN__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Lose'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Meter')){
        NM.Meter_MPAN_Annum__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Meter'));}
      
        if(mapIndexToCost.containskey(nm.index__c + 'Other')){
        NM.Other_MWh__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Other'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Register')){
        NM.Register_MPAN__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Register'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Renew')){
        NM.Renew_MPAN__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Renew'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Serve')){
        NM.Serve_MPAN_Annum__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Serve'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Support')){
        NM.Support_MWh__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Support'));
        }
    }
    }

Here is my test class:
 
@isTest
public class Test_eBit {

    static testMethod void myUnitTest() {
        
        CreateAccOpp.CreateOppty();

        List<Opportunity> opps = [SELECT id FROM Opportunity];
        List<Credit_check__c> ccs = [Select id, opportunity__c, opportunity_2__c, opportunity_3__c from credit_check__c];
                 
        Id Opp = opps.get(0).Id;  
		Id ccID = ccs.get(0).Id;
        
        Net_Margin_Calculation__c NM = new Net_Margin_Calculation__c();
        nm.Opportunity_Name__c = opp;
        
        Insert NM;
        
        Cost__c c = new Cost__c();
        	c.Fuel__c = 'Power';
       		c.product__c = 'FIXED';
        	c.channel__c = 'Acquisition - Direct Versus Indirect';
            c.category__c = 'Acquire';
        	c.value__c = 1.00;     
        Insert c;
        
        

        Opportunity Op = new Opportunity();
        	Op.id = Opp;
       		Op.Annual_Volume_GWh__c = 7;
            Op.Number_of_Meters__c = 1;
            Op.Sales_Channel__c = 'Business Movers';
            Op.Product_Type__c = 'Supply (Power NHH)';
            Op.Type = 'Existing Business';
            Op.Start_Date__c = system.today()+1;
            Op.End_Date__c = system.today()+366;
            Op.Estimated_Margin_MWh__c = 2;              
        Update Op;
      
    }
    
}

This gives me 71% coverage but I can seem to cover any of the following lines: 23 / 28 / 31 and so on.

Thanks,

A
 
Hi All,

I am having trouble getting past this error in a test class as far as I can see th owners are all set correctly.

Class:
 
public with sharing class PdfGeneratorController {

    Private final Credit_Check__c CC;    
    public PdfGeneratorController (ApexPages.StandardController stdController) {
                                           this.CC= (Credit_check__c)stdController.getrecord();
                                           
                                
}
        
  
  public PageReference savePdf() {

  List<credit_check__c> aK = [Select id, opportunity__c,opportunity_2__c, opportunity_3__c
                                From credit_check__c where id=:cc.id Limit 1];
      
     	id U1 = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress Under 1GWh');
        id B1A10 = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress 1-10GWh');
        id O10 = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress Over 10GWh');
        id Ex = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress Export');
        id Es = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress Energy Solutions');
        id Ar = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Display Atradius Results');  
      
       	id U1C = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed Under 1GWh');
        id B1A10C = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed 1-10GWh');
        id O10C = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed Over 10GWh');
        id ExC = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed Export');
        id EsC = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed Energy Solutions');

        string opp2 = string.valueof(ak[0].get('opportunity_2__c'));
        string opp3 = string.valueof(ak[0].get('opportunity_3__c'));

    PageReference pdf = new PageReference('/apex/cvs_pdf?id='+apexpages.currentpage().getparameters().get('id'));

    // create the new attachment
    Attachment attach = new Attachment();

    // the contents of the attachment from the pdf
    Blob body;

    try {

        // returns the output of the page as a PDF
        body = pdf.getcontentAsPDF();


    // need to pass unit test -- current bug    
    } catch (VisualforceException e) {
        body = Blob.valueOf('Some Text'+ e);
    }

    attach.Body = body;
    // add the user entered name
    attach.Name = cc.name+'.pdf';
    attach.IsPrivate = false;
    //attach.ContentType='PDF';
    // attach the pdf to the account
    attach.ParentId = string.valueof(ak[0].get('opportunity__c'));
     
    insert attach;
    
    if(opp2 !=NULL){
    Attachment attach2 = new Attachment();

    // the contents of the attachment from the pdf
    Blob body2;

    try {

        // returns the output of the page as a PDF
        body2 = pdf.getcontentAsPDF();


    // need to pass unit test -- current bug    
    } catch (VisualforceException e) {
        body2 = Blob.valueOf('Some Text'+ e);
    }

    attach2.Body = body2;
    // add the user entered name
    attach2.Name = cc.name+'.pdf';
    attach2.IsPrivate = false;
    //attach.ContentType='PDF';
    // attach the pdf to the account
    attach2.ParentId = opp2;
     
    insert attach2;
    }
    if(opp3 !=NULL){
    Attachment attach3 = new Attachment();

    // the contents of the attachment from the pdf
    Blob body3;

    try {

        // returns the output of the page as a PDF
        body3 = pdf.getcontentAsPDF();


    // need to pass unit test -- current bug    
    } catch (VisualforceException e) {
        body3 = Blob.valueOf('Some Text'+ e);
    }

    attach3.Body = body3;
    // add the user entered name
    attach3.Name = cc.name+'.pdf';
    attach3.IsPrivate = false;
    //attach.ContentType='PDF';
    // attach the pdf to the account
    attach3.ParentId = opp3;
     
    insert attach3;
    }
    if(cc.recordtypeid == Ar){
          if(cc.cc_type__c == '<1GWh'){
                cc.recordtypeid = U1C;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
            Else If (cc.cc_type__c == '1GWh to 10GWh'){
                cc.recordtypeid = B1A10C;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
            Else If (cc.cc_type__c == '>10Gwh'){
                cc.recordtypeid = O10C;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
            Else If (cc.cc_type__c == 'Export'){    
                cc.recordtypeid = ExC;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
            Else If (cc.cc_type__c == 'Energy Solutions'){
                cc.recordtypeid = EsC;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
        
      cc.Ownerid = cc.CreatedById; 
      cc.date_of_credit_check__c = Date.valueof(system.now()); 
      cc.cc_completed__c = system.now();
      cc.Status__c = 'Closed';
      
                  
      update cc;
        
    }
      
      
            
    
    // send the user to the account to view results
    //return new PageReference('/'+ string.valueof(ak[0].get('opportunity__c')));
    
     return new PageReference('javascript:window.close()'); 

  }

}

Test Class:
 
@isTest
public class Test_PdfGeneratorController {
    
    static User testUser;
    
    static testmethod void testPdfGenerator(){   
        test.startTest();
        id Ar = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Display Atradius Results');
        
        //Select Active user
        user usr = [select name, id from user where IsActive=true and profile.name='Indirect Sales Support Analyst' limit 1];
        
        CreateAccOpp.CreateOppty();
        
		List<Account> accs = [Select id, ownerid From Account Limit 1];
        Id Acc = accs.get(0).Id;  
        
        List<Opportunity> opps = [SELECT id, number_of_meters__c, ownerid FROM Opportunity Limit 1];
        Id Opp = opps.get(0).Id;
		       
        Credit_Check__c CC = new Credit_Check__c();
            CC.Company__c = Acc;
            CC.Credit_Check_Type__c = 'Acquisition';
            CC.Ownerid = system.UserInfo.getuserid();
        	cc.opportunity__c = opp;
        	cc.Opportunity_2__c = opp;
            cc.opportunity_3__c = opp;
            CC.Requested_Payment_Days__c = '21';
            CC.Requested_Payment_Method__c = 'BACS';
            cc.Requested_Payment_Days_2__c = '21';
            cc.Requested_Payment_Method_2__c = 'BACS';
            cc.Requested_Payment_Days_3__c = '21';
            cc.Requested_Payment_Method_3__c = 'BACS';
            CC.Approval_Status__c = 'Approved without Conditions';
            CC.Date_of_Credit_Check__c = System.today();
            CC.Experian_No_Score__c = TRUE;
            CC.Experian_No_Credit_Limit__c = TRUE;
            CC.Atradius_Buyer_Rating__c = 30;
            CC.Credit_Pricing_Check__c = TRUE;
            CC.Has_Full_Insurance__c = 'Yes';
            CC.Payment_Days__c = '21';
            CC.Payment_Method__c = 'Direct Debit';
            CC.Payment_Days_2__c = '21';
            CC.Payment_Method_2__c = 'Direct Debit';    
            CC.Payment_Days_2__c = '21';
            CC.Payment_Method_2__c = 'Direct Debit';   
            CC.Payment_Performance_Score_Unavailable__c = TRUE;
            CC.Maximum_Contract_End_Date__c = System.today()+10;
            CC.Atradius_Buyer_Rating__c = null;
            CC.Atradius_Buyer_Rating_Unavailable__c = TRUE;
            CC.Atradius_Credit_Insurance_Limit__c = null;
            CC.Experian_No_Score__c = FALSE;
            CC.Experian_No_Credit_Limit__c = FALSE;
            CC.Experian_Score__c = 30;
            CC.Experian_Credit_Limit__c = 1000;
            cc.RecordTypeId = Ar;
       insert CC;
 
      //cc.Cp_From_CC__c = true;
      // update cc;
        System.debug('Account OwnerId - '+  accs.get(0).ownerid);
		System.debug('Opportunity OwnerId - '+ opps.get(0).ownerid);
        System.debug('Credit Check OwnerId - '+  cc.ownerid);
        
      // List<Credit_Check__c> ccs = [Select id, opportunity__c, opportunity_2__c, opportunity_3__c From Credit_check__c Limit 1];
      // Id ccId = ccs.get(0).Id;
      // id opp1 = ccs.get(0).opportunity__c;
      // id opp2 = ccs.get(0).opportunity_2__c;
      // id opp3 = ccs.get(0).opportunity_3__c;
        
      // for(Credit_Check__c cc : ccs){
          	
          cc.cc_type__c ='1GWh to 10GWh';
        cc.ownerid = system.UserInfo.getUserId();
          update cc;
            
           cc.cc_type__c ='>10Gwh';
        cc.ownerid = system.UserInfo.getUserId();
           update cc;
            
           cc.cc_type__c ='Export';
        cc.ownerid = system.UserInfo.getUserId();
           update cc;
            
           cc.cc_type__c ='Energy Solutions';
        cc.ownerid = system.UserInfo.getUserId();
           update cc;
            
            //set pdf visualforce page
            PageReference pref = Page.CVS_PDF;
            //set VF page id
            pref.getParameters().put('id',cc.id);
            Test.setCurrentPage(pref);
            
            //create and link visualforce page standard controller and pdf generator extension
            ApexPages.StandardController con1 = new ApexPages.StandardController(cc); 
            PdfGeneratorController con = new PdfGeneratorController(con1);
            
            // submit the record        
            pref = con.savePdf();
            
            // assert that they were sent to the correct page
            system.assertEquals(pref.getUrl(), 'javascript:window.close()');
            
            // assert that an attachment exists for the record
            //System.assertEquals(1,[select count() from attachment where parentId = :opp1 limit 1]);
            //System.assertEquals(1,[select count() from attachment where parentId = :opp2 limit 1]);
            //System.assertEquals(1,[select count() from attachment where parentId = :opp3 limit 1]);
            test.stopTest();
            
        }
        
    }
Debug log sample:


21:15:53.287 (4287509289)|DML_BEGIN|[148]|Op:Update|Type:Credit_Check__c|Rows:1 21:15:53.299 (4299084067)|DML_END|[148] 21:15:53.299 (4299208664)|VF_PAGE_MESSAGE|Owner ID: owner cannot be blank 21:15:53.299 (4299285408)|EXCEPTION_THROWN|[148]|System.DmlException: Update failed. First exception on row 0 with id a0me00000027BnDAAU; first error: INVALID_CROSS_REFERENCE_KEY, Owner ID: owner cannot be blank: [OwnerId] 21:15:53.300 (4300317592)|SYSTEM_MODE_EXIT|false 21:15:53.300 (4300340110)|METHOD_EXIT|[96]|01pe0000000450V|PdfGeneratorController.savePdf() 21:15:53.300 (4300394260)|FATAL_ERROR|System.DmlException: Update failed. First exception on row 0 with id a0me00000027BnDAAU; first error: INVALID_CROSS_REFERENCE_KEY, Owner ID: owner cannot be blank: [OwnerId]

Help is appreciated, thanks all
Hi All,

I have been working in SF for over a year now and I am trying to tidy up some old code.

I am still unsure of mpas and how to use them, as it stands I have a matrix object that I query to return a value based on a key.

I've done this using SOQL and it works fine, I need to start reducing the number of queries I have used as I am hitting the limit regularly.
 
trigger Net_Mar_Ini on Net_Margin_Calculation__c (before insert) {
    
     string Index;
         
    for(Net_Margin_Calculation__c NM : Trigger.new){
        Index = nm.index__c;
    }  

    //Acquire:
    	list<Cost__c> LV1 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Acquire'];
    //Bad Debt:
    	list<Cost__c>  LV2 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Bad Debt'];
    //Debt Admin:    
   		list<Cost__c> LV3 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Debt Admin'];
    //Lose:
        list<Cost__c>  LV4 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Lose'];
    //Meter:
        list<Cost__c> LV5 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Meter'];
    //Other:
        list<Cost__c> LV6 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Other'];  
    //Register:
        list<Cost__c> LV7 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Register'];       
    //Renew:
        list<Cost__c> LV8 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Renew'];
    //Serve:
        list<Cost__c> LV9 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Serve'];
    //Support:
        list<Cost__c> LV10 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Support'];
        
    
    for(Net_Margin_Calculation__c NM : Trigger.new){
        
    //Acquire:
       NM.Acquire_MPAN__c = Costs.get(Index).Value__c;
        
        if(LV1.size() < 1){NM.Acquire_MPAN__c = 0; }else{NM.Acquire_MPAN__c = Double.valueOf(LV1[0].get('VALUE__C'));}
    //Bad Debt:     
        if(LV2.size() < 1){NM.Bad_Debt_MWh__c = 0; }else{NM.Bad_Debt_MWh__c = Double.valueOf(LV2[0].get('VALUE__C'));}
    //Debt Admin:
        if(LV3.size() < 1){NM.Debt_Admin_MWh__c = 0; }else{NM.Debt_Admin_MWh__c = Double.valueOf(LV3[0].get('VALUE__C'));}
    //Lose:          
        if(LV4.size() < 1){NM.Lose_MPAN__c = 0; }else{NM.Lose_MPAN__c = Double.valueOf(LV4[0].get('VALUE__C'));}
    //Meter:    
        if(LV5.size() < 1){NM.Meter_MPAN_Annum__c = 0; }else{NM.Meter_MPAN_Annum__c = Double.valueOf(LV5[0].get('VALUE__C'));}
    //Other:  
        if(LV6.size() < 1){NM.Other_MWh__c = 0; }else{NM.Other_MWh__c = Double.valueOf(LV6[0].get('VALUE__C'));}
    //Register:  
        if(LV7.size() < 1){NM.Register_MPAN__c = 0; }else{NM.Register_MPAN__c = Double.valueOf(LV7[0].get('VALUE__C'));}
	//Renew:
        if(LV8.size() < 1){NM.Renew_MPAN__c = 0; }else{NM.Renew_MPAN__c = Double.valueOf(LV8[0].get('VALUE__C'));}
 	//Serve:
        if(LV9.size() < 1){NM.Serve_MPAN_Annum__c = 0; }else{NM.Serve_MPAN_Annum__c = Double.valueOf(LV9[0].get('VALUE__C'));}
	//Support:
        if(LV10.size() < 1){NM.Support_MWh__c = 0; }else{NM.Support_MWh__c = Double.valueOf(LV10[0].get('VALUE__C'));}      
    }

}
Can someone give me a nudge in the right direction so I can change the above and thu learn something new!I need to be able to have the same end result as above but there has to be another way than SOQL queries, maybe a map but as I said I am not sure.

Cheers,

A
public class cloneM {
    
    private final Opportunity o;    
    public CloneM (ApexPages.StandardController 
                       stdController) {
                           this.o = (Opportunity)stdController.getrecord();
                       }
    
    Public opportunity newOpp{get; set;}
    
        
    public void cloneOpp(){
        
        list<es__c> esList = [select id from es__c where opportunity_name__c =: o.id];

        
        String soql = cloneUtil.getCreatableFieldsSOQL('opportunity','id=\''+o.id+'\'');
        
        opportunity opp = (opportunity)Database.query(soql);
        opportunity newOpp = opp.clone(false, true);
        newOpp.stageName = 'Not Worked';
        insert newOpp;
        
        if(esList.size() >0){             
                        
            for(es__c es : esList){
                String soql2 = cloneUtil.getCreatableFieldsSOQL('es__c','id=\''+ es.id + '\'');
                es__c oldEs = (es_mpan__c)Database.query(soql2);
                es__c newEs = oldEs.clone(false,false);
                insert newEs;
            }	
        }
    }
}

Here is my class, I am trying to create a custom button to clone a parent record and all child records associated to it. The issue is I hit a govenor limit on the when looping through the esList as I am querying all the fields for each record. I knew this would happen but I am sruggling to solve the issue around looping through a list to retrieve all fields for each record prior to insert?
 
if(esList.size() >0){             
                        
            for(es__c es : esList){
                String soql2 = cloneUtil.getCreatableFieldsSOQL('es__c','id=\''+ es.id + '\'');
                es__c oldEs = (es__c)Database.query(soql2);
                es__c newEs = oldEs.clone(false,false);
                insert newEs;
            }	
        }

This is my issue, I am calling a utility to dynamically pull all field information for each record:

Having this is the loop is the offending line..
es__c oldEs = (es__c)Database.query(soql2);
Does anyone have any ideas on how I can resolve this without having everyfield in the class? 

Thanks in advance.
 
Hi All,

Please help a struggling newbie (very struggling & very new!). I have an Apex Class & a VisualForce page which I believe should work. I am completely failing in writing a test class that gives me anything greater than 0% code coverage in my sandbox.

The basic premise is that I want to display a filtered list of records from my custom object in a visualforce page, the user will then be able to update certain fields, press Save and the records will update.

My apex class & visualforce page (/FTFEdit) code are below (these have been improved by a kind developer on these forums already).

Please, please can a nice kind person help me with a test class that works.

Thanks
Emma
 
public with sharing class Controller_FTFView{
    public List<PD_Record__c> FTFRecords {get; set;}

    public Controller_FTFView(){
        FTFRecords= [
            SELECT Name, Closure_Outcome__c, FTF__c, FTF_Comment__c, FTF_Reason__c, RFA_Number__c,WR_Number__c
            FROM PD_Record__c
            WHERE WMIS_Patch__c Like '11A5%' AND Owner_Is_Me__c = 0 AND Job_Status__c = 'Closed - Successful' AND (Closure_Outcome__c = 'Parts Ordered - In Stock' OR Closure_Outcome__c = 'Parts Ordered - OOS - Is obtainable' or Closure_Outcome__c = 'One Time Buy - Obtainable' or Closure_Outcome__c = 'Safety Reasons i.e. Manufacturer referral' or Closure_Outcome__c = 'Appliance Replacement Rec. (ART)')];
    }

    public PageReference save(){
        try{
            update FTFRRecords;
        }catch(DMLException e){
            //Report DML exceptions to the Apex Page messages element in Visualforce
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,e.getMessage()));
        }

        //Returning null for the page reference, directs user back to the same VF page, but rerenders values.
        //Otherwise, you could return another Visualforce page or a link to a record's detail page here as well.
        return null;
    }

    public PageReference cancel(){
        //Return a link to the parent record perhaps or do something else besides return null here
        return null;
    }
}
<apex:page Controller="Controller_FTFView" >
    <apex:sectionHeader title="" subtitle="Mass Edit"/>
    <apex:pageMessages id="messages" />
    <apex:form >
            <apex:pageBlock mode="detail" title="Edit the following records" id="pb">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save" rerender="pb,messages"/>
                <apex:commandButton action="{!cancel}" value="Cancel" rerender="pb,messages"/>
                 </apex:pageBlockButtons>          
            <apex:pageBlockSection columns="1">
                  <apex:pageBlockTable value="{!FTFRecords}" var="p">
                    <apex:column value="{!p.Name}"/>          
                    <apex:column value="{!p.WR_Number__c}"/>
                    <apex:column value="{!p.RFA_Number__c}"/>
                    <apex:column value="{!p.Closure_Outcome__c}"/>     
                    <apex:column headerValue="FTF?" >                   
                        <apex:inputField value="{!p.FTF__c}"/>
                    </apex:column>
                    <apex:column headerValue="FTF Reason" >                   
                        <apex:inputField value="{!p.FTF_Reason__c}"/>
                    </apex:column>
                    <apex:column headerValue="FTF Comment" >
                        <apex:inputField value="{!p.FTF_Comment__c}"/>
                    </apex:column>                    
                  </apex:pageBlockTable>
       </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>



 
HI All,

I have put a small schedulable class together to run in the evenings to identify accounts with inactive owners and change them to a holding owner until they are ready to be allocated again.

The reason they need to be with an active owner is due to us pushing in data from external systems over night to keep out accounts update.

Here is the class:
 
global class inactiveAccountOwnerChange implements schedulable {
    
    global void execute(SchedulableContext SC) {
        id SFUser;
        List <Account> accountToUpdate = [Select Id, owner.Isactive from Account where owner.isactive = False];
        List <User> SFU = [Select id from user where name = 'Salesforce Unallocated'];
        
        SFUser = string.valueof(SFU[0].get('id'));
        
        for(Account a : accountToUpdate){  
            
            a.ownerid = SFUser;         
            
            update a;
        }
    }
}

This seems to work fine the issue I am having is I am only able to cover 75% of the class due to the "inactive" owner...

Here is my test class:
 
@isTest
public class test_inactiveAccountOwnerChange {
    
    static id usr;  
    
    Private Static Void Init(){  
        
        Profile p = [SELECT Id FROM Profile WHERE Name='ACM (Business Movers)']; 
        
        User u = new User(
            Alias = 'standt34', 
            Email='standarduser12234@testorg.com', 
            EmailEncodingKey='UTF-8', 
            LastName='Testing', 
            LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', 
            ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles',
            UserName='standarduser123451@testorg.com');
        
        insert u;
        usr = u.id;
        
        account a = new account();
        a.Name = 'Test';
        a.REG_ADD_LINE_1__c = 'Line 1';
        a.REG_ADD_LINE_2__c = 'Line 2';
        a.REG_ADD_LINE_3__c = 'Line 3';
        a.REG_ADD_LINE_4__c = 'Line 4';
        a.REG_ADD_TOWN__c = 'Town';
        a.REG_ADD_POSTCODE__c = 'B63 02H';
        a.Company_Type__c = 'Limited';
        a.OwnerId = u.id;
        
        Insert a;  
    }
    
    
    
    static testMethod void inactiveOwners() {   
        
        Test.startTest();
        
        init();
        
        String CRON_EXP = '0 0 0 1 1 ? 2025';  
        String jobId = System.schedule('testScheduledApex', CRON_EXP, new inactiveAccountOwnerChange() );
        CronTrigger ct = [select id, CronExpression, TimesTriggered, NextFireTime from CronTrigger where id = :jobId];
        
        System.assertEquals(CRON_EXP, ct.CronExpression); 
        System.assertEquals(0, ct.TimesTriggered);
        System.assertEquals('2025-01-01 00:00:00', String.valueOf(ct.NextFireTime));
        
        Test.stopTest();       
    }
}
I insert a test user as active, insert the account with the active user.. I am unable to set this user to inactive at this point which in turn does not cover the final part of my class lines 12 and 14..

Any ideas on how I can get round this ?

Thanks


 
Hi all, I am really struggling with creating a testclass for the below:
 
public with sharing class myCampaigns {

	public string selectedValue { get;set; }
    public List<SelectOption> statusOptions { get;set; }
    Public Integer noOfRecords{get; set;}
    Public Integer size{get;set;}    
    public string inputText1{get;set;}
            
    string queryString;
    id uId;  
    public ApexPages.StandardSetController setCon {
    
        get{
            if(setCon == null){ 
                uId = UserInfo.getUserID();
                size = 30;
                if(selectedValue == 'All' || selectedValue == null){
                queryString = 'Select id, Company, Name, Campaign_Code__c, Ownerid, LeadSource, Status, Opportunity_Start_Date__c, Opportunity_End_Date__c, Opportunity_Close_Date__c, Opportunity_Type__c From Lead where OwnerId = :uId';    
                }else{
                queryString = 'Select id, Company, Name, Campaign_Code__c, Ownerid, LeadSource, Status, Opportunity_Start_Date__c, Opportunity_End_Date__c, Opportunity_Close_Date__c, Opportunity_Type__c From Lead where OwnerId = :uId and campaign_code__c =: selectedValue';
                }
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
                setCon.setPageSize(size);
                noOfRecords = setCon.getResultSize();
            }
            return setCon;
           
        }set;  
    }
   
    Public List<Lead> getLeads(){
        List<Lead> leadList = new List<Lead>();
        for(Lead l : (List<Lead>)setCon.getRecords())
            leadList.add(L);
        return leadList;
    }
     
    public pageReference refresh() {
        setCon = null;
        getleads();
        setCon.setPageNumber(1);
        return null;
    }
     
    public Boolean hasNext {
        get {
            return setCon.getHasNext();
        }
        set;
    }
    public Boolean hasPrevious {
        get {
            return setCon.getHasPrevious();
        }
        set;
    }
  
    public Integer pageNumber {
        get {
            return setCon.getPageNumber();
        }
        set;
    }
  
    public void first() {
        setCon.first();
    }
  
    public void last() {
        setCon.last();
    }
  
    public void previous() {
        setCon.previous();
    }
  
    public void next() {
        setCon.next();
    }

    public void autoRun()
    {
        Schema.DescribeFieldResult statusFieldDescription = Lead.Campaign_code__c.getDescribe();
        statusOptions = new list<SelectOption>();
        
        for (Schema.Picklistentry picklistEntry : statusFieldDescription.getPicklistValues())
        {
            statusOptions.add(new SelectOption(pickListEntry.getValue(),pickListEntry.getLabel()));
        }
    }
}

I don't know why, I have tried many variations and still can't even get it to initialize the controller, just remains at 0%..
This is what I have so far and would of thought it would of at least shown something?
@isTest
public class test_myCampaigns {
    
    static testMethod void myCampaignsTest(){
        
        Lead l = new lead();
        l.firstName = 'Test';
        l.lastname = 'User';
        l.Company = 'Test Company';
        insert l;
        
        List <Lead> ld = [Select id from Lead];
        
        Test.startTest();
        
        Test.setCurrentPage(Page.myCampaigns);
        
        ApexPages.StandardSetController con = new ApexPages.StandardSetController(ld);
        myCampaigns ext = new myCampaigns(con);
        ext.getLeads();
        Test.stopTest();
        
    }
}

Help is always appreciated.
Hi All,

I am trying to create a visualforce page to display as a homepage component. I have created a test page with some random characters in and created a component to add to the page layout.. All of this I have done before but for some reason the VF page comes up blank when it is added to the home page layout (wide side).

I have other dev orgs weith this working but for some reason I can't get my head around why it isn't showing?!!

Help please!
Hi all,

I have a controller and a vf page to upload documents to a folder in our community. The file uploads successfully but the file extension is not captured in the process causing issues when trying to open the file.

VF:
 
<apex:pageBlock >
    
    
    <apex:pageBlockSection showHeader="false" columns="2" id="block1">

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File Name" for="fileName"/>
          <apex:inputText value="{!document.name}" id="fileName"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File" for="file"/>
          <apex:inputFile value="{!document.body}" filename="{!document.name}"  id="file"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Description" for="description"/>
          <apex:inputTextarea value="{!document.description}" id="description"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Keywords" for="keywords"/>
          <apex:inputText value="{!document.keywords}" id="keywords"/>
        </apex:pageBlockSectionItem>

      </apex:pageBlockSection>

Controller: 
 
public with sharing class qmtDocuments {

    List<Folder> fld = [Select id from Folder where DeveloperName ='qmtDocumentsFolder' limit 1];

    public List<Document> getDocuments() {
        return [select id, Name, Description, ContentType from Document Where FolderId =:fld];
    }
    
 
  public Document document {
    get {
      if (document == null)
        document = new Document();
      return document;
    }
    set;
  }
 
  public PageReference upload() {
    
    document.AuthorId = UserInfo.getUserId();
    document.FolderId = string.valueof(fld[0].get('id')); // put it in running user's folder
    document.name = document.name;
    	
    try {
      insert document;
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading file'));
      return null;
    } finally {
      document.body = null; // clears the viewstate
      document = new Document();
   
    }
 
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'File uploaded successfully'));
    return null;
  }
 
}

Result:

User-added image

The top file I entered using standard salesforce in the backend as a test.

Any help is appreciated, cheers.
Hi All,

I would like to pass a variable to myu apex class to filter the list view returned:

I would like to add a field called category on to the visualforce page and have the SOQL where clause filter by the users selection i.e. if they select 'billing' I would want the query to be Select id, CaseNumber, ContactId, Subject, Status, Priority, CreatedDate from Case where category__c = billing'

Help is always appreciated, thanks

Class:
 
public with sharing class Pagination {


    Public Integer noOfRecords{get; set;}
    Public Integer size{get;set;}    
    
    public ApexPages.StandardSetController setCon {
        get{
            if(setCon == null){
                size = 20;
                string queryString = 'Select id, CaseNumber, ContactId, Subject, Status, Priority, CreatedDate from Case';
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
                setCon.setPageSize(size);
                noOfRecords = setCon.getResultSize();
            }
            return setCon;
        }set;  
    }


    Public List<Case> getCases(){
        List<Case> caseList = new List<Case>();
        for(Case C : (List<Case>)setCon.getRecords())
            caseList.add(C);
        return caseList;
    }
     
    public pageReference refresh() {
        setCon = null;
        getCases();
        setCon.setPageNumber(1);
        return null;
    }
     
    public Boolean hasNext {
        get {
            return setCon.getHasNext();
        }
        set;
    }
    public Boolean hasPrevious {
        get {
            return setCon.getHasPrevious();
        }
        set;
    }
  
    public Integer pageNumber {
        get {
            return setCon.getPageNumber();
        }
        set;
    }
  
    public void first() {
        setCon.first();
    }
  
    public void last() {
        setCon.last();
    }
  
    public void previous() {
        setCon.previous();
    }
  
    public void next() {
        setCon.next();
    }
}
VF:
<apex:page controller="Pagination" showHeader="false">
        <apex:pageBlock id="pb" mode="maindetail">
            <apex:pageBlockTable value="{!Cases}" var="a" >
                <apex:column headerValue="Case Number">
                <apex:outputlink value="/qmt_CaseDetail?id={!a.id}">{!a.CaseNumber}</apex:outputlink>
                </apex:column>
                <apex:column value="{!a.ContactId}"/>
                <apex:column value="{!a.Subject}"/>
                <apex:column value="{!a.Status}"/>
                <apex:column value="{!a.Priority}"/>
                <apex:column value="{!a.CreatedDate}"/>
            </apex:pageBlockTable>
            <apex:panelGrid columns="7">
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value="|<" action="{!first}" disabled="{!!hasPrevious}" title="First Page"/>
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value="<" action="{!previous}" disabled="{!!hasPrevious}" title="Previous Page"/>
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value=">" action="{!next}" disabled="{!!hasNext}" title="Next Page"/>
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value=">|" action="{!last}" disabled="{!!hasNext}" title="Last Page"/>
                <apex:outputText >{!(pageNumber * size)+1-size}-{!IF((pageNumber * size)>noOfRecords, noOfRecords,(pageNumber * size))} of {!noOfRecords}</apex:outputText>
                <apex:commandButton styleClass="metro" status="fetchStatus" reRender="pb" value="Refresh" action="{!refresh}" title="Refresh Page"/>
                <apex:outputPanel style="color:#4AA02C;font-weight:bold;" >
                    <apex:actionStatus id="fetchStatus" startText="Fetching..." stopText=""/>
                </apex:outputPanel>
            </apex:panelGrid>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Hi All,

I have recently started using maps in SF and I am struggling to work out test coverage. I managed to complete the same operation using SOQL but I waned to reduce the amount used in the org.

Here is my trigger:
 
trigger Net_Mar_Ini on Net_Margin_Calculation__c (before insert) {
    
    string index;
     Map<String, Double> mapIndexToCost = new Map<String, Double>(); 
	 set<String> setcollected  = new Set<String>();
   
    for(Net_Margin_Calculation__c NM : Trigger.new){
     index = nm.index__c;   
    }
    
    setcollected.add(index + 'Acquire');
    setcollected.add(index + 'Bad Debt');
    setcollected.add(index + 'Debt Admin');
    setcollected.add(index + 'Lose');
    setcollected.add(index + 'Meter');
    setcollected.add(index + 'Other');
    setcollected.add(index + 'Register');
    setcollected.add(index + 'Renew');
    setcollected.add(index + 'Serve');
    setcollected.add(index + 'Support');
    
    for(Cost__c objCost : [select Index__C, Value__c FROM Cost__c WHERE Index__c IN : setcollected]){
            mapIndexToCost.put(objCost.Index__c, double.valueof(objCost.Value__c));}
    
    for(Net_Margin_Calculation__c NM : Trigger.new){

        if(mapIndexToCost.containskey(nm.index__c + 'Acquire')){
       	 NM.Acquire_MPAN__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Acquire'));}
	       
        if(mapIndexToCost.containskey(nm.index__c + 'Bad Debt')){
        NM.Bad_Debt_MWh__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Bad Debt'));}
                      
        if(mapIndexToCost.containskey(nm.index__c + 'Debt Admin')){
        NM.Debt_Admin_MWh__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Debt Admin'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Lose')){
        NM.Lose_MPAN__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Lose'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Meter')){
        NM.Meter_MPAN_Annum__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Meter'));}
      
        if(mapIndexToCost.containskey(nm.index__c + 'Other')){
        NM.Other_MWh__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Other'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Register')){
        NM.Register_MPAN__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Register'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Renew')){
        NM.Renew_MPAN__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Renew'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Serve')){
        NM.Serve_MPAN_Annum__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Serve'));}
        
        if(mapIndexToCost.containskey(nm.index__c + 'Support')){
        NM.Support_MWh__c = Double.valueOf(mapIndexToCost.get(nm.index__c + 'Support'));
        }
    }
    }

Here is my test class:
 
@isTest
public class Test_eBit {

    static testMethod void myUnitTest() {
        
        CreateAccOpp.CreateOppty();

        List<Opportunity> opps = [SELECT id FROM Opportunity];
        List<Credit_check__c> ccs = [Select id, opportunity__c, opportunity_2__c, opportunity_3__c from credit_check__c];
                 
        Id Opp = opps.get(0).Id;  
		Id ccID = ccs.get(0).Id;
        
        Net_Margin_Calculation__c NM = new Net_Margin_Calculation__c();
        nm.Opportunity_Name__c = opp;
        
        Insert NM;
        
        Cost__c c = new Cost__c();
        	c.Fuel__c = 'Power';
       		c.product__c = 'FIXED';
        	c.channel__c = 'Acquisition - Direct Versus Indirect';
            c.category__c = 'Acquire';
        	c.value__c = 1.00;     
        Insert c;
        
        

        Opportunity Op = new Opportunity();
        	Op.id = Opp;
       		Op.Annual_Volume_GWh__c = 7;
            Op.Number_of_Meters__c = 1;
            Op.Sales_Channel__c = 'Business Movers';
            Op.Product_Type__c = 'Supply (Power NHH)';
            Op.Type = 'Existing Business';
            Op.Start_Date__c = system.today()+1;
            Op.End_Date__c = system.today()+366;
            Op.Estimated_Margin_MWh__c = 2;              
        Update Op;
      
    }
    
}

This gives me 71% coverage but I can seem to cover any of the following lines: 23 / 28 / 31 and so on.

Thanks,

A
 
Hi, 

This is definitely a beginner level question, but I can't find the answer.

In my email I want to display the name of an account, not the ID.

The catch is that the vf email template references a custom object's related object that is AN account (the agency account), but not THE account the the object belongs to. 

Other solutions I found say to use Account.Name but that doesn't work in this case because it isn't the record's account I'm referencing. 

The visualforce code I'm using is: {!relatedTo.Agency2__c} 

I hope that question makes some sense. I'd be grateful for any help you can offer.

​Nichelle

 

Hello, 

I am trying to create a visualforce page that displays all of the current User's Opportunities. I would like to include Opportunities that they own AND all Opportunities where they are a member of the OpportunityTEam. 

My first attempt was to do a query like this:

MyOpTeam =[SELECT id, Record_Type_Name__c,  Name, StageName, Amount,  Owner.Id FROM Opportunity WHERE id IN (SELECT OpportunityId FROM OpportunityTeamMember WHERE (UserId=:UserInfo.getUserId() )OR (Opportunity.OwnerId=:UserInfo.getUserId())];  
*** PROBLEM: this only pulled opportunities that had team members. Any opportunities that I owned that did not have a team member record were excluded. 

Could anyone look at my current code and tell me how I can go about getting these two SEPARATE queries into one list? 
public class Oppsownerteam {
public Oppsownerteam(ApexPages.StandardController controller) {
        
}
    
 Id Mouse = Userinfo.getUserId();
 public List<Opportunity> MyOwnedOpps;
 public List<Opportunity> MyTEamOpps;
 

            Public Integer Get MyOwnedOpps()
               {
                  MyOwnedOpps =[SELECT id, Record_Type_Name__c,  Name, StageName, Amount,  Owner.Id FROM Opportunity WHERE ownerid =:Mouse];  
                return   MyOwnedOpps;       
                }
            

             Public List<Opportunity> GetMyTEamOpps()
               {                        
                MyTEamOpps =[SELECT id, Record_Type_Name__c,  Name, StageName, Amount,  Owner.Id FROM Opportunity WHERE id IN (SELECT OpportunityId FROM OpportunityTeamMember WHERE UserId=:Mouse)];  
                   
                return MyTEamOpps;                               
                 }
            
  



}

 
Hi All,

I have been working in SF for over a year now and I am trying to tidy up some old code.

I am still unsure of mpas and how to use them, as it stands I have a matrix object that I query to return a value based on a key.

I've done this using SOQL and it works fine, I need to start reducing the number of queries I have used as I am hitting the limit regularly.
 
trigger Net_Mar_Ini on Net_Margin_Calculation__c (before insert) {
    
     string Index;
         
    for(Net_Margin_Calculation__c NM : Trigger.new){
        Index = nm.index__c;
    }  

    //Acquire:
    	list<Cost__c> LV1 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Acquire'];
    //Bad Debt:
    	list<Cost__c>  LV2 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Bad Debt'];
    //Debt Admin:    
   		list<Cost__c> LV3 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Debt Admin'];
    //Lose:
        list<Cost__c>  LV4 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Lose'];
    //Meter:
        list<Cost__c> LV5 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Meter'];
    //Other:
        list<Cost__c> LV6 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Other'];  
    //Register:
        list<Cost__c> LV7 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Register'];       
    //Renew:
        list<Cost__c> LV8 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Renew'];
    //Serve:
        list<Cost__c> LV9 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Serve'];
    //Support:
        list<Cost__c> LV10 = [SELECT VALUE__C FROM Cost__c WHERE Index__c = :Index + 'Support'];
        
    
    for(Net_Margin_Calculation__c NM : Trigger.new){
        
    //Acquire:
       NM.Acquire_MPAN__c = Costs.get(Index).Value__c;
        
        if(LV1.size() < 1){NM.Acquire_MPAN__c = 0; }else{NM.Acquire_MPAN__c = Double.valueOf(LV1[0].get('VALUE__C'));}
    //Bad Debt:     
        if(LV2.size() < 1){NM.Bad_Debt_MWh__c = 0; }else{NM.Bad_Debt_MWh__c = Double.valueOf(LV2[0].get('VALUE__C'));}
    //Debt Admin:
        if(LV3.size() < 1){NM.Debt_Admin_MWh__c = 0; }else{NM.Debt_Admin_MWh__c = Double.valueOf(LV3[0].get('VALUE__C'));}
    //Lose:          
        if(LV4.size() < 1){NM.Lose_MPAN__c = 0; }else{NM.Lose_MPAN__c = Double.valueOf(LV4[0].get('VALUE__C'));}
    //Meter:    
        if(LV5.size() < 1){NM.Meter_MPAN_Annum__c = 0; }else{NM.Meter_MPAN_Annum__c = Double.valueOf(LV5[0].get('VALUE__C'));}
    //Other:  
        if(LV6.size() < 1){NM.Other_MWh__c = 0; }else{NM.Other_MWh__c = Double.valueOf(LV6[0].get('VALUE__C'));}
    //Register:  
        if(LV7.size() < 1){NM.Register_MPAN__c = 0; }else{NM.Register_MPAN__c = Double.valueOf(LV7[0].get('VALUE__C'));}
	//Renew:
        if(LV8.size() < 1){NM.Renew_MPAN__c = 0; }else{NM.Renew_MPAN__c = Double.valueOf(LV8[0].get('VALUE__C'));}
 	//Serve:
        if(LV9.size() < 1){NM.Serve_MPAN_Annum__c = 0; }else{NM.Serve_MPAN_Annum__c = Double.valueOf(LV9[0].get('VALUE__C'));}
	//Support:
        if(LV10.size() < 1){NM.Support_MWh__c = 0; }else{NM.Support_MWh__c = Double.valueOf(LV10[0].get('VALUE__C'));}      
    }

}
Can someone give me a nudge in the right direction so I can change the above and thu learn something new!I need to be able to have the same end result as above but there has to be another way than SOQL queries, maybe a map but as I said I am not sure.

Cheers,

A