JSON - Encode a group of fields

What is a JavaScript Object Notation (JSON) field ?

JSON is a formatted string representing a complex object.
It can represent arrays and classes in infinite structure.

ex :

{'animal':'cat','name':'garfield', 'companions' : [{'animal':'dog', 'name':'oscar'}, {'animal':'pig', 'name':'herman'}]}

Represents :

  • animal => cat
  • name => garfield
  • companions =>
    • [0]
      • animal => dog
      • name => oscar
    • [1]
      • animal => pig
      • name => herman

Coding with JSON

Javascript frameworks and PHP are parsing and decoding automatically. At your component level it is the same, you do not need to code anything.
Just understand that your datas can contain any shape for this field, and will be stored as a string in the database.

In javascript, the string contains also methods because object methods are readable such as object properties.
JSON is also used in PHP but the methods are not contained in the JSON string when you parse the class object.

Limitation of JSON

Once the datas are stored in JSON, you cannot make any searches or SQL queries on thoses fields. Let's say it is difficult and Cook is not here to make you life harder.
So, think well your application and store in JSON only :

  • the facultative fields
  • the specific parameters
  • the exhaustive datas that will not be searchable or filterable.

Storing in JSON can save you loads of space in the database memory.



How to create a JSON field in your component ?

1. In the builder, create a new JSON field in your table.

  1. Drag a JSON field to your fields list.
    Cook Builder Field type JSON

  2. Name it. (recommended name : 'attribs')
    Cook Builder Field Attribs

  3. Instance this field in the form.
    Cook Joomla instance JSON form
    This step is very important because it will register this field in the SQL select query.
    For the moment, the field will be ignored from the form.
  4. Download your component

2. Customize manually the object structure.

  1. Open the JForms XML file : 
    models/forms/mytable.xml
  2. Find the 'attribs' node and complete the object structure.

The XML markup created is fields, and the field name (attribs) is stored in its name attribute. (see example below)

Tip: you can copy paste the field declaration you want from other XML forms.

3. Instance this JSON fieldset in your template

That's it !

Your fieldset render automatically, and the datas are managed automatically.

Get Started