Select your language

How to create custom form field for custom component Joomla 4
Today I will teach you how to code custom form field for your custom component in Joomla, especially Joomla 4?

Problem: By default, Joomla provide Numerous types of form field @ https://docs.joomla.org/Standard_form_field_types. But if you don't find a form field that is not in list, then we need to build a custom form field. This article will help you.

Solution: In file components->com_abc->forms->form.xml

<fieldset addfieldprefix="Abdul\Component\com_abc\Administrator\Field"> 
<field
name="course_id"
<strong>type="courses"</strong>
label="COM_LMST_FORM_LBL_MANAGEENROLLMENT_COURSE_ID"
description="COM_LMST_FORM_DESC_MANAGEENROLLMENT_COURSE_ID"
required="true"
default=""
/>

In this code snippet, addfieldprefix will add path to our custom field php file(in this it is located in components->com_abc->src->Field->CoursesField.php). And in field type="courses" will be used to call that php field named Courses.

Next, In file components->com_abc->src->Field->CoursesField.php

namespace Abdul\Component\com_abc\Administrator\Field;
use Joomla\CMS\Form\FormField; use Joomla\CMS\Form\Field\ListField; use Joomla\CMS\Language\Associations; use Joomla\CMS\Form\FormHelper; use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\Factory; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; /** * Supports an HTML select list of courses * * @since 1.6 */ class CoursesField extends ListField { /** * The form field type. * * @var string * @since 1.6 */ protected $type = 'courses'; /** * Method to get a list of options for a list input. * * @return array An array of JHtml options. * * @since 11.4 */ protected function getOptions() { $db = Factory::getDbo(); $user = Factory::getUser(); $query = $db->getQuery(true); // Select the required fields from the table. $query->select('c.id, c.title'); $query->from($db->qn('#__courses', 'c')); $db->setQuery($query); $allcourses = $db->loadObjectList(); $options = array(); foreach ($allcourses as $c) { $options[] = HTMLHelper::_('select.option', $c->id, $c->title); } return $options; } }

 

In this code snippet, very first line namespace Abdul\Component\com_abc\Administrator\Field; is namespace we declared to be used in xml form file. and Class name 'CoursesField' is matching with the file name. Note all is case-sensitive.

Inside class protected $type = 'courses'; is declared. and that type is used in form field type. In very last we have getOptions function which will populate final output to be sent to that custom form field.

Our Trusted Partners

We collaborate with reliable organizations and technology partners to deliver high-quality digital solutions.

Partner 1