How to save multiple row at once in cakephp

Cakephp

Posted on 18 Dec 15 by Vickey
  392

Some times we have a php array and we need to insert these value in a different row in a table for example I have an days array

$days=array('sunday','monday','tuesday');

and I want to insert these values in a different row with cakephp. For simple way i will use

foreach($days as $values)  {

	$data['Mymodel']['day']=$values;
	$this->Mymodel->create();
	$this->Mymodel->saveAll($data);
	
}

In this code each row insert with a different query but we do this at once in cakephp

foreach($days as $values)  {

     $data[]=array('day'=>$values);

}
$this->Mymodel->create();
$this->Mymodel->saveAll($data);

 

How to upload an image by using php curl request

php

Posted on 15 Dec 15 by Vickey
  1940

If you are facing problem to upload an image by using curl request you can use this code. In this code I convert an image in base64 string and pass it to a different server in a curl request and there I decode it and create an image file from this string.

here is my html form

<form method="post" id="SampleForm" action="">
	<input type="file" onchange="covertImageInBase64();" id="imageFile"/>
	<input type="text" name="image" id="image">
	<input type="submit" value="Submit">
</form>

and now convert the image in base64 string

function covertImageInBase64()
{
    var imageFile = document.getElementById("imageFile").files;
    if (imageFile.length > 0)
    {
        var imageFileUpload = imageFile[0];
        var readFile = new FileReader();
        readFile.onload = function(fileLoadedEvent) 
        {
            var base64image = document.getElementById("image");
            base64image.value = fileLoadedEvent.target.result;
        };
        readFile.readAsDataURL(imageFileUpload);
    }
}

now on submit the form send it in a curl request

if(isset($_POST['image'])){
	$curlUrl='localhost/curlfile.php';	
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL, $curlUrl);
	curl_setopt($ch,CURLOPT_POST, 1);
	curl_setopt($ch,CURLOPT_POSTFIELDS, 'image='.$_POST['image']);
	$result = curl_exec($ch);
	curl_close($ch);
}

In curlfile.php file change it into image

$base64Image=$_POST['image'];
$newImageName= time();
$getImageMimeType=substr($base64Image, 5, strpos($base64Image, ';')-5);
$imageTypeArray=array('image/png'=>'png','image/jpeg'=>'jpg','image/gif');
$imgExt=$imageTypeArray[$getImageMimeType];
$newImageName=$newImageName.'.'.$imgExt;
list($type, $base64Image) = explode(';', $base64Image);
list(, $base64Image)      = explode(',', $base64Image);
$base64Image = base64_decode($base64Image);
file_put_contents('path to your directory'.$newImageName, $base64Image);
echo $avatar=$newImageName;

 

How to calculate driving distance between two address

Js

Posted on 10 Dec 15 by Vickey
  1700

By using google api we can calculate driving or highway distance which is connecting  two address or in other word we can find the distance between two address for travel

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>
<script>
getDistance('city1','city2');
function getDistance(addressA, addressB)
{
    if (addressA == "" || addressB == "") {
        return false;
    }

    var origin = addressA;
    var destination = addressB;
    service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false
    },
    callback 
    );
}
function callback(result, status) {

	if (status == "OK") {
		if (result.destinationAddresses[0] == "") {
		    alert("Address first  not found");
		    return false;
		}
		if (result.originAddresses[0] == "") {
		    alert("Address second not found");
		    return false;
		}
		var distanceInKM = result.rows[0].elements[0].distance.text;
		var distanceInMiles = parseInt(distanceInKM) * .6214;
		alert(distanceInMiles);
	}
}
</script>

 

How to submit a form without refresh page

Jquery

Posted on 03 Dec 15 by Vickey
  882

By using jquery we can submit a form without refresh the page.Here is a sample code

File form.html

<script src="jquery.js"></script> 
<form id="contactForm" action="contact.php" method="post"> 
    Name: <input type="text" name="name" />
	Email: <input type="text" name="email" />	
    Message: <textarea name="message"></textarea> 
    <input type="submit" value="Contact Us" /> 
</form>

<script>
   $('#contactForm').submit(function() {
	var getFormData=$('#contactForm').serialize();
	$.post('form.php',getFormData  ,function (response){
		alert(response);
	})
	return false;
});
</script>

File form.php

<?php

	print_r($_POST);

?>

 

Bind and contain in cakephp

Cakephp

Posted on 26 Nov 15 by Vickey
  355

In cakephp we can assoceate models together for example I have a tables ‘users’,’posts’,’cources’,’jobs’ and their respecting models ‘ User’,’Post’,’Cource’,’Job’ . One user can have many posts,cources and jobs so I create assoceation between these

class User extends AppModel {
    public $hasMany = array(
    
        'Post' => array(
            'className' => 'Post',
            'foreignKey' => 'user_id',
        ),
        
       'Cource' => array(
            'className' => 'Cource',
            'foreignKey' => 'user_id',
        ),

        'Job' => array(
            'className' => 'Job',
            'foreignKey' => 'user_id',
        ),
    );
    
}

If I do not assoceate these in model  I can assoceate these on the fly in my controller

$this -> User -> bindModel(array(
'hasMany' => array(
    'Post' => array(
        'foreignKey' => 'user_id', 
    ),
    'Cource' => array(
        'foreignKey' => 'user_id', 
    ),
    'Job' => array(
        'foreignKey' => 'user_id', 
    ),

)));
$this->User->find(‘first’,array(‘conditions’=>array(‘User.id’=>1)));

But if I have this assoceation in Model then it will automatically work every where when data User data will be fetch

$this->User->find(‘first’,array(‘conditions’=>array(‘User.id’=>1)));

 

For example I need to retrive user data with his jobs then I use above query it will fetch all assoceated data ‘Post’,’Job’ and ’Cource’ and there is no need others data. So here I can use containable behaviorcontainable behavior to filter my result

$this->User->Behaviors->load('Containable');

$this->User->contain(Job);

$this->User->find(‘first’,array(‘conditions’=>array(‘User.id’=>1)));

We can do this by unbind also

How to use cakephp without a database

Cakephp

Posted on 25 Nov 15 by Vickey
  818

When we install cakephp in starting we see databse error on the home page.For complete installation we add our database details in cakephp\app\Config \database.php file

class DATABASE_CONFIG {

	public $default = array(
		'datasource' => 'Database/Mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'root',
		'password' => 'password',
		'database' => 'my_db',
		'prefix' => '',
		//'encoding' => 'utf8',
	);

	public $test = array(
		'datasource' => 'Database/Mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'user',
		'password' => 'password',
		'database' => 'test_database_name',
		'prefix' => '',
		//'encoding' => 'utf8',
	);
}

But because of some reason if you do not want to use any database in your website then you can do this by these below steps

1.Create 'DummyDatabase.php' file under 'cakephp\app\Model\Datasource' directory and addthe below code in this file

connected = true;
        return $this->connected;
    }

    function disconnect() {
        $this->connected = false;
        return !$this->connected;
    }

    function isConnected() {

        return true;
    }

}
?>

2.Now open your database file 'cakephp\app\Config\database.php' and replace code from 'datasource' => 'Database/Mysql' to 'datasource' => 'DummyDatabase'.

Now you can use cakephp app without a databse

Auth Allow access an action without authonticate in cakephp

Cakephp

Posted on 24 Nov 15 by Vickey
  363

In cakephp if we are using Auth component then we can not access any action without authonticate but if we need we can allow access any action by using
'allow' method.For example if i am not logedin and i want login then i need to access my login function but because of Auth componenet i can not access this then i can use the below code in my controller

public function beforeFilter() 
{
	parent::beforeFilter();
	$this->Auth->allow('login');
}

 

How to load models in cakephp controller

Cakephp

Posted on 19 Nov 15 by Vickey
  1377

In we are using correct naming convention in cakephp then the corresponding model automatically load. But if we are using more then one models in same controller then we need to load each model. We have two method to load the model

1. Load model where we need it

$this->loadModel('User');
$getUser	=	$this->User->find('all')

2. Load all models at once

public $uses	=array('Model1','Model2');

in the last method there is no need to load model every time

How to use admin routing in cakephp

Cakephp

Posted on 19 Nov 15 by Vickey
  339

For useing admin routing go to your config/core.php file and add the below line 

Configure::write('Routing.prefixes', array('admin'));

now create your function by using prefix 'admin'

class UsersController extends AppController {

	public function admin_add() {

	}


	public function admin_view() {

	}

}

and now you can access these function with these url

localhost/cakeapp/admin/users/add

localhost/cakeapp/admin/users/view

 

How to show flash messages in cakephp

Cakephp

Posted on 17 Nov 15 by Vickey
  423

In every website we need to show success and failure messages. For example on login page or on sign up page we show some success or failure messages.Cakephp provide us  'setFlash' method.By using the 'setFlash' we can set messages in Controllers and can show these messages on our views

Set message in controller

$this->Session->setFlash(__('Please, try again.'));

Show on ctp file

<?php echo $this->Session->flash(); ?>

In some cases we need to give some class or name to a flash message so that we can give some css style to this message text

$this->Session->setFlash(__('Whoops! Please try again.', null), 'default', array('class' => 'error'));

We can set flash message by giving a different name

$this->Session->setFlash(__('Invalid username or password, Please try again.', null),  'default', array('class' => 'error'),'loginMessage');
<?php echo $this->Session->flash('loginMessage'); ?>

 

www.000webhost.com