How to add a class to the last element in a submenu - php

I have a multilevel menu. I need the li element to have a custom class in the first nesting level. In this menu, there will be other nestings inside the first level of nesting, but I only need the last li element to have a custom class in the first level. How can i do this?
Now I have a code that adds a class to the last li element at the top level.
function wpb_first_and_last_menu_class($items)
{
$items[count($items)]->classes[] = 'last';
return $items;
}
add_filter('wp_nav_menu_items', 'wpb_first_and_last_menu_class');

Related

Get Child categories magento

Trying to get child of a specific category which is active. Please help. I am having trouble doing it. I'm currently able to show them all but not specifically. Would appreciate any help.
$category = Mage::getModel('catalog/category')->load(2);
$category->getChildCategories();
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
here is code to load active category
/* Load category by id*/
$cat = Mage::getModel('catalog/category')->load($id);
/*Returns comma separated ids*/
$subcats = $cat->getChildren();
//Print out categories string
#print_r($subcats);
foreach(explode(',',$subcats) as $subCatid)
{
$_category = Mage::getModel('catalog/category')->load($subCatid);
if($_category->getIsActive())
{
$caturl = $_category->getURL();
$catname = $_category->getName();
if($_category->getImageUrl())
{
$catimg = $_category->getImageUrl();
}
echo '<h2><img src="'.$catimg.'" alt="" />'.$catname.'</h2>';
}
}
?>
hope this is sure help you.
As mentioned by mhaupt, it is faster to load a collection rather than each category in a loop. But, as far as I am concerned, there is no need to manually load the child categories. Basically this is what $category->getChildrenCategories() already does.
There is also a filter to get active categories only. Just call addIsActiveFilter() on the collection.
a.) Load active child categories via getChildren()
// 1. Get a list of all child category ids (e.g "12,23,11,42")
$subcategoryIds = $category->getChildren();
// 2. Create collection
$categoryCollection = Mage::getModel('catalog/category')->getCollection();
// 3. Add all attributes to select, otherwise you can not
// access things like $cat->getName() etc.
$categoryCollection->addAttributeToSelect('*');
// 4. Filter by ids
$categoryCollection->addIdFilter($subcategoryIds);
// 5. Add filter to collection to get active categories only
$categoryCollection->addIsActiveFilter();
b.) Load active child categories with getChildrenCategories()
// 1. Load collection
$categoryCollection= $category->getChildrenCategories();
// 2. Add filter to collection to get active categories only
$categoryCollection->addIsActiveFilter();
The collection will be loaded form the database as soon as it is accessed. If the collection is not loaded and $subcategories->count() is called only a "SELECT count(*)" will be fired against the database (in contrast to count($subcategories) which will force the collection to load itself).
Iterating the collection
foreach($categoryCollection as $category) {
echo $category->getName();
}
If you add more filters to the collection after accessing it, the collection will not load itself again automatically. To apply changes to the collection, just call $categoryCollection->load() to reload the collection from the database.
Those who are saying to use getAllChildren() instead of getChildren() are simply wrong.
Both methods return the exact same thing, with one difference, getAllChildren(true) will return an array instead of a comma delimited string. getAllChildren($bool asArray) defaults to false. My point being that either way you're going to have to use
Mage::getModel('catalog/category')->load($catId);
inside of a loop unless you use the function below.
private function fetchCatsById($onlyThese)
{
$cats = Mage::getModel('catalog/category')
->getCollection(true)
->addAttributeToSelect('*')
->addIdFilter($onlyThese)
->addAttributeToFilter('level','2')
->addIsActiveFilter();
return $cats;
}
$cats = $this->fetchCatsById($onlyThese);
The one answer liyakat wrote, should not be used in professional shops, because it raises a performance issue, because of the multiple n time loads of the category object, rather use the collection of categories for that, get all children
$cat->getAllChildren()
, then limit the category collection by the needed category ids like
$coll->addIdFilter($idFilter);
then you won't have to load n times against the database.
Please do keep in mind that loads within loops are one of the most often used bad code examples in any Magento projects and to avoid them!
Hello you will see below code
$category_model = Mage::getModel('catalog/category');
$_category = $category_model->load(13);
$all_child_categories = $category_model->getResource()->getAllChildren($_category);
print_r($all_child_categories);
If you want any number of subcategories of parent category than Click here http://magentoo.blogspot.com/2014/01/get-all-subcategories-of-parent-category-magento.html

Recursive in php

Im doing a project in php CodeIgniter which has a table where all attributes_values can be kept and it is designed such that it can have its child in same tbl. the database structure is
fld_id fld_value fld_attribute_id fld_parent_id
1 att-1 2 0
2 att-2 2 0
3 att-1_1 2 1
4 att-1_2 2 1
5 att-1_1_1 2 3
here above att-1 is the attribute value of any attribute and it has two child att-1_1 and att-1_2 with parent id 1. and att-1_1 has too its child att-1_1_1 with parent_id 3. fld_parent_id is the fld_id of the same table and denotes the child of its. Now i want to show this in tree structure like this
Level1 level2 level3 ..... level n
att-1
+------att-1_1
| +------att-1_1_1
+------att-1_2
att-2
and this tree structure can vary upto n level. the attribute values with parent id are on level one and i extracted the values from level one now i have to check the child of its and if it has further child and display its child as above. i used a helper and tired to make it recursive but it didnt happen. So how could i do it such: the code is below
foreach($attributes_values->result() as $attribute_values){
if($attribute_values->fld_parent_id==0 && $attribute_values->fld_attribute_id==$attribute->fld_id){
echo $attribute_values->fld_value.'<br/>';
$children = get_children_by_par_id($attribute_values->fld_id); //helper function
echo '<pre>';
print_r($children);
echo '</pre>';
}
}
and the helper code is below:
function get_children_by_par_id($id){ //parent id
$children = get_children($id);
if($children->num_rows()!=0){
foreach($children->result() as $child){
get_children_by_par_id($child->fld_id);
return $child;
}
}
}
function get_children($id){
$CI = get_instance();
$CI->db->where('fld_parent_id',$id);
return $CI->db->get('tbl_attribute_values');
}
please help me...............
The key of recursion is an "endless" call. This can be done with a function that calls it self.
So
function get_children($parent_id)
{
// database retrieve all stuff with the parent id.
$children = Array();
foreach($results as $result)
{
$result['children'] = get_children($result['id']);
$children[] = $result;
}
return $children;
}
Or use the SPL library built into PHP already PHP recursive iterator

Yii CListView Pagination customising

is there a way to customise the Yii CListView Pagination object to show
previous 1 of n pages next
rather then
previous 1,2,3 next ?
thanks
You cannot do this by simply passing parameters to the CLinkPager in order to modify its output. So, there is no more elegant method.
But you can very easily override the Pager class by extending CLinkPager and just change the createPageButtons()-Method in the following way:
Yii::import('web.widgets.pagers.CLinkPager');
class YourLinkPager extends CLinkPager{
/**
* Creates the page buttons.
* #return array a list of page buttons (in HTML code).
*/
protected function createPageButtons()
{
if(($pageCount=$this->getPageCount())<=1)
return array();
list($beginPage,$endPage)=$this->getPageRange();
$currentPage=$this->getCurrentPage(false); // currentPage is calculated in getPageRange()
$buttons=array();
// first page
$buttons[]=$this->createPageButton($this->firstPageLabel,0,self::CSS_FIRST_PAGE,$currentPage<=0,false);
// prev page
if(($page=$currentPage-1)<0)
$page=0;
$buttons[]=$this->createPageButton($this->prevPageLabel,$page,self::CSS_PREVIOUS_PAGE,$currentPage<=0,false);
/*
* !!! change has been made here !!!
*/
$buttons[]='<li>Page '.$this->getCurrentPage(false).' of '.$this->getPageCount().'</li>';
// next page
if(($page=$currentPage+1)>=$pageCount-1)
$page=$pageCount-1;
$buttons[]=$this->createPageButton($this->nextPageLabel,$page,self::CSS_NEXT_PAGE,$currentPage>=$pageCount-1,false);
// last page
$buttons[]=$this->createPageButton($this->lastPageLabel,$pageCount-1,self::CSS_LAST_PAGE,$currentPage>=$pageCount-1,false);
return $buttons;
}
}
http://www.yiiframework.com/forum/index.php/topic/5776-customise-the-clinkpager/

cakephp Tree behavior remove parent node except children

Is it possible to remove the parent node from a Tree using CakePHP Tree Behavior?. Let's say for example I have a node like this:
<Node A>
- child 1 node A
- child 2 node A
- child 3 node A
- <Node B> (which is also a child 4 of Node A)
- child 1 node B
- child 2 node B
Is it possible to get all the chidren of Node A (using the chidren() or any other function of the Tree behavior in cakePHP), but exclude a node which has children from the result (in our case Node B)?
Any idea please?
Thanks in advance
You can but you'll need to get your hands a bit dirty because I don't think the behavior allows anything like this.
The key is that all nodes that do not have children should have a left and right value that are in sequence. You'll need to whip up a query like this:
SELECT * FROM items WHERE left > (parent's left) AND right < (parent's right) AND right = left + 1 AND parent_id = (parent's ID)
That way we're asking that all returned values are children of our parent and that their left and right values are in sequence, which they won't be if a node has children.
Looking at specifications there is no specific method for this, so you must build your own function for that using children() and childCount(). Here's the code template (I don't use Cake PHP):
$children = <call TreeBehavior children() method with $id = id of Node A and $direct = true>;
$children_without_children = array();
foreach ($children as $child) {
if (<call TreeBehavior childCount() method with $id = $child->id and $direct = true> === 0) {
$children_without_children[] = $child;
}
}
Then $children_without_children should contain what you want.
you can use this code:
$this->Node->removeFromTree($id, true);
here is code from my cakephp 2.x project:
public function delete($id = null) {
$this->ProductCategory->id = $id;
if (!$this->ProductCategory->exists()) {
throw new NotFoundException(__('Invalid product category'));
}
$this->request->allowMethod('post', 'delete');
if ($this->ProductCategory->removeFromTree($id, TRUE)) {
$this->Session->setFlash(__('The product category has been deleted.'));
} else {
$this->Session->setFlash(__('The product category could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
Using this method (e.i. removeFromTree ()) will either delete or move a node but retain its sub-tree, which will be reparented one level higher. It offers more control than delete, which for a model using the tree behavior will remove the specified node and all of its children.

PHP Menu - How To Recursively Delete Parent and Child

I am working on a data driven menu system in PHP /MySQL. I can't figure out how to delete menu items without leaving some of them orphaned.
All top level menu items have a zero (0) parent id value indicating that they are top level. My gridview displays all menus, top level and sub menu items and it allows multiple selection for delete.
The problem is that if one of the items selected in the gridview for delete is a top level menu item, all sub menus under it will become orphaned.
What is the general logic I need to implement?
Simply delete the child items when you delete some item. If you only have a 2 levels of depth this shouldn't be too much of a problem. If you can have X levels, then you'll have to recursively delete every child element for every element you delete.
The below class will work with as many childs as you can create(infinit)... so considering your mysql tabel is structered as(id,parent,name), all you need is a function that gets all items from current level, loop through each item and call recursively the function again to get child items for current loop id, each time keeping the ids found in an array to delete later, below is the full code in which I accomplished it using a class, but it can be done with a global array and function also.
//full class below comprising of 2 methods(functions)
class menu_manager{
//this is the function called with id, to initiate the recursive function below
private function remove_menu_item($id){
$ids_to_delete ="";
//Zero global arrays for more than one call for this function get child menus id first in a an array
$this->child_items_ids = array(0 => $id);
$this->incrementby_one=0;
//call recursive function with $id provided
$this->get_array_of_child_ids($id);
//then createw ids for mysql IN Statment, foreach will create - 1,10,25,65,32,45,
foreach($this->child_items_ids as $k=>$v ) $ids_to_delete.=$v.",";
//Then we wrap it in around "(" and ")" and remove last coma to provide - (1,10,25,65,32,45)
$ids_to_delete="(".substr($ids_to_delete, 0, -1).")";
//then we Delete all id in one query only
$remove = $this->db->query("DELETE FROM menu WHERE id IN $ids_to_delete ");
if(!$remove) return false;
else return true;
}
/*this is the function that will be called as many times as a child is found,
this function is called inside of itself in the query loop*/
private function get_array_of_child_ids($id){
$query = $this->db->query("SELECT id,label,parent FROM menu WHERE parent='".$id."' ");
if($query){
if($query->num_rows > 0) { // if found any items
while($list = $query->fetch_assoc()){ // we loop through each item
//increments array index by 1
$this->incrementby_one += 1;
//place current id in the array
$this->child_items_ids[$this->incrementby_one] = intval($list["id"]);
//and we call this function again for the current id
$this->get_array_of_child_ids($list["id"]);
} // while closing
} // second if closing
} //first if closing
} // recursive function closing
} // class closing
//to call the class you need:
$delete_items = new menu_manager;
$delete_items->remove_menu_item($id); //$id is the id for the item to be removed

Categories