Afegir camps personalitzats als components bàsics utilitzant un plugin

From Joomla! Documentation

Revision as of 04:40, 15 May 2019 by FuzzyBot (talk | contribs) (Updating to match new version of source page)
Other languages:
Deutsch • ‎English • ‎Nederlands • ‎català • ‎español • ‎français • ‎italiano • ‎português do Brasil • ‎русский • ‎فارسی • ‎हिन्दी • ‎বাংলা • ‎中文(台灣)‎

Alguna vegada ha desitjat que hi hagués un camp addicional per al número de telèfon, al com_contact? o ha necessitat un camp addicional per als articles al com_content? Joomla! proporciona una forma senzilla per a la integració de camps nous en components del nucli. Tot el que necessita per aconseguir-ho és un simple plugin de contingut i un override per a la disposició de la plantilla.

Aquest article mostra com afegir un camp addicional per a un component del nucli, utilitzant l'exemple d'afegir una adreça de correu electrònic addicional als contactes del com_contact.

Afegir un Camp Personalitzat

Es recomana llegir primer Creació d'un Plugin per Joomla! per a més detalls sobre com crear i instal·lar un plugin, el qual no es tractarà aquí.

Per afegir un camp a un component del sistema, necessita crear un plugin de continguts que reculli l'esdeveniment onContentPrepareForm i inserir els camps que consideri al JForm. El següent codi és per Joomla 3.1 i versions posteriors. Per Joomla! 2.5, necessita carregar els arxius d'idioma al constructor (veure J2.5: Crear un Plugin per Joomla).

<?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->isAdmin())
				{
					JForm::addFormPath(__DIR__ . '/forms');
					$form->loadFile('contact', false);
				}

				return true;
		}

		return true;
	}
}
?>

Enabling Front End Editing of Custom Fields

Enabling Frontend editing for your new custom fields is pretty easy. To add the fields to the frontend content edit form, simply add this block of code:

case 'com_contact':
	if ($app->isSite())
	{
		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.

Els camps addicionals es carreguen des de l'arxiu forms/contact.xml en el directori plugins. És important que aquests camps es trobin en un camp amb el nom de la propietat establerta a "params". Si no estableix aquest nom de propietat, apareixeran els camps en el lloc d'administració, però no es guardaran els valors.

En aquest cas estem afegint un camp d'una etiqueta per descriure el camp de correu electrònic al lloc web públic i un segon camp per al valor de l'adreça de correu electrònic.

<?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>

Finalment, necessitem un arxiu d'idioma perquè els paràmetres es vegin bé en el lloc d'administració i es puguin traduir a diferents idiomes. Aquest fitxer s'ha d'anomenar una mena de ca-ES.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"

Això és tot el que ha de fer per afegir un camp per com_contact. Si instal·leu aquest plugin, tindreu una pestanya addicional en el formulari d'edició de contactes amb el nom "Informació addicional" amb els nous camps inclosos. Si s'omplen aquests camps d'etiqueta i adreça de correu electrònic per al contacte, veurà que com_contact guardarà i recuperarà la informació correctament.

El mateix plugin es pot utilitzar per afegir més camps a diferents components; només ha d'afegir el codi corresponent a la funció onContentPrepareForm i crear els arxius apropiats al formulari XML.

Visualització del camp personalitzat

Per mostrar el camp personalitzat necessita crear un override de disposició per al component rellevant en la seva plantilla. Per a més detalls sobre la creació de plantilles vegeu Creació d'una plantilla bàsica per Joomla!. Per a més detalls sobre els overrides de disposició, veure Entendre els Overrides de sortida.

Cal copiar el fitxer <Joomla>/components/com_contact/views/contact/tmpl/default.php a <template>/html/com_contact/contact/default.php per crear les carpetes a la plantilla. Editarem aquest arxiu per incloure la informació addicional. El component com_contact carregarà automàticament els camps addicionals i ho farà amb la variable anomenada $this->params. Tot el que necessitem fer és comprovar que les dades s'han establert i, si és així, els mostrarà.

Per mostrar el camp, trobi la ubicació a<template>/html/com_contact/contact/default.php que correspon al lloc on vol mostrar l'adreça de correu electrònic addicional, i afegiu el següent codi:

<?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; ?>

Si afegeix aquest codi a la plantilla, tindrà el camp personalitzat visible al lloc web públic.