Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[PHP - CAKEPHP 2.0] CodeSnippet

[PHP - CAKEPHP 2.0] CodeSnippet

Command Create Plugin Folder

At current CakePHP source code: type command


    Console/cake bake Plugin ABC // create Plugin name = ABC

Command Create Model Folder

At current CakePHP source code: type command


    Console/cake bake Model User // create Model name = User

Command Create Controller Folder

At current CakePHP source code: type command


    Console/cake bake Controller Users // create Controller name = Users

Command Create View Folder

At current CakePHP source code: type command


    Console/cake bake View Users // create View name = Users

Joins exmaple source code


   $join = array_merge($join, array());

  'joins' => array(
      array(
          'alias' => 'member',
          'table' => Environment::read('table_prefix') . 'members',
          'type' => 'INNER',
          'conditions' => array(
              'MembersPoint.member_id = member.id',
          ),
      ),
  ),

Update All (CodeSnippet)


  $this->MembersPush->updateAll(array(
        'MembersPush.pushed' => "\"" . $date . "\"",    // update
    ), array(
         'MembersPush.device_token' => $device,  // conditions
		 'MembersPush.push_history_id' => $push_history_id,
         'MembersPush.type' => $type,
    ));

Delete All (CodeSnippet)


    $obj_CustomerMobile = ClassRegistry::init('Customer.CustomerMobile');

	$obj_CustomerMobile->deleteAll(
		array(
			'CustomerMobile.customer_id' => $id
		),
		false
	);

Had any


function filter_student_class_duplicate_data($data) {

    $result = array();
    foreach ($data as &$v) {
        $conditions = array(
            'StudentClass.student_id' 	=> $v['student_id'],
            'StudentClass.school_id' 	=> $v['school_id'],
            'StudentClass.school_class_id' => $v['school_class_id'],
        );

        if (!$this->StudentClass->hasAny($conditions)) {
            $result[] = $v;
        }
    }
    return $result;
}

Save any fields


$this->MemberLoginMethod->id = $id;
$this->MemberLoginMethod->saveField('enabled',  !$enabled);

Select Duplicate - users (name, email)


SELECT
    id, school_id, COUNT(*)
FROM
    booster_school_languages
GROUP BY
    id, school_id
HAVING 
    COUNT(*) > 3

Status, Array


public $status = array(
		1 => 'Approved', 	// default
		0 => 'Rejected',	
		2 => 'Submit'
);
// get key array_search('Approved', $this->status);

Override belongto parent appmodel


public function __construct($id = false, $table = null, $ds = null) {
    $parent = get_parent_class($this);
    $this->_mergeVars(array('belongsTo'), $parent);// override belongto parent appmodel

    parent::__construct($id, $table, $ds);
}

ONE OR


$conditions = array(
    'OR' => array(
        array( 'MemberRole.school_id' 	=> array()),
        array( 'MemberRole.role_id' 	=> $role),
    );
);

MULTIPLE OR



$conditions = array();
if ($school_id) {
    if ($role) {

        $conditions = array(
            'OR' => array(
                array(
                    'MemberRole.school_id' 	=> array(),
                    'MemberRole.role_id' 	=> $role,
                ),
                array(
                    'MemberRole.school_id' 	=> array(),
                    'MemberRole.role_id' 	=>  Environment::read('role.register'),
                ),
                array(
                    'MemberRole.school_id' 	=> $school_id,
                    'MemberRole.role_id' 	=> Environment::read('role.register'),
                ),
                array(
                    'MemberRole.school_id' 	=> $school_id,
                    'MemberRole.role_id' 	=> $role
                ),
            ),
        );
        
    }  else {
        $conditions = array(
            'MemberRole.school_id' 	=> $school_id,
        );
    }

} else {

    if ($role) {
        $conditions['OR'] = array(
            array('MemberRole.role_id' => $role),
            array('MemberRole.role_id' => Environment::read('role.register')), 			// get register role 
        );
    }
}

return $this->find('list', array(
    'fields' => array(
        'MemberLanguage.member_id',
        'MemberLanguage.name', 
        'MemberLanguage.medal',
    ),
    'conditions' => $conditions,
    'joins' => array(
        array(
            'table' => Environment::read('table_prefix') . 'member_languages', 
            'alias' => 'MemberLanguage',
            'type' => 'INNER',
            'conditions'=> array(
                'MemberLanguage.member_id = MemberRole.member_id',
                'MemberLanguage.alias' => $language,
            )
        ),
    ),
));

FILTER SEARCH


$this->virtualFields['myField'] = "CONCAT(language.name, ' (', 
language.description,  ')' )";	// using this for use concat
		
return $this->find('list', array(
    'fields' => array(
        'ImageType.id', 
        'myField',
    ),
    'conditions' => array(
        'ImageType.slug LIKE' => $slug,
    ),
    'joins' => array(
        array(
            'table' => Environment::read('table_prefix') . 'image_type_languages', 
            'alias' => 'language',
            'type' => 'INNER',
            'conditions'=> array(
                'ImageType.id = language.image_type_id',
                'language.alias = \'' . $language . '\'',
            )
        ),
    ),
));

upload image REMEMBER FORM


Form->create('BuildingPost', array('role' => 'form', 'type' => 'file')); ?>

Working With TIME



if (isset($data_search["time_start"]) && !empty(trim($data_search["time_start"]))){
   $conditions['CAST(EventPost.time_start as TIME) >='] = $data_search["time_start"];
}

// convert time TO HH:MM (don't get second)
$this->virtualFields['myField'] = "CONCAT(language.title, ' (DATE: ', EventPost.date, ' | TIME: ', 
DATE_FORMAT(EventPost.time_start, \"%H:%i\"), ' -> ', DATE_FORMAT(EventPost.time_end, \"%H:%i\"), ')' )";	
// using this for use concat

// add hour for check time start, time end

if (isset($data_search["time_start"]) && !empty(trim($data_search["time_start"]))) {
    $conditions['TIME(MemberBookFacility.time) >= '] = $data_search["time_start"];
}

if (isset($data_search["time_end"]) && !empty(trim($data_search["time_end"]))) {
    $conditions['DATE_ADD(MemberBookFacility.time, INTERVAL 1 hour) <= '] = $data_search["time_end"];	
    // date('H:i', strtotime($data_search["time_end"]));
}

Group By within contain cakephp


// https://stackoverflow.com/questions/37386189/group-by-within-contain-cakephp
// we use distinct replace it
// DISTINCT
'MemberBookFacility' => array(
    'fields' => array(
        'DISTINCT MemberBookFacility.building_facility_id',
    ),
    'BuildingFacility' => array(
        'BuildingFacilityLanguage' => array(
            'conditions' => array(
                'BuildingFacilityLanguage.alias' => $language,
            ),
        ),
        'BuildingPost' => array(
            'BuildingPostLanguage' => array(
                'conditions' => array(
                    'BuildingPostLanguage.alias' => $language,
                ),
            ),
        ),
        'fields' => array(
            'BuildingFacility.*',
        ),
    ),
),

In mysql you can order by specific field values, by using ORDER BY FIELD:


SELECT * FROM city 
WHERE id IN (10, 1, 2)
ORDER BY FIELD(id, 10, 1, 2) DESC;

// output:
// order: first those with id = 10, those with id = 1, those with id = 2
// Do in cake
	'order' => array(
		'FIELD(City.id, 10, 1, 2)',
	),

// or
    'order' => array(
		'FIELD(City.id, 10, 1, 2) DESC',
	),

CKFINDER, CKEDITOR CONFIG


webroot/js/ckfinder/config.php
'baseUrl'      => '/js/ckfinder/userfiles/',

$config['authentication'] = function () {
    return true;    // true: for remove security of the browser
};

enabled CkEditor/ckfinder
webroor/js/ckeditor/config.js

if your DOMAIN is localhost: http://localhost/paragonasia-portal/ -> pls config
'/paragonasia-portal/webroot/js/ckfinder/ckfinder.html',

if your DOMAIN is: http://paragonasia-portal/ -> pls config
'/webroot/js/ckfinder/ckfinder.html',

// pls config below for discard missing controller, because of cakephp can access into wberoot/js
CKEDITOR.editorConfig = function( config ) {
	// Define changes to default configuration here. For example:
	// config.language = 'fr';
	// config.uiColor = '#AADC6E';

   config.filebrowserBrowseUrl      = '/paragonasia-portal/webroot/js/ckfinder/ckfinder.html',
   config.filebrowserImageBrowseUrl = 
   	'/paragonasia-portal/webroot/js/ckfinder/ckfinder.html?type=Images',
   config.filebrowserFlashBrowseUrl = 
   	'/paragonasia-portal/webroot/js/ckfinder/ckfinder.html?type=Flash',
   config.filebrowserUploadUrl      = 
   	'/paragonasia-portal/webroot/js/ckfinder/ckfinder/upload.php?type=files';
   config.filebrowserImageUploadUrl = 
   	'/paragonasia-portal/webroot/js/ckfinder/ckfinder/upload.php?type=images';
   config.filebrowserFlashUploadUrl = 
   	'/paragonasia-portal/webroot/js/ckfinder/ckfinder/upload.php?type=flash';
};

// show ckeditor when you wanna load. example in admin_add, admin_edit ctp
cα»₯ thể trong Plugin/Blog/View/admin_add.ctp, Plugin/Blog/View/admin_edit.ctp

Html->script('ckeditor/ckeditor.js?v=' . date('U'));
	echo $this->Html->script('ckfinder/ckfinder.js?v=' . date('U'));
?>

WORKING WITH DATE TIMES (MOMENTJS)

 $(document).ready(function() {

var currentYear = new Date().getFullYear();
var currentDate = new Date();
var firstDateOfCurrentMonth = moment().clone().startOf('month').format("YYYY-MM-DD");
var currentWeekNumber = moment(currentDate, 'DD-MM-YYYY').week();

// ----- year -----
$('#current_year').on('click', function() {
currentYear = new Date().getFullYear();
var from = currentYear + '0101';
var to = currentYear + '1231';

$('#date_from').val(moment(from).format("YYYY-MM-DD"));
$('#date_to').val(moment(to).format("YYYY-MM-DD"));
});

$('#previous_year').on('click', function() {
currentYear--;
var from = currentYear + '0101';
var to = currentYear + '1231';

$('#date_from').val(moment(from).format("YYYY-MM-DD"));
$('#date_to').val(moment(to).format("YYYY-MM-DD"));
});

$('#next_year').on('click', function() {
currentYear++;
var from = currentYear + '0101';
var to = currentYear + '1231';

$('#date_from').val(moment(from).format("YYYY-MM-DD"));
$('#date_to').val(moment(to).format("YYYY-MM-DD"));
});

// ----- month -----
$('#current_month').on('click', function() {

// get first day of current month
firstDateOfCurrentMonth = moment().clone().startOf('month').format("YYYY-MM-DD"); // moment().clone().startOf('month').format("YYYY-MM-DD");

var futureMonth = firstDateOfCurrentMonth;
var futureMonthEnd = moment(futureMonth).endOf('month').format("YYYY-MM-DD");

$('#date_from').val(futureMonth);
$('#date_to').val(futureMonthEnd);
});

$('#previous_month').on('click', function() {

var futureMonth = moment(firstDateOfCurrentMonth).add(-1, 'M').format("YYYY-MM-DD");
var futureMonthEnd = moment(futureMonth).endOf('month').format("YYYY-MM-DD");

$('#date_from').val(futureMonth);
$('#date_to').val(futureMonthEnd);

firstDateOfCurrentMonth = futureMonth;
});

$('#next_month').on('click', function() {
var futureMonth = moment(firstDateOfCurrentMonth).add(+1, 'M').format("YYYY-MM-DD");
var futureMonthEnd = moment(futureMonth).endOf('month').format("YYYY-MM-DD");

$('#date_from').val(futureMonth);
$('#date_to').val(futureMonthEnd);

firstDateOfCurrentMonth = futureMonth;
});

// ----- date -----
$('#current_date').on('click', function() {

// get first day of current date
currentDate = new Date();
var date = moment(currentDate).format("YYYY-MM-DD");

$('#date_from').val(date);
$('#date_to').val(date);
});

$('#previous_date').on('click', function() {
var date = moment(currentDate).subtract(1, 'days').format("YYYY-MM-DD");

$('#date_from').val(date);
$('#date_to').val(date);
currentDate = date;

});

$('#next_date').on('click', function() {
var date = moment(currentDate).add(1, 'days').format("YYYY-MM-DD");

$('#date_from').val(date);
$('#date_to').val(date);
currentDate = date;
});


// ----- week -----
$('#current_week').on('click', function() {
currentDate = new Date();
currentWeekNumber = moment(currentDate, 'DD-MM-YYYY').week();

startOfWeek = moment().day("Sunday").week(currentWeekNumber).format('YYYY-MM-DD');
endOfWeek = moment().day("Saturday").week(currentWeekNumber).format('YYYY-MM-DD');

// const startOfWeek = moment().clone().startOf('week').format('YYYY-MM-DD');
// const endOfWeek = moment().clone().endOf('week').format('YYYY-MM-DD');

$('#date_from').val( startOfWeek );
$('#date_to').val( endOfWeek );
});

$('#previous_week').on('click', function() {
currentWeekNumber --;

startOfWeek = moment().day("Sunday").week(currentWeekNumber).format('YYYY-MM-DD');
endOfWeek = moment().day("Saturday").week(currentWeekNumber).format('YYYY-MM-DD');
$('#date_from').val( startOfWeek );
$('#date_to').val( endOfWeek );

});

$('#next_week').on('click', function() {
currentWeekNumber ++;

startOfWeek = moment().day("Sunday").week(currentWeekNumber).format('YYYY-MM-DD');
endOfWeek = moment().day("Saturday").week(currentWeekNumber).format('YYYY-MM-DD');
$('#date_from').val( startOfWeek );
$('#date_to').val( endOfWeek );
});
});

 

 

 Zidane


πŸ™‡πŸΌ We Appreciate Your Comments and Suggestions - Webzone - all things Tech Tips web development πŸ™‡πŸΌ
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com