Skip to content

Instantly share code, notes, and snippets.

@jedateach
Last active December 16, 2015 11:59
Show Gist options
  • Save jedateach/5431637 to your computer and use it in GitHub Desktop.
Save jedateach/5431637 to your computer and use it in GitHub Desktop.
getting an OrderItemList, instaed of HasManyList
<?php
//in Order class
public function getComponents($componentName, $filter = "", $sort = "", $join = "", $limit = null) {
$components = parent::getComponents($componentName, $filter = "", $sort = "", $join = "", $limit = null);
if($componentName === "Items" && get_class($components) !== "UnsavedRelationList"){
$query = $components->dataQuery();
$components = new OrderItemList("OrderItem", "OrderID");
if($this->model) $components->setDataModel($this->model);
$components->setDataQuery($query);
$components = $components->forForeignID($this->ID);
}
return $components;
}
<?php
/**
* Additional functions for Item lists.
*/
class OrderItemList extends HasManyList{
function Quantity(){
return $this->Sum('Quantity');
}
function Plural(){
return $this->Quantity() > 1;
}
/**
* Sums up all of desired field for items, and multiply by quantity.
* Optionally sum product field instead.
*
* @param $field - field to sum
* @param boolean $onproduct - sum from product or not
* @return number - sum total of field
*/
public function Sum($field, $onproduct = false){
$total = 0;
foreach($this->getIterator() as $item){
$quantity = ($field == "Quantity") ? 1 : $item->Quantity;
if(!$onproduct){
$total += $item->$field * $quantity;
}elseif($product = $item->Product()){
$total += $product->$field * $quantity;
}
}
return $total;
}
}
@NicoHaase
Copy link

Line 6 of Order.php will do wrong stuff: you will overwrite any given value for $filter, $sorr, $join or $limit there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment