Back to Form class

Method getInstance

public static \Joomla\CMS\Form\Form
getInstance
(mixed $name, mixed $data = null, mixed $options = [], mixed $replace = true, mixed $xpath = false)
Method to get an instance of a form.
Parameters
  • string $name The name of the form.
  • string $data The name of an XML file or string to load as the form definition.
  • array $options An array of form options.
  • bool $replace Flag to toggle whether form fields should be replaced if a field already exists with the same group/name.
  • string|bool $xpath An optional xpath to search for the fields.
Returns
  • \Joomla\CMS\Form\Form Form instance.
Since
  • 1.7.0
Deprecated
  • 5.0
-
  • \InvalidArgumentException if no data provided.
  • \RuntimeException if the form could not be loaded.
Class: Form
Project: Joomla

Method getInstance - Source code

/**
 * Method to get an instance of a form.
 *
 * @param   string          $name     The name of the form.
 * @param   string          $data     The name of an XML file or string to load as the form definition.
 * @param   array           $options  An array of form options.
 * @param   boolean         $replace  Flag to toggle whether form fields should be replaced if a field
 *                                    already exists with the same group/name.
 * @param   string|boolean  $xpath    An optional xpath to search for the fields.
 *
 * @return  Form  Form instance.
 *
 * @since   1.7.0
 * @deprecated  5.0 Use the FormFactory service from the container
 * @throws  \InvalidArgumentException if no data provided.
 * @throws  \RuntimeException if the form could not be loaded.
 */
public static function getInstance($name, $data = null, $options = [], $replace = true, $xpath = false)
{
    // Reference to array with form instances
    $forms =& self::$forms;
    // Only instantiate the form if it does not already exist.
    if (!isset($forms[$name])) {
        $data = trim($data);
        if (empty($data)) {
            throw new \InvalidArgumentException(sprintf('%1$s(%2$s, *%3$s*)', __METHOD__, $name, \gettype($data)));
        }
        // Instantiate the form.
        $forms[$name] = Factory::getContainer()->get(FormFactoryInterface::class)->createForm($name, $options);
        // Load the data.
        if (substr($data, 0, 1) === '<') {
            if ($forms[$name]->load($data, $replace, $xpath) == false) {
                throw new \RuntimeException(sprintf('%s() could not load form', __METHOD__));
            }
        } else {
            if ($forms[$name]->loadFile($data, $replace, $xpath) == false) {
                throw new \RuntimeException(sprintf('%s() could not load file', __METHOD__));
            }
        }
    }
    return $forms[$name];
}