Codeigniter Recusrsive Category List

Conside categories table with structure is id, name, parent_id.  A category can have many subcategories and a subcategory can have many sub-sub categories.

This is the code to get all categories and their subcategories.


$tree = $this->get_category_by_parent(0);

public function get_category_by_parent($parent_id = 0) {
		  $categories = array();
		  $this->db->from('categories');
		  $this->db->where('parent_id', $parent_id);
		  $result = $this->db->get()->result();
		  foreach ($result as $mainCategory) {
		    $category = array();
		    $category['id'] = $mainCategory->id;
		    $category['name'] = $mainCategory->name;
		    $category['parent_id'] = $mainCategory->parent_id;
		    $category['sub_categories'] = $this->get_category_by_parent($category['id']);
		    $categories[$mainCategory->id] = $category;
		  }
		  return $categories;
}

Category-subcategory Dropdownlist,
category_model.php:


public function fetchCategoryTree($parent_id = 0, $spacing = '', $user_tree_array = '') {
 
      if (!is_array($user_tree_array))
        $user_tree_array = array();

      $this->db->where('parent_id', $parent_id);
      $query = $this->db->get('categories');
      $result = $query->result();
      foreach ($result as $mainCategory) {
        $user_tree_array[] = array("id" => $mainCategory->id, "name" => $spacing . $mainCategory->name);
          $user_tree_array = $this->fetchCategoryTree($mainCategory->id, $spacing . '  ', $user_tree_array);
      }
      return $user_tree_array;
    }

views/category/index.php:

<?php
$this->load->model(‘category_model’);

$categoryList = $this->category_model->fetchCategoryTree();
?>
<select>
<?php foreach($categoryList as $cl) { ?>
<option value=”<?php echo $cl[“id”] ?>”><?php echo $cl[“name”]; ?></option>
<?php } ?>
</select>

Category-SubCategory Listing,
category_model.php:

function fetchCategoryTreeList($parent_id = 0, $user_tree_array = ”) {
if (!is_array($user_tree_array))
$user_tree_array = array();

$this->db->where(‘parent_id’, $parent_id);
$query = $this->db->get(‘categories’);
$result = $query->result();
$user_tree_array[] = “<ul>”;
foreach ($result as $mainCategory) {
$user_tree_array[] = “<li>”. $mainCategory->name.”</li>”;
$user_tree_array = $this->fetchCategoryTreeList($mainCategory->id, $user_tree_array);
}
$user_tree_array[] = “</ul>”;

return $user_tree_array;
}

views/category/index.php:

<?php
$this->load->model(‘category_model’);

$res = $this->category_model->fetchCategoryTreeList();
foreach ($res as $r) {
echo $r;
}

?>

Advertisements

PHP CodeSniffer – Coding Standard Tool

Install PHP-Coding-Standards

> pear install PHP_CodeSniffer-2.8.1

Install WordPress-Coding-Standards

> cd /var/www/html
> git clone -b master https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards.git wpcs
> phpcs –config-set installed_paths /var/www/html/wpcs

Install Codeigniter-Coding-Standards

> git clone https://github.com/thomas-ernest/CodeIgniter-for-PHP_CodeSniffer.git
> ant

or

> ant -Dphpcs.dir=”/usr/share/php/PHP/CodeSniffer”

Check Supported standards

> phpcs -i

Uninstall PHP-Coding-Standards

> pear uninstall PHP_CodeSniffer-2.8.1

Check Errors and Warnings

> phpcs file.php

Autofix Errors

> phpcbf file.php

Alphabetic Pagination in CakePHP

Open your controller file,

function index($page = 1) {
 $alphabets = range('A', 'Z');
 $alphagroups = array_chunk($alphabets,3);
 $alphagroups[] = array(0,9);
 $cur_alpha = (isset($page))?($page-1):0;
 if($cur_alpha >= 9){
  $reg_cond = '0123456789';
 } else {
  $reg_cond = trim(implode('', $alphagroups[$cur_alpha]));
 }
 $this->set('cur_alpha', $cur_alpha);
 $this->set('alphas', $alphagroups);
 $total = $this->Vendor->find('count');
 $this->set('total', $total);
 $this->Vendor->recursive = -1;
 $vendors = $this->Vendor->find('all', array(
  'conditions' => array('Vendor.name REGEXP' => '^['.$reg_cond.']')
));
 $this->set('vendors', $vendors);
}

Open index.ctp

foreach ($alphas as $key=>$alpha):
 $alphacode = implode("-",$alpha);
 if($key == $cur_alpha):
    echo $alphacode;
 else: 
    echo $html->link(__($alphacode, true), array('action'=>'index', $key+1));
 endif;
endforeach;

Categories followed by their subcategories in dropdown – Yii2.0

For Example

Parent1
__Child1-Parent1
__Child2-Parent1
__|__Child1-Child2-Parent1
Parent2
__Child1-Parent2
__Child2-Parent2
__|__Child1-Child2-Parent2
Parent3
Parent4
__Child-parent4

Create category table.

CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`description` text NOT NULL,
`image` varchar(250) NOT NULL,
`order` int(11) NOT NULL,
`parent_id` int(11) NOT NULL,
`status` int(11) NOT NULL DEFAULT '0' COMMENT '0=> inactive, 1=>active',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Open models/Category.php. Then add below code,

public function getCategories($parent_id = 0, $exclude = '', $space = '', $categories='')
{
if($parent_id == 0){
$space = '';
$categories = array();
}else{
$space .='- ';
}

$model = Category::findAll([
'parent_id' => $parent_id,
]);
if(!empty($model)){
foreach ($model as $key) {
if($key->id == $exclude) continue;
$categories[] = array('id'=>$key->id, 'name'=>$space.$key->name);
$categories = $this->getCategories($key->id, $exclude, $space, $categories);
}
}

return $categories;
}

Open views/category/_form.php

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Category;
?>

<?php 
 $category = new Category;
 $categories = $category->getCategories(0, $model->id);
 $items = ArrayHelper::map($categories, 'id', 'name');
?>
<?php echo $form->field($model, 'parent_id')->dropDownList($items,['prompt'=>'--None--']); ?>
'btn btn-success']) ?>
<?php ActiveForm::end(); ?> </div>

Woocommerce – Display shopping cart details on a WordPress menu

Open your theme’s functions.php.

Add below code:

add_filter('wp_nav_menu_items','wc_custom_menu_cart', 10, 2);
function wc_custom_menu_cart($menu, $args) {

 // Check if WooCommerce is active and add a new item to a menu assigned to Primary Navigation Menu location
 if ( !in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || 'primary' !== $args->theme_location )
 return $menu;

 $cart_url = WC()->cart->get_cart_url();
 $shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) );
 $viewing_cart = __('View your shopping cart', 'exploore');
 $start_shopping = __('Start shopping', 'exploore');
 $count = (int) WC()->cart->cart_contents_count;
 $cart_contents = sprintf(_n('%d item', '%d items', $count, 'exploore'), $count);
 $cart_total = WC()->cart->get_cart_total();
 
 $menu_item = '<li>';
 if ( $count > 0 ) { 
 $menu_item.= '<a class="cart-contents" href="'. $cart_url .'" title="'. $viewing_cart .'">';
 } else {
 $menu_item.= '<a class="cart-contents" href="'. $shop_page_url .'" title="'. $start_shopping .'">';
 }
 $menu_item.= '<i class="fa fa-shopping-cart"></i> ';
 $menu_item.= $cart_contents.' - '. $cart_total;
 $menu_item.= '</a>';
 $menu_item.= '</li>';

 $menu.=$menu_item;

 return $menu;
}

function my_header_add_to_cart_fragment( $fragments ) {
 
 ob_start();
 $cart_url = WC()->cart->get_cart_url();
 $shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) );
 $viewing_cart = __('View your shopping cart', 'exploore');
 $start_shopping = __('Start shopping', 'exploore');
 $count = WC()->cart->cart_contents_count;
 $cart_contents = sprintf(_n('%d item', '%d items', $count, 'exploore'), $count);
 $cart_total = WC()->cart->get_cart_total();

 if ( $count == 0 ) {
 ?>
 <a class="cart-contents" href="<?php echo $shop_page_url;?>" title="<?php echo $start_shopping;?>"><i class="fa fa-shopping-cart"></i> <?php echo $cart_contents.' - '. $cart_total;?></a>
 <?php } else { ?>
 <a class="cart-contents" href="<?php echo $cart_url;?>" title="<?php echo $viewing_cart;?>"><i class="fa fa-shopping-cart"></i> <?php echo $cart_contents.' - '. $cart_total;?></a>
 <?php
 }
 $fragments['a.cart-contents'] = ob_get_clean();
 
 return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment' );

Yii2 advanced – Hide frontend/web and backend/web from url

Step 1
Create .htaccess file in root folder, i.e advanced/.htaccess and write below code.
—————

Options +FollowSymlinks
RewriteEngine On

# deal with admin first
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^admin/assets/(.*)$ backend/web/assets/$1 [L]
RewriteRule ^admin/css/(.*)$ backend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/backend/web/(assets|css)/ <------
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^.*$ backend/web/index.php [L]

RewriteCond %{REQUEST_URI} ^/(assets|css) <------
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/(frontend|backend)/web/(assets|css)/ <------
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php

—————

Note : if you are trying in local server then replace ^/ with ^/project_name/ where you see arrow sign.
Remove those arrow sign

Step 2
Now create a components/Request.php file in common directory and write below code in this file.
—————

namespace common\components;


class Request extends \yii\web\Request {
    public $web;
    public $adminUrl;

    public function getBaseUrl(){
        return str_replace($this->web, "", parent::getBaseUrl()) . $this->adminUrl;
    }


    /*
        If you don't have this function, the admin site will 404 if you leave off 
        the trailing slash.

        E.g.:

        Wouldn't work:
        site.com/admin

        Would work:
        site.com/admin/

        Using this function, both will work.
    */
    public function resolvePathInfo(){
        if($this->getUrl() === $this->adminUrl){
            return "";
        }else{
            return parent::resolvePathInfo();
        }
    }
}

—————

Step 3
Installing component. Write below code in frontend/config/main.php and backend/config/main.php files respectively.
————————-


//frontend, under components array
'request'=>[
    'class' => 'common\components\Request',
    'web'=> '/frontend/web'
],
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
],

// backend, under components array
'request'=>[
    'class' => 'common\components\Request',
    'web'=> '/backend/web',
    'adminUrl' => '/admin'
],
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
],

————————-

Step 4 (Optional, if doesn’t work till step three)

create .htaccess file in frontend/web and backend/web directories
————————-


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]

————————-

Note: make sure you have enabled your mod rewrite in apache

Thats it! You can try your project with
http://www.project.com/admin, http://www.project.com

in local server
localhost/project_name/admin, localhost/project_name

Copy from: http://stackoverflow.com/questions/28118691/yii2-htaccess-how-to-hide-frontend-web-and-backend-web-completely

Install Yii2 advanced in Ubuntu

Step 1. Create an advanced project with composer

root@manager:/var/www/html# composer create-project --prefer-dist yiisoft/yii2-app-advanced yii2advanced

Step 2. Change to the yii2advanced folder and run the init command

root@manager:/var/www/html# cd yii2advanced
root@manager:/var/www/html/yii2advanced# php init
Yii Application Initialization Tool v1.0
Which environment do you want the application to be initialized in?
[0] Development
[1] Production

Your choice [0-1, or “q” to quit] 0

Initialize the application under ‘Development’ environment? [yes|no] y

Start initialization …

generate backend/config/main-local.php
generate backend/config/params-local.php
generate backend/web/index-test.php
generate backend/web/index.php
generate common/config/main-local.php
generate common/config/params-local.php
generate console/config/main-local.php
generate console/config/params-local.php
generate frontend/config/main-local.php
generate frontend/config/params-local.php
generate frontend/web/index-test.php
generate frontend/web/index.php
generate yii
generate cookie validation key in backend/config/main-local.php
generate cookie validation key in frontend/config/main-local.php
chmod 0777 backend/runtime
chmod 0777 backend/web/assets
chmod 0777 frontend/runtime
chmod 0777 frontend/web/assets
chmod 0755 yii

… initialization completed.

Step 3. Create the database

mysql> create database yii2advanced;

Open common/config/main-local.php set your mysql connection.

 'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
'username' => 'root',
'password' => 'redhat',
'charset' => 'utf8',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
// 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,
],
],
];

Step 4. Run the Yii Migration Tool

root@manager:/var/www/html/yii2advanced# php yii migrate

Yii Migration Tool (based on Yii v2.0.11.1)

Creating migration history table "migration"...Done.
Total 1 new migration to be applied:
m130524_201442_init

Apply the above migration? (yes|no) [no]:y
*** applying m130524_201442_init
> create table {{%user}} ... done (time: 0.140s)
*** applied m130524_201442_init (time: 0.186s)
1 migration was applied.

Migrated up successfully.

Contact Form 7 -continued

Contact form 7 save uploaded files in server and display uploaded image in mail(not as mail attachment)

Action hook: wpcf7_before_send_mail

The best way is to create a custom post type and save posted datas.

First, create contact form. Here my form name is ‘Application Form’.
add-new-contact-form-wordpress-site-wordpress

Then create post type:

function create_posttype() {
   register_post_type( 'online_applications',
   array(
     'labels' => array(
         'name' => __( 'Online Applications' ),
         'singular_name' => __( 'Online Application' )
      ),
      'public' => true,
      'has_archive' => true,
      'rewrite' => array('slug' => 'online_applications'),
      'supports' => array('title','thumbnail')
    )
    );
}
add_action( 'init', 'create_posttype' );

Then call function to save posted datas:

add_action('wpcf7_before_send_mail', 'save_application_form' );
function save_application_form($wpcf7)
{
    global $wpdb;
    $formtitle  = $wpcf7->title;
    $submission = WPCF7_Submission::get_instance();
    if ($submission) {
        $submited = array();
        $formData       = $submission->get_posted_data();
        $uploaded_files = $submission->uploaded_files(); 
    
        if ( $formtitle == 'Application Form') {
          $newpost = array(
          'post_type' => 'online_applications',
          'post_title' => $formData['name']. ' - ' .$formData['email'],
          'post_status' => 'pending');

          $newpostid = wp_insert_post($newpost);
          add_post_meta($newpostid, 'name', $formData['name']);
          add_post_meta($newpostid, 'email', $formData['email']);
          add_post_meta($newpostid, 'photograph', $formData['photograph']);

          //save photograph
          $wud = wp_upload_dir();
          $image_name     = $formData['photograph'];
          $image_location = $uploaded_files["photograph"];
          $image_content  = file_get_contents($image_location);
          $upload = wp_upload_bits($image_name, null, $image_content);
          $chemin_final = $upload['url'];
          $filename = $upload['file'];
          if ($filename > '') {
              require_once(ABSPATH . 'wp-admin/includes/admin.php');
              $wp_filetype = wp_check_filetype(basename($filename), null);
              $attachment = array(
                  'post_mime_type' => $wp_filetype['type'],
                  'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
                  'post_content' => '',
                  'post_status' => 'inherit'
              );
              $attach_id = wp_insert_attachment($attachment, $filename, $newpostid);
              require_once(ABSPATH . 'wp-admin/includes/image.php');
              $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
              wp_update_attachment_metadata($attach_id, $attach_data);
              update_post_meta($newpostid, "_thumbnail_id", $attach_id);
          }

          //code to display uploaded image in mail template - starts here
          $photo_url = wp_get_attachment_url( get_post_thumbnail_id($newpostid) );
          $photo_url = isset($formData['photo_url']) ? $formData['photo_url'] : $photo_url;
          $photo_url = '<img src="'.$photo_url.'" alt="photo" width="250" height="250" />';
          // do some replacements in the cf7 email body
          $mail         = $wpcf7->prop('mail');
          // Find/replace the "[photo_url]" tag as defined in your CF7 email body
          // and add changes name
          $mail['body'] = str_replace('[photo_url]', $photo_url, $mail['body']);
          $wpcf7->set_properties(array(
              "mail" => $mail
          ));
          //code to display uploaded image in mail template - ends here
        }
        // return current cf7 instance
        return $wpcf7;
  }
}