Search code examples
sugarcrmsugarbean

How can I get a subtotal by looping. Using SugarCRM CE 6.5.13


I am trying to get a total from the rows returned for the selected opportunity.

When a opportunity is selected each product they have purchased and its price is listed. I am trying to use the price for each purchased product to get a subtotal for all sales made with that opportunity.

Here is the code I have:

function total(&$focus, $event, $arguments)
{
    $total = 0;
    foreach ($this->bean->Product_Sales['sales_price_c'] as $entry) {
        $total += unformat_number($entry['sales_price_c']);
    }
    $this->bean->ss->assign('total_sales_c', format_number($total));
}

Example of how rows are returned:

[Product_Name_Field] [Product_Price_Field] [Sales_Person_Field] [Etc_Field]

Only qty(1) Product sold per returned row.

What am I doing wrong?
Thanks in advance.


Solution

  • Okay I figured it out!!!!

    This is File view.detail.php in Custom/Module/Opportunities/Views/

    <?php
    if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
    
    require_once('include/MVC/View/views/view.detail.php');
    
    class OpportunitiesViewDetail extends ViewDetail {
    
      function OpportunitiesViewDetail(){
      parent::ViewDetail();
      }
    
      function display() {
    $account = new Opportunity();//var = new ModuleName() in singular form
    $account->retrieve($_REQUEST['record']);//This grabs the record
    $contacts = $account->get_linked_beans('opportunities_op_ps_product_sales_1','Contact');
    //this uses the get_linked_beans(Param 1 is the linked var name found in the vardefs ,Param 2 is the name of the object you are creating. The name can be anything you like.)
    
    // loop through the created associations to get fields.
    foreach ( $contacts as $contact ) {
        $total += $contact->sales_price_c;//add the value of each sale to the variable
    }
    //populate the field you want with the value in the $total var
    echo "
           <script>
        var total = '$total';
           $(document).ready(function(){
        $('#total_sales_c').after(total); });
           </script>";
    
      parent::display();
      }
    }
    ?>
    

    Hopefully this will help others.