• Salesforce Developer
  • NEWBIE
  • 250 Points
  • Member since 2014

  • Chatter
    Feed
  • 7
    Best Answers
  • 1
    Likes Received
  • 3
    Likes Given
  • 1
    Questions
  • 64
    Replies
I am trying to update some accounts in the anonymous window and get the Too many DML rows error message. What am I doing wrong? 
 
​List<Account> acc = new List<Account>();

for(Account a:[SELECT Id, Industry from Account WHERE Industry='Architect']){
    
    a.Industry='Architecture';
    acc.add(a);
}

update acc;

Yogesh
I am a beginner to SF coding. I am getting this error  System.LimitException: Too many query rows: 50001 at line 17

my code is this, i am not sure why i am getting this error.

public class TransferTriggerHandler {
    public static final string COMMENT_TRUNCATED_MSG = Label.Comment_Truncated_Msg;
    public void OnAfterInsert(Transfer__c[] newTransObjects){
        
        
        List<Case> caseList = new List<Case>();
        List<CaseComment> caseCommentList = new List<CaseComment>();
        Map<id,Case> caseMap =  new Map<id,Case>([Select Id,Action_Owner__c,Action_Owner_Assignee__c,Minutes_Worked__c,accountId,account.ownerId from Case]); 
       
        boolean isPublish = false;
        String comment;
        
        for(Transfer__c trans: newTransObjects) {
            comment = 'New Transfer :'+trans.Name;
            comment += ' |Assigned Group:' + (trans.Action_Owner__c != null? trans.Action_Owner__c :' ') ;
            comment += ' |Summary of Issue:' + (trans.Summary_of_Issue__c != null ? trans.Summary_of_Issue__c : ' ');
            comment += ' |Customer Hardware Details:' + (trans.Customer_Hardware_Details__c != null ? trans.Customer_Hardware_Details__c : '') ;
            comment += ' |Work Done So Far:' + (trans.Work_Done_So_Far__c !=null ? trans.Work_Done_So_Far__c : '');
            comment += ' |Evidence/Supporting Details:' + (trans.Evidence_Supporting_Details__c !=null ? trans.Evidence_Supporting_Details__c : ''); 
            comment += ' |Expected Next Actions:' + (trans.Expected_next_actions__c != null ? trans.Expected_next_actions__c : '');
            comment += ' |Escalation Reason: ' + (trans.Escalation_Reason__c != null ? trans.Escalation_Reason__c : '');
            
            if (comment.length() > maxCommentLength) {
                //This comments is too long, we need to truncate it/
                comment =  comment.substring(0, maxCommentLength) + COMMENT_TRUNCATED_MSG;                    
            }
            
            Case c = caseMap.get(trans.case__c);
            CaseComment cc = new CaseComment(CommentBody= comment, IsPublished=isPublish,ParentId= c.id);
            caseCommentList.add(cc);
            insert caseCommentList;
           
            if(trans.Action_Owner__c =='Sales'){
           
                c.Action_Owner_Assignee__c = c.account.ownerid ;
                c.Action_Owner__c =trans.Action_Owner__c;
                c.Minutes_Worked__c= trans.Minutes_Worked__c;
            }
            else{
                c.Action_Owner_Assignee__c = null;
                c.Action_Owner__c =trans.Action_Owner__c;
                c.Minutes_Worked__c= trans.Minutes_Worked__c;
            }
            caseList.add(c);
        }
        try{
            if(caseList.size() > 0) {
                update caseList;
            }
        }  
        catch (Exception e){
            System.debug('Failed in transfer trigger handler class insertion'+e);
        }          
        
    }
    

    @TestVisible private static integer maxCommentLength {
        get
        {
            List<AddTransferFieldstoCase__c> tfc = AddTransferFieldstoCase__c.getall().values();
           
            integer returnValue = 4000;
           
            if (tfc.size() > 0) {
                returnValue = (integer)(tfc[0].MaxCommentLength__c);
            }

           
            returnValue = returnValue - COMMENT_TRUNCATED_MSG.length();

            if (returnValue < 0) throw new CommentConvertException('Maximum comment length is less than Zero. Check settings.');
            return returnValue;
        }
    }
    
    public class CommentConvertException extends Exception {}
}
  • October 31, 2017
  • Like
  • 0
trigger Contact on Contact (before insert, before update) {
    for (Contact c1 : trigger.new)
    {
        string fullname = c1.LastName;
        string firstname = c1.FirstName;
        if( fullname.containsWhitespace() == true )
        {
            if (String.isBlank(firstname) == true)
            {
                string fn;
                string ln;
                fn = fullname.substring(0,fullname.indexOf(' '));
                ln = fullname.substring(fullname.indexOf(' ')+1);
                c1.LastName = ln;
                c1.FirstName = fn;
            }
        }
    }
}

As the topic says, this works when I create a record through the GUI but not when loading records through Data Loader (CLI Batch or Bulk).

I am attempting to split the value in LastName whenever the FirstName is blank and the LastName has a space in it.
Hi All,
I am trying to generate apex class using the SFDC Partner WSDL , however i am getting the following issue while parsing the WSDL:
Apex Generation Failed
Unsupported schema type: {http://www.w3.org/2001/XMLSchema}anyType

Can someone please point me what i am doing wrong in here.

Thanks in Advance !!
  • September 17, 2017
  • Like
  • 0
Greetings, I've got a Gridbuddy visualforce page embedded on accounts, but when I enable the Clickjacking protecting on Visualforce pages, the accounts page displays an error and the entire account record does not. Are there any steps I can take to allow my VF page to appear and work when clickjacking is enabled.
User-added image

My code is as below.
<apex:page standardController="Account" sidebar="false" showHeader="false">
    <GBLite:EmbedComponent baseGridUrl="{!$Page.GBLite__Grid}" />

    <iframe id="gridFrame" scrolling="auto" height="480" width="100%" frameborder="0" src="{!gridPage}gname=Moves Managed Tasks&id={!Account.Id}&sh=0&ssb=0&sbb=1&sfname=default"></iframe>
</apex:page>

 


const filter1= { $schema: "http:/000000",
target: {
table: "VW_SF_VIS_ORG", column: "RETAILER_CD" },
operator: "In",
values: ["88888"]
}
HI Experts,

I am new to the developmen. I have one urgent requirement, (Selected) Multiple FieldApi need to be  display When Select Multiple Fields. My Coding is followed that.
User-added image

@controller
public class AutoTableGenerate {

     public string FieldApi {get;set;}
     public boolean displayPopup {get; set;}
     public string AccId{get; set;}
	 public String selectedField {get; set;}    

    public Set<String> unSelectedNames = new Set<String>();
    public Set<String> selectedNames = new Set<String>();
    public Set<String> inaccessibleNames = new Set<String>();
    public List<String> selected   { get; set; }
    public List<String> unselected { get; set; }
   

    public AutoTableGenerate(ApexPages.StandardSetController controller) {
        //AccId = ApexPages.currentPage().getParameters().get('ID');
    }

        Public List<SelectOption> getAccountFields(){
        String selectedObject = Account.sObjectType.getDescribe().getName();
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Schema.SObjectType ObjectSchema = schemaMap.get(selectedObject);
        Map<String, Schema.SObjectField> fieldMap = ObjectSchema.getDescribe().fields.getMap();
        List<SelectOption> options = new List<SelectOption>();
        for (String fieldName: fieldMap.keySet()){  
            //system.debug('field name: | ' +  fieldName + ' &  label: | ' + fieldMap.get(fieldName).getDescribe().getLabel() );
            options.add(new SelectOption(fieldName,fieldMap.get(fieldName).getDescribe().getLabel())) ;
        }
        return options;
    }
    
    
       //getting API Of Selected Fields
    public void getFieldAPI()
    {
        System.debug('Selected Field | ' + selectedField);
        FieldApi = '{{!'+ selectedField + '}}';
    }
    
     public void closePopup() {
        displayPopup = false;
    }
 
    public void showPopup() {
        displayPopup = true;
    }
    


    // Create the select options for the two select lists on the page
    public List<SelectOption> getSelectedOptions() { 
        return selectOptionsFromSet(selectedNames);
    }
    public List<SelectOption> getUnSelectedOptions() { 
        return selectOptionsFromSet(unSelectedNames);
    }
    
    private List<SelectOption> selectOptionsFromSet(Set<String> opts) {
        List<String> optionsList = new List<String>(opts);
        List<SelectOption> options = new List<SelectOption>();
        for (String s : optionsList) {
            options.add(new 
                SelectOption(s, decorateName(s), inaccessibleNames.contains(s)));
        }
        return options;
    }

    private String decorateName(String s) {
        return inaccessibleNames.contains(s) ? '*' + s : s;
    } 



    public void doAdd() {
        moveFields(selected, selectedNames, unSelectedNames);
    }
    public void doRemove() {
        moveFields(unselected, unSelectedNames, selectedNames);
    }
    
    Public void moveFields(List<String> items, 
            Set<String> moveTo, Set<String> removeFrom) {
        for (String s: items) {
            if( ! inaccessibleNames.contains(s)) {
                moveTo.add(s);
                removeFrom.remove(s);
            }
        }
    }
}

@VF Page
<apex:page standardController="Account" recordSetVar="ignored" extensions="AutoTableGenerate" showHeader="false" sidebar="false" id="thepageid">
    <apex:form id="theformid">
        <apex:includescript value="{!URLFOR($Resource.CkEditor, 'ckeditor/ckeditor.js')}" />
        <apex:pageBlock >
            <center>
                <apex:commandLink value="Save" action="{!save}" target="_parent" styleClass="btn" style="text-decoration:none;padding:4px;" />
                <apex:commandButton value="Cancel"/>
                <apex:commandButton value="Insert Field" action="{!showPopup}" rerender="tstpopup"/>
            </center>
            
            <apex:pageblockSection columns="1">
                <apex:tabPanel switchType="client" selectedTab="name1" id="theTabPanel">
                    <apex:tab label="Template Body" name="name1"  >
                        <apex:inputtextarea id="editor1"  styleClass="ckeditor" richtext="false"/>
                    </apex:tab>
                    
                    <apex:tab label="Header" name="name2" id="tabTwo">
                        <apex:inputtextarea id="editor2"  styleClass="ckeditor" richtext="false"/>
                    </apex:tab>
                    
                    <apex:tab label="Footer" name="name3" id="tabThree">
                        <apex:inputtextarea id="editor3"  styleClass="ckeditor" richtext="false"/>
                    </apex:tab>
                    <apex:tab label="Page Settings" name="name4" id="tabFour">Page Settings</apex:tab>
                </apex:tabPanel>
            </apex:pageblockSection>
        </apex:pageBlock> 
        
        <apex:outputPanel id="tstpopup">
            <apex:outputPanel styleClass="popupBackground" layout="block" rendered="{!displayPopUp}"/>
            <apex:outputPanel styleClass="custPopup" layout="block" rendered="{!displayPopUp}">
                
                <div style="background-color:#E5E6E6;">
                    <span align="right" > <h3><b>Fields For : Account</b></h3></span>
                </div>
                <div>
                    <p style="font-size:13px;">Select a field, then click Insert. Labels followed by a ">" indicate that there are more fields available. If you need to extend further, you can manually edit the value or consider creating a formula field on your base object: Account.</p>  
                </div>
                <apex:pageBlock id="selectionBlock">
                    <apex:pageMessages />
                    <apex:pageBlockSection columns="6">
                        <apex:panelGrid id="pn1" columns="4">
                            <apex:panelGroup >
                                <apex:selectList id="unselected_list" required="false" 
                                                 value="{!selected}"  multiselect="true" size="15" style="width:250px">
                                    <apex:selectOptions value="{!AccountFields}"/>
                                    <apex:actionSupport event="onchange" action="{!getFieldAPI}" reRender="selectionBlock"/> 
                                </apex:selectList>
                            </apex:panelGroup>
                            <apex:panelGroup id="pn2">
                                <br /><br /><br /><br />
                                <apex:outputtext value="Add"/><br/>
                                <apex:commandButton image="{!URLFOR($Resource.RightArr)}"
                                                    action="{!doAdd}" rerender="selectionBlock" style="border:none; padding:0px 0px 0px 0px;"  status="statLoad2"/>
                                <br/><br/>
                                <apex:commandButton image="{!URLFOR($Resource.LeftArr)}"
                                                    action="{!doRemove}" rerender="selectionBlock" style="border:none; padding:0px 0px 0px 0px;"  status="statLoad2"/><br/>
                                <apex:outputtext value="Remove"/><br />
                            </apex:panelGroup>
                            
                            <apex:panelGroup id="pn3" >
                                <apex:selectList id="selected_list" required="false" rendered="True"
                                                 value="{!unselected}" multiselect="true" size="15" style="width:250px">
                                    <apex:selectOptions value="{!selectedOptions}"/>
                                </apex:selectList>
                            </apex:panelGroup> 
                            
                            <apex:panelGroup id="pn4">
                                <br /><br /><br /><br />
                                <apex:outputtext value="Up" /><br />
                                <apex:commandButton image="{!URLFOR($Resource.UpArr)}"  
                                                    style="border:none; padding:0px 0px 0px 0px;"  status="statLoad2"/><br /><br />
                                <apex:commandButton image="{!URLFOR($Resource.DownArr)}" 
                                                    style="border:none; padding:0px 0px 0px 0px;"  status="statLoad2"/><br />
                                <apex:outputtext value="Down"/><br />
                            </apex:panelGroup>  
                        </apex:panelGrid>
                        
                    </apex:pageBlockSection>
                    <p>The following will be inserted into your template: </p><br />
                    <apex:inputText value="{!FieldApi}" size="100"/>  <br /><br /><center> 
                    <apex:commandButton value="Insert Field" action="{!closePopup}" oncomplete="insert('{!FieldApi}');" rerender="tstpopup"/>
                    &nbsp;&nbsp;&nbsp;
                    <apex:commandButton value="Cancel" action="{!closePopup}"  rerender="tstpopup"/></center>
                    
                </apex:pageBlock>
            </apex:outputPanel>
        </apex:outputPanel>
        
        
        
    </apex:form>
    
    <!-- Internal Script -->
    <script type="text/javascript">
    window.onload = function()
    {
        var editor = CKEDITOR.instances['thepageid:theformid:theTabPanel:editor1'];
        if(editor){
            editor.destroy();}
        var ckEditor = CKEDITOR.replace('thepageid:theformid:theTabPanel:editor1', {
            fullPage: true,
            extraPlugins: 'docprops',
            allowedContent: true
        });
        
        ckEditor.on("instanceReady",function() {
            
            // overwrite the default save function
            ckEditor.addCommand( "save", {
                modes : { wysiwyg:1, source:1 },
                exec : function () {
                    
                    // get the editor content
                    var theData = ckEditor.getData();
                    alert("insert your code here");
                }
            }); }); 
    }
    
    function abc()
    {
        var element = CKEDITOR.instances['editor1'].getData();
        alert(element);
    }
    
    insert=function(FieldApi){
        var CKEDITOR   = window.CKEDITOR;
        for ( var i in CKEDITOR.instances ){
            var currentInstance = i;
            break;
        }
        var oEditor   = CKEDITOR.instances[currentInstance];
        oEditor.focus();
        oEditor.insertHtml(FieldApi);
    };
    </script>
    
    
    <style type="text/css">
        .custPopup{
        background-color: white;
        border-width: 2px;
        border-style: solid;
        z-index: 9999;
        left: 38%;
        padding:10px;
        position: absolute;
        /* These are the 3 css properties you will need to change so the popup 
        displays in the center of the screen. First set the width. Then set 
        margin-left to negative half of what the width is. You can add 
        the height property for a fixed size pop up if you want.*/
        width: 800px;
        margin-left: -250px;
        top:65px;
        }
        .popupBackground{
        background-color:black;
        opacity: 0.10;
        filter: alpha(opacity = 20);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 9998;
        }
    </style>
    
</apex:page>

I hope you can able to come with good solution. Hearty Thanks in advance.

Regards,
Soundar.​
Hi All, 

Need Help ! I have a requirement where I have to implement a search functionality. On enter a particular term it will search records and then return results. Also I have to add a "No item found" Option in a list of records. I have used StandardSetController for this , but when I try to add a dummy record named " No Item Found " in the List and then pass the list to the instance of StandardSetController, I am getting error "Modified rows exist in the records collection!" on the VF page. I understand the meaning of the error but can anybody suggest me how should this can be accomplished.

Thanks in advance !
Hi All, 

Need Help ! I have a requirement where I have to implement a search functionality. On enter a particular term it will search records and then return results. Also I have to add a "No item found" Option in a list of records. I have used StandardSetController for this , but when I try to add a dummy record named " No Item Found " in the List and then pass the list to the instance of StandardSetController, I am getting error "Modified rows exist in the records collection!" on the VF page. I understand the meaning of the error but can anybody suggest me how should this can be accomplished.

Thanks in advance !
I have got 58% code covereage for the chatterTooltip class mentioned in code sample and i am facing difficulty while increasing remaining code coverage.

Please suggest me onthis , Thanks in advance...
Class :

public class chatterTooltip {
    public string uID   { get; set; }
    
    public User u       { get; set; }
    
    public integer followers    { get; set; }
    public integer following    { get; set; }
    
    public boolean followingme  { get; set; }
    
    public string lastUpdate    { get; set; }
    public string timestr       { get; set; }
    
    public boolean isTest       { get; set; }
    
    public chatterTooltip() {
        isTest = false;
    }
    
    public string getUserName() {
        if( uID == null )
            return null;
            
        if( u != null )
            return u.name;
            
        User[] us = [select id, name 
            from User
            where id = :uID];
            
        if( us.isEmpty() )
            return '';
            
        u = us[0];
            
        loadData();
            
        return u.name;
    }
    
    public void loadData() {
        integer qlimit = ( isTest ? 1 : 1000 );
        
        EntitySubscription[] ess = [select id, parentid
            from EntitySubscription
            where parentid = :uID
            or subscriberid = :uID limit :qlimit];
            
        followers = 0;
        
        for( EntitySubscription es : ess )
            if( es.parentid == uID )
                followers++;
                
        following = ess.size() - followers;
        
        if( UserInfo.getUserId() != uID ) {
            EntitySubscription[] ess2 = [select id
                from EntitySubscription
                where parentid = :UserInfo.getUserId()
                and subscriberid = :uID];
                
            followingme = ess2.size() > 0;
        } else
            followingme = false;
            
        UserFeed[] ufs = [select id, FeedPost.body, createddate
            from UserFeed
            where parentid = :uID
            order by createddate desc limit 1];
            
        if( ufs.isEmpty() )
            return;
            
        lastUpdate = ufs[0].FeedPost.body;
        
        if( lastUpdate == null )
            return;
        
        if( lastUpdate.length() > 70 )
            lastUpdate = lastUpdate.substring( 0, 70 ) + '...';
            
        timestr = relativeTime( ufs[0].createddate );
    }
    
    public string relativeTime( Datetime dt ) {
        long diff =  ( Datetime.now().getTime() - dt.getTime() ) / 1000;
        string unit;
        
        if( diff < 60 )
            unit = 'second';
        else if( diff < 60 * 60 ) {
            diff /= 60;
            unit = 'minute';
        } else if( diff < 60 * 60 * 24 ) {
            diff = diff / 60 / 60;
            unit = 'hour';
        } else {
            diff = diff / 60 / 60 / 24;
            unit = 'day';
        }
        
        if( diff > 1 )
            unit += 's';
            
        return diff + ' ' + unit + ' ago';
    }
    
}

Test class :

@Istest 
Public class Test_chatterTooltip{

    static testmethod void runTest(){
    
            //Find user with Profile = Sales and Service
        Profile sysadm = [Select id from Profile where Name = 'System Administrator' limit 1];
        User u = new User(
            Alias = 'standt', 
            Email='standarduser@testorg.com',
            EmailEncodingKey='UTF-8',
            LastName='Testing',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            ProfileId = sysadm.Id,
            TimeZoneSidKey='America/Los_Angeles',
            UserName='standarduser@testorg.com'
            );
            
        chatterTooltip ct = new chatterTooltip();
        ct.isTest = true;
        ct.uid = UserInfo.getUserId();
        
        ct.getUserName();
        ct.relativeTime(datetime.now());      
        ct.loadData(); 
                         
      }

Uncovered code
I wrote a trigger that works perfectly in sandbox and has 83% test coverage and deployed it to production, then Trigger was worked smoothly up to 9 months,from 5days back onwords its not working in the production instance where as Working in Sandbox now also and I don't get any error messages, but the thing that it's supposed to do (Query and fill customer field in Case Based on SuppliedEmail) just doesn't happen. In production, it also has 83% coverage. Any ideas what's going on?
 
Here's the code:

Trigger CaseCustomer on Case (before insert,after update) {
    Try{
    Set<String> stemail = new Set<String>();
    List<Customer__c> custlst = new List<Customer__c>();
    Map<String,Customer__c> mpemailtocustomer = new Map<String,Customer__c>();
    List<Case> updcaselst = new List<Case>();
    Map<String,Entitlement> mpentitle = new Map<String,Entitlement>();
    Set<Id> casid = new Set<Id>();
    List<CaseMilestone> cmsToUpdate = new List<CaseMilestone>();
    
    if(Trigger.isAfter)
    {
        for(Case icas:Trigger.New)
        {
            if((trigger.newMap.get(icas.id).Status!= trigger.oldMap.get(icas.id).Status) && icas.Status == 'Closed')
            {
                casid.add(icas.id);
                System.debug(casid);
            }
        }
        if(casid.size()>0)
        {
            cmsToUpdate = [select Id,completionDate from CaseMilestone where caseId IN :casid];
            System.debug(cmsToUpdate);
        }
        if(cmsToUpdate.size()>0)
        {
            for(CaseMilestone icasn:cmsToUpdate)
            {
                icasn.completionDate = System.now();
            }
            update cmsToUpdate;
        }
        
    }
    
   else
   {
    for(Case icas:Trigger.New)
    {
        if(icas.SuppliedEmail != null)
        {
            stemail.add(icas.SuppliedEmail);
            System.debug(stemail);
        }
    }
    if(stemail.size()>0)
    {
        custlst = [SELECT ID,Email__c FROM Customer__c WHERE Email__c IN:stemail];
        System.debug(custlst);
    }
    if(custlst.size()>0)
    {
        for(Customer__c icus:custlst)
        {
            mpemailtocustomer.put(icus.Email__c,icus);
            System.debug(mpemailtocustomer);
        }
    
    }
    List<Entitlement> entlst = [SELECT id,Name FROM Entitlement];
    if(entlst.size()>0)
    {
        for(Entitlement ient :entlst)
        {
            mpentitle.put(ient.Name,ient);
        }
    }
    
        for(Case icas : Trigger.New)
        {
            if(mpemailtocustomer.containskey(icas.SuppliedEmail))
            {
                icas.Customer__c = mpemailtocustomer.get(icas.SuppliedEmail).ID;           
            }
            if(icas.Origin == 'Email' ||  icas.Origin == 'Phone' || icas.Origin == 'Web')
            {
                icas.EntitlementId = mpentitle.get('Response').Id;
                System.debug(icas.EntitlementId);
            }
        }
    
    }
    }catch(exception e)
    {
        System.debug(e.getlinenumber()+e.getmessage());
    }
}
  • January 09, 2018
  • Like
  • 0
Hi

I am trying to send an email with pdf whenever a pdf is attached in "Notes and Attachment" section. Whenever I try to upload it is giving me an error 

10:04:27:005 FATAL_ERROR System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, No body supplied for the file attachment.: [fileAttachments]

Please find the below code for Apex trigger.
trigger EmailTrigger on ContentVersion (after insert) 
{
List<Messaging.SingleEmailMessage> allMessages = new List<Messaging.SingleEmailMessage>();
for(ContentVersion cv : trigger.new)
{
Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
attachment.setBody(cv.ContentBodyId);
attachment.setFileName(cv.Title + '.' + cv.FileType);

Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] { 'andre.nobre@cleantechsolar.com' };
message.subject = 'Test Mail';
message.plainTextBody = 'Attached file name: ' + cv.Title;
message.setFileAttachments(new Messaging.EmailFileAttachment[] {attachment});

allMessages.add(message); 
}

Messaging.sendEmail(allMessages);
}
Kindly help me to rectify the same.
 
Requirement: If the richText field is edited, throw error.
Implementation:
One vallidation rule: ISCHANGED( RichText__c )
This rule is throwing error all the time, even if you do not edit RichText field.

Any suggestions on how to achieve the requirement with out of box functionality?

 
  • November 17, 2017
  • Like
  • 0
Hi ,

I need help for test class to cover the below class as follows, I have test class which is covering only 20% need help to cover above


 
APEX CLASS :

global with sharing class iDealPageRedirectExtn {

    public static Integer count{get; set;}
    public static Integer count2{get; set;}
    public static Integer count3{get; set;}
    public static Integer count4{get; set;}
    public iDealPageRedirectExtn(ApexPages.StandardController controller){
       
        	String accountId = ApexPages.CurrentPage().getParameters().get('id');
        if(accountId!=null){
            System.debug(count+' '+count2+' '+count3+' '+count4);
            count 	=	 0;
            count2  =	 0;
            count3	= 	 0;
            count4	=	 0;
      		 count =[select count() from Agency_Info__c where Account__c= :accountId and Recordtype.Name='Distribution' limit 1];             
        	 count2 =[select count() from Agency_Info__c where Account__c=:accountId and PCC__c!='' and Recordtype.Name='GDS' limit 1];             
             count3 =[select count() from Agency_Info__c where Account__c in (select Primary_Account__c from Account_Relation__c where Related_Account__c=:accountId and Active__c=TRUE) and PCC__c!='' limit 1];             
             count4 =[select count() from Contract__c where Account__c=:accountId];           
            System.debug(count+' '+count2+' '+count3+' '+count4);
            }
        
    }    
}

Kindly help me pls

Thanks in Advance​
I am trying to update some accounts in the anonymous window and get the Too many DML rows error message. What am I doing wrong? 
 
​List<Account> acc = new List<Account>();

for(Account a:[SELECT Id, Industry from Account WHERE Industry='Architect']){
    
    a.Industry='Architecture';
    acc.add(a);
}

update acc;

Yogesh
Hi I m little confused with the difference between issued and Dml Statements,Total number of SOQL queries issued 100, Total number of DML statements issued 150. i used FOR loop for insertion, I know its not best practice, I m trying to learn possibilities, I did nt use any soql query then why i m getting System.LimitException: Too many SOQL queries: 101, but insert is DML operation right? it should hit DML Exception 151? someone please explain me this.  

public class accountinse {
    
    public PageReference show(){
        List<Account> ac=new List<Account>();
        for(Integer i=0; i<200; i++){
            
            
            a.Name='testing12535'+i;
            a.AccountNumber='4857885';
            a.Type='Prospect';
            a.Industry='Biotechnology';
            a.AnnualRevenue=158758;
            a.Rating='cold';
            a.Phone='18578558';
            a.Identity_Proof__c='Adhar Card; PAN Card';
            a.Last_Name__c='a';
            ac.add(a);
        
        }
        insert ac;
        return null;
    }

}
Hi all,

I have a requirement to sent email alert to lead owner  and conditions are like
  1. Alert will go to lead owner after 2 hours from lead created time
  2. Lead owner will get mail only Week days and not in week ends
I am a beginner to SF coding. I am getting this error  System.LimitException: Too many query rows: 50001 at line 17

my code is this, i am not sure why i am getting this error.

public class TransferTriggerHandler {
    public static final string COMMENT_TRUNCATED_MSG = Label.Comment_Truncated_Msg;
    public void OnAfterInsert(Transfer__c[] newTransObjects){
        
        
        List<Case> caseList = new List<Case>();
        List<CaseComment> caseCommentList = new List<CaseComment>();
        Map<id,Case> caseMap =  new Map<id,Case>([Select Id,Action_Owner__c,Action_Owner_Assignee__c,Minutes_Worked__c,accountId,account.ownerId from Case]); 
       
        boolean isPublish = false;
        String comment;
        
        for(Transfer__c trans: newTransObjects) {
            comment = 'New Transfer :'+trans.Name;
            comment += ' |Assigned Group:' + (trans.Action_Owner__c != null? trans.Action_Owner__c :' ') ;
            comment += ' |Summary of Issue:' + (trans.Summary_of_Issue__c != null ? trans.Summary_of_Issue__c : ' ');
            comment += ' |Customer Hardware Details:' + (trans.Customer_Hardware_Details__c != null ? trans.Customer_Hardware_Details__c : '') ;
            comment += ' |Work Done So Far:' + (trans.Work_Done_So_Far__c !=null ? trans.Work_Done_So_Far__c : '');
            comment += ' |Evidence/Supporting Details:' + (trans.Evidence_Supporting_Details__c !=null ? trans.Evidence_Supporting_Details__c : ''); 
            comment += ' |Expected Next Actions:' + (trans.Expected_next_actions__c != null ? trans.Expected_next_actions__c : '');
            comment += ' |Escalation Reason: ' + (trans.Escalation_Reason__c != null ? trans.Escalation_Reason__c : '');
            
            if (comment.length() > maxCommentLength) {
                //This comments is too long, we need to truncate it/
                comment =  comment.substring(0, maxCommentLength) + COMMENT_TRUNCATED_MSG;                    
            }
            
            Case c = caseMap.get(trans.case__c);
            CaseComment cc = new CaseComment(CommentBody= comment, IsPublished=isPublish,ParentId= c.id);
            caseCommentList.add(cc);
            insert caseCommentList;
           
            if(trans.Action_Owner__c =='Sales'){
           
                c.Action_Owner_Assignee__c = c.account.ownerid ;
                c.Action_Owner__c =trans.Action_Owner__c;
                c.Minutes_Worked__c= trans.Minutes_Worked__c;
            }
            else{
                c.Action_Owner_Assignee__c = null;
                c.Action_Owner__c =trans.Action_Owner__c;
                c.Minutes_Worked__c= trans.Minutes_Worked__c;
            }
            caseList.add(c);
        }
        try{
            if(caseList.size() > 0) {
                update caseList;
            }
        }  
        catch (Exception e){
            System.debug('Failed in transfer trigger handler class insertion'+e);
        }          
        
    }
    

    @TestVisible private static integer maxCommentLength {
        get
        {
            List<AddTransferFieldstoCase__c> tfc = AddTransferFieldstoCase__c.getall().values();
           
            integer returnValue = 4000;
           
            if (tfc.size() > 0) {
                returnValue = (integer)(tfc[0].MaxCommentLength__c);
            }

           
            returnValue = returnValue - COMMENT_TRUNCATED_MSG.length();

            if (returnValue < 0) throw new CommentConvertException('Maximum comment length is less than Zero. Check settings.');
            return returnValue;
        }
    }
    
    public class CommentConvertException extends Exception {}
}
  • October 31, 2017
  • Like
  • 0
Hello,

I am getting the following error message when detonating this trigger below:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger OpportunityTeamMembers caused an unexpected exception, contact your administrator: OpportunityTeamMembers: execution of BeforeInsert caused by: System.ListException: Before Insert or Upsert list must not have two identically equal elements: Trigger.OpportunityTeamMembers: line 28, column 1​
 
trigger OpportunityTeamMembers on Opportunity (before insert) {
    List<OpportunityTeamMember> myOpptyTeamMembers = new List <OpportunityTeamMember>();
    for(Opportunity myOpp : Trigger.new){
        //Create an Oppty Team Member
        OpportunityTeamMember otm = new OpportunityTeamMember();
        otm.opportunityId = myOpp.Id;
        // If a Manager exist, add it to the list of myOpptyTeamMembers
        if(myOpp.Owner.ManagerId != null){
            otm.userId = myOpp.owner.ManagerId;
            otm.TeamMemberRole = 'Sales Manager';
            myOpptyTeamMembers.add(otm);
        }
        // If Dependents exist, add it/them to the list of myOpptyTeamMembers
        List<User> dependentUsers = [SELECT Id
                                     FROM User
                                     WHERE ManagerId = :myopp.OwnerId];
        if(dependentUsers.size()>0){
            // Loop on dependentUsers List
            OpportunityTeamMember otm2 = new OpportunityTeamMember();
            for(User myDependentUser : dependentUsers){
                otm2.UserId         = myDependentUser.Id;
                otm2.TeamMemberRole = 'Sales Rep';
                myOpptyTeamMembers.add(otm2);
            }
        }
    }
    // Add/Insert Team Members to the myOpp
    insert myOpptyTeamMembers;
}

According to the error message, it sounds like I am trying to insert a List (myOpptyTeamMembers) with two identical items (?).
I guess that, to Salesforce, two identical items would be identicals if their Id were the same, right? This would mean that, in myOpptyTeamMembers (which is the list I am inserting at the end of the code), there are 2 records Opportunity Team Members with the same Id?
How could this be possible?
Any clue?
(Thank you very much)
We currently have a trigger that was set up by a third party vendor automatically adds an Account Team based on the linked account data of our syncing database.  There is one representaive that the trigger doesn't seem to be recognizing.

I'm unfamiliar with the coding to be able to pin point the issue.  Is there anyone that can point me in the direction of a solution?

trigger AddAccountTeamMembers on Account (after insert,after update){
 //Get User's Name,Id and Store into userMap
   Map<String,Id> userMap=new Map<String,Id>();
   List<Id> userIds= New List<Id>();
   for(User u:[Select id,name from user]){
       userMap.put(u.name,u.id);
       userIds.add(u.Id);
    }
  if(trigger.isInsert && trigger.isAfter){
    Set<Id> repId=new Set<Id>();
    Set<Id> accList=new Set<Id>();
    List<AccountTeamMember> memberList=new List<AccountTeamMember>();   
  //Add account repid and account id's
    for(Account acc : trigger.new){
      repId.add(acc.OASP__OAS_Rep__c);
      accList.add(acc.id);
    }
    Map<id,String> conMap=new Map<id,String>();
  //Query the contacts with account RepId's
    if(repId != null && !repId.isEmpty()){
       for(Contact con: [Select id,name from Contact where Id In:repId]){
          conMap.put(con.id,con.name);
       }
    }
    for(Account acc : trigger.new){
  //Splitting the contacts
     String contactName = conMap.get(acc.OASP__OAS_Rep__c);
     if(contactName!=null){
        List<String> conSplit=contactName.Split(' and ');
  //Add the contacts into Account Team Members
        for(String temp: conSplit){
             AccountTeamMember accMember=new AccountTeamMember();
             accMember.TeamMemberRole='Account Manager';
             accMember.AccountId=acc.id;
             accMember.UserId=(Id)userMap.get(temp);
             memberList.add(accMember);
             
        }
      } 
    } 
    System.debug('++Acc Team Member++'+memberList);
   //insert the contacts and Sharing rules
    if(memberList!=null){
      Database.insert(memberList,false);
    }
    System.debug('++Account List++'+accList);
    //Use future method for Insert Account Share Access
    if(accList != null && accList.size()>0 && memberList.size()>0)
    FutureAccountShare.updateAccountShareAccess(accList);
  }
  if(trigger.isUpdate && trigger.isAfter){
    Set<Id> accId=new Set<Id>();
    Set<Id> repId=new Set<Id>();
    Map<String,AccountTeamMember> accTeamMap = New Map<String,AccountTeamMember>();
    list<AccountTeamMember> accmemlist = New list<AccountTeamMember>();
    list<AccountTeamMember> accteamMembers = New list<AccountTeamMember>();
    Map<id,String> conMap=new Map<id,String>();   
    Set<AccountTeamMember> uniquedelete = new Set<AccountTeamMember>();
    
     for(Account acct: trigger.new){
        accId.add(acct.Id);
        repId.add(acct.OASP__OAS_Rep__c);
     }
     for(Account acct: trigger.old){
        repId.add(acct.OASP__OAS_Rep__c);
     }
     
     For(AccountTeamMember acctmem: [Select id,AccountId,UserId,AccountAccesslevel,TeamMemberRole  from AccountTeamMember where AccountId In: accId]){
          accTeamMap.put(acctmem.AccountId+'&'+acctmem.UserId,acctmem);
          accmemlist.Add(acctmem);
     }
     if(repId != null && !repId.isEmpty()){
       for(Contact con: [Select id,Name from Contact Where ID IN: repId]){
         conMap.put(con.id,con.name);
       }
     }
     Set<Id> accupdateId=new Set<Id>();
     for(Account temp: trigger.New){
      if(temp.OASP__OAS_Rep__c != Trigger.oldMap.get(temp.id).OASP__OAS_Rep__c){
       accupdateId.add(temp.Id);
       for(Id userTemp: userIds){
        String Name = conMap.get(Trigger.oldMap.get(temp.id).OASP__OAS_Rep__c);
        if(Name!=null){
        List<String> contSplitdelete =Name.Split(' and ');
         for(String str: contSplitdelete){
            AccountTeamMember AccmemId = accTeamMap.get(temp.Id+'&'+userMap.get(str)); // 
            if(AccmemId != null) {
              uniquedelete.add(AccmemId);
            }
          }
        }
       }
      } 
     }
     if(uniquedelete!=null){ 
         List<AccountTeamMember> finalDelete = new list<AccountTeamMember>();
         finalDelete.addALL(uniquedelete);
         Database.delete(finalDelete,false);
     }
     List<AccountTeamMember> teamMember=new List<AccountTeamMember>();
        for(Account accUpdate : trigger.new){
        if(accUpdate.OASP__OAS_Rep__c != Trigger.oldMap.get(accUpdate.id).OASP__OAS_Rep__c){
         String contName = conMap.get(accUpdate.OASP__OAS_Rep__c);
          if(contName!=null){
             List<String> contSplit=contName.Split(' and ');
             for(String temp1: contSplit){
                AccountTeamMember acctMember=new AccountTeamMember();
                acctMember.TeamMemberRole='Account Manager';
                acctMember.AccountId=accUpdate.id;
                acctMember.UserId=(Id)userMap.get(temp1);
                teamMember.add(acctMember);          
             }
          }
        } 
        }
     if(teamMember!=null){
     //Insert Account Team Members and Sharing rules for update
      Database.insert(teamMember,false);
     }
 //Use future method for Update Account Share Access
 if(accupdateId != null && accupdateId.size()>0){
    FutureAccountShare.updateAccountShareAccess(accupdateId);
  }
  }
}
I have an Apex Class that generates a List of Events:
 
Public class AgentAppointmentsPast30 {
    
	String sortOrder = ' Who.Name ';
    String ascendingOrDescending = ' ASC ';
    String UserID = UserInfo.getUserId();
    String dateTimeFormat = DateTime.now().format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
    
    String myRequest = 'SELECT id, Owner.Id, type, subject, Decision_Made_by_Client__c, Appointment_Result__c, Reason_for_Cancellation_No_Show__c,'+
                ' WhoId, Who.Name, Appoint_Set_By__c, ActivityDateTime, No_Show_Cancelled_Disposition__c,Request_to_Shuffle__c,Contact_Name__r.Actual_Sale_Date__c, Contact_Name__r.Foreclosure_Status__c, Contact_Name__r.FAIR_Packet__c,'+ 
        	    ' Contact_Name__c, Contact_Name__r.Name, Contact_Name__r.Id, Contact_Name__r.Account.Property_Address__c,Contact_Name__r.Account.Name, Contact_Name__r.Account.Id'+
                ' FROM Event ' + 
                ' WHERE Owner.Id = \''+UserId+'\' And RecordTypeId = \'0126A0000004Qle\' AND ( ActivityDateTime = LAST_N_DAYS:30 OR (ActivityDateTime = TODAY And Type != \'Appointment - Booked\' And Type != \'Appointment - Confirmed\' ))'+
				' ORDER BY ';

    
    	public void sortByContact() 	{this.sortOrder = ' Who.Name ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
   		public void sortByActivityDateTime() 	{this.sortOrder = ' ActivityDateTime ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByType() 	{this.sortOrder = ' Type ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortBySubject() 	{this.sortOrder = ' Subject ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByOutcome() 	{this.sortOrder = ' Decision_Made_by_Client__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByOutcomeNotes() 	{this.sortOrder = ' Appointment_Result__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByNoShowDisp() 	{this.sortOrder = ' No_Show_Cancelled_Disposition__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByNoShowReason() 	{this.sortOrder = ' Reason_for_Cancellation_No_Show__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByAddress() 	{this.sortOrder = ' Contact_Name__r.Account.Name ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByPacket() 	{this.sortOrder = ' Contact_Name__r.FAIR_Packet__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}



        List<Event> events;
     	public List<Event> getEvents() {
		events = new List<Event>();
        events = Database.query(myRequest + sortOrder + ascendingOrDescending);
        system.debug(events);
        return events;}

  		public void saveAndReturn() {
        update events;        
        }
}
I use the following test class:
 
@isTest
public class AgentAppointmentsPast30Test {
    
    static testMethod void TestApptPast30(){
        
        Account Testaccount = new account();
       	Testaccount.name = '123 Test Drive';
        Testaccount.RecordTypeId = '0126A0000004Qo4';
        Testaccount.APN__c = '123';
        Testaccount.OwnerId = '0056A000000HeMZ';
        insert Testaccount;
        
        Contact Testcontact = new contact();
        Testcontact.Lastname = 'Berenato';
        Testcontact.AccountId = Testaccount.Id;
        Testcontact.RecordTypeId = '0126A0000004QlU';
        Testcontact.OwnerId = '0056A000000HeMZ';
        insert Testcontact;
        
        Event Testevent = new event();
		Testevent.WhoId = Testcontact.id;        
        Testevent.Subject='Test';
        Testevent.type='Appointment - Booked';
        Testevent.RecordTypeId = '0126A0000004Qle';
        Testevent.ActivityDateTime=date.valueOf('2017-10-17 11:00:00z');
        Testevent.DurationInMinutes=120;
        insert Testevent;
        
        AgentAppointmentsPast30 at = new AgentAppointmentsPast30();
      	List<Event> list1 = at.getEvents();
        at.saveAndReturn();
        at.sortByActivityDateTime();
        at.sortByAddress();
        at.sortByContact();
        at.sortByNoShowDisp();
        at.sortByNoShowReason();
        at.sortByOutcome();
        at.sortByOutcomeNotes();
        at.sortByPacket();
        at.sortBySubject();
        at.sortByType();
        system.assertEquals(1, list1.size());
    }
}

I've never been able to have the event from the Test Class meet the criteria from the Apex Class, I always get the error:

System.AssertException: Assertion Failed: Expected: 1, Actual: 0

Even if I remove everything from the WHERE clause except the getUserId.

However, my Visualforce page in the Sandbox seems to be working fine, minus one major error.

If I assign two events to myself, I see them both in the Apex PageBlockTable.

User-added image

If I edit the event that is farther in the future, I click the Save Button I added to the table.

User-added image

The page reloads:

User-added image

The records are sorted by ActivityDateTime.

And then I manually refresh the page.

User-added image

And the event that was originally farther in the past gets automatically updated to match the new events edit.

As if the Save button is saving the new value to all of the records.

I'm totally stumped on how this is happening. I can't seem to find any workflow rule that would suggest this, and I've tested it several times outside of the PageBlockTable (in the Event's Detail page) and can't find proof that it updates both records independently.

Does anyone know what might be causing this, or why my Apex Class can't pass its test?



 
Hi guys,
i have requirement like this..

for example i have two fileds in my system. one is Number of views and pdfURL.

i have added one url link to pdfURL. when i am going to click that url field i need to display number of views field is 1

if i will going to click 10 times that link value number of views field should be 10.

Please help me on this urgent.

thanks advacne
Hi,
 
Can someone explain to me how to write a test class for an apex trigger like the following one ? This trigger assigns new Leads in Salesforce to the existing Account owner if the domain email address matches the Account's domain.

I'm new to writing Apex but it is working in the Sandbox. I just need a test class to be able to deploy it to Production.


Thanks 

 
trigger addAccount on Lead (before insert){

    //Use a set instead of a list to gather all of the unique domains
    Set<String> leadDomains = new Set<String>();

    //Loop through leads to populate the set
    for(Lead l : trigger.new){
        leadDomains.add(l.domain__c);
    }

    //Query for accounts
    List<Account> leadAccounts = [Select Id, OwnerId, domain__c From Account Where domain__c = :leadDomains];

    //Create Map and loop through list to populate the map
    Map<String,Account> accMap = new Map<String,Account>();
    for(Account a : leadAccounts){
        accMap.put(a.domain__c,a);
    }

    //Loop through leads and assign correct owner from Map
    for(Lead l2 : trigger.new){
        if(accMap.containsKey(l2.domain__c)){
            l2.OwnerId = accMap.get(l2.domain__c).OwnerId;
            l2.Existing_Account__c = true;
            
         
        }
        else{
           
        }
    }


}

 
Hi, i want to write trigger code for the following requirement. i have two objects courses and students .
in course object i have two fields coursename and no of students. in student object i have Name and a lookup field (with course object). if a student  select a course the no of student field count should be incresed.if i delete a student  the count should be decresed.
Hello, I have a custom button with this conditional logic:
if('{!User.ProfileId}'!=='00e40000000zCOY')
{
window.alert("You do not have permission to send survey");
}
else
blah blah blah

This looks to make sure the person pushing the button has the right profile.  It works fine but now I want to add another profile that would be allowed.  So if not profile 1 OR not profile 2, fire the window alert, else go ahead and do something.

If tried multiple things but can't get it to work.  Any suggestions would be appreciated.

Recently, I was writing some classes that needed to detect if the org they were in was a sandbox or not and determine which endpoint to call accordingly. Since there isn's an isSandbox method in Apex, I had to create my own. This will work in visualforce controllers/extensions and from standard classes. You can read the full details at http://www.ericsantiago.com/eric_santiago/2011/12/determining-salesforce-server-pod-and-if-sandbox-via-apex.html

 

Code as follows

 

public String currentPod { 
            String server;
            
            if (ApexPages.currentPage() != null){ //called from VF page
            		server = ApexPages.currentPage().getHeaders().get('X-Salesforce-Forwarded-To');
            } else { //called via standard class
            		server = URL.getSalesforceBaseUrl().getHost();
            }
            
            if ( server != null && server.length() > 0){
                server = server.substring(0 ,server.indexOf('.'));
                
            }
            return server ; 
   }

   public Boolean isSandbox {
            String pod = currentPod();
            if (pod != null && pod.length() > 0 && pod.toUpperCase().startsWith('C')){
                return true;
            }
            return false;
   }

 

Hi there,

I have a trigger to keep Opportunity and Quote Line Items custom field synced. In this process I compare some of the fields of QuoteLineItem and OpportunityLineItem (to find out which ones are corresponding). So I query the items and check for some fields, including UnitPrice. When the user's profile currency is different from the related records currency, the UnitPrice is being converted in one of the objects (QuoteLineItem), but not in the other (OpportunityLineItem), so my mapping fails and my trigger does nothing because it couldn't find a matching item to sync fields. These are the queries my trigger does:
 
String qliQuery = 'select Id, QuoteId, PricebookEntryId, UnitPrice, Quantity, SortOrder, CurrencyIsoCode' + qliFields + ' from QuoteLineItem where Id in (' + qliIds + ') order by QuoteId, SortOrder ASC';
List<QuoteLineItem> qlis = Database.query(qliQuery);

String oliQuery = 'select Id, OpportunityId, PricebookEntryId, UnitPrice, Quantity, SortOrder, CurrencyIsoCode' + oliFields + ' from OpportunityLineItem where OpportunityId in (' + oppIds + ') order by OpportunityId, SortOrder ASC';
List<OpportunityLineItem> olis = Database.query(oliQuery);
Where qliFields and oliFields define which custom fields will be synced, qliIds contains the new QuoteLineItems being created, and oppIds are the IDs of the Opportunities related to the entries that fired this trigger.

These queries are done in an after insert context in the QuoteLineItem object. The result of the both queries is below (I ommited some of the irrelevant fields):
 
[Debug] COMPARING: QuoteLineItem:{Id=0QLc0000002mkaVGAQ, QuoteId=0Q0c0000000acKFCAY, PricebookEntryId=01u0B00000rRLZmQAO, UnitPrice=2855.60, Quantity=1.00, CurrencyIsoCode=USD, ...}

[Debug] COMPARING: OpportunityLineItem:{Id=00kc000000AREWCAA5, OpportunityId=006c000000GFc4SAAT, PricebookEntryId=01u0B00000rRLZmQAO, UnitPrice=1298.00, Quantity=1.00, CurrencyIsoCode=USD, ...}
Note that UnitPrice is returning 2855.60 in this query (which is 1298.00 * 2.20, our default currency conversion rate). Although, both records are registered with CurrencyIsoCode as USD (as they should be). All other records (Opportunity, Quote, PricebookEntry) are registered as USD.

So, when comparing by UnitPrice, those two records never match and my trigger fails its goal. I will remove this comparison and use other criteria for matching, so my problem will be solved for now, but I would like very much to understand this behavior.

​Any help? Thanks in advance.
Hi.

In the VF I used the date format as YYYY-MM-dd in the 
<apex:outputText value="{0,date,YYYY/MM/dd}">
Before the last week of the year it was OK. When the new year falls in the  last week of Decemeber comes the issue.
For example
2014:
S   M  T  W Th F Sat
28 29 30 31 1   2 3

In the above calendar 1st Jan of 2015 falls in the Thurusday.So when I viewd the records of 28,29,30 of December 2014 It showed as
2015-12-28
2015-12-29
2015-12-30
2015-12-31

After that I came to know that
@"YYYY" is week-based calendar year.
@"yyyy" is ordinary calendar year.
http://realmacsoftware.com/blog/working-with-date-and-time

cheers
suresh



 

Posting this in order to help others who, months from now, might Google "OP_WITH_INVALID_USER_TYPE_EXCEPTION" and find this explanation.

 

We wrote an Apex trigger on the User object, to insert a custom object record anytime a user updates their Chatter status.  This was done to fulfill a client's requirement to audit all Chatter activity.

 

The trigger worked fine, until one day the client signed up some Chatter Free users.  When such a user tried to update their status, they got a pop-up with an OP_WITH_INVALID_USER_TYPE_EXCEPTION error.

 

We scratched our collective heads for awhile.  After all, Apex triggers run in "system mode," right?  That is supposed to mean that "object and field-level permissions of the current user are ignored."  And yet this trigger seemed like it was running in "user mode," enforcing restrictions based on who the current user was.

 

The root cause turned out to be that a Chatter Free user cannot be the owner of a custom object record, and SFDC by default sets the current user as a new record's first owner.  We discovered this when we realized, via experiment, that Apex triggers fired as the result of actions by Chatter Free users could definitely update an existing record, but were having problems creating records.

 

So the simple solution was to explicitly set the owner of the new record to some fully-licensed user prior to inserting it.