I'm developing custom component and I use Ajax for calling various tasks via controller.
I've one form, where user inputs data which should get validated before database transaction. I'm using JTable for interacting with database.
There are two ways to have Server-side validation:
1) Using Model by extending JModelForm and override validate() method of that form which can return a messages to JResponseJSon object in controller.
2) Overriding JTable's check() method which will check the data (and return messages to JResponseJson Object) before it get's store in database.
Both of the above methods validate data at Server-side. My question would be, what is the best way out of above two considering I'm using JResponseJson object to deal with my application in AJAX way.
Here is my controller Code:
/**
* Overrided Method to save a record.
*
* @return boolean True if successful, false otherwise.
*
* @since 12.2
*/
public function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$app = JFactory::getApplication();
$model = $this->getModel();
$helpdesk = $model->getTable();
$data = $this->input->post->get('jform', array(), 'array');
$key = $helpdesk->getKeyName();
$recordId = $this->input->getInt($key);
// Populate the row id from the session.
$data[$key] = $recordId;
// Access check.
if (!$this->allowSave($data, $key))
{
$this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $this->getRedirectToItemAppend()), JText::_('COM_HELPDESK_SAVE_ACCESS_ERROR'), 'warning');
return FALSE;
}
$response = $model->save($data);
// Attempt to save the data.
if ($response === false)
{
echo new JResponseJson($response, NULL, true);
$app->close();
}
$this->postSaveHook($model, $data);
if ($model->getState('request.new') == '1')
{
$recordId = (int) $model->getState('request.id');
// Set Success Message for New Request.
echo new JResponseJson(NULL, JText::sprintf('COM_HELPDESK_REQUEST_NEW_SAVE_SUCCESS', $recordId));
$app->close();
}
else
{
// Set Success Message for Existing Request.
echo new JResponseJson(NULL, JText::sprintf('COM_HELPDESK_REQUEST_EDIT_SAVE_SUCCESS', $recordId));
$app->close();
}
}
Here is my JTable's check method code:
/**
* Overloaded check function
*
* @return boolean True on success, false on failure
*
* @see JTable::check
* @since 1.5
*/
public function check()
{
$app = JFactory::getApplication();
$type = 'error';
$flag = true;
if (trim($this->subject) == '')
{
$app->enqueueMessage(JText::_('COM_HELPDESK_SUBJECT_ERROR'), $type);
$flag = false;
}
if (trim($this->description) == '')
{
$app->enqueueMessage(JText::_('COM_HELPDESK_DESCRIPTION_ERROR'), $type);
$flag = false;
}
if ($this->priority == 0)
{
$app->enqueueMessage(JText::_('COM_HELPDESK_PRIORITY_ERROR'), $type);
$flag = false;
}
return $flag;
}