Aggiunta di campi personalizzati ai componenti principali utilizzando un plugin

From Joomla! Documentation

Revision as of 11:50, 7 March 2022 by Ino (talk | contribs) (Created page with "===Abilitazione della modifica front-end dei campi personalizzati===")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Other languages:
Deutsch • ‎English • ‎Nederlands • ‎català • ‎español • ‎français • ‎italiano • ‎português do Brasil • ‎русский • ‎فارسی • ‎हिन्दी • ‎বাংলা • ‎中文(台灣)‎

Hai mai desiderato che ci fosse un campo del numero di telefono in più in com_contact o hai bisogno di un campo aggiuntivo per gli articoli in com_content? Joomla! fornisce un modo semplice per integrare nuovi campi con componenti fondamentali come questi. Tutto ciò che serve per raggiungere questo obiettivo è un semplice plug-in di contenuto e un override layout nel tuo Template.

Questo articolo mostra come aggiungere un campo aggiuntivo a un componente principale usando l'esempio dell'aggiunta di un indirizzo e-mail aggiuntivo ai contatti in com_contact. Se hai bisogno di aggiungere campi personalizzati a com_content per i tuoi articoli Joomla, cambia semplicemente qualsiasi riferimento da "contatto" a "contenuto" nel codice qui sotto. E nota che com_content usa "attribs" e non "params" per il valore dei campi e per l'override.

Aggiunta di campo personalizzato

Si consiglia di leggere prima Creazione di un plug-inCreating a Plugin for Joomla! per i dettagli su come creare e installare un plug-in, che non è trattato qui.

Per aggiungere un campo a un componente di sistema è necessario creare un plugin di contenuto che raccolga l'evento onContentPrepareForm e inserisca i propri campi nella data JForm. Il seguente codice è per Joomla 3.1 e successivi.

<?php
// no direct access
defined ('_JEXEC') or die;
class plgContentExample extends JPlugin
{
	/**
	 * Load the language file on instantiation.
	 * Note this is only available in Joomla 3.1 and higher.
	 * If you want to support 3.0 series you must override the constructor
	 *
	 * @var boolean
	 * @since <your version>
	 */
	protected $autoloadLanguage = true;

	/**
	 * Prepare form and add my field.
	 *
	 * @param   JForm  $form  The form to be altered.
	 * @param   mixed  $data  The associated data for the form.
	 *
	 * @return  boolean
	 *
	 * @since   <your version>
	 */
	function onContentPrepareForm($form, $data)
	{
		$app    = JFactory::getApplication();
		$option = $app->input->get('option');

		switch($option)
		{
			case 'com_contact' :
				if ($app->isClient('administrator'))
				{
					JForm::addFormPath(__DIR__ . '/forms');
					$form->loadFile('contact', false);
				}

				return true;
		}

		return true;
	}
}
?>

Abilitazione della modifica front-end dei campi personalizzati

Abilitare la modifica del frontend per i tuoi nuovi campi personalizzati è abbastanza semplice. Per aggiungere i campi al modulo di modifica del contenuto del frontend, aggiungi semplicemente questo blocco di codice:

case 'com_contact':
	if ($app->isClient('site'))
	{
		JForm::addFormPath(__DIR__ . '/forms');
		$form->loadFile('contact', false);
	}
	return true;

Add that immediately below the existing instance of it.

Once you've got that done, create a template override for the content form edit.php file. If you're creating a set of custom fields for com_contact, you would copy /components/com_contact/views/form/tmpl/edit.php to /templates/your-template-name/html/com_contact/form/edit.php

Inside your layout override, add your new fields in the form where you want them to appear (e.g., below the title, below the description), making sure that the field names match the XML file from your plugin (you'll create this next).

<?php // Checking if this is an existing item or not ?>
<?php if ($this->item->id) : ?>
  <?php // If it is an existing item, get the attribs part of the existing record ?>
  <?php $attribs = json_decode($this->item->attribs); ?>
  <?php // Set the value of the custom field to what is already saved. ?>
  <?php // Duplicate for the number of fields you need, changing the field_name as needed. ?>
  <?php echo $this->form->setValue('field_name', 'attribs', $attribs->field_name); ?>
<?php endif; ?>
<?php // This line needs added to the file right where you want to display it. So, if you want it to show right after the description field, find the description field and place this right after it. Duplicate for the number of fields you need, changing the field_name as needed. ?>
<?php // Now we display the field. If we are editing an existing item, the previously saved data will be populated already ?>
<?php echo $this->form->renderField('field_name', 'attribs'); ?>

With that done, your fields will now appear and be stored via frontend editing.

The additional fields are loaded from the file forms/contact.xml in the plugin directory. It's important that these fields are in a fields element with the name property set to "params". If you don't set this property name, the fields will appear in the admin site but the values will not be saved. Note: In com_content your field must be named "<fields name="attribs">" otherwise the fields will appear in the admin site but the values will not be saved.

In this case we are adding a field for a label to describe the email field in the public website and a second field for the value of the email address.

<?xml version="1.0" encoding="UTF-8"?>
<form>
	<fields name="params">
		<fieldset name="params" label="PLG_CONTENT_EXAMPLE_FIELDSET_LABEL">
			<field
				name="contact_emaillabel2"
				type="text"
				label="PLG_CONTENT_EXAMPLE_CONTACT_EMAILLABEL2"
			/>
			<field
				name="contact_email2"
				type="text"
				label="PLG_CONTENT_EXAMPLE_CONTACT_EMAIL2"
				filter="email"
			/>
		</fieldset>
	</fields>
</form>

Finally we need a language file so that the parameters are presented nicely in the admin site and are translatable into different languages. This file needs to be called something like en-GB.plg_content_example.ini.

PLG_CONTENT_EXAMPLE_FIELDSET_LABEL="Additional Information"
PLG_CONTENT_EXAMPLE_CONTACT_EMAIL2="Additional email address"
PLG_CONTENT_EXAMPLE_CONTACT_EMAILLABEL2="Additional email label"

That's it for adding the field to com_contact. If you install this plugin, you'll have an additional tab in the contact editing form called "Additional Information" with the new fields included. If you fill in the new label and email address fields for a contact, you'll see that com_contact will store and retrieve the information for you.

The same plugin can be used to add more fields to different components; just add the relevant code into the onContentPrepareForm function and create the appropriate XML form files.

Displaying the Custom Field

To display the custom field you need to create a layout override for the relevant component in your template. For more details on creating templates see Creating a basic Joomla! template. For details on layout overrides, see Understanding Output Overrides.

Copy the file <Joomla>/components/com_contact/views/contact/tmpl/default.php to <template>/html/com_contact/contact/default.php, creating the folders in your template as necessary. We're going to edit this file to include the additional information. The com_contact component will automatically load the additional fields for us and load it into a variable called $this->params. All we need to do is check that the data is set and, if so, display it.

To display the field, find the location in <template>/html/com_contact/contact/default.php that corresponds to where you'd like the additional email address to be displayed and add the following code:

<?php if ($this->params->get('contact_emaillabel2', false)) : ?>
	<div>
		<span class="contact-additionalemail"><?php echo $this->params->get('contact_emaillabel2'); ?>:&emsp;<a href="mailto:<?php echo $this->params->get('contact_email2'); ?>"><?php echo $this->params->get('contact_email2'); ?></a><br/></span>
	</div>
<?php endif; ?>

If you add this code and install your template, you will now have the custom field displaying in your public Website.