How to get last level category of each product in magento - categories

I am trying to get last level category name with its product count for each product on listing page. explained as below-
Category
-> Sub-category 1
->Sub-sub-category 11 -> Product 1
->Sub-sub-category 12
-> Sub-sub-sub-category 13 ->Product 2
-> Sub-category 2
->Sub-sub-category 21
-> Sub-sub-sub-category 22 ->Product 3
->Sub-sub-category 23 -> Product 4
I want to get only categories "Sub-sub-category 11", "Sub-sub-sub-category 13", "Sub-sub-sub-category 22" and "Sub-sub-category 23" which are the last level categories of Products 1, Products 2, Products 3, Products 4.
I found below link get last level category name of a product in magento but it only gets third level category.

A little late, but this can be accomplished very simply, use this function when you want to get the category of the deepest level for a given product :
public function getProductLastLevelCategory(Mage_Catalog_Model_Product $product)
{
/** #var Mage_Catalog_Model_Resource_Category_Collection $categories */
$categories = $product->getCategoryCollection()
->addAttributeToSelect('*')
->addOrder('level');
return $categories->getFirstItem();
}
The base collection contains all the categories the given product belongs to, and the trick relies on sorting them by level (implicitly DESC).

Hi you can use the method getChildrenCount() for your category and check if it's equal to 0
if($category->getChildrenCount() == 0) {
// Do something
}

at my problem i try this code and success
<?php
$_helper = $this->helper('catalog/category');
$_storeCategories = $_helper->getStoreCategories();
?>
<?php
function getLastCategory($_categories)
{
$_helper = Mage::helper('catalog/category');
if (count($_categories) > 0) {
foreach ($_categories as $_category) {
$_category = Mage::getModel('catalog/category')->load($_category->getId());
$_subcategories = $_category->getChildrenCategories();
if (count($_subcategories) > 0) {
getLastCategory($_subcategories);
} else {
echo($_category->getName()."<br />" );
}
}
}
}
$lastCategory = getLastCategory($_storeCategories);
?>

Related

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

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.
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.

Statistic Calculations in laravel

I'm working on a project for golfstatistics. Right now I made it so far to enter and edit golfstatistics. I'm working with laravel 5 btw.
My database schema works like this:
Every round you play saves one entry in the round table with information like (date, playid, weather, courseid)
for every hole played an entry in the score table is made. There I have a reference to the roundid and information like (score, fairwayhit, greenhit, putts, penalties, ....)
No I want to create reports where I can filter for date and course etc.
What I did for now is. I created a Statistic class where I can pass the date, playerid, roundid, courseid in the construct. The construct will query all the rounds played, matching those filters.
Then, foreach statistic I made a public function ex. scoring_average, greenhit_percantage, putts_per_round, putts_per_greeninregulation etc. there are about 15 stats.
So my question is: is that right what I'm doing here? because I have about 15 functions just to calculate statistics.
Please give me some advice if you have a better solution.
Thank you
class Statistic {
/**
* The table associated with the model.
*
* #var string
*/
public $rounds = [];
public function __construct($user_id, $roundid = null, $start = "2000-01-01", $end = "2030-01-01", $courseid = 0){
$this->rounds = Round::where('user_id', '=', $user_id)->get();
}
public function score(){
if(count($this->rounds) > 0){
$avg = 0;
foreach($this->rounds as $round){
$scores = Score::where('round_id', '=', $round->id)->get(['score']);
foreach($scores as $score){
$avg += $score->score;
}
}
return $avg / count($this->rounds);
} else {
return "N/A";
}
}
public function fir(){
if(count($this->rounds) > 0){
$fairway = [];
foreach($this->rounds as $round){
$scores = Score::where('round_id', '=', $round->id)->get(['fir']);
foreach($scores as $score){
if($score->fir != 0){
array_push($fairway, $score->fir);
}
}
}
$hits = array_count_values($fairway);
//unset($hits[0]); //unsets par 3 with value 0
return self::percArray($hits);
return $perc;
} else {
return "N/A";
}
}

Is that possible to generate unique Id for list item across site collection?

Ex: I have 10 sites and every site have 5 list. From site 1 i have adding one item in listX now id will be like "1" and creating another item in listB of 4th sub site so now id will "2"... So it has to go on like this how to achieve this?
I need to update this with all list item added event ? also how to get the latest id?
I have tried this code with custom forms it's work's cool, but thinking this may give concurrency issue
public static void ID()
{
if ((field.InternalName.Equals("Field1")))
{
{
string template;
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.RootWeb)
{
template = web.Properties["eydtemplate"].ToString();
}
}
if ("eydadvisory" == template)
{
SPListItemCollection items = _currentList.Items;
if (_currentList.ItemCount == 0)
{
webControl.Field.DefaultValue = (1).ToString();
}
else
{
SPQuery query = new SPQuery();
query.RowLimit = 1;
query.Query = " <OrderBy><FieldRef Name='" + field.InternalName + "' Ascending='FALSE' /></OrderBy>";
webControl.Field.DefaultValue = (Convert.ToInt64(_currentList.GetItems(query).Cast<SPListItem>().FirstOrDefault()[field.InternalName]) + 1).ToString();
}
}
}

Conditional if a post in tt_news belongs to certain category

I made a custom marker for tt_news which shows the first image from the media field, OR the third if it belongs to certain category (lets say category with ID = 2). I dont know how to make that conditional. This is what I have so far:
10 = IMAGE
10.file{
width = 550
height = 350
import = uploads/pics/
import{
field = image
listNum = 0
#If also belongs to the category "Startseite", the listNum should be 2
listNum.stdWrap.override = TEXT
listNum.stdWrap.override{
value = 0
if{
#??????
}
}
}
}
You need to write custom condition as described in doc in userFunc section (bottom)
http://typo3.org/documentation/document-library/core-documentation/doc_core_tsref/4.3.2/view/1/4/
News and categories are connected with MM relation so you just to check if MM table contains this pair...
typo3conf/localconf.php:
function user_newsInCategory($catUid) {
$ttNewsGet = (t3lib_div::_GP('tx_ttnews'));
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'uid_foreign',
'tt_news_cat_mm',
'uid_foreign = ' . $catUid . ' AND uid_local=' . intval($ttNewsGet['tt_news'])
);
return ($GLOBALS['TYPO3_DB']->sql_num_rows($res) > 0) ? true : false;
}
somwhere in TS after your 10 = IMAGE { ... } block:
[userFunc = user_newsInCategory(2)]
10.file.import.listNum = 2
[end]
edit:
As you can see in the sample it works only if news is displayed (ie. if param &tx_ttnews[tt_news] exists in URL)
To check similar check per each list item you need to use custom marker via hook (as described in tt_news manual) by using extraItemMarkerProcessor - then you can use similar condition per each $row to display different images.