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

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.

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.

Related

Is there a way to use create() method on laravel eloquent model where data will call there corresponding set{field}Attribute method?

I'm trying to use create() method to create an object say 'user' from laravel-excel Import class say 'UserImport'. In the collection method, I grabbed the first row as the properties of the user and every cell in the subsequent row bears the data for the user on each row.
Using the create method will ensure that field that is not in my fillable will not be inserted as fields are dynamically gotten. I need the create method to use setGenderAttribute defined on the User model so as to transform 'male', 'm' in the excel gender column to constant User::GENDER_MALE and 'female', 'f' to constant User::GENDER_FEMALE.
public function collection(Collection $rows)
{
$keys = [];
// Extract spreadsheet head
foreach ($rows[0] as $key) {
$keys[] = Str::snake($key);
}
$j = 0;
foreach ($rows as $row) {
// Offset the head from the data set
if ($j == 0) {
$j++;
continue;
}
// get data from each row
$data = [];
$i = 0;
foreach ($keys as $key) {
$data[$key] = $row[$i];
$i++;
}
// Create user from each row
$user = User::create($data);
event(new MemberAdded($user));
}
}
It throws the following error integer value: 'male' for column users.gender
I've gotten to the answer. Laravel create method on eloquent actually call all the set{field}Attribute before actually doing database insertion. The problem was in one of the 'set' method. There was a bug in it and laravel fall back to the original field which was a string whose column was defined as integer in the database table schema.

Catalog Price Rule Magento 2

I have created a custom module in Magento 2. In which i want to show some banners, Countdown timer and extra details on product page, also label or text on category page. for this i extended the catalog sales rule module. Added some extra field according to my requirements. Now i want to show get all those products ids on which sale rule has applied with all other details like Top Banner, Countdown timer according to sale etc.
my Block Code is
<?php
namespace Custom\Sales\Block;
class Flash extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\CatalogRule\Model\ResourceModel\Rule\CollectionFactory $ruleFactory,
array $data = []
) {
$this->_ruleFactory = $ruleFactory;
parent::__construct($context, $data);
}
public function getCatalogeRuleId()
{
$catalogRuleCollection = $this->_ruleFactory->create()
->addFieldToFilter('is_active',1);
// return $catalogRuleCollection;
$resultProductIds = [];
foreach ($catalogRuleCollection as $catalogRule) {
$productIdsAccToRule = $catalogRule->getMatchingProductIds();
// echo json_encode($productIdsAccToRule); exit;
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
foreach ($productIdsAccToRule as $productId => $ruleProductArray) {
if (!empty($ruleProductArray[$websiteId])) {
$resultProductIds[$productId] = $catalogRule->getData();
}
}
return $resultProductIds;
}
}
}
Now when i print my array i get only one sale rule data , however i have created 3 different sales

Creating cumulative pdf of orders in magento

I want to create a pdf of first 300 orders in magento. I want a functionality in which i will get first 300 orders and print their images(each order has different image) in a pdf. So how can i implement this functionality in magento. Is there any extension for that?
Take a look at /app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
public function pdfinvoicesAction(){
$orderIds = $this->getRequest()->getPost('order_ids');
$flag = false;
if (!empty($orderIds)) {
foreach ($orderIds as $orderId) {
$invoices = Mage::getResourceModel('sales/order_invoice_collection')
->setOrderFilter($orderId)
->load();
if ($invoices->getSize() > 0) {
$flag = true;
if (!isset($pdf)){
$pdf = Mage::getModel('sales/order_pdf_invoice')->getPdf($invoices);
} else {
$pages = Mage::getModel('sales/order_pdf_invoice')->getPdf($invoices);
$pdf->pages = array_merge ($pdf->pages, $pages->pages);
}
}
}
if ($flag) {
return $this->_prepareDownloadResponse(
'invoice'.Mage::getSingleton('core/date')->date('Y-m-d_H-i-s').'.pdf', $pdf->render(),
'application/pdf'
);
} else {
$this->_getSession()->addError($this->__('There are no printable documents related to selected orders.'));
$this->_redirect('*/*/');
}
}
$this->_redirect('*/*/');
}
From the above function you could assign the first 300 order ids to $orderIds (or modify Mage::getResourceModel('sales/order_invoice_collection to get the first 300 records)
See magento orders list query
Changes :
public function pdfinvoicesAction(){
$orderIds = $this->getRequest()->getPost('order_ids');
To (something like)
public function pdfinvoices($orderIds){
$orderIds = (array) $orderIds; // first 300 record ids
Change line to save pdf to file
return $this->_prepareDownloadResponse(
'invoice'.Mage::getSingleton('core/date')->date('Y-m-d_H-i-s').'.pdf', $pdf->render(),
'application/pdf'
);
To
$pdf->render();
// use the order_id for the pdf name like
$pdf->save("{$orderId}.pdf");
see Error in generated pdf file using zend_pdf under Magento
You could also delete the $this->_redirect('//')

Retrieve specific column from database and display on screen using CodeIgniter

I have a database table called input_types with a various input types:
[id] [input_type_Name]
1 text
2 radio
3 checkbox
4 select
... ...
I want to retrieve the names from the table and put them in an array so that I can then use form_dropdown to show them to the user in a dropdown.
The problem with how I'm doing it now is that I create optiongroups.
How I do it now:
Model
function get_inputTypes() {
$this->db->select('input_type_name');
$query = $this->db->get('input_types');
if($query->num_rows() > 0) {
return $query->result_array();
}
else {
return false;
}
}
Controller
$results = $this->survey_model->get_inputTypes();
$data['inputTypes'] = $results;
View
<label for="inputType">Input type:</label>
<?php echo form_dropdown('inputType', $inputTypes); ?>
This however doesn't create the desired effect. My dropdown gets populated, but because I have a multidimensional array the dropdown has optgroups.
I just want to have my selected data in a simple array. Why is this so freaking hard in CodeIgniter and php in general.
C# is much easier :/
Solution
The solution is very simple, use a foreach to loop through the multidimensional array in the model:
foreach($query->result() as $input_type) {
$data[] = $input_type->input_type_name;
}
return $data;
What do you mean by "This however doesn't create the desired effect" ?
Make sure you pass the $data to your view:
$this->load->view('viewname', $data);
The solution is very simple, use a foreach to loop through the multidimensional array in the model:
foreach($query->result() as $input_type) {
$data[] = $input_type->input_type_name;
}
return $data;

How can I set the order of Zend Form Elements and avoid duplicates

In Zend Form, if two elements have the same order, then Zend will totally ignores the second element (instead of displaying it under the first). Take the following code as an example. Notice that the City and Zip Code elements have the same order of 4
$address = new Zend_Form_Element_Textarea('address');
$address->setLabel('Address')
->setAttrib('cols', 20)
->setAttrib('rows', 2)
->setOrder(3)
;
$city = new Zend_Form_Element_Text('city');
$city->setLabel('City')
->setOrder(4)
;
$postal = new Zend_Form_Element_Text('postal');
$postal->setLabel('Zip Code')
->setOrder(4);
When this form renders, the Zip Code element is nowhere to be found.
If I want to set elements like a buttons dynamically, but tell it to render at the end of the form, how would I do this and not run into the problem of having two elements with the same order?
public function addSubmitButton($label = "Submit", $order = null)
{
$form_name = $this->getName();
// Convert Label to a lowercase no spaces handle
$handle = strtolower(str_replace(" ","_",$label));
$submit = new Zend_Form_Element_Submit($handle);
$submit->setLabel($label)
->setAttrib('id', $form_name . "_" . $handle)
;
///////// Set the button order to be at the end of the form /////////
$submit->setOrder(??????);
$this->addElement($submit);
}
If you really need to use the setOrder() method, I'd work with order numbers 10, 20, 30, 40, ... This way it will be easy to add elements in between already set Elements.
Furthermore, in order to avoid using order-numbers twice, you could use an array, where you store all the numbers from 1 to X. Whenever you set an order number, you set it via a method called getOrderNumberFromArray() which returns the next higher or lower order number still available in the array and unsets this array element.
Alternatively, and maybe even better, you could do getOrder() on the element you want to have before the new element, then increment this order number by X and then loop through the existing form elements and check that the order number doesn't exist yet.
Or you could just use getOrder() on the Element you want to show before and after the new element and make sure you don't use the same order numbers for the new element.
Sorry to be late to the question. What I did was extend Zend_Form and override the _sort() method as follows:
/**
* Sort items according to their order
*
* #return void
*/
protected function _sort()
{
if ($this->_orderUpdated) {
$items = array();
$index = 0;
foreach ($this->_order as $key => $order) {
if (null === $order) {
if (null === ($order = $this->{$key}->getOrder())) {
while (array_search($index, $this->_order, true)) {
++$index;
}
$items[$index][]= $key;
++$index;
} else {
$items[$order][]= $key;
}
} else {
$items[$order][]= $key;
}
}
ksort($items);
$index = 0;
foreach($items as $i=>$item){
foreach($item as $subItem){
$newItems[$index++]=$subItem;
}
}
$items = array_flip($newItems);
asort($items);
$this->_order = $items;
$this->_orderUpdated = false;
}
}
This differs from the original sort method by putting the items in an array based off of their index and then doing a depth-first traversal to flatten the array.
Try this code:
$elements = array();
$elements[] = new Zend_Form_Element_Textarea('address');
......
$elements[] = new Zend_Form_Element_Text('city');
.......
$elements[] = new Zend_Form_Element_Submit($handle);
.....
$this->addElements($elements);
All you need to do is add them in the order you want them to show
what i would do is - use a temp array for that - in that keep the element names in desired order (don't mind the keys). Then use foreach like this:
foreach(array_values($tempArray) as $order => $name) {
$form->$name->setOrder($order+1);
}
Note the array_values - it will return the values as numbered array ;) Not sure if setOrder(0) works - that's why there is +1