如何从PHP动态生成表单的XML?


10

我需要根据用户的项目列表生成页面/表单。照原样,用户可以指定一个项目列表,这些项目具有该项目的文本说明,以及它是a text还是list字段类型。(想象一下可以检出的设备列表,并且要检查的项目列表随设备的类型而变化。肯定有一些共享项目,但是它们随设备类型,型号等而有所不同。)因此,可以简单地models\forms\添加一个新的字段集和一系列新的字段,而不是简单地从该文件夹中加载现有的XML文件并运行它。

如果是这样的话,

  1. 如何完成的?
  2. 正确的位置在哪里,以便MVC像对待“标准” XML格式一样对待它?
  3. 如何最好地检索这些字段的列表以在视图中显示?

models \ myform.php

$form = $this->loadForm('com_mycomponent.myform', 'myform', array('control' => 'jform', 'load_data' => $loadData));

控制器/myform.php

// Get the user data.
$data = JFactory::getApplication()->input->get('jform', array(), 'array');

// Validate the posted data.
$form = $model->getForm();
if (!$form) {
    JError::raiseError(500, $model->getError());
    return false;
}
...
// Validate the posted data.
$data = $model->validate($form, $data);
...
// Attempt to save the data.
$return = $model->save($data);

Answers:


4

我正在使用jForm和方法setField()以及getFieldset()设置和检索字段,但是Joomla引发了错误。在尝试添加listJoomla 之前,我无法解析XML,直到我添加了option_on="Yes"option_off="Yes"。(我不确定这些是什么/为什么是必要的,但是使用它们,下面的代码可以工作)。

models \ myform.php

 public function getForm($data = array(), $loadData = true)
{
    // Get the form.
    $form = $this->loadForm('com_mycomponent.mymodel', 'myform', array('control' => 'jform', 'load_data' => $loadData));
    if (empty($form)) {
        return false;
    }
    $element = new SimpleXMLElement('<fieldset name="myFieldset">
        <field name="myfield1" type="list"
        label="My List"
        default="2"
        option_on="Yes"
        option_off="Yes">
        <option value="1">Low</option>
        <option value="2">Normal</option>
        <option value="3">High</option>
        </field>
        <field name="myfield2" type="text" label="My field 1" class="inputbox" size="30" />
        <field name="myfield3" type="text" label="My field 2" class="inputbox" size="30" />
    </fieldset>');
    $form->setField($element);
    return $form;
}

views / myview / tmpl / default.php

$this->form->getFieldset('myFieldset'), true)
// Loop through these results and display them accordingly
$myFieldset = $this->form->getFieldset('myFieldset');
if(count($myFieldset)){
    foreach($myFieldset as $field) {
        $field_name = $field->getAttribute('name');
        echo $this->form->getLabel($field_name);
        echo $this->form->getInput($field_name);
    }

}

控制器/ myview.php

// Get the user data.
$data = JFactory::getApplication()->input->get('jform', array(), 'array');
/* $data DOES contain my input fields*/
// The model/table doesn't contain columns for my custom fields, so the data to be saved has to be manipulated here to "go somewhere permanent".

// Validate the posted data.
$form = $model->getForm();
/* $form DOES contain my input fields*/
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.