Wednesday, September 9, 2015

prestashop add custom field in contact us form


In this tutorial, i will show you how to add custom field in our prestashop1.6 default contact form, first lets open \default-bootstrap\contact-form.tpl and add this codes
<p class="form-group">
 <label for="email">{l s='Name'}</label>
 <input class="form-control grey" type="text" id="name" name="name" value="{if isset($name)}{$name|escape:'htmlall':'UTF-8'|stripslashes}{/if}" />      
</p>
<p class="form-group">
 <label for="email">{l s='Contact Number'}</label>
 <input class="form-control grey" type="text" id="number" name="number" value="{if isset($number)}{$number|escape:'htmlall':'UTF-8'|stripslashes}{/if}" />
</p>

You may add this in any arrangement you like but make sure that is is within the form

 Next Step: lets open our Controller for our contact form. \controllers\front\ContactController.php
Find this line
$message = Tools::getValue('message'); // Html entities is not usefull, iscleanHtml check there is no bad html tags.
add this after
$name = Tools::getValue('name');
$number = Tools::getValue('number');
And then we must pass this to the mail template, find this line of codes
if (!count($this->errors))
   {
    $var_list = array(
        '{order_name}' => '-',
        '{attached_file}' => '-',
        '{message}' => Tools::nl2br(stripslashes($message)),
        '{email}' =>  $from,
        '{product_name}' => '',       
       ); 
It should look like the codes below, we added 2 new variable
if (!count($this->errors))
   {
    $var_list = array(
        '{order_name}' => '-',
        '{attached_file}' => '-',
        '{message}' => Tools::nl2br(stripslashes($message)),
        '{email}' =>  $from,
        '{product_name}' => '',
        '{name}' => Tools::nl2br(stripslashes($name)),
        '{number}' => Tools::nl2br(stripslashes($number)),
       ); 
We are going to give back the variables that we have submitted in our controller to our view so that when a user encounter an mistake, his/her input will remain. find this code
public function initContent()
{
 parent::initContent();

 $this->assignOrderList();

 $email = Tools::safeOutput(Tools::getValue('from',
 ((isset($this->context->cookie) && isset($this->context->cookie->email) && Validate::isEmail($this->context->cookie->email)) ? $this->context->cookie->email : '')));
 $this->context->smarty->assign(array(
  'errors' => $this->errors,
  'email' => $email,
  'fileupload' => Configuration::get('PS_CUSTOMER_SERVICE_FILE_UPLOAD'),
  'max_upload_size' => (int)Tools::getMaxUploadSize()
 ));

 if (($id_customer_thread = (int)Tools::getValue('id_customer_thread')) && $token = Tools::getValue('token'))
 {
  $customer_thread = Db::getInstance()->getRow('
   SELECT cm.*
   FROM '._DB_PREFIX_.'customer_thread cm
   WHERE cm.id_customer_thread = '.(int)$id_customer_thread.'
   AND cm.id_shop = '.(int)$this->context->shop->id.'
   AND token = \''.pSQL($token).'\'
  ');

  $order = new Order((int)$customer_thread['id_order']);
  if (Validate::isLoadedObject($order))
   $customer_thread['reference'] = $order->getUniqReference();
  $this->context->smarty->assign('customerThread', $customer_thread);
 }

 $this->context->smarty->assign(array(
  'contacts' => Contact::getContacts($this->context->language->id),
  'message' => html_entity_decode(Tools::getValue('message')),
 ));

 $this->setTemplate(_PS_THEME_DIR_.'contact-form.tpl');
}
change $this->context->smarty->assign(array( take note that we added our 2 variables
$this->context->smarty->assign(array(
 'contacts' => Contact::getContacts($this->context->language->id),
 'message' => html_entity_decode(Tools::getValue('message')),
 'name' => html_entity_decode(Tools::getValue('name')),
 'number' => html_entity_decode(Tools::getValue('number')),
));

At this point everything is already working but first we need to indicate in our email template that we must add the 2 new variables, Open \mails\en\contact.html 
<span style="color:#333"><strong>Customer Name:</strong></span> {name}<br /><br />
<span style="color:#333"><strong>Customer Number:</strong></span> {number}<br /><br />
And thats it it should work!!

Friday, August 28, 2015

Add back button to prestashop1.6 inside product page

This code shows how to add back button inside prestashops product page, The button will only show if you are inside a product page ,you can also add the codes to breadcrumbs.tpl for better viewing
{if $page_name == 'product'} 
 <div class="pull-right">   
   <a class="backCat" href="{$link->getCategoryLink($category->id_category, $category->link_rewrite)|escape:'html':'UTF-8'}" title="Back"><i class="fa fa-arrow-left"></i> Back</a>
 </div> 
{/if}
Css
.backCat{
 display: inline-block;
 padding: 0px 11px;
 border: 1px solid #D6D4D4;
 font-weight: bold;
 font-size: 12px;
 line-height: 24px;
 min-height: 6px;
 border-radius: 3px;
 overflow: hidden;
 margin-bottom: 16px;
 position: relative;
 z-index: 1;
}
In some case, if the category of our product is two or more, we can use an alternative that is much simple
<a class="backCat" href="{literal}javascript:history.back();{/literal}" title="Back"><i class="fa fa-arrow-left"></i> Back</a>

Friday, May 22, 2015

Real time calculator using jquery

In this tutorial, i will show you how i created a realtime calculator using jquery
This is the specs of our calculator
-on type, the calculator must automatically solve the math equation.
-when we click the operators, it must automatically calculate the inputed numbers in the field
-there must be validation, only numbers is required.
Im going to show first the live example.
first we created the html
 
+ =
+ - x /
Then the javascript
We will capture the input of the user when he/she types on the field
 $( ".1st" ).keyup(function() {
  var1s = $( ".1st" ).val(); //get the value of input      
  if(var1s.match(/^\d+$/)){
   $('.messageError').html(''); //validate if numbers
   sums();      
  }else{
   $('.messageError').html('sorry number only for the first value'); //throws warning if error      
  }     
 });
 
 $( ".2nd" ).keyup(function() {
  var2s = $( ".2nd" ).val();      
  if(var2s.match(/^\d+$/)){
   $('.messageError').html('');
   sums();      
  }else{
   $('.messageError').html('sorry number only for the second value');      
  }     
 });     
 
Next is we will capture the event when an user clicks on our operator
$( ".add" ).click(function() {     
  $('.operator').html('+'); 
  sums();      
 });
 $( ".minus" ).click(function() {
  $('.operator').html('-'); 
  sums();     
 });
 $( ".times" ).click(function() {
  $('.operator').html('x');
  sums();     
 });
 $( ".divide" ).click(function() {
  $('.operator').html('/');
  sums();     
});
We will create an function for sum(), this will calculate the math equation.
 function sums(){
  var1 =  parseInt($( ".1st" ).val()); 
  var2 =  parseInt($( ".2nd" ).val()); 
  operator = $( ".operator" ).html();   
  sum = (var1 + var2);
  switch (operator) { 
   case '+': 
    sum = (var1 + var2);
    break;
   case '-': 
    sum = (var1 - var2);
    break;
   case 'x': 
    sum = (var1 * var2);
    break;  
   case '/': 
    sum = (var1 / var2);
    break;
   default:
    sum = (var1 + var2);
  }     
   $( ".answer" ).html(sum);
   
   $(".answer").each(function(c, obj){
     $(obj).text(addCommas(parseFloat($(obj).text()).toFixed(2)));
   });    
 }
We also add addCommas() function for auto conversion of commas ex. 5,000.00
 
 function addCommas(nStr)
 {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
 } 
And then the is the overall script when combined
$( document ).ready(function() {
 $( ".1st" ).keyup(function() {
  var1s = $( ".1st" ).val(); //get the value     
  if(var1s.match(/^\d+$/)){
   $('.messageError').html('');//validate if numbers
   sums();      
  }else{
   $('.messageError').html('sorry number only for the first value');//throws warning if error     
  }     
 });
 
 $( ".2nd" ).keyup(function() {
  var2s = $( ".2nd" ).val();      
  if(var2s.match(/^\d+$/)){
   $('.messageError').html('');
   sums();      
  }else{
   $('.messageError').html('sorry number only for the second value');      
  }     
 });     
 
   
 $( ".add" ).click(function() {     
  $('.operator').html('+'); 
  sums();      
 });
 $( ".minus" ).click(function() {
  $('.operator').html('-'); 
  sums();     
 });
 $( ".times" ).click(function() {
  $('.operator').html('x');
  sums();     
 });
 $( ".divide" ).click(function() {
  $('.operator').html('/');
  sums();     
 });    
 
 function sums(){
  var1 =  parseInt($( ".1st" ).val()); 
  var2 =  parseInt($( ".2nd" ).val()); 
  operator = $( ".operator" ).html();   
  sum = (var1 + var2);
  switch (operator) { 
   case '+': 
    sum = (var1 + var2);
    break;
   case '-': 
    sum = (var1 - var2);
    break;
   case 'x': 
    sum = (var1 * var2);
    break;  
   case '/': 
    sum = (var1 / var2);
    break;
   default:
    sum = (var1 + var2);
  }     
   $( ".answer" ).html(sum);
   
    $(".answer").each(function(c, obj){
     $(obj).text(addCommas(parseFloat($(obj).text()).toFixed(2)));
     });    
 }
 
 function addCommas(nStr)
 {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
 }      
}); 

Palindrome solution type2 using array_reverse

In this tutorial i created an function that will tell if a given word is palindrome or not this is another solution to palindrome using array_reverse
 
 palindrome('axa');
 function palindrome($input){ 
    $split = str_split($input); //make the input array
    $reverse = array_reverse($split); // reverse the array
    foreach($reverse as $char){
      $newChar .= $char; //append the letters
    } 
    if($input === $newChar){
      echo "Palindrome";
    }else{
      echo "Not Palindrome";
    }
 }
the result will look like this
Palindrome
note that "axa" is the word that i want to check if it is palindrome or not, you can change it to the one you desired to check.

Palindrome solution for php

In this tutorial i created an function that will tell if a given word is palindrome or not
 
 palindrome2('axa');
 function palindrome2($input){ 
    $split = str_split($input); //make the input array
    $count = strlen($input) - 1;//minus 1 bec array start at 0
    for($x=$count;$x >= 0;$x--){
      $newChar .= $split[$x]; //append the letters
    }  
    if($input === $newChar){
      echo "Palindrome";
    }else{
      echo "Not Palindrome";
    }
 }
the result will look like this
Palindrome
note that "axa" is the word that i want to check if it is palindrome or not, you can change it to the one you desired to check.

Tuesday, May 19, 2015

Enable tooltip and popover in bootstrap

By default, tooltip and popover in bootstrap is not yet enabled. to enable this
We just need to add this code anywhere to our html to make tooltip and popover work.

Thursday, May 7, 2015

Select default dropdown value using jquery

If we want set our dropdowns default value using jquery, we can use .val() jquery function
This is an alternative to the static html selected="selected" if we want to set an default value when our page load dynamically.

Html

Jquery
  $('select.sampleClass').val('test2'); 

Tuesday, April 21, 2015

Enable email sending or useFileTransport in yii2

In yii2 contact us, if you are seeing this message
Note that if you turn on the Yii debugger, you should be able to view the mail message on the mail panel of the debugger. Because the application is in development mode, the email is not sent but saved as a file under C:\UniServerZ\www\runtime/mail. Please configure the useFileTransport property of the mail application component to be false to enable email sending. 
the solution here is simple, just open
/yii2/config/web.php
and find the word useFileTransport and set it to false
  'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
        ],
note: your previous email that was not sent can be found in yii2\runtime\mail

Monday, March 9, 2015

Activate friendly url in yii2

What is friendly url?
friendly URL is a Web address that is easy to read and includes words that describe the content of the webpage. Friendly url can help visitors remember the web address and it is also a factor for search engine optimization.

How to activate it in yii2
Friendly url in yii2 is not activated by default. To activate it we need edit our configurations at
"config/web.php"

This is the content of web.php
$params = require(__DIR__ . '/params.php');
$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'MRPGvrWJP19gG6ABE8zAzpOvg_I6Lm1J',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => require(__DIR__ . '/db.php'),
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module';
}

return $config;
inside 'components' => [] we will add a code to activate friendly url
'urlManager' => [
   'enablePrettyUrl' => true,
   'rules' => [
    // your rules go here
   ],   
  ],
The result must look like this
$params = require(__DIR__ . '/params.php');

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
       'urlManager' => [
           'enablePrettyUrl' => true,
           'rules' => [
               // your rules go here
            ],   
       ],
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'MRPGvrWJP19gG6ABE8zAzpOvg_I6Lm1J',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => require(__DIR__ . '/db.php'),
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module';
}

return $config;

Remove index.php in Url
Following the instruction above, Our url link will look like this http://localhost/web/index.php/site/about
If you want to remove index.php in the url, We need to add  'showScriptName' => false, settings in our url manager.
The result of our url manager settings must look like this
'urlManager' => [
   'enablePrettyUrl' => true,
   'showScriptName' => false,       
   'rules' => [  
            
   ],   
  ],
Remember that this will lead to error since we remove index.php in our url. In order to resolve this, We need to add a new .htaccess file in our /web/ folder,
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

Make root folder accessible and redirect to web folder in yii2

In yii2, by default, the root folder will show the list of file under it when viewed in browser.

To view the actual website, We need to go inside the /web/ folder
ex. http://www.example.com/basic/web/index.php

in order for us to go to http://www.example.com/index.php and display the content of our /web/ folder
We need to edit our .htaccess file
Options +FollowSymLinks

RewriteEngine On
RedirectMatch ^/$ /web/

note that Options +FollowSymLinks is an option to activate the rewriteengine on my Uniserver, In other server, This may not be required

How to make rewrite engine work on Uniserver

Inorder for the "RewriteEngine On" to work in Unizeserver we just need to put
Options +FollowSymLinks
inside our .htaccess file

Saturday, March 7, 2015

Intalling yii2 in windows using composer

In this tutorial, I will show you how to get started in yii2. First you need to choose which template to use. For this tutorial we will use Basic Application Template.

Before we can install via composer, we need to install composer in our windows computer.
A detailed tutorial can be found here
How to install composer in windows with php.exe
After Installing Composer, we can now start to use it by opening our  command terminal




















We need to change directory first using "cd" going to our uniservers path




 At this point, We are inside www folder, We will tell composer to install yii files here.

composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic namesample
 

 

 This may take a while, It will install all yii2 files inside our www folder.

After the installation process is done, We can now check our www folder.

\www\namesample is generated

 Your folder must look like this



















You can visit this page by running your uniserver and pointing it to

http://localhost/namesample/web/




If you can see this page, Then you have successfully created your Yii-powered application.


How to install composer in windows with php.exe

In this tutorial, I will show you how to install composer on windows 7.

So what is Composer? 
Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.

You can download the windows installer at https://getcomposer.org/download/
















As you notice when installing, It will ask you where your php.exe is located. as a default, Windows7 doesn't have php included. We can solve this by using our uniservers preinstalled php.




















What is Uniserver?
Uniserver or Uniform Server is a lightweight server solution for running a web server under the WindowsOS. It is less than 10MiB, it includes the latest versions of Apache2, Perl5, PHP5, MySQL5, phpMyAdmin and more.

You can download UniserverZ at http://www.uniformserver.com/ZeroXI_documentation/

 Install unizerver on your desired location.

After the installation of uniserver, we now have our php.exe, it can be found on

C:\UniServerZ\core\php54\php.exe 

We can now proceed on installing composer on windows by providing the link of our php.exe that can be found on our uniserver.


To verify if composer is really installed, We can open our cmd terminal and type "composer"







Friday, January 23, 2015

Add div element on click and make it draggable using jquery

In this tutorial, i will show you how to add an box,div or element in an certain area then after it has been inserted, we will make it draggable.

We will use jquery ui and we will use the jquery offset function to accomplish this task, first we will get the coordinates of the clicked area then add an box on that spot.

Preview of the whole function
    
$('#layoutSpace').click(function(e){    
    var offset = $(this).offset();  
    areaBox = 50;//to center the mouse point
    mouseX = (e.pageX - offset.left - areaBox );
    mouseY =  (e.pageY - offset.top - areaBox );   
    $('#layoutSpace').append('<div class="dbox" style="left:'+ mouseX +'px;top:'+ mouseY  +'px;"></div>');
    //run the draggable function
 runTheDrag(); 
});    

MainlayoutX = $('#layoutSpace').offset().left; //Get main layout of the mainContainer
MainlayoutY = $('#layoutSpace').offset().top; //Get main layout of the mainContainer

//function for draggable box
function runTheDrag(){
    $(".dbox").draggable({ 
        containment: '#layoutSpace',
        scroll: false,   
        drag: function(){
            var offset = $(this).offset(); 
            var left = offset.left - MainlayoutX;
            var top = offset.top - MainlayoutY;   
            
            $(".dbox .xAxis").val(left);
            $(".dbox .yAxis").val(top);      
        }
    });    
}

This code will will register the area that is clicked by the mouse and add an box on that spot

    var offset = $(this).offset();  
    areaBox = 50;//to center the mouse point
    mouseX = (e.pageX - offset.left - areaBox );
    mouseY =  (e.pageY - offset.top - areaBox );   
    $('#layoutSpace').append('<div class="dbox" style="left:'+ mouseX +'px;top:'+ mouseY  +'px;"></div>');
    //run the draggable function
    runTheDrag(); 
});  
runTheDrag() function is to make the box draggable on click using jquery ui
 runTheDrag();

 function runTheDrag(){
    $(".dbox").draggable({ 
        containment: '#layoutSpace',
        scroll: false,   
        drag: function(){
            var offset = $(this).offset(); 
            var left = offset.left - MainlayoutX;
            var top = offset.top - MainlayoutY;   
            
            $(".dbox .xAxis").val(left);
            $(".dbox .yAxis").val(top);      
        }
    });    
} 

As you notice, we inserted the runTheDrag() function on to the click function
The reason is we need to rerun the jquery code on click to register the draggable function again on the newly added box.

Live Demo

Add div element on click in a certain coordinate using jquery

Add div element on click in a certain coordinate using jquery
Using jquery offset, we will get the coordinates of the clicked area then add an box on that spot.
$('#layoutSpace').click(function(e){    
    var offset = $(this).offset();  
    areaBox = 50;//to center the mouse point
    mouseX = (e.pageX - offset.left - areaBox );
    mouseY =  (e.pageY - offset.top - areaBox );   
    $('#layoutSpace').append('
'); });
to center the box coordinate we will divide our box into 2
in my case, my box width and height is 100px so i will divide it to 2 and that would be 50.
areaBox = 50;//to center the mouse point
after that we will minus it to our x and y axis to center it up
  mouseX = (e.pageX - offset.left - areaBox );
  mouseY =  (e.pageY - offset.top - areaBox );
Live Demo

Get axis on click jquery

get x and y axis on click using jquery

We will use jquery offset to determine the coordinates of the click in our specified div
$('#layoutSpace').click(function(e){    
    var offset = $(this).offset();  
    mouseX = (e.pageX - offset.left );
    mouseY =  (e.pageY - offset.top );   
    $('.axisXY').html("X: " + mouseX + " Y: " + mouseY);
});

LIVE DEMO click anywhere on the box