POPUP home page disclaimer #
After you click the button a cookie will prevent it from appearing on the next page load. You can add to the address bar to reset and have the popup appear again: www.domain.com?clearCookie

CSS




/* Popup container */
.popup-container {
    display: none;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #f1f1f1;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    padding: 15px;
    box-sizing: border-box;
    animation: slide-up 0.5s ease-out;
    text-align: center;
}

/* Button to close the popup */
.close-button {
    background-color: #4962AA;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

/* Animation for sliding up */
@keyframes slide-up {
    from {
        transform: translateY(100%);
    }
    to {
        transform: translateY(0);
    }
}


                    

HTML




<div id="popup" class="popup-container">
Text goes here

    <button class="close-button" onclick="closePopup()">
        OK
    </button>


</div>

                    
                

Javascript




// Function to open the popup
function openPopup() {
    document.getElementById('popup').style.display = 'block';
}

// Function to close the popup
function closePopup() {
    document.getElementById('popup').style.display = 'none';
    document.cookie = 'popupClosed=true; expires=' + new Date(new Date().getTime() + 24 * 60 * 60 * 1000).toUTCString() + '; path=/';
}

function clearCookie() {
    // Set the 'popupClosed' cookie to expire in the past, effectively deleting it
    document.cookie = 'popupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}

if (document.cookie.indexOf('popupClosed=true') === -1) {
    setTimeout(function () {
        openPopup();
    }, 1000);
} else {
    // Show an alert if the cookie is set
    //alert('Popup already closed!');
}

<?php if (isset($_GET['clearCookie'])): ?>
    document.cookie = 'popupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';

    if (document.cookie.indexOf('popupClosed=true') === -1) {
    alert('Cookie is cleared')
    } else {
    alert('NO');
    }
<?php endif; ?>





                    
                
GIT remove .idea project files already pushed


                git rm -r --cached .idea
                git commit -am "Removed .idea"
                git push


                    
GIT RESET --hard


git log --oneline
git reset --hard commit_hash
git push --force

                    
Auth Change password field


//add new database field
ALTER TABLE `users` ADD `password_v4` VARCHAR(200) NOT NULL AFTER `password`;
ALTER TABLE `users` ADD `reset_token` VARCHAR(200) NOT NULL AFTER `password_v4`;
ALTER TABLE `users` ADD `user_type` VARCHAR(20) NOT NULL AFTER `reset_token`;

//change password to a new link - application.php
$authenticationService->loadIdentifier('Authentication.Password', [
    'fields' => [
        'username' => 'email',
        'password' => 'password_v4',
    ]
]);

//Users controller - RESET PASSWORD
$row->password_v4 = $passObj->hash($postData['new_password']);



//Users table - SAVE user password
$user->password_v4 = $password;
if ($this->save($user)) {

                    
HTML Link
$this->Html->link('Name', ['prefix' => 'Staff','controller' => '', 'action' => ''], ['class' => 'btn btn-primary', 'confirm' => '']);
PHP USORT

$default['field'] = 'votes';
$default['dir'] = 'DESC';
usort($status, function ($item1, $item2) use ($default) {
    $field = $default['field'];
    $dir = $default['dir'];
    if ($item1[$field] == $item2[$field]) return 0;
    if ($dir == 'ASC') {
        return $item1[$field] < $item2[$field] ? -1 : 1;
    } else {
        return $item1[$field] > $item2[$field] ? -1 : 1;
    }
});

                    
CakePHP 4 Contain with conditions #
$row = $this
    ->find()
    ->contain('ASSOCIATED_MODEL',  function(\Cake\ORM\Query $q) {
        return $q->where(['ASSOCIATED_MODEL.removed' => 0]);
    })
    ->contain('ANOTHER_ASSOCIATED_MODEL',  function(\Cake\ORM\Query $q) {
        return $q->where(['ANOTHER_ASSOCIATED_MODEL.removed' => 0]);
    })
    ->contain('ANOTHER_ASSOCIATED_MODEL.DEEPER_ASSOCIATED_MODEL',  function(\Cake\ORM\Query $q) {
        $q->order('id DESC');
        $q->limit(1);
        return $q;
    })
    ->where([
        'MODEL.id' => $id
    ])
->first();
                    
Offset Anchor for Fixed Header
<a class="anchor" id="top"></a>

                    

a.anchor {
    display: block;
    position: relative;
    top: -100px;
    visibility: hidden;
}

                    
Language Switching
$this->Html->link('English',
    ['language' => 'en'],
    ['class' => $this->Lang->getActiveClass('en')
]);
$this->Html->link('French',
    ['language' => 'fr'],
    ['class' => $this->Lang->getActiveClass('fr')]
);
$this->Html->link('Spanish',
    ['language' => 'es'],
    ['class' => $this->Lang->getActiveClass('es')]
);
$this->Html->link('Lang-not-set', array());
Auth
NOT logged in (Login) / Reset / AddUser / StaffPrefx / AdminPrefix
<?php if ($this->Auth->isLoggedIn()): ?>
LOGGED IN (<?php echo $this->Html->link('Logout', '/logout'); ?>)
<?php else: ?>
NOT logged in (<?php echo $this->Html->link('Login', '/login'); ?>)
<?php endif; ?>

<?php echo $this->Html->link('Reset', array('prefix' => false, 'controller' => 'Users', 'action' => 'beginReset')); ?>

<?php echo $this->Html->link('AddUser', array('prefix' => false, 'controller' => 'Users', 'action' => 'add')); ?>

<?php echo $this->Html->link('StaffPrefx', array(
'prefix' => 'Staff',
)); ?>

<?php echo $this->Html->link('AdminPrefix', array(
'prefix' => 'Admin',
)); ?>


                    
VUE - Axios POST
function postExample() {
        window.axios.defaults.headers.common['X-CSRF-TOKEN'] = "$csrf_token";

    console.log('formdata - submit form');
    console.log(this.formData);

    var objData = JSON.stringify(this.formData);

    console.log('objData');
    console.log(objData);
    let URL = "/SetupPages/get";
    axios.post(URL, objData).then(function (response) {
    console.log("response");
    console.log(response);
    if (response.data.STATUS == 200) {
    console.log();
    } else {
    console.log('Fail - something went wrong');
    }
    });
}
                    
AngularJS (deprecated) - HTTP POST


                        var xhttp = new XMLHttpRequest();

                        xhttp.open("POST", URL, true);
                        xhttp.setRequestHeader('x-csrf-token', '$csrf_token');
                        xhttp.onload = function(event);
                        ....
                    
VUE - Axios GET
function getExample() {
    console.log(URL);
    let URL = "/SetupPages/get";
    axios.get(URL).then(function (response) {
    console.log("response");
    console.log(response);
    if (response.data.STATUS == 200) {
        console.log();
    } else {
        console.log('Fail - something went wrong');
    }
    });
}
                    
JSON
function jsonName(){
    $jsonData = file_get_contents('php://input');
    if (empty($jsonData)) {
    $jsonData ='{"id":-1}';
    }

    $user_id = $this->getUserId();
    $res = $this->Models->function($user_id, $jsonData);

    $this->jsonHeaders( json_encode($res) );
}
                    
Transaction


    $errors = false;

    $connection = ConnectionManager::get('default');
    $connection->begin();

    if ($anyProblems) {
    $errors = true;
    }

    if ($errors) {
    $connection->rollback();
    } else {
    $connection->commit();
    }

                    
CSS Hide / show on Desktop / phone

@media screen and (max-width: 600px) {
    .hiddenDesktop {
        display: none;
    }
}

@media screen and (min-width: 600px) {
    .hiddenPhone {
        display: none;
    }
}
                    
VUEjs - Conditional classes
:class="{greyed: shipping.key === 'create'}"

                    
CakePHP 4 datepicker
$this->Form->text('date',['type' => 'date']); ?>
CakePHP4 - Table Locator
$object = $this->getTableLocator()->get('MODEL')->method();
CakePHP4 - Factor Locator
$object = FactoryLocator::get('Table')->get('MODEL')->method();
VUEjs - Dropdown


<label>Gender <small class=""red-font"">*</small></label>
<select id=""id"" v-model=""formData.inputname"" name=""formData.inputName"" class=""form-control"">
<option v-for=""(value, key) in dropdown"" :value=""key"">{{value}}</option>
</select>

                    
CakePHP4 - find LIST
$list = $this->MODEL->find('list', ['keyField' => 'id', 'valueField' => ('user_type')])->toArray();
CakePHP4 - JoinTable in Model
$this->belongsToMany('Users',
    ['joinTable' => 'rebate_dealers_users',
    'foreignKey' => 'rebate_dealer_id',
    'targetForeignKey' => 'user_id'
]);
                    
CakePHP4 - Add created / modified automatically

                        //add to initialize in model
                        $this->addBehavior('Timestamp');
                    
VUEjs - joinTable
<li ng-repeat="season in dealer.rebate_seasons" ng-if="season._joinData.visible_supplier">
CakePHP 4 - Find first
$user = $this->ind()->select('id')->where(['email' => $email])->first();
                    
CakePHP 4 - Delete link
echo $this->Html->link('Delete', ['prefix' =>'Manager', 'action' => 'delete', $each[ 'id' ]],['confirm' => 'Are You sure you want to delete']);?>
                    
CakePHP 4 - New layout
$this->viewBuilder()->setLayout("vue_layout"); // assign layout
                    
$this->viewBuilder()->disableAutoLayout(); // to disable layout
                    
Javascript - hide / add class
document.getElementById("results").setAttribute("style", "display: none;");
                    
document.getElementById("results").classList = "msg-success";
                    
CakePHP4 - Save data with entity
$data = json_decode($jsonData, true);
$dataEntity = $this->newEntity($data);
                    
VUEjs - Foreach
Object.entries(newThis.jobTitles).forEach(entry => {    const [key, value] = entry;    console.log('key');    console.log(key);    console.log('value');    console.log(value);    });

                    
CakePHP4 - Form Create
$this->Form->create(null, ['url' => ['language' => $this->Lang->get(), 'controller' => 'Users', 'action' => 'submitToUpdatecase']]); ?>
                    
public function addUser(){
$user = $this->Users->newEmptyEntity();
if ($this->request->is('post')) {
    $userData = $this->Users->patchEntity($user, $this->request->getData());
    // Edit: some of the entity properties are manually set at this point, e.g.
    $userData->group_id = 1;
    if ($this->Users->save($userData)) {
        $userData = json_encode($userData->toArray());
        $this->Flash->success('User Saved');
    }else{
        $this->Flash->error('Error not Saved');
    }
}// end of  post

                    
PHP - Render PDF #

Allows to render a PDF from a HTML page which contains various data you want your client to print. IMPORTANT: You MUST add IP verification or token authorization as the concept is insecure

//located in a prefix to ensure only validated users can initiate
public function download($id) {
    $setupCase = new SetupCase; //our setup case library
    $setupCase->createPdf(Router::url('/', true).'Users/download/'.$id.'?token=123', 'infoPdf.pdf');
}
                    
//This is located in our SetupCase library in a util class
var $dpi = 30;
var $factor = 1;
function setSize($width, $height) {
    $this->width_pixels = $width * (($this->dpi * $this->factor) + 0); //1 in = 96 px / add fine adjustments to the end
    $this->height_pixels = $height * (($this->dpi * $this->factor) + 0); //1 in = 96 px
}
function createPdf($url, $filename) {

    $this->setSize(8.5, 11);

    //dd($url);
    $cmd = "wkhtmltopdf "
    . " --dpi ".$this->dpi." --page-width ".$this->width_pixels." --page-height ".$this->height_pixels
    ." --margin-top 0 --margin-right 0 --margin-bottom 0 --margin-left 0 " . $url . " " . TMP.$filename;
    if (isset($_GET['debug'])) {
    dd($cmd); //used to debug and get the link for testing
    }
    exec($cmd);
    header("Content-type:application/pdf");
    header("Content-Disposition:attachment;filename=\"$filename\"");
    //Add more headers here
    readfile(TMP.$filename);
    exit;
}
                    
//this is located in an un-authenticated function call (without a prefix)

public function download($id) {

    //@todo add security here to ensure this view never get's displayed to the public (ip address / token etc)
    $this->viewBuilder()->setLayout('print'); //make sure you create a print layout

    //get your data you want to display in the view which will be saved as a pdf
    $info = $this->Users->find('all',[
    'conditions' => [],
    'contain' => ['Groups']
    ])->first()->toArray();

    $this->set(compact('info'));

}
                    
//templates/Users/download.php
    < h1>< ?= $info['name']; ?>
                        ......

                    
Cake Initial index/edit table

Controller

function index() {
    $cols = $this->MODEL->getSchema()->columns();
    $this->set('cols', $cols);

    $rows = $this->MODEL->find('all');
    $this->set(compact('rows'));
}//index

function edit($id=false) {

        $cols = $this->MODEL->getSchema()->columns();
        $this->set('cols', $cols);

        $row = $this->MODEL->newEmptyEntity();
        $postData = $this->request->getData();

        if (!empty($postData)) {
            $row = $this->MODEL->patchEntity($row, $postData);
            if ($this->MODEL->save($row)) {
                $this->Flash->success('Saved');
                if (in_array($row['cameFrom'], ['/', ''])) {
                    $this->redirect(['action' => 'index']);
                } else {
                    $this->redirect($row['cameFrom']);
                }
            } else {
                $this->Flash->error('Error saving');
            }
        } else {// end of  post
            if ($id === 'new') {
                //New - row entity will be used
            } else {
                $row = $this->MODEL->get($id);
            }
            $row->cameFrom = $this->referer();
        }
        $this->set('row', $row);
    }//edit

function delete($id = NULL) {
    if (!$id) {
        $this->Flash->error('Specify ID');
        $this->redirect(array('prefix'=>'Staff', 'action' => 'index'));
    }else {
        $entity = $this->MODEL->get($id);
        if ($this->MODEL->delete($entity)) {
            $this->Flash->success('Deleted '.$entity->name);
        } else {
            $this->Flash->error('Error cannot delete');
        }
        $this->redirect($this->referer());
    }
}//delete

View - index.php

<table class="table">
    <thead>
    <tr>
        <th>
            Actions
        </th>
        <?php foreach ($cols as $col): ?>
            <th>
                <?= $col; ?>
            </th>
        <?php endforeach; ?>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($rows as $row): ?>
        <tr>
            <th>
                <?= $this->Html->link('Edit', [
                    'action' => 'edit', $row['id']
                ], ['class' => 'btn btn-primary']); ?>
            </th>
            <?php foreach ($cols as $col): ?>
                <th>
                    <?= $row[$col]; ?>
                </th>
            <?php endforeach; ?>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

View - edit.php

<?= $this->Form->create($row, array(
    'novalidate' => true,
    //'type' => 'file' //uncomment if you want to upload files
)); ?>
<?= $this->Form->hidden('id'); ?>
<?= $this->Form->hidden('cameFrom'); ?>

<?php foreach ($cols as $col): ?>
    <?= $this->Form->control($col, ['class' => 'form-control']); ?>
<?php endforeach; ?>

<?= $this->Form->button('Save', ['class' => 'btn btn-primary']); ?>
<?= $this->Form->end(); ?>

OLD TO BE MOVED ABOVE

CodeBlock Description
Language
File Storage (Store files on your server)

Filename: cache (key_name: cache) Download
X
Object Storage (Store files in a database)

Filename: cache (key_name: cache) Download
X
Responsive Table HTML table adjusts to rows when on a mobile device. Desktop is a normal table view
Sticky div / Floating div A div will float (or stick to the top of the window) as the user scrolls.
VUE validation Validate a form with a simple validation object
VUE timed form submission Form input will only submit after the user stops typing for a few seconds
Auto pagination As the user scrolls to the bottom of the page, the system will automatically load the next page / set of results. Instead of manually pushing next / previous pages.
Digital Signage Template Basic template for digital signage. Title, subtitle, text cycling between slides which can be scheduled with a php array
Activity Monitor Tracks actions of users on predefined actions in a database for long term and ease of viewing
View-ActivityLog Test-addToLog
Drag and Drop Upload Drag and drop files on the screen to upload efficiently
Add-Files
Google Analytics GA4 Google Analytics
GoogleAnalytics
Export to CSV Export an array into a CSV file that is downloaded to your computer. Simply add to your controller a basic array of your prepared data. It will auto create the CSV and add headers to download to your computer
SetupCase::downloadCsv($rows, $filename, $columnsSort = false);
Render PDF
(COMING SOON...)
Render a PDF from a custom HTML view and export and save to your computer
JSON API Headers
(COMING SOON...)
Common function to always call the correct JSON headers when you are sending data between the front-end / back-end API
Read more with fade Show partial text with a fade out and link to reveal all Read more with fade
Code Blocks