Tuesday, January 22, 2013

A find condition about hasMany(has many) relationship in cakephp

Suppose you have two model User and UserRole.
And User has many UserRole.
Now you want to find User By specific UserRole.

User:
Fields: id, name, others........
var $hasMany = array(
    "UserRole"
);

UserRole:
Fields: id, user_id, role_id, others...var 
$belongsTo = array("User");

First you need to find all UserRole by your own conditions:

$userRoles = $this->UserRole->find("all", array(
    "conditions" => array(
        "UserRole.condition" => $value
    )
));

Now find User by UserRole as follows:

$users = $this->User->find("all", array(
    "conditions" => array(
        "User.id" => Set::extract("/UserRole/user_id", $userRoles)
    )
));


BINGO...

Monday, January 21, 2013

stop a page from exit or unload using jquery

<html>
<head>
<title>Refresh a page in jQuery</title>
 
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
 
</head>
 
<body>
 
<h1>Stop a page from exit with jQuery</h1>
 
<button id="reload">Refresh a Page in jQuery</button>
 
<script type="text/javascript">
 
 $('#reload').click(function() {
 
   location.reload();
 
 });
 
 $(window).bind('beforeunload', function(){
  return 'Are you sure want to leaving?';
 });
 
</script>
 
</body>
</html>

convert string to input stream(InputStream) using java

package com.pritom;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class StringToInputStreamExample {
    public static void main(String[] args) throws IOException {
    String str = "This is a String to InputStream";
 
    // convert String into InputStream
    InputStream is = new ByteArrayInputStream(str.getBytes());
 
    // read it with BufferedReader
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
 
    String line;
    while ((line = br.readLine()) != null) {
       System.out.println(line);
    }
 
    br.close();
   }
}

Friday, January 18, 2013

Cakephp delete and update records by conditions

Delete Records:
$this->ModelName->deleteAll(
    array(
        "ModelName.id" => 10
    )
);

Update Records:
$this->ModelName->updateAll(
    /* UPDATE FIELD */
    array(
        "ModelName.is_active" => 0,
    ),
    /* CONDITIONS */
    array(
        "ModelName.id" => 20,
        "ModelName.name LIKE" => '%SEARCH_TEXT%',
        "ModelName.name <>" => 'NOT_EQUAL_VALUE',
        'ModelName.integer_field > ' => 50, [Can use operand here]
        'TIMESTAMPDIFF(DAY, ModelName.date, NOW())' => 22 [number of day]
    )
);

jQuery post call using ajax

jQuery.ajax({
    type: "POST",
    url: "http://domain.com/save_form_data",
    data: jQuery("form").serializeArray(),
    success: function(data) {
        console.log(data);
        alert("Success");
    },
    error: function() {
       alert("Error occurred."); 
    }
});

Wednesday, January 16, 2013

CKEDITOR instances and operations by jQuery

 var id = "CKEDITOR_100";

/* Get CKEDITOR */
var editor = CKEDITOR.instances[id];

/* Set data to CKEDITOR */
editor.setData("The Content");

/* Update CKEDITOR content */
try {
    for (var i in CKEDITOR.instances) {
        if (CKEDITOR.instances[i]) {
            CKEDITOR.instances[i].updateElement();
        }
    }
} catch (ex) {

}

/* Destroy CKEDITOR */
editor.destroy();

jsFiddle example of CKEDITOR instance update content

Thursday, January 3, 2013

Jquery call function, name taken from a string

Get function name from a string.
var formcheck = "function_name";
if (typeof window[formcheck] === 'function'){
    formok = window[formcheck]();
    e.preventDefault();
}

function function_name(){
    alert("Checked");
    return false;
}

Tuesday, January 1, 2013

PHP filter with preg_replace allow only letters and some other characters

Only receive - letters, numbers, spaces
$str = preg_replace("/[^A-Za-z0-9 ]/","",$str);
$str = preg_replace("/[^A-Za-z0-9\s]/","",$str);
$str = preg_replace("/[^A-Za-z0-9[:space:]]/","",$str);
$str = preg_replace("/([^a-z0-9A-Z[:space:]\'\"\?\!\,\.\-\:\~]+)/", "", $str]);
$str = preg_replace("/([--]+)/", "-", $str); 
 
$str = preg_replace("/<\/address>\r\n/e", "'</address>'", $str); 
When using the /e modifier in preg_replace, you have to pass a string of code to 
be evaluated as the replacement parameter, not an already-evaluated expression.
 
$str = preg_replace("/<\/address>[[:space:]]*?<address/e", "'</address><address'", $str); 
 
 
 

Round to a certain number of places using jQuery

For rounding decimals you can use the built-in JavaScript methods toFixed or toPrecision.
var num = 10;
var result = num.toFixed(2); // result will equal 10.00

num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2

num = 5000.2349;
result = num.toPrecision(4); // result will equal 5000

num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2