• Eldon
  • SMARTIE
  • 1064 Points
  • Member since 2016
  • Salesforce Consultant
  • Onivation


  • Chatter
    Feed
  • 30
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 26
    Questions
  • 222
    Replies
Hi! I finally got this simple Apex Trigger working in Sandbox:
trigger restrictFileDeletion on ContentDocument (before delete) {
    String profileName=[SELECT id,Name FROM Profile WHERE Id =:UserInfo.getProfileId()].Name; 
       for (ContentDocument cd : Trigger.old){     
        If(profileName=='ALS Community v6'){
            cd.addError('You cannot delete this record!');
        }
    }
}

Then I went to deploy in production and I received this error "Code Coverage Failure The following triggers have 0% code coverage.  Each trigger must have at least 1% code coverage.restrictFileDeletion.

I have read all related threads and Trailhead, and I'm still stuck on how to write a test class to get this to deploy in production. I would be so appreciate of any help to get this working. I was so excited to get this working in Sandbox, now I've wasted hours, and it's still not working in production. Thanks in advance!!
public static List<Lead> leadsThatMissed(List<Lead> leads) {
		List<Lead> missedLeads = new List<Lead>();
		for (Lead ld : leads) {
			if( ld.Next_Call_Date__c == Date.today().addDays(-1)) {
				ld.Call_Type__c = 'Missed';
				ld.Next_Call_Date__c = 
					ld.Next_Call_Date__c.addDays(1);
				missedLeads.add(ld);
			}
		}
		return missedLeads;
	}
In the above snippet on an Apex class, the ld.Next_Call_Date__c field is a date/time field and I need to get the date value from that field so the comparison works. Basically, I want to say If DATEVALUE(Next_Call_Date__C) == YESTERDAY then do everyhting in the code. 

I tried ld.Next_Call_Date__c.date but that did not work. Any thoughts? Thanks.
 

Hello,

I want to call a webservice with a POST method.

I have a webservice link, JSON file a,d i know that it accepts post method.

I want to know how can i call this service from Salesforce

thank you for suggestions

Hello Group,

I'm trying to create a simple inline VF page but not able to filter just the records I need.

I'm working with 3 objects = Accounts >Customer Visit >Visit Notes.  
I just want to display the last 2 or 3 "Visit Notes" records when a new "Customer Visit" is created,  so our Reps can more easily follow up on their action items.

Customer Visit is a Lookup to Accounts, and Visit Notes is a Master-Detail to Customer Visit.
Visit Notes also has a Lookup relationship to Accounts.

I've tried several different WHERE clauses but only to produce a variety of compiler errors.
Any help would be greatly appreciated!
Hi - I'm trying to write a trigger that will update Recurring Donations when a related opportunity is created or edited.  We need to map encrypted credit card fields on the opportunity to encrypted fields on the Recurring Donation.  I'm a novice when it comes to trigger/apex and have been trying to repurpose from other people's post but I'm not having any luck.  Below is the starting point using test checkbox fields.  If we can get this to work then I can modify it for more fields.  In the developer console I'm not getting any errors - but when I edit an Opportunity the Recurring Donation is not updating. 

Here is the code I was using. 

trigger TestRD1 on Opportunity (after insert, after update) {
    List<Opportunity> opps = new List<Opportunity>(); 
    List<npe03__Recurring_Donation__c> RDs = new List<npe03__Recurring_Donation__c>();
    
    
    for (Opportunity opp : Trigger.new) {
        opps = [SELECT Id, Test_Checkbox__c FROM Opportunity LIMIT 1];
        RDs = [SELECT Id, Test_Checkbox__c FROM npe03__Recurring_Donation__c WHERE Id =: opp.npe03__Recurring_Donation__c];
    }

    for( Opportunity O : opps) {
    for (npe03__Recurring_Donation__c RD: RDs){
        if(O.Test_Checkbox__c== true ){
            RD.Test_Checkbox__c=true;
        }
            
    }
        update RDs;
    }} 
Hello Developers!

I have been working on a trigger that needs to count the number of related "conference" Opportunities that are associated with a Product voucher. This allows tracking of Product vouchers of a particular conference. Basically I need to count the number of Opportunities (ConferenceOppty = TRUE) that are associated with the Product (Product2).

The rollup count field is in the Product object and it's called "Related_Conference_Opportunities__c." 

Any assistance will be greatly appreciated!
trigger RelatedVoucherOpportunity on Product2 (after insert, after update, after delete, after undelete) {
  
  Set<Id> oppIds = new Set<Id>();
 
  Map<Id,Opportunity> oppRecords = new Map<Id,Opportunity>();
  
  for(Product2 p2:Trigger.isDelete?Trigger.old:Trigger.new)
    oppIds.add(p2.oppIds);
 
  oppIds.remove(null);

  for(Id oppId:oppIds)
    oppRecords.put(oppId,new Opportunity(Id=oppId,ConferenceOppty__c = TRUE));
 
  for(Product2 c:[select id,Related_Conference_Opportunities__c from Product2 where id in :oppIds])
    oppRecords.get(p2.oppIds).ConferenceOppty__c += p2.Related_Conference_Opportunities__c;
  
  Database.update(oppRecords.values());
}

 
  • February 08, 2017
  • Like
  • 0
Hi ,

I have a requirement to send an email through code and I need to create letterhead in it. Is there any way to do it?
Hi All,

I had a requirement of redirecting the user to a VF page upon record type selection in Product2 object.

I overrided the New button with a VF page and a corresponding extension class. However the redirection was happening only upon clicking buttons like "Cancel" and "Save" and not upon clicking "Continue" button post record type selection.

I tried replacing the Product2 object with Case in the code just to ensure that the logic was fine in my code and it was working fine.

Please help me out in this.

 
Hi Team,

Need help.
My requirement is to get the total sum of amount field in account object from opportunity. what i have done is i have created a rollup summary in account object with child as opportunity. So i am getting the total amount of all opportunities associated with an account. Now i have to get total amount for all account. ie sum of the roll up summary. Is that possible..
heloo

Master object is opportunity . There is a button on Opportunity to merge fields of opportunity to a document using a conga composer. I also want to merge contact name which has role 'Decision Maker' . How to get this functionality
Hi guys,

I have 2 custom objects (ObjectA__c and ObjectB__c)
in ObjectA__c I have created a lookup field for ObjectB__c.

My problem occurs when I want to have a field CountUsed__c in ObjectB__c that counts the number of times the object is used in the lookup field in ObjectA__c.

I've tried creating a formula field, but not it's not clear to me what the formula should be.
I also tried creating an Apex trigger. However, I couldn't get the select statement to work.

I want a field in ObjectB__c that is readonly and counts the number of time the object is used in the lookupfield @ ObjectA__c

Please advice the correct way to approach this :)

Hi,
i have assigned a string to a variable and want to display the string in 2 lines.
expected result:

User-added image
Sample code

VF Code
-----------------------------------------------------------
<apex:page controller="BreakString1Controller">

    <apex:outputText value="{!str2}"></apex:outputText>

</apex:page>

Controller code
-----------------------------------------------------------------------
public class BreakString1Controller {

    public string str1 = 'Quick brown fox jumps \n '+' <br/>'+' over the lazy dog';
    public string str2 {get; set;}

    public BreakString1Controller (){
        str2 = str1;
    }

}
Any help would pe appreciated
Hello,

I wanted to know the advantages of creating the Sites in SF and what are basics i should know.

thanks for suggestion !
  • January 20, 2017
  • Like
  • 0

We have a custom object to replace the Schedule feature on Opportunity Product. I used a Lookup field on Opportunity Product to create a 1:1 relationship with the custom object Schedule. I want to create a formula field on Schedule to calculate revenue based on Sales Price and some other fields. How do I reference the Sales Price (UnitPrice) in the formula? 
Is there any way to store the List of Contacts on some Field of Account?

Suppose there is a Text Area Long Field on Account where I want to store the names of all the contacts for the account.
 
How to do that?
Hi,

I am new to salesforce lightening concept , i am trying to perform some DML operations(insert , update) using lightening in my developer org

I would like to have a sample code and its flow for reference

Kindly help me pls

Thanks in advance
Hi All,

I'm a begginer in Apex Triggers. The following is a trigger I used but its not working. My Trigger should not allow ANY USERS to delete the record if the record creater (User) becomes INACTIVE. This trigger never allowed me to delete a record eventhough the User is active. Help n Thanks.

trigger  preventdelete  on  Loan__c (before delete){
    for(Loan__c  loan:Trigger.old){
          if(loan.CreatedBy.IsActive == FALSE ){
         loan.addError('You cant delete this record since it is created by an inactive user');
       }
     }
   }
HI,

I am trying to check the chkbox on oppty if their are atleast one child record (Lookup relationship to custom object) , If all records attached to Oppty are deleted, this box should be unchecked.

Any suggestions?
Hi All, any one plz help me out on this,

I have a custom object called " Quotation", with a field called " Total Premium". The object has a look up relationship with another custom object " Cover". In the cover object i have field called " Gross Premium". I need that all the Cover object records addded to the Quotation object, The gross premium from those will sum up and autopopulate in teh Total premium field. Deleting or adding the records, should affect the Total premium field value.

User-added image

I have written the below trigger, but its showing the error as,
Error: Compile Error: unexpected token: trigger trgSummarizeCover at line 1 column 0
Can anyone plz figure it out whats wrong in my code and rectify it. Thanks
 
trigger trgSummarizeCover on Cover__c (after delete, after insert, after update) {

  //Limit the size of list by using Sets which do not contain duplicate elements
  set<Id> QuotationIds = new set<Id>();

  //When adding new CustomObject or updating existing CustomObject
  if(trigger.isInsert || trigger.isUpdate){
    for(Cover__c p : trigger.new){
      QuotationIds.add(p.Quotation__c);
    }
  }

  //When deleting CustomObject
  if(trigger.isDelete){
    for(Cover__c p : trigger.old){
      QuotationsIds.add(p.Quotation__c);
    }
  }

  //Map will contain one Quotation Id to one sum value
  map<Id,Double> QuotationMap = new map <Id,Double>();

  //Produce a sum of Cover__c and add them to the map
  //use group by to have a single Quotation Id with a single sum value
  for(AggregateResult q : [select Id,sum(Gross_premium_policy__c)
    from Cover__c where Quotation__c IN :QuotationIds group by Quotation__c]){
      QuotationMap.put((Id) q.get('Quotation__c'),(Double)q.get('expr0'));
  }

  List<Quotation__c> QuotationsToUpdate = new List<Quotation__c>();

  //Run the for loop on Quotation using the non-duplicate set of Quotation Ids
  //Get the sum value from the map and create a list of Quotations to update
  for(Quotation__c o : [Select Id, Total_Premium__c from Quotation__c where Id IN :QuotationIds]){
    Double Cover__c sum = QuotationMap.get(o.Id);
    o.Total_Premium__c = Cover__c sum;
    QuotationsToUpdate.add(o);
  }

  update QuotationsToUpdate;
}


 
Hi All,

In my contact object I have a field named NewsletterStatus. When my apex class is executed by a guest user, the method Schema.sObjectType.contact.fields.Newsletter_Status__c.isUpdateable() is returning false even though the guest profile and admin profile have edit access to this field and the object. Any reason for this?

Thanks in advance
Eldon K
  • June 01, 2021
  • Like
  • 0
Hi All,

I am trying to display the notes associated with a custom object record. I have the correct ContentNote Ids but when I give the following SOQL in an apex class, I am receiving an error.
[SELECT Id,Title, Content,CreatedDate, TextPreview FROM ContentNote WHERE Id IN: contentIds]

No such column 'TextPreview' on entity 'ContentNote'. If you are attempting to use a custom field, be sure to append the '__c' 

The same SOQL works fine in the query editor though. I am able to the see the correct records and the TextPreview field in console.
I am trying to display these notes in a VF page and if I use the field 'Content' in the page its displayed as below:
          core.filemanager.ByteBlobValue@19c5beb6

Is there any way to display the text value of the notes in VF page?

Thanks in advance
Eldon K
 
  • December 23, 2020
  • Like
  • 0
Hi All,

I am trying to update a field when a file in the related list files is downloaded. Is there a way to create a trigger for this use case? 

Thanks in advance
  • May 29, 2020
  • Like
  • 0
Hi ,

First of all sorry for posting something not related to SF developement. I am right now trying to find out a topic for my master thesis and i would like to do something related to salesforce. It would be really helpfull if someone could suggest me some ideas or places i can look for some interesting topics. I am pursuing MSc in business informatics btw. 

Thanks in advance.
  • June 30, 2018
  • Like
  • 0
Hi,

I am trying to grey out(disable) createPDF button(std button) in the quote object when a checkbox value is ticked. Is there any way to do this? Also is it possible to put an error message on clicking that std button when checkbox value is ticked.

PS: What i did currently as a workarround is to create 2 different recordtype with one not containing createPDF button and one contains it and assign it according to the checkbox value in quote trigger.

Thanks
  • June 07, 2017
  • Like
  • 0
Hi all,

I need to autofill ship to address and bill to address from some custom fields instead of std account address while creating quotes from opportunity.
this is what i was thinking of doing
 
        opportunity opp = [select id,Billing_City__c from opportunity where id = :oppid limit 1];
        return new PageReference('/0Q0/e?retURL=%2F'+oppid+'&oppid='+oppid+'&BilltoCity='+opp.Billing_City__c);

Its not working i need the separate API names of shiptoaddress and billtoaddress for the quote object. Any ideas?
  • May 11, 2017
  • Like
  • 0
Hi,

Given below is my code for javascript button to update the status field
 
{!REQUIRESCRIPT("/soap/ajax/31.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")} 

try{ 


var myquery = "SELECT Id, Name, status FROM lead WHERE Id = '{!Lead.Id}' limit 1"; 

result = sforce.connection.query(myquery); 
records = result.getArray("records"); 

var myLead= records[0]; 
var updateLead = new Array(); 

myLead.status = "Unqualified"; 
updateLead.push(myLead); 

result = sforce.connection.update(updateLead); 

if(result[0].success == "true"){ 
location.reload(); 
} 
else{ 
alert( 
"An Error has Occurred. Error: \r\n" + 
result[0].errors.message 
); 
} 
} 
catch(e){ 
alert( 
"An Un-expected Error has Occurred. Error: \r\n" + 
e 
); 
}

But i am geting the following error,

faultcode:'soapenv:Client', faultstring:'A duplicate value was specified for field 'Status' in object 'Lead', duplicate value 'Unqualified' prior value 'New'', }


What could be the reason?
  • April 20, 2017
  • Like
  • 0
Hi,

I am trying to create an email templae in html without letterhead. Following is my html body
 
<html>
<style>
.para1{
font-size : 11pt;
font-family : calibri;
}
.para2{
font-size : 10pt;
font-family : calibri;
}
.icons{
padding-left : 10px;
}
</style>
<body>



<div class = "para1" >
Hi {!Lead.FirstName}, <br><br>

Thanks for taking the time to speak with me today.  I have included a quote for you below.<br><br>

test paragraph

Let me know a good time for a quick demonstration of our software!<br><br>

Thank you,<br>

{!User.Name} <br></div>
<div class ="para2">
test test<br>
{!User.Phone} ext. {!User.Extension} <br><br>

<a href="http://www.test.com"><img src="https://c.test.content.force.com/servlet/servlet.ImageServer?id=01541000001gmDR&oid=&lastMod=1489741933000" alt="Company Logo" 
height="64" width="134"/>
<br> 	

<div class="icons"> 
<a href="http://www.facebook.com/Pointos"><img src="https://c.test.content.force.com/servlet/servlet.ImageServer?id=01541000001gmDW&oid=&lastMod=1489741926000" height="22" width="22"></a>

<a href="http://www.twitter.com/PointOSXE"><img src="https://c.test.content.force.com/servlet/servlet.ImageServer?id=01541000001gmDb&oid=&lastMod=1489742012000" height="22" width="22"></a>

<a href="http://www.linkedIn.com/"><img src="https://c.test.content.force.com/servlet/servlet.ImageServer?id=01541000001gmDS&oid=&lastMod=1489741971000" height="22" width="22"></a>
</div> 
</div>
 <br>

</body>
</html>

When i preview it i am getting everything correct as below,

User-added image

Font size as calibri and till thankyou my font size is 11 and after that font size is 10. 

But in my gmail i am getting unformatted mail body. Same font size and type for all and image i shown and link is working but image is not padded as given in style.

Also in my outlook i am getting the font size and type correectly but my images(fb,twitter etc) are not showing.but Link is working.

What can be done here.

Thanks
  • March 17, 2017
  • Like
  • 0
Hi All,

I Need to track the origin of the pages. ie from which page its navigated to the current page, whether the page is browsed by clicking on a link in the mail etc.

Thanks
  • March 15, 2017
  • Like
  • 1
Hi,

I am trying to fire a lightning event from my nouislider function. It was working a while ago. But now it stopped working all of a sudden.
Below is my lightning component part,
 
<aura:component controller="shoponklik.LightningCartApexController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    
    <ltng:require styles="/resource/shoponklik__w3,/resource/shoponklik__ecart/jquery.nouislider.min.css"	
                  scripts="/resource/shoponklik__ecart/jquery.js,/resource/shoponklik__ecart/jquery.nouislider.all.min.js" 
                  afterScriptsLoaded="{!c.callSlider}"/>
    <style>
        body{
        overflow-x:hidden;
        overflow-y:auto;
        }
    </style>
    
    <aura:handler name="init" value="{!this}" action="{!c.itemList}"></aura:handler>   
    <aura:handler event="c:PriceSelectionChange" action="{!c.filter}"/>
    <aura:handler event="c:SearchKeyChange" action="{!c.filter}"/>

Below is the function that is called after loading nouislider,
 
callSlider:function(component, event, helper) {
        
        var $slider = $("#slider");
       
        var maxProdVal=0;
        var stepsize=0;
        var action=component.get("c.getItemList"); 
        action.setCallback(this, function(response){
            var state= response.getState();            
            var tempItems;
            if (state == "SUCCESS"){
                tempItems=response.getReturnValue();
                for(var i = 0; i<tempItems.length;i++){
                    
                    if(response.getReturnValue()[i].item.UnitPrice>maxProdVal)
                    {
                        maxProdVal=response.getReturnValue()[i].item.UnitPrice;
                       
                        if(maxProdVal>=50000){
                            stepsize=1000;
                            
                        }
                        else if(maxProdVal>=10000 && maxProdVal<50000){
                            stepsize=500;
                            
                        }
                            else if(maxProdVal>=2000 && maxProdVal<10000){
                                stepsize=250;
                            }
                                else if(maxProdVal<2000 && maxProdVal>=1000){
                                    stepsize=100;
                                }
                                    else{
                                        stepsize=50;
                                    } 
                    }
                    /*checking discount*/
                      if(response.getReturnValue()[i].item.shoponklik__Discount__c==null){
                        tempItems[i].disc='false';
                    }
                    else
                    {
                        tempItems[i].disc='true';
                    }
                    
                    
                }
                
                
                component.set("v.Items",tempItems);           
                
                
                
                $slider.noUiSlider({
                    
                    
                    start: [0, maxProdVal],
                    connect: true,
                    step: stepsize,
                    range: {
                        'min': 0,
                        'max': maxProdVal
                    }
                });
                $slider.Link('lower').to('-inline-<div class="tooltip"></div>', function ( value ) {
                    
                    $(this).html(
                        '<span>' + '₹ '+(value / 1) + '</span>'
                    );
                });
                $slider.Link('upper').to('-inline-<div class="tooltip"></div>', function ( value ) {
                    $(this).html(
                        '<span>' + '₹ '+(value / 1) + '</span>'
                    );
                });
                $slider.on({
                    change: function(event){
                        var minMax =  $slider.val();
                        
                        component.set("v.minprice",minMax[0]);
                        component.set("v.maxprice",minMax[1]);
                        
                         $A.enqueueAction(action);
        var myEvent2 = $A.get("e.shoponklik:PriceSelectionChange");
                        myEvent2.fire();
                     
                    }
                       
                });
               
            }});
                
    },

But it is showing the following error when i change the slider that is onchange.

Uncaught TypeError: Cannot read property 'fire' of undefined throws at components
That is the line myEvent2.fire();  is throwing error.

Any help would be appreciated
  • November 07, 2016
  • Like
  • 0
Hi,

Like i posted above wht is the difference between using Schema.RecordTypeInfo returned by Case.sObjectType.getDescribe().getRecordTypeInfos() and using 
 SOQL to query Case records in the org to get all the RecordType values available for Case 

I stumbled upon this question while going through a question to display all the available record types for a case Object. 

Regards
  • October 10, 2016
  • Like
  • 0
Hi

I am trying to query my standard pricebook in my apex method by following code,

PriceBook2 PB=[select id,Name from Pricebook2 where IsStandard = true];

Im getting the result in my application but when i write test class and call the method containing that code im getting the following error,

System.QueryException: List has no rows for assignment to SObject.

finally i did my test class using seealldata=true and im able to get the results

What is the reason for this?

 
 
  • September 20, 2016
  • Like
  • 0
Hi 

Im trying to create a community user in my test class having a contact associated with it. But when i insert the user im getting error.
 
account userAccount=new account(
           name='userAccount'
       );
       insert userAccount;
       
       contact userContact=new contact(
           lastname='userName',
           AccountId=userAccount.id
       );
       insert userContact;
       
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       system.debug('portalRole is ' + portalRole);
       
       
       Id p = [select id from profile where name='Partner Community User'].id;
       User user2 = new User(
           contactid=userContact.id,
           UserRoleId = portalRole.Id,
           ProfileId = p,
           Username = 'TestUserCheckOut@gmail.com',
           Alias = 'batman',
           Email='bruce.wayne@wayneenterprises.com',
           EmailEncodingKey='UTF-8',
           Firstname='Bruce',
           Lastname='Wayne',
           LanguageLocaleKey='en_US',
           LocaleSidKey='en_US',
           TimeZoneSidKey='America/Chicago'
       );
       insert user2;
       system.runAs(user2){
           
           LightningCartApexController.CheckOut();           
       }

Im getting teh following error,

System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): User, original object: Account: []
 
Thank you
  • September 15, 2016
  • Like
  • 0
i have my map in my apex as follows,

 map<id,list<OrderDetailsClass>> OrderedProductsInOrder=new map<id,list<OrderDetailsClass>>();
where OrderDetailsClass is wrapper class which stores info of order products. Im getting ids of orders as keys and corresponding order products as value.


I set the result from apex to JS  like below,

 var getOrdersAction=component.get("c.getOrdersApex"); //getOrdersApex is the apex method
         getOrdersAction.setCallback(this, function(response){
           
             var OLE=getOrdersAction.getReturnValue();
             component.set("v.orderProducts",OLE);


Now i have 1 order id and 3 order products corresponding to that order. im getting it in my JS controller  when i give alert like below,

alert(component.get("v.orderProducts")['80128000000C3hVAAS']); // 80128000000C3hVAAS is my order id

I have 1 order and 3 order products associated with it. Im getting 3 order products in the alert. Now i want to display it in my component. That is group order products under each orders.
How can we do that?
 
  • August 30, 2016
  • Like
  • 0
How to query the particular product name and product fields from the order items?
  • August 30, 2016
  • Like
  • 0
What is the best way to return two sobject lists from a single apex method?
  • August 30, 2016
  • Like
  • 0
1.Why are we getting error When we query like this in query editor?
SELECT Name, (SELECT Name FROM OpportunityLineItem)  FROM Product2

2.Is there any relationship between Product2 and OpportunityLineItem because i see relationship in schema builder but cannot see any relation field in opportunity line item to product2
  • August 24, 2016
  • Like
  • 0
Hi,

Im trying to create an Order and related order products in apex using lightning.
So basically i want to call a server method that creates order and order products when i click a checkout button.
I am able to do it in my lightning app. But when i put my component in a community(Napili template), and login as a community user , order and order products are not getting created when i call the same server method and my community page is getting refreshed instead. 
the server method is as follows,


@auraenabled
    public static string CheckOut(){
        
       
        String userID;
        userID = UserInfo.getUserId();
        list<user> u=[select id,Name from user where id=:userID];
        string nam= u[0].Name +'-Automated';
        list<Opportunity> Oppid=[select id from opportunity where name=:nam];
        system.debug('Oppid'+Oppid[0].id);
        string OID;
        OID=Oppid[0].id;
        
        list<OpportunityLineItem> OppListItems=[select OpportunityId,Quantity,UnitPrice,PriceBookEntryId,Product2Id,InMyCart__c,Wishlisted__c 
                                         from OpportunityLineItem where InMyCart__c=:true AND OpportunityId=:OID];
             
        if(OppListItems.size()>0){
            Order NewOrder = new Order(
               
                AccountId='0012800000ZKzhH',
                Status='Draft',
                EffectiveDate=System.today(),
               
                Pricebook2Id ='01s28000006q8A8',
                OpportunityId=Oppid[0].id
                
            );
            
            insert NewOrder;
             
            list <OrderItem> OrderitemList=new list<OrderItem>();
            
            For(integer i=0;i<OppListItems.size();i++){
                
                if(OppListItems[i].InMyCart__c==true){
                    OppListItems[i].InMyCart__c=false;
                    OrderItem OI=new OrderItem(
                        OrderId=NewOrder.Id,
                        Quantity=OppListItems[i].Quantity,
                        
                        PriceBookEntryId=OppListItems[i].PriceBookEntryId,
                        UnitPrice=OppListItems[i].UnitPrice
                        // Product2Id=OppLI[i].Product2Id
                        
                    );
                    OrderitemList.add(OI);
                }
            }
            system.debug('OrderitemList'+OrderitemList);
            insert OrderitemList;
            system.debug('OppLI'+OppListItems);
            update OppListItems;
            
            list<OpportunityLineItem> OppLIToDelete=[select id,name from OpportunityLineItem where InMyCart__c=:false AND WishListed__c=:false];
            delete OppLIToDelete;
            
            
        }   
        return OID;
    }



OppLIToDelete  is getting deleted . But order and order products are not getting created. Any help would be appreciated.

Thankyou
  • August 18, 2016
  • Like
  • 0
Hi,

Im trying to create an Order and related order products in apex using lightning.
So basically i want to call a server method that creates order and order products when i click a checkout button.
I am able to do it in my lightning app. But when i put my component in a community(Napili template), and login as a community user , order and order products are not getting created when i call the same server method and my community page is getting refreshed instead. 
the server method is as follows,


@auraenabled
    public static string CheckOut(){
        
       
        String userID;
        userID = UserInfo.getUserId();
        list<user> u=[select id,Name from user where id=:userID];
        string nam= u[0].Name +'-Automated';
        list<Opportunity> Oppid=[select id from opportunity where name=:nam];
        system.debug('Oppid'+Oppid[0].id);
        string OID;
        OID=Oppid[0].id;
        
        list<OpportunityLineItem> OppListItems=[select OpportunityId,Quantity,UnitPrice,PriceBookEntryId,Product2Id,InMyCart__c,Wishlisted__c 
                                         from OpportunityLineItem where InMyCart__c=:true AND OpportunityId=:OID];
             
        if(OppListItems.size()>0){
            Order NewOrder = new Order(
               
                AccountId='0012800000ZKzhH',
                Status='Draft',
                EffectiveDate=System.today(),
               
                Pricebook2Id ='01s28000006q8A8',
                OpportunityId=Oppid[0].id
                
            );
            
            insert NewOrder;
             
            list <OrderItem> OrderitemList=new list<OrderItem>();
            
            For(integer i=0;i<OppListItems.size();i++){
                
                if(OppListItems[i].InMyCart__c==true){
                    OppListItems[i].InMyCart__c=false;
                    OrderItem OI=new OrderItem(
                        OrderId=NewOrder.Id,
                        Quantity=OppListItems[i].Quantity,
                        
                        PriceBookEntryId=OppListItems[i].PriceBookEntryId,
                        UnitPrice=OppListItems[i].UnitPrice
                        // Product2Id=OppLI[i].Product2Id
                        
                    );
                    OrderitemList.add(OI);
                }
            }
            system.debug('OrderitemList'+OrderitemList);
            insert OrderitemList;
            system.debug('OppLI'+OppListItems);
            update OppListItems;
            
            list<OpportunityLineItem> OppLIToDelete=[select id,name from OpportunityLineItem where InMyCart__c=:false AND WishListed__c=:false];
            delete OppLIToDelete;
            
            
        }   
        return OID;
    }



OppLIToDelete  is getting deleted . But order and order products are not getting created. Any help would be appreciated.

Thankyou
 
  • August 18, 2016
  • Like
  • 0
Hi,

I need to call an apex server function in lightning in every 10 seconds.Is there anyway to achieve this?

Thank you
  • August 08, 2016
  • Like
  • 0
Hi All,

I Need to track the origin of the pages. ie from which page its navigated to the current page, whether the page is browsed by clicking on a link in the mail etc.

Thanks
  • March 15, 2017
  • Like
  • 1
I need to add a column with number of days since a task created date. Please could someone help with the code so I can just insert my created date field into it.

TIA.

Dave.
Hi All,

In my contact object I have a field named NewsletterStatus. When my apex class is executed by a guest user, the method Schema.sObjectType.contact.fields.Newsletter_Status__c.isUpdateable() is returning false even though the guest profile and admin profile have edit access to this field and the object. Any reason for this?

Thanks in advance
Eldon K
  • June 01, 2021
  • Like
  • 0
Hi All,

I am trying to display the notes associated with a custom object record. I have the correct ContentNote Ids but when I give the following SOQL in an apex class, I am receiving an error.
[SELECT Id,Title, Content,CreatedDate, TextPreview FROM ContentNote WHERE Id IN: contentIds]

No such column 'TextPreview' on entity 'ContentNote'. If you are attempting to use a custom field, be sure to append the '__c' 

The same SOQL works fine in the query editor though. I am able to the see the correct records and the TextPreview field in console.
I am trying to display these notes in a VF page and if I use the field 'Content' in the page its displayed as below:
          core.filemanager.ByteBlobValue@19c5beb6

Is there any way to display the text value of the notes in VF page?

Thanks in advance
Eldon K
 
  • December 23, 2020
  • Like
  • 0
I have a trigger which is added to object A in which I need to show error on save button but at the same time I need to insert record in a custom object B. I am using trigger.new[0].addError('Message') and then using database.insert to insert the data in the custom object B but the record is not getting created as I read in documentation that addError rollbacks the DML operation but I need both the error and DML operation to function.  Can anyone help me with this?
I have always been able to avoid writing code till today. Our marketing team created several hundred Pardot Landing pages for our business partners sales reps to enter leads into. 
These leads come into Salesforce and have a text field  populated called Landing_Page_ID__c . The field is basically firstname.lastname  of the partner sales rep.  

I need to be able to populate a lookup on the lead called Territory_Manager__c . (this is the contact record of the partner sales rep who submiited the lead)  I have created a new field on the Conact called LPID_c which matches the text from the Landing_Page_ID__c.

I am going to watch videos and trailheads but I thought I would ask here first since I am on a deadline to fix this.
 
Account - Standard Object
Case - Child of Account
Milestone__Project__c - Child of Case

The After-Insert Trigger will send an email message anytime an account has 8 cases or more created in a 5 day period.  The email will be sent to one of two addresses (depending on Project.status).  How do I access the Milestone__Project__c.Status field?  I cannot get the syntax correct.
 
public class CaseHandlerCountAlert{
public static void CaseCounter(){

    List<AggregateResult> AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co, (Id FROM Milestone1_Project__c mi)
                                FROM Case
                                WHERE CreatedDate = LAST_N_DAYS:5
                                GROUP BY AccountId, Account.Name
                                HAVING COUNT(Id)  >= 8
                                WHERE Id IN :Trigger.new];
                                

            for(AggregateResult aggr:AggregateResultList){ 

                    Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                        if((aggr.get(mi.status) == "Transition"){    // If Status = Transition
                            // Set Outgoing Email to Implementation Coordinator "Implementation.Consultalt "
                            message.toAddresses = new String[] { Milestone1_Project__c.Client_Advisor_Email__c };
                        }
                        else if ((aggr.get(mi.status) == "Live"){  // If Status equals "Live" - Out Of Transition
                            // Private method retrieves email address from Customer Success Managers
                            message.toAddresses = new String[] { getAddresses() };
                        } 
                            // Set Email Template Id
                    //EmailTemplate templateId = [Select id from EmailTemplate where name = 'Template Name'];  
                    //mail.setTemplateID(templateId.Id);
                    message.setSubject = 'Subject Test Message';
                    message.setPlainTextBody = 'Account name: ' + aggr.get('name') + ' has ' + (Integer)aggr.get('co') + ' cases opened in the last 8 days.';
                    Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
                    Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
                System.debug('Account Name: ' + aggr.get('name'));           
            }
            } 

            private List<String> getAddresses(){
            List<User> UserList =
                    [SELECT id, name, email, isactive, profile.name, userrole.name, usertype
                    FROM User 
                    WHERE id 
                    IN (SELECT userorgroupid 
                    FROM groupmember
                    WHERE group.name = 'Customer Success Managers')];

            Set<String> emailString = new Set<String>();

            for(User u: UserList){
                emailstring.add(u.email);
                // System.debug(u.email);
            }   
            //System.debug('The list ' + emailstring);
            return (emailString);
            }    
            }

 
Hi! I finally got this simple Apex Trigger working in Sandbox:
trigger restrictFileDeletion on ContentDocument (before delete) {
    String profileName=[SELECT id,Name FROM Profile WHERE Id =:UserInfo.getProfileId()].Name; 
       for (ContentDocument cd : Trigger.old){     
        If(profileName=='ALS Community v6'){
            cd.addError('You cannot delete this record!');
        }
    }
}

Then I went to deploy in production and I received this error "Code Coverage Failure The following triggers have 0% code coverage.  Each trigger must have at least 1% code coverage.restrictFileDeletion.

I have read all related threads and Trailhead, and I'm still stuck on how to write a test class to get this to deploy in production. I would be so appreciate of any help to get this working. I was so excited to get this working in Sandbox, now I've wasted hours, and it's still not working in production. Thanks in advance!!

Salute.

I'm trying to add to the contact list page an indication of the role of each indirect contact. Like this:

   public List<Contact> Contacts { get{  
     return [SELECT Id, Name, Account.Name, Title, Email, Phone, Relations__c FROM Contact LIMIT 1000];  
   } set;}  
   
   public List<Role> Roles { get{  
     return [SELECT Role FROM AccountContactRoles];  
   } set;}  I tried adding Role or AccountContactRole fields, but they are not recognized. What I need to do?
I tried to indicate the Role field in the first request, but received a recognition error (which is logical, there is no such field in the standard contact card).

Then I made the second request only for roles, but it also produces Compile Error: Invalid type: Roles.

What i need to do?
How can i automatically create quote line item and add opportunity line item as quote line item when i will create Quote .I Have tried this trigger which is not working as per my requirement .
trigger createQuoteLineDetails on CQuote__c(after insert,before insert) {

CQuote__c ord=trigger.new[0];

// Fetch Opp Id
COpportunity__c oppId=[select id from COpportunity__c where id=:ord.QOpp_Name__c];

// Fetch Opp Lines 
List<Opportunity_LineItem__c> opplines=[select id,CurrencyIsoCode,Opportunity__r.name,Principal_Name__c, Product_Category__c,Product_Description__c,
                        Product__c,Quantity__c,Unit_Price__c from Opportunity_LineItem__c where Opportunity__c=:oppId.id];

    // Loop Opportunity Lines
    for(Opportunity_LineItem__c oppline:opplines){
        
        // Create Order Line Object
        Quote_Line_Item__c QLine = new Quote_Line_Item__c ();
        QLine.Quote_Name__c= ord.Id;
       
       
        insert QLine ;
    }

}

 
Hi,

i have one checkbow field in opportunity record when i am clone the opportunity record i want checkbox field valueas automatically true for new records 

 
I have Quote object which has Child object Quotation Line Item and I have PO object which has child object named Project .

PO has Lookup with Quote, So when I will create a new PO from Quote, Same number of Projects should create under PO against each Quotation Line Item,

I tried the following code but it is not capturing Quotation Line Item Name against which one which project created. Please Help me to Resolve this
User-added image
 
How to query all the users in a particualr queue

thanks
Hi,,

I have created 4 fields on price book enteries.

Product Material No.
Sales Unit Of Measure
Region
Currency.

I require a combination of these 4 fields to be the primary key(5th field) for my product. Such that , that primary key be the determinant for the price of my product.

If any of the 4 fields differ in value from the previously existing combination , It will set a new price for a product.

I understand , there is no apex trigger or workflow rule on pricebook. How do i achieve this functionality?



 
Consider Account(std object),Vehicle(custom object-lookup to account) and forms(another custom object- loookup to account).There is a field on custom object Vehicle called "Expiration date". Customers will apply for a form once their vehicles gets expired to get renewed. The forms are shared to account and vehicles(sharing rule).I want to send an email alert  to a team (details of vehicle) when the vehicle gets expired and didnot apply for renewal. Bit confused but can we do this? Batch class or trigger?
Hi, 

  In below helper class i have commented there are two condition update for contact and lead Please suggest me how to make this out of for loop and code bulkified.  Please suggest
public class CtapAssessmentTriggerUtils { 
  
    public static void processInsert(List<CTAP_Assessment__c> newLst) {
        List<Contact> cntlst = new List<Contact>();
        List<Lead>    ledlst = new List<Lead>();
        Set<String> emailSet = new Set<String>();
        Set<String> partnerSet = new Set<String>();
        Lead l = new lead();
        
        Map<String, Id> mapEmailToConId = new Map<String, Id>();
        Map<String, Id> mapEmailToLeadId = new Map<String, Id>();
        List<Lead> newLeadLst = new List<Lead>();
        Map<String, CTAP_Assessment__c> newLeadforCtapMap = new Map<String, CTAP_Assessment__c> ();
        Map<Id,Id> PartnerActMap = new Map<Id,Id>();
         
        // collect emails in a set
        for(CTAP_Assessment__c ctap : newLst) {
            CountryCodeMap__c codeMap = CountryCodeMap__c.getInstance(ctap.Country_Code__c);                   
            system.debug('__kkk__' +codeMap);
            if(codeMap != null) {
                ctap.End_Customer_Country__c = codeMap.Country_Name__c;
            }
            emailSet.add(ctap.Contact_Email__c);
            partnerSet.add(ctap.Partner_Account__c);
            system.debug('ctap.Contact_Email__c ' + ctap.Contact_Email__c);
        }
        // removing nulls
        emailSet.remove(null);
        
        system.debug('emailSet '  + emailSet);
        
        if(!emailSet.isEmpty()) {
            for(Contact objCon : [select id,email from contact where email IN :emailSet]){
                mapEmailToConId.put(objCon.Email, objCon.Id);
                objCon.Lead_Source_Temp__c = 'CTAP Assessement'; //Update Contact Lead Source added by Sudhir
                cntlst.add(objCon);
            }
            
            for(Lead objLead: [select id,email from Lead where email IN :emailSet]){
                mapEmailToLeadId.put(objLead.Email, objLead.Id);
                objLead.Lead_Source_Temp__c = 'CTAP Assessement'; //Update Lead Source added by Sudhir
                ledlst.add(objLead);
            }
        }        
                
         for(Account ObjPartnerAct : [select id,owner.name,ownerid from account where id in :partnerSet]){
            PartnerActMap.put(ObjPartnerAct.id,ObjPartnerAct.ownerid);
         }
         
        // asssign based on map key match with email
        for(CTAP_Assessment__c ctap : newLst){
            if( mapEmailToConId.get(ctap.Contact_Email__c) != null){
              ctap.Contact__c = mapEmailToConId.get(ctap.Contact_Email__c);
              ctap.Lead__c = null;
                if (!cntlst.isEmpty()){  // Conditional update contact
                   update cntlst;
                  }
             }else if ( mapEmailToLeadId.get(ctap.Contact_Email__c) != null) {
              ctap.Lead__c = mapEmailToLeadId.get(ctap.Contact_Email__c);
              ctap.Contact__c = null;
                   if (!ledlst.isEmpty()){ //Conditional update lead
                   update ledlst;
                  }
              }
              else {         
                  // Create a new lead         
                  l.Company = ctap.End_Customer_Name__c;
                  l.FirstName = ctap.Contact_First_Name__c; 
                  l.LastName = ctap.Contact_Last_Name__c; 
                  l.Email = ctap.Contact_Email__c;
                  l.Phone = ctap.Phone__c;
                  l.Title = ctap.Title__c;
                  l.Industry = ctap.Industry__c;
                  l.Lead_Source_Temp__c = 'CTAP Assessement';
                  l.LeadSource = 'CTAP Assessement';
                  l.street = ctap.Address__c;
                  l.Country = ctap.End_Customer_Country__c;
                  l.State = ctap.state__c;
                  l.Postalcode = ctap.postalcode__c;
                  l.Employee_Size__c = ctap.Employee_Size__c;  

                  if(ctap.Country_Code__c == 'US') {// verify for the Assignment rule test for US 
                      l.Run_Assignment_Rule__c = true;
                  } else if(ctap.Partner_Account__c !=  null && ( ctap.Country_Code__c != 'US') ){ //Here it checks only for country USA
                    l.Ownerid = PartnerActMap.get(ctap.Partner_Account__c);  
                  }  
                                              
                 if(ctap.Contact_Email__c <> null && 
                    ctap.End_Customer_Country__c <> null &&
                    ctap.End_Customer_Name__c <> null &&
                    ctap.Contact_First_Name__c <> null ) {                                                    
                   newLeadLst.add(l);
                  }
                  
                 newLeadforCtapMap.put(ctap.Contact_Email__c, ctap);
             
          } 
        }
        
           if ( !newLeadLst.isEmpty() ){
                insert newLeadLst;
                    
                 for(Lead lead : newLeadLst){
                    CTAP_Assessment__c ctap = newLeadforCtapMap.get(lead.Email);
                    ctap.Lead__c = lead.id; //Assign new lead to ctap lead
                 }
            }
    }
     
    public static void processUpdate(Map<id,CTAP_Assessment__c> newMap, Map<id,CTAP_Assessment__c> oldMap) {
        List<CTAP_Assessment__c> changedLst = new List<CTAP_Assessment__c>();
        for(CTAP_Assessment__c ctap : newMap.values()){
            CTAP_Assessment__c oldCtap = oldMap.get(ctap.id);
              if(ctap.Contact_Email__c != null){
                changedLst.add(ctap);
            }
        
            if(!changedLst.isEmpty())
                processInsert(changedLst);
        }
    }
    
  
    
  
}

Thanks
Sudhir
Dear Friends, 

Need your help, My Question is...

There is a Trigger Code on Task object, Which is going to update a custom field on Opporunity (There is DML Update operation on Task Object for Opportunity). And there is also a trigger code on Opportunity (after Update). So Whenever i create a task, and i am comparing (Task.WhatId==Opp.WhatID), In the Console it is saying that ' Attempt to Derefernce a null Object ',. How to over come on this. How to use Recursive trigger here. Please help me on this. Thank you.  
Hello Group,

I'm trying to create a simple inline VF page but not able to filter just the records I need.

I'm working with 3 objects = Accounts >Customer Visit >Visit Notes.  
I just want to display the last 2 or 3 "Visit Notes" records when a new "Customer Visit" is created,  so our Reps can more easily follow up on their action items.

Customer Visit is a Lookup to Accounts, and Visit Notes is a Master-Detail to Customer Visit.
Visit Notes also has a Lookup relationship to Accounts.

I've tried several different WHERE clauses but only to produce a variety of compiler errors.
Any help would be greatly appreciated!
Hi,
I am trying create a multilingual lightning application in salesforce and I was wondering if any sample solution or documentation that can provide me some direction on how to approach the development.

Thanks in advance.