function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Filipe BaradelliFilipe Baradelli 

DUPLICATE_VALUE, This price definition already exists in this price book: []

public pageReference addToCart() {
        if(!Catalog_Order__c.sObjectType.getDescribe().isUpdateable() || !Catalog_Line_Item__c.sObjectType.getDescribe().isCreateable()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        if( productId == null ) {} else {
        // First make sure that our Order is in the database
        upsert myOrder;
        orderId = myOrder.Id;

        produto = productId;
        // Check if the product is already in the Cart
        if( productSet.contains( productId ) ) { } else {
            // Here is where we add the ID to the set...
            productSet.add( productId );
            // ...and to the Order.
            Catalog_Line_Item__c li =  new Catalog_Line_item__c();
            li.Product__c = productId;
            produto = productId;
            li.Catalog_Order__c = myOrder.Id;
            li.Quantity__c = 1;
            insert li;        
            
            // Added to Cart
            }
        }
        // Clear the parameter and reupsert
        productId = null;
        upsert myOrder;
        return null;
    }
 public PageReference toCart() {

        integer stdPriceBookRecId2; 
        List<Pricebook2> stdPriceBookRecId = new List<Pricebook2>();
        Catalog_Order__c[] orderQuery = [SELECT Items__c,Total_Cost__c,Account__c,Id,(SELECT Id,Product__c,Product_Short_Description__c,Product_Price__c,Product_Name__c,Quantity__c,VF_Image__c FROM Catalog_Line_Items__r) FROM Catalog_Order__c WHERE Status__c = 'Cart' AND CreatedById =:UserInfo.getUserId() ORDER BY LastModifiedDate DESC NULLS FIRST LIMIT 1];

        // Insert Pricebook
        PriceBook2 customPriceBook = new PriceBook2();
        customPriceBook.Name='Custom Pricebook';
        customPriceBook.IsActive=true;
        insert customPriceBook;
        
        // Query Standard and Custom Price Books
        Pricebook2 customPriceBookRec=[select Id from Pricebook2 where id=:customPriceBook.Id];
        stdPriceBookRecId = [SELECT Id, isstandard FROM Pricebook2 WHERE IsStandard=true];
        
        // Create Standard PriceBookEntry
        PriceBookEntry stdPriceBookEntry = new PriceBookEntry();
        stdPriceBookEntry.Product2Id=produto;
        stdPriceBookEntry.Pricebook2Id=stdPriceBookRecId[0].Id;
        stdPriceBookEntry.UnitPrice=2001;
        stdPriceBookEntry.IsActive=true;
        insert stdPriceBookEntry;
        
        // Create Custom PriceBookEntry
        PriceBookEntry customPriceBookEntry = new PriceBookEntry();     
        customPriceBookEntry.Product2Id=produto;
        customPriceBookEntry.Pricebook2Id=customPriceBookRec.Id;
        customPriceBookEntry.UnitPrice=5001;
        customPriceBookEntry.IsActive=true;
        insert customPriceBookEntry;
        
        // Create Opportunity
        Opportunity opp = new Opportunity();
        opp.Name = 'OPORTUNIDADE TESTE';
        opp.CloseDate= System.Today();
        opp.StageName='Prospecting';
        insert opp;
        
        // Add product and Pricebook to the particular opportunity using OpportunityLineItem 
        OpportunityLineItem oppLineItem = new OpportunityLineItem();
        oppLineItem.OpportunityId = opp.Id;
        oppLineItem.PricebookEntryId = customPriceBookEntry.Id;
        oppLineItem.UnitPrice = 7001;
        oppLineItem.Quantity = 4;
        insert oppLineItem;  
        
        
        if(!Catalog_Order__c.sObjectType.getDescribe().isAccessible()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        try{
            myOrder = [SELECT Items__c,Lines__c,Total_Cost__c,Account__c,Id,(SELECT Id,Product__c,Product_Short_Description__c,Product_Price__c,Product_Name__c,Price__c,Quantity__c,Subtotal__c,VF_Image__c FROM Catalog_Line_Items__r) FROM Catalog_Order__c WHERE Id =: orderId LIMIT 1];
        } catch (exception e) {System.debug(e.getMessage());}

        PageReference next = new PageReference('/apex/catalog_cart');
        next.setRedirect(false);
        // Directing to Cart
        return next;
    }
This is the code.

These are pieces of Catalog_Controller Class that I'm modifying to add the products of the Catalog Order to an Opportunity that's created when the catalog is submited. The error : 
' Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, This price definition already exists in this price book: [] '
appers.

Can someone help me?

Thanks.
Best Answer chosen by Filipe Baradelli
Kevin CrossKevin Cross
The problem is not the :produto, that part is correct.  "Beyond that, note that a SELECT usually brings back an instance of sObject, in this case Product2."  Moreover, because you did not LIMIT the results, you are getting a List<Product2>.  You cannot assign that to a Decimal.  Therefore, you would need to bring this back to another variable first (especially to check if a row actually exists before using column) or you can do this if you know with absolute certainty there always will be a value.

[SELECT Default_Price__c FROM Product2 WHERE Id = :produto LIMIT 1].Default_Price__c

However, this is safer:
 
customPriceBookEntry.UnitPrice=5001;
Product2 p = ​[SELECT Default_Price__c FROM Product2 WHERE Id = :produto LIMIT 1];
if (p != null) customPriceBookEntry.UnitPrice=p.Default_Price__c;

Hope that helps.

All Answers

Veenesh VikramVeenesh Vikram
This might help you:
https://success.salesforce.com/answers?id=90630000000gmJnAAI

Let me know if it does!

Veenesh
Kevin CrossKevin Cross
You just do INSERT statements in your code, so I am guessing the error is as it says in that the records already exist.  You may want to rewrite the code to pull the existing record first.  If the object is null, then create new. 
Filipe BaradelliFilipe Baradelli
So how could I make the part of this validation? I've tried to modify the UnityPrice, but it doesn't works. Can you give me an example more specific of this code? 

Thanks.
Kevin CrossKevin Cross
Okay, please give me specifics on what you are trying to do in the code and where the error is coming up (i.e., which line).  You have so many inserts, it is difficult to tell which one is wrong as they all potentially may need to be upserts or pull existing first.  For example, you create a custom pricebook which does not specify IsStandard true or false then you grab the first standard pricebook in the next line.  You then enter a price break for the standard pricebook.  

Two sets of questions come to mind:
- How do you stop the custom pricebook from coming up in that query?  i.e., is the default for IsStandard false or true?
- If there are more than one pricebook with standard flag, wouldn't this code always return the same id making line 50-51 a non-unique combo after this has been run before?  i.e., how do you know if the price book entry already exists or not?  What are the unique fields?
Filipe BaradelliFilipe Baradelli
One of the my problems was the concept of PriceBookEntry. I was creating, like you mentioned, a extra pricebook with no function. After I removed the standard pricebook it works. But how I mentioned, I'm unable to add the price of the submited product in the pricebook. The error is when I put a variable inside SELECT query: customPriceBookEntry.UnitPrice=[SELECT Default_Price__c FROM Product2 WHERE Id = produto]; // Line 60
The produto variable is the Id variable that contains the Id of the product (like in the line 58).
The error is that is found "produto" in the sentence, like this variable is not recognized inside the SELECT.

Thanks for the help.
Kevin CrossKevin Cross
I do not see that code on line 60, is it different than what you posted which uses literal values for price?
For the variable, it should be Id = :produto noting the colon binds the value as a variable versus a column or literal.  Beyond that, note that a SELECT usually brings back an instance of sObject, in this case Product2.
Filipe BaradelliFilipe Baradelli
I did'n post the code with the line 60 how I mentioned. I tried to use Id =:produto in the query, but it doesn't wor. The error: Illegal assignment from List<Product2> to Decimal. I've tried to pass the variable from Id to String, to use Id LIKE :produto. But it doesn't work too.
Kevin CrossKevin Cross
The problem is not the :produto, that part is correct.  "Beyond that, note that a SELECT usually brings back an instance of sObject, in this case Product2."  Moreover, because you did not LIMIT the results, you are getting a List<Product2>.  You cannot assign that to a Decimal.  Therefore, you would need to bring this back to another variable first (especially to check if a row actually exists before using column) or you can do this if you know with absolute certainty there always will be a value.

[SELECT Default_Price__c FROM Product2 WHERE Id = :produto LIMIT 1].Default_Price__c

However, this is safer:
 
customPriceBookEntry.UnitPrice=5001;
Product2 p = ​[SELECT Default_Price__c FROM Product2 WHERE Id = :produto LIMIT 1];
if (p != null) customPriceBookEntry.UnitPrice=p.Default_Price__c;

Hope that helps.
This was selected as the best answer
Filipe BaradelliFilipe Baradelli
Now I undertand the problem. I thought the only thing to change was the type of the variable.
You helped me so much. Thank you.
Kevin CrossKevin Cross
Good deal.  I am very glad that helped. 
Best regards and happy coding,
Kevin
Filipe BaradelliFilipe Baradelli
I'm with an other problem. Could you see it too? 
https://developer.salesforce.com/forums/ForumsMain?id=906F0000000kGk2IAE#!/feedtype=SINGLE_QUESTION_DETAIL&dc=Developer_Forums&criteria=OPENQUESTIONS&id=906F0000000kJWmIAM