Jump to content
mrkhan

Menu Building

Recommended Posts

Hello,

i am trying to build one Page in CMS for menu Building.

i have created a field name "menu_page" Page type & one text filed name "depth"

now i have crated a new repeater name "menus" with above both fields.

menus (repeater)
                             menu_page (page type, single page)
                             depth (text)

now i add it one page name "header" and added values as bellow

menus1
             menu_page "about us" depth (0)
menus2
             menu_page "About Company" depth (1)
menus3
             menu_page "Products" depth (3)
menus4
             menu_page "Contact Us" depth (0)

in my template file i have code as bellow

<ul>
<?php
$menus=$pages->get("/header/");
foreach($menus as $menu)
{
?>
<li><a href="<?php echo $menu->url;?>"><?php echo $menu->title;?></a></li>
<?php
}
?>
</ul>

This shows TOP menu Menu but how to get SUB menu according to Dept of each menu.

Thanks

Share this post


Link to post
Share on other sites

If you're already trying to build menus manually an not automated from the page tree, then you should take a look at kongondo's menu builder module. 

  • Like 1

Share this post


Link to post
Share on other sites

If you're already trying to build menus manually an not automated from the page tree, then you should take a look at kongondo's menu builder module. 

Hello,

i saw that module but want to create my page for creating menu through page not through module.

Thanks

Share this post


Link to post
Share on other sites

Is there a specific reason to do so? Maybe we can help you out without the need for you to reinvent the wheel.

  • Like 1

Share this post


Link to post
Share on other sites

Hello,

i am trying to build one Page in CMS for menu Building.

i have created a field name "menu_page" Page type & one text filed name "depth"

now i have crated a new repeater name "menus" with above both fields.

menus (repeater)
                             menu_page (page type, single page)
                             depth (text)

now i add it one page name "header" and added values as bellow

menus1
             menu_page "about us" depth (0)
menus2
             menu_page "About Company" depth (1)
menus3
             menu_page "Products" depth (3)
menus4
             menu_page "Contact Us" depth (0)

in my template file i have code as bellow

<ul>
<?php
$menus=$pages->get("/header/");
foreach($menus as $menu)
{
?>
<li><a href="<?php echo $menu->url;?>"><?php echo $menu->title;?></a></li>
<?php
}
?>
</ul>

This shows TOP menu Menu but how to get SUB menu according to Dept of each menu.

Thanks

I completely agree with LostKobrakai, however to answer your question I would do the following:

<ul>
<?php
foreach($page->menus as $item) {
	$prev = $item->prev->depth ? : 0;
	$next = $item->next->depth ? : 0;
	$depth = $item->depth;
	$count = $depth - $next;

	echo ($prev < $depth ? "<ul><li>" : "<li>") . "<a href='{$item->menu_page->url}'>{$item->menu_page->title}</a>";

	if($count == 0) {
		echo "</li>";
	} else if($count > 0) {
		for($c = 1; $c <= $count; $c++) { echo "</li></ul>"; }
                echo "</li>";
	}
} ?>
</ul> 

I've just tried to come up with this from my head, so it might need a little tweaking. 

EDIT:

Updated based on Macrura's notes. 

  • Like 1

Share this post


Link to post
Share on other sites

yes, sometimes for simple sites i do something like this (usually use a table, but repeater should work);

i'm not sure about depth - seems maybe unnecessary;

i usually have a checkbox called child which simply makes the current row/repeater a child of the previous non-child item in the order that the items appear in...

also i think you can maybe use this shorter ternary syntax if you are using the code above

$prev = $item->prev->depth ?: 0;    
$next = $item->next->depth ?: 0;
  • Like 1

Share this post


Link to post
Share on other sites

Hello @Macrura,

thanks for your reply. your idea look similar to me what i am looking.

could you please share with me your code for this purpose and checkbox for child.

many thanks

Share this post


Link to post
Share on other sites

sure - here's the function - you'd need to have fields for menu_group (checkbox), menu_page (page select) and menu_href (url) which overrides page select;

in this case you also need to set the href as a # for the parent items, but you could change this probably

function semanticNav($field) {
	$page = wire('page');
	$menu = $field;
	$out = '';
	$group = false;

	foreach($menu as $item) {
		$class = '';

		// if this item is not in a group, but group is true from previous
		// item, close the ul /li now:
		if($item->menu_group != 1 && $group) $out .= "</ul>\n</li>\n";

		$url = '';
		if($item->menu_page->id) $url = $item->menu_page->url;
		if($item->menu_href) $url = $item->menu_href;
		if($item->menu_page->id == $page->rootParent->id) $class = " class='current'";

		if($item->menu_group == 1 && $item->menu_href == '#') {
			$out .= "<li class=\"dropdown\">\n";
			$out .= "\t<a href='#' class='dropdown-toggle' data-toggle='dropdown'>$item->menu_title</a>\n";
			$out .= "\t\t<ul class=\"dropdown-menu\">\n";
			$group = true;
		}

		// Sub items
		if($item->menu_group == 1 && $item->menu_page->id) {
			$out .= "\t<li{$class}><a href='$url'>$item->menu_title</a></li>\n";
			$group = true;
		}
		// Regular Items:
		if($item->menu_group != 1 && $item->menu_page->id) {
			$out .= "\t<li{$class}><a href='$url'>$item->menu_title</a></li>\n";
			$group = false;
		}

	}

	return $out;
}

Share this post


Link to post
Share on other sites

Hello @Macrura,

really thanks for your code but unfortunately i am unable to do what i need, i think code is great but only i am unable to understand.

like i have menus like that

Home
About us
Products
     Product 1
         sub product
     Product 2
         sub product1
         sub product2
    Product 3
         sub product
Contact us

i can't understand how i will add 2 sub level products in page?

as i told you i am using repeater when i add item i can select the page and select the check box for group and set the url , but how i will add 2nd menus like under 

product -> Product 2 ->sub product1

could you please show me some pics of your page view & how you make repeater with fields?

really appreciate all your help

Thanks

Share this post


Link to post
Share on other sites

my setup and that function is really only for simple sites needing only 2 levels; also for the way i have it setup i'm using a table, but it should work with any wirearray.

in your case it seems that you may be better off using MSN, or Menu builder, or even a separate branch of the page tree which can generate an MSN menu but specifying a root page argument, and then overriding the URL to be the page select instead of the virtual menu page/node.

there are a lot of posts on this forum with recursive functions for making menus of all kinds, from all different types of sources, be it the page tree, a menu tree, or repeaters; here are some:

https://processwire.com/talk/topic/9033-mega-menu/?hl=%2Bnested+%2Bmenu#entry87159

https://processwire.com/talk/topic/8544-want-to-create-a-custom-menu/?hl=%2Bnested+%2Bmenu#entry82687

https://processwire.com/talk/topic/3650-multi-level-menu/?hl=%2Bnested+%2Bmenu

https://processwire.com/talk/topic/2787-custom-menu-not-related-to-page-tree/?hl=%2Bnested+%2Bmenu

  • Like 1

Share this post


Link to post
Share on other sites

My menus work like this

First create a "menu" template,

a simple empty template that will hold "menu-item" pages as children.

Then create the "menu-item" template that can hold 'menu-item' pages as children,

fill it with these fields :

- (title field) The title for the menu

- (item field) A page reference (Single Page or NullPage) field that will link any page in the site except pages with menu or menu-item template.

- (isExternalLink field) A checkbox that tells if the link is outside the site.

- (externalLink field) a Textbox that holds the external url if the checkbox isExternalLink is active.

You can add many additional fields depending on your needs, like css, js, or other information.

When that is done just create a page named "Menu" with the "menu" template,

later add children pages with the "menu-item" template.

Now you have a menu that can be rendered

like any other page in processwire.

$menu = $pages->get('/menu');
foreach($menu->children as $menu_item) {
    
    if($menu_item->isExternalLink){
      echo "{$menu_item->externalLink}";
    } else {
      echo "{$menu_item->item->url}";
    }
}

With this approach you can rely on the Processwire backend

to give order to the items and create as many children and deep levels as you like

  • Like 4

Share this post


Link to post
Share on other sites

to answer mrkhan's query regarding the way my setup for this example is, here is the screenshot of the table that generates the menu:

post-136-0-83350600-1450974640_thumb.jpg

@clsource - your example is also the same as what is discussed in depth in my last link provided in my prior post; which has the same features/setup. Visitors looking at this thread may want to visit that topic because it also provides the comprehensive code to output the markup for such a setup.

  • Like 3

Share this post


Link to post
Share on other sites

to answer mrkhan's query regarding the way my setup for this example is, here is the screenshot of the table that generates the menu:

attachicon.gifmenu_table.jpg

@clsource - your example is also the same as what is discussed in depth in my last link provided in my prior post; which has the same features/setup. Visitors looking at this thread may want to visit that topic because it also provides the comprehensive code to output the markup for such a setup.

How to implement like as your screenshoot ?

I'm going to use pw's out-of-box functionality and core modules to build a menu navigation, allow people to select which page to show on an menu navigation.

I knew that Page field in the right module for selecting pages.But in your screenshot, u can have three fields in a row, text, page and url

Which technique u used ?

Share this post


Link to post
Share on other sites

yes, as mentioned you could use whatever you have in your kit and prefer to use, table, pagetable, repeaters, pages...

though you may want to give Menu Builder a try...

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By MoritzLost
      In this tutorial I want to write about handling special cases and change requests by clients gracefully without introducing code bloat or degrading code quality and maintainability. I'll use a site's navigation menu as an example, as it's relatable and pretty much every site has one. I'll give some examples of real situations and change requests I encountered during projects, and describe multiple approaches to handling them. However, this post is also about the general mindset I find useful for ProcessWire development, which is more about how to handle special cases and still keep your code clean by making the special case a normal one.
      The problem: Special cases everywhere
      Since ProcessWire has a hierarchical page tree by default, as a developer you'll usually write a function or loop that iterates over all children of the homepage and displays a list of titles with links. If the site is a bit more complex, maybe you additionally loop over all grandchildren and display those in drop-down menus as well, or you even use a recursive function to iterate over an arbitrary amount of nested child pages. Something like this:
      function buildRecursiveMenu(Page $root): string { $markup = ['<ul class="navigation">']; foreach ($root->children() as $child) { $link = '<a class="navigation__link" href="' . $child->url() . '">' . $child->title . '</a>'; $children = $child->hasChildren() ? buildRecursiveMenu($child) : ''; $markup[] = "<li class="navigation__item">{$link}{$children}</li>"; } $markup[] = '</ul>'; return implode(PHP_EOL, $markup); } But then the requests for special cases come rolling in. For example, those are some of the requests I've gotten from clients on my projects (by the way, I'm not saying the clients were wrong or unreasonable in any of those cases - it's simply something I needed to handle in a sensible way):
      The homepage has the company's name as it's title, but the menu link in the navigation should just say "Home". The first page in a drop-down menu should be the top-level page containing the drop-down menu. This was requested because the first click on the top-level item opens the sub-navigation instead of navigating to that page (espcially on touch devices, such as iPads, where you don't have a hover state!), so some visitors might not realize it's a page itself. Some top-level pages should be displayed in a drop-down menu of another top-level page, but the position in the page tree can't change because of the template family settings. The menu needs to contain some special links to external URLs. For one especially long drop-down menu, the items should be sorted into categories with subheadings based on a taxonomy field. In general, my solutions to those requests fall into three categories, which I'll try to elaborate on, including their respective benefits and downsides:
      Checking for the special case / condition in the code and changing the output accordingly (usually with hard-coded values). Separating the navigation menu from the page tree completely and building a custom solution. Utilizing the Content Management Framework by adding fields, templates and pages that represent special states or settings. Handling it in the code
      This is the simplest solution, and often the first thing that comes to mind. For example, the first request (listing the homepage as "Home" instead of it's title in the navigation) can be solved by simply checking the template or ID of the current page inside the menu builder function, and changing the output accordingly:
      // ... $title = $child->template->name === 'home' ? 'Home' : $child->title; $link = '<a class="navigation__link" href="' . $child->url() . '">' . $title . '</a>'; // ... This is definitely the fastest solution. However, there are multiple downsides. Most notably, it's harder to maintain, as each of those special cases increases the complexity of the menu builder function, and makes it harder to change. As you add more special conditions, it becomes exponentially harder to keep changing it. This is the breeding ground for bugs. And it's much harder to read, so it takes longer for another developer to pick up where you left (or, as is often cited, for yourself in six months). Also, now we have a hard-coded value inside the template, that only someone with access to and knowledge of the template files can change. If the client want's the link to say "Homepage" instead of "Home" at some point, they won't be able to change it without the developer. Also, each special case that is hidden in the code makes it harder for the client to understand what's going on in terms of template logic - thus increasing your workload in editorial support.
      That said, there are definitely some times where I would go with this approach. Specifically:
      For smaller projects that you know won't need to scale or be maintained long-term. If you are the only developer, and/or only developers will edit the site, with no "non-technical" folk involved. For rapid prototyping ("We'll change it later") Building a custom solution
      My initial assumption was that the main navigation is generated based on the page tree inside ProcessWire. But of course this isn't set in stone. You can just as easily forgo using the page tree hierarchy at all, and instead build a custom menu system. For example, you could add a nested repeater where you can add pages or links on a general settings page, and generate the menu based on that. There are also modules for this approach, such as the Menu Builder by @kongondo. This approach is not the quickest, but gives the most power to the editors of your site. They have full control over which pages to show and where. However, with great power comes great responsibility, as now each change to the menu must be performed manually. For example, when a new page is added, it won't be visible in the menu automatically. This is very likely to create a disconnect between the page tree and the menu (which may be what you want, after all). You may get ghost pages that are not accessible from the homepage at all, or the client may forgot to unpublish pages they don't want to have any more after they've removed them from the menu.
      I would only go with this approach if there are so many special cases that there hardly is a "normal case". However, even then it might not be the best solution. The direct relationship between the page tree, the menu structure and page paths are one of the strongest features of ProcessWire in my opinion. If many pages need to be placed in special locations without much structure in regards to what templates go where, maybe you only need to loosen up the template family settings. I have built one site without any template family restrictions at all - any page of any template can go anywhere. It's definitely a different mindset, but in this case it worked well, because it allowed the client to build custom sections with different page types grouped together.
      It's a trade-off, as it is so often, between flexibility and workload. Weigh those options carefully before you choose this solution!
      Utilizing the CMF
      This is the middle ground between the two options above. Instead of building a completely custom solution, you keep with the basic idea of generating a hierarchical menu based on the page tree, but add fields and templates that allow the editor to adjust how and where individual pages are displayed, or to add custom content to the menu. of course, you will still write some additional code, but instead of having hard-coded values or conditions in the template, you expose those to the client, thereby making the special case one of the normal cases. The resulting code is often more resilient to changing requirements, as it can not one handle that specific case that the client requested, but also every future change request of the same type. The key is to add fields that enable the client to overwrite the default behaviour, while still having sensible defaults that don't require special attention from the editor in most cases. I'll give some more examples for this one, as I think it's usually the best option.
      Example 1: Menu display options
      This is probably the first thing you thought of for the very first change request I mentioned (displaying the homepage with a different title). Instead of hard-coding the title "Home" in the template, you add a field menu_title that will overwrite the normal title, if set. This is definitely cleaner than the hard-coded value, since it allows the client to overwrite the title of any page in the menu.
      I'll only say this much in terms of downsides: Maybe the menu title isn't really what the client wanted - instead, perhaps they feel limited because the title is also displayed as the headline (h1) of the page. In this case, the sensible solution would be an additional headline field that will overwrite the h1, instead of the menu_title field. Which fields are really needed is an important consideration, because you don't want to end up with too many. If each page has fields for the title, a headline, a menu title and an SEO-title, it's much more complicated than it needs to be, and you will have a hard time explaining to the client what each field is used for.
      Another example in this category would be an option to "Hide this page in the menu". This could be accomplished by hiding the page using the inbuilt "hidden" status as well, but if it's hidden it won't show up in other listings as well, so separating the menu display from the hidden status might be a good idea if your site has lots of page listings.
      Example 2: "Menu link" template
      One solution that is quite flexible in allowing for custom links to pages or external URLs is creating a menu-link template that can be placed anywhere in the page tree. This templates can have fields for the menu title, target page and/or external target URL. This way, you can link to another top-level page or an external service inside a drop-down menu, by placing a Menu Link page at the appropriate position. This is also a clean solution, because the navigation menu will still reflect the page tree, making the custom links visible and easily editable by the editors.
      A minor downside is that those templates are non-semantical in the sense that they aren't pages with content of their own. You'll need to make sure not to display them in listings or in other places, as they aren't viewable. It may also require loosening up strict family rules - for example, allowing for Menu Link pages to be placed below the news index page, which normally can only hold news pages.
      Example 3: Drop-down menu override
      This one is a more radical solution to override drop-down menus. You add a repeater field to top-level pages, similar to the one mentioned as a custom solution, where you can add multiple links to internal pages or URLs. If the repeater is empty, the drop-down menu is generated normally, based on the sub-pages in the page tree. But if the repeater contains some links, it completely overrides the drop-down menu. It's similar to the fully custom solution in that as soon as you override a sub-menu for a top-level page, you have to manually manage it in case the page structure changes. But you can make that decision for each top-level page individually, so you can leave some of them as is and only have to worry about the ones that you have overwritten.
      Again, this offers sensible defaults with good customizability. A downside is that the mixed approach may confuse the client, if some changes to the page tree are reflected in the drop-down menu directly, while others don't seem to have any effect (especially if you have multiple editors working on a site).
      Finding the right solution
      So how do you choose between the approaches? It depends on the client, the requirements, and on what special cases you expect and want to handle. Sometimes, a special request can be turned down by explaining how it would complicate editorial workflows or have a negative impact on SEO (for example, if you risk having some pages not accessible from the homepage at all). Also, make sure you understand the actual reason behind a change request, instead of just blindly implementing the suggestion by the client. Often, clients will suggest solutions without telling you what the actual problem is they're trying to solve.
      For example: In one case, I implemented the drop-down override mentioned in example three. However, what the client really wanted was to have the top-level page as the first item in the drop-down menu (see the example requests mentioned above). So they ended up overwriting every single drop-down menu, making the menu harder to maintain. In this case, it would have been better to go with a more specialized solution, such as adding a checkbox option, or even handling it in the code, since it would have been consistent throughout the menu.
      Another example was mentioned above: If the client requests an additional "Menu title" field, maybe what they really need is a "Headline" field. I recommend reading Articulating Design Decisions by Tom Greever; it includes some chapters on listening to the client, finding out the real reason behind a change request, and responding appropriately. It's written from a design perspective, but is applicable to development as well, and since UX becomes more important by the day, the lines between the disciplines are blurred anyway.
      Conclusion
      I realize now this reads more like a podcast (or worse, a rant) than an actual tutorial, but hopefully I got my point across. ProcessWire is at is greatest if you utilize it as a Content Management Framework, creating options and interfaces that allow for customizability while retaining usability for the client / editor. I usually try to hit a sweet spot where the editors have maximum control over the relevant aspects of their site, while requiring minimal work on their part by providing sensible defaults. Above, I listed some examples of requests I've gotten and different solutions I came up with to handle those with custom fields or templates. Though in some cases the requirements call for a custom solution or a quick hack in the template code as well!
      What are some of the special requests you got? How did you solve them? I'd love to get some insights and examples from you. Thanks for reading!
    • By wiredny
      I want to remove the "Home" page from the navbar, but keep the other pages (About, Templates, etc) on the navbar? How is this done?
       
       
    • By louisstephens
      So I was tinkering around with the "select fields" field type and added it to a repeater. My thoughts were I could have a user select a field (textarea, text, etc etc) that I defined and give it a name (another field in the repeater) and create their own form on the page. To be honest, I am now a little lost with rendering the form and mailing the results as potentially the form will be unique and custom every time.  The only way I know to handle the output is by going about it this way:
      $forms = $page->form_select_fields; foreach($forms as $form) { if($form->name === "form_input") { //output input with custom name } elseif($form->name === "form_textarea") { //output input with custom name } } Is there a better way to go about rendering the elements from the repeater? As far as the custom sending goes, I am really at a loss since it would be pretty dynamic. Has anyone used this type of approach, and if so, how did you handle this without going insane?
    • By kaba86
      Hello PW Community, really glad that discovered this CMS recently, it is very strange it took so long That idea of no front design limitations is just awesome!
      Need to say that I have a bit of knowledge of html and css, but almost no php, so I need your help.
      What I want to do is an article posting  cms, with this structure:
       
      - Homepage - Projects - Articles -- Category 1 --- Articles of category 1 -- Category 2 --- Articles of category 2 - About - Contact Found this ProcessWire Profile https://github.com/tutsplus/how-to-create-an-ajax-driven-theme-for-processwire
      It covers almost all my needs, except the menu. When I add a childpage for this page http://artist.nicegrp.com/publications/world-world/ , World:World doesn't appear under Writings & Publications.
      I need a menu that works like a breadcrumb, that shows on the menu the category that you are viewing. So when I'm in articles page, on the menu it shows only articles and it's categories. When I get into a category, that category takes state active link but doesn't show on the menu links and titles for contained articles. How can I do that?
      Sorry for my long writing and English, it is not my native but I hope you understood what I need. Can you help me with that?
      Thank you
       
    • By rareyush
      hi everyone
       
      I am trying get a full width sub-menu on 3rd item in menu or navbar which is coming from a loop.
      i was hoping this can be done by using jquery by targeting 3rd element in navbar but jquery is blocked in some browser by default so is there any other method I can do this
×
×
  • Create New...