Monday, 2 July 2018

How to use registered post type Hook

How to use registered_post_type Hook and modify post type registration

Create custom post type hook for products inside function.php file

add_action( 'init', 'wpyog_register_products_cpt' );
/**
 * Register Products Custom Post Type 
 */
function wpyog_register_products_cpt() {
    // change 'wpyog_products' to whatever your text_domain is.
    
    /** Setup labels */
    $labels = array(
        'name'               => x_( 'Products', 'wpyog_products' ),
        'singular_name'      => x_( 'Product', 'wpyog_products' ),
        'add_new'            => x_( 'Add New', 'wpyog_products' ),
        'all_items'          => x_( 'All Products', 'wpyog_products' ),
        'add_new_item'       => x_( 'Add New Product', 'wpyog_products' ),
        'edit_item'          => x_( 'Edit Product', 'wpyog_products' ),
        'new_item'           => x_( 'New Product', 'wpyog_products' ),
        'view_item'          => x_( 'View Product', 'wpyog_products' ),
        'search_items'       => x_( 'Search Products', 'wpyog_products' ),
        'not_found'          => x_( 'No Products found', 'wpyog_products' ),
        'not_found_in_trash' => x_( 'No Products found in trash', 'wpyog_products' ),
        'parent_item_colon'  => x_( 'Parent Product:', 'wpyog_products' ),
        'menu_name'          => x_( 'Products', 'wpyog_products' )
    );
    
    /** Setup args */
    $args = array(
        'labels'              => $labels,
        'description'         => x_( 'Products post type', 'wpyog_products' ),
        'public'              => true,
        'menu_position'       => 20,
        'supports'            => array( 'title', 'editor', 'excerpt', 'page-attributes', ),
        'has_archive'         => 'books',
        'rewrite'             => array( 'slug' => 'product', ),
    );
    
    /** Register Custom Post Type */
    register_post_type( 'wpyog_products', $args );
}

So if I wanted to change the label, add function inside function.php file:

add_action( 'registered_post_type', 'wpyog_products_label_rename', 10, 2 );
/**
 * Modify registered post type
 *
 * @param string $post_type Registered post type name.
 * @param array $args Array of post type parameters.
 */
function wpyog_products_label_rename( $post_type, $args ) {
    if ( 'wpyog_products' === $post_type ) {
        global $wp_post_types;
$args->labels->menu_name = __( 'Custom Products', 'wpyog_products' );
        $args->exclude_from_search = false;
        $wp_post_types[ $post_type ] = $args;
$wp_post_types['wpyog_products']->exclude_from_search = false;
    }



So if I wanted to change the taxonomy slug, add function inside function.php file:

function wpyog_modify_taxonomy() {
$product_category_args = get_taxonomy( 'kbe_taxonomy' ); // returns an object
// make changes to the args
// in this example there are three changes
// again, note that it's an object
$product_category_args->show_admin_column = true;
$product_category_args->rewrite['slug'] = 'product_resources';
$product_category_args->rewrite['with_front'] = true;

// re-register the taxonomy
register_taxonomy( 'kbe_taxonomy', 'product_resources', (array) $product_category_args );
}

add_action( 'init', 'wpyog_modify_taxonomy', 11 );

Monday, 11 June 2018

How to change integer value in number format jQuery

Here are simple way you can change integer value in number format on key up using jQuery

Html Code:
<input type="text" name="amount" class="required" value="">

jQuery Code:
<script>
jQuery.noConflict();
jQuery(document).ready( function($){ 
$(document).on('keyup', 'input.required', function(event){
if($(this).hasClass('field-error')){
$(this).css('border-color', '#83A4C5');
$(this).removeClass('field-error');
}   
var selection = window.getSelection().toString();
if ( selection !== '' ) {
return;
}           
// When the arrow keys are pressed, abort it.
if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
return;
}      
var $this = $( this );           
// Get the value.
var input = $this.val();            
var input = input.replace(/[\D\s\._\-]+/g, "");
input = input ? parseInt( input, 10 ) : 0;
$this.val( function() {
return ( input === 0 ) ? "" : input.toLocaleString( "en-US" );
} );      
});
});
</script>

Monday, 23 April 2018

How to implement routing in Nodejs

A route is a mapping from a url to an object.It handles HTTP client requests.

Basic Routing

Hope you have install and have basic knowledge Express module.
npm install express

Note: Above command download the required express modules and install them.

Here is our Server file.

var express = require( 'express' );
var app = express();
//Creating Router() object
var router = express.Router();
// Provide all routes here, this is for Home page.
router.get("/",function(req,res){
  res.json({"message" : "Hello World"});
});
app.use("/",router);
// Listen to this Port
app.listen(3000,function(){
  console.log("Live at Port 3000");
});

Code Explanation:

1. In our first line of code, include the "express module."
2. Create object of the express module.
3. Creating a callback function. This function call when you hit url from browser http://localhost:3000 .It send the string 'Hello World' to the web page.
4. The 'res' parameter is used to send content back to the web page.
5. Create object of route() module. And handle get request.

Basic middleware routing :

// Router middleware, mentioned it before defining routes.

router.use(function(req,res,next) {
  console.log("/" + req.method);
  next();
});

Create a router file named route.js in the app directory, with the following content:

var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Home page content')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About page content')
})
module.exports = router

Load the router module in the app:

var routes = require('./route');
app.use('/child', routes)

Now make a requests to /child and /child/about

Tuesday, 17 April 2018

How to implement Real time notification in NodeJs

Here are simple steps to create real time notification using NodeJs, Socket.io and Mysql

Socket.IO enables real-time bidirectional event-based communication.It has two parts: a client-side library that runs in the browser, and a server-side library for node.js. Install Socket.IO


npm install --save socket.io

I hope you have install express and mysql. This are basic few code inside server file.

var express = require( 'express' );
var app = express();
app.use( express.static( __dirname + '/public') );

var mysql = require('mysql');
var server = require( 'http' ).Server( app );
var io = require( 'socket.io' )( server );
server.listen( 3000, function(){
  console.log( 'listening on *:3000' );

} );
app.get('/', function(req, res) {
   res.sendFile(__dirname + '/index.html');

});

The require('socket.io')(http) creates a new socket.io instance attached to the http server.

Now make mysql connection

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "nodejs"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");

});

Now in index.html I add the following snippet before the </body>:
It load the socket.io-client, and then connect with server.
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();

</script>

Now in server file I add the following snippet. It will check connection event for incoming sockets,

io.on('connection', function(socket){
  console.log('a user connected');
});

Now add event on client side
socket.on('user list', function(list){
$('.blink_me').text(list[0].totalUsers);

});

Handle event in server side.

io.on('connection', function(socket){
  setInterval(function() { // send total users after 4 second
      con.query("SELECT count(*) as totalUsers FROM customer", function(err, result) {
if(err){
throw err;
}
io.emit('user list', result);
  });
   }, 4000);

});

Some Important points

Socket Event Handling

In order to send an event to everyone, Socket.IO gives us the io.emit:

io.emit('some event', { for: 'everyone' });

You can create and execute custom events using the socket.emit function.

eg: socket.emit('customEvent', { content: 'A custom event created !'});

in view file use it
var socket = io();
socket.on('customEvent', function(data){document.write(data.content)});

You can also emit events from the client side. To emit an event from your client, use the emit function on the socket object.
var socket = io();
socket.emit('clientEvent', 'Sent an event from the client!');

inside server file
socket.on('clientEvent', function(data) {
  console.log(data);

});

Socket Broadcasting
Broadcasting means sending a message to all connected clients.To broadcast an event to all the clients, we can use the io.sockets.emit method.

inside server file:
var clients = 0;
io.on('connection', function(socket) {
   clients++;
   io.sockets.emit('broadcast',{ description: clients + ' clients connected!'});
   socket.on('disconnect', function () {
      clients--;
      io.sockets.emit('broadcast',{ description: clients + ' clients connected!'});
   });
});

On the client side
socket.on('broadcast',function(data) {
document.write(data.description);

});

Thursday, 28 December 2017

How to Implement CRUD in Node js With MySQL

How to Implement CRUD in Node.js With MySQL

In this post, we are going to create a simple CRUD application in Node.js with MySQL as the database. We are using EJS as the template engine.

Before get started with this tutorial: You need to have Node installed. Read my previous post for Node.js installation.






Step 1: Create index.js as main file and package.json file

package.json
{
"name": "curdnode",
"version": "1.0.0",
"description": "Create simple curd example in nodejs",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "techsudhir",
"license": "ISC"
}

index.js
console.log('Welcome You');

Now open up your command line and run :
npm start

Output:
Welcome You

Stop the current server by hitting CTRL + C in the command line.

Step 2: Now install required dependency for CRUD application

a) Express dependency
   npm install express --save
 
b) Path dependency
   npm install path --save
 
c) Body Parser dependency
   npm install body-parser --save
 
d) MySQL dependency
   npm install mysql --save
 
e) EJS template
   npm install ejs --save
 
Step 3: We are using http method to handling GET/POST request
    var http = require("http");

Now use all dependency

var express = require('express');
var path = require('path');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "nodejs"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

Step 4: Now create port and run from browser
   app.listen(3015, function () {
  console.log('Example app listening on port 3015!');
   });
 
   Now Run in browser localhost:3015
 
 
CRUD - Implementation begain from here

Note: For view handling create folder views at root directory

Use GET method for GET type request handling
app.get('/', function (req, res) {
    res.render('pages/index', {
title : 'Node Curd'
    });
});

Inside views folder create pages folder. Inside pages folder create index.ejs file

views/pages/index.ejs

We are using EJS template engine

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- include elements head -->
    <% include ../partials/head %>
</head>
<body class="container">

<header>
    <!-- include elements head -->
    <% include ../partials/header %>
</header>

<main>
    <div class="jumbotron">
        <h1>This is great</h1>
        <p>Welcome to templating using EJS</p>
<p><%= tagline %></p>
<ul>
    <% drinks.forEach(function(drink) { %>
        <li><%= drink.name %> - <%= drink.drunkness %></li>
    <% }); %>
</ul>
    </div>
</main>

<footer>
    <% include ../partials/footer %>
</footer>

</body>
</html>


views/partials/head.ejs
Partial view include in index file
<meta charset="UTF-8">
<title><%= title %></title>

<!-- CSS (load bootstrap from a CDN) -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>
    body    { padding-top:50px; }

</style>

views/partials/header.ejs
Partial view include in index file

<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon glyphicon-tree-deciduous"></span>
EJS Is Fun
</a>
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/customer">Customer</a></li>
<li><a href="/add-customer">Add New Customer</a></li>
</ul>
</div>
</div>

</nav>

views/partials/header.ejs
Partial view include in index file
<p class="text-center text-muted">© Copyright 2017 Appt Medical</p>

Node Create add method inside index.js file
app.get('/add-customer', function(req, res) {
    res.render('pages/add-customer',{title : 'Add New Customer'});
});

Create its views 
views/pages/add-customer.ejs

<!DOCTYPE html>
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">

<header>
<% include ../partials/header %>
</header>

<main>
<div class="row">
<div class="col-sm-8">    
<div class="well">
   <form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-sm-2" for="inputName">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputName" placeholder="Name" name="name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputEmail">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail" placeholder="Email" name="email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputPassword">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" name="password">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputAddress">Address</label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="inputAddress" placeholder="Address" name="address"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputPhone">Phone</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPhone" placeholder="Phone" name="phone">
</div>
</div>
<div class="form-group">        
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>

<div class="col-sm-4">        
<div class="well">
<h3>Look I'm A Sidebar!</h3>
</div>
</div>

</div>
</main>

<footer>
<% include ../partials/footer %>
</footer>

</body>
</html>

Create POST method handle request and insert into database
app.post('/add-customer', function(request, response){
response.setHeader('Content-Type', 'application/json');
var users={
"name":request.body.name,
"email":request.body.email,
"password":request.body.password,
"address":request.body.address,
"phone":request.body.phone,
}

con.query('INSERT INTO customer SET ?',users, function (error, results, fields) {
if (error) {
console.log("error ocurred",error);
response.send({
  "code":400,
  "failed":"error ocurred"
})
}else{
console.log('The solution is: ', results);
return response.redirect('/customer');
}
});

});

Node Create edit method inside index.js file
app.get('/customer/:id',function(req,res) {
var customerId = req.params.id;
con.query('select * from customer where id = ?', customerId, function(err,result) {
res.render('pages/edit-customer',{title : 'Customer',customer:result});
});
});

Create its views 
views/pages/edit-customer.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

<header>
    <% include ../partials/header %>
</header>

<main>
<div class="row">
    <div class="col-sm-8">    
        <div class="well">
           <form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-sm-2" for="inputName">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputName" placeholder="Name" name="name" value="<%=  customer[0].name %>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputEmail">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail" placeholder="Email" name="email" value="<%=  customer[0].email %>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputAddress">Address</label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="inputAddress" placeholder="Address" name="address"><%=  customer[0].address %></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputPhone">Phone</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPhone" placeholder="Phone" name="phone" value="<%=  customer[0].phone %>">
</div>
</div>
<div class="form-group">        
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
        </div>
    </div>

    <div class="col-sm-4">        
        <div class="well">
            <h3>Look I'm A Sidebar!</h3>
        </div>
    </div>

</div>
</main>

<footer>
    <% include ../partials/footer %>
</footer>

</body>
</html>

Create POST method handle request and update into database
app.post('/customer/:id',function(req,res) {
var customerId = req.params.id;
res.setHeader('Content-Type', 'application/json');
var users={
"name":req.body.name,
"email":req.body.email,
"address":req.body.address,
"phone":req.body.phone,
}
console.log(users);
con.query(' UPDATE customer SET ? where id = ? ',[users,customerId], function (error, results, fields) {
if (error) {
console.log("error ocurred",error);
res.send({
  "code":400,
  "failed":"error ocurred"
})
}else{
console.log('The solution is: ', results);
return res.redirect('/customer');
}
});

});

Create method list all rows index.js file
app.get('/customer', function(req, res) {
con.query("SELECT * FROM customer", function(err, result) {
if(err){
            throw err;
}
req.flash('success', 'Registration successfully');
res.locals.message = req.flash();
res.render('pages/customer',{title : 'Customer',customer:result});
  });
});

Create its views 
views/pages/customer.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

<header>
    <% include ../partials/header %>
</header>

<main>
<div class="row">
    <div class="col-sm-8">  
<% if(locals.message){ %>
    <div class="alert alert-success" role="alert">
        <strong>Well done!</strong> <%=message.success%>
    </div>
<% } %>
        <div class="well">
            <h3>Teacher Listing</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<% for(i=0;i<customer.length;i++){ %>
<tr>  
<td><%=  customer[i].name %>&nbsp;</td>  
<td><%=  customer[i].email %>&nbsp;</td>
<td><%=  customer[i].address %>&nbsp;</td>
<td><%=  customer[i].phone %>&nbsp;</td>
<td><a href="/customer/<%=  customer[i].id %>">Edit</a>
<a href="/delete/<%=  customer[i].id %>">Delete</a>
</td>
</tr>                                   
<% } %>
</tbody>
</table>
        </div>
    </div>
</div>
</main>

<footer>
    <% include ../partials/footer %>
</footer>

</body>

</html>

Create delete method inside index.js file
app.get('/delete/:id',function(req,res) {
var customerId = req.params.id;
con.query('DELETE FROM customer WHERE id = ?', customerId, function (err, result) {
if (err) throw err;
console.log('Deleted ' + result.affectedRows + ' rows');
}
);
return res.redirect('/customer');

});

Friday, 8 September 2017

How to Create a jQuery Autocomplete in Wordpress

How to Create a jquery-ui Autocomplete in wordpress.

Autocomplete provides suggestions while you type into the text field. In Wordpress we fetch dynamically matched pattern.

Include javascript and css files in header.

Create action inside functions.php or inside plugin code.

add_action('wp_head', 'custom_register_scripts');

function custom_register_scripts(){
wp_register_style( 'techsudhir_jquery_ui_css', plugin_dir_url(__FILE__) . 'css/jquery-ui.css', false,'1.0.0' );
wp_enqueue_style( 'techsudhir_jquery_ui_css' );

wp_register_script('techsudhir_jquery_ui_js',plugin_dir_url(__FILE__) . 'js/jquery-ui.js',array('jquery'),'1.1', false);
wp_enqueue_script('techsudhir_jquery_ui_js');

wp_localize_script( 'techsudhir_autocomplete', 'jqueryAutocomplete', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'techsudhir_autocomplete' );
}

Now add script for Autocomplete

jQuery("#destination_id").autocomplete({
source: function(req, response){
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: jqueryAutocomplete.ajaxurl,
data: 'action=wpyog_search_program&term='+req.term,
success: function(data) {
response(jQuery.map(data, function (item) {
return {
label: item.name,
value: item.id
};
}));
}
});
},
select: function(event, ui) {
jQuery("#destination_id").val(ui.item.label); 
jQuery("#program_id").val(ui.item.value); 
return false;
// save selected id to hidden input
},
minLength: 3
});

Create action inside functions.php or inside your plugin code.

add_action('wp_ajax_nopriv_wpyog_search_program', 'wpyog_search_program');
add_action('wp_ajax_get_wpyog_search_program', 'wpyog_search_program');
function wpyog_search_program(){
global $wpdb;
$suggestions=array();
$search_key = $_REQUEST['term'];
$table_trips = $wpdb->prefix . "wpyog_trips"; // Use custom table for data fetch
    $tripRows = $wpdb->get_results("SELECT id, title, description from $table_trips where title like '%$search_key%' or description like '%$search_key%'");
foreach($tripRows as $row){
$suggestion = array();
        $suggestion['id'] = $row->id;
        $suggestion['name'] = (!empty($row->title))?$row->title:$row->description;
$suggestions[]= $suggestion;
}  
    echo json_encode($suggestions);
    // Don't forget to exit!
    exit;
}

Monday, 28 August 2017

Simple CRUD Example in Cakephp

Simple CRUD Operation in CakePHP 2.x

This tutorial will explain about CRUD Operation in CakePHP. Here we will perform mysql Insert, Select, Update, Delete operation in cakePHP Framework. As we know CakePHP uses MVC design patterns.

Here we will cover following points:
1. MySQL Database Table Used
2. We are using CakePHP Version 2.x
3. Create/Select/Update/Delete records.

We have assume that you have already created you database table. Here is simple users table structure.
CREATE TABLE `users` (
  `id` bigint(20) UNSIGNED NOT NULL primary key AUTO_INCREMENT,
  `firstname` varchar(128) NOT NULL,
  `lastname` varchar(128) DEFAULT NULL,
  `username` varchar(128) DEFAULT NULL,
  `password` varchar(128) DEFAULT NULL,
  `email` varchar(128) DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
)

Create action inside Users controller.
Controller: app/Controller/UsersController.php

Create add function inside controller: add() function is used to save data. Here we are using "User" model.
public function add() 
{
  if ($this->request->is(array('post', 'put'))) {
{
$this->User->create();
if ($this->User->save($this->request->data)) 
{
$this->Session->setFlash(('Users has been saved successfully'));
return $this->redirect(array('controller' => 'Users', 'action' => 'index'));
} else 
{
$this->Session->setFlash(('User could not be saved. Please, try again.'));
}
}
}

Create view file for add action
View: app/View/Users/add.ctp

<h1>Add User</h1>
<?php
echo $this->Form->create('User');
echo $this->Form->input('firstname');
echo $this->Form->input('lastname');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('email');
echo $this->Form->end('Save');
?>

Create edit function: In edit(), here $id parameter to access an existing record. 
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(_('Invalid user'));
}
if ($this->request->is(array('post', 'put'))) {
$this->User->id = $id;
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->findById($id);
}
}

View file for edit action
View: app/View/Users/edit.ctp

<h1>Edit User</h1>
<?php
echo $this->Form->create('User');
echo $this->Form->input('firstname');
echo $this->Form->input('lastname');
echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->end('Save User');
?>

Create Delete Function: delete() function deletes the data which is ID. 
public function delete($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(('The user has been deleted.'));
} else {
$this->Session->setFlash(('The user could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}

Index Function: index() action is used to fetch data from database users table 

public function index()
{
$users = $this->User->find('all');
$this->set('users', $users);
}
View: app/View/Users/index.ctp
<h2>Users</h2>
<!-- link to add new users-->
<div class='pull-right'>
    <?php echo $this->Html->link( '+ New User', array( 'action' => 'add' ) ); ?>
</div> 
<table>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Username</th>
        <th>Email</th>
        <th>Actions</th>
    </tr>
<?php
    //loop to show all fetched records
    foreach( $users as $user ){
     
        echo "<tr>";
            echo "<td>{$user['User']['firstname']}</td>";
            echo "<td>{$user['User']['lastname']}</td>";
            echo "<td>{$user['User']['username']}</td>";
            echo "<td>{$user['User']['email']}</td>";            
            //here are the links to edit and delete actions
            echo "<td class='actions'>";
                echo $this->Html->link( 'Edit', array('action' => 'edit', $user['User']['id']) );
                echo $this->Form->postLink( 'Delete', array(
                        'action' => 'delete', 
                        $user['User']['id']), array(
                            'confirm'=>'Are you sure you want to delete that user?' ) );
            echo "</td>";
        echo "</tr>";
    }
?>    
</table>