Magento 2 : Invalid Key. Please Refresh The Page as we create / login to account

I have installed LAMP (Stack) to my Ubuntu laptop and successfully installed Magento 2.x

So the problem occurred when I need to log in with the customer account at the front-site

I have error message “Magento 2 : Invalid Key. Please Refresh The Page”

so here is the solution I’ve done before

  1. Edit my php.ini files and increase php_value_max_input_vars to 75000 or higher.
  2. Restart my apache server
  3. Clear browse cache
  4. Try to login/create account again

Magento 2 Translation Templates Override/Replace

Create Custom Theme based on parent theme

Let’s say we will create a custom theme based on Magento/luma as parent. We have to create three required files to add custom theme in magento 2 under directory apps/design/frontend/Silumansupra/default

  • theme.xml
  • registration.php
  • composer.json

Magento 2 Custom Theme Configuration - SilumanSupra.com

So your app/design/frontend/Silumansupra/default/theme.xml

file should look something like this:

<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../lib/internal/Magento/Framework/Config/etc/theme.xsd">
  <title>Custom Silumansupra</title>
  <parent>Magento/luma</parent>
</theme>

Next, we have to create registration.php

<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
     <title>SilumanSupra Custom Theme</title> <!-- your theme's name -->
     <parent>Magento/luma</parent> <!-- the parent theme, in case your theme inherits from an existing theme -->
 </theme>

And now we create composer.json file

{
    "name": "silumansupra/custom",
    "description": "N/A",
    "require": {
        "php": "~5.5.0|~5.6.0|~7.0.0",
        "magento/theme-frontend-blank": "*",
        "magento/framework": "*"
    },
    "type": "magento2-theme",
    "version": "100.0.1",
    "license": [
        "OSL-3.0",
        "AFL-3.0"
    ],
    "autoload": {
        "files": [
            "registration.php"
        ]
    }
}
Change Configuration Theme on backoffice

Login to your backoffice/admin page and change theme configuration at Content – Configuration.

Magento 2 Custom Theme Configuration - SilumanSupra.com

Create transaction file

As we will override/replace string in Customer Login page, we have to create translation file under apps/design/frontend/Silumansupra/default/i18n

Create file en_US.csv under directory structure above.  We can create (or you can just copy paste from magento 2 default theme files). Here we will use en_US.csv file in vendor/magento/theme-frontend-luma/i18n/en_US.csv and replace some strings with our own.

For example, we will change String “Customer Login” to “Customer Login Custom” in login page.

"Customer Login","Customer Login Custom"

Magento 2 Custom Theme Configuration - SilumanSupra.com

You can cache:flushafter save and change translation files in editor and then refresh the page.

Reference:

  • https://devdocs.magento.com/guides/v2.4/frontend-dev-guide/translations/theme_dictionary.html
  • https://www.mageplaza.com/devdocs/how-to-create-magento-2-theme.html

Custom Server-Side Datatables With CodeIgniter

Untuk Datatable yang kita gunakan kali ini menggunakan Datatables Server Side dengan database MySQL.

Alasan menggunakan server-side processing adalah ketika menggunakan banyak sekali data (di atas 1000 baris) user tidak perlu menunggu semua data (baris) di proses di server dan ditampilkan ke view, dan mengakibatkan website kita terasa lambat.

Tutorial kali ini kita membahas tentang penggunaan server-side datatable dengan custom parameter.

Requirement

  • CodeIgniter 3.x
  • Bootstrap
  • JQuery
  • Datatables

Creating Table  and Datatable Function View

buat tabel di file views

<table class="table table-bordered table-hover" id="tabeldata">
        <thead class="thead-inverse">
         <tr>
          <th style="width: 50px">NO</th>
          <th>NAMA</th>
          <th>KOTA</th>
          <th>EMAIL</th>
          <th>TELP</th>
          <th>#</th>
         </tr>
        </thead>
        <tbody></tbody>
</table>

tabel kita beri atribut id=”tabeldata” yang nantinya digunakan sebagai selector pada js untuk menampilkan data dari database menggunakan AJAX JQuery.

Next, kita akan menggunaan fungsi untuk generate data dari database dengan AJAX JQuery

$('#tabeldata').DataTable({
      "destroy": "true",
      "processing": true,
      "serverSide": true,
      "order": [],
      "ordering": false,
      "responsive": true,
      "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "Semua"]],
      "language": {
       "infoFiltered": "",
       "processing": "<tr><td colspan='6' class='text-center'><i class='fa fa-spin fa-refresh'></i> Loading Data...</td></tr>"
      },
      "ajax": {
       "url": "<?= site_url() . "data/getdata" ?>",
       "type": "POST",
       "dataType": "json",
       tryCount: 0,
       retryLimit: 3,
       'data': function (data) {
        data.filter_kota = $("#filter-data").find("[name=val_filter_kota]").val();
       },
       "dataFilter": function (response) {
        return response;
       },
      },
     });

sebelumnya kita mendefinisikan data sebagai fungsi di sini:

'data': function (data) {
   data.filter_kota = $("#filter-data").find("[name=val_filter_kota]").val();
},

karena kita menambahkan custom parameter sebagai value untuk filter data dari database, maka kita perlu menambahkan <form> di atas tabel sebagai filter tambahan data.

<div class="row">
 <div class="col-lg-6">
   <form id="filter-data">
    <label class="label label-info small"><i class="fa fa-filter"></i> Filter Kota</label><br>
     <select class="form-control select-filter-kota">
      <option value="*"> Semua Kota</option>
      <option value="Malang"> Malang</option>
      <option value="Surabaya"> Surabaya</option>
      <option value="Jakarta"> Jakarta</option>
     </select>
     <input type="hidden" name="val_filter_kota">
   </form>
 </div>
</div>

untuk sementara ini, file view sudah selesai dan kita akan lanjutkan ke bagian Controller

Creating Controller

Buat file controller sesuai dengan request dari AJAX Datatables, Data.php dan fungsi getdata()

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Data extends CI_Controller {

 public function __construct() {
  parent::__construct();
  $this->load->model('m_data');
 }

function listData() {
  $list = $this->m_data->get_datatables();
  $data = array();
  $no   = $_POST['start'];
  $nos  = $no + 1;
  foreach ($list as $key => $val) {
   $id    = $val->id;
   $row   = [];
   $row[] = "<td>". $val->nama ."</td>";
   $row[] = "<td>". $val->kota ."</td>";
   $row[] = "<td>". $val->email ."</td>";
   $row[] = "<td>". $val->telp ."</td>";
   $row[] = "<td><a href='". site_url() ."detail/". $id ."'><i class='fa fa-search'></i> Detail</a></td>";
   );
   $data[] = $row;
  }
  $output = array(
    "draw"            => $_POST['draw'],
    "recordsTotal"    => $this->m_data->count_all_(),
    "recordsFiltered" => $this->m_data->count_filtered_(),
    "data"            => $data,
  );
  //output dalam format JSON
  echo json_encode($output);
 }

}

Pada file controllers/Data.php kita menginisiasi Model M_Data.php dan return value yang kita dapat diiterasi menggunakan foreach dan ditampung ke dalam variabel $data sebagai array(). Sedangkan untuk variabel $row sendiri merupakan array dari baris data yang akan kita lempar ke tabel di view sebelumnya.

Creating Models

Buat model dengan nama M_Data.php sesuai dengan nama yang kita inisiasi di controllers/Data.php tadi

<?php

class M_data extends CI_Model {

 public function __construct() {
  parent::__construct();
 }

 function get_datatables() {
  $this->select = "*";
  $sql          = $this->manualQuery($this->input->post(), true, true);
  $query        = $this->db->query($sql);
  return $query->result();
 }

 function manualQuery($params, $page = false, $filter = false) {
  $this->column_search = ['nama','email','telp'];
  $sql  = "SELECT * FROM `tabel_data` ";
  $filt = "";
  if ($filter) {
   if (!empty($params['param'])) {
    $flt  = "params = '" . $params['params'] . "' ";
    $filt .= (empty($filt) ? " " . $flt : " AND " . $flt);
   }

   if (!empty($params['search']['value'])) {
    $flt = " ";
    $flt .= " (";
    $e   = end($searchArr);
    foreach ($searchArr as $val) {
     $flt .= $val . " LIKE '%" . $params['search']['value'] . "%'";
     if ($val != $e) {
      $flt .= " OR ";
     }
    }
    $flt  .= ")";
    $filt .= (empty($filt) ? " " . $flt : " AND " . $flt);
   }

   $customFilter = "kota";
   if (!empty($params['filter_kota']) && $params['filter_kota'] !== "*") {
    $flt  = $customFilter . " = '" . $params['filter_kota'] . "' ";
    $filt .= (empty($filt) ? " " . $flt : " AND " . $flt);
   } 

   $filt = (empty($filt) ? "" : " WHERE " . $filt);
   $sql  .= $filt . " ";
  }
  if ($page && $params['length'] != "-1") {
   $sql .= " LIMIT " . $params['length'] . " OFFSET " . $params['start'];
  }

  return $sql;
 }

 function count_filtered_() {
  $sql = $this->manualQuery($this->input->post(), false, true);
  return count($this->db->query($sql)->result());
  // return $sql;
 }

 public function count_all_() {
  $this->select = " COUNT(0) as total ";
  $sql          = $this->manualQuery($this->input->post(), false, false);
  return count($this->db->query($sql)->result());
 }

}

All done.

Parameters?

Installing CodeIgniter Tutorial

So, kali ini saya coba mendokumentasikan caranya instalasi PHP Framework Codeigniter di tutorial ini.

Requirement

  • Webserver (Apache/Nginx). Mac/Windows bisa menggunakan XAMPP/Laragon, Linux bisa install dari repo atau LAMPP.
  • PHP 5.6+ (CodeIgniter 3)
    • Berdasarkan dokumentasi dari codeigniter.com versi stabil adalah CI v3
    • CodeIgniter 3.1.11 is the current version of the framework, intended for use with PHP 5.6+.There have been a number of refinements since version 2, notably with the database, session handling and encryption. Development of this version is ongoing.

Download

Download atau clone source/zip di

Setup The Code

  • Ekstrak zip file atau copy-paste ke htdocs (Apache/Xampp/Lampp) atau root directory webserver
  • Hit URL di localhost/{folder_mu}

Debugging Code

CodeIgniter 3.x
Create helper file inside application/helper

function debug($data) {
 echo "<pre>";
 print_r($data);
 echo "</pre>";
 exit;
}

Call it with $autoload[‘helper] in application/config/autoload.php

Use it with parameter debug($parameter)

Example:

 $data = array(
   "var1" => "variable #1", 
   "date" => date('Y-m-d H:i:s')
 );
 debug($data);

so you will get the view like this

Debugging in Codeigniter - Silumansupra.com

Progressing…

First, sudah lama saya tidak ‘berusaha’ untuk menuangkan ide dan keluh kesah di sebuah media digital. Kira-kira hampir 10 tahun semenjak selesai kuliah saya juga tidak pernah ingin menulis di blog (alamat lama: lumansupra.wordpress.com)

Akhir-akhir ini entah mengapa tiba-tiba muncul hasrat untuk menulis di halaman blog ini. Baik pas saat nyetir ke tempat kerja ataupun pulang kerja (karena waktu paling privasi menurut saya 😀 ) Continue reading “Progressing…”