I have to create multiple records at the same time using RESTful api. This is my code
i followed the code tutorial in this link http://www.yiiframework.com/wiki/175/how-to-create-a-rest-api
public function actionCreate()
{
switch($_GET['model'])
{
// Get an instance of the respective model
case 'exam':
$model = new Exam;
break;
case 'userexam':
$model= new Userexam;
break;
case 'userquestionanswer':
$model = new Userquestionanswer;
break;
default:
$this->_sendResponse(501,
sprintf('Mode <b>create</b> is not implemented for model <b>%s</b>',
$_GET['model']) );
Yii::app()->end();
}
// Try to assign POST values to attributes
$json=CJSON::decode(file_get_contents("php://input"));
foreach($json as $each){
$saved=true;
foreach($each as $var=>$value)
{
// Does the model have this attribute? If not raise an error
if($model->hasAttribute($var))
$model->$var = $value;
else
$this->_sendResponse(500,sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>',$var,
$_GET['model']));
}
// Try to save the model
if($model->save())
$saved=$saved && true;
else {
// Errors occurred
$saved=$saved && false;
$msg = "<h1>Error</h1>";
$msg .= sprintf("Couldn't create model <b>%s</b>", $_GET['model']);
$msg .= "<ul>";
foreach($model->errors as $attribute=>$attr_errors)
{
$msg .= "<li>Attribute: $attribute</li>";
$msg .= "<ul>";
foreach($attr_errors as $attr_error)
$msg .= "<li>$attr_error</li>";
$msg .= "</ul>";
}
$msg .= "</ul>";
$this->_sendResponse(500, $msg );
}
}
if($saved==true){
$this->_sendResponse(200,CJSON::encode(array('code'=>'200','message'=>'Record succesfully saved')));
}
}
and my json is
[{"title":"utyu","class":"5","examDate":"2013-07-15","dueDate":"2013-07-20","userId":"1","isActive":"0"},
{"title":"qwer","class":"5","examDate":"2013-07-15","dueDate":"2013-07-20","userId":"1","isActive":"0"}]
but when i execute this action only last object is added i.e.,
title =>qwer is only added but not "utyu".