Recursive dropdown menu not showing correctly on Bootstrap Codeigniter - php

I have issues displaying a dropdown menu generated by a recursive function using a database. The parents are shown correctly below the items, but not as nav items, but just as a basic list.
Here's the image with how it actually looks:
And here's how it SHOULD look:
Some relevant code:
Model:
<?php
class New_menu_model extends CI_Model {
function get_domains() {
$result = $this->db->get ( 'domenii' );
return $result->result_array();
}
}
function recursive($parent, $result) {
$has_children = false;
foreach ( $result as $key => $value ) {
if ($value ['parent'] == $parent) {
if ($has_children === false && $parent) {
$has_children = true;
echo '<ul>' . "\n" ;
}
echo '<li>' . "\n";
echo '' . $value ['nume_domeniu'] . '' . " \n";
echo "\n";
recursive ( $key + 1, $result );
echo "</li>\n";
}
}
if ($has_children === true && $parent)
echo "</ul>\n";
}
?>
View:
<li class="dropdown"><?php echo recursive(0, $menu); ?></li>
Thanks!

It should be something like:
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
Dropdown <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<?php echo recursive(0, $menu); ?>
</ul>
</li>
...and check echo '<ul>' . "\n" ; , it could be echo '<ul class="dropdown-menu">' . "\n" ; so the code should be:
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
Dropdown <span class="caret"></span>
</a>
<?php echo recursive(0, $menu); ?>
</li>

Related

How to set first menu active in mega menu?

I am trying to create a hoverable mega menu, all works fine except the active one.
I checked in source codes and active class is added, but it doesn't show up the content until mouseenter on it.
see image please :
And this is when I go on it with mouse, it show up with no problem.
I gues I need to set main (FINANCE is main menu in pic) menu active, but dont know how to pass it to submenu.
Here is my full code :
$stmt_menu = $pdo->prepare("SELECT * FROM categories WHERE parentId = ? LIMIT 5");
$stmt_menu->execute([0]);
if ($stmt_menu->rowCount() > 0) {
$query = $stmt_menu->fetchAll();
foreach ($query as $row) {
if ($row['cat_type'] == 'mega') {
?>
<li class="dropdown megamenu-fw mega-li-<?php echo $row['catId']; ?>">
<?php echo $row['catName']; ?><span class="caret"></span>
<ul class="dropdown-menu megamenu-content dropdown-top" role="menu" aria-expanded="true" data-mega-ul="<?php echo $row['catId']; ?>">
<li>
<?php
$stmt_menu = $pdo->prepare("SELECT * FROM categories WHERE parentId = ? LIMIT 5");
$stmt_menu->execute([$row['catId']]);
if ($stmt_menu->rowCount() > 0) {
$subquery = $stmt_menu->fetchAll();
?>
<div class="sub-menu-left">
<ul class="nav-sub-categories">
<?php
$i = 0;
foreach ($subquery as $subq) {
$actives = '';
if($i == 0){
$actives = ' active';
}
?>
<li data-category-filter="<?php echo $subq['cat_seo_url']; ?>-<?php echo $subq['catId']; ?>" class="li-sub-category<?php echo $actives; ?>"><?php echo $subq['catName']; ?></li>
<?php
$i++;
}
?>
</ul>
</div>
<div class="sub-menu-right">
<?php
$i = 0;
foreach ($subquery as $subcats) {
$actives = '';
if($i == 0){
$actives = ' active';
}
?>
<div class="sub-menu-inner filter-<?php echo $subcats['cat_seo_url']; ?>-<?php echo $subcats['catId']; ?><?php echo $actives; ?>">
<div class="row row-menu-right">
<div class="col-sm-3 menu-post-item">
<div class="post-item-image">
<a href="is-allowance-instantly-strangers-applauded">
<img src="assets/img/img_bg_md.png" data-src="uploads/images/202203/image_380x226_624239afd7295.jpg" alt="Is allowance instantly strangers applauded" class="lazyload img-responsive img-post" width="1" height="1"/>
</a>
</div>
<h3 class="title"><?php echo $subcats['cat_seo_url']; ?> Is allowance instantly strangers applauded</h3>
<p class="post-meta">
admin
<span>Mar 28, 2022</span>
<span><i class="icon-comment"></i>2</span>
<span class="m-r-0"><i class="icon-eye"></i>894</span>
</p>
</div>
</div>
</div>
<?php
$i++;
}
?>
</div>
<?php
}
?>
</li>
</ul>
</li>
<?php
} elseif ($row['cat_type'] == 'dropdown') {
echo ' <li class="nav-item"><a class="nav-link" href="' . $row["cat_seo_url"] . '">test</a></li>';
} else {
echo ' <li class="nav-item"><a class="nav-link" href="' . $row["cat_seo_url"] . '">' . $row["catName"] . '</a></li>';
}
}
}

Adding categories & subcategories to a blog

Ok, I have done lots of research and looked at lots of stackoverflow questions but none have answered my question.
I'm building a simple blog and am at the moment i'm trying to build a simple categories/subcategories system but have hit an obstacle in making the subcategories load under their parent. If you know an easier method to the one i am doing below please let me know.
Here is how my db is structured:
id || name || parent_id || status
------------------------------------------
1 || category1 || NULL || 1
2 || subcategory1 || 1 || 1
Then i have my model code:
public function getCategories()
{
$results = $this->db->select('msi_items_categories','status = 1 AND parent_id = NULL');
if( !is_array($results[0]) ) {
$new_results = array();
array_push($new_results, $results);
return $new_results;
} else {
return $results;
}
}
public function getSubCategories($parent)
{
$bind = [':parent' => $parent];
$results = $this->db->select('msi_items_categories','status = 1 AND parent_id = :parent');
if( !is_array($results[0]) ) {
$new_results = array();
array_push($new_results, $results);
return $new_results;
} else {
return $results;
}
}
This is my controller code:
public function error()
{
$getSettings = $this->setting->getAll();
$getCategories = $this->setting->getCategories();
$getSubCategories = $this->setting->getSubCategories();
if(is_array($getCategories[0]) ) {
$isCategory = true;
} else {
$isCategory = false;
}
if(is_array($getSubCategories[0]) ) {
$isSubCategory = true;
} else {
$isSubCategory = false;
}
$data = [
'settings' => $getSettings,
'mainCategory' => $getCategories,
'subCategory' => $getSubCategories,
'isCategory' => $isCategory
'isSubCategory' => $isSubCategory
];
$this->view('index', $data);
}
Then I have my templatecode which is where im trying to do the foreach and the top category works fine but i just can't figure out how i do the subcategories. Before i started using the MVC model, i would simply just put the class inside the main category foreach and then put the id but now its all done in the controller so i cannot figure out how i do subcategories using the MVC model.
<?php foreach($data['mainCategory'] as $category) : ?>
<li class="dropdown">
<a class="dropdown-toggle nav-link dropdown-toggle pl-0" data-toggle="dropdown" aria-expanded="false" href="#"><?php echo $category['name']; ?></a>
<div class="dropdown-menu" role="menu">
<a class="dropdown-item" role="presentation" href="#"><i class="text-black-50 fas fa-box"></i> All <?php echo $category['name']; ?></a>
<div class="dropdown-divider" role="presentation"></div>
<?php foreach($data['subCategory'] as $scategory) : ?>
<a class="dropdown-item" role="presentation" href="#"><i class="text-black-50 <?php echo $scategory['icon']; ?>"></i> <?php echo $scategory['name']; ?></a>
<?php endforeach; ?>
</div>
</li>
<?php endforeach; ?>
Thanks very much!
$query = 'SELECT id, parent_id, name, icon FROM categories ORDER BY name';
$result = mysqli_query($conn, $query) OR trigger_error($query.'<br>'.mysqli_error($conn),E_USER_ERROR);
$refs = Array();
$categories = Array();
while($row = mysqli_fetch_assoc($result))
{
$thisref = &$refs[$row['id']];
$thisref['name'] = $row['name'];
$thisref['icon'] = $row['icon'];
if($row['parent_id']) $refs[$row['parent_id']]['children'][$row['id']] = &$thisref;
else $categories[$row['id']] = &$thisref;
}
echo '<ul class="nav navbar-nav mr-auto">';
foreach($categories as $category)
{
echo '<li class="dropdown">';
echo is_array($category['children'])
? '<a class="dropdown-toggle nav-link dropdown-toggle pl-0" data-toggle="dropdown" aria-expanded="false" href="#">'.$category['name'].'</a>'.sub($category['children'])
: $category['name'];
echo '</li>';
}
echo '</ul>';
function sub(&$subCat)
{
echo '<div class="dropdown-menu" role="menu">
<a class="dropdown-item hide-me" role="presentation" href="#"><i class="fas fa-fire mr-2"></i> Most Popular </a>
<div class="dropdown-divider hide-me" role="presentation"></div>';
foreach($subCat as $id => $subcategory)
{
echo '<a class="dropdown-item" role="presentation" href="'.FULL_ROOT.'/category/'.$id.'/"><i class="'.$subcategory['icon'].' mr-2"></i>'.$subcategory['name'].'</a>';
}
echo '</div>';
}

Adding an active class according to URL

I have a php/mysql driven menu. I am trying to add an active class to the menu item whenever the URI reflects that menu item (basically, when I am on that page) but every example I find is with a menu that is not populated through an array or repeater like mine.
How can manipulate the active class you see below so that it shows only when I am on that page?
Here is my menu
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['id'] == 2){
// below is the active class that is now being populated accross all items equally
echo '<li class="nav-item dropdown active">';
echo '<a href="#" class="nav-link dropdown-toggle animated fadeIn animation-delay-7" data-toggle="dropdown" data-hover="dropdown" role="button" aria-haspopup="true" aria-expanded="false" data-name="services">';
echo $row["pagename"];
echo '<i class="zmdi zmdi-chevron-down"></i>';
echo '</a>';
// create a new list
echo '<ul class="dropdown-menu">';
// loop second/submenu query results
while($sub_row = $result2->fetch_assoc()) {
echo '<li>';
echo '' . $sub_row["pagename"] . '';
echo '</li>';
}
echo "</ul>";
echo '</li>';
} else { // for all other menu links
echo '<li class="nav-item dropdown active">';
echo '' . $row["pagename"] . '';
echo '</li>';
}
}
} else {
echo "0 results";
}
?>
The screenshot below shows the result after it renders. Notice the active class highlighted in yellow, it is added to every item in my main menu (the way I have it coded, which it's wrong of course). The green is the $sub_row["link"] (to answer Mark's question below
Notice, the active class is only needed to be added programmatically on the main menu. (the else portion of my code).
The screenshot below shows how the active class affects the menu item if the user was in the www.domain.com/how-it-works.php page. The active class contians the styles to make the menu item appear that way.
Thanks in advance
Hard to test with not having the DB outputs to match against mate but try this, basically you want an if statement to get the current page URL and match it against the url you get back from the DB.
<?php
if ($result->num_rows > 0) {
$pageURL = str_replace('/', '', $_SERVER['REQUEST_URI']);
$homeURL = $_SERVER['REQUEST_URI'];
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['id'] == 2){ ?>
<li class="nav-item dropdown">
<a href="" class="nav-link dropdown-toggle animated fadeIn animation-delay-7" data-toggle="dropdown" data-hover="dropdown" role="button" aria-haspopup="true" aria-expanded="false" data-name="services">
<?php echo $row["pagename"];?>
<i class="zmdi zmdi-chevron-down"></i>
</a>
<ul class="dropdown-menu">
<?php while($sub_row = $result2->fetch_assoc()) {?>
<li>
<a href="<?php echo $sub_row["link"]; ?>" class="dropdown-item">
<?php echo $sub_row["pagename"] ?>
</a>
</li>
<?php } ?>
</ul>
</li>
<?php
} else if($row['id'] == 1){ ?>
<li class="nav-item dropdown <?php echo ($homeURL == $row["link"])? 'active' : '';?>">
<a href="<?php echo $row["link"]; ?>" class="nav-link dropdown-toggle animated fadeIn animation-delay-7">
<?php echo $row["pagename"]; ?>
</a>
</li>
<?php
} else { ?>
<li class="nav-item dropdown <?php echo ($pageURL == $row["link"])? 'active' : '';?>">
<a href="<?php echo $row["link"]; ?>" class="nav-link dropdown-toggle animated fadeIn animation-delay-7">
<?php echo $row["pagename"]; ?>
</a>
</li>
<?php }
}
} else {
echo "0 results";
}
?>
Edit:
Bit that gets the current page url is:
$pageURL = end(explode('/', $_SERVER['REQUEST_URI']));
Bit that does the check is (this is just a shorthand if statement:
<?php echo ($pageURL == $row["link"])? 'active' : '';?>

Active Class in Navbar - Whats wrong with my php?

I'm having a bit of trouble trying to get my head around some php code.
To explain:
I have a navbar made from bootstrap.
I want this nav bar to change it's active class depending on the page.
I have a subnav within the navbar with an li class of 'dropdown'.
When this page is active this li class wants to change to 'dropdown active'
When other pages are active, they just want a simple class of 'active'.
My code is as follows:
PHP:
$pageLoc = 'where';
$nav_items = array('index'=>'Home', 'where'=>'Where?', 'appeals'=>'Current Appeals', 'news'=>'Latest News', 'events'=>'Events', 'dontate'=>'Dontate', );
$nav_sub = array('africa'=>'Africa', 'bangladesh'=>'Bangladesh', 'gaza'=>'Palestine/Gaza', 'kashmir'=>'Kashmir', 'pakistan'=>'Pakistan', 'uk'=>'United Kingdom' );
foreach ($nav_items as $nav_href=>$nav_title) {
if ($pageLoc == $nav_href) && ($pageLoc == 'where') {
echo '<li class="dropdown active">' . $nav_title . '</li>';
}
elseif ($pageHref == $nav_href) && ($pageLoc == 'no') {
echo '<li class="dropdown">' . $nav_title . '</li>';
}
elseif ($pageHref == $nav_href) {
echo '<li class="active">' . $nav_title . '</li>';
}
else {
echo '<li>' . $nav_title . '</li>';
}
}
Navbar:
<ul class="nav pull-right">
<li class="pull-right">
<a class="btn-danger" href="donate"><i class="icon-medkit"> DONATE!</i></a>
</li>
</ul>
<ul class="nav pull-right">
<li class="">
Home
</li>
<li class="dropdown">
<a href="../where/" class="dropdown-toggle disabled" data-toggle="dropdown">
Where?
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="nav-header">Where we operate</li>
<li class="divider"></li>
<li>Africa</li>
<li>Bangladesh</li>
<li>Palestine/Gaza</li>
<li>Kashmir</li>
<li>Pakistan</li>
</ul>
</li>
<li class="">
Current Appeals
</li>
<li class="">
Latest News
</li>
<li class="">
Events
</li>
</ul>
I am aware that this php is generating a syntax error. I am no pro unfortunately! :( This is
what I originally had:
foreach ($nav_items as $nav_href=>$nav_title) {
if ($pageHref == $nav_href) {
echo '<li class="active">' . $nav_title . '</li>';
}
else {
echo '<li>' . $nav_title . '</li>';
}
}
You've written:
if ($pageLoc == $nav_href) && ($pageLoc == 'where')
It should say:
if ($pageLoc == $nav_href && $pageLoc == 'where')
On a more general note, the absence of detailed debugging information is a pain, but there are workarounds. For example, if you delete half of the code and try to run it again*, does it still give a syntax error? If so, delete a bit more and see what happens; if not, undelete some and see if it works. Keep trying this and narrowing it down until you find where the error is.
*(obviously, don't delete in such a way that you create syntax errors; for example, if you delete the end of an if clause including the }, you'll get non-matching brackets.)

php array and returning a default value?

Here is my code:
<div class="search-menu">
<div class="btn-group fc">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
<?php
$currencies = explode(',', hana_get_opt('_cc'));
foreach ($currencies as $currency) {
if ($currency == get_option('woocommerce_currency')){
echo $currency;
break;
}else{
echo "Select Currency";
break;
}
}
?>
<span class="caret"></span>
</a>
<ul class="dropdown-menu currency_switcher">
<?php
foreach ($currencies as $currency) {
if ($currency == get_option('woocommerce_currency'))
echo '<li>' . $currency . '</li>';
else
echo '<li>' . $currency . '</li>';
}
?>
</ul>
</div>
</div>
Which works great it returns a list of my currencies and updates the page accordingly, I have just on question if the user has yet to set a value I would like it to say either select currency or just apply the first option from my hana_get_opt('_cc') array as the default.
Here is the html generated code:
<div class="btn-group fc">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">undefined<span class="caret"></span></a>
<ul class="dropdown-menu currency_switcher">
<li>SEK</li>
<li>EUR</li>
</ul>
</div>
I am no php coder and much appreciate any help provided
Chris
if(get_option('woocommerce_currency')==' ')
{
$currencies = explode(',', hana_get_opt('_cc'));
foreach ($currencies as $currency)
{
if $currency == get_option('woocommerce_currency'){
{
echo $currency;
break;
}
else{
echo "Select Currency";
break;
}
}
}
else
{
echo "Select Currency";
$currencies = explode(',', hana_get_opt('_cc'));
$currency=$currencies [0];
}
based on the assumption that get_option('woocommerce_currency') would return null if no currency is selected
<div class="search-menu">
<div class="btn-group fc">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
<?php
$currencies = explode(',', hana_get_opt('_cc'));
$currentCurrency = get_option('woocommerce_currency')
if ($currentCurrency === false) {
echo "select currency";
}
else{
echo $currentCurrency;
}
?>
<span class="caret"></span>
</a>
<ul class="dropdown-menu currency_switcher">
<?php
foreach ($currencies as $currency) {
if ($currency == $currentCurrency)
echo '<li>' . $currency . '</li>';
else
echo '<li>' . $currency . '</li>';
}
?>
</ul>
replace the if clause if ( $currentCurrency != null ) with whatever applies, if get_option('woocommerce_currency') returns anything other as null if not yet set

Categories