3

I have developed a code to create dynamic textboxes on click of "Add" button using javascript -

Javascript

function GetDynamicTextBox(value,index) {
    return
     '<input type="text" name="jform[options][]" id="jform_options_'+index+'" value="">' +
       '<input type="button" value="Remove" class="remove btn-danger" />'
}

formname.xml

<field name="options][" type="text" label="Options" multiple="true" description=""></field>

When I click on Add button , it will append n number of textboxes . But I am facing a problem in saving this field in database.

database

columnname = options, type= text

I want to save the values entered in textboxes in form of json. For this I am trying to override the controller save method-

controllername.php

public function save($key = null, $urlVar = null){

    if($_POST['jform']){
        $jinput = JFactory::getApplication()->input;
        $postData = $jinput->post->get('jform', array(), 'array');
            $postData['options']=json_encode(implode(',',$postData['options'])); 
        // Save it back to the $_POST global variable
        JRequest::setVar('jform', $postData, 'post');
    }
    // Finally, save the processed form data
    return parent::save('id', $urlVar);
}

But all the rest values in the form are saving but not the "options field." - Note: you can see the image attached to understand what i am trying to achieveenter image description here

  • Any help would be appreicated

2 Answers 2

2

You can do it using prepareTable in the model of your component. Check this example out where I get an the values of array of checkboxes "categories" and then save them creating a comma separated values variable using implode.

Instead of course, you may use json_encode.

protected function prepareTable($table)
{
    // Set the publish date to now
    $db = $this->getDbo();

    if($table->id==0)
    {
        $table->created = JFactory::getDate()->toSql();
    }

    $table->modified = JFactory::getDate()->toSql();

    $jinput = JFactory::getApplication()->input;


    $categories = $jinput->get('categories',null,'ARRAY');

    if($categories!=null)
        $table->categories = implode(",",$categories);
    else 
        $table->categories ='';


}
0

you must save options as array json in database so change this line

  $postData['options']=json_encode(implode(',',$postData['options'])); 

to

  $postData['options']=json_encode($postData['options']); 

then in loadFormData method in your model , you need to use json_decode for decode your array

also you can use Repeatable field type for your form , and if you set name of your field as params , the all the jobs will be handled by joomla

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.