Tuesday, December 30, 2014

Remove index.php from url YII

Standard



create .htaccess under www-->yiisitename 

add following code on .htaccess


Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php

http://localhost/sitename/index.php   - default yii url

http://localhost/sitename/  - now run like this

Wednesday, December 17, 2014

datetime - How to Minus & pluse two dates in php

Standard

How do I return the  date as pulse & Minus?

add days


 
                    $date=date_create(date("Y-m-d"));
                    date_add($date,date_interval_create_from_date_string("10 days"));
                    echo date_format($date,"Y-m-d"); 
Minus days
 
                   $mydate = date("Y-m-d");

$lastday = strtotime("-1 days", strtotime($mydate));

echo date("Y-m-d", $lastday);

Tuesday, December 16, 2014

create CSV report in DB data YII

Standard

hi guys this is my testing code about yii  CSV report i created data table name as deal  and i created Deal control & crud

this is my data table



CREATE TABLE IF NOT EXISTS `deals` (
  `DealId` int(11) NOT NULL AUTO_INCREMENT,
  `DealName` varchar(255) NOT NULL,
  `Dealdescription` text NOT NULL,
  `Price` int(11) NOT NULL,
  `Discount` float NOT NULL,
  `StartingDate` varchar(50) NOT NULL,
  `EndingDate` varchar(50) NOT NULL,
  `DealCategory` varchar(45) NOT NULL,
  `DriverId` int(11) NOT NULL,
  `CreateDate` datetime NOT NULL,
  `ModifiedDate` datetime NOT NULL,
  `Status` enum('0','1') NOT NULL DEFAULT '0',
  PRIMARY KEY (`DealId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

this is my report funtion in deal controller


condition = "DealId=".$DealId;
                                    $models=  Deals::model()->findAll($criteria);
                                   // echo '
'.  print_r($models,1).'
'; // die(); // Pick a filename and destination directory for the file // Remember that the folder where you want to write the file has to be writable $filename =Yii::getPathOfAlias('webroot').'/report/'.$DealId.'_report_by_'.$DealId.".csv"; // Actually create the file // The w+ parameter will wipe out and overwrite any existing file with the same name $handle = fopen($filename, 'w+'); // Write the spreadsheet column titles / labels fputcsv($handle, array( 'Dea lId', 'Deal Name', 'Deal description', 'Price', 'Discount', 'Start Date', 'EndDate', 'Deal Category', 'Driver Name', 'Status', )); foreach($models as $row) { fputcsv($handle, array ( $row['DealId'], $row['DealName'], $row['Dealdescription'], $row['Price'], $row['Discount'], $row['StartingDate'], $row['EndingDate'], $row['DealCategory'], $row['DriverId'], $row['Status'], )); } // Finish writing the file fclose($handle); $this->redirect(Yii::app()->getBaseUrl(true).'/report/'.$DealId.'_report_by_'.$DealId.'.csv', array('target'=>'_blank')); } $this->render('report',array( 'report'=>$report, )); } }
then i add report.php in view deal folder
add following code in report.php
actionReport(1);

?>
now you can get csv file

thank

Monday, December 8, 2014

YII ACCESS RULES from data base

Standard

this is represent haw add user access for specific users in to page

i have 2 table 

  1. 1.user table
  2. 2.user level table

user table


CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(128) NOT NULL,
  `email` varchar(128) NOT NULL,
  `Telephone` varchar(12) NOT NULL,
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ModifiedDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `lastvisit_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `superuser` int(1) NOT NULL DEFAULT '0',
  `UserLevel` int(1) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `email` (`email`),
  KEY `status` (`status`),
  KEY `superuser` (`superuser`)
);

Userlevel table

CREATE TABLE IF NOT EXISTS `userlevels` (
  `UserLevelId` int(11) NOT NULL AUTO_INCREMENT,
  `UserLevels` varchar(45) DEFAULT NULL,
  `CreateDate` datetime NOT NULL,
  `ModifiedDate` datetime NOT NULL,
  `Status` enum('0','1') NOT NULL DEFAULT '0',
  PRIMARY KEY (`UserLevelId`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `userlevels`
--

INSERT INTO `userlevels` (`UserLevelId`, `UserLevels`, `CreateDate`, `ModifiedDate`, `Status`) VALUES
(0, 'Guest', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0'),
(1, 'Admin', '2014-06-16 09:10:23', '0000-00-00 00:00:00', '1'),
(2, 'Staff', '2014-12-10 00:00:00', '0000-00-00 00:00:00', '1');

i created Userrule.php file under protect -> components folder


class Userrule extends CWebModule
{
 

 static private $_getaccess;
        
        public static function getAccess($userlevel) {
            
            if(is_array($userlevel))
                {
                 if (!self::$_getaccess) 
                 {
                $criteria = new CDbCriteria;
               $criteria->addInCondition('UserLevel',$userlevel,true); 


//                $criteria->params = array(':userlevel' => $userlevel);
                //Apply To Model
                $usernames = Users::model()->findAll($criteria);
//                echo '
'.  print_r($usernames,1).'
'; // die(); $Access_name = array(); foreach ($usernames as $username) array_push($Access_name,$username->username); self::$_getaccess = $Access_name; } return self::$_getaccess; } else { if (!self::$_getaccess) { $criteria = new CDbCriteria; $criteria->condition = 'UserLevel='.$userlevel; //Apply To Model $usernames = Users::model()->findAll($criteria); $Access_name = array(); foreach ($usernames as $username) array_push($Access_name,$username->username); self::$_getaccess = $Access_name; } return self::$_getaccess; } } }

in above param function  define which user should be access

now you can call this function  in to accessRules() in every controller & add which user level will be access


public function accessRules()
 {
  return array(
   array('allow',  // allow all users to perform 'index' and 'view' actions
    'actions'=>array('index','view'),
    'users'=>  Userrule::getAccess(array(0,1,6)),//send as array
   ),
                        array('allow',  // allow all users to perform 'index' and 'view' actions
    'actions'=>array('create'),
//    'users'=>  Userrule::getAccess(1),
                                'users'=>  Userrule::getAccess(array(1,6)),//send as array
//                            'users'=>array('admin','channa'),
   ),
   array('allow', // allow admin user to perform 'admin' and 'delete' actions
//    'actions'=>array('admin','delete'),
    'actions'=>array('delete','update'),
                            'users'=>  Userrule::getAccess(1),//send as variable
   ),
   array('deny',  // deny all users
    'users'=>array('*'),
   ),
  );
 }

sd

Friday, December 5, 2014

Yii User access rules

Standard



this for YII USER MODULE
Load and store the user's data every time a page is requested. To do this, modify the Controller class as follows:
i added this on  compound controller becouse  All controller classes for this application should extend from this base class.





          public function isGuest() {
            $user=User::model()->active()->findbyPk(Yii::app()->user->id);
//            print_r($user->superuser);
            if($user->superuser==0)
            {throw new CHttpException(403, 'You have no permission to view this content');}
           
            return UserModule::isAdmin();
        }

add this expression for all accessRules

 public function accessRules()
 {
            return array(

            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                        'actions'=>array('index','view','delete', 'admin'),
                        'expression'=> $this->isAdmin(),
                        ),
                       
            );
 }



Thursday, December 4, 2014

YII Send Email & get Template content from database Part -2

Standard



i created template folder on view & create file name as user_registation.php


sample email template by channa smcs

add add this site controll In code comment u can get basic undestand about what i did

public function actionEmail()
 { 
//            echo '
'.(print_r($_POST,1)).'
'; if(isset($_POST)) { // get data on variable by channa $variables=array( '{fname}'=>'channa', '{lname}'=>'bandara', '{email}'=>'channasmcs@gmail.com', '{dob}'=>'1989-01-01', '{password}'=>'thisiamy password', ); // get template using template name by channa $templatedata= self::getemailtemple('User Registration Template') ;// function in controller(configuration) // get template data in to variable by channa $description=$templatedata->description; $subject=$templatedata->subject; // send $description $description to VariableReplaceArray by channa $emailbody= $this->VariableReplaceArray($description, $variables) ; //function in controller(configuration) // send email detail to templte using renderPartial by channa $emailbodydetail=array( 'emailbodydetail'=>$emailbody, ); // send message detail to template by channa $messageUser = $this->renderPartial('/template/user_register',$emailbodydetail,true); // set up email configuration by channa $name = 'channa'; $email = 'hellochannasmcs@gmail.com'; $Telephone = '0715977097'; $to = 'hellochannasmcs@hotmail.com'; $subject = $subject; $messageAdmin = "Deal Admin"; self::email($name, $email, $subject, $messageUser); self::email($name, $email, $subject, $messageAdmin, TRUE); // // echo '
'.(print_r($messageUser,1)).'
'; // echo '
'.(print_r($messageAdmin,1)).'
'; } // $this->renderPartial('/template/view'); $this->render('email'); } }
i added  this on controoler file in configuration folder


//        get email template from database by channa
         public static function getemailtemple($temppalatename) {
            
             return $templatedetail=  Emailtemplate::model()->find("name='".$temppalatename."'");
            
        }
  // repalce variable syntex related with initialz input by channa
        
                public function VariableReplaceArray($message,$variables) 
                {
//                    print_r($variable);
                    
                     $getvariableArray=array_keys($variables);
                     $replacevariableArray=array_values($variables);
                     return str_replace($getvariableArray,$replacevariableArray,$message);
                }
        

YII Send Email & get Template content from database Part -1

Standard


in priviouse blog  make send user email & admin email .
in this blog i coding sent email using email template  & get email content from data base .

1.create email template table to insert email data




CREATE TABLE IF NOT EXISTS `emailtemplate` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(55) NOT NULL,
  `variables` varchar(255) NOT NULL,
  `subject` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `status` enum('1','0') NOT NULL DEFAULT '1' COMMENT '0=inactive,1=active',
  PRIMARY KEY (`id`),
  KEY `id` (`id`)
);

then  i created back end data manage option in my web site back end ..pretty cool



insert data like this 



INSERT INTO `emailtemplate` (`id`, `name`, `variables`, `subject`, `description`, `status`) VALUES
(1, 'User Registration Template', '{fname},{lname},{email},{dob}{password}', 'User Registration', '\r\n Thank You Regiter With Us ....

\r\n\r\n After you register, your request will be sent to the site administrator for approval. You will then receive an email with further instructions.

\r\n
\r\n Your name : {fname} {lname}
\r\n
\r\n Email : {email}
\r\n
\r\n DOB: {dob}
\r\n
\r\n Password: {password}
\r\n
\r\n Thank you
\r\n
\r\n Stream line staff
\r\n', '1');
now back end look like this


i initialize variable for uni q detail variable is static & we can use it globally

                   please see        Part -2



send email YII

Standard



In this tutorial, how to send user email & admin email .most developers are doesn't like  use extension i think that is good because that extension may be  have unnecessary things we need .but extension  is very helpful for reduce our coding time  .for this complete mr. gayan senjeewa  help  & i really appreciate for that .thanks 

here code

i used to controller file on components folder because.All controller classes for this application should extend from this base class.

this is main email sending function .add this on  controller 



 
//Controller in confuguration
 public static function email($userName, $userEmail, $subject, $message, $toAdmin = FALSE, $isCC = FALSE) {
            $subject='=?UTF-8?B?'.base64_encode($subject).'?=';
            $to = '';
            $from = '';
            $cc = '';
            
            if ($toAdmin) {
                $to = 'admin@mail.com';//admin Email
                $from = 'supportemail@mail.com'; //support user email for 

                
            } else {
                $to = $userEmail;
                $from =  'admin@mail.com';//admin Email
            }
            
            if($isCC) {
                $headers="From: <{$from}>\r\n".
                        "Cc: {$from}\r\n".
                        "Reply-To: {$from}\r\n".
                        "MIME-Version: 1.0\r\n".
                        "Content-Transfer-Encoding: 8bit\r\n".
                        "Content-Type: text/html; charset=ISO-8859-1\r\n";
            } else {
                $headers="From: <{$from}>\r\n".
                        "Reply-To: {$from}\r\n".
                        "MIME-Version: 1.0\r\n".
                        "Content-Transfer-Encoding: 8bit\r\n".
                        "Content-Type: text/html; charset=ISO-8859-1\r\n";
            }
            
            return mail($to, $subject,$message,$headers);
        }

i update actionContact funtion


 public function actionContact()
 {
  $model=new ContactForm;
  if(isset($_POST['ContactForm']))
  {

//   $model->attributes=$_POST['ContactForm'];
   if($model->validate())
   {
//    $name='=?UTF-8?B?'.base64_encode($model->name).'?=';
//    $subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
//    $headers="From: $name <{$model->email}>\r\n".
//     "Reply-To: {$model->email}\r\n".
//     "MIME-Version: 1.0\r\n".
//     "Content-Type: text/plain; charset=UTF-8";
//
//    mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
//    
                $name = $model->name;
                $email = $model->email;
                $Telephone = '0715977097';
                $to = 'admin@mail.com';
                $subject = $model->subject;
                    
                $messageUser = "Thank you for contacting us";
                      
                $messageAdmin = "
                Deal Admin,   
                
                you have email from   $model->name from $model->email
        
                $model->body
                thank you
                    
                ";
                self::email($name, $email, $subject, $messageUser);//send mail to user
                self::email($name, $email, $subject, $messageAdmin, TRUE);//send mail to admin  
    Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
    $this->refresh();
   }
  }
  $this->render('contact',array('model'=>$model));
 }

Monday, December 1, 2014

get image on Gridview YII

Standard




in this  you can call image view on YII grid view


<!--
 

 widget('zii.widgets.grid.CGridView', array( 
                'id'=>'modelname-grid',
                'dataProvider'=>$media->search(),
                'filter'=>$media,
                'columns'=>array(
//          'id',
                        array(       
                                    'name'=>'url',
                                    'header'=>'url ',
                                    'value'=>'CHtml::image(Yii::app()->request->baseUrl."/images/media/".$data->url,
                                     "",
                                     array(\'width\'=>100, \'height\'=>60))',
                                     'type'=>'raw',
                                ),
  'name',
  'createdate',
                        array(
                                'class'=>'CButtonColumn',
                                'template'=>'{delete}',
                        ),
                ),
        )); ?>