Magento Issues with category dropdown - magento

I need to display all the subcategories under root category name using . I am unable to find the root category details. Root category name is displaying as '/' How to overcome this issue?
Currently i am getting all the categories including root categories (/).
My code is as in below:
public function toOptionArray()
{
$categories = array();
$categoryCollection = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter(
'path',
array('neq' => '1')
);
foreach ($categoryCollection as $category) {
var_dump($category->getData());
echo '<br />';
$category = Mage::getModel('catalog/category')->load($category->getId());
$categories[$category->getId()] = $category->getUrlPath();
}
return $categories;
}
protected function _renderOptions(Varien_Object $row)
{
$categories = $this->getColumn()->getOptions();
$html = sprintf('<select class="category_select" name="mapping[%s]">', $row->getData('reference_id'));
$html .= '<option value=""></option>';
foreach ($categories as $id => $name) {
$html .= sprintf(
'<option value="%s"%s>%s</option>',
$this->escapeHtml($id),
$id == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
}
$html .= '</select>';
return $html;
}
I need to add into the category dropdown, which is subcategories displaying under root category name.
Can anyone help me please.
Thank You.

I fixed the issue using following:
protected function _renderOptions(Varien_Object $row)
{
$categories = $this->getColumn()->getOptions();
$parentIdArray = array();
foreach ($categories as $id => $name) {
$category = Mage::getModel('catalog/category')->load($id);
$parentId = $category->getParentId();
if($parentId == 1){
$parentIdArray[] = $id;
}
}
$html = sprintf('<select class="category_select" name="mapping[%s]">', $row->getData('reference_id'));
$html .= '<option value=""></option>';
foreach ($parentIdArray as $parentId) {
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$name = $parentCategory->getName();
$html .= sprintf(
'<optgroup label="'.$name.'">
<option value="%s"%s>%s</option>
</optgroup>',
$this->escapeHtml($parentId),
$parentId == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
$categories = Mage::getModel('catalog/category')->getCategories($parentId);
$subCategories = $this->get_categories($categories);
foreach ($subCategories as $id => $name) {
$html .= sprintf(
'<option style="padding-left: 10px;" value="%s"%s>%s</option>',
$this->escapeHtml($id),
$id == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
}
}
$html .= '</select>';
return $html;
}
public function get_categories($categories) {
$subCategories = array();
foreach($categories as $category) {
$subCategory = Mage::getModel('catalog/category')->load($category->getId());
$subCategories[$subCategory->getId()] = $subCategory->getUrlPath();
if($category->hasChildren()) {
$children = Mage::getModel('catalog/category')->getCategories($category->getId());
$childrenCategories = $this->get_categories($children);
foreach ($childrenCategories as $id => $name) {
$subCategories[$id] = $name;
}
}
}
return $subCategories;
}

Related

Magento 2 get filter list

I have Magento 2.4.3
I want to get filter list because i want to print price range list in to onother my section of site. (TopMenu.php)
I tried:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$stateFilter = $objectManager->create('\Magento\Catalog\Model\Layer\FilterList');
$selectedFilters = $stateFilter->getFilters();
foreach($selectedFilters as $filter){
$html .= $filter->getName();
$html .= $filter->getLabel();
}
But i get this error:
Cannot instantiate interface Magento\Catalog\Model\Layer\FilterableAttributeListInterface
How can I get what I want?
I found this solution:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$filterableAttributes = $objectManager->getInstance()->get(\Magento\Catalog\Model\Layer\Category\FilterableAttributeList::class);
$layerResolver = $objectManager->getInstance()->get(\Magento\Catalog\Model\Layer\Resolver::class);
$filterList = $objectManager->getInstance()->create(
\Magento\Catalog\Model\Layer\FilterList::class,
[
'filterableAttributes' => $filterableAttributes
]
);
$layer = $layerResolver->get();
$filters = $filterList->getFilters($layer);
$maxPrice = $layer->getProductCollection()->getMaxPrice();
$minPrice = $layer->getProductCollection()->getMinPrice();
$i = 0;
$filterAttrs = [];
$html .= '<ul>';
foreach($filters as $filter)
{
$values = [];
$attr_code = (string)$filter->getRequestVar();
$attr_label = (string)$filter->getName();
if(strtolower($filter->getName())=='price')
{
$html .= (string)$filter->getName();
$items = $filter->getItems();
foreach($items as $item)
{
$html .= '<li>';
$html .= '<a href="/onepage/?price='.$item->getValue().'">';
$html .=$item->getLabel();
$html .= '</a>';
$html .= '</li>';
}
}
}
$html .= '</ul>';

N-tier navigation in codeigniter

How to create top navigation in code-igniter?
In controller I have declare a function and call model
private function getNavigation(){
$this->load->model('xx');
$data['nav'] = $this->xx->prepareTree();
$this->load->view('index',$data);
}
And In model I have declare three functions
public function prepareTree(){
$this->db->select("`catalog_parent` as parent_id, `catalog_name` as menu_item, `catalog_id` as id, `catalog_template` as pager_id");
$this->db->from("catalog_category");
$this->db->where("`catalog_navigation` = '1'");
$this->q = $this->db->get();
$create = '';
if ($this->q->num_rows() > 0) {
$create = $this->prepareList($this->q->result_array());
}
if(!empty($create)){
return $this->category_tree($create);
} else {
return '';
}
}
private function prepareList(array $items, $pid = 0) {
$output = array();
foreach ($items as $item) {
if ((int) $item['parent_id'] == $pid) {
if ($children = $this->prepareList($items, $item['id'])) {
$item['children'] = $children;
}
$output[] = $item;
}
}
return $output;
}
private function category_tree($menu_items, $child = false){
$output = '';
if (count($menu_items)>0) {
$output .= ($child === false) ? '<ul id="main-menu" class="sm sm-blue">' : '<ul>' ;
foreach ($menu_items as $item) {
$output .= '<li>';
$output .= ''.$item['menu_item'].'';
if (isset($item['children']) && count($item['children'])) {
$output .= $this->category_tree($item['children'], true);
}
$output .= '</li>';
}
$output .= '</ul>';
}
return $output;
}
If some suggest an more easy way please suggest us.
Thanks

Like Query Is Not Working properly

In Code igniter Model I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
public function fetchdeal_products($id) {
$this->db->select('*');
$this->db->from('products');
$q = $this->db->like("name", $id);
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
//Controller
function ajaxdealcategorydata($id = NULL) {
$this->sma->checkPermissions('index');
$id = $this->input->get('id');
$subcategories = $this->pos_model->getdealcategory($id);
$scats = '';
foreach ($subcategories as $category) {
$scats .= "<button id=\"subcategory-" . $category->id . "\" type=\"button\" value='" . $category->id . "' class=\"btn-prni subcategory\" ><img src=\"assets/uploads/thumbs/" . ($category->image ? $category->image : 'no_image.png') . "\" style='width:" . $this->Settings->twidth . "px;height:" . $this->Settings->theight . "px;' class='img-rounded img-thumbnail' /><span>" . $category->name . "</span></button>";
}
$products = $this->ajaxdealproducts($id);
if (!($tcp = $this->pos_model->products_count($id))) {
$tcp = 0;
}
echo json_encode(array('products' => $products, 'subcategories' => $scats, 'tcp' => $tcp));
}
I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
function ajaxdealproducts() {
$this->sma->checkPermissions('index');
if ($this->input->get('id') ) {
$id = $this->input->get('id');
} else {
$category_id = $this->pos_settings->default_category;
}
if ($this->input->get('subcategory_id')) {
$subcategory_id = $this->input->get('subcategory_id');
} else {
$subcategory_id = NULL;
}
if ($this->input->get('per_page') == 'n') {
$page = 0;
} else {
$page = $this->input->get('per_page');
}
$this->load->library("pagination");
$config = array();
$config["base_url"] = base_url() . "pos/ajaxdealproducts";
$config["total_rows"] = $subcategory_id ? $this->pos_model- >products_count($id, $subcategory_id) : $this->pos_model->products_count($id);
$config["per_page"] = $this->pos_settings->pro_limit;
$config['prev_link'] = FALSE;
$config['next_link'] = FALSE;
$config['display_pages'] = FALSE;
$config['first_link'] = FALSE;
$config['last_link'] = FALSE;
$this->pagination->initialize($config);
$products = $this->pos_model->fetchdeal_products($id, $config["per_page"], $page);
$pro = 1;
$prods = '<div>';
foreach ($products as $product) {
$count = $product->id;
if ($count < 10) {
$count = "0" . ($count / 100) * 100;
}
if ($category_id < 10) {
$category_id = "0" . ($category_id / 100) * 100;
}
$prods .= "<button id=\"product-" . $category_id . $count . "\" type=\"button\" value='" . $product->code . "' title=\"" . $product->name . "\" class=\"btn-prni btn-" . $this->pos_settings->product_button_color . " product pos-tip\" data-container=\"body\"><img src=\"" . base_url() . "assets/uploads/thumbs/" . $product->image . "\" alt=\"" . $product->name . "\" style='width:" . $this->Settings->twidth . "px;height:" . $this->Settings->theight . "px;' class='img-rounded' /><span>" . character_limiter($product->name, 15) . "</span></button>";
$pro++;
}
$prods .= "</div>";
if ($this->input->get('per_page')) {
echo $prods;
} else {
return $prods;
}
}
The database LIKE function only creates a LIKE in the SQL statement. You'll still need to call the GET mothod afterwards; Like this;
$this->db->like('name', $id);
$q = $this->db->get();
You are using $this->db_like() incorrectly.
$this->db->like('title', 'match');
// Produces: WHERE title LIKE '%match%'
(from documentation)
In your case the usage would be
$this->db->like('name', 'rice')
More info
public function fetchdeal_products($id)
{
$query = $this->db->query("Select products.* From products Where (products.name Like '%$id%')");
$result = $query->result_array();
return $result;
}
you have to write it as bellow.
public function fetchdeal_products($id) {
$this->db->like("name", $id);
$q = $this->db->get('products');
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}

Remove Custom Option "None"

I'm new to Magento. We've created a custom option. But whenever we choose "radial" it always displays a "None" option that we need to remove. I from what I understand this is pulling in some code from Magento Core.
This is the HTML that I need to edit:
<dt><label>Add a Display Case:</label></dt>
<dd class="last">
<div class="input-box">
<ul id="options-7-list" class="options-list"><li><input type="radio" id="options_7" class="radio product-custom-option" name="options[7]" onclick="opConfig.reloadPrice()" value="" checked="checked" /><span class="label"><label for="options_7">None</label></span></li><li><input type="radio" class="radio product-custom-option" onclick="opConfig.reloadPrice()" name="options[7]" id="options_7_2" value="19" price="45" /><span class="label"><label for="options_7_2">Acrylic Cube <span class="price-notice">+<span class="price">$45.00</span></span></label></span></li><li><input type="radio" class="radio product-custom-option" onclick="opConfig.reloadPrice()" name="options[7]" id="options_7_3" value="20" price="75" /><span class="label"><label for="options_7_3">Lucite Case <span class="price-notice">+<span class="price">$75.00</span></span></label></span></li></ul> </div>
</dd>
This is where I think it outputs....
<?php
class OptionExtended_Block_Product_View_Js extends Mage_Catalog_Block_Product_View_Options
{
protected $config = array();
protected $thumbnailDirUrl = '';
protected $pickerImageDirUrl = '';
protected function _construct()
{
$children = array();
$sd = array();
$configValues = array();
$inPreConfigured = $this->getProduct()->hasPreconfiguredValues();
$storeId = Mage::app()->getStore()->getId();
$product_id = $this->getProduct()->getId();
$filter = Mage::getModel('core/email_template_filter');
$options = $this->getProduct()->getOptions();
foreach ($options as $option){
if (!is_null($option->getLayout())){
$id = (int) $option->getOptionId();
if (!is_null($option->getRowId()))
$option_id_by_row_id[$option->getTemplateId()][(int) $option->getRowId()] = $id;
$this->config[0][$id][0] = $option->getNote() != '' ? $filter->filter($option->getNote()) : '';
$this->config[0][$id][1] = $option->getLayout();
$this->config[0][$id][2] = (int) $option->getPopup();
if ($inPreConfigured){
$configValues[$id] = array();
if (is_null($option->getRowId())){
$configValue = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $id);
if (!is_null($configValue))
$configValues[$id] = (array) $configValue;
}
} else {
$sd[$option->getTemplateId()][$id] = explode(',', $option->getSelectedByDefault());
}
if (!is_null($option->getValues())){
foreach ($option->getValues() as $value) {
$valueId = (int) $value->getOptionTypeId();
$this->prepareImages($value->getImage());
$rowId = (int) $value->getRowId();
$valueId_by_row_id[$value->getTemplateId()][$rowId] = $valueId;
$children[$value->getTemplateId()][$valueId] = explode(',', $value->getChildren());
$this->config[1][$valueId][0] = $value->getImage();
$this->config[1][$valueId][1] = $value->getDescription() != '' ? $filter->filter($value->getDescription()) : '';
$this->config[1][$valueId][2] = array();
$this->config[1][$valueId][3] = array();
}
}
}
}
$options = Mage::getModel('optionextended/option')
->getCollection()
->joinNotes($storeId)
->addFieldToFilter('product_id', $product_id);
foreach ($options as $option){
$id = (int) $option->getOptionId();
if (!is_null($option->getRowId()))
$option_id_by_row_id['orig'][(int) $option->getRowId()] = $id;
$this->config[0][$id][0] = $option->getNote() != '' ? $filter->filter($option->getNote()) : '';
$this->config[0][$id][1] = $option->getLayout();
$this->config[0][$id][2] = (int) $option->getPopup();
if ($inPreConfigured){
$configValues[$id] = array();
if (is_null($option->getRowId())){
$configValue = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $id);
if (!is_null($configValue))
$configValues[$id] = (array) $configValue;
}
} else {
$sd['orig'][$id] = explode(',', $option->getSelectedByDefault());
}
}
$values = Mage::getModel('optionextended/value')
->getCollection()
->joinDescriptions($storeId)
->addFieldToFilter('product_id', $product_id);
foreach ($values as $value) {
$valueId = (int) $value->getOptionTypeId();
$this->prepareImages($value->getImage());
$rowId = (int) $value->getRowId();
$valueId_by_row_id['orig'][$rowId] = $valueId;
$children['orig'][$valueId] = explode(',', $value->getChildren());
$this->config[1][$valueId][0] = $value->getImage();
$this->config[1][$valueId][1] = $value->getDescription() != '' ? $filter->filter($value->getDescription()) : '';
$this->config[1][$valueId][2] = array();
$this->config[1][$valueId][3] = array();
}
if ($inPreConfigured){
foreach ($configValues as $optionId => $v){
$this->config[0][$optionId][3] = array();
foreach($v as $valueId)
$this->config[0][$optionId][3][] = (int) $valueId;
}
} else {
foreach ($sd as $templateId => $v){
foreach ($v as $optionId => $vv){
$this->config[0][$optionId][3] = array();
foreach($vv as $rowId)
if ($rowId != '')
$this->config[0][$optionId][3][] = $valueId_by_row_id[$templateId][(int)$rowId];
}
}
}
foreach ($children as $templateId => $v){
foreach ($v as $valueId => $vv){
foreach ($vv as $rowId){
if ($rowId != ''){
if (isset($option_id_by_row_id[$templateId][(int)$rowId]))
$this->config[1][$valueId][2][] = $option_id_by_row_id[$templateId][(int)$rowId];
else
$this->config[1][$valueId][3][] = $valueId_by_row_id[$templateId][(int)$rowId];
}
}
}
}
}
public function getConfig()
{
return Zend_Json::encode($this->config);
}
public function prepareImages($image)
{
if ($image){
$thumbnailUrl = $this->makeThumbnail($image);
$pickerImageUrl = $this->makePickerImage($image);
if ($this->thumbnailDirUrl == ''){
$this->thumbnailDirUrl = str_replace($image, '', $thumbnailUrl);
$this->pickerImageDirUrl = str_replace($image, '', $pickerImageUrl);
}
}
}
public function makeThumbnail($image)
{
$thumbnailUrl = $this->helper('catalog/image')
->init($this->getProduct(), 'thumbnail', $image)
->keepFrame(true)
// Uncomment the following line to set Thumbnail RGB Background Color:
// ->backgroundColor(array(246,246,246))
// Set Thumbnail Size:
->resize(100,100)
->__toString();
return $thumbnailUrl;
}
public function makePickerImage($image)
{
$pickerImageUrl = $this->helper('catalog/image')
->init($this->getProduct(), 'thumbnail', $image)
->keepFrame(false)
->resize(30,30)
->__toString();
return $pickerImageUrl;
}
public function getThumbnailDirUrl()
{
return $this->thumbnailDirUrl;
}
public function getPickerImageDirUrl()
{
return $this->pickerImageDirUrl;
}
public function getPlaceholderUrl()
{
return Mage::getDesign()->getSkinUrl($this->helper('catalog/image')->init($this->getProduct(), 'small_image')->getPlaceholder());
}
public function getProductBaseMediaUrl()
{
return Mage::getSingleton('catalog/product_media_config')->getBaseMediaUrl();
}
public function getInPreconfigured()
{
return $this->getProduct()->hasPreconfiguredValues() ? 'true' : 'false';
}
}
I think you are doing something wrong.
From this picture you can see that you can add your options which are then displayed in the frontend. Only these options will be displayed!
You do not need to make any changes in the Magento Core code to fix your problem.
If you still have problems please provide us with some screenshots and URL to your Magento web shop if possible.
Are you using an extension such as SWMS Option Image or similar to add extras like images to your custom options? This extension adds the None option.
You will need to go into the community folder and select your extension and edit the default.php and change "None" to "Standard" or something similar.
For SWMS Option image I changed:
/community/Swms/Optionimage/Block/Product/View/Options/Type/Select.php
<label for="options_'.$_option->getId().'">' . $this->__('Standard') . '</label>
I've got another solution. Edit the csv file. Mage_Catalog.csv. Add a row for None and add the word Standard to the next column.
Issue was resolved by modifying the this file:
app/code/local/Mage/Catalog/Block/Product/View/Options/Type/Select.php
modified lines 102-106
<?php
switch ($_option->getType()) {
case Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO:
$type = 'radio';
$class = 'radio';
if (!$_option->getIsRequire()) {
// $selectHtml .= '<li><input type="radio" id="options_'.$_option->getId().'" class="'.$class.' product-custom-option" name="options['.$_option->getId().']"' . ($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"') . ' value="" checked="checked" /><span class="label"><label for="options_'.$_option->getId().'">' . $this->__('None') . '</label></span></li>';
}
break;
case Mage_Catalog_Model_Product_Option::OPTION_TYPE_CHECKBOX:
$type = 'checkbox';
$class = 'checkbox';
$arraySign = '[]';
break;
}
?>
I have the same issue, also what i have found if the field is not required magento will generate "None" option. Fast solution but not recommended is hide the option by css.

How do I get bundle option selection SKU?

<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app("default");
$orderNumber = 260038;
$order = Mage::getModel('sales/order')->loadByIncrementId($orderNumber);
foreach ($order->getAllItems() as $item){
$productOptions = $item->getProductOptions();
echo $product_id = $item->product_id;
$_product=Mage::getModel('catalog/product')->load($product_id);
if ($_product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
if (isset($productOptions['bundle_options']))
{
foreach ($productOptions['bundle_options'] as $productOption)
{
echo $value = $productOption['value'][0]['title'];
echo ' || ';
echo $value = $productOption['value'][0]['qty'];
echo ' || ';
echo $value = $productOption['value'][0]['price'];
echo "<br>";
}
}
}
}
I am able to get the title, qty and the price of product, I also want to get the product SKU.
Bundle products can have options, options can have selections. This is 'two-tier' structure. If you just want to get all selections without options, you can use something like this:
$selections = $product->getTypeInstance(true)
->getSelectionsCollection($product->getTypeInstance(true)
->getOptionsIds($product), $product);
foreach($selections as $selection){
echo $selection->getSku();
}
But if you want get full information about options and their selections, use next way (based on your example):
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app("default");
$orderNumber = 260038;
$order = Mage::getModel('sales/order')->loadByIncrementId($orderNumber);
$store_id = $order->getStoreId();
foreach ($order->getAllItems() as $item){
$product = Mage::getModel('catalog/product')->setStoreId($store_id)->load($item->product_id);
$options = Mage::getModel('bundle/option')->getResourceCollection()
->setProductIdFilter($item->product_id)
->setPositionOrder();
$options->joinValues($store_id);
$selections = $product->getTypeInstance(true)
->getSelectionsCollection($product->getTypeInstance(true)
->getOptionsIds($product), $product);
foreach ($options->getItems() as $option) {
$option_id = $option->getId();
echo 'Option: ' . $option->getTitle() . ' [id: ' . $option_id . ']<br />';
foreach($selections as $selection){
if($option_id == $selection->getOptionId()){
$selection_id = $selection->getId();
$selection_name = $selection->getName();
$selection_qty = $selection->getSelectionQty();
$selection_sku = $selection->getSku();
$selection_product_id = $selection->getProductId();
$selection_weight = $selection->getWeight();
$selection_price = $selection->getPrice();
$data = 'Selection Name: ' . $selection_name;
$data .= ', SKU: ' . $selection_sku;
$data .= ', Qty: ' . $selection_qty;
$data .= ', ID: ' . $selection_id;
$data .= ', Product ID: ' . $selection_product_id;
$data .= ', Weight: ' . $selection_weight;
$data .= ', Price: ' . $selection_price;
echo $data . '<br />';
}
}
}
}
?>
Here we go,
To get product sku by selected option id:
$optionId = "selected option id";
$bundleTable = Mage::getSingleton('core/resource')->getTableName('catalog_product_bundle_selection');
$collection=Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect(array('name', 'price'));
$collection->getSelect()->joinLeft(array('bundleselect'=> $bundleTable),"entity_id = bundleselect.product_id","product_id");
$collection->getSelect()->where(" bundleselect.selection_id IN (".$optionId.") " );
$origPrice = '0';
foreach($collection as $prod) {
$origPrice += $prod->getSku();
}
echo $origSku;
Magento 2 get bundle options with their selections details.
Class BundleItemDetails
public function __construct(
\Magento\Catalog\Model\ProductRepository; $productRepository
)
{
$this->productRepository = $productRepository;
}
public function execute(){
$product = $this->productRepository->get("test-bundle-product");
$optionsCollection = $product->getTypeInstance(true)
->getOptionsCollection($product);
$optionDetails = [];
foreach ($optionsCollection as $option){
$selections = $product->getTypeInstance(true)
->getSelectionsCollection(
$option->getOptionId(),$product
);
//selection details by optionids
foreach ($selections as $selection) {
$optionDetails[$option->getOptionId()] = $selection->getSku();
}
}
}
}

Resources