Saturday, March 9, 2019

ReactJS > Load Different Component Based on Different Conditions

I want to load different component based on URL or as I think, any different condition. So if URL is myreact.com/user/1000 it should load AdminUserComponent and if URL is myreact.com/user/5000 it should load StaffUserComponent. Its just an example, we can handle any type of conditions based on situation.
So our Route would be like

<Route path="/user/:user_param" component={UserDecideWrapper} />
And the UserDecideWrapper is nothing but a if else condition block to decide which component will load or not.

class ComponentDecide extends MainActivity {
    render() {
        let id = parseFloat(this.props.match.params.id);
        if (isNaN(id)) {
            return <Home {...this.props}/>
        }
        if (id === 1000) {
            return <AdminUserComponent {...this.props}/>
        }
        return <StaffUserComponent {...this.props}/>
    }
}
{...this.props} indicated that props will be passed as constructor.

Install ReactJS along with Laravel 5.X along with higher version such 6.X

We need npm command, so for this we need to install NodeJS first, this will create NPM along with this, for windows users, go to https://nodejs.org/en/ and download your suitable installer and install if not alredy installed..
Now we will create an Laravel project first using following command (this will take some time):
composer create-project --prefer-dist laravel/laravel ReactJSLaravelTutorial


Laravel installed:

Now we need to initiate scaffolding with React. Luckily for us, there is a preset Artisan command we can use for that. The preset command was added in Laravel 5.5, which allows us to specify our JavaScript framework of choice.

php artisan preset react

After that, we need to install the JavaScript dependencies of our project. By default, package.json file is there, so we just need to type the following command to get the NPM dependencies.

Please run npm install && npm run dev to compile your fresh scaffolding.
We should now have an Example.js file inside resources/assets/js/components, which is a basic React component. Also, resources/assets/js/app.js has been updated to make use of the Example component.

Now go to your database manager, for example, phpMyAdmin or MySQL work bench and create one database.
Go to .env file and enter your database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db-laravel1
DB_USERNAME=root
DB_PASSWORD=
Now we will create a model using command: php artisan make:model Project -m (this will create an migration script):

D:\all-my-php-projects\ReactJS\ReactJSLaravelTutorial>php artisan make:model Project -m
Model created successfully.
Created Migration: 2019_03_03_153423_create_projects_table

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    protected $fillable = ['name', 'description'];
}

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProjectsTable extends Migration
{
    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('description');
            $table->boolean('is_completed')->default(0);
            $table->timestamps();
        });
    }

    public function down()
    {
        
    }
}

And execute command php artisan migrate, this will create/modify table as needed.
We’ll start by defining the API endpoints. Open routes/api.php and replace it content with the code below:

<?php
Route::get('projects', 'ProjectController@index');
Route::post('projects', 'ProjectController@store');
Route::get('projects/{id}', 'ProjectController@show');
Route::put('projects/{project}', 'ProjectController@markAsCompleted');
Now we will create controller using command: php artisan make:controller ProjectController

<?php
namespace App\Http\Controllers;

use App\Project;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    public function index()
    {
        $projects = Project::where('is_completed', false)
            ->orderBy('created_at', 'desc')
            ->withCount(['tasks' => function ($query) {
                $query->where('is_completed', false);
            }])
            ->get();

        return $projects->toJson();
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required',
            'description' => 'required',
        ]);

        $project = Project::create([
            'name' => $validatedData['name'],
            'description' => $validatedData['description'],
        ]);

        return response()->json('Project created!');
    }

    public function show($id)
    {
        $project = Project::with(['tasks' => function ($query) {
            $query->where('is_completed', false);
        }])->find($id);

        return $project->toJson();
    }

    public function markAsCompleted(Project $project)
    {
        $project->is_completed = true;
        $project->update();

        return response()->json('Project updated!');
    }
}
We’ll be using React Router to handle routing in our application. For this, we need to render a single view file for all our application routes. Open routes/web.php and replace it content with the code below:

Route::view('/{path?}', 'app');
Next, let’s create the app.blade.php view file. We’ll create this file directly within the resources/views directory, then paste the following code in it:

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Project Management</title>
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app"></div>

<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
The App component will serve as the base for our React components. Let’s rename the default Example component to App and replace it content with the following code:
// resources/js/components/App.js

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Header from './Header'
import ProjectsList from './ProjectsList'

class App extends Component {
    render () {
        return (
            <BrowserRouter>
                <div>
                    <Header />
                    <Switch>
                        <Route exact path='/' component={ProjectsList} />
                    </Switch>
                </div>
            </BrowserRouter>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('app'));


Now install react router using command: npm install react-router-dom

update resources/assets/js/app.js as below:

require('./bootstrap');
require('./components/App');
Create a new Header.js file within the resources/js/components directory and paste the code below in it:

import React from 'react'
import { Link } from 'react-router-dom'

const Header = () => (
    <nav className='navbar navbar-expand-md navbar-light navbar-laravel'>
        <div className='container'>
            <Link className='navbar-brand' to='/'>Project Management</Link>
        </div>
    </nav>
);

export default Header
Create a new ProjectsList.js file within the resources/js/components directory and paste the code below in it:

import axios from 'axios'
import React, { Component } from 'react'
import { Link } from 'react-router-dom'

class ProjectsList extends Component {
    constructor () {
        super();
        this.state = {
            projects: []
        }
    }

    componentDidMount () {
        axios.get('/api/projects').then( response => {
            this.setState({
                projects: response.data
            })
        })
    }

    render () {
        const { projects } = this.state;
        return (
            <div className='container py-4'>
                <div className='row justify-content-center'>
                    <div className='col-md-8'>
                        <div className='card'>
                            <div className='card-header'>All projects</div>
                            <div className='card-body'>
                                <Link className='btn btn-primary btn-sm mb-3' to='/create'>
                                    Create new project
                                </Link>
                                <ul className='list-group list-group-flush'>
                                    {projects.map(project => (
                                        <Link
                                            className='list-group-item list-group-item-action d-flex justify-content-between align-items-center'
                                            to={`/${project.id}`}
                                            key={project.id}>
                                            {project.name}
                                            <span className='badge badge-primary badge-pill'>{project.tasks_count}</span>
                                        </Link>
                                    ))}
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default ProjectsList
This is the basic structure for ReactJS with Laravel. Execute php artisan serve to start server.
Some sample screen shots:



Run command npm run dev (for windows user, run command as an administrator) to compile ReactJS code once you made some changes.

Below is GitHub link of this project:

https://github.com/pritomkucse/reactjs-with-laravel-6.X

After download source from GitHub run command composer install to install laravel dependencies, then run php artisan migrate for database migration (but make sure you configure database in .env file) and then run npm install to install ReactJS dependencies. Finally run npm run dev to package ReactJS and then browser your project directory. That's all.


Sample .env File
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:PuBBf9PHnf4RkJokRNDMeTDY6SWWr8s2TilF9E3b4Fs=
APP_DEBUG=true
APP_URL=http://react-with-laravel.com
APP_PATH=/

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db-laravel1
DB_USERNAME=root
DB_PASSWORD=1234

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Sample Virtual Host File

<VirtualHost react-with-laravel.com:80>
    DocumentRoot "C:\Users\PRITOM\Desktop\MINE\reactjs-with-laravel-6.X\public"
    ServerName react-with-laravel.com
    ErrorLog "logs/react-with-laravel.com-error.log"
    CustomLog "logs/react-with-laravel.com-access.log" combined
    <Directory "C:\Users\PRITOM\Desktop\MINE\reactjs-with-laravel-6.X">
        Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            Require all granted
    </Directory>
</VirtualHost>

Sunday, March 3, 2019

Install ReactJS on Windows using NPM with help of NODEJS

First needs to install NodeJS, for windows users, go to https://nodejs.org/en/ and download your suitable installer and install if not alredy installed.
After installation completed go to your installation directory (for me its C:\Program Files\nodejs\node_modules) and check there is a folder named "npm", if exists open a command prompt (WINDOWS_BUTTON+CMD) and type command "npm -v" to see if nodejs installed properly.

Now time to install React from Terminal: npm install -g create-react-app, it will take some time to complete.

If successful, you should be able to get version: create-react-app --version
Now time to create a project: create-react-app react_app1, after create project navigate to project directory using cd react_app1

Expected output in terminal (and should auto open browser to port 3000) on start project using command npm start:


Friday, March 1, 2019

How to install Laravel 5 with Xampp (Windows)

Requirements
  1. PHP >= 5.5.9
  2. OpenSSL PHP Extension
  3. PDO PHP Extension
  4. Mbstring PHP Extension
  5. Tokenizer PHP Extension
Install Xampp
First of all, we need Xampp, so we can download it from the official page: Download Xampp
Install Composer
After you've downloaded and installed Xampp, we need to install Composer.
Composer is a PHP package manager that is integrated with Laravel Framework. In Windows we can install it easy going to the official page and download the installer. Composer Download page

Install Laravel Framework
We are prepared to install and configure a Laravel Framework. First of all, we have to navigate to htdocs folder to install it and run this following command:
composer create-project laravel/laravel laravel "5.1.*"
When it finishes, it will create following directory schema:

Now browse your laravel project into browser:


Monday, February 25, 2019

Online CSV Viewer

Use this tool as a CSV Viewer capable of reading delimited data.
Online Viewer

Friday, February 22, 2019

WordPress | Customizing Taxonomies as Dropdowns in Quick Edit | Display a custom taxonomy as a dropdown on the quick edit posts page

We need to display custom taxonomy options in post quick edit page as dropdown as below screen shot:

The very first step is to register taxonomy.
https://pritomkumar.blogspot.com/2019/02/wordpress-plugin-how-to-create-custom.html will help you.
Now the target is to display taxonomy options in quick edit posts page. For that we have to register some actions as below:
<?php
add_action('admin_enqueue_scripts', array(self::class, 'my_add_admin_scripts'));

add_filter('manage_posts_columns', array(self::class, 'add_post_fake_column'), 10, 2);
add_filter('manage_edit-post_columns', array(self::class, 'remove_post_fake_column'));
add_action('quick_edit_custom_box', array(self::class, 'add_post_quick_edit_box'), 10, 2);
add_action('save_post', array(self::class, "my_taxonomy_post_save_callback"), 1, 2);

$action_name = 'plugin_my_personal_taxonomy';
add_action ('wp_ajax_' . $action_name, array(self::class, 'ajax_call_your_function'));
add_action ('wp_ajax_nopriv_' . $action_name, array(self::class, 'ajax_call_your_function'));
<?php
public static function my_add_admin_scripts() {
    global $pagenow;

    $taxonomy = MY_TAXONOMY_PLUGIN_CORE . 'color';
    wp_register_script(
        'MY_TAXONOMY_PLUGIN_CORE',
        MY_TAXONOMY_PLUGIN_URL . 'assets/script7.js',
        array('jquery')
    );

    $params = array(
        'BASE_URL' => MY_TAXONOMY_PLUGIN_URL,
        'ADMIN_URL' => admin_url()
    );
    wp_localize_script( 'MY_TAXONOMY_PLUGIN_CORE', 'MY_TAXONOMY_PLUGIN_CORE', $params);

    wp_enqueue_script('MY_TAXONOMY_PLUGIN_CORE');

    wp_enqueue_style(
        "MY_TAXONOMY_PLUGIN_CORE", MY_TAXONOMY_PLUGIN_URL . "assets/style7.css"
    );
}
<?php
public static function add_post_fake_column($posts_columns, $post_type) {
    $posts_columns['fake_column_taxonomy_color'] = 'Fake Column (Invisible)';
    return $posts_columns;
}

public static function remove_post_fake_column($posts_columns) {
    unset($posts_columns['fake_column_taxonomy_color']);
    return $posts_columns;
}
<?php
public static function add_post_quick_edit_box($column_name, $post_type) {
    if (true) {
        $taxonomy = get_taxonomy(self::getTaxonomyName());

        $taxonomy_options = get_terms(array(
            'taxonomy' => self::getTaxonomyName(),
            'hide_empty' => false,
        ));

        if (count($taxonomy_options) > 0) {
            $post_terms = [];
            $post_id = isset($GLOBALS['post_id']) ? $GLOBALS['post_id'] : get_the_ID();
            foreach(wp_get_post_terms($post_id, self::getTaxonomyName()) as $o) {
                $post_terms[$o->term_id] = 1;
            }

            global $taxonomy_data_map;
            $taxonomy_data_map = [];
            $taxonomy_data_map['name'] = self::getTaxonomyName();
            $taxonomy_data_map['value_field'] = $taxonomy->hierarchical ? 'term_id' : 'name';
            $taxonomy_data_map['options'] = $taxonomy_options;
            $taxonomy_data_map['selected'] = $post_terms;

            include_once MY_TAXONOMY_PLUGIN_DIR . 'templates/taxonomy_post_quick_edit.php';
            wp_nonce_field( MY_TAXONOMY_PLUGIN_NONCE_FIELD_NAME, MY_TAXONOMY_PLUGIN_NONCE_FIELD_NAME );
        }
    }
}
taxonomy_post_quick_edit.php

<?php
global $taxonomy_data_map;
$terms = $taxonomy_data_map['options'];
$value_field = $taxonomy_data_map['value_field'];
$selected = $taxonomy_data_map['selected'];
?>
<fieldset class="inline-edit-col-left my_taxonomy_plugin_color-quick-editor">
    <div class="inline-edit-col">
        <span class="title"><?= __('Colors') ?></span>
        <select name='<?= $taxonomy_data_map['name'] ?>[]' id='<?= $taxonomy_data_map['name'] ?>' multiple>
            <?php
            foreach ($terms as $term) {
                $_checked = isset($selected[$term->term_id]) ? 'selected' : '';
                echo "<option value='{$term->{$value_field}}' {$_checked}>{$term->name}</option>\n";
            }
            ?>
        </select>
    </div>
</fieldset>
<?php
public static function my_taxonomy_post_save_callback($id, $post) {
    if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) || !current_user_can('edit_page', $id)) {
        return $id;
    }
    if (!isset($_POST[MY_TAXONOMY_PLUGIN_NONCE_FIELD_NAME])) {
        return $id;
    }
    if (!wp_verify_nonce($_POST[MY_TAXONOMY_PLUGIN_NONCE_FIELD_NAME], MY_TAXONOMY_PLUGIN_NONCE_FIELD_NAME)) {
        return $id;
    }
    if (!current_user_can( 'edit_post', $id)) {
        return $id;
    }

    $taxonomy = get_taxonomy(self::getTaxonomyName());
    $field = $taxonomy->hierarchical ? 'term_id' : 'name';

    $taxonomy_options = array();
    foreach(get_terms(array('taxonomy' => self::getTaxonomyName(), 'hide_empty' => false)) as $o) {
         $taxonomy_options[strval($o->{$field})] = 1;
    }

    if (count($taxonomy_options)) {
        $options = array();
        foreach((isset($_POST[self::getTaxonomyName()]) ? $_POST[self::getTaxonomyName()] : array()) as $i) {
            if (isset($taxonomy_options[$i])) {
                array_push($options, $i);
            }
        }
        wp_set_post_terms($id, $options, self::getTaxonomyName());
    }
    else {
        wp_set_post_terms($id, array(), self::getTaxonomyName());
    }

    return $id;
}
<?php
public static function ajax_call_your_function() {
    $case = isset($_REQUEST['case']) ? $_REQUEST['case'] : '';
    switch ($case) {
        case 'post-quick-edit':
            $id = isset($_REQUEST['id']) ? doubleval($_REQUEST['id']) : 0;
            if ($id > 0) {
                $GLOBALS['post_id'] = $id;
                self::add_post_quick_edit_box(null, null);
                wp_die();
            }
            break;
    }
    header("HTTP/1.1 404");
    echo __("Not Found");
    exit;
}
script7.js

jQuery(document).ready(function(){
    var $ = jQuery, body = $(document.body);

    if (typeof inlineEditPost !== 'undefined') {
        (function ($, inlineEditPost) {
            // inlineEditTax does not invoke any events, but does ensure to stop
            // propagation to all other event handlers; swap it out.
            inlineEditPost.realOne = inlineEditPost.edit;

            inlineEditPost.edit = function (link) {
                // Invoke original edit event handler.
                this.realOne(link);

                var id = inlineEditPost.getId(link), tr = $(link).closest("table").find("tr#edit-" + id);
                var qe = tr.find(".my_taxonomy_plugin_color-quick-editor");
                if (qe.length) {
                    $.ajax ({
                        url: MY_TAXONOMY_PLUGIN_CORE.ADMIN_URL + '/admin-ajax.php',
                        type: 'POST',
                        dataType: 'HTML',
                        data: {
                            action: 'plugin_my_personal_taxonomy',
                            case: 'post-quick-edit',
                            id: id
                        },
                        success: function (resp) {
                            qe.html($(resp).html());
                        },
                        error: function (xhr, ajaxOptions, thrownError) {

                        },
                    });
                }
                return false;
            }
        })($, inlineEditPost);
    }
});

Download full plugin from BitBucket