0

I have a custom console component I'm using to add Product Line Items to an Opportunity. I've been modifying a Salesforce Labs app that was built to Create Orders and add products to them. I wand to assign the selectedPricebook to be the Pricebook from the Opportunity (line 13) rather than the first Pricebook in the list of Pricebooks (line 11).

    public with sharing class CreateOLI_Ext {

    private final Opportunity opp;
    public string selectedPricebook {get;set;}
    public List<PricebookEntry> pricebookEntries {get; private set;}

    public CreateOLI_Ext(ApexPages.StandardController stdController) {
        this.opp = (Opportunity)stdController.getRecord();
        List<Pricebook2> pricebooks = [SELECT Id, Name from Pricebook2 where IsActive = true];
        if (pricebooks.size() > 0) {
            selectedPricebook = pricebooks[0].Id;
        }
        //selectedPricebook = opp.Pricebook2Id;
        loadPricebookEntries();
    }

    public List<SelectOption> getPricebookOptions() {
        List<SelectOption> options = new List<SelectOption>();
        List<Pricebook2> pricebooks = [SELECT Id, Name from Pricebook2 where IsActive = true];
        for(Pricebook2 pricebook : pricebooks) {
          options.add(new SelectOption(pricebook.Id,pricebook.Name));
        }
        return options;
    }

    public void loadPricebookEntries() {
        pricebookEntries = [SELECT Id, Name, Product2.Name, Product2.ProductCode,
                            UnitPrice  
                           FROM PricebookEntry
                           WHERE Pricebook2Id =: selectedPricebook and IsActive = true];
    }
}

Here is the Visualforce page:

<apex:page showHeader="false" sidebar="false" standardStylesheets="false" standardController="Opportunity"
           extensions="CreateOLI_Ext" docType="html-5.0" applyHtmlTag="false" applyBodyTag="false">
<html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
    <head>
        <apex:stylesheet value="{!URLFOR($Resource.SLDS0121_Order, 'assets/styles/salesforce-lightning-design-system-vf.css')}" />
    </head>
    <body>
    <apex:remoteObjects >
        <apex:remoteObjectModel name="Product2" fields="Id,Name,ProductCode">
        </apex:remoteObjectModel>
        <apex:remoteObjectModel name="OpportunityLineItem" fields="OpportunityId,UnitPrice,PricebookEntryId,Quantity">
        </apex:remoteObjectModel>
    </apex:remoteObjects>
    <style>
        body {
            margin: 0;
        }
        .quantity {
        float: left;
        width: 50px;
        height: 30px;
        margin-right: 10px;
        }
        .list-group-item {
        margin-top: 10px;
        border-radius: 4px;
        background: #eee;

        }
        .order-panel {
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 10px 15px;
        background: #eee;
        }
        .order-item {
        padding: 0;
        border:0;
        }
    </style>
    <div class="slds">   
        <div class="slds-page-header" role="banner" style="padding: 15px;background: #E2E7ED;">

            <div class="slds-grid">
                <div class="slds-col slds-has-flexi-truncate">
                    <h3 class="slds-text-heading--medium slds-truncate" title="Order Form"
                        style="font-size: 18px;">Product Selection</h3> </div>
                <div class="slds-col slds-no-flex slds-align-bottom">
                    <p style="color: #8992A1;" id="header-info">
                        No item added
                    </p>
                </div>
            </div>
        </div>
        <apex:form style="background: #F8F9FB;">
            <div style="padding:20px 20px 0px 20px;">
            <div id="entry-list">
                <div class="slds-form--stacked">
                    <div class="slds-form-element">
                        <div class="slds-form-element__control slds-input-has-icon slds-input-has-icon--right">
                            <svg aria-hidden="true" class="slds-input__icon slds-icon-text-default">
                                <use xlink:href="{!URLFOR($Resource.SLDS0121_Order,'/assets/icons/utility-sprite/svg/symbols.svg#search')}"></use>
                            </svg>
                            <input type="text" class="slds-input search" id="search" placeholder="Enter product name or product code" />

                        </div>
                    </div>
                    <div class="slds-form-element">
                        <apex:selectList styleClass="slds-select " id="pricebook" style="height:34px;"
                                         value="{!selectedPricebook}" multiselect="false" size="1">
                            <apex:actionSupport event="onchange" action="{!loadPricebookEntries}" rerender="entryList"
                                                oncomplete="makeOptionList()"/>
                            <!--<apex:selectOption itemLabel="Select a pricebook"
                                               itemValue=""></apex:selectOption>-->
                            <apex:selectOptions value="{!PricebookOptions}" />
                        </apex:selectList>
                    </div>
                </div>
                <p class="slds-text-heading--label slds-truncate" style="margin-top: 20px;margin-bottom:10px;"
                   title="Products">Products</p>
                <apex:outputPanel id="entryList">

                    <ul class="list slds-list--vertical slds-has-cards--space">
                        <apex:repeat value="{!pricebookEntries}" var="entry">
                            <li class="slds-list__item" style="background: white;">
                                <div class="slds-tile slds-tile--board slds-media">

                                    <div class="slds-media__figure">
                                        <div class="slds-icon slds-icon-standard-product">
                                            <img src="{!URLFOR($Resource.SLDS0121_Order,'/assets/icons/standard/product_60.png')}"
                                                         width="40"/>
                                        </div>
                                    </div>
                                    <div class="slds-media__body">
                                        <div class="slds-grid">
                                            <div  class="slds-col slds-size--3-of-4">
                                                <div class="slds-grid slds-grid--align-spread slds-has-flexi-truncate">
                                                    <p class="slds-tile__title slds-truncate"><a class="name"><apex:outputField value="{!entry.Product2.Name}"/></a></p>
                                                </div>
                                                <div class="slds-tile__detail slds-text-body--small">
                                                    <p class="slds-truncate code">
                                                        <apex:outputField value="{!entry.Product2.ProductCode}" />
                                                    </p>
                                                    <p class="slds-truncate">
                                                        <apex:outputField value="{!entry.UnitPrice}" />
                                                    </p>
                                                </div>
                                            </div>
                                            <div  class="slds-col slds-size--1-of-4">
                                                <button type="button" class="slds-button slds-button--neutral" style="float:right;width:40px;padding:0;" 
                                                        onclick="addToOrder('{!JSINHTMLENCODE(entry.Id)}','{!JSINHTMLENCODE(entry.Product2.Name)}','{!entry.UnitPrice}');">
                                                    <img src="{!URLFOR($Resource.SLDS0121_Order,'/assets/icons/utility/add_60.png')}"
                                                         width="20"/>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </li>
                        </apex:repeat>
                    </ul>
                </apex:outputPanel>

            </div>

                <p class="slds-text-heading--label slds-truncate" style="margin-top: 20px;margin-bottom:10px;"
                   title="Products">Your Products</p>
                <p class="slds-text-body--small" id="order-placeholder">
                    No product added yet...
                </p>
            </div>
            <div  id="order-table" style="display:none;">
            <table class="slds-table slds-table--bordered">
                <thead>
                    <tr class="slds-text-heading--label">
                        <th scope="col">
                            <span class="slds-truncate">QTY</span>
                        </th>
                        <th scope="col">
                            <span class="slds-truncate">Product</span>
                        </th>
                        <th scope="col">
                            <span class="slds-truncate"></span>
                        </th>
                    </tr>
                </thead>
                <tbody id="order-list">
                    <!-- sample entry
                    <tr class="slds-hint-parent">
                        <td data-label="QTY">
                            <span class="slds-truncate">
                                <input type="number" class="slds-input" style="width:50px;"/>
                            </span>
                        </td>
                        <td data-label="Product name">
                            <a class="slds-truncate">Product name</a>
                        </td>
                        <td class="slds-row-action">
                            <div style="float:right;">
                                <svg aria-hidden="true" class="slds-button__icon slds-button__icon--hint slds-button__icon--medium">
                                    <use xlink:href="{!URLFOR($Resource.SLDS0121_Order,'/assets/icons/utility-sprite/svg/symbols.svg#close')}"></use>
                                </svg>
                                <span class="slds-assistive-text">Remove</span>
                            </div>
                        </td>
                    </tr>-->
                </tbody>
            </table>

            </div>
            <div style="padding: 20px; min-height: 80px;">
                <div style="float:right;">
                    <button type="button" onclick="RefreshButton()" class="slds-button slds-button--brand " id="refresh" disabled="false">
                        Refresh
                    </button>                    
                    <button type="button" onclick="clearOrder()" class="slds-button slds-button--neutral ">
                        Clear
                    </button>
                    <button type="button" onclick="createOrder()" class="slds-button slds-button--brand" id="submit" disabled="disabled">
                        Add
                    </button>

                </div>
            </div>

        </apex:form>
    </div>
        <apex:includeScript value="{!URLFOR($Resource.FastOrderJs, 'jquery.min.js')}"/>
        <apex:includeScript value="{!URLFOR($Resource.FastOrderJs, 'list.min.js')}"/>
    <script src="/support/console/35.0/integration.js" type="text/javascript"></script>
    <script>
        var DisableFlag = 'true';
        //sforce.console.openPrimaryTab(null, '/' + orderId, true);
        var orders = [];
    var options = {
        valueNames: [ 'name', 'code'],
        page: 5,
    };
    var entryList = new List('entry-list', options);
    function makeOptionList() {
        entryList = new List('entry-list', options);
        RefreshButtonDisplay(DisableFlag);

    }
    function updateHeaderInfo() {
        if (orders.length === 0) {
            $('#header-info').html('No item added'); 
        } else if (orders.length === 1) {
            $('#header-info').html('<a>1 item added</a>'); 
        } else {
            $('#header-info').html('<a>' + orders.length + ' items added</a>'); 
        }
    }
    function addToOrder(entryId, entryName, entryPrice) {
        $('#order-table').css('display','block');
        $('#order-placeholder').css('display','none');
        $('#submit').prop('disabled',false);
        var index = findOrderItem(entryId);
        if (index > -1) {
            ++orders[index].Quantity;
            $('#' + entryId).val(orders[index].Quantity);
        } else {
            orders.push({ Id: entryId, Price: entryPrice, Quantity: 1});
            $('#order-list').append('<tr class="slds-hint-parent"><td data-label="QTY">' +
                                   '<span class="slds-truncate">' + 
                                    '<input type="number" class="slds-input quantity" style="width:60px;border:none;"' + 
                                    ' value="1" min="1" onchange="changeQuantity(this, \'' +
                                    entryId + '\')" id="'+ entryId + '"/> ' +
                                   '</span></td><td data-label="Product Name"><a class="slds-truncate">' +
                                    entryName + '</a></td><td class="slds-row-action"><div style="float:right;cursor:pointer;" onclick="removeEntry(this, \'' 
                                    + entryId + '\')">' +
                                    '<svg aria-hidden="true" class="slds-button__icon slds-button__icon--hint slds-button__icon--medium">' +
                                    '<use xlink:href="' + 
                                    "{!URLFOR($Resource.SLDS0121_Order,'/assets/icons/utility-sprite/svg/symbols.svg#close')}" + 
                                    '"></use>' +
                                    '</svg></div></td></tr>'
                                   );
        }
        updateHeaderInfo();
    }
    function changeQuantity(quantity, entryId) {
        var index = findOrderItem(entryId);
        orders[index].Quantity = $(quantity).val();
    }
    function removeEntry(quantity, entryId) {
        var index = findOrderItem(entryId);
        if (index > -1) {
            orders.splice(index, 1);
            $(quantity).parent().parent().remove();
        }
        if (orders.length === 0) {
            $('#order-placeholder').css('display','block');
            $('#order-table').css('display','none');
            $('#submit').prop('disabled',true);
        }
        updateHeaderInfo();
    }
    function findOrderItem(entryId) {
        for(var i = 0; i < orders.length; ++i) {
            if (orders[i].Id === entryId) {
                return i;
            }
        }
        return -1;
    }
    function clearOrder() {
        orders = [];
        $('#order-list').html('');
        $('#order-placeholder').css('display','block');
        $('#order-table').css('display','none');
        $('#submit').prop('disabled',true);
        $('#search').val('');
        updateHeaderInfo();
    }
    function createOrder() {
        //var details = { 
        //    AccountId: '{!Opportunity.Account.Id}',
        //    Status: 'Draft',
        //    EffectiveDate: new Date(),
        //    Pricebook2Id: $('select[id*="pricebook"]').val(),
        //};
        //var order = new SObjectModel.Order();
        //order.create(details, function(err) {
        //    if(err) { 
        //        console.log(err);
        //        alert(err.message);
        //    }
        //    else {
        //        console.log('order created: ' + order.get('Id')); // Id is set when create completes
        //        createOrderItems(order.get('{!Opportunity.Id}'));
        //    }
        //});

        createOrderItems('{!Opportunity.Id}');
        clearOrder();
        //RefreshPrimaryTab();
        DisableFlag = "false";
        RefreshButtonDisplay(DisableFlag);
    }

    function createOrderItems(orderId) {
        for (var i = 0; i < orders.length; ++i) {
            var details = {
                OpportunityId: orderId,
                UnitPrice: orders[i].Price,
                PricebookEntryId: orders[i].Id,
                Quantity: orders[i].Quantity,
            };
            var orderItem = new SObjectModel.OpportunityLineItem();
            orderItem.create(details, function(err) {
                if(err) { 
                    console.log(err);
                    alert(err.message);
                }
                else {
                    // this is the OLI
                    console.log(orderItem.log());     // Dump OLI to log
                    console.log(orderItem.get('Id')); // Id is set when create completes
                }
            });
        }
        openSubtab('/' + orderId);
    }

    function openSubtab(subtabUrl)
    {
        // Use the results primary tab id and open a new subtab
        //var openSubtab = function(result)
        //{
        //    sforce.console.openSubtab(result.id, subtabUrl, true);    
        //};
        //sforce.console.getEnclosingPrimaryTabId(openSubtab);

    }

    function RefreshButtonDisplay(dFlag)
    {
        if(dFlag  == 'true') {
            $('#refresh').prop('disabled',true);
        }
        else {
            $('#refresh').prop('disabled',false);
        }
    }

    function RefreshButton()
        {
            RefreshPrimaryTab();
            DisableFlag = "true";
            RefreshButtonDisplay(DisableFlag);
        }

    function RefreshPrimaryTab() 
        {
            sforce.console.getFocusedPrimaryTabId(showTabId);
        }

        var showTabId = function showTabId(result) 
        {
            var tabId = result.id;
            //alert('Primary Tab IDs: primaryTabId ' + tabId );
            sforce.console.refreshPrimaryTabById(tabId , true, refreshSuccess);
        };

        var refreshSuccess = function refreshSuccess(result) 
        {
            //Report whether refreshing the primary tab was successful
            if (result.success == true) 
            {
                //alert('Primary tab refreshed successfully');
                RefreshButtonDisplay(DisableFlag);
            } 
            else 
            {
                //alert('Primary did not refresh');
            }
        };

    </script>

    </body>
</html>
</apex:page>
0
    if (pricebooks.size() > 0) {
        selectedPricebook = pricebooks[0].Id;
    }

Would be changed to:

    selectedPricebook = opp.Pricebook2Id;

Make sure you include {!Opportunity.Pricebook2Id} somewhere in your page so that the SOQL query built for your page will contain the data for your controller. Something like this:

<apex:outputText rendered="false">{!Opportunity.Pricebook2Id}</apex:outputText>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.