I have set up this method for updating a model via AJAX, and have tried to extend it by also creating a new model if it doesn’t exist.
public function actionAjaxUpdate($id = null)
{
if($id === null)
$model = new MyObject;
else
$model = $this->loadModel($id);
if(isset($_POST['MyObject']))
{
$model->attributes = $_POST['MyObject'];
$model->save();
}
}
Sample URLs sent when updating via AJAX, the digits at the end being the model ID:
/admin/myObject/ajaxUpdate/1
/admin/myObject/ajaxUpdate/2
/admin/myObject/ajaxUpdate/3
...
The problem here is that while updating works fine as an ID is provided, creating a new model doesn’t work. Because the ID does not exist yet for new items, the URL route will return a 404:
The requested URL /cmsadmin/myObject/ajaxUpdate was not found on this
server.
What would be a good approach to solving this problem?
I have tried overloading the same method without the $id parameter, but PHP does not support overloading, as discussed in this thread: Method overloading in a model of Yii framework
Please leave a comment if any additional information is required.
==== Additional Information ====
main.php
<?php
$backend = dirname(dirname(__FILE__));
$frontend = dirname($backend);
Yii::setPathOfAlias('admin', $backend);
return array(
'basePath' => $frontend,
'controllerPath' => $backend . '/controllers',
'viewPath' => $backend . '/views',
'runtimePath' => $backend . '/runtime',
'components' => array(
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'caseSensitive' => false,
'appendParams' => true,
'rules' => array(
'admin/<controller:\w+>/<action:\w+>/<id:\d+>'=>'/<controller>/<action>',
'admin/<controller:\w+>/<action:\w+>'=>'/<controller>/<action>',
...
I had the same problem but I passed in the
id=0for insert andid=1for update. Make sure the id field is set to auto-increment so it is not required.Now check if id is 1 then do insert else update the record.