4

I need help to store data in json format in my DB like {name:'1', name2:'2'}.

So far I have this:

model/form/category.xml:

<fieldset>
    <field
        name="name"
        type="text"
        label="name"
    />
    <field
        name="name2"
        type="text"
        label="name"
    />
</fieldset>

view/category/tmpl/edit.php:

<?php echo $this->form->getInput('name'); ?></li>
<?php echo $this->form->getInput('name2'); ?></li>

I need to send these 2 fields as a json-encoded string into 1 DB field.

3

You need both PHP functions to do this work:

json_encode :

http://www.php.net/manual/de/function.json-encode.php

json_decode:

http://www.php.net/manual/de/function.json-decode.php

Maybe something like this:

<?php
$arr = array ();
$arr[name] = $this->form->getInput('name');
$arr[name2] = $this->form->getInput('name2');     
echo json_encode($arr);
?>
  • 1
    It's not the answer. Joomla uses MVC and you didn't show what code should be placed in model and view/tmpl – stckvrw May 19 '15 at 19:14
1

Enclose those two fields in a element in your form xml file.

<fields label="COM_COMPONENTNAME_FIELDNAME_FIELDSET_LABEL" name="fieldname">
  <fieldset label="COM_COMPONENTNAME_FIELDNAME_FIELDSET_LABEL" name="basic">
     <field name="name" type="text" label="name"/>
     <field name="name2" type="text" label="name"/>
  </fieldset>
</fields>

Now the both fields will go as json data into the table column "fieldname" (change it to your actual fieldname)

-1

json_decode on Model->getItem()

json_encode on Model->save()

class CompModelName extends JModelAdmin
{

    public function save($data = array())
    {
        if(isset($data['prices']) && is_array($data['prices'])) $data['prices']=json_encode($data['prices']);
        return parent::save($data);
    }

    public function getItem($pk = null)
    {
        if (!$item = parent::getItem($pk))
        {           
            throw new Exception('Failed to load item');
        }
        $item->prices=json_decode($item->prices,true);
        return $item;
    }
}
  • Could you possibly include a bit more explanation about why this solution is appropriate and uses best practices? I don't know if this is a working solution and I wish the downvoter would would have had the courage to leave a comment, but this is nearly a code-only answers. Code-only answers are low value on Stack Exchange sites because they do very little to educate/empower thousands of future researchers. – mickmackusa Mar 20 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.