Tuesday, October 24, 2017

laravel 5 - Properly handle TokenMismatchException

In laravel 5 , When the token is expired you could get the TokenMismatchException. So we can avoid the exception and redirect back to the page with some error notification messages is best for the users.

I searched around and could not find a 100% definitive solution to this. I was able to find this bit of code but it does not seem to make any difference: App\Exceptions\Handler.php

 
public function render($request, Exception $exception){ 
  if ($exception instanceof TokenMismatchException){ 
    return redirect(url()->previous())->with('alert-danger', 
"Oops! Seems you couldn't submit form for a long time. 
Please try again."); 
    }
    return parent::render($request, $exception); 
 }

Friday, August 25, 2017

jQuery push multiple values in input tag


Just set value to input store it in some temporary variable, append the value you want to store and set the value of input to this temporary variable eg.

<input id="user" type="text" name="user" class="form-control" />
<input id="user_id" type="hidden" name="user_id" value="" />

var oldValue = $("#user_id").val();
var arr = oldValue === "" ? [] : oldValue.split(',');
arr.push(yardval);
var newValue = arr.join(',');
$("#user_id").val(newValue);
 
 

Monday, August 14, 2017

Tinymce aws s3 upload plugin

Tinymce editor have lots of plugins and it is very useful. Today i have shared one of the useful plugin with you peoples.

Feature of this plugin:
- Upload the file in the tinymce and it will save the file in the aws s3 bucket and return the URL.


Please refer the URL for source code and  implementation : https://github.com/OGPoyraz/tinymce-aws-s3-upload-plugin

Special thanks to !!!

Thursday, August 10, 2017

Laravel - TNTSearch driver with Laravel Scout

Laravel Scout provides a simple, driver-based solution for adding full-text search to your Eloquent models. i have recommend using Laravel Scout for querying large databases, this will be where it will be at it’s most useful and powerful.

For More Refer : https://laravel-news.com/tntsearch-with-laravel-scout

Monday, July 03, 2017

Yii Form Validation With Ajax submit button

Step 1: @ your controller action
public function actionMyAction()
{       
    $model=new User;             
    $this->performAjaxValidation($model);  

    if(isset($_POST['User']))
    {
        $model->attributes=$_POST['User'];
        $valid=$model->validate();            
        if($valid){

           //do anything here
             echo CJSON::encode(array(
                  'status'=>'success'
             ));
            Yii::app()->end();
            }
            else{
                $error = CActiveForm::validate($model);
                if($error!='[]')
                    echo $error;
                Yii::app()->end();
            }
   }
}
Step 2: @ your view Your form may look like this
<?php
$form=$this->beginWidget('CActiveForm', array(
        'id'=>'user-form',
        'enableAjaxValidation'=>true,
        'action'=>$this->createUrl('myController/MyAction'),
        'enableClientValidation'=>true,
     
));
   ?>
<div class="errorMessage" id="formResult"></div>
<div id="AjaxLoader" style="display: none">
<img src="<?php echo Yii::app()->request->baseUrl; ?>
/images/spinner.gif"></img></div>
<div class="row-user-single">
    <?php echo $form->labelEx($model,'attribute1'); ?>
    <?php echo $form->passwordField($model,'attribute1',
    array('size'=>60,'maxlength'=>500)); ?>
    <?php echo $form->error($model,'attribute1'); ?>
</div>

<div class="row-user-single">
    <?php echo $form->labelEx($model,'attribute2'); ?>
    <?php echo $form->passwordField($model,'attribute2',
array('size'=>60,'maxlength'=>500)); ?>
    <?php echo $form->error($model,'attribute2'); ?>
</div>
<div class="buttons">

 <?php echo CHtml::ajaxSubmitButton('Save',
CHtml::normalizeUrl(array('myController/MyAction','render'=>true)),
    array(
        'dataType'=>'json',
        'type'=>'post',
        'success'=>'function(data) {
            $("#AjaxLoader").hide();  
           if(data.status=="success"){
            $("#formResult").html("form submitted successfully.");
            $("#user-form")[0].reset();
           }
            else{
           $.each(data, function(key, val) {
           $("#user-form #"+key+"_em_").text(val);                                                    
           $("#user-form #"+key+"_em_").show();
           });
           }       
       }',                    
        'beforeSend'=>'function(){                        
              $("#AjaxLoader").show();
         }'
        ),array('id'=>'mybtn','class'=>'class1 class2')); ?>
<?php $this->endWidget();?>
there are only two things to be noted as follows:
1. @ your controller call validate of your model and return a json object if form is invalid
2. @ your view break this json object (OR traverse through it) and show the error messages under respective elements of the form.

For more refer please go to the link . Thanks to  riyazMuhammed 
 

Tuesday, June 13, 2017

Yii CListView ajax load more

Below solution is works fine.
 
InfiniteScroll Extension Path : 

https://github.com/erikuus/Yii-Extensions/tree/master/widgets
 
Implementation:

<?php
        $this->widget('zii.widgets.CListView', array(
                    'dataProvider'=>$dataProvider,
                    'itemView'=>'/jobs/viewJobList',
                    'summaryText'=>false,
                    'emptyText'=>"<p> No Jobs!!!</p>",
                    'id'=>'ajaxJobListView',
                   'template' => '{items} {pager}',
                   'ajaxUpdate'=>true,
                    'pager' => array(
                        'class' => 'ext.infiniteScroll.IasPager',
                        'rowSelector'=>'.row',
                        'listViewId' => 'ajaxJobListView',
                        'header' => '',
                        'loaderText'=>Yii::t('app','Loading'),
                        'options' => array('history' => false, 'triggerPageTreshold' => 1,

 'trigger'=>Yii::t('app','Load More')),
                    ),
                'afterAjaxUpdate'=>"function(id, data) {
                    $.ias({
                        'history': false,
                        'triggerPageTreshold': 1,
                        'trigger': Yii::t('app','Load More'),
                        'container': '#ajaxJobListView',
                        'item': '.row',
                        'pagination': '#ajaxJobListView .pager',
                        'next': '#ajaxJobListView .next:not(.disabled):not(.hidden) a',
                        'loader': Yii::t('app','Loading')
                    });
                }",
            ));?>

Wednesday, April 05, 2017

jQuery - How to convert a Title to a URL slug

Title : <input type="text" name="title" id="title"><br>
Slug  : <input type="text" name="slug-title" id="slug-title">


var slug = function(str) {
    var slug1 = '';
    var trimmed = $.trim(str);
    slug1 = trimmed.replace(/[^a-z0-9-]/gi, '-').
    replace(/-+/g, '-').
    replace(/^-|-$/g, '');
    return slug1.toLowerCase();
}
       
$("#title").keyup(function(){       
    var Text = $(this).val();
    $('#slug-title').val(slug(Text));             
});

$("#slug-title").keyup(function(){       
    var Text = $(this).val();
    $('#slug-title').val(slug(Text));             
});

Output:
Title: 123@345#456&421*322
Slug : 123-345-456-421-322

Demo : https://jsfiddle.net/vasashiner/Ltg06sax/

Monday, March 20, 2017

Yii2 gridview sum of column value

Here is some of the sample code to get the sum of the column values in the footer in the gridview. It was 100% working in the gridview in Yii2.

All you need to change is the values

 [
   'label' => 'cost',
   'attribute' => 'cost',
   'value' => function ($model, $key, $index, $widget) {
                            return $model->cost;
                    },
   'footer' => $cost,
 ],

The above code should be added in the gridview with footer enabled.

'showFooter' =>true,

Here cost the value which need to be totaled, so you need to change according to your needs. You also need to add the below code in the view page.

<?php
$cost = 0;
if (!empty($dataProvider->getModels())) {
 foreach ($dataProvider->getModels() as $key => $val) {
     $cost += $val->cost;
    }
}
?>

Use this code and calculate sum of values in the footer in the Yii2 Gridview.

Thanks for the code to make it easy. For more refere go to techken.in

Friday, March 10, 2017

Opencart .htacess file with page speed

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 month"
ExpiresByType image/jpeg "access 1 month"
ExpiresByType image/gif "access 1 month"
ExpiresByType image/png "access 1 month"
ExpiresByType text/css "access 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month" 
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresByType font/opentype "access 1 month"
ExpiresByType application/x-font-woff "access 1 month"
ExpiresDefault "access 2 days"
</IfModule>
## EXPIRES CACHING ##

<IfModule mod_mime.c>
 AddType application/x-javascript .js
 AddType text/css .css
</IfModule>

<IfModule mod_deflate.c>
 AddOutputFilterByType DEFLATE text/css application/x-javascript text/x-component text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon application/javascript
 <IfModule mod_setenvif.c>
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
 </IfModule>
 <IfModule mod_headers.c>
  Header append Vary User-Agent env=!dont-vary
 </IfModule>
</IfModule>

# 1.To use URL Alias you need to be running apache with mod_rewrite enabled.
# 2. In your opencart directory rename htaccess.txt to .htaccess.
# For any support issues please visit: http://www.opencart.com

Options +FollowSymlinks

# Prevent Directoy listing
Options -Indexes

# Prevent Direct Access to files
<FilesMatch "(?i)((\.tpl|\.ini|\.log|(?<!robots)\.txt))">
 Order deny,allow
 Deny from all
</FilesMatch>

# SEO URL Settings
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R=301]
# If your opencart installation does not run on the main web folder make sure you folder it does run in ie. / becomes /shop/

RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?route=common/home[?\s] [NC]
RewriteRule ^ /? [R=301,L]

RewriteCond %{QUERY_STRING} ^$ [OR]
RewriteCond %{REQUEST_URI} !index\.php/?$
RewriteRule ((^|/)index\.php)+/?(.*)$ /$3 [R=301,L,QSA,NC]


### Additional Settings that may need to be enabled for some servers
### Uncomment the commands by removing the # sign in front of it.
### If you get an "Internal Server Error 500" after enabling any of the following settings, restore the # as this means your host doesn't allow that.

# 1. If your cart only allows you to add one item at a time, it is possible register_globals is on. This may work to disable it:
# php_flag register_globals off

# 2. If your cart has magic quotes enabled, This may work to disable it:
# php_flag magic_quotes_gpc Off

# 3. Set max upload file size. Most hosts will limit this and not allow it to be overridden but you can try
# php_value upload_max_filesize 999M

# 4. set max post size. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value post_max_size 999M

# 5. set max time script can take. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_execution_time 200

# 6. set max time for input to be recieved. Uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_input_time 200

# 7. disable open_basedir limitations
# php_admin_value open_basedir none

# Use PHPcur as default
AddHandler application/x-httpd-phpcur .php
<IfModule mod_suphp.c>
    suPHP_ConfigPath /opt/phpcur/lib
</IfModule>

Friday, March 03, 2017

jquery difference between map vs each function

The each method is meant to be an immutable iterator, where as the map method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.

Another important thing to note is that the each function returns the original array while the map function returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.

For example:

var items = [1,2,3,4];

$.each(items, function() {
  alert('this is ' + this);
});

var newItems = $.map(items, function(i) {
  return i + 1;
});


// newItems is [2,3,4,5]

You can also use the map function to remove an item from an array.  For example:

var items = [0,1,2,3,4,5,6,7,8,9];

var itemsLessThanEqualFive = $.map(items, function(i) {
  // removes all items > 5
  if (i > 5)
    return null;
  return i;
});
// itemsLessThanEqualFive = [0,1,2,3,4,5]


Wednesday, February 22, 2017

Datepicker onSelect Issue Fixed

The first time the datepicker is initialized, the original dom element is marked with a new class addition, called hasDatepicker that prevent subsequent initialization/reconfiguration. The way I found to get rid of it is to remove that marker befor doing any modification to the datepicker's configuration. Thus:

$(function() {
   $('#date_caisse').removeClass('hasDatepicker');
   $('#date_caisse').datepicker({
       onSelect: function(dateText, inst) {
           alert('overridden!');
       }
   });
});
 
Give it a try! Thanks for themarcuz . 

Saturday, January 21, 2017

Php - Adding divs to a foreach loop every 4 times

Basically what i need to do is wrap a div around the output of the data every 4 loops.

I have the following loop:

foreach( $users_kicks as $kicks ) {
    echo $kicks->brand;
}

For every 4 times it echos that out i want to wrap it in a  so at the end it will look like so:

<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>
<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>
<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>


Solution:
=========
$count = 1;

foreach( $users_kicks as $kicks )
{
    if ($count%4 == 1)
    { 
         echo "<div>";
    }
    echo $kicks->brand;
    if ($count%4 == 0)
    {
        echo "</div>";
    }
    $count++;
}
if ($count%4 != 1) echo "</div>";

//This is to ensure there is no open div if the number of elements in user_kicks is not a multiple of 4



Cheers and thanks !!! For get more refer this link

Wednesday, January 04, 2017

Opencart - Shipping For Multiple Flat Rates


Do you want a second (or third, or fourth) flat rate for your site’s shipping? OpenCart doesn’t include a shipping method that allows for multiple flat rates by default, but you can easily set up multiple flat shipping options using the built-in Weight Based Shipping extension.

1. In System > Localisation > Geo Zones, set up a duplicate geo zone for each flat rate that you want. For example, if you wanted these three shipping options available to the U.S.:
  • Standard: $5.00
  • Express: $12.00
  • Next-Day: $18.00
then you would create three geo zones all with United States selected as the country, named “Standard”, “Express”, and “Next-Day”.

2. In Extensions > Shipping > Weight Based Shipping, create a rate for each geo zone with a rate (in the format Weight:Cost) like so:
RATE #1
  • Geo Zone: Standard
  • Rates: 999999:5.00
RATE #2
  • Geo Zone: Express
  • Rates: 999999:12.00
RATE #3
  • Geo Zone: Next-Day
  • Rates: 999999:18.00
Don’t forget to enable the extension as a whole in the “General” tab, and each geo zone in its own tab. If you have other geo zones for other purposes then leave those disabled in their tabs. If you need a tax rate applied to the shipping costs, then select the Tax Class in the “General” tab.

3. During checkout, each option will be presented to the customer on the “Delivery Method” step. They are ordered alphabetically by name, so if you need them in a particular order then you should name them accordingly.

4. If you want to remove the cart weight that is attached to each rate title, then you can make the following edit:

IN:
/catalog/model/extension/shipping/weight.php
REPLACE:
$result['name'] . ' (' . $this->language->get('text_weight') . ' ' . $this->weight->format($weight, $this->config->get('config_weight_class_id')) . ')',
WITH:
$result['name']
 
And that’s it! Your OpenCart store now has multiple flat rate shipping options for your customer.

Thanks to for the article