For smart Primates & ROBOTS (oh and ALIENS ).

Friday, April 17, 2015

session destroyed after redirect in codeigniter

Problem:

Working CodeIgniter framework you can face the session problem. the problem is when you storing the values in session and redirect the page. then session destroyed automatically, it is loosing session data even you have properly loaded session library $this->load->library('session') in constructor.

see the below code:

public function myset() 
{
        $this->session->set_userdata('mydata', 'data');
        redirect('/', 'refresh');
}


function index()
{
          // loosing here data
          $mydata = $this->session->userdata('mydata');

}






Solution:

As we are seeing many new frameworks are coming today. but the Mother and base of all frameworks is Core PHP,  So we must have good knowledge about Core PHP. Here I have solved this session problem by Core PHP.

Example:

session_start();
public function myset() 
{
        $_SESSION['mydata']='data'
        redirect('/', 'refresh');
}


function index()
{      $mydata='';
        if(isset($_SESSION['mydata']) && !empty($_SESSION['mydata'])) {
                  $mydata= $_SESSION['mydata']);
        }

}

Share:

Wednesday, April 15, 2015

How to use multilanguage in CodeIgniter

Problem:

Suppose you want to use Italian language in CodeIgniter then how to do it?



Solution:

CodeIgniter provide a facility that you can store the predefined words in array in separate files. after that you can use it as per your requirements.

Example:

1- create a folder name "italian" under "application\language".
2- under this folder create a "italian_lang.php" file as below matter. change it's matter as per your requirements.
<?php
$lang['home_slide_1']        = "Rendi <span>unici</span> i tuoi parastinchi";
$lang['home_latuaidea_title']        = "La tua <br/>idea";
/// and many more....
?>
now your file is created, now the question is that how to use it?
4- in view where you want to write italian text at the top of file load this file as below method:
$this->lang->load('italian', 'italian');


<?php echo $this->lang->line('home_slide_1');?>
<?php echo $this->lang->line('home_latuaidea_title');?>


Share:

Friday, April 10, 2015

Run custom sql query in CakePHP 3.0

Problem:

How to Run custom sql query in CakePHP 3.0

Solution & Example:

File : src\Model\Table\ArticlesTable.php
<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Datasource\ConnectionManager;
class ArticlesTable extends Table
{
    var $conn;
    public function initialize(array $config) {
        $this->conn = ConnectionManager::get('default');
    }
    function get_all_users($id) {
        $stmt = $this->conn->prepare('SELECT * from users WHERE id>= :id');
        $stmt->bind( ['id' => $id], ['id' => 'integer']);
        $stmt->execute();
        return $stmt->fetchAll('assoc');
     } 
}
?>

File: src\Controller\ArticlesController.php
<?php
namespace App\Controller;

use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
//use MyClass\MyClass;
use MyLib\UtilClass;

 class ArticlesController extends AppController
 {
     public $helpers = array('Html', 'Form');
     public function index() {

    }
    public function showarticles(){
         $data = $this->Articles->get_all_users(3);
         $this->set('data',$data);
    }
}


File: src\Template\Articles\showarticles.ctp
<?php
foreach ($data as $row){
               echo '<br/>'.$row['username']. '-------' . $row['password'];
         }
?>









Share:

Thursday, April 09, 2015

Add new row dynamically in JTable

Problem:

Add new row dynamically in JTable
This is Java code allow to you add a new row in JTable.
when you press enter then a new row automatically inserted and you can make more entry.


Add new row dynamically in JTable









Solution & Example:

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
public class t1 extends JFrame {
DefaultTableModel model;
JTable table;
JScrollPane sc1;
public t1() {
super("Data Entry Form By Amit Gaur (amitt800@gmail.com)");
int i,j;
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
model = new DefaultTableModel();
table = new JTable(model);
model.addColumn("Name");
model.addColumn("ID");
model.addColumn("Salary");
model.addColumn("Jobs");
model.addRow(new Object[]{"","","",""});
table.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
model.addRow(new Object[]{"", "","",""}); } }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { } } );

sc1 = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); cp.add(sc1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,600);
setVisible(true);
}
public static void main(String[] ss) {
new t1();
}
}




Share:

Wednesday, April 08, 2015

How to create own custom class in cakephp 3.0

Problem:

How to use own custom class or library class in CakePHP 3.0
If you have own useful library and you want to use it in your CakePHP 3.0 MVC Framework then follow below steps.


Solution:

If you have good knowledge of Core PHP then It will be easy to create own custom class in CakePHP 3.0 and use it. follow below steps:

1# Create the folder "MyLib" at root of CakePHP 3.0 structure where bin,config,logs folders are showing. you can also create it in the "vendor" folder but I think we should not create in there.

2# Create "UtilClass.php" file in the "MyLib" folder.

3# And last use it in your controller with it's path.

Example:

1# Create the folder "MyLib" at root of cakephp 3.0 structure where bin,config,logs folders are showing.

2# Create "UtilClass.php" file in the "MyLib" folder with below code:
<?php
namespace MyLib; //it is important,it is folder name
class UtilClass
{
    public function show()
    {
        return 'I am from my custom class in cakephp 3.0';
    }
}
?>


3# Use is as below code in any controller:
<?php
use MyLib\UtilClass;
 class TransportersController extends AppController
 {
     public function index() {

    }

    public function showtransporter(){
      require_once(ROOT .DS. "MyLib" . DS . "UtilClass.php");
      $util_obj = new UtilClass();
      echo $util_obj->show();

  }
}
?>
Share:

Tuesday, April 07, 2015

Model in CakePHP 3.0

Problem:

CalePHP 3.0 is different than it previous versions. Lot of things removed. In new CakePHP 3.0  
How to use Model in CakePHP 3.0 using new ORM model

Solution:

See below example

Example:


Create ArticlesController.php controller in "src\Controller" folder
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
class ArticlesController extends AppController
{
     public function index() {

     }
    public function showarticles() {
        $data = $this->Articles->find();
        foreach ($data as $row){
          echo $row->title;
       }
    }
}

ArticlesTable.php in "src\Model\Table" folder
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class ArticlesTable extends Table
{

}
?>

Create Article.php in "src\Model\Entity" folder
<?php
// src/Model/Entity/Article.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Article extends Entity
{
       
}
?>






Share:

Saturday, April 04, 2015

custom query in cakePHP 3.0

Problem:

How to execute custom query in cakePHP

Solution:

Use ConnectionManager::get() and it's method newQuery() you can pass custom sql query

Example:


Change your database information in "config\app.php" file as below:

  'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'username' => 'root',
            'password' => '',
            'database' => 'petro_app',
            'encoding' => 'utf8',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,
        ],
        ],
    ],


At the top in php code file where you want to execute sql query access ConnectionManager class as below:

use Cake\Datasource\ConnectionManager;

In method run sql query as below:
File name HardSelectionController.php   with complete code


use Cake\Datasource\ConnectionManager;

class HardSelectionController extends AppController  {

    public function showhardselection() {
      $conn = ConnectionManager::get('default');
      $query = $conn->newQuery();
     $query->select('*')
                ->from('user_info');
                ->where(['active' => true]);
    foreach ($query as $row) {
         echo $row['u_login'];
    }
}
}
Share:

Form in CakePHP 3.0

Problem:

How to create Form in CakePHP 3.0

Solution:

To create form in CakePHP 3.0 you need to use $this->Form->create() and along with this also use
echo $this->Form->input(), $this->Form->label(), $this->Form->text(), $this->Form->button() and never forget that every for must close with $this->Form->end(array('')) method.


Example:

Create this view file  "showhardselection.ctp" under "src\Template\HardSelection" folder.
<?php
echo $this->Form->create('UserForm', array('url' => array(
                        'controller' => 'HardSelection',
                        'action' => 'showsubmitdata')));
echo $this->Form->input('email');
echo $this->Form->label('username', 'Your username');
echo $this->Form->text('username');
echo $this->Form->button('Submit');
echo $this->Form->end(array(''));
?>

Create this controller file "HardSelectionController.php" in"src\Controller" folder.
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;

class HardSelectionController extends AppController
 {
     public function index() {

    }
    public function showhardselection(){
       
    }
    public function showsubmitdata() {
        if($this->request->is('post')) {
            $email = $this->request->data['email'];
            $username = $this->request->data['username'];
            $this->set('email',$email);
            $this->set('username',$username);           
        }
    }
}

Create this view file  "showsubmitdata.ctp" under "src\Template\HardSelection" folder.
<?php
if(isset($email)) {
    echo 'user email:'.$email;   
}
if(isset($username)){
    echo '<br/>user name:'.$username;   
}
?>

Share:

Friday, April 03, 2015

How to change default controller in CakePHP 3.0

Problem:

How to change default controller in CakePHP 3.0. You know that default page of CakePHP 3.0 is Pages and it's action is display.

Solution:

To change default controller in CakePHP 3.0 open config.php which is located under "config" folder.
and change :

$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
TO
$routes->connect('/', ['controller' => 'Welcome', 'action' => 'index', 'home']);

Where Welcome is your created controller.

Share:

Thursday, April 02, 2015

Notice (8): Undefined variable in cakephp

Problem:

You can get the error message Notice (8): Undefined variable in CakePHP while passing variable value from Controller to View. How to overcome this error?




Solution:

If you mistakenly create a method in predefined Controller "PagesController.php" which is automatically created by default. So don't touch or use "PagesController.php". you need to create own Controller ans create method and pass variable.
In other clear wording "do not use PagesController.php file, create own controller class"

Example:

See below incorrect code:
File:    src\Controller\PagesController.php

<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;

class PagesController extends AppController
{
    public function display()
    {
        $path = func_get_args();

        $count = count($path);
        if (!$count) {
            return $this->redirect('/');
        }
        $page = $subpage = null;

        if (!empty($path[0])) {
            $page = $path[0];
        }
        if (!empty($path[1])) {
            $subpage = $path[1];
        }
        $this->set(compact('page', 'subpage'));

        try {
            $this->render(implode('/', $path));
        } catch (MissingTemplateException $e) {
            if (Configure::read('debug')) {
                throw $e;
            }
            throw new NotFoundException();
        }
    }
   
    public function myshow() {
      $this->set('color', 'pink');
    }
}

File: \src\Template\Pages\myshow.ctp
<?php
   echo $color;
?>


See below Correct code:
Create a new File BooksController
File:  src\Controller\BooksController.php

<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
class BooksController extends AppController
{    
      public function index()
    {

    }
    public function myshow() {
       $this->set('color','pink');
    }
}

Create a new file myshow.ctp
File: \src\Template\Books\myshow.ctp
<?php
   echo $color;
?>

So do not use PagesController.php file, create own controller class





Share:

Ads Inside Post

Powered by Blogger.

Archive