Yii layout doesn't get applied to view - php

I'm having this problem where a view is not being run through the layout on the server, but in a local instance it works just fine without any changes. There are actually two views that have this problem, 'index' view and 'update' and 'create' view. Both of these views are partially rendering another view, 'index' is partially rendering '_view' and 'update' and 'create' are partially rendering '_form'. In the controller I'm specifying what layout should be used to render the views and made sure that the layout is not being overwritten from the action that handles each view. The code in question is as follows:
index.php
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
_view.php
<div class="well">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('naslov')); ?>:</b>
<?php echo CHtml::encode($data->naslov); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('category_id')); ?>:</b>
<?php
$cat = Category::model()->findByPk($data->category_id);
$parent = $cat->parent()->find();
$c = $parent->title." / ".$cat->title;
echo CHtml::encode($c); ?>
<br />
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('image_path')); ?>:</b>
<?php echo CHtml::encode($data->image_path); ?>
<br />
</div>
update.php and create.php
<?php $this->renderPartial('_form', array('model'=>$model)); ?>
_form.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'news-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
)); ?>
// form code
<?php $this->endWidget(); ?>
and in the controller that extends a base controller i define which layout is to be used
public $layout='//layouts/column2';
I've looked through the application.log file trying to find anything that might cause this but didn't find anything.
EDITED:
Here is the controller Create action:
public function actionCreate() {
$model = new News;
if (isset($_POST['News'])) {
$model->attributes = $_POST['News'];
$model->body = $_POST['News']['body'];
$model->author = Yii::app()->user->id;
$model->meta_description = $_POST['News']['meta_description'];
$path = $this->upload_path;
$image_temp = CUploadedFile::getInstance($model, 'image_path');
$new_image_ext = pathinfo($image_temp, PATHINFO_EXTENSION);
$new_image_subpath = uniqid(rand(), true) . '.' . $new_image_ext;
$new_image_subpath = substr($new_image_subpath, 0, 1) . '/' . substr($new_image_subpath, 1, 1) . '/' . $new_image_subpath;
$new_image_path = $path . $new_image_subpath;
$model->image_path = $new_image_subpath;
if (!file_exists(dirname($new_image_path))) {
mkdir(dirname($new_image_path), 0777, true);
}
}
if ($model->save()) {
$image_temp->saveAs($new_image_path, false);
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('create', array(
'model' => $model,
));
}
And the Update action:
public function actionUpdate($id) {
$model = $this->loadModel($id);
$this->pageTitle = "Vesti - Izmena vesti: " . $model->naslov . "";
if (isset($_POST['News'])) {
$model->attributes = $_POST['News'];
$model->body = $_POST['News']['body'];
$model->modified_on = date("d-m-y H:m:s");
$model->meta_description = $_POST['News']['meta_description'];
$model->attributes = $_POST['News'];
if ($_FILES['News']['name']['image_path'] != "") {
$uploadedFile = CUploadedFile::getInstance($model, 'image_path');
$path = $this->upload_path;
$image_temp = CUploadedFile::getInstance($model, 'image_path');
$new_image_ext = pathinfo($image_temp, PATHINFO_EXTENSION);
$new_image_subpath = uniqid(rand(), true) . '.' . $new_image_ext;
$new_image_subpath = substr($new_image_subpath, 0, 1) . '/' . substr($new_image_subpath, 1, 1) . '/' . $new_image_subpath;
$new_image_path = $path . $new_image_subpath;
$model->image_path = $new_image_subpath;
if (!file_exists(dirname($new_image_path))) {
mkdir(dirname($new_image_path), 0777, true);
}
} else {
unset($model->image_path);
}
if ($model->save()) {
if ($_FILES['News']['name']['image_path'] != "") {
$image_temp->saveAs($new_image_path, false);
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('update', array(
'model' => $model,
));
}
And the _form view:
<script type="text/javascript">
function showSEOServices() {
$("#seo_options").slideToggle();
}
function slugPopulate(s, d, a) {
if(a==1) {
var d = $("#News_category_id").val();
} else {
var s = $("#News_naslov").val();
}
$.ajax({
type: "GET",
url: 'index.php?r=news/slug',
data: "s=" + s + "&d=" + d,
success: function(data) {
$("#News_url_slug").val(data);
}
});
}
</script>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'news-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
)); ?>
<p class="note">Polja sa <span class="required">*</span> su obavezna.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'naslov'); ?>
<?php echo $form->textField($model,'naslov',array('size'=>60,'maxlength'=>255, 'onChange' => "slugPopulate(this.value, '', 1);")); ?>
<?php echo $form->error($model,'naslov'); ?>
</div>
<div class="row">
Top sekcija:<br>
<?php echo $form->checkBox($model,'top_section'); ?>
</div>
<div class="row">
Normalna sekcija:<br>
<?php echo $form->checkBox($model,'normal_section'); ?>
</div>
<div class="row">
Donja sekcija:<br>
<?php echo $form->checkBox($model,'bottom_section'); ?>
</div>
<div class="row">
Boja članka u listingu:<br>
<?php if($model->isNewRecord!='1'){ ?>
<input type="color" name="News[news_color]" id="News_news_color" value="<?php echo $model->news_color; ?>">
<?php } else { ?>
<input type="color" name="News[news_color]" id="News_news_color" value="">
<?php } ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'body'); ?>
<?php $this->widget('ext.editMe.widgets.ExtEditMe', array(
'model'=>$model,
'attribute'=>'body',
)); ?>
<?php echo $form->error($model,'body'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'category_id'); ?>
<?php echo $form->dropDownList($model, 'category_id', $model->getCategoryOptions(),array('onChange' => "slugPopulate('', this.value, 2);")); ?>
<?php echo $form->error($model,'category_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'image_path'); ?>
<?php echo CHtml::activeFileField($model, 'image_path'); ?>
<?php echo $form->error($model,'image_path'); ?>
</div>
<!-- FOTOGRAFIJA -->
<?php if($model->isNewRecord!='1'){ ?>
<div class="row">
<?php echo CHtml::image('/resources/uploads/news/'.$model->image_path,"image",array("width"=>200, "class" => "img-thumbnail")); ?>
</div>
<?php } ?>
<!-- FOTOGRAFIJA END -->
<!-- SEO opcije -->
<button type="button" onClick="showSEOServices()" class="btn btn-labeled btn-default">
<span class="btn-label"><i class="fa fa-map-marker"></i> </span>Prikaži opcije za SEO
</button>
<div id="seo_options" class="alert alert-info" style="display:none;">
<div class="row">
<?php echo $form->labelEx($model,'url_slug'); ?>
<?php echo $form->textField($model,'url_slug',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'url_slug'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'meta_title'); ?>
<?php echo $form->textField($model,'meta_title',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'meta_title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'meta_description'); ?>
<?php echo $form->textArea($model,'meta_description',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'meta_description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'meta_keywords'); ?>
<?php echo $form->textField($model,'meta_keywords',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'meta_keywords'); ?>
</div>
</div>
<!-- SEO opcije kraj -->
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->dropDownList($model, 'status', $model->getStatusOptions()); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row buttons">
<button class="btn btn-success ladda-button" data-style="expand-right"><span class="ladda-label">Sačuvaj</span></button>
<?php //echo CHtml::submitButton($model->isNewRecord ? 'Kreiraj' : 'Sačuvaj', array("class" => "btn btn-success ladda-button", "data-style" => "expand-right")); ?>
</div>
<?php $this->endWidget(); ?>

Related

yii - insert data into two tables via single form

I am very much a novice with PHP and the Yii framework.
Click here to see a sample of my SQL database setup http://i.stack.imgur.com/W6qQj.png
I have set up controllers and models for all three tables and have set up CRUD views from Gii for the Users table. I have read through this -> http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models/ and tried multiple sets of code examples etc... and failed. The best I can do is get the create form to insert all the data into the users table but not the email table. I believe my short coming is in my UsersController.php -> public function actionCreate() section. Can someone help me out with a sample piece of code to make the information post into the email table?
---EDIT---
As requested below is the requested info...
UsersController.php
public function actionCreate()
{
$model = new Users;
if (isset($_POST['Users'])) {
$model->attributes = $_POST['Users'];
$model->password=crypt($model->password,'salt');
$model->datecreated = new CDbExpression('NOW()');
if ($model->save()) {
$modelEmail = new Email;
$modelEmail->attributes = $_POST['Email'];
$modelEmail->fer_users_id = $model->id;
if ($modelEmail->save())
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
This is the users/_form.php view file:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'firstname'); ?>
<?php echo $form->textField($model,'firstname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'firstname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastname'); ?>
<?php echo $form->textField($model,'lastname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'lastname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx(Email::model(),'emailaddress'); ?>
<?php echo $form->textField(Email::model(),'emailaddress',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error(Email::model(),'emailaddress'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'fer_roles_id'); ?>
<?php
echo $form->dropDownList($model, 'fer_roles_id',
CHtml::listData(Roles::model()->findAll(), 'id', 'description'),
array('class' => 'my-drop-down', 'options' => array('2' => array('selected' => "selected")
)
)
);
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
you could do this:
Controller:
<?php
public function actionCreate()
{
$model = new Users;
$model1 = new Email;
$roles = Roles::model()->findAll();
if(isset($_POST['Users']))
{
$model->attributes = $_POST['Users'];
$model->password = crypt($model->password, 'salt');
$model->datecreated = new CDbExpression('NOW()');
$model->save();
$model1->attributes = $_POST['Users']['emailaddress'];
$model1->fer_users_id = $model->id;
$model1->save();
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('create', array(
'user'=>$model,
'email'=>$model1,
'roles'=> $roles
));
}
?>
your view:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($user); ?>
<div class="row">
<?php echo $form->labelEx($user,'username'); ?>
<?php echo $form->textField($user,'username',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'password'); ?>
<?php echo $form->passwordField($user,'password',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'firstname'); ?>
<?php echo $form->textField($user,'firstname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'firstname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'lastname'); ?>
<?php echo $form->textField($user,'lastname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'lastname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($email,'emailaddress'); ?>
<?php echo $form->textField($email,'emailaddress',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($email,'emailaddress'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'fer_roles_id'); ?>
<?php
echo $form->dropDownList($user, 'fer_roles_id',
CHtml::listData($roles, 'id', 'description'),
array('class' => 'my-drop-down', 'options' => array('2' => array('selected' => "selected")
)
)
);
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($user->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
if you get any error with this, let me know..

Updating Fields on a form with ajax and json

I want to update some fields in my form, after retrieving data from a db using ajax & json.
This is the code:
In my form:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'anagrafica-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'codicefiscale'); ?>
<?php echo $form->textField($model,'codicefiscale',array('size'=>20,'maxlength'=>16)); ?>
<?php echo $form->error($model,'codicefiscale'); ?>
<div id="bottone_ricerca" style="display:inline;">
<?php
echo CHtml::ajaxButton( 'Ricerca',
$this->createUrl('anagrafica/popolaAnagrafica'),
array(
'type' => 'POST',
'datatype' => 'json',
'data' => array('codfisc' => 'js:$(\'#AnagraficaForm_codicefiscale\').val()'),
'success' => 'function(response){
$("#cand").html(response);
$("#'.CHTML::activeId($model,'cognome').'").val(response.cognome);
$("#'.CHTML::activeId($model,'nome').'").val(response.nome);
$("#'.CHTML::activeId($model,'email').'").val(response.email);
}'
),
array()
);
?>
</div>
<div id="cand">
</div>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cognome'); ?>
<?php echo $form->textField($model,'cognome',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'cognome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nome'); ?>
<?php echo $form->textField($model,'nome',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'nome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'indirizzo'); ?>
<?php echo $form->textField($model,'indirizzo',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'indirizzo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cap'); ?>
<?php echo $form->textField($model,'cap',array('size'=>10,'maxlength'=>5)); ?>
<?php echo $form->error($model,'cap'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'comune'); ?>
<?php echo $form->textField($model,'comune',array('size'=>25,'maxlength'=>20)); ?>
<?php echo $form->error($model,'comune'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'provincia'); ?>
<?php echo $form->textField($model,'provincia',array('size'=>5,'maxlength'=>2)); ?>
<?php echo $form->error($model,'provincia'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'telefono'); ?>
<?php echo $form->textField($model,'telefono',array('size'=>20,'maxlength'=>15)); ?>
<?php echo $form->error($model,'telefono'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Inserisci'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
In my controller:
public function actionPopolaAnagrafica()
{
$codfisc = Yii::app()->request->getParam('codfisc');
echo $codfisc;
if (Yii::app()->request->isAjaxRequest) {
if ($codfisc == '') {
echo CJSON::encode(array(
'error' => 'true',
'status' => 'Richiesta non valida.'
));
Yii::app()->end();
} else {
//$sql = "SELECT * FROM user WHERE username = ':codfisc'";
$sql = "SELECT * FROM user WHERE username = '".$codfisc . "'";
$cmd = Yii::app()->db->createCommand($sql);
//$cmd->bindParam(":codfisc", $codfisc, PDO::PARAM_STR);
$result = $cmd->queryRow();
$sql2 = $cmd->text;
if($result) {
echo CJSON::encode(array(
'error' => 'false',
'status' => 'Codice Fiscale esistente',
'username' => $result['username'],
'cognome' => $result['cognome'],
'nome' => $result['nome'],
'email' => $result['email']
)
);
Yii::app()->end();
} else {
echo CJSON::encode(array(
'error' => 'true',
'status' => 'Il codice fiscale ' . $codfisc . ' non esiste. SQL = ' . $sql2 . '.'
));
Yii::app()->end();
}
}
}
I can't update fields. The response is:
xxxyyyddxdd{"error":"false","status":"Codice Fiscale
esistente","username":"xxxyyyddxdd","cognome":"Cognome","nome":"Nome","email":"prova#email.it"}
but it should be:
{"error":"false","status":"Codice Fiscale
esistente","username":"xxxyyyddxdd","cognome":"Cognome","nome":"Nome","email":"prova#email.it"}
Where's my mistake?
Thanks
You need to remove the following line:
echo $codfisc;
(second line in function actionPopolaAnagrafica)
public function actionPopolaAnagrafica()
{
$codfisc = Yii::app()->request->getParam('codfisc');
//this LINE!!!!!!!!!!!!!!!!!!!!!!!
echo $codfisc;
Change :
'success' => 'function(response){
$("#cand").html(response);
$("#'.CHTML::activeId($model,'cognome').'").val(response.cognome);
With this :
'success' => 'function(response){
$("#cand").html(response);
var obj = jQuery.parseJSON( response );
console.log(obj.cognome);
$("#'.CHTML::activeId($model,'cognome').'").val(obj.cognome);
Parse JSON data before you put in HTML value.
Use console.log(obj.cognome); to debug value in chrome.

How to Update a field based on the submit button - Yii

I'm new to Yii framework. I have to create three buttons in my form (update.php). i.e. (Save, Approve, Reject). I'm using the following fields in my form.
<?php
/* #var $this MessageTemplateController */
/* #var $model MessageTemplate */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'message-template-form',
'enableAjaxValidation'=>false,
)); ?>
<?php
echo $form->errorSummary($model);
?>
<div class="row">
<?php //$model->ReviewedDate=date('Y-m-d H:i:s');?>
<?php echo $form->labelEx($model,'ReviewedDate'); ?>
<?php echo $form->textField($model,'ReviewedDate',array('value'=>'0000-00-00 00:00:00','readonly' => true)); ?>
<?php echo $form->error($model,'ReviewedDate'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'SmsText'); ?>
<?php echo $form->textArea($model,'SmsText',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'SmsText'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'UpdatedDate'); ?>
<?php echo $form->textField($model,'UpdatedDate'); ?>
<?php echo $form->error($model,'UpdatedDate',array('value'=>date('Y-m-d H:i:s'),'readonly' => true)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Approved'); ?>
<?php echo $form->hiddenField($model, 'Approved'); ?>
<?php echo $form->error($model,'Approved'); ?>
</div>
<div class="row">
<div class="row">
<?php echo $form->labelEx($model_al, 'username'); ?>
<?php $identity=Yii::app()->user->name;?>
<?php echo $form->textField($model_al, 'username',array('value'=>$identity,'readonly' => true), array('size' => 60, 'maxlength' => 250)); ?>
<?php echo $form->error($model_al, 'username'); ?>
<div>
<div class="row">
<?php echo $form->labelEx($model_al, 'updatedtime'); ?>
<?php echo $form->textField($model_al, 'updatedtime',array('value'=>date('Y-m-d H:i:s'),'readonly' => true), array('size' => 60, 'maxlength' => 250)); ?>
<?php echo $form->error($model_al, 'updatedtime'); ?>
<div>
<div class="row">
<?php echo $form->labelEx($model_al, 'comments on approval/rejection'); ?>
<?php echo $form->textField($model_al, 'comments',array('size' => 60, 'maxlength' => 250)); ?>
<?php echo $form->error($model_al, 'comments'); ?>
<div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save', array('name' => 'save')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Accept', array('name' => 'accept')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Reject', array('name' => 'reject')); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Now I have created three buttons.There is a field called approved in the above form.
I want this actions to happen when i click on the following buttons :
1. Save - All fields have to be saved but not approved(keep it as default).
2. Accept - All fields have to be saved with Approved changing to 1 in database.
3. Reject - All fields have to be saved with Approved changing to 0 in database.
How can I do this.
EDit
I have added the following in my controller.
public function actionUpdate($id)
{
$model_mt=new Messagesintable;
$model_al=new AuditLogin;
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['MessageTemplate']) && isset($_POST['AuditLogin']))
{
$model->attributes=$_POST['MessageTemplate'];
list($name,$mobile,$email)=retrieve_persondetails($id);
if($model->save())
{
$model_al->attributes=$_POST['AuditLogin'];
if ($model_al->save())
$this->redirect(array('admin','id'=>$model->Id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
You can check whether which submit button is clicked with these conditions and write your action inside.
if($_POST) {
if (isset($_POST['Save'])) {
// your code here
}
if (isset($_POST['Accept'])) {
// your code here
}
if (isset($_POST['Reject'])) {
// your code here
}
}

internal server Error when load ajax in yii

I had problem in loading Ajax , I knew that by got screanshot of request by
Tamper Data :
http://up.arabseyes.com/uploads/02_12_1213544389861.jpg
result was : internal server Error .
What is the problem in my code ?
View :
<?php
/* #var $this UsersController */
/* #var $model Users */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-index-form',
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'الأسم الأول'); ?>
<?php echo $form->textField($model,'first_name'); ?>
<?php echo $form->error($model,'الأسم الاول'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'العائلة'); ?>
<?php echo $form->textField($model,'last_name'); ?>
<?php echo $form->error($model,'العائلة'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'كلمة المرور'); ?>
<?php echo $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'تأكيد كلمة المرور'); ?>
<?php echo $form->passwordField($model,'passwordconfirm'); ?>
<?php echo $form->error($model,'passwordconfirm'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'البريد الإلكتروني '); ?>
<?php echo $form->textField($model,'email'); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'تأكيد البريد الإلكتروني'); ?>
<?php echo $form->textField($model,'emailconfirm'); ?>
<?php echo $form->error($model,'emailconfirm'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'تاريخ الميلاد'); ?>
<?php
$this->widget(
'ext.jui.EJuiDateTimePicker',
array(
'model' => $model,
'attribute' => 'birth_date',
'language'=> 'en',//default Yii::app()->language
'mode' => 'date',//'datetime' or 'time' ('datetime' default)
'options' => array(
'dateFormat' => 'yy-mm-dd',
//'timeFormat' => '',//'hh:mm tt' default
),
)
);
?>
<?php echo $form->error($model,'birth_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'الجنس'); ?>
<?php echo chtml::activeDropDownList($model,'gender',$model->getStatusOption(),array('prompt'=>'أختر جنسك')
); ?>
<?php echo $form->error($model,'gender'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'البلد'); ?>
<?php
/*
echo chtml::activeDropDownList($model,'country',$model->getcountry(),array('prompt'=>'اختر بلدك ') ,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('current/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
))
);
*/
echo CHtml::activedropDownList($model,'country',$model->getcountry(),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('Register/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
))
);
?>
<?php echo $form->error($model,'country'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'المدينة'); ?>
<?php
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city','', array());
?>
<?php echo $form->error($model,'city'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'رمز الاتصال'); ?>
<?php echo $form->textField($model,'mobile_code'); ?>
<?php echo $form->error($model,'mobile_code'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'رقم الجوال'); ?>
<?php echo $form->textField($model,'mobile_number'); ?>
<?php echo $form->error($model,'mobile_number'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('تسجيــــــــــــل'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Controller :
....
public function actionDynamiccities() /// call Ajax
{
$data=Cities::model()->findAll('country=:country_id',
array(':country_id'=>(int) $_POST['country']));
$data=CHtml::listData($data,'id','city_name_e');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
};
}
....
Thanks in Advance .

Yii has many through ajax validation

public function actionEquipmentLoanRequestCreate()
{
if(isset($_POST['EquipmentRequest']))
{
$ids = $_POST['EquipmentRequest']['equipID'];
$equipment = Equipment::model()->findAllByPk($ids);
$requests = self::instantiateEquipmentRequests($equipment);
//echo "<pre>";
//die(count($requests)." ".CActiveForm::validate($requests));
$booking = new EquipmentBooking;
if(isset($_POST['EquipmentRequest']) && $_POST['EquipmentBooking'])
{
$booking->attributes = $_POST['EquipmentBooking'];
$requestPostedVars = $_POST['EquipmentRequest'];
//have posted collection of equipment
//need to take count
//request below not really useful???
$equipmentRequests = array();
foreach($requestPostedVars as $request)
{
if(isset($request))
{
$equipmentRequest = new EquipmentRequest('loanRequest');
$equipmentRequest->attributes = $request;
array_push($equipmentRequests,$equipmentRequest);
}
}
$models = $equipmentRequests;
$models[]=$booking;
$this->performAjaxValidation($models);
$booking->equipment = $equipmentRequests;
if ($booking->save()){
self::assignBookingIds($equipmentRequests,$booking);
$this->redirect('index');
}
}
//displays view to create loan request
$this->render('equipment-loan-request',array('requests' => $requests,'booking' => $booking));
} else {
Yii::app()->user->setFlash('error', "You need to select equipment first!");
$this->redirect(array('simulation/equipment'), true);
}
}
public function instantiateEquipmentRequests($equipment)
{
$equipmentRequests = array();
foreach($equipment as $item)
{
$request = new EquipmentRequest('loanRequest');
$request->equipment = $item;
$request->qty = 1;
array_push($equipmentRequests,$request);
}
return $equipmentRequests;
}
form view ignore excess button replacing later -- ive directly tried calling the requests as opposed to just the bookings or both below as well to no avail.
<?php $form=$this->beginWidget('CActiveFormExtended', array(
'id' => 'equipment-booking-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange'=>true,
),
)); ?>
<div class="content-bg">
<?php
echo $form->errorSummary($requests);
if(isset($requests) && count($requests) > 0) {
foreach($requests as $i => $request) {
$this->renderPartial('_requestedEquipment', array("index" => $i, "request" => $request, "form"=> $form));
}
}?>
</div>
<br />
<hr class="brown"/>
<h2>Request Details</h2>
<div class="content-bg">
<h3>Step 1</h3>
<?php echo $form->label($booking,'organisation'); ?>
<?php echo $form->dropDownList($booking, 'organisation', $booking::$organisations,array('id' => 'organisation', 'class' => "selectfield",'empty' => 'Select')); ?>
</div>
<br />
<div class="content-bg">
<h3>Step 2</h3>
<?php echo $form->label($booking,'name'); ?>
<?php echo $form->textField($booking,'name',array('size'=>60,'maxlength'=>255)); ?>
    <?php echo $form->error($booking,'name'); ?>
<?php echo $form->label($booking,'email'); ?>
<?php echo $form->textField($booking,'email',array('size'=>60,'maxlength'=>255)); ?>
    <?php echo $form->error($booking,'email'); ?>
<?php echo $form->label($booking,'phone'); ?>
<?php echo $form->textField($booking,'phone',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'phone'); ?>
</div>
<br />
<div class="content-bg">
<h3>Step 3</h3>
<?php echo $form->label($booking,'address'); ?>
<?php echo $form->textField($booking,'address',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'address'); ?>
<?php echo $form->label($booking,'suburb'); ?>
<?php echo $form->textField($booking,'suburb',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'suburb'); ?>
<?php echo $form->label($booking,'postcode'); ?>
<?php echo $form->textField($booking,'postcode',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'postcode'); ?>
</div>
<br />
<div class="content-bg">
<h3>Step 4</h3>
<div class="five columns alpha">
<?php echo $form->label($booking,'pickupDate'); ?>
<?php echo $form->dropDownDayList($booking, 'pickupDate',array('class' => 'date-day pickup_select','id' => 'pickup')); ?>
<?php echo $form->dropDownYearList($booking,1, 'pickupDate',array('class' => 'date-monthyear pickup_select','id' => 'pickup-month')); ?>
<?php echo $form->hiddenField($booking, 'pickupDate',array('id' => 'pickupData')); ?>
<?php echo $form->error($booking,'pickupDate'); ?>
</div>
<div class="five columns alpha">
<?php echo $form->label($booking,'returnDate'); ?>
<?php echo $form->dropDownDayList($booking, 'returnDate',array('class' => 'date-day return_select','id' => 'return')); ?>
<?php echo $form->dropDownYearList($booking,1, 'returnDate',array('class' => 'date-monthyear return_select','id' => 'return-month')); ?>
<?php echo $form->hiddenField($booking, 'returnDate',array('id' => 'returnData')); ?>
<?php echo $form->error($booking,'returnDate'); ?>
</div>
<br class="clear"/>
</div>
<br />
<div class="content-bg">
<h2>Terms & Conditions</h2>
<p>By submitting this loan enquiry you agree to and acknowledge our Equipment Loan Terms and Conditions.</p>
</div>
<?php echo CHtml::submitButton('Submit'); ?>
<br />
<input class="orange-btn right" type="submit" value="Submit Loan Request">
<?php $this->endWidget(); ?>
</div>
EquipmentRequest partial
<div class="selected-equipment" id="request_<?php echo $request->equipment->equipName; ?>">
<div class="equipment-selected"><?php echo $request->equipment->equipName; ?></div>
<div class="equipment-qty"><?php echo $form->textField($request, "[$index]qty", array('value' => 1,'class' => 'requestQuantity')); ?></div>
<?php echo $form->error($request,"[$index]qty"); ?>
<div class="equipment-update"><span>Remove</span></div>
<?php echo $form->hiddenField($request, "[$index]equipID",array('value' => $request->equipment->equipID)); ?>
   <?php echo $form->error($request,"[$index]equipID"); ?>
<br class="clear">
</div>
EDIT
Please note I have rectified the above issue. Was mainly caused by an incorrect usage of performAjaxValidate, which I have now set to call both the booking and the collection of equipmentRequests.
This is now letting me get 2 validation error message objects back, 1 for both models. however only the booking model is being passed to the error summary div.
#bool.dev appreciate your assistance so far, any ideas with the above, have tried merging the collection of equipment request objects and booking object to the one argument call in errorSummary
I've edited the above to show updated controller actions and views
When you want errorSummary() for more than one model, use:
$form->errorSummary(array($model1,$model2,$model3));

Categories