I am creating a menu dynamically based on the categories registered on the dataBase, What I need is:
When someone click in the link, this option should have the css class 'active', showing in with page the user is and even the pages are created dynamically.
I have no idea how to do this because I am php student and I couldn't find this information in google for "Dynamically menus" Thank you very much.
<nav class="menu">
<ul class="list">
<li class="line"><a id="item" href="index.php">Home</a></li>
<?php
$categories = $db->select("select * from tbl_category");
if($categories){
while ($result = $categories->fetch_assoc()){
echo <<<HTML
<li id="line" ><a class="item" href="categories.php?category=$result[id]">$result[name]</a></li>
HTML;
}
}
?>
</ul>
<nav>
First of all, you're looping through that while loop and adding the id of "line" to each and every <li> element. I suggest you create unique id's for each list item. I don't necessary advocate using the code the way you have it, just as an example, here's your code edited to do just that:
if($categories){
$i = 1;
while ($result = $categories->fetch_assoc()){
$i++;
echo <<<HTML
<li id="line$i" ><a class="item" href="categories.php?category=$result[id]">$result[name]</a></li>
HTML;
}
}
Then when someone clicks on your link, just use jQuery with something like this:
$(".item").click(function() {
$(this).parent('li').addClass('active');
});
Try something like that:
<nav class="menu">
<ul class="list">
<li class="line"><a id="item" href="index.php">Home</a></li>
<?php
$current_page = isset($_GET['category']) ? $_GET['category']: -1;
$categories = $db->select("select * from tbl_category");
if($categories){
while ($result = $categories->fetch_assoc()){
echo '<li id="line">';
if($result['category'] === $current_page) {
// If we're currently in the active page then add the active class to the <a>
echo '<a class="item active" href="categories.php?category='. $result[id] .'">';
} else {
echo '<a class="item" href="categories.php?category='. $result[id] .'">';
}
echo $result['name'];
echo '</a>';
echo '</li>';
}
}
?>
</ul>
<nav>
Thank you all for help, based on your code, I solved doing this:
menu.php:
<nav class="menu" id="menu">
<ul id="list" class="list">
<li id="line" class="<?php if($presentPage == '0')echo 'active';?>"><a id="item" class="item" href="index.php">Home</a></li>
<?php
function checked($pp, $id){
if($pp == $id){
$status = 'active';
return $status;
}
}
$query = "select * from tbl_category";
$category = $db->select($query);
if($category){
while ($result = $category->fetch_assoc()){
echo "
<li id='line' class='".checked($presentPage, $result['id'])."'><a id='item' class='item' href='categories.php?category=".$result['id']."'>".$result['name']."</a></li>
";//end echo
}//end while
}//end if
?>
</ul>
</nav>
In my index.php:
<?php $presentPage = 0;?>
<?php require_once 'header.php';?>
<?php require_once 'menu.php';?>
and in my categories.php:
<?php
if (!isset($_GET['category']) || $_GET['category'] == NULL) {
$presentPage = 0;
}else{
$presentPage = intval($_GET['category']);//just to make sure that the variable is a number
}
?>
<?php require_once 'header.php';?>
<?php require_once 'menu.php';?>
///...my code...
and in my CSS of course:
.active{
background: linear-gradient(#821e82, #be5abe);
}
Thats is working perfectly for me, Thank for all help.
Related
I'd like to add condition to my code so that after click on label it link me to other page. Now this code link to other article on the website. So I guess what should I add to get from my label to other page.
Thank you for answers!
My code is below:
<ul class="nav nav-tabs aboutUsTabs nav-justified" role="tablist">
<?php foreach ($this->items as $key=>$item ){
if($item['children']){ ?>
<li role="presentation" class="<?php if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){ echo 'active'; } ?>"><?php echo $item['menu']->title;?></li>
<?php }else{ ?>
<li role="presentation" class="<?php if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){ echo 'active'; } ?>"><?php echo $item['menu']->title;?></li>
<?php } ?>
<?php } ?>
</ul>
All this start/stop of PHP code hurts my eyes! Anyways, linking to other pages is done with tags. Not quite sure I understand your question, but you could (if you mean labels for form elements) do something like this;
<label for=""> Something Meaningful </label>
I'm sorry, but I took the liberty to clean up your code a little. Hopefully this will make it more readable;
<ul class="nav nav-tabs aboutUsTabs nav-justified" role="tablist">
<?php
foreach ($this->items as $key=>$item ){
$active = NULL;
if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){
$active = 'active';
}
$menu = NULL;
if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){
$menu = 'active';
}
if($item['children']){
echo'<li role="presentation" class="'.$active.'">
'.$item['menu']->title.'
</li>';
}else{
echo'<li role="presentation" class="'.$menu.'">
'.$item['menu']->title.'
</li>';
}
}
?>
</ul>
For your comment question, if you know what item needs a different value, it could be the title f.ex. then you can check against that value and change the output of your element. Maybe something like;
if($item['children']){
if($item['title'] == 'Unique Identifier for your element') {
// In here you could manipulate the output of that one item you want to exclude/change
} else {
// Your normal output
echo'<li role="presentation" class="'.$active.'">
'.$item['menu']->title.'
</li>';
}else{ ... }
And even better would be to perform the check beforehand, so maybe something like;
$link = '#about-us-page-'.$item['menu']->id;
if($item['title'] == "That identifier") {
$link = 'somethingElse';
}
and then change the value of your href tag to;
'.$item['menu']->title.'
Say I have
$output = '';
and I want to include the following code within the double ''.
<ul class="nav megamenu">
<?php if (!$logged) { ?>
<li class="home">
<a href="?route=common/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
<?php if ($logged) { ?>
<li class="home">
<a href="?route=subscribers/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
How could I go about doing this?
You could use output buffering, something like this:
<?php ob_start();?>
<ul class="nav megamenu">
<?php if (!$logged) { ?>
<li class="home">
<a href="?route=common/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
<?php if ($logged) { ?>
<li class="home">
<a href="?route=subscribers/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
<?php
$output = ob_get_contents();
ob_end_clean();
?>
See In Action
Using this method of starting a buffer and then assigning the result to a variable is very handy and is used in some MVC frameworks.
Simple example:
<?php
/* Assign an array of values that will be passed
* to the loader then extracted into local variables */
$data['logged']=true;
$output = loadContentView('top_nav', $data);
function loadContentView($view, $data=null){
$path = SITE_ROOT.'/path/to/views/'.$view.'.php';
if (file_exists($path) === false){
return('<span style="color:red">Content view not found: '.$path.'</span>');
}
/* Extract $data passed to this function */
if($data != null){
extract($data);
}
ob_start();
require($path);
$return = ob_get_contents();
ob_end_clean();
return $return;
}
?>
I just changed my code to this instead... much easier
Thanks everyone for all the help!
<?php
if (!$this->customer->isLogged()) {
$output = '<ul class="nav megamenu"><li class="home"><span class="menu-title">Home</span></li>';
}else{
$output = '<ul class="nav megamenu"><li class="home"><span class="menu-title">Home</span></li>';
}
?>
I'm trying to create a Mega Menu using PHP and I'm having a problem getting the structure to output correctly. I've hard-coded the Mega Menu to test everything and it works fine, but obviously I need PHP to create it for me.
I have an example with the Mega Menu hard-coded so everyone can see what I'm trying to create:
http://www.libertyeaglearms.com/dev
Or here's the code:
DESIRED OUTPUT:
<div id="wrapper">
<ul class="mega-menu">
<li class="mega-menu-drop">
Firearms
<div class="mega-menu-content">
<div class="column">
<h4>Rifles</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
<div class="column">
<h4>Handguns</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
<div class="column">
<h4>Shotguns</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
</div>
</li>
<li class="mega-menu-drop">
Archery
<div class="mega-menu-content">
<div class="column">
<h4>Bows</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
<div class="column">
<h4>Arrows</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
CURRENT OUTPUT: (very messed up. be warned, lol)
<div id="wrapper">
<ul class="mega-menu">
<li class="mega-menu-drop">
archery
<div class="mega-menu-content">
<div class="column">
<h4>compound</h4>
<ul>
<h4>bows</h4>
<ul>
</div>
</li>
<li class="mega-menu-drop">
firearms
<div class="mega-menu-content">
<div class="column">
<h4>rifle ammunition</h4>
<ul>
<h4>ammunition</h4>
<ul>
</div>
</li>
</ul>
</div>
HERE MY PHP:
$json = json_decode($category->buildDepartments(NULL),true);
function buildDepartments($array,$parent)
{
$html = '';
foreach($array as $category)
{
if($category['parent'] == $parent)
{
if($category['parent'] == NULL)
{
$html .= '<li class="mega-menu-drop">' . "\n\t\t\t\t";
$html .= ''.$category['category_name'].'' . "\n\t\t\t\t";
$html .= '<div class="mega-menu-content">' . "\n\t\t\t\t\t";
$html .= '<div class="column">' . "\n\t\t\t\t\t\t";
$html .= buildDepartments($array,$category['category_id']);
$html .= '</div>' . "\n\t\t\t";
$html .= '</li>' . "\n\t\t\t";
}
else
{
$html .= buildDepartments($array,$category['category_id']);
$html .= '<h4>'.$category['category_name'].'</h4>' . "\n\t\t\t\t\t\t";
$html .= '<ul>' . "\n\t\t\t\t";
}
}
}
return $html;
}
print(buildDepartments($json,NULL));
HERE'S MY DATABSE:
EDIT AFTER BOUNTY
Building off what icktoofay suggested, I cannot seem to figure out the foreach() loops. The problem I'm getting is I get the department name inside the mega menu when I should see category and sub categories. I think the problem is I need to perform a loop with a specific parent id in order to get all the children, but I'm not really sure if that's the problem. Here's the code:
<div id="wrapper">
<ul class="mega-menu">
<?php $json = json_decode($category->buildDepartments(NULL)); ?>
<?php foreach($json as $category): ?>
<li class="mega-menu-drop">
<?php if($category->parent === NULL){echo $category->category_name;} ?>
<div class="mega-menu-content">
<?php foreach($category as $subcategory): ?>
<div class="column">
<?php if($category->category_id === $category->parent){echo '<h4>' . $category->category_name . '</h4>';}?>
<ul>
<?php foreach($category as $subcategory)
{
echo '<li>' . $category->category_name . '</li>';
}
?>
</ul>
</div>
<?php endforeach; ?>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
Since it's a fixed depth and the format for each level is different, recursion may not be appropriate. Additionally, putting everything in strings is inelegant. Instead, you may want to try weaving the HTML and loops together like this:
<div id="wrapper">
<ul class="mega-menu">
<?php foreach($categories as $category): ?>
<li class="mega-menu-drop">
<?php echo $category->name; ?>
<div class="mega-menu-content">
<?php foreach($category->subcategories as $subcategory): ?>
<!-- and so on -->
<?php endforeach; ?>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
The code I've used here assumes you've already got it from a sort-of-flat-array to a tree-like structure. For example, if we've got a Category class:
class Category {
public $id;
public $parentID;
public $name;
public $parent;
public $subcategories;
public function __construct($id, $parentID, $name) {
$this->id = $id;
$this->parentID = $parentID;
$this->name = $name;
$this->parent = null; // will be filled in later
$this->subcategories = array(); // will be filled in later
}
}
And an array of associative arrays like you might get from a database call (which we'll call $flatCategories), we can build a bunch of not-yet-connected Category instances like this:
$categories = array();
foreach($flatCategories as $flatCategory) {
$categories[$flatCategory['id']] =
new Category($flatCategory['category_id'],
$flatCategory['parent'],
$flatCategory['category_name']);
}
Then we can connect them all up into a hierarchal structure:
foreach($categories as $category) {
if($category->parentID !== null) {
$category->parent = $categories[$category->parentID];
$category->parent->subcategories[] = $category;
}
}
Now they're all linked up and we only care about keeping references to the roots:
$roots = array();
// This could, of course, be merged into the last loop,
// but I didn't for clarity.
foreach($categories as $category) {
if($category->parentID === null) {
$roots[] = $category;
}
}
Now $roots contains all the root categories, and it's fairly simple to traverse. In my example at the top, I was assuming $categories had something similar to $roots in it.
you need to generate something called a super tree and use a recursive function to echo out each branch, this will allow for an unlimited depth tree, but, it also allows for an unknown depth tree.
First, SQL:
SELECT category_id, parent, category_name
Second, use SQL to create tree:
$super_tree = array();
while(($row = mysql_fetch_assoc($res)) != NULL) {
$parent = $row['parent'] == NULL ? 0 : $row['parent']; //clean up the parent
$super_tree[$parent][$row['category_id']] = $row['category_name'];
}
Third, echo out the tree
function echo_branch($tree_branch, $tree_root) {
echo("<ul>\n"); //open up our list for this branch
foreach($tree_branch as $id => $name) { //foreach leaf on the branch
echo("<li>"); //create a list item
echo("{$name}"); //echo out our link
if(!empty($tree_root[$id])) { //if our branch has any sub branches, echo those now
echo_branch($tree_root[$id], $tree_root); //pass the new branch, plus the root
}
echo("</li>\n"); //close off this item
}
echo("</ul>\n"); //close off this list
}
echo_branch($super_tree[0], $super_tree); //echo out unlimited depth tree structure
this allows for unlimited depth in your tree structure and allows for simple code to be able to create the structure within the code base.
All that you would need to do now is add in your extra's such as classes and your extra html elements in the correct places.
if you are looking to track the current depth of the tree to be able to echo different things depending on the depth, you can make the following alterations
In the function definition
function echo_branch($tree_branch, $tree_root, $depth) {
In the recursive call within the if
echo_branch($tree_root[$id], $tree_root, $depth++);
In the initial call
echo_branch($super_tree[0], $super_tree, 0);
Look like you are using the variable
$category
when you should use
$subcategory
Try this:
<div id="wrapper">
<ul class="mega-menu">
<?php $json = json_decode($category->buildDepartments(NULL)); ?>
<?php foreach($json as $category): ?>
<li class="mega-menu-drop">
<?php if($category->parent === NULL){echo $category->category_name;} ?>
<div class="mega-menu-content">
<?php foreach($category as $subcategory): ?>
<div class="column">
<?php if($subcategory->category_id === $category->parent){echo '<h4>' . $category->category_name . '</h4>';}?>
<ul>
<?php foreach($subcategory as $subcategory2)
{
echo '<li>' . $subcategory2->category_name . '</li>';
}
?>
</ul>
</div>
<?php endforeach; ?>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="menu clearfix">
<ul>
<li>start</li>
<li>rating</li>
<li>upload</li>
</ul>
Was a while since i used php. Is there any smart way to do a foreach in php and render this menu + an "active" class to the clicked link. So if the active page is "rating", the html would render:
<div class="menu clearfix">
<ul>
<li>start</li>
<li>rating</li>
<li>upload</li>
</ul>
Thanks
Assuming the $_GET value of p would be rating (or any other link in the menu for that matter), one could do something like this:
<?php
echo "<div class=\"menu clearfix\">";
echo "<ul>";
$links = array('rating', 'upload', 'about');
foreach ($links as $link) {
$active = "";
if (!empty($_GET['p']) && $link == $_GET['p']){
$active = 'class="active"';
}
echo "<li><a href=\"./?p=$link\" $active>$link</a></li>";
}
echo "</ul></div>"
?>
As far as I understand you want to know which li is active after request.
If it is - you have to get $_GET parameter smth like $_GET['p'].
And do rendering, smth like:
foreach($ul as $li)
{
if ($_GET['p'] == $li->code)
echo 'class="active"';
}
For example:
<div class="menu clearfix">
<ul>
<?php foreach($ul as $li): ?>
<li><a href="<?php echo $li->url;?>" <?php echo $_GET['p']==$li->get ? class="active" : ''?>><?php echo $li->name;?></a></li>
<?php endforeach; ?>
</ul>
<ul class="sub-nav" >
<?php
$full_name = $_SERVER['PHP_SELF'];
$name_array = explode('/',$full_name);
$count = count($name_array);
$page_name = $name_array[$count-1];
?>
<li><a class="<?php echo ($page_name=='where-to-buy.php')?'active':'';?>" href="where-to-buy.php">WHERE TO BUY</a></li>
<li><a class="<?php echo ($page_name=='about.php')?'active':'';?>" href="about.php">ABOUT US</a></li>
<li><a class="<?php echo ($page_name=='contact.php')?'active':'';?>" href="contact.php">CONTACT US</a></li>
Please follow below URL to live demo...
https://webdesignerhut.com/active-class-navigation-menu/
Im trying to validate my output data from a php site that Im calling with
<?php include_once('nav.inc.php');
?>
The thing is when Im using this code
<ul>
<li>GÄSTBOK</li>
<li>OM MIG</li>
<li>PORTFOLIO</li>
<li>CURRICULUM VITAE</li>
</ul>
I wont get any errors, But when Im trying with the other code I get alot of errors. Is there any way to write the code so It validates ?
This is the code thas bugging me
<?php
$index = 'menu';
$gb = 'menu';
$portfolio = 'menu';
$cv = 'menu';
$menuLinkid=basename($_SERVER['PHP_SELF'],'.php');
if($menuLinkid=='index'){
$index = 'myButtons';
}else if($menuLinkid=='gb'){
$gb ='myButtons';
}else if($menuLinkid=='portfolio'){
$portfolio ='myButtons';
}else if($menuLinkid=='cv'){
$cv ='myButtons';
}
?>
<div id="fronticon">
<a href="contact.php"><img src="images/em.png" alt="Email" title="Email"/>
</a>
</div>
<ul>
<li><a class="<?php echo $index; ?> "href="index.php">OM MIG</a></li>
<li><a class="<?php echo $gb; ?> "href="gb.php">GÄSTBOK</a></li>
<li><a class="<?php echo $portfolio;?> " href="portfolio.php">PORTFOLIO</a></li>
<li><a class="<?php echo $cv; ?> "href="cv.php">CURRICULUM VITAE</a></li>
</ul>
Thanks
You need spaces between the ?> " and the href. You can't have them next to each other with no space.
Should be:
<li><a class="<?php echo $index; ?> " href="index.php">OM MIG</a></li>