Welcome, Guest
Username: Password: Remember me

TOPIC: Inject data to a form save

Inject data to a form save 04 Oct 2017 18:21 #15342

  • dyvel
  • dyvel's Avatar
  • Offline
  • Elite Member
  • Posts: 200
  • Thank you received: 11
  • Karma: 10
Hi

I have a form, where I like to add some additional info like user id to the form submission - this is data that should not be presented to the user as a form field.
In my view.html.php I can echo $model_client->getItems()->id and get the id I would like to add, but not sure how I pass it to the save function in the model.

Any help is appreciated :-)
The administrator has disabled public write access.

Inject data to a form save 04 Oct 2017 20:33 #15343

  • Romkabouter
  • Romkabouter's Avatar
  • Offline
  • Elite Member
  • Posts: 290
  • Thank you received: 125
  • Karma: 48
If you want the current userid save to the database, you can add the wizard "Author" to the table.
That will create a field "created_by" and "modified_by" for you :)
When submitting the form, that data will be filled.

In general for injecting data to the form, you have to fork the controller save() function.

Docs about forks: www.j-cook.pro/index.php/f/forks

First add the hidden field (i.e. yourfield) to the table, but not to the form.
When you have forked the controller file, add in that file:
	public function save($key = null, $urlVar = null)
	{
            //check for session
	    JSession::checkToken() or JSession::checkToken('get') or jexit(JText::_('JINVALID_TOKEN'));
            // get the form
	    $jinput = JFactory::getApplication()->input;
	    $data  = $jinput->post->get('jform', array(), 'array');
            $user = JFactory->getUser();
            //inject data
	    $data["yourfield"] = $user->id; //can be any data, depending on your needs 
            // set the post var
	    $jinput->post->set('jform',$data);
            // call save of the parent
 	    parent::save($key, $urlVar);
       }

Copy the form xml from models/forms/yourtable.xml to fork/models/forms/yourtable.xml
Remove all fields from the fieldset "yourtable.form" and add
		<field name="yourfield"
				alias="yourfield"
				label=""
				filter="INT"
				type="hidden"/>

By adding an extra field of type hidden, you should see that field as an hidden input on your form (check if it is).
Then, because you are calling parent::save the normal process will be executed (with saving the model to the database with your injected data)
The administrator has disabled public write access.
The following user(s) said Thank You: admin, dyvel

Inject data to a form save 04 Oct 2017 22:05 #15345

  • dyvel
  • dyvel's Avatar
  • Offline
  • Elite Member
  • Posts: 200
  • Thank you received: 11
  • Karma: 10
Thank you!
Your post was very helpfull - got it working :-)
The administrator has disabled public write access.
Time to create page: 0.079 seconds

Get Started