Product count for anchored category in Magento2 - magento2

I am using the Megamenu third-party module in Magento 2 and I have customized this module due to some custom requirements.
I need to count product same as display in the admin category section for the anchored category and using the below code
$category->getProductCollection()->count()
this code is returning 0 products while this category is anchored and its subcategory has some product so it should count it subcategories product same as display in the admin section.
Please advise what will the code to get the products.
Thanks,

Please make sure you have successfully reindexed after setting the anchor via php bin/magento indexer/reindex.
Then try following code:
Include product collection factory to your construct
public function __construct(
// ...
\Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection,
// ...
) {
// ...
$this->productCollection = $productCollection;
// ...
}
And count the product collection filtered by your category.
$products = $this->productCollection->create();
$products->addCategoryFilter($category);
$products->count();

Related

Display rowcount beside each filter at grid

I am using AG grid enterprise to display my data. I have filters for each columns. I want to show the count of each filter element inside the filter drop-down itself. Please help. It's like if the filter shows that we have only us and Canada in the country column, I want to display the frequencies of us and canada inside parenthesis beside these filter elements
Update: added working sample
filterParams: { cellRenderer: "countryFilterRenderer"}
countryFilterRenderer(params) {
let count = this.rowData.filter(i=>i.country.name==params.value).length;
return `${params.value}(${count})`;
}
rowData:[{country:{name:..., code:...}];
rowData definition just for clarity.
For more info check doc with samples, and official demo with sources.
Update: added hot data sample
Once we need to have data - related from sorting or filtering we can use API methods: forEachNodeAfterFilter, forEachNodeAfterFilterAndSort, getDisplayedRowCount.
sportFilterRenderer(params){
let count;
if(this.gridApi.getDisplayedRowCount() != this.rowData.length){
count = 0;
this.gridApi.forEachNodeAfterFilter(node=>{
if(node.data.sport == params.value)
count++;
})
}
else{
count = this.rowData.filter(i=>i.sport==params.value).length;
}
return `${params.value}(${count})`;
}
https://plnkr.co/edit/bCI0SJ (check country and sport filters)
On sample plnkr count in sport filter would be recalculated every time once you will select\deselect anything from country filter
Update: hot changes handling via cellRenderer
So ag-grid team noticed about this issues and they have it on backlock - before this - there is no way to handle your requirement in the same way as we tried. Here you can find an issue (AG-2078)

Get an array with DomainObjects in a single Extbase ControllerAction argument

I'm creating an extbase extension to handle very simple product orders.
The model is:
Order --1:n--> OrderItem --1:1--> Product
To order a selection of products, the customer goes to checkout page and uses a Fluid based Order form. All selected products are available in the fluid template as {products}.
The OrderController->createAction processes new Orders by creating OrderItems from the given Products.
Writing the code I'd like to have would look like this:
class OrderController
{
public function create(Order $order, array $products)
{
foreach ($products as $product) {
$orderItem = new OrderItem()
->setProduct($product)
->setPrice($product->getPrice());
$order->addOrderItem($orderItem);
}
$this->orderRepository->add($order);
}
}
How to assign products to a Fluid form fields, in order to receive them as ControllerAction array argument?
How to trigger extbase to automagically provide an array of product objects to the ControllerAction?
I wonder if it is even possible to simplify the Controller createAction like shown below and assemble objects elsewhere:
public function create(Order $order) {
$this->orderRepository->add($order);
}
My suggestion for the fluid template would be:
// basic form with the order as main object
<f:form action="create" object="{order}">
// each order item with a product, using index to have no array with an empty index (Extbase does not like that)
<f:for each="{products}" key="index" as="product">
// Here you can set the product
<f:form.hidden prpoerty="orderItems.{index}.product" value="{product} />
</f:for>
</f:form>
This should be enough to use your single-line create action.
You can change the field type from select to whatever you want, but the __identity is mandatory to say Extbase which record it has to link.
When you want the orderItems to be new created, you need to remove the __identity field.

Laravel Eloquent Relationship 3 tables

I am a newbie to Laravel 5.2 and am working on a legacy system and am a bit confused regarding eloquent and would appreciate someone giving me the code.
There are 3 tables:
cards
categories
cards2cat
cards can be part many categories which are kept in cards2cat table.
The cards2cat table has the following structure
id (primary key)
image (card)
category
What I want to do is to have a method in the Cards model called something like getCardsWithCategores which returned the cards info plus the names of the categories from the category table.
The categories table has a key of id and a field category.
Thanks!
Go to your Card2Cats model and add this:
public function categories()
{
return $this->hasOne('App\Categories','id','category');
}
public function cards()
{
return $this->hasOne('App\Cards','id','image');
}
For the query you do this:
$cards = Card2Cat::with('categories','cards')->get();
foreach ($cards as $key => $value) {
echo $value->id.', Card:'.$value->cards->name.', Category:'.$value->categories->category.'<br>';
//$value->cards gives you all column of cards and you can do
//$value->cards->colName
// same goes for $value->categories
}
Make sure the spelling of your classes and table column names are correct before running the code :D

how to show list of CustomerId in dropdown list

i want to create Customer diary on the base of customerID that present in customer table.
In customerID field i want dropdown list having list of CustomerId's that are present in database
How can i do that ? can someone help me please
var _objAllCustomerIds = null;
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
_objAllCustomerIds = context.MyCustomers.Select(customer => customer.Id).ToList();
}
//where AdventureWorksEntities is your DBcontent containing all your entities
//MyCustomers is the entities representation of your customer table
if this is in your .aspx file
then in your .aspx.cs file (assuming you're using code behind) you'd get the list of customer IDs and then bind that list to this dropdown.
Does this answer from another question help?
How to bind the selected value of a DropDownList

Display Latest Magento products without setting date

I use Magento 1.7.0.2.
I'd like to show the 8 latest added products in my homepage, but without setting a date "from" and "to". I need it to be automatically.
Does anyone know of a solution?
Product IDs are incremental. By ordering them descending and limiting the collection to 8 you will have 8 last products.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order('entity_id desc')->limit(8);
/* just for testing
Mage::log($collection->getSelect()->assemble());
foreach ($collection as $product) {
Mage::log($product->getSku());
} */
With the collection you can do whatever you need, add visibility and status filter etc.
in order to do that you will need to use the date that the order was created. The key to display all products information as price, name, and etc. is to us ->addAttributeToSelect('*') Here is the script:
$store_id = Mage::app()->getStore()->getId();
$_products = Mage::getResourceModel('reports/product_collection')
->addStoreFilter($store_id)
->addAttributeToFilter('visibility', 4)
->addAttributeToFilter('status', 1)
->addAttributeToSelect('*')
->setVisibility(array(2,3,4))
->setOrder('created_at', 'desc')
->setPage(1, 9);