echo 'http://'. $_SERVER[HTTP_HOST] . $_SERVER['REQUEST_URI'];
Labels
- bootstrap (1)
- css (4)
- jquery (16)
- Live Demo (14)
- Others (2)
- PHP (4)
- prestashop 1.6 (7)
- Topic - Advance (7)
- Topic - basic (27)
- Topic - Semi Advance (16)
- wordpress (6)
- wordpress plugins (1)
- YII (14)
Thursday, October 30, 2014
Get current link or url including parameters in php
The code below shows how to get the current url or link and the parameters of a page.
for example we can get http://sample.com/?id=1&name=juan exactly the same. This is very useful in anchor with links
Tuesday, October 28, 2014
Display all model data using findAll in yii
To display all the data in a model,Using findAll function is one of the easiest way of doing it.
first we will assign findAll() in a variable.
$User = user::model()->findAll();$User is now an array, we will now loop our variable and display the content.
$User = user::model()->findAll();
foreach($User as $row){
echo 'username -' . $row;
}
We can also add sorting by just adding
'order'=>'id'note: you can change the 'id' to a different field that you want to sort Now, Inert the code to findAll() to add sorting and thats it.
$User = user::model()->findAll(array('order'=>'id DESC'));
foreach($User as $row){
echo 'username -' . $row;
}
Saturday, October 25, 2014
Insert session variable after logging in Yii
In this tutorial i will demonstrate how to insert session variable after logging in yii blog demo.
First open folder/protected/components/UserIdentity.php , we will use set state function to insert session variable.
$this->setState('sessionName', 'value of session');
insert the code inside public function authenticate(); Make sure that the code is inside the else clause before
we assign a session variable. The reason why we put it inside the else clause is that we want to start assigning
session variable if the user successfully pass all the login validation. Check the code below for sample.
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
private $_id;
/**
* Authenticates a user.
* @return boolean whether authentication succeeds.
*/
public function authenticate()
{
$user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$user->id;
$this->username=$user->username;
//insert session variable here
$this->setState('role_id', $user->role_id);
$this->setState('nameOfUser', $user->username);
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}
/**
* @return integer the ID of the user record
*/
public function getId()
{
return $this->_id;
}
}
to call the session variable anywhere, just use this code
echo Yii::app()->user->role_id; echo Yii::app()->user->nameOfUser;
Tuesday, October 21, 2014
Restrict access to a page without using accessRules (admin only) in yii
In this tutorial i will show you how to restrict diffrent types of access to a page without using accessRules().
In my example. I am going to edit my PostController.php, comment out some array in our accessRules, follow the codes below.
/**
* 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'),
// '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('admin'),
// ),
array('allow', // deny all users
'users'=>array('*'),
),
);
}
in PostController or any controller, we just need to insert this line of code to the controller function that we are going to restrict.
note that you can change Yii::app()->user->role_id depending on the id that you are going to validate. In my example, i already set an session variable role_id
after i login.
public function actionIndex()
{
if(isset(Yii::app()->user->role_id)){
if (Yii::app()->user->role_id != 1) {
throw new CHttpException(403, 'You have no permission to view this content');
}
}else{
throw new CHttpException(403, 'You have no permission to view this content');
}
// some codes .....
}
DRY , we dont want to repeat ourself from typing this line of code again and again so we will put it in a custom class. Check this tutorial for more clarification about creating custom class Create custom class and function in yii
class CustomClass
{
//level 1 = admin
public function adminOnly() {
if(isset(Yii::app()->user->role_id)){
if (Yii::app()->user->role_id != 1) {
throw new CHttpException(403, 'You have no permission to view this content');
}
}else{
throw new CHttpException(403, 'You have no permission to view this content');
}
}
}
in PostController, we just need to insert this line of code.
public function actionIndex()
{
CustomClass::adminOnly();
// some codes .....
}
Now our index page is restricted to admin only. It will only allow user to view the index page with a role id of 1.Note that you need to put this code CustomClass::adminOnly(); to any page that you want to restrict.
The advantage of using class is it lessen our time on writing tons codes again and again.
Updating the code is also easy since we are only going to update our main function and it will be applied to the rest.
Saturday, October 18, 2014
Create custom class and function in yii
first open 'folder/protected/components' and create CustomClass.php
add this code inside CustomClass.php , after this no more tweaking is needed.
CustomClass will automatically be loaded in our system.
class CustomClass
{
function test() {
echo 'The class work';
}
}
to call our custom function we can simply use this code
<div> hello, <?php CustomClass::test(); ?> </div>Seperating our custom function is a good idea if we are planning to use several function rather than combining it with other php files.
Wednesday, October 15, 2014
Auto show all image inside a folder using php
This script automatically gets all image name inside a folder and show it in html file.
This is very usefull if we have so many image that we want to show. for example we want to show
500 images, instead of writing 500 lines of code we can get it in less than 20 lines of code.
Explanation :
First we need to know where our image folder is,
We put all the names inside an array then we use array_diff to remove ".." and "."
We will loop all the names inside the array and show it in html using img tag.
<ul>
<?php
$imgpath = 'img/'; // take note of the trailing slash
//array_diff ,remove '..' and '.' so that it will not be included in our list
$img = array_diff(scandir($imgpath), array('..', '.'));
//Loop the array
foreach($img as $imgs){
?>
<li>
<div>
<img src=<?php echo $imgpath . $imgs; ?>>
</div>
</li>
<?php
}
?>
</ul>
Use subfolder and show the folder name
The first loop, We find first all the folders name.
The second loop finds the image name inside the first loop.
<ul>
<?php
$imgpath = 'img/'; // take note of the trailing slash
//array_diff ,remove '..' and '.' so that it will not be included on our list
$folder = array_diff(scandir($imgpath), array('..', '.'));
//Loop the array
foreach($folder as $folders){
//defined path + the folder name
$imgfolder = $imgpath . $folders;
//scan all the content of the folder and gets the content inside it.
$files2 = array_diff(scandir($imgfolder), array('..', '.'));
foreach($files2 as $imgs){
?>
<li>
<div>
<?php echo substr($folders,0,25 );?></br>
<img src=<?php echo $imgpath . $folders .'/'. $imgs; ?>>
</div>
</li>
<?php
}
}
?>
</ul>
Monday, October 13, 2014
Make the table auto adjust using css - fluid table 100% width
Make the table auto adjust using css
table{
width:100%;
table-layout: fixed;
padding:0 5%;
}
Live Demo
Sunday, October 12, 2014
Image upload and show the image in yii
Before we begin, we must have an img_path field in our database this is where we will store our image path for showing it later on our view, that is all we need for now.
Model
In our Model Post, we will create a non database field. we will use this non database field as a temporary holder for our image data.
Open the view where the form is generated, in my case it is under views/post/_form.php change the htmlOptions option to multipart
We will insert our image only if our controller receives a post request coming from our form
Yii::app()->basePath
get the root path of the yii application
preg_replace('@[\s!:;_\?=\\\+\*/%&#]+@', '-', $model->title)
replace 'space' to '-' ex ('hello m' is equals to 'hello-m'), I use my field title as the name of the image when it is save on the folder
mb_strtolower($model->image->getExtensionName())
change 'JPG' to 'jpg'for consistency.
Adding all up
ex : <img src=<?php echo $var->img_path;?>
Model
In our Model Post, we will create a non database field. we will use this non database field as a temporary holder for our image data.
class Post extends CActiveRecord
{
/**
* The followings are the available columns in table 'tbl_post':
* @var some var here
*/
public $image;
}
We will add validation on our function rules
class Post extends CActiveRecord
{
public function rules()
{
array('image', 'required','on'=>'insert'),
array('image', 'file', 'types'=>'jpg, gif, png,jpeg','allowEmpty' => true)
}
}
ViewOpen the view where the form is generated, in my case it is under views/post/_form.php change the htmlOptions option to multipart
$form=$this->beginWidget('CActiveForm', array(
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
We can now get our non database model in our view.
Note that setting the $image in our model is important. Our CActiveForm will get data fields on our model and use it on our view.
Controllerecho $form->labelEx($model, 'image'); echo $form->fileField($model, 'image'); echo $form->error($model, 'image');
We will insert our image only if our controller receives a post request coming from our form
public function actionCreate()
{
$model=new Post;
if(isset($_POST['Post']))
{
$model->attributes=$_POST['Post'];
//*** image upload start here ***//
$model->image=CUploadedFile::getInstance($model,'image');
//save the image on our folder with the name sample.jpg
$model->image->saveAs('../img/sample.jpg');
//store the path in our database
$model->img_path = 'img/sample.jpg');
//*** end image upload ***//
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
at this point the image uploader is already functional but we want it to be dynamic so we will add validation
check first if image is set before running the upload code
if(isset($model->image)){
//save the image on our folder with the name sample.jpg
$model->image->saveAs('../img/sample.jpg');
//store the path in our database
$model->img_path = 'img/sample.jpg');
}
make the naming more dynamic and safe.
I use the field title as the name of the image when it is save. you can change this depending on the database model you have.
$model->image->saveAs(Yii::app()->basePath . '/../img/' . preg_replace('@[\s!:;_\?=\\\+\*/%&#]+@', '-', $model->title) . '.' . mb_strtolower($model->image->getExtensionName()) );
$model->img_path = 'img/' . preg_replace('@[\s!:;_\?=\\\+\*/%&#]+@', '-', $model->title) . '.' . mb_strtolower($model->image->getExtensionName());
Explanation : Yii::app()->basePath
get the root path of the yii application
preg_replace('@[\s!:;_\?=\\\+\*/%&#]+@', '-', $model->title)
replace 'space' to '-' ex ('hello m' is equals to 'hello-m'), I use my field title as the name of the image when it is save on the folder
mb_strtolower($model->image->getExtensionName())
change 'JPG' to 'jpg'for consistency.
Adding all up
public function actionCreate()
{
$model=new Post;
if(isset($_POST['Post']))
{
$model->attributes=$_POST['Post'];
//*** image upload start here ***//
$model->image=CUploadedFile::getInstance($model,'image');
if(isset($model->image)){
//save the image on our folder with the name sample.jpg
$model->image->saveAs(Yii::app()->basePath . '/../img/' . preg_replace('@[\s!:;_\?=\\\+\*/%&#]+@', '-', $model->title) . '.' . mb_strtolower($model->image->getExtensionName()) );
//store the path in our database
$model->img_path = 'img/' . preg_replace('@[\s!:;_\?=\\\+\*/%&#]+@', '-', $model->title) . '.' . mb_strtolower($model->image->getExtensionName());
}
//*** end image upload ***//
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
We already have the image path in our database and the image itself in our folder. We can now show our image in view by simply calling the image path on any html file that we want it to appear.ex : <img src=<?php echo $var->img_path;?>
Saturday, October 11, 2014
Get data in yii using primary key or attribute
Get data in yii using findByPk or findByAttributes
Select an model base on pk
you can use this on any model that you had generated
$var = Users::model()->findByPk(Yii::app()->user->id);We can get the data that we want by simply calling our field name that is on our table for example
echo $var->name;note that the word 'name' is on our user table that why we can call it. Select an model base on field attribute In this case, if you dont know the primary key of what you are going to query but knows part of the field. you can use findByAttributes instead of using by findByPk
$var = Post::model()->findByAttributes(array('first_name'=>'juan'));
//select an model base on attribute with more settings
$var = Users::model()->findByAttributes(
array('first_name'=>'juan','last_name'=>'luna'),
'status=:status',
array(':status'=>1)
);
Include external file to a layout in yii
include external file to a layout.
require_once(Yii::app()->basePath . '/views/site/pages/sample.php');
Friday, October 10, 2014
Show the list of carrier in product page prestashop
We will show all the list of our carrier in our product page. to do this
First we will create a function in root_folder/controllers/front/ProductController.php , note that you can add this script on any
controller that you desired.
find this line of code and add the function
public function initContent()
{
parent::initContent();
.......
//add custom function here
$this->setTemplate(_PS_THEME_DIR_.'product.tpl');
}
add this function inside initContent()
function sinelectnacarrier(){
}
first define a null var inside our function
$namecar = '';Prepare our sql statement, there are many data that will show when we query our carrier because prestashop is not deleting the records of carrier in the database when we delete it in backoffice, the solution to this is to add an where clause.
$db = Db::getInstance(); $sql = 'SELECT * FROM '._DB_PREFIX_.'carrier WHERE '._DB_PREFIX_.'carrier.deleted = 0';We will loop our data and append it to our var $namecar
if ($results = Db::getInstance()->ExecuteS($sql))
foreach ($results as $row){
//append data to variable $namecar
$namecar.= "id_carrier : " . $row['id_carrier'] . ' - Name :' . $row['name'] . "";
}
we will return an array with the corresponding carrier id and its name.
return $namecar;And finally we will assign the return value of our function to a tpl file so that we can use it later on our tpl file
$this->context->smarty->assign("listOfCarrier", sinelectnacarrier());
Adding it all up
function sinelectnacarrier(){
$namecar = '';
$db = Db::getInstance();
//there are many data that will show here, we will remove the deleted carrier
$sql = 'SELECT * FROM '._DB_PREFIX_.'carrier WHERE '._DB_PREFIX_.'carrier.deleted = 0';
if ($results = Db::getInstance()->ExecuteS($sql))
foreach ($results as $row){
//append data to variable $namecar
$namecar.= "id_carrier : " . $row['id_carrier'] . ' - Name :' . $row['name'];
}
//return an array with the corresponding carrier id and its name
return $namecar;
}
// assign it to the tpl var
$this->context->smarty->assign("listOfCarrier", sinelectnacarrier());
To call our assigned value in our tpl file, open root_folder/themes/default-bootstrap/product.tpl
paste this code to the part where you want the list of carrier to be shown.
{$listOfCarrier}
Wednesday, October 8, 2014
Run javascript function on arrow keys when press
The function triggers when we press any keys on our keyboard. for example in our function left(), when we click our keyboards left button the div #result will change its html. see live demo for clarification.
function left() {
$('.result').html('left');
}
function right() {
$('.result').html('right');
}
function up() {
$('.result').html('up');
}
function down() {
$('.result').html('down');
}
document.onkeydown = function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 39:
left();
break;
case 37:
right();
break;
case 38:
up();
break;
case 40:
down();
break;
}
};
Live Demo
Expand and shrink animate on click jquery
This short jquery script makes an element shrink or expand on click. Simple logic is added to make the script toggle on click.
$(document).ready(function() {
var move = "expand";
$('div').click(function(){
if (move == "expand"){
$('div').animate({width:"30px",height:"30px"},500);
move = "shrink";
} else {
$('div').animate({width:"80px",height:"80px"},500);
move = "expand";
}
});
});
Live Demo
Bouncing ball using jquery every seconds
Create a bouncing ball using jquery. The div moves up after 1 second and move down after.
$(function () {
toggle=1;
function bounce(){
if(toggle == 1){
$(".ball").animate({top:'-=80px'}, 1000);
toggle = 0;
}else{
$(".ball").animate({top:'+=80px'},1000);
toggle = 1;
}
}
setInterval(bounce, 800);
});
Live Demo
Monday, October 6, 2014
Display the old price in prestashop tpl
This code shows the old price of a product if it is discounted in tpl
note: this tpl code only works if $product array is set within the page
note: this tpl code only works if $product array is set within the page
{convertPrice price=$product.price_without_reduction}
Alternate table td color using nth child
Use css nth child to alternate the colors on a table's td
table tr:nth-child(odd){ background-color:#D6E8FC; }
table tr:nth-child(even){ background-color:#fff; }
Timer function jquery
This timer is a sample of jquery that is using a normal javascript function to refresh or auto load its content.
Function timer is very useful when we want our javascript function to rerun for an specified time.
$(function () {
var num = 1;
//our function
function theFunction(){
num++;
$('.time').html(num);
}
//run every 1 second
setInterval(theFunction, 1000);
});
Live Demo
Auto refresh div with external php or html file in jquery
This tutorial will help you auto refresh a div using jquery load() function. We will change the #theDiv to the external php or html files content every 5 seconds
Html sample
take not that we first load the sample.php so that it will run immediately after our page loads. then after 5 seconds. the set interval will run and run every 5 seconds
Html sample
Jquery CodeThe content of this div will refresh
take not that we first load the sample.php so that it will run immediately after our page loads. then after 5 seconds. the set interval will run and run every 5 seconds
//load first the sample.php
$( "#theDiv" ).load( "../external/sample.php" );
//after 5 seconds run this code
setInterval(function () {
$( "#imgdiv" ).load( "../external/sample.php" );
}, 5000);
Jquery animate to right in 8 seconds
Use jquery to move / animate an element to the right or to left in 8 seconds. note that seconds in jquery is in thousand, so if we are going to make our animation in 15 seconds, it will be 15000
$(document).ready(function() {
$("div").animate({
left:'+=300px',
}, 8000);
});
Live Demo
Sunday, October 5, 2014
login form header wordpress plugin
this is a very light weight plugin that will show login input upon activation. modifying it is also easy. individual css and html file is included.
Download
transfer or move local website to online server in prestashop1.6
Transferring or migrating your locally hosted prestashop1.6 website to your online server looks difficult but in reality, it is easy. just follow these simple steps.
Clear your cache first
1. copy or upload all the files to our online server.
2. export the current database and save the .sql file.
3. On our online server and local server must have the same logical path.
4. create a database on our online server (better if same name as the local).
5. select first the created database and import the database .sql to online sql.
6 change the config/settings.inc.php to your proper website details, database password, name etc.
7. go to your database, under PS_CONFIGURATION table change PS_SHOP_DOMAIN and PS_SHOP_SSL to your registered domain. (ex. www.example.com).
8. go to your database, under PS_SHOPURL and change domain and domain_ssl to your registered domain. (ex. www.example.com).
1. copy or upload all the files to our online server.
2. export the current database and save the .sql file.
3. On our online server and local server must have the same logical path.
4. create a database on our online server (better if same name as the local).
5. select first the created database and import the database .sql to online sql.
6 change the config/settings.inc.php to your proper website details, database password, name etc.
7. go to your database, under PS_CONFIGURATION table change PS_SHOP_DOMAIN and PS_SHOP_SSL to your registered domain. (ex. www.example.com).
8. go to your database, under PS_SHOPURL and change domain and domain_ssl to your registered domain. (ex. www.example.com).
And thats it, it should be working.
You can also check these table, if you find any other trace of your old domain, you must change it to your online domain
– ps_shop_url
– ps_connections_source
– ps_pagenotfound
– ps_shop_url
– ps_connections_source
– ps_pagenotfound
Presta TPL naming guide
Shopping cart
step1(shopping cart summary)
shopping-cart.tpl
* the product table
shopping-cart-product-line.tpl
step2(login)
authenticate.tpl
step3(address)
order-address.tpl
step4(shipping)
order-carrier.tpl
step5(payment)
order-payment.tpl
step finish(order summation)
depends on the payment module, payment_execution.tpl
User Page
.
My account
my-account.tpl
Order History
history.tpl
My Personal Information
identity.tpl
My address
addresses.tpl
Upadte address
address.tpl
contact us form
contact-form.tpl
1st level category
category.tpl
jquery codes anywhere in html or php file in wordpress
If your having trouble on running jquery codes that is hardcoded in your .php or .html file try using these codes
jQuery(document).ready(function() {
alert('this is alert!');
})
Saturday, October 4, 2014
Total discounted price code in prestashop
By the default, The discounted price is not always available on any page when it is needed. In this tutorial, i will show you how to query the discounted price. i created a function that can be use on any controller if you need to get the discounted price.
function get_price_discounted($prod_id)
{
//get first the discount of an item
$sql1 ='SELECT reduction
FROM '._DB_PREFIX_.'specific_price
WHERE id_product = '.$prod_id ;
$discount = Db::getInstance()->getValue($sql1);
//get the current price of an item
$sql2 ='SELECT price
FROM '._DB_PREFIX_.'product
WHERE id_product = '.$prod_id ;
$priceOrig = Db::getInstance()->getValue($sql2);
//return the discounted value of a product
return $discountedPrice = ($priceOrig - ($priceOrig * $discount));
}
//use the function and assign it to a TPL variable
'discounted_price' => $this->get_price_discounted(Tools::getValue('id_product'));
Friday, October 3, 2014
Drop down menu in Yii with class
These codes show you how to make the zii.widgets.CMenu a drop down menu with custom classes for css customization
$this->widget('zii.widgets.CMenu', array(
'items' => array(
//1st sample
array(
'label' => 'drop down menu',
'url' => '#',
'linkOptions'=> array(
'class' => '',
),
'itemOptions' => array('class'=>'li_subClass'),
'items' => array(
array(
'label' => 'link 1',
'url' => '#'
),
array(
'label' => 'link 2',
'url' => '#'
),
)
),
//2nd sample with custom class
array(
'label' => 'drop down menu with custom class',
'url' => '#',
'linkOptions'=> array(
'class' => '',
),
'itemOptions' => array('class'=>'li_subClass'),
'items' => array(
array(
'label' => 'link 1',
'url' => '#'
),
array(
'label' => 'link 2',
'url' => '#'
),
)
),
//ordinary menu
array('label'=>'Style', 'url'=>array('#', 'view'=>'about')),
array('label'=>'Submit Painting','url'=>array('post/Submitpaintings', 'view'=>'about'),'itemOptions' => array('class'=>'btnSubmit')),
),
'encodeLabel' => false,
'htmlOptions' => array(
'class'=>'menu',
),
'submenuHtmlOptions' => array(
'class' => 'sub-menu',
)
));
Subscribe to:
Comments (Atom)

