'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange' => false,
'validateOnType' => false,
// 'errorCssClass' => 'has-error',
// 'successCssClass' => 'has-success',
// 'afterValidate' => 'js:function(form, data, hasError){}'
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
Tuesday, December 8, 2015
Yii validation OnSubmit OnChange
Thursday, December 3, 2015
Yii MetaTags
Yii::app()->clientScript->registerMetaTag(null, null, null,array('charset'=>'utf-8'));
Yii::app()->clientScript->registerMetaTag('IE=edge',null,null,array('http-equiv'=>'X-UA-Compatible'));
Yii::app()->clientScript->registerMetaTag('text/html;charset=UTF-8', null, 'content-type');
Yii::app()->clientScript->registerMetaTag('width=device-width, initial-scale=1.0',null,null,array('name'=>'viewport'));
Yii::app()->clientScript->registerMetaTag(Yii::app()->name, 'author');
Yii::app()->clientScript->registerMetaTag('Jibon Bikash Roy, jibon.bikash@gmail.com', 'developer');
Yii::app()->clientScript->registerMetaTag('Keyword1, keyword2', 'keywords');
//Output
Yii::app()->clientScript->registerMetaTag('Site Description Details', 'description');
//Output
Yii::app()->clientScript->registerMetaTag('text/html;charset=UTF-8', null, 'content-type');
//Output
Yii::app()->clientScript->registerMetaTag('userid=xyz; expires=Wednesday, 08-Aug-15 23:59:59 GMT;', null, 'cookie');
//Output
Yii::app()->clientScript->registerMetaTag('NOINDEX, NOFOLLOW', 'ROBOTS');
//Output
Yii::app()->clientScript->registerMetaTag('INDEX, NOFOLLOW', 'ROBOTS');
//Output
Yii::app()->clientScript->registerMetaTag('NOINDEX, FOLLOW', 'ROBOTS');
//Output
facebook Share Metataq
Yii::app()->clientScript->registerMetaTag(Yii::app()->getBaseUrl(true).'/uploads/workshop/thumbs/'.$model->banner, null, null, array('property' => "og:image"));
Yii::app()->clientScript->registerMetaTag($model->course_title, null, null, array('property' => "og:title"));
Yii::app()->clientScript->registerMetaTag($this->createAbsoluteUrl('longCourse/view',array('id'=>$model->id)), null, array('property' => "og:url"));
Yii::app()->clientScript->registerMetaTag(Yii::app()->name, null, null, array('property' => "og:site_name"));
Yii::app()->clientScript->registerMetaTag("website", null, null, array('property' => "og:type"));
Monday, November 30, 2015
Yii addNotInCondition
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->addNotInCondition('id',array(1));
$criteria->compare('name',$this->name,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
Saturday, November 28, 2015
Yii How to Add and Upload an Image using editMe
$this->widget('ext.editMe.widgets.ExtEditMe', array(
'model' => $model,
'attribute' => 'content',
'ckeConfig'=>array('enableTabKeyTools'=>true,'enterMode'=>2),
'filebrowserImageBrowseUrl'=>Yii::app()->baseUrl.'/kcfinder/browse.php?type=files',
'filebrowserImageUploadUrl'=>Yii::app()->baseUrl.'/kcfinder/upload.php?type=files',
'filebrowserBrowseUrl'=>Yii::app()->baseUrl.'/kcfinder/upload.php?type=files',
'filebrowserUploadUrl'=>Yii::app()->baseUrl.'/kcfinder/upload.php?type=files'
));
// Edit configure in kcfinder/conf/config.php
'disabled' => false,
'uploadURL' => "../upload",
//
Dowbload kcfinder from http://kcfinder.sunhater.com/download
Thursday, November 26, 2015
Yii Redirect to login for unauthorized user
public function accessRules()
{
return array(
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','index','view','create','update'),
//'users'=>array('admin'),
'expression'=>'$user->isAdmin()',
),
array('deny', // deny all users
'users'=>array('*'),
'deniedCallback' => array($this, 'redirecting'),
),
);
}
public function redirecting(){
$this->redirect(array('/login'));
}
Wednesday, November 25, 2015
yii how to use og meta tag for facebook share
Yii::app()->clientScript->registerMetaTag(Yii::app()->name,null,null,array('property'=>'og:site_name'));
Yii::app()->clientScript->registerMetaTag($this->createAbsoluteUrl('video/details',array('id'=>$video->id, 'slug'=>$video->slug)),null,null,array('property'=>'og:url'));
Yii::app()->clientScript->registerMetaTag($video->tittle,null,null,array('property'=>'og:title'));
Yii::app()->clientScript->registerMetaTag($video->details,null,null,array('property'=>'og:description'));
Yii::app()->clientScript->registerMetaTag("movie",null,null,array('property'=>'og:type'));
if($video->screensort):
$path_image = YiiBase::getPathOfAlias('webroot').'/upload/'.$video->screensort;
$cropimg= Yii::app()->easyImage->thumbSrcOf($path_image, array('crop' => array('width' => 270, 'height' => 150)));
Yii::app()->clientScript->registerMetaTag($cropimg,null,null,array('property'=>'og:image'));
Yii::app()->clientScript->registerMetaTag("270",null,null,array('property'=>'og:image:width'));
Yii::app()->clientScript->registerMetaTag("150",null,null,array('property'=>'og:image:height'));
endif;
Wednesday, October 28, 2015
Css Hack for Safari Browser
@media screen and (-webkit-min-device-pixel-ratio:0) {
/* put webkit CSS here*/
.search-form{
margin-top: 8px; margin-bottom: 5px; margin-left: -78px !important; margin-top: -73px; position: absolute;
}
// for Safari
::i-block-chrome, .eflat-menu li a {
padding-right:17px !important;
}
}
Wednesday, October 14, 2015
Yii Delete Records With Multi Check Box
Yii::app()->clientScript->registerScript('deleteall','
$("#deleteall").click(function(){
var checked=$("#casecategory-grid").yiiGridView("getChecked","casecategory-grid_c0");
var count=checked.length;
if(count>0 && confirm("Do you want to delete these "+count+" item(s)"))
{
$.ajax({
data:{checked:checked},
url:"'.CHtml::normalizeUrl(array('Casecategory/removeall')).'",
success:function(data){$("#casecategory-grid").yiiGridView("update",{});},
});
}
});
');
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'casecategory-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'class'=>'CCheckBoxColumn', //CHECKBOX COLUMN ADDED.
'selectableRows'=>2, //MULTIPLE ROWS CAN BE SELECTED.
),
'name',
array(
'name'=>'parent',
'type'=>'raw',
'value'=>'$data->getparent ? $data->getparent->name : " No Parent"',
// 'filter' => CHtml::listData(User::model()->findAll(), 'id', 'fullname'),
),
array(
'class'=>'CButtonColumn',
),
),
));
echo CHtml::button("Remove Selected Items",array("id"=>"deleteall"));
// Controller
public function actionRemoveall()
{ if(Yii::app()->request->getIsAjaxRequest())
{
$checkedIDs=$_GET['checked'];
foreach($checkedIDs as $id)
Casecategory::model()->deleteByPk($id);
}
}
Wednesday, October 7, 2015
Create a widget on Yii
// protected/components/SubscriberFormWidget.php
class SubscriberFormWidget extends CWidget{
//put your code here
public $form;
public function run()
{
$model=new Subscribe;
// Uncomment the following line if AJAX validation is needed
if(isset($_POST['ajax']) && $_POST['ajax']==='subscribe-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['Subscribe']))
{
$model->attributes=$_POST['Subscribe'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('subscriberFormWidget',array(
'modelsubs'=>$model,
));
// $this->render('subscriberFormWidget', array('modelsubs'=> new Subscribe()));
}
}
// protected/components/views/subscriberFormWidget.php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'subscribe-form',
'action'=>Yii::app()->createUrl('subscribe/create'),
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
)
));
echo $form->error($modelsubs,'mobile_no');
echo $form->textField($modelsubs,'mobile_no',array('size'=>60,'maxlength'=>254,'class'=>'subscribe-now', 'placeholder'=>'Enter Your Mobile Number …'));
echo CHtml::submitButton($modelsubs->isNewRecord ? 'Subscribe Now' : 'Save',array('class'=>'btn btn-info btn-lg'));
$this->endWidget();
Inside any view
$this->widget('SubscriberFormWidget');
Wednesday, September 16, 2015
Yii EGMap color change
Add 'style' => '['.EGMap::MAPTYPECONTROL_STYLE_HORIZONTAL_BAR.', "map_style"]', in view page
$gMap = new EGMap();
$gMap->setWidth('auto');
$gMap->setHeight(500);
$gMap->zoom = 11;
$mapTypeControlOptions = array(
'position' => EGMapControlPosition::RIGHT_TOP,
'style' => '['.EGMap::MAPTYPECONTROL_STYLE_HORIZONTAL_BAR.', "map_style"]',
);
Replace this code in EGMap.php
public function registerMapScript($afterInit=array(), $language = null, $region = 'bd', $position = CClientScript::POS_LOAD)
{
// TODO: include support in the future
$params = 'sensor=false';
$params .= '&libraries=places';
if ($language !== null)
$params .= '&language=' . $language;
if ($region !== null)
$params .= '& region=' . $region;
CGoogleApi::init();
CGoogleApi::register('maps', '3', array('other_params' => $params));
$this->registerPlugins();
$js = '';
$init_events = array();
if (null !== $this->_appendTo)
{
$init_events[] = "$('{$this->getContainer()}').appendTo('{$this->_appendTo}');" . PHP_EOL;
}
// this for color change
$style_array_here="[
{ featureType: 'landscape',
elementType: 'all',
stylers: [ { hue: '#fad99d' }, { saturation: 87 }, { lightness: -10 }, { visibility: 'on' } ] },{ featureType: 'water', elementType: 'all', stylers: [ { hue: '#fad99d' }, { saturation: 82 }, { lightness: 16 }, { visibility: 'on' } ] } ];
var styledMap = new google.maps.StyledMapType(styles,
{name: 'Styled Map'})
";
$init_events[] = 'var styles = '.$this->encode($style_array_here).';' . PHP_EOL;
$init_events[] = 'var mapOptions = ' . $this->encode($this->options) . ';' . PHP_EOL;
$init_events[] = 'var '.$this->getJsName() . ' = new google.maps.Map(document.getElementById("' . $this->getContainerId() . '"), mapOptions); '.$this->getJsName().'.mapTypes.set("map_style", styledMap); '.$this->getJsName().'.setMapTypeId("map_style");' . PHP_EOL;
// add some more events
$init_events[] = $this->getEventsJs();
$init_events[] = $this->getMarkersJs();
$init_events[] = $this->getDirectionsJs();
$init_events[] = $this->getPluginsJs();
$init_events[] = $this->getPolygonsJs();
$init_events[] = $this->getCirclesJs();
$init_events[] = $this->getRectanglesJs();
if (is_array($afterInit))
{
foreach ($afterInit as $ainit)
$init_events[] = $ainit;
}
if ($this->getGlobalVariable($this->getJsName() . '_info_window'))
$init_events[] = $this->getJsName() . '_info_window=new google.maps.InfoWindow();';
if ($this->getGlobalVariable($this->getJsName() . '_info_box') && $this->resources->itemAt('infobox_config'))
$init_events[] = $this->getJsName (). '_info_box=new InfoBox('.
$this->resources->itemAt('infobox_config').');';
// declare the Google Map Javascript object as global
$this->addGlobalVariable($this->getJsName(), 'null');
$js = $this->getGlobalVariables();
Yii::app()->getClientScript()->registerScript('EGMap_' . $this->getJsName(), $js, CClientScript::POS_HEAD);
$js = 'function ' . $this->_containerId . '_init(){' . PHP_EOL;
foreach ($init_events as $init_event)
{
if ($init_event)
{
$js .= $init_event . PHP_EOL;
}
}
$js .= '
} google.maps.event.addDomListener(window, "load",' . PHP_EOL . $this->_containerId . '_init);' . PHP_EOL;
Yii::app()->getClientScript()->registerScript($this->_containerId . time(), $js, CClientScript::POS_END);
}
Tuesday, September 15, 2015
yii Select2 replacement for select boxes
Yii::import('ext.select2.Select2');
$data = CHtml::listData(Judge::model()->findAll(),'name', 'name');
echo Select2::multiSelect('judge', $model->judge, $data, array(
'required' => 'required',
'style' => 'width: 237px;',
'placeholder' => 'Judge Name',
'select2Options' => array('maximumSelectionSize' => 1,),
));
Wednesday, September 9, 2015
Add width, height and others attribute for image and link
echo CHtml::link(CHtml::image(Yii::app()->baseUrl."/uploads/promotion/".$promotion->image,$promotion->description,array('class'=>'promotion', 'title'=>$promotion->description)), "$promotion->url", array('target'=>'_self','class'=>'promotion'));
echo CHtml::image(Yii::app()->request->baseUrl.'/img/image.png',
'this is alt tag of image',
array('width'=>'100px','height'=>'100px','title'=>'image title here'));
Sunday, September 6, 2015
Limit Content Length in Yii
public function getPagesummary($id=null){
$model= Model::model()->findByPk($id);
$wordlimit= strip_tags($model->details);
if (str_word_count($wordlimit, 0) > 40) {
$words = str_word_count($wordlimit, 2);
$pos = array_keys($words);
$textt = substr($wordlimit, 0, $pos[40]) . '...';
return $textt;
}
else
return $wordlimit;
}
public function limitWords($id, $limit=50) {
$model= Model::model()->findByPk($id);
$text= strip_tags($model->details);
$word_arr = explode(" ", $text);
if (count($word_arr) > $limit) {
$words = implode(" ", array_slice($word_arr , 0, $limit) ) . ' ...';
return $words;
}
return $text;
}
$model->getPagesummary($model->id)
$model->limitWords($model->id)
yii Get The First Image From a Post
public function catch_that_image($str){
$output = preg_match_all('/
]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $str, $matches);
return $matches[1][0];
}
$recentnew->catch_that_image($recentnew->details);
Monday, August 24, 2015
Yii count()
echo Video::model()->count();
by using params: Video::model()->count('video_type <> :type', array('type' => $video_type);
using commandBuilder: Yii::app()->db->createCommand() ->select('COUNT(*)') ->from('video') ->where('video_type <> '.$video_type) ->queryScalar();
Saturday, August 22, 2015
yii Criteria date_format between
$lastmonth= date('Y-m-d', strtotime('today - 30 days'));
$today= date('Y-m-d');
$criteria = new CDbCriteria;
$criteria->addCondition(
"DATE_FORMAT(create_date, '%Y-%m-%d') >='$lastmonth'
and
DATE_FORMAT(create_date, '%Y-%m-%d') <= '$today'"
);
$criteria->limit = 10;
$criteria->order = 'total_view DESC';
//$criteria->group = 'id';
$modelvideo= Video::model()->findAll($criteria);
Monday, August 17, 2015
Register function through clientScript->registerScript
Yii::app()->clientScript->registerScript('rightclick', "
$('body').bind('contextmenu', function(e){
return false;
});
");
Tuesday, August 11, 2015
yii CStarRating displays and rating
$this->widget('CStarRating',array(
'name'=>'video_rating',
// 'minRating'=>1,
// 'maxRating'=>10,
'starCount'=>10,
'allowEmpty' => FALSE,
'value'=>$model->videorating($model->id),
'callback'=>'
function(){
$.ajax({
type: "POST",
url: "'.Yii::app()->createUrl('video/rating', array('id'=>$model->id)).'",
data: "star_rating=" + $(this).val(),
success: function(data){
$("#mystar_voting").html(data);
}})}'
));
Wednesday, August 5, 2015
Yii homeUrl and baseUrl
Yii::app()->getBaseUrl(true); // => http://localhost/yii_projects Yii::app()->getHomeUrl(); // => /yii_projects/index.php Yii::app()->getBaseUrl(false); // => /yii_projects
Thursday, July 30, 2015
Using counters with ActiveRecord
public function actionDetails($id)
{
$video = Video::model()->findByPk($id);
$video->total_view += 1;
$video->save();
$this->render('details',array(
'model'=>$this->loadModel($id),
));
}
public function actionDetails($id)
{
$video = Video::model()->findByPk($id);
$video->saveCounters(array('total_view'=>1));
$this->render('details',array(
'model'=>$this->loadModel($id),
));
}
public function actionDetails($id) {
Video::model()->updateCounters(
array('total_view'=>1),
array('condition' => "id = :id"),
array(':id' => $id),
);
$this->render('details', array('video' => $video));
}
Saturday, May 30, 2015
Yii EGMap With Autocomplete Search Location
1. Add this function into extension EGMap.php
public function addAutocomplete($inputId = null)
{
if ($inputId === null)
$autocomplete = new EGMapAutocomplete();
else
$autocomplete = new EGMapAutocomplete($inputId);
$this->resources->add('autocomplete', new CTypedList('EGMapAutocomplete'));
$this->resources->itemAt('autocomplete')->add($autocomplete);
}
public function getAutocompleteJs()
{
$return = '';
if (null !== $this->resources->itemAt('autocomplete'))
{
foreach ($this->resources->itemAt('autocomplete') as $autocomplete)
{
$return .= $autocomplete->toJs($this->getJsName());
$return .= "\n ";
}
}
return $return;
}
2. Create New file EGMapAutocomplete.php
class EGMapAutocomplete extends EGMapBase
{
//String $url url of image
protected $inputId;
protected $marker_object = 'google.maps.places.Autocomplete';
const GMAP_LIBRARY = 'http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false';
public function __construct( $inputId = 'searchTextField',$js_name = 'autocomplete')
{
$this->inputId = $inputId;
$this->setJsName($js_name);
}
/**
*
* @return inputId
*/
public function getInputId()
{
return $this->inputId;
}
/**
*
* @return string js code to create the autoComplete
*/
public function toJs($map_js_name = 'map')
{
$this->options['map'] = $map_js_name;
$return = "var input = document.getElementById('".EGMap::encode($this->inputId)."');". PHP_EOL;
$return .= $this->getJsName() . ' = new ' . $this->marker_object . '(input);' . PHP_EOL;
$return .= $this->getJsName().".bindTo('bounds', ".$map_js_name.");" . PHP_EOL;
$event = new EGMapEvent('place_changed', "function() {
".$map_js_name."_info_window.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
".$map_js_name.".fitBounds(place.geometry.viewport);
} else {
".$map_js_name.".setCenter(place.geometry.location);
".$map_js_name.".setZoom(17);
}
".$map_js_name."_marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
".$map_js_name."_info_window.setContent('' + place.name + '
' + address);
".$map_js_name."_info_window.open(map, marker);
}",false);
$return .= $event->getEventJs($this->getJsName()) . PHP_EOL;
return $return;
}
}
3. Add $params .= '&libraries=places'; this into registerMapScript function before CGoogleApi::init();
4. Add $init_events[] = $this->getAutocompleteJs(); into registerMapScript function bellow $init_events[] array.
Yii::import('ext.EGMap.*');
$gMap = new EGMap();
$gMap->setJsName('map');
$gMap->setWidth(827);
$gMap->setHeight(400);
$gMap->zoom = 6;
$gMap->addAutocomplete();
$mapTypeControlOptions = array(
'position' => EGMapControlPosition::RIGHT_TOP,
'style' => EGMap::MAPTYPECONTROL_STYLE_HORIZONTAL_BAR
);
$gMap->mapTypeId = EGMap::TYPE_ROADMAP;
$gMap->mapTypeControlOptions = $mapTypeControlOptions;
$icon = new EGMapMarkerImage("http://google-maps-icons.googlecode.com/files/workoffice.png");
$icon->setSize(32, 37);
$icon->setAnchor(16, 16.5);
$icon->setOrigin(0, 0);
$count = $dataProvider->getTotalItemCount();
if ($count > 0) {
$i = 0;
foreach($dataProvider->getData() as $record) {
$marker[$i] = new EGMapMarker($record->lat, $record->lng, array('title' => Yii::t('catalog', $record->nama),
'icon'=>$icon, 'draggable'=>false), 'marker', array());
$info_window_m[$i] = new EGMapInfoWindow(''.$record->nama.'');
$marker[$i]->addHtmlInfoWindow($info_window_m[$i]);
$gMap->addMarker($marker[$i]);
$i++;
}
$gMap->setCenter($marker[0]->lat, $marker[0]->lng);
$gMap->zoom = 12;
} else {
$gMap->setCenter(23.716564, 90.402359);
}
$gMap->renderMap(array(), Yii::app()->language);
Tuesday, May 26, 2015
Yii CJuiDatePicker
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'attribute' => 'from_date',
'options' => array(
'dateFormat' => 'dd-mm-yy',
'showOtherMonths' => true,
'selectOtherMonths' => true,
'changeYear' => true,
'changeMonth' => true,
'showButtonPanel' => FALSE,
),
'htmlOptions' => array(
'size' => '10',
'maxlength' => '10',
),
));
Table prefix in Yii
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=proficiency',
'emulatePrepare' => true,
'username' => 'test',
'password' => '12345665',
'charset' => 'utf8',
'tablePrefix' => 'my_',
),
Saturday, May 23, 2015
DataProvider with date condition
$dataProvider2=new CActiveDataProvider('LongCourse', array(
'criteria'=>array(
'condition'=>"DATE(t.course_show_date) >= DATE(NOW()) AND published=:published ",
'params'=>array(':published'=>'Yes'),
),
'sort'=>array(
'defaultOrder'=>'id DESC',
),
'pagination'=>false,
));
Friday, May 22, 2015
Yii file_exists() Checking
if(file_exists("".Yii::getPathOfAlias('webroot')."/images/certificate/".$model->certificate_coc_no"")){
echo CHtml::image(Yii::app()->baseUrl."/images/certificate/".$model->certificate_coc_no,
$model->name,
array("width"=>"100px" ,"height"=>"80px", "style"=>"vertical-align:middle; margin-left: auto; margin-right: auto; display: block; float: none;"));
}
OR
if(file_exists("".YiiBase::getPathOfAlias('webroot')."/images/certificate/".$model->certificate_coc_no"")){
echo CHtml::image(Yii::app()->baseUrl."/images/certificate/".$model->certificate_coc_no,
$model->name,
array("width"=>"100px" ,"height"=>"80px", "style"=>"vertical-align:middle; margin-left: auto; margin-right: auto; display: block; float: none;"));
}
Tuesday, May 19, 2015
Thursday, April 30, 2015
Deny user agent strings Yii
array(
'deny',
'expression' => function(){
return strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE;
},
'message' => "You're using the wrong browser, sorry.",
),
Subscribe to:
Comments (Atom)