I have one textfield and one textarea with CKeditor using yii framework. validation for textfield is working but validation for textArea is not working.can please any one help me..
Thank you in advance.
I assume you mean clientside validation is not working. This is because Yii validation is triggered before CKEditor updates the textarea.
You can let CKEDITOR update the textarea before validating, and clientside/ajax validation will work as expected:
<?php $form = $this->beginWidget('CActiveForm', array(
'enableAjaxValidation' => true, // one or both
'enableClientValidation' => true, // one or both
'clientOptions' => array(
'validateOnSubmit' => true, // optional
'beforeValidate' => new CJavaScriptExpression('function(form) {
for(var instanceName in CKEDITOR.instances) {
CKEDITOR.instances[instanceName].updateElement();
}
return true;
}'),
),
)); ?>
Related
This is my view page
<?php echo $form->dropDownListRow($order,'area_id',Area::model()->getActiveAreaList(),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/getdeliveryforarea'),
'update'=>'#pickup_time_slot', //selector to update
'data' => array('area_id' => 'js:this.value',),
)));
?>
<?php echo $form->dropDownListRow($order,'pickup_time_slot',array(),array('prompt'=>'Select time')); ?>
and in my controll the getdeliveryforarea is like
public function actionGetdeliveryforarea()
{
$data=Areatimeslot::model()->findAll('area_id=:area_id',
array(':area_id'=>(int) $_POST['id']));
$data=CHtml::listData($data,'id','name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
here my dependent dropdown is not working ,from getActiveAreaList i will get the area list in first dropdown and once i choose an area it must show corrosponding time list in second dropdown,i hope someone will help me out,thanks in advance
Use Juqery migrate plugin or try something like,
jQuery.browser = {};
(function () {
jQuery.browser.msie = false;
jQuery.browser.version = 0;
if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
jQuery.browser.msie = true;
jQuery.browser.version = RegExp.$1;
}
})();
In yii2 project I have my own file structure setup. Anything uploaded will get saved as a file type. I can get the file dimensions using the file uploaded in the temp folder by yii2. Using those dimensions I set my own width and height and compare them. If the height and width is more than what I have declared It has display an error message in the form. Which I am unable to do it.
My Active Form
<div class="company-form">
<?php
$form = ActiveForm::begin([
'action'=>['company/logo', 'id'=>$model->company_id],
'validateOnSubmit' => true,
'options' =>
['enctype' => 'multipart/form-data','class' => 'disable-submit-buttons','id'=> 'companyLogoForm'],
'fieldConfig' => [
'template' => "<div class=\"row\">
<div class=\"col-xs-6 margin-top-8\">{label}</div>\n<div class=\"col-xs-6 text-right\">{hint}</div>
\n<div class=\"col-xs-12 \">{input}</div>
</div>",
],
]); ?>
<?= $form->errorSummary($model, $options = ['header'=>'','class'=>'pull-left']); ?>
<?= $form->field($model, 'company_name')->hiddenInput(['maxlength' => true])->label(false) ?>
<?= $form->field($file, 'file')->fileInput([])->label(Yii::t('app', 'Attach Logo'),['class'=> 'margin-top-8']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Save') : Yii::t('app', 'Save'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary','data' => ['disabled-text' => 'Please Wait']]) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My Controller Action
public function actionLogo($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$file = new File;
$file->load(Yii::$app->request->post());
$a = UploadedFile::getInstance($file,'file');
$size = getimagesize($a->tempName);
$maxWidth = 500;
$maxHeight = 500;
if ($size[0] > $maxWidth || $size[1] > $maxHeight)
{
$model->addError('file', $error = 'Error Message');
if($model->hasErrors()){
return ActiveForm::validate($model);
}
}
$file->file = UploadedFile::getInstance($file,'file');
$file->file_name = $file->file->name;
$file->file_user = Yii::$app->user->id;
$file->file_type = 1;
if($file->save()){
$file->file_path = Files::getFilePath($file->file_id);
$validDir = $file->file->createFileDir($file->file_path, $file->file_id);
if($validDir){
$file->file->saveAs($file->file_path, false);
if($file->save()){
$model->company_file = $file->file_id;
$model->save();
return $this->redirect(['index']);
}
}
}
}
}
How do I add error message in the controller and pass that to display on my form on the modal box.
Note: my form is displayed on the modal box.
Thank you!!
You should handle the file processing in your model - or even better, create a specific UploadForm model for this purpose.
In that case you can use File Validation or a custom validator to set errors during model validation.
The built-in yii\validators\FileValidator gives you plenty pf validation rules out of the box.
This is actually pretty well explained in the documentation: Uploading Files
See also the documentation for FileValidator
Example for validating an uploaded image file:
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
Try this validation rule
['imageFile', 'image', 'minWidth' => 250, 'maxWidth' => 250,'minHeight' => 250, 'maxHeight' => 250, 'extensions' => 'jpg, gif, png', 'maxSize' => 1024 * 1024 * 2],
I want to put reset button under the action column only one time in GridView widget..
Any solution or suggestions?
Thanks
Set header property of ActionColumn:
[
'class' => 'yii\grid\ActionColumn',
'template' => '<div class="pull-right" >{update}{delete}</div>',
'header' => '<button>Button</button>'
]
Update:
As already answered you can create custom column, and you may add only additional filter property so that you can customize this property for each grid.
class CustomActionColumn extends yii\grid\ActionColumn
{
public $filter = "";
protected function renderFilterCellContent()
{
return $this->filter;
}
}
Then you set filter in grid definition:
[
'class' => 'CustomActionColumn',
'template' => '<div class="pull-right" >{update}{delete}</div>',
'filter' => '<button>Button</button>'
]
To, put button in ActionColumn on header so, follow below steps:
Create a file CustomActionColumn.php in components folder.
Put below code in above file
namespace app\components;
use yii\grid\ActionColumn;
use yii\helpers\Html;
class CustomActionColumn extends ActionColumn
{
protected function renderFilterCellContent()
{
return Html::button('Reset', ['class' => 'btn btn-primary']);
}
}
Now in your Gridview widget use CustomActionColumn instead of ActionColumn
Like as
[
'class' => 'app\components\CustomButton',
],
Done.
Note:- Using these steps you can just display button in header.
To display both a button and ActionColumn label you could override yii\grid\ActionColumn renderFilterCellContent() method with your own class like this:
namespace app\components;
class FilterActionColumn extends ActionColumn
{
public $filterContent;
/**
* Renders the filter cell content.
* The default implementation simply renders a blank space.
* This method may be overridden to customize the rendering of the filter cell (if any).
* #return string the rendering result
*/
protected function renderFilterCellContent()
{
return $this->filterContent;
}
}
Then you able to add both label and button to GridView replace default ActionColumn like this
In your view
use app\components\FilterActionColumn;
Replace default GridView ActionColumn
[
'class' => FilterActionColumn::className(),
// Add your own filterContent
'filterContent' => Html::a('Your button', ['some/url'], [
'class' => 'btn btn-default', 'title' => 'Some btn title',
]),
'header'=> 'Your label',
// Another ActionColumn options
// ..
],
You could see extended example here, i.e. if you need more than one button https://github.com/nick-denry/yii2-filter-action-column
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'emptyCell' => Html::a('<i class="fa fa-refresh"></i> Reset', ['index'], ['class' => 'btn btn-primary btn-xs', 'style' => 'margin: 2px;']),
]);
use emptyCell to set button...
I want to UPDATE record without losing the File that i have uploaded. Below is my create action.
public function actionCreate()
{
$model = new Page;
if (isset($_POST['Page']))
{
$model->attributes = $_POST['Page'];
$model->filename = CUploadedFile::getInstance($model, 'filename');
if ($model->save())
{
if ($model->filename !== null)
{
$dest = Yii::getPathOfAlias('application.uploads');
$model->filename->saveAs($dest . '/' . $model->filename->name);
$model->save();
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
In yii, update method is designed to update the values that you are posting from your form. It will not update all Model properties.
For suppose, your Page model has 4 model properties, assume all are mandatory.
title
description
keywords
image
Since you don't want to update image field, you can make it non mandatory field by setting scenario for image field in your Page model rules.
class Page extends CActiveRecord
{
/*
Coding
*/
public function rules()
{
return array(
array('title, description,keywords', 'required'),
array('image', 'file', 'types'=>'jpg, png'),
array('image', 'required', 'on' => 'insert'),
// => You need image field to be entered on Create, not on Update
.................
}
}
So, Show file input in your form on Create, Hide on Update action so that image field won't submit.
//Your page form
<?php if($model->isNewRecord):?>
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
<?php endif;?>
Since your are using Yii-2 you can use skippOnEmpty validator for the same.
It appears that the links aren't in correct order and I can't figure out why. I have it in other grids, they seem to be fine.
This is what the link shows:
index.php?ajax=gridID&id=180&r=controller/action
when it's suppose to show:
index.php?r=controller/action&id=180
this is my value in gridview:
'value'=>function($data,$row){
if (intval($data->sid) ==$someID){
if($data->accept == "ACCEPTED")
return CHtml::Link("[X]", array("controller/action","id"=>$data->id),
array('confirm' => 'Are you sure?',
'class'=>'stat')
);
}
where grid is suppose to refresh on confirm:
<?php
Yii::app()->clientScript->registerScript('stat', "
$('#gridId a.stat').live('click', function() {
$.fn.yiiGridView.update('gridId', {
type: 'POST',
url: $(this).attr('href'),
success: function() {
$.fn.yiiGridView.update('gridId');
}
});
return false;
});"
);
?>
if you need generate url on "path" format (controller/action/id/180) and without script name you can set urlFormat property in UrlManager to "path" and set showScriptName property to false. Look this and this
in aplication config file:
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
)