CActiveForm object does not render JS code - yii

I have a simple CFormModel subclass that is used as a form to change a password. The class has only two attributes (password1, password2 - for confirmation -). Here is the code:
class ChangePasswordForm extends CFormModel {
public $password1;
public $password2;
public function rules() {
return array(
array('password1, password2', 'required'),
array('password2', 'compare', 'compareAttribute'=>'password1'),
array('password1, password2', 'safe'),
);
}
public function attributeLabels() {
return array(
'password1' => 'Enter new password',
'password2' => 'Confirm new password',
);
}
}
In a controller view file, I use a CActiveForm object to render this form:
<?php
$form=$this->beginWidget('CActiveForm',
array(
'id'=>'change-pwd-form',
'action'=>array('site/changePasswordPost'),
'enableClientValidation'=>true,
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)
);
echo $form->errorSummary($changePwdForm);
?>
<fieldset><legend>Change your password</legend>
<div class="row">
<?php
echo $form->labelEx($changePwdForm, 'password1');
echo $form->passwordField($changePwdForm, 'password1');
?>
</div>
<div class="row">
<?php
echo $form->labelEx($changePwdForm, 'password2');
echo $form->passwordField($changePwdForm, 'password2');
?>
</div>
<div class="row">
<?php
echo CHtml::submitButton('Change password');
?>
</div>
</fieldset>
<?php
$this->endWidget();
?>
In the controller action, I render the view above, passing a ChangePasswordForm object:
$changePwdForm = new ChangePasswordForm;
$this->render('changePassword', array('userid'=>$userid, 'userType'=>$t,
'changePwdForm'=>$changePwdForm));
Yii::app()->end();
The problem is that while the view is rendered, no Javascript code is generated. Nothing. So clicking on the submit button, although it should not let me do it (since the two password fields are required), it does submit. What is wrong with the code above and no Javascript is created?

Add $form->error() for fields that you need to validate. I suppose you perform ajax validation in controller, if not - search by performAjaxValidation here

Related

Post inside controller not loading into model in Yii2

When I want to get the variable from the form the post action doesn't load .
This is my view:
<?php
$form = ActiveForm::begin();
?>
<div class="form-group">
<input type="text" name="username" placeholder="FullName">
<?= Html::a(Yii::t('app', 'Start'), ['start', 'link' => $model->link], ['type' => 'button','class' => 'btn btn-primary btn-round']) ?>
</div>
<?php ActiveForm::end(); ?>
This is my controller:
if ($model->load(Yii::$app->request->post())){
exit(var_dump('everything is ok'));
}else {
exit(var_dump('nothing is right'));
}
The result is 'nothing is right'.
Apart from using the anchor link instead of a submit button, you are not using model to create active input hence the field names are without model names or the standard array format that Yii accepts, you should pass empty string to the load method as second parameter which is formName like below
$model->load(Yii::$app->request->post(),'');
So your complete form should look like
<?php
$form = ActiveForm::begin(
[
'action' => 'start',
]
);
?>
<div class="form-group">
<input type="text" name="username" placeholder="FullName">
<?php echo Html::submitButton(Yii::t('app', 'Start'), ['class' => 'btn btn-primary btn-round']) ?>
</div>
<?php ActiveForm::end();?>
EDIT
and your controller code should look like below, mind the first check it needs to be there so that the code is run when you submit only not on page load
if (Yii::$app->request->isPost) { //this should be here before the rest of the code
if ($model->load(Yii::$app->request->post(), '')) {
exit(var_dump('everything is ok'));
} else {
exit(var_dump('nothing is right'));
}
}
This is because load() method looks for post data inside model name property and you are writing the input yourself instead of using the Yii method for forms.
So your post Yii::$app->request->post() returns:
array(
'username' => 'value of username',
)
And your $model->load looks for
array(
'modelName' => array(
'username' => 'value of username',
)
)
To make your post data too look like that you could do it the right way that is, delete your Input and use this method inside the form:
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
Or the wrong way, modify your input and inside username use:
<input type="text" name="modelName[username]" placeholder="FullName">
Of course where I put username you must put your real model name.
Finally I find the solution
<?php
$form = ActiveForm::begin(
[
'action' => 'start',
]
);
?>
<div class="form-group">
<input type="text" name="username" placeholder="FullName">
<?= Html::a('submit', Url::to(['start', 'link' => $model->link]), ['data-method' => 'POST']) ?>
</div>
<?php ActiveForm::end();?>
thank you for all

change value in datepicker on selection of combo value in yii

I have a combo box in a form. According to the selected value from combo ,value of date must be changed in datepicker.How to do this?
code goes like this:
<div class="row col2">
<?php $records = CHtml::listData(CodeValue::model()->findAll(array('order' => 'code_lbl','condition'=>"code_type= 'visit_type'")), 'code_id', 'code_lbl');?>
<?php echo $form->labelEx($model,'visit_type'); ?>
<?php echo $form->dropDownList($model,'visit_type',$records,array('empty' => 'Select Visit Type')); ?>
<?php echo $form->error($model,'visit_type'); ?>
</div>
<div class="row col2">
<?php echo $form->labelEx($model,'next_visited_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'model' => $model,
'attribute'=>'next_visited_date',
//'flat'=>true,//remove to hide the datepicker
'options'=>array(
'showAnim'=>'drop',//'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
'dateFormat' => 'yy-mm-dd',
'showButtonPanel' => true, // show button panel
),
'htmlOptions'=>array(
'style'=>''
),
));
?>
<?php echo $form->error($model,'next_visited_date'); ?>
</div>
I have to change the visit date according to visit type selected.
You'll have to use ajax for this:
Change your drop down to use ajax, something like:
<?php echo $form->dropDownList($model,'visit_type',$records,array(
'empty' => 'Select Visit Type',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('controller/myAction'),//your controller and action name
'update'=>'#Model_next_visited_date', //replace Model with the model name
'success'=> 'function(data) {
$("#Model_next_visited_date").empty(); //replace Model with the model name
$("#Model_next_visited_date").val(data); //replace Model with the model name
} '
)));
?>
and create a new action:
public function actionMyAction()
{
//you will receive drop down value in $_POST['Model']['visit_type']
// Place your date logic here.....
}
Hope that helps

clear inputed data after ajaxsubmit and updating clistview

in views index.php i have
<?php
$this->widget('zii.widgets.CListView',array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'id'=>"post_list",
));
?>
<div id="addtodo">
<?php $this->renderPartial('ajax_page', array('model' => $model, ));?>
</div>
and in ajax_page.php
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'post-todo',
'enableAjaxValidation'=>false,
)); ?>
<?php
echo $form->textFieldRow(
$model,
'title',
array(
'class' => 'input-medium span6 addtodo',
'placeholder'=>'New todo task',
'prepend' => '<i class="glyphicon glyphicon-plus"></i>',
)
);
?>
<div class="row buttons">
<?php echo CHtml::ajaxSubmitButton ("Post",
CHtml::normalizeUrl(array('todo/add')),
array("success"=>'js:function(data){$.fn.yiiListView.update("post_list",{});}'),
array('class'=>'')
); ?>
</div>
<?php $this->endWidget(); ?>
So, All work fine. but after updating CListview, inputed text keeping in input form .
How to clear input form after updating CListview with Ajax?
You can do this by using the javascript .reset() method. You will need to change your ajax button to this;
<?php echo CHtml::ajaxSubmitButton ("Post",
CHtml::normalizeUrl(array('todo/add')),
array("success"=>'js:function(data){
$.fn.yiiListView.update("post_list",{});
$("#post-todo")[0].reset();
}'),
array('class'=>'')
); ?>

How can I display a warning message on textfield in Yii

I'm new to Yii framework and I need to display the validation error message as in login form "Username cannot be blank". Now, I have a text field where I updated the fields and the during validation I want a message to be displayed. How can I do this?
Controller
public function actionUpdate($id)
{
$model = $this->loadModel($id);
// set the parameters for the bizRule
$params = array('GroupzSupport'=>$model);
// now check the bizrule for this user
if (!Yii::app()->user->checkAccess('updateSelf', $params) &&
!Yii::app()->user->checkAccess('admin'))
{
throw new CHttpException(403, 'You are not authorized to perform this action');
}
else
{
if(isset($_POST['GroupzSupport']))
{
$password_current=$_POST['GroupzSupport']['password_current'];
$pass=$model->validatePassword($password_current);
$model->attributes=$_POST['GroupzSupport'];
if($pass==1)
{
$model->password = $model->hashPassword($_POST['GroupzSupport']['password_new']);
if($model->save())
$this->redirect(array('/messageTemplate/admin'));
}
else {$errors="Incorrect Current password"; print '<span style="color:red"><b>';
print '</b><b>'.$errors;
print '</b></span>';}
}
$this->render('update',array(
'model'=>$model,
));
}
}
View
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'password-recovery-reset-password-form',
'enableAjaxValidation'=>false,
)); ?>
<div class="row"><?php
echo $form->labelEx($model,'username');
echo $form->textField($model,'username',array('size'=>45,'maxlength'=>150));
echo $form->error($model,'username');
?></div>
<div class="row">
<?php echo $form->labelEx($model,'current password'); ?>
<?php echo $form->passwordField($model,'password_current',array('size'=>30,'maxlength'=>30)); ?>
<?php echo $form->error($model,'password_current'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'new password'); ?>
<?php echo $form->textField($model,'password_new',array('size'=>30,'maxlength'=>30)); ?>
<?php echo $form->error($model,'password_new'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'confirm new password'); ?>
<?php echo $form->passwordField($model,'password_repeat',array('size'=>30,'maxlength'=>30)); ?>
<?php echo $form->error($model,'password_repeat'); ?>
</div>
<div class="row buttons"><?php
echo CHtml::submitButton('Reset Your Password');
?></div><?php
$this->endWidget(); ?>
</div>
Now currently I'm displaying it at the top.
I want to display it right on the textfield as in login page. How can I do this?
Before redirect, add the message to the desired field.
In the model Validator:
$this->addError('field_name', "Message error.");
Or in Controller action:
$model->addError('field_name', "Message error.");

yii controller can't set post

friends!
i generated a dynamic product field and quantity filed with javascript in order customer makes ordering over one product. but why does controller can't set POST['OrderDetail']? the controller can save only one model, Order.
Please help to correct me.
I have four models: Product, Customer, Order, and Order_detail.
view/order/_form.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'order-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,'customer_id'); ?>
<?php //echo $form->textField($model,'customer_id'); ?>
<?php echo $form->dropDownList($model,'customer_id',CHtml::listData(Customers::model()->findAll(),'customer_id','fullname'),
array('empty' => '--- Choose---')); ?>
<?php echo $form->error($model,'customer_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'order_status'); ?>
<?php echo $form->textField($model,'order_status'); ?>
<?php //echo $form->dropDownList($model,'order_id', array(1=>'Pending', 2=>'Processing',3=>'Completed'));?>
<?php echo $form->error($model,'order_status'); ?>
</div>
<?php /*?>
<div class="row">
<?php echo $form->labelEx($model,'lat'); ?>
<?php echo $form->textField($model,'lat'); ?>
<?php echo $form->error($model,'lat'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lng'); ?>
<?php echo $form->textField($model,'lng'); ?>
<?php echo $form->error($model,'lng'); ?>
</div>
<?php */?>
<div class="row">
<?php echo $form->labelEx($model,'address'); ?>
<?php echo $form->textField($model,'address',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'staff_id'); ?>
<?php //echo $form->textField($model,'staff_id'); ?>
<?php echo $form->dropDownList($model,'staff_id',CHtml::listData(Staff::model()->findAll(),'staff_id','fullname'),
array('empty' => '--- Choose---')); ?>
<?php echo $form->error($model,'staff_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'received_date'); ?>
<?php echo $form->textField($model,'received_date'); ?>
<?php echo $form->error($model,'received_date'); ?>
</div>
<script type="text/javascript">
function addProduct() {
var ni = document.getElementById('divProduct');
var numi = document.getElementById('countLastInput');
var num = (document.getElementById('countLastInput').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = num;
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = <?php echo $form->dropDownList($orderdetail,'product_id',CHtml::listData(Products::model()->findAll(),'product_id','product_name'),
array('empty' => '--- Choose---','name'=>'productorder[]')); ?>+<?php echo $form->textField($orderdetail,'qty', array('name'=>'qtyorder[]')); ?>+'Remove';
ni.appendChild(newdiv);
}
function removePhoto(divNum) {
var d = document.getElementById('divProduct');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
var minus=document.getElementById('countLastInput').value;
document.getElementById('countLastInput').value=minus-1;
}
</script>
<div id="divProduct"> </div>
<input type="button" name="service_photo" value="Add Product" class="Allbutton" onclick="addProduct();" />
<input type="hidden" value="0" id="countLastInput" name="countLastInput" />
<?php /*?>
<div class="row">
<?php echo $form->labelEx($orderdetail,'product_id'); ?>
<?php echo $form->dropDownList($orderdetail,'product_id',CHtml::listData(Products::model()->findAll(),'product_id','product_name'),
array('empty' => '--- Choose---')); ?>
<?php echo $form->error($orderdetail,'product_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($orderdetail,'qty'); ?>
<?php echo $form->textField($orderdetail,'qty'); ?>
<?php echo $form->error($orderdetail,'qty'); ?>
</div>
<?php /*?>
<?php //$orderdetail=new OrderDetail();?>
<?php //echo $this->renderPartial("_partial_order",array('orderdetail'=>$orderdetail));?>
<?php /* ?><form action="php_multiple_textbox4.php" method="post" name="form1">
<input type="text" name="txtSiteName[]">
<input name="btnButton" type="button" value="+" onClick="JavaScript:fncCreateElement();"><br>
<span id="mySpan"></span>
<input name="btnSubmit" type="submit" value="Submit">
</form>
<?php */?>
<?php /*?>
<div class="row">
<?php echo $form->labelEx($model,'completed_date'); ?>
<?php echo $form->textField($model,'completed_date'); ?>
<?php echo $form->error($model,'completed_date'); ?>
</div>
<?php */?>
<?php /*?>
<div class="row">
<?php echo $form->labelEx($model,'created_date'); ?>
<?php echo $form->textField($model,'created_date'); ?>
<?php echo $form->error($model,'created_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'upated_date'); ?>
<?php echo $form->textField($model,'upated_date'); ?>
<?php echo $form->error($model,'upated_date'); ?>
</div>
<?php */?>
<?php /*?>
<table id="students">
<thead>
<tr>
<td>Product Name</td>
<td>Quantity</td>
<td>
<?php echo CHtml::link('<b>Add Product</b>', '', array('onClick'=>'addProduct($(this))', 'class'=>'add'));?>
</td>
</tr>
</thead>
</table>
<input type="hidden" value="0" id=lastInput name="lastInput" />
<?php */?>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
OrderController.php
<?php
class OrderController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
public $orderid;
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','showlog'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('*'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('*'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionShowLog(){
//Yii::log("hi, h r u?" ,"trace","application.controllers.OrderController");
var_dump(Yii::getLogger()->getLogs());
//Yii::trace("The actionCreate() method is being requested","application.controllers.OrderController");
}
public function actionCreate()
{
$model=new Order;
$orderdetail=new OrderDetail();
$product=new Products();
$date=date('y-m-d');
// Uncomment the following line if AJAX validation is needed
//$this->performAjaxValidation(array($model,$orderdetail));
if(isset($_POST['Order']))
{
$model->attributes=$_POST['Order'];
$model->lat='12.53';
$model->lng='13.2';
$model->completed_date=$date;
$model->received_date=$date;
$model->created_date=$date;
$model->upated_date=$date;
if($model->save())
{
Yii::log("order save","info","application.controllers.OrderController");
if(isset($_POST['OrderDetail'])){
for($i=1;$i<count($_POST['productorder']);$i++){
//$orderdetail->attributes=$_POST['OrderDetail'];
$orderdetail->product_id=$_POST['productorder'][$i];
$orderdetail->qty=$_POST['qtyorder'][$i];
$orderdetail->order_id= $model->order_id;
$orderdetail->order_item_status=1;
$orderdetail->created_date=$date;
$orderdetail->updated_date=$date;
$orderdetail->save();
}
$this->redirect(array('view','id'=>$model->order_id));
//$qty=$orderdetail->qty=$_POST['qty'];
//$productid=$orderdetail->product_id=$_POST['txtproduct'];
/*
for($i=1;$i<=count($qty);$i++){
$orderdetail->order_id= $model->order_id;
$orderdetail->order_item_status=1;
$orderdetail->created_date=$date;
$orderdetail->updated_date=$date;
$orderdetail->product_id=1;
//$orderdetail->qty=$qty[$i];
//$orderdetail->save();
var_dump($_POST['qty']);
}
$this->redirect(array('view','id'=>$model->order_id));
*/
}else{
Yii::log("Failed ordedetails","warning","application.controllers.OrderController");
}
//$OrderDetailController=new OrderDetail();
//$this->redirect(array('OrderDetail/create'));
}
}
$this->render('create',array(
'model'=>$model,
'orderdetail'=>$orderdetail,
'product'=>$product,
));
}
/*
public function actionCreate()
{
Yii::import('ext.multimodelform.MultiModelForm');
$model = new Order;
$orderdetail=new OrderDetail();
$product=new Products();
$validatedMembers = array(); //ensure an empty array
if(isset($_POST['Order']))
{
$model->attributes=$_POST['Order'];
if( //validate detail before saving the master
MultiModelForm::validate($model,$validatedMembers,$deleteItems) &&
$model->save()
)
{
//the value for the foreign key 'groupid'
$masterValues = array ('order_id'=>$model->order_id);
if (MultiModelForm::save($model,$validatedMembers,$deleteMembers,$masterValues))
$this->redirect(array('view','id'=>$model->order_id));
}
}
$this->render('create',array(
'model'=>$model,
//submit the member and validatedItems to the widget in the edit form
'orderdetail'=>$orderdetail,
'product'=>$product,
'validatedMembers' => $validatedMembers,
));
}
*/
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$date=date('y-m-d');
$model=$this->loadModel($id);
//$orderdetail=new OrderDetail();
$product=new Products();
$orderdetail=OrderDetail::model()->findByAttributes(array('order_id'=>$_GET['id']));
//$product->findByAttributes(array('order_id'=>$_GET['id']));
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Order']))
{
$model->attributes=$_POST['Order'];
$model->lat='12.53';
$model->lng='13.2';
$model->completed_date=$date;
$model->received_date=$date;
$model->created_date=$date;
$model->upated_date=$date;
if($model->save())
if(isset($_POST['OrderDetail'])){
$orderdetail->attributes=$_POST['OrderDetail'];
$orderdetail->order_id= $model->order_id;
$orderdetail->order_item_status=1;
$orderdetail->created_date=$date;
$orderdetail->updated_date=$date;
if($orderdetail->save())
$this->redirect(array('view','id'=>$model->order_id));
}
}
$this->render('update',array(
'model'=>$model,
'orderdetail'=>$orderdetail,
'product'=>$product,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Order');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Order('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Order']))
$model->attributes=$_GET['Order'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Order::model()->findByPk((int)$id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
//$model=Order::model()->with(Products::model(),OrderDetail::model())->findByPk((int)$id);
// if($model===null)
// throw new CHttpException(404,'Page not found.');
//return $model;
}
/**
* Performs the AJAX validation.
* #param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='order-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
Thanks in advance.
Try to enable CWebLogRoute to see if you have any security issues.
Yii wiki: How to log and debug variables using CWebLogRoute