How to get menu parameter in frontend of custom extension

Select your language

How to create custom form field for custom component Joomla 4

Problem: You need to show or hide some information based on menu item parameter you set from admin menu parameter of that custom component.

Solution: 

We have to perform following steps:

For example we have component com_mydocs. In file components->com_mydocs->tmpl->cate->default.xml

<metadata>
	<layout title="List All Categories" option="">
		<help
			key="key"
		/>
		<message>
			<![CDATA[List All Categories]]>
		</message>
	</layout>

	<!-- Add fields to the parameters object for the layout. -->
	<fields name="request">
		<fieldset name="request"
		>
			<field
				name="id"
				type="category"
				label="JGLOBAL_FIELD_CATEGORIES_CHOOSE_CATEGORY_LABEL"
				extension="com_mydocs"
				show_root="false"
				required="false"
			/>
		</fieldset>
	</fields>

	<fields name="params">
		<fieldset name="basic" label="JGLOBAL_CATEGORIES_OPTIONS">

            <field name="docdetailpage" type="menuitem" default="" label="Select a menu" description="Select a menu" />

		</fieldset>
	</fields>

</metadata>

We added two type of fields group in our code, fields named request contain fieldset request and fields named params contain fieldset basic. And each group contain specific field, first one has field named id and of type category, which will fetch all categories specific to that component. And second named docdetailpage of type menuitem, which show available menu on site to select from.

First of all import namespace Factory, if you have not done so far. At very top of your code.

use Joomla\CMS\Factory;

Now following code will get 'id' field value for you in model.php class

// Get Menu Param		
$input = Factory::getApplication()->input;
$rootcateid= $input->get('id', 0, 'int');

And following line of code will fetch params -> basic field name value for you in default.php , a tmpl field

$app = Factory::getApplication();
$sitemenu = $app->getMenu();
$activeMenuitem = $sitemenu->getActive();
$menu_params = $activeMenuitem->getParams();
$docdetailpage=$menu_params->get("docdetailpage");

Be sure ! you can use that code snippet in any where in your custom extension, as Factory::getApplication(); is available at any where in your code, after you import its namespace.