Yiiframework Range Slider input - php

I have a user settings page where users can change the settings of the application. The users can input a number between 0 and 10. See screenshot: http://oi43.tinypic.com/2uerazp.jpg
Now I would like to transform the input fields into a range slider using the CJuiSliderInput widget of the yiiframework: http://www.yiiframework.com/doc/api/1.1/CJuiSliderInput#maxAttribute-detail
I cannot seem to get the code working, this is the current code in view:
<?php foreach($settings as $i=>$value): ?>
<?php $setting=UserSetting::model()->findByPk($value->setting_id); ?>
<h4><?php echo CHtml::encode($setting->label); ?></h3>
<?php echo CHtml::activeTextField($value,"[$i]value"); ?>
<?php endforeach; ?>
I would like to replace the activeTextField with
$this->widget('zii.widgets.jui.CJuiSliderInput',array(
'model'=>$model,
'attribute'=>'[$i]value',
'maxAttribute'=>'timeMax',
// additional javascript options for the slider plugin
'options'=>array(
'range'=>true,
'min'=>0,
'max'=>10,
),
));
What values do I need to fill in to the widget to get it to work? Each textField input is from a different model btw.
The controller looks something like this(don't know if you need it):
$settingsvalues = UserSettingValue::model()->findAll('client_id=:id', array(
':id' => $id,
));
if(isset($_POST['UserSettingValue'])){
$valid = true;
foreach($settingsvalues as $i=>$value){
if(isset($_POST['UserSettingValue'][$i]))
$value->attributes = $_POST['UserSettingValue'][$i];
$value->save();
$valid = $value->validate() && $valid;
}
if($valid)
$value->save();
}
$this->render('settings',array(
'model' => $model,
'settings' => $settingsvalues,
));
Thanks a lot!

I fixed the problem by putting a javascript function in the slider. It is not exactly as I intended in the beginning, but it'll do. The slider now changes the value in the input fields.
<?Php
$this->widget('zii.widgets.jui.CJuiSliderInput',array(
'name' => $i,
'model'=>$value,
'attribute'=>"value",
'event'=>'change',
//'value'=>'$value',
'options'=>array(
'min'=>0,
'max'=>10,
'animate' => true,
'slide'=>'js:function(event,ui){$("#UserSettingValue_'.$i.'_value").val(ui.value);}',
),
)); ?>

This was a little big to be a comment. But please try the following
$this->widget('zii.widgets.jui.CJuiSliderInput',array(
'name'=>'$setting->label',
'attribute'=>'[$i]value',
'value'=>$value,
'options'=>array(
'min'=>0,
'max'=>10,
),
));
Also please try this
$this->widget('zii.widgets.jui.CJuiSliderInput',array(
'name'=>'$setting->label',
'attribute'=>'[$i]value',
'value'=>$value,
'options'=>array(
'min'=>0,
'max'=>10,
),
'htmlOptions'=>array(
'style'=>'height:20px;',
),
));

Related

Page size dropdownlist and CListView not working in yii

I am traying to make a dropdown pagination in my project, but it's not working correctly.
Whatever the number that I select in the dropdownlist, it still shows 10 items in the page.
What I am missing ?
Thank you.
Screenshot
The view code :
<?php
//$dataProvider->pagination->pageSize = 25;
$pageSize=Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']);
echo CHtml::dropDownList('pageSize',$pageSize,array(5=>5,10=>10,15=>15,20=>20,25=>25,30=>30),
array('onchange'=>"$.fn.yiiGridView.update('packages-grid',{ data:{pageSize: $(this).val() }})",
'empty'=>'-- Select Page Range --','style'=>'width:198px;'));
$this->widget('zii.widgets.CListView', array(
'id'=>'propertylistview',
'dataProvider'=>$dataProvider,
'summaryText'=>'',
'itemView'=>'_propertyview',
'sortableAttributes' => array(
.........
)
));
?>
The controller code :
public function actionAdmin(){
if (isset($_GET['pageSize'])) {
Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);
unset($_GET['pageSize']);}
$model=new Packages('search');
$model->unsetAttributes();
if(isset($_GET['Packages']))
$model->attributes=$_GET['Packages'];
$dataProvider=new CActiveDataProvider('Packages');
$this->render('admin',array('model'=>$model,'dataProvider'=>$dataProvider,
));
}
I already added this to model search
return new CActiveDataProvider(get_class($this),array(
'pagination'=>array(
'pageSize'=> Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']),
),
'criteria'=>$criteria,
));
and this to config/main.php
'params'=>array('defaultPageSize'=> '10'),
You're doing an ajax call but in your widget you do not state any update part to update. ajaxUpdate is the solution.
And you are using 'onchange'=>"$.fn.yiiGridView.update while using a CListView so change the js to 'onchange'=>"$.fn.yiiListView.update and:
<?php
// your code
$this->widget('zii.widgets.CListView', array(
'id'=>'propertylistview',
'ajaxUpdate' => 'propertylistview', //add this line
'dataProvider'=>$dataProvider,
'summaryText'=>'',
'itemView'=>'_propertyview',
'sortableAttributes' => array(
//etc.. )
));
?>

how to create custom autocomplete textfield in yii

I am new to yii. I need to write custom yii auto complete.I knew that CJuiAutocomplete is there.but I need to implement own custom auto complete. can anyone pls guide me or help me to develop custom autocomplete textfield. taking the id while displaying name in the textfield.
Thanks in advance
Here is an action in site controller...
public function actionAutoComplete($term){
$query = Yourmodel::model()->findallbyattributes( array('somecolumn'=>$term));
$list = array();
foreach($query as $q){
$data['value']= $q['id'];
$data['label']= $q['name'];
$list[]= $data;
unset($data);
}
echo json_encode($list);
}
and here is a search form in your view:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'searchform',
'enableAjaxValidation'=>false,
'action' => '/'
)); ?>
<fieldset>
<div class="input-append">
<?php
echo CHtml::hiddenField('selectedvalue','');
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name'=>'searchbox',
'value'=>'',
'source'=>CController::createUrl('/site/autoComplete'),
'options'=>array(
'showAnim'=>'fold',
'minLength'=>'2',
'select'=>'js:function( event, ui ) {
$("#searchbox").val( ui.item.label );
$("#selectedvalue").val( ui.item.value );
return false;
}',
),
'htmlOptions'=>array(
'onfocus' => 'js: this.value = null; $("#searchbox").val(null); $("#selectedvalue").val(null);',
'class' => 'input-xxlarge search-query',
'placeholder' => "Search...",
),
));
echo '<button class="btn" type="submit">Submit</button>';
?>
</div>
</fieldset>
<?php $this->endWidget(); ?>
</form>
Because of this condition
array('somecolumn'=>$term)
it will show results only if you write full string. For example, you have ['coffee', 'cake']. When you type in search box it wont show results for coff, cof, co, ca, cak etc. only will show results if you enter full word coffee, you will get ['coffee'] as result.
So you need something like:
$match = $_GET['term'];
$tags = Tags::model()->findAll(
'tag_name LIKE :match',
array(':match' => "%$match%")
);
This will show results for coff, cof, co, ca, cak etc.

yii : how to ajax update the cgridview

Q : How to ajax update the CgridVeiw?
Status : I've done with cookie. but there are a problem. it is when the page upload, the date are always show in from-date and to-date text box. and When reload the page, it doesn't clear out.
This is my view
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'page-form',
'enableAjaxValidation'=>true,
)); ?>
<div style="margin-top:30px;">
<b>From :</b>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name'=>'from_date', // name of post parameter
//'value'=>Yii::app()->request->cookies['from_date']->value, // value comes from cookie after submittion
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<span> </span>
<b>To :</b>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name'=>'to_date',
//'value'=>Yii::app()->request->cookies['to_date']->value,
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<span> </span>
<?php echo CHtml::submitButton('Go'); ?>
<?php
echo CHtml::ajaxSubmitButton('Search', CHtml::normalizeUrl(array('index')),
array(
'success'=>'js:'
.'function(){'
.'$.fn.yiiGridView.update("acc-payment-recei-grid", {url:"index"});'
.'}',
),
array('id'=>'go', 'name'=>'go'));
?>
<?php $this->endWidget(); ?>
<p style="float:right;">
New Payment Receive
</p>
</div>
<style>
.items table tr:last-child td:first-child {
-moz-border-radius-bottomleft:10px;
-webkit-border-bottom-left-radius:10px;
border-bottom-left-radius:10px
}
.items table tr:last-child td:last-child {
-moz-border-radius-bottomright:10px;
-webkit-border-bottom-right-radius:10px;
border-bottom-right-radius:10px
}
</style>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'acc-payment-recei-grid',
'dataProvider'=>$accpaymentrecei->search(),
//'filter'=>$accpaymentrecei,
'columns'=>array(
//'id',
array('name' => 'acc_category_id',
'value'=>'(isset($data->acccategories->name)) ? CHtml::encode($data->acccategories->name) :""',
),
array('name' => 'acc_recei_id',
'header'=> 'Account Received',
//'value'=>'(isset($data->method)) ? CHtml::encode($data->method) :""',
),
array(
'name' => 'date',
'value'=>'($data->date= 0) ? "" : date("d M yy",strtotime($data->date))',
),
array('name' => 'method',
'value'=>'(isset($data->method)) ? CHtml::encode($data->method) :""',
),
array('name' => 'description',
//'value'=>'(isset($data->method)) ? CHtml::encode($data->method) :""',
),
/*
'created_date',
'updated_date',
'file_name',
*/
array(
'class'=>'CButtonColumn',
),
),
));
This is controller
public function actionIndex()
{
$accpaymentrecei=new AccPaymentRecei('search');
$accpaymentrecei->unsetAttributes(); // clear any default values
if(isset($_GET['AccPaymentRecei']))
$accpaymentrecei->attributes=$_GET['AccPaymentRecei'];
$acccategory = AccCategory::model()->findAll();
$arr_method = array('Cash'=>'Cash', 'Cheque'=>'Cheque', 'Credit Card'=>'Credit Card', 'Bank Transfer'=>'Bank Transfer');
$this->from_to_date($accpaymentrecei);
//exit();
$this->render('index',array(
'accpaymentrecei'=>$accpaymentrecei,
'acccategory'=>$acccategory,
'arr_method'=>$arr_method,
));
}
protected function from_to_date($model)
{
unset(Yii::app()->request->cookies['from_date']); // first unset cookie for dates
unset(Yii::app()->request->cookies['to_date']);
//$model=new XyzModel('search'); // your model
$model->unsetAttributes(); // clear any default values
if(!empty($_POST))
{
Yii::app()->request->cookies['from_date'] = new CHttpCookie('from_date', $_POST['from_date']); // define cookie for from_date
Yii::app()->request->cookies['to_date'] = new CHttpCookie('to_date', $_POST['to_date']);
$model->from_date = $_POST['from_date'];
$model->to_date = $_POST['to_date'];
}else{
Yii::app()->request->cookies['from_date'] = new CHttpCookie('from_date', date("Y/m/d"));
Yii::app()->request->cookies['to_date'] = new CHttpCookie('to_date', date("Y/m/d"));
}
}
Code below - it's only example, main principles of solution. First principle: we don't need refresh page (by the submit), we need only refresh CGridView after request.
The solution has a few parts:
We need form with some parameters. In your case - fromDate and toDate. You have this one already. But we don't need any submit element. At all! We will use AJAX.
We need some function for initiate AJAX-request. For example, let's event for this request will be change of parameters *from_date* or *to_date*. This function also must update CGridView after request.
We need action in controller for processing AJAX-request.
Let's begin from part 2. It may be some like this:
Yii::app()->clientScript->registerScript('scriptId',
"var ajaxUpdateTimeout;
var ajaxRequest;
$('**selector_for_parameters_fields**').change(function(){
ajaxRequest = $(this).serialize();
clearTimeout(ajaxUpdateTimeout);
ajaxUpdateTimeout = setTimeout(function () {
$.fn.yiiGridView.update(
// this is the id of the CGridView
'acc-payment-recei-grid',
{data: ajaxRequest}
)
},
// this is the delay
300);
});"
);
Place this code into view. Notes:
$(this).serialize() - key moment. Look for more info
selector_for_parameters_fields - give them ( fromDate and toDate ) some unique
selector
We use some delay (300 ms) for decreasing loading from unnecessary AJAX-requests
Now - about action in Controller
public function actionIndex($fromDate='', $toDate='')
{
$criteria = new CDbCriteria();
if(!empty($fromDate))
$criteria->addSearchCondition('your search condition about fromDate');
if(!empty($toDate))
$criteria->addSearchCondition('your search condition about toDate');
$dataProvider=new CActiveDataProvider('YourModel',
array('criteria' => $criteria,));
$this->render('YourView',array('dataProvider'=>$dataProvider,));
}
It must works, but requires some tuning for concrete conditions.

yii ajax xupload form submit is not working

Q1 : form submitting is not working.
Q2 : how to limit upload files (e.g 1 - 5 files only)
status : create a form with ajax upload xupload
My model (fadepreciation.php)
public function afterSave( ) {
$this->addImages( );
parent::afterSave( );
}
public function addImages( ) {
//If we have pending images
if( Yii::app( )->user->hasState( 'images' ) ) {
$userImages = Yii::app( )->user->getState( 'images' );
//Resolve the final path for our images
$path = Yii::app( )->getBasePath( )."/../images/uploads/{$this->id}/";
//Create the folder and give permissions if it doesnt exists
if( !is_dir( $path ) ) {
mkdir( $path );
chmod( $path, 0777 );
}
//Now lets create the corresponding models and move the files
foreach( $userImages as $image ) {
if( is_file( $image["path"] ) ) {
if( rename( $image["path"], $path.$image["filename"] ) ) {
chmod( $path.$image["filename"], 0777 );
$img = new Image( );
$img->size = $image["size"];
$img->mime = $image["mime"];
$img->name = $image["name"];
$img->source = "/images/uploads/{$this->id}/".$image["filename"];
$img->somemodel_id = $this->id;
if( !$img->save( ) ) {
//Its always good to log something
Yii::log( "Could not save Image:\n".CVarDumper::dumpAsString(
$img->getErrors( ) ), CLogger::LEVEL_ERROR );
//this exception will rollback the transaction
throw new Exception( 'Could not save Image');
}
}
} else {
//You can also throw an execption here to rollback the transaction
Yii::log( $image["path"]." is not a file", CLogger::LEVEL_WARNING );
}
}
//Clear the user's session
Yii::app( )->user->setState( 'images', null );
}
}
My view (_form.php)
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'fa-depreciation-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<!-- Other Fields... -->
<div class="row">
<?php echo $form->labelEx($model,'photos'); ?>
<?php
$this->widget( 'xupload.XUpload', array(
'url' => Yii::app( )->createUrl( "/fadepreciation/upload"),
//our XUploadForm
'model' => $photos,
//We set this for the widget to be able to target our own form
'htmlOptions' => array('id'=>'fa-depreciation-form'),
'attribute' => 'file',
'multiple' => true,
//Note that we are using a custom view for our widget
//Thats becase the default widget includes the 'form'
//which we don't want here
//'formView' => 'application.views.faDepreciation._form',
)
);
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
My controller (fadepreciation.php)
public function actionCreate()
{
$model=new FaDepreciation;
Yii::import( "xupload.models.XUploadForm" );
$photos = new XUploadForm;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['FaDepreciation']))
{
//Assign our safe attributes
$model->attributes=$_POST['FaDepreciation'];
//Start a transaction in case something goes wrong
$transaction = Yii::app( )->db->beginTransaction( );
try {
//Save the model to the database
if($model->save()){
$transaction->commit();
$this->redirect(array('view','id'=>$model->id));
}
} catch(Exception $e) {
$transaction->rollback( );
Yii::app( )->handleException( $e );
}
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
Yii::import( "xupload.models.XUploadForm" );
$photos = new XUploadForm;
$this->render('create',array(
'model'=>$model,
'photos'=>$photos,
));
}
public function actionUpload( ) // From xupload nothing change
What you need to do is to create a custom form.
Copy the content from xupload _form and paste it removing the begin form - end form.
Add to your widget 'formView' the reference at the custom form.
what is the issue about submission form?
yes file limit can be done. Please make sure you follow these http://www.yiiframework.com/wiki/348/xupload-workflow/
Q1: form submition is not working, because the XUpload widget generates its own form tag. so your generated HTML has a form embebed in another form, you should use formView option of the widget to point to a view that has no form tags, as described in the xupload workflow wiki
Q2: You should use maxNumberOfFiles option in the widget config
It all should look like this:
<?php
$this->widget( 'xupload.XUpload', array(
'url' => Yii::app( )->createUrl( "/fadepreciation/upload"),
//our XUploadForm
'model' => $photos,
//We set this for the widget to be able to target our own form
'htmlOptions' => array('id'=>'fa-depreciation-form'),
'attribute' => 'file',
'multiple' => true,
//Note that we are using a custom view for our widget
//Thats becase the default widget includes the 'form'
//which we don't want here
'formView' => 'application.views.faDepreciation._form',
'options' => array('maxNumberOfFiles' => 5)
)
);
?>
Just use 'showForm' parameter as follow:
<?php
$this->widget( 'xupload.XUpload', array(
...
'showForm' => false,
...
));
?>
Maybe, this option been added in next versions of xupload.
I know that it's an old post but maybe this answer will help someone to solve this issue.
I found out that it's caused by the last line in the file /xupload/views/form.php (with default settings). It looks like the if statement is somehow working opposite... in mining that for false value it's rendering the code. For example:
<?php
echo $this->showForm;
if($this->showForm) echo CHtml::endForm();
echo $this->showForm;
?>
returns:
Maybe I'm missing something but it looks weird... isn't it?

Yii zii.widgets.grid.cgridview with type html render failed

I use this grid to view a table with data:
View part:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'news-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'name'=>'enable',
'type'=>'html',
'value'=>'$data->stateHtmlIcon',
),
),
)); ?>
In my model:
public function getStateHtmlIcon() {
if ($this->enable == AbstractModel::ENABLE) {
return '<font class="icon-enable"></font>';
} else {
return '<font class="icon-disable"></font>';
}
}
It doesn't work, the render stop when display column with stateHtmlIcon.
When I comment 'type'=>'html' in the grid (view part), it works but in the column the html is not rendered correctly
<font class="icon-enable"></font>
instead of icon displayed with css style.
So I think I don't use correctly 'type'=>'html?
I recently used
array(
'type' => 'raw',
'value' => 'CHtml::link([...])',
),
which does the job.
See also
http://www.yiiframework.com/doc/api/1.1/CDataColumn#type-detail
http://www.yiiframework.com/doc/api/1.1/CFormatter
You should use 'raw' as the type. see CFormatter
raw: the attribute value will not be changed at all.

Categories