Journal Theme for MultiVendor

The long awaited Journal Theme for MultiVendor is finally here.

The theme has undergone customization to make it compatible with MultiVendor for OpenCart 3.x

Kindly note that this Journal Theme is specifically for MultiVendor the normal Journal theme won’t work.

 

Journal Theme for MultiVendor

Journal MultiVendor Theme DEMO  

If you already have the normal Journal Theme for OpenCart you can request for customization by emailing us info@ovicko.com

Customization cost $20

Yii 2 RESTful api upload single image

Upload image in Yii 2 REST API

Hey guys, here comes another year and another code snippeton how to upload images via Yii2 REST API.

I have made this extremely easy by commenting the code,in case you get stuck drop a comment 🙂

public function actionSinglefile()
{
 
  \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  //response array
  $response = array();
  //create date string to be used a year
  $ymd = date("Ymd");
  //get the 'image' being send via api
  //Returns an uploaded file according to the given file input name.
  //The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').

  $uploadedFile = UploadedFile::getInstanceByName('image');
  if ($uploadedFile) {
    //get the uploaded file name
    $filename = $uploadedFile->name;
    //pathinfo() returns more info about the $uploadFile
    $pathinfo = pathinfo($uploadedFile);
    //create a new filename to avoid file collission
    $filename = $pathinfo['filename'].date('YmdHis').rand(10000,99999);
    //get extension
    $extension  = $uploadedFile->getExtension();
    //directory to save the image
    $save_path = \Yii::getAlias('@backend') . '/web/uploads/' . $ymd . '/';
    //check if dir already exists 
      if (!file_exists($save_path)) {
        //make dir ,give permissions
          mkdir($save_path, 0777, true);
        }
        //save file
      $uploadedFile->saveAs($save_path . $filename. '.' . $extension);
    return $response = array(
                              'fileinfo' => pathinfo($uploadedFile),
                              'filename' => $filename
                            );
  } else {
    return array(
                  'file' => $uploadedFile->error,
                );
  }

  
}

 

Yii REST API Guide

How to delete blank empty lines from your code

I will keep this short because again we devs like straight,brief and clear  instructions.

Assume you have such kind of code and you want to remove all these empty lines .How will you go about it?

<?php

// Heading

$_['heading_title']    = 'My Downloads';

$_['heading_title1']    = 'Add Download';



// Text

$_['text_success']     = 'Success: You have modified downloads!';

$_['text_upload']      = 'Your file was successfully uploaded!';

$_['text_loading']      = 'Loading..';



$_['text_edit']      = 'Edit';



$_['text_no_results']      = 'No Results Found';



// Column

$_['column_name']      = 'Download Name';

$_['column_remaining'] = 'Total Downloads Allowed';

$_['column_action']    = 'Action';



$_['column_date_added'] = 'Date Added';


 

Easy! us regular expressions.

Use^\n to be precise.

In your IDE use Find using Regular expressions and Replace.

Example

Find: ^\n

Replace with: (nothing,blank)
So the results of my code will be.

<?php
// Heading
$_['heading_title']    = 'My Downloads';
$_['heading_title1']    = 'Add Download';
// Text
$_['text_success']     = 'Success: You have modified downloads!';
$_['text_upload']      = 'Your file was successfully uploaded!';
$_['text_loading']      = 'Loading..';
$_['text_edit']      = 'Edit';
$_['text_no_results']      = 'No Results Found';
// Column
$_['column_name']      = 'Download Name';
$_['column_remaining'] = 'Total Downloads Allowed';
$_['column_action']    = 'Action';
$_['column_date_added'] = 'Date Added';

Looks good 🙂

In case you have spaces in the line then you can use ^[\s]*?[\n\r]+

May you are wondering what all these regex thing is,have a look look at PHP Regex cheat sheet.

Cheat Sheet

[abc] A single character of: a, b or c
[^abc] Any single character except: a, b, or c
[a-z] Any single character in the range a-z
[a-zA-Z] Any single character in the range a-z or A-Z
^ Start of line
$ End of line
\A Start of string
\z End of string
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\w Any word character (letter, number, underscore)
\W Any non-word character
\b Any word boundary
(...) Capture everything enclosed
(a|b) a or b
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a{3} Exactly 3 of a
a{3,} 3 or more of a
a{3,6} Between 3 and 6 of a

Options

i case insensitive  m treat as multi-line string  s dot matches newline  x ignore whitespace in regex  A matches only at the start of string  D matches only at the end of string  U non-greedy matching by default

You have other great ways of doing this? let us know!

Donwload OpenCart 3x MultiVendor Extension

Converting your OpenCart Extensions to OpenCart 3x the easy way

Hi there!

OpenCart 3x version already out and I am sure some guys like me are struggling to get their extensions updated to fit the Twig templating Engine introduced in OpenCart 3.

I will summarize what I have learnt and also give you some tricks I got from the OpenCart page.

Use regular expressions in PHP IDE to mass search and replace.

This will save you hours of going through your files one by one.

-Be careful with it,make sure you understand the regex before you do anything.

Examples given by OpenCart

The format used here is:

-Example

-Regex

-Replace

Eg

Example: <?php echo $var; ?>

Regex: <\?php echo [$](\w*\b)[;] \?\>

Replace: {{ $1 }}
<?php echo $error_name[$language['language_id']]; ?>

<\?php\s+echo\s+[$](\w+)\[[$](.*)\[\'(.*)\'\]\]\; \?\>

{{ $1[$2.$3] }}
<?php $attribute_row = 0; ?>

<\?php [$](\w*\b) = 0[;] \?\>

{% set $1 = 0 %}
<?php $filter_row++; ?>

<\?php [$](\w*\b)\+\+\; \?\>

{% set $1 = $1 + 1 %}

 

<?php echo $var['key']; ?>

<\?php echo [$](\w*\b)\[\'(\w*\b)\'\]; \?>

{{ $1.$2 }}

 

<?php if ($error_height) { ?>

<\?php if \([$](\w+\b)\) \{ \?\>

{% if $1 %}

 

<?php if (isset($error_name[$language['language_id']])) { ?> 
<\?php\s+if\s+\(isset\([$](\w+\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\)\) \{ \?\> 
{% if $1[$2.$3] %}

 

<?php if (in_array($category['category_id'], $selected)) { ?> 
<\?php if \(in_array\([$](\w+\b)\[\'(.*\b)\'\], [$](\w+\b)\)\) \{ \?\>
{% if $3 in $1.$2 %}
<?php if (in_array($marketplace_code, $marketplaces_processing)) { ?> 
<\?php if \(in_array\([$](\w+\b), [$](\w+\b)\)\) \{ \?\>
 {% if $1 in $2 %}
<?php if ($attribute_group['attribute_group_id'] == $attribute_group_id) { ?> 
<\?php if \([$](\w+\b)\[\'(.*\b)\'\] == [$](.*\b)\) \{ \?\>
 {% if $1.$2 == $3 %}
<?php if ($custom_field['type'] == 'date') { ?> 
<\?php if \([$](\w+\b)\[\'(.*\b)\'\] == \'(.*\b)\'\) \{ \?\> 
{% if $1.$2 == '$3' %}
<?php if ($sort == 'pd.name') { ?>
 <\?php\s+if\s+\([$](\w+\b) == \'(.*\b)\'\)\s+\{\s+\?\> 
{% if $1 == '$2' %}
<?php if ($voucher['order']) { ?>
 <\?php if \([$](\w+\b)\[\'(\w+\b)\'\]\) \{ \?\> 
{% if $1.$2 %}
<?php if (!$shipping) { ?> 
<\?php if \(\![$](\w+\b)\) \{ \?\> 
{% if not $1 %}
<?php echo (isset($account_custom_field[$custom_field['custom_field_id']]) ? $account_custom_field[$custom_field['custom_field_id']] : $custom_field['value']); ?>

<\?php\s+echo\s+\(isset\([$](\w+\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\)\s+\?\s+[$](.*\b)\[[$](.*\b)\[\'(.*\b)\'\]\] : [$](.*\b)\[\'(.*\b)\'\]\);\s+\?\>

{% if $1[$2.$3] %} {{ $4[$5.$6] }} {% else %} {{ $7.$8 }} {% endif %}
<?php echo (isset($account_custom_field[$custom_field['custom_field_id']]) ? $account_custom_field[$custom_field['custom_field_id']] : ''); ?>

<\?php\s+echo\s+\(isset\([$](\w+\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\)\s+\?\s+[$](.*\b)\[[$](.*\b)\[\'(.*\b)\'\]\] : \'\'\);\s+\?\>

{% if $1[$2.$3] %} {{ $4[$5.$6] }} {% endif %}
<?php echo isset($information_description[$language['language_id']]) ? $information_description[$language['language_id']]['description'] : ''; ?>

<\?php\s+echo\s+isset\([$](\w+\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\)\s+\?\s+[$](.*\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\[\'(.*\b)\'\] : \'\';\s+\?\>

{% if $1[$2.$3] %} {{ $4[$5.$6].$7 }} {% endif %}

 

<?php } elseif ($percentage) { ?>

<\?php \} elseif \([$](\w+\b)\) \{ \?\>

{% elseif $1 %}
<?php } elseif ($amazon_login_button_size == 'large') { ?>

<\?php \} elseif \([$](\w+\b) == \'(.*\b)\'\) \{ \?\>

{% elseif $1 == '$2' %}
<?php } elseif ($percentage < 0) { ?>

<\?php \} elseif \([$](\w+\b) \> 0\) \{ \?\>

{% elseif $1 in < 0 %}
<?php foreach ($var1 as $var2) ?>

<\?php foreach \([$](.*\b) as [$](.*\b)\) \{ \?\>

{% for $2 in $1 %}

<?php foreach ($custom_field['custom_field_value'] as $custom_field_value) { ?>

<\?php foreach \([$](.*\b)\[\'(.*\b)\'\] as [$](\w+)\) \{ \?\>

{% for $3 in $1.$2 %}
<?php foreach ($setting['returns']['paidby'] as $v) { ?>

<\?php foreach \([$](.*\b)\[\'(.*\b)\'\]\[\'(.*\b)\'\] as [$](\w+)\) \{ \?\>

{% for $4 in $1.$2.$3 %}
<?php foreach ($marketplaces as $id => $name) { ?>

<\?php foreach \([$](\w+)\s+as\s+[$](\w+)\s+=\>\s+[$](\w+)\)\s+\{ \?\>

{% for $2, $3 in $1 %}
<?php foreach ($capture['shipping_info'] as $key => $shipping_info) { ?>

<\?php foreach \([$](.*)\[\'(.*)\'\]\s+as\s+[$](.*)\s+=\>\s+[$](\w+)\)\s+\{ \?\>

{% for $3, $4 in $1.$2 %}

Close the ifs and for statements manually with the below syntax.

{% endif %}

{% endfor %}
<?php if ($rating == 2) { ?>//change 2 to any number 
<\?php\s+if\s+\([$](\w+\b) == \d\)\s+\{\s+\?\>
{% if $1 == $2 %}

 

Get module,controller and action ID in Yii 2

This tutorial will show you how to get the module ID,controller ID and action ID.

1.From the Views

Module ID $this->context->module->id
Controller ID $this->context->id
Action ID $this->context->action->id

2.From the controller

 Module ID   Yii::$app->controller->module->id;
 Controller ID   Yii::$app->controller->id
 Action ID  Yii::$app->controller->action->id; or
Module ID       $this->module->id;
Controller ID   $this->id;
Action ID       $this->action->id;

3.in the beforeAction method

Module ID      $action->controller->module->id;
Controller ID   $action->controller->id;
Action ID       $action->id;

Now you know it! Let us know your views so that we help where possible. 🙂

Get Yii RESTful guide manual

Using Yii aliases

Aliases are used to represent file paths or URLs so that you don’t have to hard-code absolute paths or URLs in your project. An alias must start with the @ character to be differentiated from normal file paths and URLs. Alias defined without leading @ will be prefixed with @ character.

Yii has many pre-defined aliases already available. For example, the alias @yii represents the installation path of the Yii framework; @web represents the base URL for the currently running Web application.[Adapted from Yii guide]

In this example you will learn how to use aliases to read files from a certain directory in your app.

First set an alias using Yii:setAlias method in common/config/bootstrap.php

Yii::setAlias('@shopfolders', dirname(dirname(__DIR__)). '/uploads/');

 

Now we can access the alias anywhere in the app using Yii:getAlias(@shopfolders)

Add a controller action that will handle the reading of folders

public function actionDetails()
{
    $dir = Yii::getAlias('@shopfolders').'/';
    $files = array();
    // Open a known directory, and proceed to read its contents
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
               // echo 
                //$files[]['filename'] = $file;
                //$files[]['filetype'] = filetype($dir . $file);
                if ($file != '.' && $file != '..') {
                    $files[] = array('filename' => $file,
                    'filetype' => filetype($dir . $file)
                 );
                }
                
            }
            closedir($dh);
        }
    }

    return $this->render('details',[
    'files'=>$files
        ]);
}

 

The view file

<?php
/* @var $this yii\web\View */
?>
<div>
<ul>
<?php
foreach ($files as $file) {
  echo "<li>".$file['filename']."    ". $file['filetype']."</li>";
}
//var_dump(json_encode($files));
?>
</ul>	
</div>

 

That is it! 🙂

Example of output

Get Yii 2 RESTful guide

Log the URLs users visited in Yii 2

In this example we will use Yii 2 behavior to log the URLs user have visited on our Yii 2 powered application.
Lets get started.

1.Create a behavior folder in the commons directory,then create LogactionBehavior class.

<?php
namespace common\behaviors;

use Yii;
use yii\web\Controller;
use yii\base\Behavior;
use yii\web\Request;

class LogactionBehavior extends Behavior
{
    /**
     * 
     * @var yii\web\Request
     */
    private $request;

    /**
     * Use dependency injection to inject yii\web\Request
     * @param array $config
     * @param yii\web\Request  $request
     */
    public function __construct($config =[],Request $request)
    {
        parent::__construct($config);
        $this->request = $request;
    }

    /**
     * Activation of events
     * Register beforeAction to  Controller::EVENT_BEFORE_ACTION 
     * Register afterAction to Controller::EVENT_AFTER_ACTION 
     * @return array
     */
    public function events()
    {
        return [
            Controller::EVENT_BEFORE_ACTION => 'beforeAction',
            Controller::EVENT_AFTER_ACTION => 'afterAction'
        ];
    }

    /**
     * log
     */
    public function beforeAction()
    {
        $date =date("Y/m/d h:i:sa");
        $url = $this->request->url;
        $ip = $this->request->userIP;
        $params = $this->request->getRawBody();
        $log = $date."   ".$url."  ".$params."   ".$ip;
        Yii::info($log);
        Yii::beginProfile('myBenchmark');//log user activty to,myBenchmark---change modify the name
    }

    public function afterAction()
    {
        Yii::endProfile('myBenchmark');//end analysis
    }
}

 

2 Controller behavior

public function behaviors()
{
    return [
        LogactionBehavior::className(),
    ];

 

3 Add to application configuration

'log'=>[
    'targets' => [
        [
            'class'=> 'yii\log\FileTarget',
            'levels' => ['info','profile'],
            'logVars' => [],
        ]

    ]
]

 

Get Yii RESTful guide

Upload multiple images in Yii 2 framework

Uploading single file

 

1.Create a  model models/UploadForm.php

namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

/**
 * UploadForm is the model behind the upload form.
 */
class UploadForm extends Model
{
    /**
     * @var UploadedFile file attribute
     */
    public $file;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['file'], 'file'],
        ];
    }
}

You can add more validation rules of the files uploaded.

public function rules()
{
    return [
        [['file'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png',],
    ];
}

Allow user to upload .jpg and .png files only.

public function rules()
{
    return [
        [['file'], 'file', 'skipOnEmpty' => false],
    ];
}

This means file must be uploaded and will not continue if empty

2.Create a view

<?php
use yii\widgets\ActiveForm;
?>

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>

<?= $form->field($model, 'file')->fileInput() ?>

<button>Submit</button>

<?php ActiveForm::end() ?>

3.Create a controller

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;

class SiteController extends Controller
{
    public function actionUpload()
    {
        $model = new UploadForm();

        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file && $model->validate()) {                
                $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
            }
        }

        return $this->render('upload', ['model' => $model]);
    }
}

Uploading Multiple Images

1.Create model class.

class UploadForm extends Model
{
    /**
     * @var UploadedFile|Null file attribute
     */
    public $file;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['file'], 'file', 'maxFiles' => 10], // <--- here!
        ];
    }
}

maxFiles is the maximum number of files a user can upload.

2. Create view

<?php
use yii\widgets\ActiveForm;

$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>

<?= $form->field($model, 'file[]')->fileInput(['multiple' => true]) ?>

    <button>Submit</button>

<?php ActiveForm::end(); ?>

The difference between the single file view  and multiple files view is

$form->field($model, 'file[]')->fileInput(['multiple' => true]) 3. Create controller
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;

class SiteController extends Controller
{
    public function actionUpload()
    {
        $model = new UploadForm();

        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstances($model, 'file');

            if ($model->file && $model->validate()) {
                foreach ($model->file as $file) {
                    $file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
                }
            }
        }

        return $this->render('upload', ['model' => $model]);
    }
}

You can check if the upload directory exists by using this simple function.

 
public function fileExists($uploadpath)

{
    if(!file_exists($uploadpath)){
        mkdir($uploadpath);
    }
    return $uploadpath;
}

$filePath = $this->fileExists(Yii::$app->basePath.'/uploads/');  //upload directory

 

Reference Yii 2 Guide

Yii 2 RESTful service guide with examples

Create a Yii 2 Module

In this tutorial, you will learn how to generate and configure a Yii 2 module.

So letes get started!

First make sure you have installed Yii framework template,either basic or advanced template will do.

We will use Yii 2’s Gii tool to help you generate templates for the module.

To can access Yii 2 Gii tool navigate to yourdomain/index.php?r=gii .

                                                                                            Yii 2 Gii tool interface

Step 1: Select the Module Generator option

Step 2: Enter your module ID and Class

In this case my module ID is post and the Module class is backend\modules\post\PostModule.

 

C

Step 3: Click Preview button to preview then Generate button to generate the files shown in the preview.

Step 4: Add the Post module to your application configuration:

Add the Module class to your modules  configuration

'post' => [
            'class' => 'backend\modules\post\PostModule',
        ],

Add Module alias to to alias array

'aliases' => 
       ......
       'post' => '@backend/modules/post',
       ......
   ],
Module file structure

You now have your module! access it in the backend  by navigating to yourdomain/backend/post/default/index

Thanks for reading this far, if helpful let alot of folks know it.:)

OpenCart library part 1

In this series you will learn OpenCart in built library that will be handy when  when writing your own OpenCart modules and extensions.

After working on OpenCart for more than three years I think its good to share some of my knowledge with you guys

This part will mainly deal with the library/cart/cart.php for OpenCart 3.x.

The cart.php has the following methods:
$this->cart->update($cart_id, $quantity);
Updates the quantity of a product in the cart with ID = $cart_id

$this->cart->getProducts();
Returns an array of the products in the cart and their details.

$this->cart->add($product_id, $quantity = 1, $option = array(), $recurring_id = 0);
Adds a product of ID= $product_id to the cart,

$this->cart->remove($cart_id);
Deletes the cart with ID = $cart_id.

$this->cart->clear ();
Removes all the products in the current users cart at once

$this->cart->getRecurringProducts ();
Returns an array of products that are recurring.

$this->cart->getWeight ();
Returns the sum of the weights of all products in the cart that have shipping requirement.

$this->cart->getSubtotal ();
Returns the subtotal of all the products in the cart before applying tax

$this->cart->getTaxes();
Returns an array of total taxes applied to products in the cart:

$this->cart->getTotal();
Returns the total cost of all products in the cart after applying tax:
This is normally the final amount the customer has to pay.

$this->cart->countProducts();
Returns the total number of the products in the cart:

$this->cart->hasProducts();
Returns the count of the products in the cart:

$this->cart->hasRecurringProducts();
Returns the count of the recurring products in the cart:

$this->cart->hasStock();
Returns a Boolean value indicating whether product in the cart is available (true) or the product is out of stock (false).

$this->cart->hasShipping();
Returns a Boolean value indicating whether product in the cart requires shipping.

$this->cart->hasDownload();
Returns a Boolean value indicating whether a product is downloadable or not.

Stay tuned for the next article

Huh! you dont have to remember them  all, just know they exists and they could be of help!

If its helpful consider sharing and let me know your ideas 🙂

Get Open Cart Order PDF Invoice generator