Create Dynamic Slug Using Codeigniter

Kailash Singh

Create Dynamic Slug Using Codeigniter

Published Apr 10,2022 by Kailash Singh

0 Comment     4042 Views    


In this tutorial, we are going to teach you. How to create dynamic slug in codeigniter.

Step 1: Create Controller and page all code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Create_dynamic_slug_using_codeigniter extends CI_Controller 
{
	public function index()
	{
		$data['heading'] = 'Create Dynamic Slug Using Codeigniter';
		$data['product_list'] = $this->db->select('*')
										 ->from('codeigniter_dynamic_slug')
										 ->get()
										 ->result_array();
		$this->load->view('product_list',$data);
	}

	public function add()
	{
		$data['heading'] = 'Create Dynamic Slug Using Codeigniter';

		$this->form_validation->set_rules('product_name', 'Product Name', "required");
		$this->form_validation->set_rules('product_url', 'Product URL', "required");
		$this->form_validation->set_rules('product_price', 'Product Price', 'trim|required|numeric|greater_than[0]');
		$this->form_validation->set_rules('product_description', 'Product Description', 'required');

		if ($this->form_validation->run() === TRUE) 
		{
			$urlExistCount = $this->db->select('*')->from('codeigniter_dynamic_slug')->where('url',$this->input->post('product_url'))->get()->num_rows();
			if($urlExistCount > 0)
			{
				$this->session->set_flashdata('error','Product url already exist. Please change the product!');	
				return redirect('create_dynamic_slug_using_codeigniter/add');
			}
			else
			{
				$data = array(
					'product_name' => $this->input->post('product_name'), 
					'url' => $this->input->post('product_url'), 
					'price' => $this->input->post('product_price'), 
					'description' => $this->input->post('product_description'), 
					'created_at' => date('Y-m-d H:i:s A')
				);
				$this->db->insert('codeigniter_dynamic_slug',$data);
				$this->session->set_flashdata('success','Product has been added succesfully');	
				return redirect('create_dynamic_slug_using_codeigniter');
			}

		}
		$this->load->view('add_product',$data);
	}


	public function edit()
	{
		$product_id = $this->uri->segment(3);
		$data['heading'] = 'Create Dynamic Slug Using Codeigniter';

		$this->form_validation->set_rules('product_name', 'Product Name', "required");
		$this->form_validation->set_rules('product_url', 'Product URL', "required");
		$this->form_validation->set_rules('product_price', 'Product Price', 'trim|required|numeric|greater_than[0]');
		$this->form_validation->set_rules('product_description', 'Product Description', 'required');

		if ($this->form_validation->run() === TRUE) 
		{

			$urlExistCount = $this->db->select('*')
								  ->from('codeigniter_dynamic_slug')
								  ->where(['url'=>$this->input->post('product_url'),'id <>' => $product_id])
								  ->get()
								  ->num_rows();
			if($urlExistCount > 0)
			{
				$this->session->set_flashdata('error','Product url already exist. Please change the product!');	
				return redirect('create_dynamic_slug_using_codeigniter/edit/'.$product_id);
			}
			else
			{
				$data = array(
					'product_name' => $this->input->post('product_name'), 
					'url' => $this->input->post('product_url'), 
					'price' => $this->input->post('product_price'), 
					'description' => $this->input->post('product_description'), 
				);
				$this->db->where('id',$product_id);
				$this->db->update('codeigniter_dynamic_slug',$data);
				$this->session->set_flashdata('success','Product has been updated succesfully');	
				return redirect('create_dynamic_slug_using_codeigniter');
			}
			
		}

		$data['product'] = $this->db->select('*')->from('codeigniter_dynamic_slug')->where('id',$product_id)->get()->row_array();
		$this->load->view('edit_product',$data);
	}

	public function view()
	{
		$url = $this->uri->segment(3);
		$data['heading'] = 'Create Dynamic Slug Using Codeigniter';
		$data['product'] = $this->db->select('*')->from('codeigniter_dynamic_slug')->where('url',$url)->get()->row_array();
		$this->load->view('view_product',$data);
	}

	public function create_seo_url() 
	{
	    $msg = array();
	   
	    $product_id = (int) $this->input->post('product_id');

	    $friendly_url = $this->input->post('friendly_url', TRUE);

	    $this->db->select('*');
	    $this->db->from('codeigniter_dynamic_slug');
	    $this->db->where('url', $friendly_url);

	    if ($product_id > 0) 
	    {
	      	$this->db->where('id !=', $product_id);
	    }

	    $query = $this->db->get();

	    if ($query->num_rows() > 0) 
	    {
			$msg['status'] = 1;
			$msg['msg'] = 'URL already exists';
	    } 
	    else 
	    {
			$msg['status'] = 0;
			$msg['msg'] = 'URL passed';
	    }
	    echo json_encode($msg);
	    exit();
 	}

}

 

Step 2: Create view page for product list.

<!DOCTYPE html>
<html lang="en">
<head>
  <title> <?php echo $heading; ?>- Elevenstech Web Tutorials</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <style type="text/css">
    @media screen and (min-width: 768px){
      .jumbotron {
          padding-top: 20px;
          padding-bottom: 20px;
      }
    }
  </style>
</head>
<body>

<div class="jumbotron text-center">
  <h3>Elevenstech Web Tutorials</h3>
  <h3><?php echo $heading; ?></h3> 
</div>
  
<div class="container">
    <div class="row">
      <div class="col-sm-10">
          <h3>Product List</h3>
      </div>
      <div class="col-sm-2" style="padding: 10px;">
          <a style="float: right;" href="<?php echo base_url(); ?>create_dynamic_slug_using_codeigniter/add" class="btn btn-primary">Add Product</a>
      </div>
    </div>
    <div class="row">
      <?php if(is_array($product_list)){ ?>
        <div class="col-sm-12">
          <?php if($success = $this->session->flashdata('success')){ ?>
            <div class="alert alert-success">
              <p><?php echo $success; ?></p>
            </div>
          <?php } ?>
          <table class="table table-bordered table-striped">
            <thead>
              <tr class="btn-primary">
                <th>S.No</th>
                <th>Product</th>
                <th>Price</th>
                <th width="30%">Description</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <?php $i = 1; foreach ($product_list as $product) { ?>
                <tr>
                  <td><?php echo $i; ?></td>
                  <td><?php echo $product['product_name']; ?></td>
                  <td>Rs. <?php echo $product['price']; ?></td>
                  <td><?php echo substr($product['description'],0,100); ?></td>
                  <td align="center" width="20%">
                    <a href="<?php echo base_url(); ?>create_dynamic_slug_using_codeigniter/edit/<?php echo $product['id']; ?>" class="btn btn-primary">Edit</a>

                    <a href="<?php echo base_url(); ?>create_dynamic_slug_using_codeigniter/view/<?php echo $product['url']; ?>" class="btn btn-warning">View</a>
                  </td>
                </tr>
              <?php $i++; } ?>
            </tbody>
          </table>
        </div>
      <?php }else{ ?> 
        <div class="col-sm-12" style="margin-top: 20px;">
          <div class="alert alert-success">
            <p>Products Not Available</p>
          </div>
        </div>
      <?php } ?>
  </div>
  
</div>

</body>
</html>

 

Step 3: Create add page for add product.

<!DOCTYPE html>
<html lang="en">
<head>
  <title> <?php echo $heading; ?> - Elevenstech Web Tutorials</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <style type="text/css">
    .card-box{
      margin: 10px 5px; border: 1px solid #ccc; border-radius: 3px;; padding: 10px 0px;
    }

    @media screen and (min-width: 768px){
      .jumbotron {
          padding-top: 20px;
          padding-bottom: 20px;
      }
    }

  </style>
</head>
<body>

<div class="jumbotron text-center">
  <h3>Elevenstech Web Tutorials</h3>
  <h3><?php echo $heading; ?></h3> 
</div>
  
<div class="container">
  <div class="row">

      <div class="col-sm-12">
        
        <form action="" method="POST">
          <div class="row">
            <div class="col-sm-12">
              <h3><strong>Add Product</strong></h3>
              <?php if($error = $this->session->flashdata('error')){ ?>
                <div class="alert alert-danger">
                  <p><?php echo $error; ?></p>
                </div>
              <?php } ?>
            </div>
            <div class="col-sm-4">
              <label>Product <label class="text-danger">*</label>:</label>
              <input type="text" name="product_name" class="form-control slug_generate" placeholder="Enter Product Name" value="<?php echo set_value('product_name'); ?>">
              <?php echo form_error('product_name','<p class="text-danger">','</p>'); ?>
            </div>
            <div class="col-sm-4">
              <label>Friendly Url (Slug) <label class="text-danger">*</label>:</label>
              <input type="text" name="product_url" id="url_slug" class="form-control" value="<?php echo set_value('product_name'); ?>" readonly>
              <p id="msg_response"></p>
              <?php echo form_error('product_url','<p class="text-danger">','</p>'); ?>
            </div>
            <div class="col-sm-4">
              <label>Price <label class="text-danger">*</label>:</label>
              <input type="text" name="product_price" class="form-control" placeholder="Enter Product Price" value="<?php echo set_value('product_price'); ?>">
              <?php echo form_error('product_price','<p class="text-danger">','</p>'); ?>
            </div>
          </div>
          <div class="row" style="margin-top: 20px;">
            <div class="col-sm-12">
              <label>Description <label class="text-danger">*</label>:</label>
              <textarea class="form-control" rows="6" name="product_description"><?php echo set_value('product_description'); ?></textarea>
              <?php echo form_error('product_description','<p class="text-danger">','</p>'); ?>
            </div>
          </div>
          <div class="row" style="margin-top: 20px;">
            <div class="col-sm-12">
              <button class="btn btn-primary" name="submit">Add Now</button> 
              <a href="<?php echo base_url(); ?>create_dynamic_slug_using_codeigniter" class="btn btn-danger">Back</a>
            </div>
          </div>
        </form>
      </div>

      
  </div>
 


</div>

<script type="text/javascript">
	$(document).ready(function(){

		$(".slug_generate").keyup(function(){

          var Text = $('.slug_generate').val();
          Text = Text.toLowerCase();
          url_string = Text.replace(/[^a-zA-Z0-9]+/g,'-');

         $.ajax({
              type: "POST",
              url: "<?php echo base_url(); ?>Create_dynamic_slug_using_codeigniter/create_seo_url",
              dataType: "json",
              data:{
                  friendly_url : url_string
              },
              success: function(response) 
              {
                  if(response.status == 0)
                  { 
                    $('#msg_response').html('<p class="text-success">'+response.msg+'</p>');
                  }
                  else{
                    $('#msg_response').html('<p class="text-danger">'+response.msg+'</p>')
                  }
              }
          });
          $("#url_slug").val(url_string);   
             
        });
        
	});
</script>

</body>
</html>

 

Step 4: Create edit page for update product.

<!DOCTYPE html>
<html lang="en">
<head>
  <title> <?php echo $heading; ?> - Elevenstech Web Tutorials</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <style type="text/css">
    .card-box{
      margin: 10px 5px; border: 1px solid #ccc; border-radius: 3px;; padding: 10px 0px;
    }

    @media screen and (min-width: 768px){
      .jumbotron {
          padding-top: 20px;
          padding-bottom: 20px;
      }
    }

  </style>
</head>
<body>

<div class="jumbotron text-center">
  <h3>Elevenstech Web Tutorials</h3>
  <h3><?php echo $heading; ?></h3> 
</div>
  
<div class="container">
  <div class="row">

      <div class="col-sm-12">
        
        <form action="" method="POST">
          <div class="row">
            <div class="col-sm-12">
              <h3><strong>Edit Product</strong></h3>
              <?php if($error = $this->session->flashdata('error')){ ?>
                <div class="alert alert-danger">
                  <p><?php echo $error; ?></p>
                </div>
              <?php } ?>
            </div>
            <div class="col-sm-4">
              <label>Product <label class="text-danger">*</label>:</label>
              <input type="text" name="product_name" class="form-control slug_generate" placeholder="Enter Product Name" value="<?php echo $product['product_name']; ?>">
              <?php echo form_error('product_name','<p class="text-danger">','</p>'); ?>
            </div>
            <div class="col-sm-4">
              <label>Friendly Url (Slug) <label class="text-danger">*</label>:</label>
              <input type="text" name="product_url" id="url_slug" class="form-control" value="<?php echo $product['url']; ?>" readonly>
              <p id="msg_response"></p>
              <?php echo form_error('product_url','<p class="text-danger">','</p>'); ?>
            </div>
            <div class="col-sm-4">
              <label>Price <label class="text-danger">*</label>:</label>
              <input type="text" name="product_price" class="form-control" placeholder="Enter Product Price" value="<?php echo $product['price']; ?>">
              <?php echo form_error('product_price','<p class="text-danger">','</p>'); ?>
            </div>
          </div>
          <div class="row" style="margin-top: 20px;">
            <div class="col-sm-12">
              <label>Description <label class="text-danger">*</label>:</label>
              <textarea class="form-control" rows="6" name="product_description"><?php echo $product['description']; ?></textarea>
              <?php echo form_error('product_description','<p class="text-danger">','</p>'); ?>
            </div>
          </div>
          <div class="row" style="margin-top: 20px;">
            <div class="col-sm-12">
              <button class="btn btn-primary" name="submit">Update Now</button> 
              <a href="<?php echo base_url(); ?>create_dynamic_slug_using_codeigniter" class="btn btn-danger">Back</a>
            </div>
          </div>
        </form>
      </div>

      
  </div>
 


</div>


<script type="text/javascript">
  $(document).ready(function(){

      $(".slug_generate").keyup(function() {
          var Text = $('.slug_generate').val();
          Text = Text.toLowerCase();
          Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');

          var url_string = Text;
          var product_id =  '<?php echo $this->uri->segment(3); ?>';
          $.ajax({
              type: "POST",
              url: "<?php echo base_url(); ?>Create_dynamic_slug_using_codeigniter/create_seo_url",
              dataType: "json",
              data:{
                  friendly_url : url_string,
                  product_id : product_id
              },
              success: function(response) 
              {
                  if(response.status == 0)
                  { 
                    $('#msg_response').html('<p class="text-success">'+response.msg+'</p>');
                  }
                  else{
                    $('#msg_response').html('<p class="text-danger">'+response.msg+'</p>')
                  }
              }
          });

          $("#url_slug").val(url_string);        
        });

  });
</script>
</body>
</html>

 

Step 5: Create view page for product view.

<!DOCTYPE html>
<html lang="en">
<head>
  <title> <?php echo $heading; ?> - Elevenstech Web Tutorials</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <style type="text/css">
    .card-box{
      margin: 10px 5px; border: 1px solid #ccc; border-radius: 3px;; padding: 10px 0px;
    }

    @media screen and (min-width: 768px){
      .jumbotron {
          padding-top: 20px;
          padding-bottom: 20px;
      }
    }

  </style>
</head>
<body>

<div class="jumbotron text-center">
  <h3>Elevenstech Web Tutorials</h3>
  <h3><?php echo $heading; ?></h3> 
</div>
  
<div class="container">
  <div class="row">

      <div class="col-sm-12">
        
        <form action="" method="POST">
          <div class="row">
            <div class="col-sm-12">
              <h3><strong>View Product</strong></h3>
            </div>
            <div class="col-sm-12">
              <p><b>Product Name : </b><?php echo $product['product_name']; ?></p>
              <p><b>Url : </b><?php echo $product['url']; ?></p>
              <p><b>Price : </b><?php echo $product['price']; ?></p>
              <p><b>Description : </b><?php echo $product['description']; ?></p>
            </div>
          </div>
    
          <div class="row" style="margin-top: 20px;">
            <div class="col-sm-12">
              <a href="<?php echo base_url(); ?>create_dynamic_slug_using_codeigniter" class="btn btn-danger">Back</a>
            </div>
          </div>
        </form>
      </div>

      
  </div>
 


</div>



</body>
</html>

 


Comments ( 0 )


SEARCH POST HERE

Support Us

Subscribe My YouTube Channel

Join Our Telegram Channel & Support Eachother

CATEGORIES

INTERVIEW QUESTIONS

PROJECT SOURCE CODE






POPULAR POSTS