Custom field for module and display data like checkboxes

For Joomla! 4.x Coding related discussions, you could also use: http://groups.google.com/group/joomla-dev-general

Moderators: ooffick, General Support Moderators

Forum rules
Forum Rules
Absolute Beginner's Guide to Joomla! <-- please read before posting, this means YOU.
Forum Post Assistant - If you are serious about wanting help, you will use this tool to help you post.
Windows Defender SmartScreen Issues <-- please read this if using Windows 10.
Post Reply
zeus07
Joomla! Intern
Joomla! Intern
Posts: 51
Joined: Fri Feb 05, 2016 12:25 am

Custom field for module and display data like checkboxes

Post by zeus07 » Thu Apr 04, 2024 11:21 am

Hi!

I created module and want to display on backend in module a list of checkboxes from DB table.
I created custom field and placed it to fields/sqlcheckboxes.php.

Code for file fields/sqlcheckboxes.php:

Code: Select all

<?php
/**
 * @package     Joomla.Platform
 * @subpackage  Form\Field
 *
 * @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 * @author      3ehrang <[email protected]>
 */

namespace VPJoomla\Module\Faq\Form\Field;

use Joomla\CMS\Form\Field\CheckboxesField;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;

defined('_JEXEC') or die;

/**
 * Supports a custom SQL select list for module settings.
 *
 * @since  Joomla 4.0
 */
class SQLCheckBoxesField extends CheckboxesField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  Joomla 4.0
	 */
	protected $type = 'SQLCheckBoxes';

	/**
	 * The keyField.
	 *
	 * @var    string
	 * @since  Joomla 4.0
	 */
	protected $keyField;

	/**
	 * The valueField.
	 *
	 * @var    string
	 * @since  Joomla 4.0
	 */
	protected $valueField;

	/**
	 * The translate.
	 *
	 * @var    boolean
	 * @since  Joomla 4.0
	 */
	protected $translate = false;

	/**
	 * The query.
	 *
	 * @var    string
	 * @since  Joomla 4.0
	 */
	protected $query;

	/**
	 * Method to get the custom field options.
	 * Use the query attribute to supply a query to generate the list.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   Joomla 4.0
	 */
	protected function getOptions(): array
	{
		$options = [];

		// Get the database object.
		$db = $this->container->get('DatabaseDriver');

		// Set the query and get the result list.
		$db->setQuery($this->query);
		$items = $db->loadObjectList();

		// Build the field options.
		if (!empty($items)) {
			foreach ($items as $item) {
				$key = $this->keyField;
				$value = $this->valueField;
				$optionText = $this->translate ? Text::_($item->$value) : $item->$value;
				$options[] = HTMLHelper::_('select.option', $item->$key, $optionText);
			}
		}

		return $options;
	}

	/**
	 * Method to setup the field.
	 *
	 * @param   \SimpleXMLElement  $element  The SimpleXMLElement object representing the <field /> tag for the form field object.
	 * @param   mixed              $value    The form field value to validate.
	 * @param   string             $group    The field name group control value. This acts as an array container for the field.
	 *                                       For example if the field has name="foo" and the group value is set to "bar" then the
	 *                                       full field name would end up being "bar[foo]".
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   Joomla 4.0
	 */
	public function setup(\SimpleXMLElement $element, $value, $group = null): bool
	{
		$return = parent::setup($element, $value, $group);

		if ($return) {
			$this->keyField = (string) ($element['key_field'] ?? 'value');
			$this->valueField = (string) ($element['value_field'] ?? $element['name']);
			$this->translate = (bool) ($element['translate'] ?? false);
			$this->query = (string) $element['query'];
		}

		return $return;
	}
}
This is code for field in mod_faq.xml:

Code: Select all

<fields name="faq" addfieldpath="/modules/mod_faq/fields">
                    <field name="title"
                           id="faq-item"
                           type="SQLCheckBoxes"
                           translate="types"
                           query="SELECT id, title FROM #__faq_item WHERE state = 1"
                           key_field="id"
                           value_field="title"
                           required = "true"
                           multiple="true"
                           label="MOD_FAQ_SELECT_QUESTION_LABEL"
                           description="MOD_FAQ_SELECT_QUESTION_DESC"
                           class="check-dox-faq-item"/>
                </fields>
I can't see something errors on backend, but my custom field empty and look like text field.
empty-field.png
Help me please to fix this. Thanks!
You do not have the required permissions to view the files attached to this post.

zeus07
Joomla! Intern
Joomla! Intern
Posts: 51
Joined: Fri Feb 05, 2016 12:25 am

Re: Custom field for module and display data like checkboxes

Post by zeus07 » Tue Apr 09, 2024 8:30 am

Someone can help with this question?

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2959
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: Custom field for module and display data like checkboxes

Post by SharkyKZ » Tue Apr 09, 2024 8:35 am

Replace addfieldpath with addfieldprefix="VPJoomla\Module\Faq\Form\Field".

zeus07
Joomla! Intern
Joomla! Intern
Posts: 51
Joined: Fri Feb 05, 2016 12:25 am

Re: Custom field for module and display data like checkboxes

Post by zeus07 » Tue Apr 09, 2024 9:29 am

SharkyKZ wrote:
Tue Apr 09, 2024 8:35 am
Replace addfieldpath with addfieldprefix="VPJoomla\Module\Faq\Form\Field".
Now I recreated my field and it look like this:
fields/FAQItemsField.php

Code: Select all

<?php
namespace VPJoomla\Module\Faq\Field;

use Joomla\CMS\Form\FormField;
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;

defined('_JEXEC') or die;

/**
 * Custom field for selecting FAQ items from the database.
 *
 * @since  Joomla 4.0
 */
class FAQItemsField extends FormField
{
	protected $type = 'FAQItems';

	/**
	 * Method to render the field input.
	 *
	 * @return  string  The field HTML.
	 */
	protected function getInput(): string
	{
		// Get database object
		$db = Factory::getDbo();

		// Build query to fetch FAQ items
		$query = $db->getQuery(true)
			->select($db->quoteName(['id', 'title']))
			->from($db->quoteName('#__faq_items'))
			->where($db->quoteName('state') . ' = 1');

		// Set the query and get the result list
		$db->setQuery($query);
		$faqItems = $db->loadAssocList();
		//$faqItems = $db->loadObjectList();

		// Start building the checkboxes HTML
		$html = '<div class="faq-items-checkboxes">';

		if (!empty($faqItems)) {
			foreach ($faqItems as $item) {
				$html .= '<div class="form-check">';
				$html .= HTMLHelper::_('form.checkboxes', 'params[faq_items][]', $item['id'], $item['title'], 'value', 'text', (array)$this->value, true);
				$html .= '</div>';
			}
		}

		$html .= '</div>';

		return $html;
	}
}
This is mod_faq.xml

Code: Select all

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" client="site" version="4.0" method="upgrade">
	<name>FAQ Content</name>
	<creationDate>02/04/2024</creationDate>
	<author>2z &amp; zeus07</author>
	<authorEmail>[email protected], [email protected]</authorEmail>
	<authorUrl>https://vpjoomla.school</authorUrl>
	<license>GNU General Public License version 3 or later; see LICENSE.txt</license>
	<version>4.0.0</version>
	<description>MOD_FAQ_XML_DESCRIPTION</description>
	<namespace path="src">VPJoomla\Module\Faq</namespace>

	<files>
		<filename module="mod_faq">mod_faq.php</filename>
		<folder>src</folder>
		<folder>fields</folder>
		<folder>tmpl</folder>
	</files>

	<languages>
		<language tag="en-GB">language/en-GB/en-GB.mod_faq.ini</language>
		<language tag="en-GB">language/en-GB/en-GB.mod_faq.sys.ini</language>
		<language tag="ru-RU">language/ru-RU/ru-RU.mod_faq.ini</language>
		<language tag="ru-RU">language/ru-RU/ru-RU.mod_faq.sys.ini</language>
	</languages>

	<config>
		<fields name="params">
			<fieldset name="basic">
				<field name="name" type="text" label="MOD_FAQ_MODULE_TITLE" description="" size="10" />
				<fields name="faq" addfieldprefix="VPJoomla\Module\Faq\Form\Field">
					<field
						name="faq_items"
						type="FAQItems"
						translate="types"
						label="MOD_FAQ_SELECT_QUESTION_LABEL"
						description="MOD_FAQ_SELECT_QUESTION_DESC"
						multiple="true"
						required="true"
					/>
				</fields>
			</fieldset>
			<fieldset name="advanced">

				<field
						name="layout"
						type="modulelayout"
						label="JFIELD_ALT_LAYOUT_LABEL"
						class="custom-select"
				/>

				<field
						name="moduleclass_sfx"
						type="textarea"
						label="COM_MODULES_FIELD_MODULECLASS_SFX_LABEL"
						rows="3"
				/>

				<field
						name="cache"
						type="list"
						label="COM_MODULES_FIELD_CACHING_LABEL"
						default="0"
				>
					<option value="1">JGLOBAL_USE_GLOBAL</option>
					<option value="0">COM_MODULES_FIELD_VALUE_NOCACHING</option>
				</field>

				<field
						name="cache_time"
						type="number"
						label="COM_MODULES_FIELD_CACHE_TIME_LABEL"
						default="0"
				/>

				<field
						name="cachemode"
						type="hidden"
						default="itemid"
				>
					<option value="itemid"></option>
				</field>
			</fieldset>
		</fields>
	</config>
</extension>
src/Helper/FaqHelper.php

Code: Select all

<?php

namespace VPJoomla\Module\Faq\Site\Helper;

use Joomla\CMS\Factory;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\Database\DatabaseDriver;

defined('_JEXEC') or die;

class FaqHelper {
	public static function getArticleUrl(int $id = null)
	{
		if ($id != null) {
			$app   = Factory::getApplication();
			$menu  = $app->getMenu();

			// Get the database object.
			$db = Factory::getContainer()->get(DatabaseDriver::class);
			$query = $db->getQuery(true);

			$query->select('link');
			$query->from('#__menu');
			$query->where($db->quoteName('menutype') . ' = ' . $db->quote($menu) . 'AND' . $db->quoteName('link') . ' LIKE ' . $db->quote('index.php?option=com_content&view=article&id=' . $id . '%') . 'AND' . $db->quoteName('published') . ' = ' . $db->quote(1));

			$db->setQuery($query);
			$results = $db->loadObject();
			if ($results->link) {
				return $results->link;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	/**
	 * @param $id
	 *
	 * @return mixed
	 */
	public static function getFaqItem($id = null)
	{

		$id = substr(json_encode($id), 1, -1);

		// Get the database object.
		$db = Factory::getContainer()->get(DatabaseDriver::class);
		$query = $db->getQuery(true);

		$query->select(array('*'));
		$query->from($db->quoteName('#__faq_item'));
		$query->where($db->quoteName('id') . ' IN ' . '('. $id .')');

		$db->setQuery($query);
		$result = $db->loadObjectList();
		if($result){
			return $result;
		}
	}
}
Maybe I made mistake at code?

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2959
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: Custom field for module and display data like checkboxes

Post by SharkyKZ » Thu Apr 11, 2024 8:07 am

Change the namespace in the field class to VPJoomla\Module\Faq\Site\Field. Make the same change in addfieldprefix attribute. Move the field file to src/Field.

zeus07
Joomla! Intern
Joomla! Intern
Posts: 51
Joined: Fri Feb 05, 2016 12:25 am

Re: Custom field for module and display data like checkboxes

Post by zeus07 » Thu Apr 11, 2024 8:19 am

SharkyKZ wrote:
Thu Apr 11, 2024 8:07 am
Change the namespace in the field class to VPJoomla\Module\Faq\Site\Field. Make the same change in addfieldprefix attribute. Move the field file to src/Field.
Thanks, I did this yesterday, but the same result

robbiej
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Wed Apr 06, 2016 11:22 am

Re: Custom field for module and display data like checkboxes

Post by robbiej » Mon Apr 15, 2024 9:45 pm

Could you list your code files after you made the suggested change? Include the full pathname with each code file.

It sounds as if your field definition isn't being called. You could add Joomla Log statements (https://docs.joomla.org/Using_JLog) into your code to see if that's the case, or use a debugger and set a breakpoint on the code.

Namespacing could well be the problem. It's documented at https://manual.joomla.org/docs/general- ... amespaces/.

After you install your extension you shouldn't be "placing" the code in any other directory. Using namespacing rules Joomla will find the field definition in the site module directory based on your namespace, ie where it's been installed into.


Post Reply

Return to “Joomla! 4.x Coding”