• sandeep1989
  • NEWBIE
  • 65 Points
  • Member since 2012

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 14
    Replies

I'm writing a test class for a trigger that runs on after insert or after update on Opps. My after insert test is working fine but I can't seem to get the update test to work. 

// Create the new Opportunity record
        Account a = new Account(~sets fields~);
        Opportunity opp = new Opportunity(CurrencyIsoCode = 'EUR', License_Amount__c = double.valueOf('1000.00') ~sets other required fields~);
        insert opp;

        test.startTest();
        
        opp.License_Amount__c = double.valueOf('2000.00');
        update opp;
        
        test.stopTest();
        
        //query the updated opp
        Opportunity oppRecordUpdated = [SELECT Amount_USD__c, Amount FROM Opportunity WHERE ID = :opp.ID];
                 
        // If the trigger works, then the opp's Amount_USD__c field should now be 2000 EUR converted to USD
        System.assertEquals(Math.roundtolong(oppRecordUpdated.Amount_USD__c), Math.roundtolong(oppRecordUpdated.Amount / EUR.ConversionRate));
        

        }

}

 what's happening is Amount USD is not getting updated - the number returned is based on what happened on the insert, not on the update. When I check my code coverage on the trigger, it shows the update trigger as NOT having coverage. How do I ensure that update trigger is run? Thought I had it with the starttest statement but apparently not. 

  • June 19, 2013
  • Like
  • 0

Hello,

 

I want to retrieve Corporate currency value using SOQL query.

 

I have checked Organization object - it has information for Locale & Language but it doesn't have information for Corporate Currency value.

 

How can I retrieve Corporate currency value?

 

Thanks

Hi and thanks in advance for your help.

I have created a custom activity field (Time zone) and it is available to both tasks and events.  I want the time zone field to retain the value for the time zone field on subsequent task and events added.

For example, an event/ task is added to a lead and a timezone is chosen.  The agent then hits the save and add new event, I want the Timezone field to contain the value from the first event/task.

Thank you

Does anyone know how to generate a customised unique Opportunity proposal reference?

 

I am looking to create within SalesForce a customised proposal reference number as an Opportunity field that uses the value from a user defined service line to create a unique reference that is sequential to each service line .... ie

 

{YY}{MM} (Service_value__c )-{0}

 

eg 130600-001, 130601-001 etc ...

 

any help appreciated in solving this one

 

Fraser - Perth, WA

Hi!  I am trying to get me org ready for a server change and am trying to make my buttons domain independent.  For instance, I have a button that references a URL:

 

Button URL:  https://mkto-si.na0.visual.force.com/apex/mkto_si__Send_Marketo_Email?contactType=Lead&contactIds={!Lead.Id}

 

I will no longer be on server na0.  How do I make this button work regardless of the domail?  I tried the following to no avail:

.../apex/mkto_si__Send_Marketo_Email?contactType=Lead&contactIds={!Lead.Id}

apex/mkto_si__Send_Marketo_Email?contactType=Lead&contactIds={!Lead.Id}

 

Nothing seems to work.

I'm writing a test class for a trigger that runs on after insert or after update on Opps. My after insert test is working fine but I can't seem to get the update test to work. 

// Create the new Opportunity record
        Account a = new Account(~sets fields~);
        Opportunity opp = new Opportunity(CurrencyIsoCode = 'EUR', License_Amount__c = double.valueOf('1000.00') ~sets other required fields~);
        insert opp;

        test.startTest();
        
        opp.License_Amount__c = double.valueOf('2000.00');
        update opp;
        
        test.stopTest();
        
        //query the updated opp
        Opportunity oppRecordUpdated = [SELECT Amount_USD__c, Amount FROM Opportunity WHERE ID = :opp.ID];
                 
        // If the trigger works, then the opp's Amount_USD__c field should now be 2000 EUR converted to USD
        System.assertEquals(Math.roundtolong(oppRecordUpdated.Amount_USD__c), Math.roundtolong(oppRecordUpdated.Amount / EUR.ConversionRate));
        

        }

}

 what's happening is Amount USD is not getting updated - the number returned is based on what happened on the insert, not on the update. When I check my code coverage on the trigger, it shows the update trigger as NOT having coverage. How do I ensure that update trigger is run? Thought I had it with the starttest statement but apparently not. 

  • June 19, 2013
  • Like
  • 0

Hi there, I was hoping I would be able to get some guidance on the preferred solution to get this working in salesforce.

 

There is currenty a formula field in our opportunities that look at three fields to caculate whether an opportunity is active: 

 

AND( IsWon = True, Billing_Start_Date__c  <= TODAY(), Contract_End_Date__c  >= TODAY()).

 

The issue is that I plan on rolling up opportunities that are "active" on the account, however salesforce doesn't support filtering the opportunities for rollup using a formula field.

 

Looking at the conditions of when an opportunity is active, it seems either a workflow rule or apex trigger should be used to update the Active flag in the opportunity so that I could use it as a condition to rollup opps on the account.  However, this will need to trigger on a nighty basis and compare the opportunity date fields to today.  

 

Has anyone worked on a similar solution and would know whether the apex trigger should be appropriate for this solution?Or could I get this to work with time dependent workflow rules?  Any help is greaty appreciated.

 

Thanks!

Steve 

I have a button on task list view which allows users to mass update their tasks.

 

I  have one issue when users are trying to update their tasks using My mass updates tasks functionality they are unable to update their recurring tasks. It throws an exception and when i test it i was able to update some and unable to update some.

 

 

caused by: System.DmlException: Update failed. First exception on row 0 with id 00T3000001rxU18EAE; first error: INVALID_FIELD_FOR_INSERT_UPDATE, You cannot update the Status of a recurring task.: [Status]

 

public class TaskListViewController { 
     
    public String objectId {get; set;}
    public Integer numLeft {get; set;}
    public Integer total {get; set;}    
    private Integer startNdx = 0;
    private static Integer PAGESIZE = 8;
    private List<Task> fullTaskList = new List<Task>();
    private List<Task> displayedTaskList = new List<Task>();
    
    
    public TaskListViewController() {

    }
    
    public PageReference refreshPage() {
        return null;
    }
   
    public List<Task> getTasks() {
        String ownerId = UserInfo.getUserId();
        if (fullTaskList.isEmpty())
        {
            fullTaskList = [SELECT Id, WhatId, WhoId, ActivityDate, subject,Activity_Type__c ,status, priority, Description,  ReminderDateTime, IsReminderSet,isClosed 
                            FROM Task 
                            WHERE isClosed = false 
                            AND OwnerId = :ownerId];
            numLeft = fullTaskList.size();
            total = numLeft;
            if(numLeft <> 0)
                this.objectId = ((Task) fullTaskList[0]).id;
         }
        
        displayedTaskList.clear();
        if(numLeft <> 0)
        {
        Integer endNdx = startNdx + PAGESIZE;
        if (endNdx > total)
            endNdx = total;
            
        for (Integer i=startNdx; i<endNdx; i++)
            displayedTaskList.add(fullTaskList.get(i));
         }           
        return displayedTaskList;
    }
 
    private void updateTaskStatus() {
        System.debug('before : ' + fullTaskList);
        Integer i = 0;
        for (i=0; i<fullTaskList.size(); i++) {
            Task t = fullTaskList.get(i);
            if (this.objectId.equals(t.id)) {
                System.debug('updating status of ' + t);                                
                Task tmp = [SELECT Id, WhatId, WhoId, ActivityDate, subject, status, priority, Description, ReminderDateTime, IsReminderSet, isClosed 
                            FROM Task 
                            WHERE id = :t.id];
                fullTaskList.set(i, tmp);
                System.debug('updated to ' + tmp);
                //this.updatedItemStatus = tmp.status;
                break;
            }
        }
        
        System.debug('after : ' + fullTaskList);               
    }
    
    private void nextTask() {
        for (Task t : fullTaskList) {
            if (!t.isClosed) {
                System.debug('found non-closed object with id ' + t.id);
                this.objectId = t.id;
                break;
            }
        }
    }
  

    public void previous() {
        startNdx -= PAGESIZE;
    }
    
    public void next() {
        startNdx += PAGESIZE;
    }    
    
    public void refreshNumbers() {
        updateTaskStatus();
        nextTask();
        this.numLeft = 0;
        for (Task t : fullTaskList) {
            if (!t.isClosed) {
                this.numLeft++;
            }
        }        
      }
    
    public Boolean getHasNext() {
        return total > (startNdx + PAGESIZE);
    }
    
    public Boolean getHasPrevious() {
        return startNdx > 0;
    }    

    public Integer getNum() {
        return total;
    } 
    public PageReference Cancel() {
    PageReference Activitiespage = Page.Activities;
           Activitiespage.setRedirect(true);
           return Activitiespage;
       
    }
    public PageReference save(){       
        for (Task t : fullTaskList) {
           update t;
           
        }
       PageReference Activitiespage = Page.Activities;
           Activitiespage.setRedirect(true);
           return Activitiespage;
    }
    }

 

<apex:page controller="TaskListViewController" standardStylesheets="true" showHeader="true">

    <apex:form id="taskList">
         <script>
            
            function checkIfNeedRefresh() {
                //alert('checking for full refresh');
                var left = document.getElementById('{!$Component.taskList.numberOfItemsLeft}');
                //alert('found items left todo : ' + left.innerHTML);
                var tmp = parseInt(left.innerHTML);
                if (tmp == NaN || tmp == 0) {  
                    parent.refreshPage(); 
                } 
            }

            
        </script>
        <apex:pageBlock id="pageBlock" title="My Tasks List">
        
            <apex:pageBlockButtons >
                    <apex:commandButton action="{!save}" value="Save" id="theButton"/>
                    <apex:commandButton action="{!Cancel}" value="Cancel" id="theButton1"/>
            </apex:pageBlockButtons>
            
            <apex:outputText rendered="{!(tasks.size = 0)}" value="No Open Tasks To display." escape="false"/>
            
            <apex:pageBlockTable value="{!tasks}" var="o" id="table2" rendered="{!IF(tasks.size > 0, true, false)}">
           
<!--
                <apex:column >
                    <apex:commandLink action="{!go}" value="{!o.subject}" reRender="detail">
                         <apex:param value="{!o.id}" name="objectId" assignTo="{!objectId}"></apex:param>
                    </apex:commandLink>
                </apex:column> 
-->
                <apex:column >
                     <apex:facet name="header" ><strong>Subject</strong></apex:facet> 
                     <apex:outputLink title="" value="/{!o.Id}">{!o.subject}</apex:outputLink>
                </apex:column>
<!--
                <apex:column >   
                   <apex:commandLink action="{!go}" rerender="form"> {!o.Subject}
                         <apex:param name="id" value="{!o.Id}"/>
                   </apex:commandLink>
                </apex:column> 
-->
                <apex:column id="status" headerValue="Status"> 
                    <apex:inputField value="{!o.status}"/>
                </apex:column>
<!--            <apex:column id="priority" headerValue="Priority"> 
                    <apex:inputField value="{!o.priority}"/>
                </apex:column> 
-->
                <Apex:column id="type" headervalue="Activity Type">
                  <apex:inputField value="{!o.Activity_Type__c}"/>
                </apex:column>
                
                <apex:column id="ActivityDate" headerValue="Due Date" >
                      <apex:inputField value="{!o.ActivityDate}"/>
                </apex:column>              
                <apex:column id="WhatId" headerValue="Activity Related to" value="{!o.WhatId}"/>
                <apex:column id="WhoId" headerValue="Contact/Lead" value="{!o.WhoId}"/>
<!--            <apex:column id="IsReminderSet" headerValue="Reminder"> 
                      <apex:inputField value="{!o.IsReminderSet}"/>
                </apex:column>
-->                
                <apex:column id="ReminderDateTime" headerValue="Reminder" >
                      <apex:inputField value="{!o.ReminderDateTime}"/>
                </apex:column>
                <apex:column id="Description" headerValue="Comments" >
                      <apex:inputField value="{!o.Description}"/>
                </apex:column>
            
            </apex:pageBlockTable>
        </apex:pageBlock>
        
        <apex:panelGrid columns="2">
            <apex:commandLink action="{!previous}" rendered="{!hasPrevious}">Previous Page</apex:commandlink>
            <apex:commandLink action="{!next}" rendered="{!hasNext}">Next Page</apex:commandlink>
        </apex:panelGrid>
        <apex:outputText id="numberOfItemsLeft" value="{!numLeft}" style="visibility:hidden"/>
        <apex:actionFunction action="{!refreshNumbers}" immediate="true" name="refreshNumbers" rerender="numberOfItemsLeft, detail, table" oncomplete="checkIfNeedRefresh();"/>
    </apex:form>

</apex:page>
  • June 19, 2013
  • Like
  • 0

Hello,

 

I want to retrieve Corporate currency value using SOQL query.

 

I have checked Organization object - it has information for Locale & Language but it doesn't have information for Corporate Currency value.

 

How can I retrieve Corporate currency value?

 

Thanks

Hi 

 

I have 5000 records for one list view named all my contacts i want all the 5000 records in my controller so i can send messages to them but i am getting only 2000 records.How can I get all 5000 records

I have a VF page with APEX controller. The controller does a 'contact' DB query. This works fine for contacts that are part of an account. If however there is a contact which is not part of an account, the controller DB query doesn't return the correct results.

 

I presume this has something to do with "Contacts not associated with accounts are private and cannot be viewed by other users or included in reports." which is displayed on the "Edit contact" page.

 

Is there a way I can allow the VF/Apex page of mine access to view ALL contacts (including the ones that do not belong to an account)? And more importantly, can I add this setting (if it exists) as part of my app which includes this VF/Apex page.

 

  • May 15, 2013
  • Like
  • 0

Hi -

 

In our instance, Account is set to private. We have sharing rules to share accounts by criteria. For example, grant read /write access to all account of AS record type with Role: AS. We load data using an application user named "Migration User" who is assigned to the System Administrator role. By default, all loaded accounts will be owned by the Migration User. We have a custom application that perform account merging. One of the steps is to clone and recreate Notes & Attachments because there isn't a way to re-parent these records to the master Account. When an AS user tries to merge two accounts, the cloning step is failing if there are Notes & Attachments owned by the Migration User.  This is the error that we're getting:

 

INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []. 

 

However, this same user can create new and/or edit existing Notes record owned by the Migration User.

 

Here is the snippet of code where notes are collected for cloning.

 

public static list<Note> getNoteToMerge(list<Account> masterList, List<Account> aList)
{
list<Note> nList = new list<Note>();

for(Note n : [SELECT Id, OwnerId, isPrivate FROM Note WHERE ParentId IN :aList])
{
/* query note and then clone it */
String idStr = 'id=' + '\'' + n.Id + '\'';
system.debug(LoggingLevel.Info, '***************************** idStr: ' + idStr);
String soql = getCreatableFieldsSOQL('note', idStr);
Note result = (Note)Database.query(soql);
Note cloneNote = result.clone(false, true, true, false);
cloneNote.ParentId = masterList[0].Id;
cloneNote.OwnerId = n.OwnerId;
cloneNote.isPrivate = n.isPrivate;
nList.add(cloneNote);
}
return nList;
}

 

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

 

// Returns a dynamic SOQL statement for the whole object, includes only creatable fields since we will be inserting a cloned result of this query
public static string getCreatableFieldsSOQL(String objectName, String whereClause){

String selects = '';

if (whereClause == null || whereClause == ''){ return null; }

// Get a map of field name and field token
Map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();
list<string> selectFields = new list<string>();

if (fMap != null){
for (Schema.SObjectField ft : fMap.values()){ // loop through all field tokens (ft)
Schema.DescribeFieldResult fd = ft.getDescribe(); // describe each field (fd)
if (fd.isCreateable()){ // field is creatable
selectFields.add(fd.getName());
}
}
}

if (!selectFields.isEmpty()){
for (string s:selectFields){
selects += s + ',';
}
if (selects.endsWith(',')){selects = selects.substring(0,selects.lastIndexOf(','));}

}

return 'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause;

}

 

Any input on how to fix this issue is greatly appreciated.

 

HI,today, I use AccountShare object, but I get two problems, first one is: Field(AccountShare's all field)  is not writeable

 

 The second is:insert not allowed on AccountShare.

 

 I hope the very grateful to help me to solve the master,thanks!!!

 

//my apex

AccountShare thisAccountShare = new AccountShare();  
              thisAccountShare.userorgroupid=userId;  
              thisAccountShare.accountid = accId;  
              thisAccountShare.accountaccesslevel = 'Edit';   
              thisAccountShare.ContactAccessLevel = 'Edit';
              listAccShr.add(thisAccountShare);

 

insert listAcShr;