2

在我的 joomla 自定义组件中,我使用了 SQL 字段类型 (item.xml):

    <field name="colors" type="sql" query="SELECT id ,name FROM #__products_colors" multiple="multiple" key_field="id" value_field="name" class="inputbox"
         label="colors" description="COM_PRODUCTS_FORM_DESC_ITEM_COLORS" /> 

在我看来,我这样称呼这个领域:

<?php echo $this->form->getInput('colors'); ?>

这给了我一个漂亮而流畅的选择框,如下所示:

<select id="jform_colors" class="inputbox" multiple="multiple" name="jform[colors][]" aria-invalid="false">
<option value="1">blue</option>
<option value="2">yellow</option>
<option value="3">red</option>
<option value="4">green</option>
<option value="5">purple</option>

当我保存此颜色字段时,例如在选择蓝色和红色后,它会在我的数据库中保存为 1,3。Joomla 为我做所有的工作......(感谢 Joomla)

现在也许我变得贪婪了,但不知何故,当我在保存后编辑条目时,我希望 Joomla 为我预先选择这些值。它对所有其他类型的字段都这样做,那么为什么不在这里呢?有什么我忘记了吗?

谢谢你的建议!

编辑:答案中的绑定功能,我对其进行了一些调整。

    public function bind($array, $ignore = '') {
    if (isset($array['params']) && is_array($array['params'])) {
        $registry = new JRegistry();
        $registry->loadArray($array['params']);
        $array['params'] = (string) $registry;
    }
    //print_r($array);
    if (key_exists('colors', $array) && is_array($array['colors'])) {
        echo "pwn";
        $array['colors'] = implode(',', $array['colors']);
    }

    if (isset($array['metadata']) && is_array($array['metadata'])) {
        $registry = new JRegistry();
        $registry->loadArray($array['metadata']);
        $array['metadata'] = (string) $registry;
    }
    return parent::bind($array, $ignore);
}

并且不要使用 filter="safehtml" :)

祝大家好运!

4

2 回答 2

5

如果您遵循 Joomla 的标准,您的模型中应该有一个名为“loadFormData”的方法。在那里,您可以确定从数据库中获取该字段时将其转换为数组,例如:

<?php
protected function loadFormData()
{
    // Check the session for previously entered form data.
    $data = JFactory::getApplication()->getUserState('com_yourcomponent.edit.item.data', array());

    if (empty($data)) {
        $data = $this->getItem();
    }

    // THIS IS WHAT YOU MUST BE MISSING
    if (is_array($data) && !is_array($data['colors'])){
        $data['colors'] = explode(',',$data['colors']);
    } elseif (is_object($data) && !is_array($data->colors)) {
        $data->colors = explode(',',$data->colors);
    }

    return $data;
}
?>

您还需要在表类中覆盖您的绑定方法:

<?php
public function bind($src, $ignore = array())
{
    if (parent::bind($src, $ignore) && is_array($this->colors)){
        $this->colors = implode(',', $this->colors);
    }
}
于 2012-01-11T04:34:53.280 回答
0

我的数据存储的有点像 {"0":"3841","1":"3889"} 所以正确的转换代码是

$data->postcode = (array)json_decode($data->postcode);

谢谢你的解决方案,很有帮助。

于 2012-01-17T16:32:42.787 回答