Skip to content

Blog Công Nghệ

MENUMENU
  • Trang chủ
  • Giới Thiệu
  • Lập Trình
    • Lập Trình Website
      • Laravel
        • Phân Tích Dự Án
      • PHP
      • SQL
      • HTML
      • CSS
      • Javascipt
      • My Project
      • Wordpress
    • Luyện Skill
    • Lập trình winform
    • CSDL
    • Lập Trình Android
    • Trí tuệ nhân tạo
    • Khai Khoáng Dữ Liệu
    • Arduino
    • Khác
    • Đồ án
  • Phần Mềm
    • Powerpoint
    • Tool
  • Cuộc sống và Giải trí
    • Hợp âm
    • web5ngay - youtube
    • Công Giáo
    • Kỹ Năng Sống
    • Street Workout
  • Danh sách bài viết
  • Guide line
    • Guild line phỏng vấn
    • Guide lines Laravel
    • Guide line Module Frontend
  • Tóm tắt sách
  • Fanpage

Blog Công Nghệ

Nơi chia sẻ kiến thức

Kinh nghiệm OpenCart

19 Tháng Ba, 2021 by admin
Lượt xem: 46

Trang chủ: opencart

Trang download các phiên bản của opencart: https://opencart.tips/

Opencart là một hệ thống quản lý thông tin (content management system – CMS) có mã nguồn mở. Chúng được thiết kế đặc biệt dành riêng cho các website kinh doanh trong lĩnh vực thương mại điện tử, thông qua cấu trúc ngôn ngữ lập trình PHP kết hợp với mô hình MVC (L).

Contents

  • 1. Cài đặt OpenCart
    • 1.1 Tạo CSDL
    • 1.2 Cài đặt Opencart
    • 1.3 Cài OpenCart Tiếng Việt (có thể bỏ qua)
      • Bước 1 :
      • Bước 2:
      • Bước 3:
      • Bước 4:
  • 2. Các nguồn bài viết tham khảo:
  • 3. Enable Twig
  • 4. Tạo một module mới
    • 4.1 Tạo file Controller
    • 4.2 Tạo file language
    • 4.3 Tạo file view
    • 4.4 Kích hoạt module
  • 5. Controller
    • 5.1. Tạo mới (CRUD – Create)
    • 5.2. Cập nhật (CRUD – Update)
    • 5.3. Xóa (CRUD – Delete)
  • 6. View CRUD
  • 7. Model
    • 7.1 Get all
    • 7.2 Get by id
    • 7.3 Insert
    • 7.4 Update
    • 7.5 Delete
    • 7.6 Lấy giá trị của query trả về
  • 8. Cách đặt tên
  • 9. Lấy các ngày của tháng
  • 10. Twig
    • 10.1 Echo
    • 10.2 For
    • 10.3 If else
    • 10.4 Tạo biến, gán giá trị
    • 10.4 Lấy chiều dài mảng
    • 10.5 Kiểm tra tồn tại – giống isset
    • 10.5 Format number
    • 10.6 Include
    • 10.7 Ghi chú
    • 10.8 Truy xuất phần tử của mảng, đối tượng
    • 10.9 Sắp xếp mảng
    • 10.10 utf8
    • 10.11 Date
    • 10.12 Debug – giống print_r
    • 10.13 Macro – giống function tái sử dụng
  • 11. Lỗi thiếu mCrypt khi cài đặt
  • 12. vqmod
    • 12.1 Cài vqmod
    • 12.2 Cấu trúc vqmod
    • 12.3 Viết vqmod
    • 12.4 Controller vqmod
    • 12.5 View vqmod
    • 12.6 Model vqmod

1. Cài đặt OpenCart

1.1 Tạo CSDL

Các bạn truy cập vào PhpMyadmin để tạo 1 Database rỗng. Link: http://localhost/phpmyadmin

1.2 Cài đặt Opencart

– Các bạn giải nén mã nguồn Opencart vào copy thư mục upload vào thư mục htdocs của Xampp. Bạn đổi tên thư mục upload thành tên mà bạn muốn nhé.

– Tiếp theo, các bạn chạy đường dẫn: http://localhost/thu_muc_chua_opencart

Hướng Dẫn Cài Đặt Opencart Trên Localhost

– Các bạn bấm Continue để chuyển sang bước tiếp theo:

Hướng dẫn cài đặt Opencart trên Localhost

Chuyển sang bước này, các bạn sẽ gặp 1 số lỗi. Các bạn cần phải thực hiện những công việc sau:

– Đổi tên file config-dist.php trong thư mục gốc và thư mục admin thành config.php
– Bật cURL trên Xampp: Các bạn mở file xampp/php/php.ini. Tìm dòng ;extension=php_curl.dll, các bạn bỏ dấu ; lưu lại. Sau đó các bạn restart lại Apache

Sau khi làm xong các công việc trên, các bạn F5 lại trang xem có còn thông báo lỗi gì không. Nếu không còn lỗi gì các bạn bấm Continue để chuyển qua bước tiếp theo.

Ps: Các bạn đừng quan tâm đến cái lỗi Magic Quotes GPC

Hướng Dẫn Cài Đặt Opencart trên Localhost

Tại bước này, các bạn nhập những thông tin của server, tài khoản, mật khẩu của người quản trị

– Database Driver: MySQLi (Nên chọn MySQLi, ở các phiên bản PHP cao sẽ bị lỗi nếu chọn MySQL)

– Database Host: localhost

– User: root (Mặc định trên xampp)

– Password: Để trống (Mặc định trên xampp)

– Database Name: Nhập vào tên CSDL lúc các bạn tạo trong PhpMyadmin

– Database Prefix: Nhập tiền tố của các bảng trong CSDL

Thông tin tài khoản, mật khẩu, email người quản trị (Phải nhớ để đăng nhập vào trang quản trị)

Sau khi đã nhập đầy đủ các thông tin, các bạn bấm Continue để cài đặt và chuyển qua bước tiếp theo

Hướng dẫn cài đặt Opencart trên Localhost

– Tại bước này, hệ thống yêu cầu các bạn xóa thư mục cài đặt trong mã nguồn (Chính là thư mục install)

Như vậy là chúng ta đã cài đặt xong Opencart trên Localhost.

Nếu các bạn vào trang chủ của website Opencart bạn vừa cài mà xuất hiện lỗi:

Notice: Trying to get property of non-object in E:\xampp\htdocs\opencart\index.php on line 50
Notice: Trying to get property of non-object in E:\xampp\htdocs\opencart\index.php on line 59
Warning: Invalid argument supplied for foreach() in E:\xampp\htdocs\opencart\index.php on line 59
Notice: Trying to get property of non-object in E:\xampp\htdocs\opencart\index.php on line 67

Lỗi này là do bạn cài đặt trên server chạy phiên bản PHP thấp hơn 5.3 mà bạn chọn kiểu kết nối MySQLi.

Các bạn khắc phục lỗi này như  sau:

Các bạn mở file config.php trong thư mục gốc và thư mục admin, tìm dòng:

define('DB_DRIVER', 'mysqli');

Thay bằng:

define('DB_DRIVER', 'mysql');

Nguồn: https://hoangan.net/huong-dan-cai-dat-opencart-tren-localhost.html

1.3 Cài OpenCart Tiếng Việt (có thể bỏ qua)

Bước 1 :

Copy các file trong thư mục upload và up lên thư mục gốc trên website của bạn

Bước 2:

Vào System/Localisation/Languages/ chọn Insert để thêm ngôn ngữ. Điền vào các thông tin sau:

Cài đặt tiếng Việt cho Opencart 2.x

Cài đặt tiếng Việt cho Opencart 2.x

– Language Name: vietnamese
– Code: vi
– Locale: vi_VN.UTF-8,vi_VN,vi-vn,vietnamese
– Image: vn.png
– Directory: vietnamese
– Filename: vietnamese
– Status: Enabled
Sau đó save lại.

Bước 3:

Vào Settings chọn tab Local sửa:
Language: là ngôn ngữ của shop -> các bạn chọn Vietnamese.
Administration Language: là ngôn ngữ trang quản trị -> các bạn chọn Vietnamese.

Bước 4:

Xem thành quả của mình

Nguồn: https://opencart84.com/cai-dat-tieng-viet-cho-opencart.html

2. Các nguồn bài viết tham khảo:

  • Bài 01: Opencart là gì? Tìm hiểu Opencart Development

  • Bài 02: Cấu trúc thư mục và mô hình MVC(L) trong Opencart

  • Website: Hoàng Web
  • Creating a Custom Page in OpenCart 3 – categories listing page

3. Enable Twig

Bạn cố gắng sửa file twig nhưng nó không thay đổi. Mình đã mất rất nhiều thời gian cho vấn đề này khi mới học. Bạn hãy bật cho phép chỉnh sửa twig lên.

Bạn đăng nhập vào admin => Nút cài đặt màu xanh bên phải

Bật On hết các giá trị

4. Tạo một module mới

Trong thư mục admin:

4.1 Tạo file Controller

Bạn tạo file mới:

  • trong đường dẫn controller/extension/module
  • tên file tùy ý, nhưng nên gợi nhớ. Ví dụ mình tạo file phongban.php
  • Nội dung file, bạn copy bên dưới vào
<?php
class ControllerExtensionModulePhongban extends Controller
{
	//controller
	public function index() {

	
		$this->load->language('extension/module/phongban');
	    $this->document->setTitle($this->language->get('meta_title'));
	
	    $data['column_left'] = $this->load->controller('common/column_left');
	    $data['column_right'] = $this->load->controller('common/column_right');
	    $data['content_top'] = $this->load->controller('common/content_top');
	    $data['content_bottom'] = $this->load->controller('common/content_bottom');
	    $data['footer'] = $this->load->controller('common/footer');
	    $data['header'] = $this->load->controller('common/header');
	    $data['meta_title'] = $this->language->get('meta_title');
	    $data['text_confirm'] = $this->language->get('text_confirm');

		
		$this->response->setOutput($this->load->view('extension/module/phongban', $data));
   
	}


	//====================================================================
	//model
	
}

?>

Lưu ý sửa file: Bạn copy và sửa những nội dung sau:

  • Dòng 2: bạn thay thành tên file của bạn Viết hoa chữ cái đầu.
    ControllerExtensionModule………..
    Mình đặt tên file phongban.php => ControllerExtensionModulePhongban
    nhansu.php => ControllerExtensionModuleNhansu
  • Dòng 8, 21: bạn thay thành tên file của bạn (phongban, nhansu,…)
    $this->load->language(‘extension/module/………..’);
    $this->response->setOutput($this->load->view(‘extension/module/………..’, $data));

4.2 Tạo file language

Bạn tạo file mới:

  • trong đường dẫn language/en-gb/extension/module
  • tên file giống như tên controller lúc nãy. Ví dụ mình tạo file phongban.php
  • Nội dung file, bạn copy bên dưới vào
<?php
$_['meta_title'] = 'QLNS Phòng ban'; 
$_['heading_title'] = 'QLNS Phòng ban'; // tên của module

$_['text_extension']    = 'Extensions';
$_['text_success']      = 'Success: You have modified PhongBan Content module!';
$_['text_edit']         = 'Edit PhongBan Content Module';
// Entry
$_['entry_name']        = 'Module Name';
$_['entry_title']       = 'Heading Title';
$_['entry_status']      = 'Status';
// Error
$_['error_permission']  = 'Warning: You do not have permission to modify PhongBan Content module!';
$_['error_name']        = 'Module Name must be between 3 and 64 characters!';

$_['text_confirm'] = 'Bạn có chắc chắn muốn xóa danh mục này?';

4.3 Tạo file view

Bạn tạo file mới:

  • trong đường dẫn view/template/extension/module
  • tên file giống như tên controller và language lúc nãy. Ví dụ mình tạo file phongban.twig
  • Nội dung file, bạn copy bên dưới vào
{{ header }}{{ column_left }}
<!-- Nội dung trang -->

<!-- /// -->
{{ footer }} 

4.4 Kích hoạt module

Vào trang admin

Tiếp theo vào Extensions => Extensions

Chọn Modules

Tìm tên module và nhấn vào nút dấu “+” màu xanh. Nếu thành  công sẽ ra nút dấu “-” màu đỏ.

Nhấn nút hình cây viết màu xanh để đi đến trang của module.

5. Controller

5.1. Tạo mới (CRUD – Create)

<?php
class ControllerExtensionModulePhongBan extends Controller
{
	//controller
	public function index() {

	
		$this->load->language('extension/module/phongban');
	    $this->document->setTitle($this->language->get('meta_title'));
	
	    $data['column_left'] = $this->load->controller('common/column_left');
	    $data['column_right'] = $this->load->controller('common/column_right');
	    $data['content_top'] = $this->load->controller('common/content_top');
	    $data['content_bottom'] = $this->load->controller('common/content_bottom');
	    $data['footer'] = $this->load->controller('common/footer');
	    $data['header'] = $this->load->controller('common/header');
	    $data['meta_title'] = $this->language->get('meta_title');
	    $data['text_confirm'] = $this->language->get('text_confirm');

	    $data['action_add'] = $this->url->link('extension/module/phongban', 'user_token=' . $this->session->data['user_token']);
	    $data['action_edit'] =  $this->url->link('extension/module/phongban', 'user_token=' . $this->session->data['user_token'] . '&masua=');
	    $data['action_delete'] =  $this->url->link('extension/module/phongban', 'user_token=' . $this->session->data['user_token'] . '&ma=');

	    $info = "";
    	$status = "success";
    		    
	    if( isset( $this->request->post['save'] ) ) {
	    	$ten = $this->request->post['ten'];
	    	$validate = $this->validateForm( $ten );
	    	if ( $validate == "ok" ) {
	    		if( $this->add() ) {
	    			$info = "Thêm thành công phòng ban $ten";
	    		} else {
	    			$info = "Thêm không thành công phòng ban $ten";
					$status = "danger";
	    		}
	    	}else {
	    		$info = "Thêm không thành công - ".$validate;
				$status = "danger";
	    	}

	    }    

	    $data['status'] = $status;
		$data['info'] = $info;
		$data['list']=$this->md_getAll();

		
		$this->response->setOutput($this->load->view('extension/module/phongban', $data));
   
	}

	public function validateForm($ma) {
		if($ma == "")
			return "Tên phòng ban không được để trống";
		if(strlen($ma) < 3)
			return "Tên phải có ít nhất 3 ký tự";
		else return "ok";
	}

	

	//====================================================================
	//model
	public function md_getAll() {
		$query = $this->db->query("select * from ". DB_PREFIX . "department");
		return $query->rows;
	}

}

?>

5.2. Cập nhật (CRUD – Update)

<?php
class ControllerExtensionModulePhongBan extends Controller
{
	//controller
	public function index() {

	
		$this->load->language('extension/module/phongban');
	    $this->document->setTitle($this->language->get('meta_title'));
	
	    $data['column_left'] = $this->load->controller('common/column_left');
	    $data['column_right'] = $this->load->controller('common/column_right');
	    $data['content_top'] = $this->load->controller('common/content_top');
	    $data['content_bottom'] = $this->load->controller('common/content_bottom');
	    $data['footer'] = $this->load->controller('common/footer');
	    $data['header'] = $this->load->controller('common/header');
	    $data['meta_title'] = $this->language->get('meta_title');
	    $data['text_confirm'] = $this->language->get('text_confirm');

	    $data['action_add'] = $this->url->link('extension/module/phongban', 'user_token=' . $this->session->data['user_token']);
	    $data['action_edit'] =  $this->url->link('extension/module/phongban', 'user_token=' . $this->session->data['user_token'] . '&masua=');
	    $data['action_delete'] =  $this->url->link('extension/module/phongban', 'user_token=' . $this->session->data['user_token'] . '&ma=');

	    $info = "";
    	$status = "success";

	    if( isset( $this->request->post['update'] ) ) {

	    	$ten = $this->request->post['ten'];
	    	$ma = $this->request->post['id'];
	    	$item = $this->md_getByMa($ma);
	    	$ten_cu = $item[0]["department_name"];
	    	$validate = $this->validateForm( $ten );
	    	if ( $validate == "ok" ) {
	    		if( $this->update() ) {
	    			if($ten == $ten_cu)
	    				$info = "Cập nhật thành công phòng ban $ten";
	    			else $info = "Cập nhật thành công phòng ban $ten (tên trước đó là $ten_cu)";
	    		} else {
	    			$info = "Cập nhật không thành công phòng ban $ten_cu";
					$status = "danger";
	    		}
	    	}else {
	    		$info = "Cập nhật không thành công - ".$validate;
				$status = "danger";
	    	}

	    }

	    

	    $data['status'] = $status;
		$data['info'] = $info;
		$data['list']=$this->md_getAll();

		
		$this->response->setOutput($this->load->view('extension/module/phongban', $data));
   
	}


	public function update() {
		$id = $this->request->post['id'];
		$ten = $this->request->post['ten'];
		$chiChu = $this->request->post['ghi-chu'];
	
		$status = $this->md_update( $id, $ten, $chiChu );
		$url = '';
	    
		if($status) {
			date_default_timezone_set("Asia/Ho_Chi_Minh");
			$user =  $this->session->data["user_id"];
			$time = date("Y-m-d H:i:s");
			$this->md_add_log("Sửa", $ten, $time, $user, $id);
			return true;
		}
		else {
			return false;
		}
	}

	public function validateForm($ma) {
		if($ma == "")
			return "Tên phòng ban không được để trống";
		if(strlen($ma) < 3)
			return "Tên phải có ít nhất 3 ký tự";
		else return "ok";
	}

	

	//====================================================================
	//model
	public function md_getAll() {
		$query = $this->db->query("select * from ". DB_PREFIX . "department");
		return $query->rows;
	}

	public function md_getByMa( $id ) {
		$query = $this->db->query("select * from ". DB_PREFIX . "department where id = '". $id ."'");
		return $query->rows;
	}

	public function md_update( $id, $ten, $ghiChu ) {
		try{
			$query = $this->db->query("update ". DB_PREFIX . "department set department_name='". $ten ."', note = '". $ghiChu ."' where id='". $id ."'");
			return true;
		} catch( Exception $ex) {
			return false;
		}
	}
}

?>

5.3. Xóa (CRUD – Delete)

<?php
class ControllerExtensionModulePhongBan extends Controller
{
	//controller
	public function index() {

	
		$this->load->language('extension/module/phongban');
	    $this->document->setTitle($this->language->get('meta_title'));
	
	    $data['column_left'] = $this->load->controller('common/column_left');
	    $data['column_right'] = $this->load->controller('common/column_right');
	    $data['content_top'] = $this->load->controller('common/content_top');
	    $data['content_bottom'] = $this->load->controller('common/content_bottom');
	    $data['footer'] = $this->load->controller('common/footer');
	    $data['header'] = $this->load->controller('common/header');
	    $data['meta_title'] = $this->language->get('meta_title');
	    $data['text_confirm'] = $this->language->get('text_confirm');

	    $data['action_add'] = $this->url->link('extension/module/phongban', 'user_token=' . $this->session->data['user_token']);
	    $data['action_edit'] =  $this->url->link('extension/module/phongban', 'user_token=' . $this->session->data['user_token'] . '&masua=');
	    $data['action_delete'] =  $this->url->link('extension/module/phongban', 'user_token=' . $this->session->data['user_token'] . '&ma=');

	    $info = "";
    	$status = "success";
    	
    	if( isset( $this->request->get['ma'] ) ) {
	    	$id =  $this->request->get['ma'];
	    	$item = $this->md_getByMa($id);
	    	$ten_cu = $item[0]["department_name"];

    		if( $this->delete( $id ) ) {
    			$info = "Xóa thành công phòng ban $ten_cu";
    		} else {
    			$info = "Xóa không thành công phòng ban $ten_cu";
				$status = "danger";
    		}
	    }
	    
	    $data['status'] = $status;
		$data['info'] = $info;
		$data['list']=$this->md_getAll();

		
		$this->response->setOutput($this->load->view('extension/module/phongban', $data));
   
	}

	public function delete( $id ) {
		date_default_timezone_set("Asia/Ho_Chi_Minh");
		$user =  $this->session->data["user_id"];
		$time = date("Y-m-d H:i:s");
		$this->md_add_log("Xóa", '-1', $time, $user, $id);
		$status = $this->md_delete( $id );
		$url = '';
		if($status) {
			return true;
		}
		else {
			return false;
		}
	}

	//====================================================================
	//model

	public function md_delete( $id ) {
		try{
			$query = $this->db->query("delete from ". DB_PREFIX . "department where id = '". $id ."'");
			return true;
		} catch( Exception $ex) {
			return false;
		}
	}

}

?>

6. View CRUD

{{ header }}{{ column_left }}
<div id="content">
  <div class="page-header">
    <div class="container-fluid">
      <div class="pull-right">
        <button type="button" data-toggle="tooltip" title="{{ button_filter }}" onclick="$('#filter-product').toggleClass('hidden-sm hidden-xs');" class="btn btn-default hidden-md hidden-lg"><i class="fa fa-filter"></i></button>


        <a href="#" data-toggle="modal" data-target="#modal_add" class="btn btn-primary"><i class="fa fa-plus"></i></a>
        <!-- Modal -->
                    <div class="modal fade" id="modal_add" role="dialog">
                      <div class="modal-dialog">
                      
                        <!-- Modal content-->
                        <div class="modal-content">
                          <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <h4 class="modal-title">Thêm phòng ban mới</h4>
                          </div>
                          <div class="modal-body">
                            <form action="{{ action_add }}" method="post">
                            <div class="form-group">
                            <label for="ma">Tên phòng ban:</label>
                            <input type="text" class="form-control" id="ma" name="ten">
                          </div>
                          <div class="form-group">
                            <label for="ten">Ghi chú:</label>
                            <input type="text" class="form-control" id="ten" name="ghi-chu">
                          </div>
                          <button type="submit" class="btn btn-primary" name="save">Thêm</button>
                          </form>
                          </div>
                        </div>
                        
                      </div>
                    </div> <!-- end modal -->


        
        
      </div>
      <h1>{{ heading_title }}</h1>
      <ul class="breadcrumb">
        {% for breadcrumb in breadcrumbs %}
        <li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
        {% endfor %}
      </ul>
    </div>
  </div>

  {% if (info is defined) and (info != "") %}
  <div class = "container-fluid">
    <div class="row" style="margin-bottom: 10px">
        <div class="col-md-12">
          <div class="alert alert-{{ status }}">
          {{ info }}
          </div>
        </div>
    </div>
  </div>
  {% endif %}
  <div class="container-fluid">{% if error_warning %}
    <div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> {{ error_warning }}
      <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>
    {% endif %}
    {% if success %}
    <div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> {{ success }}
      <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>
    {% endif %}
    <div class="row">
      <div class="col-md-12 col-md-pull-0 col-sm-12">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title"><i class="fa fa-list"></i> {{ text_list }}</h3>
          </div>
          <div class="panel-body">
            <form action="{{ delete }}" method="post" enctype="multipart/form-data" id="form-product">
              <div class="table-responsive">
                <table class="table table-bordered table-hover">
                  <thead>
                    <tr>
                      <td class="text-left"> STT </td>
                      <td class="text-left"> Phòng ban </td>
                      <td class="text-left"> Ghi chú </td>
                      <td class="text-right" style="width: 10%"> Hành động </td>
                    </tr>
                  </thead>
                  <tbody>
                  {% set i = 1 %}
                  {% set pagi = 1 %}
                  {% if list %}
                  {% set valueList = list|length %}
                  {% for value in list %}
                  <tr class="tr_{{ pagi }}">
                    <td class="text-left"> {{ i }} </td>
                    <td class="text-left">{{ value.department_name }}</td>
                    <td class="text-left">{{ value.note }}</td>
                    
                    <td class="text-right">

                    <a href="#" data-toggle="modal" data-target="#modal_Edit_{{ value.id }}" class="btn btn-primary"><i class="fa fa-pencil"></i></a>

                    <a href="{{ action_delete }}{{ value.id }}"><button type="button" form="form-product" formaction="{{ delete }}" data-toggle="tooltip" title="{{ button_delete }}" class="btn btn-danger" onclick="return confirm('{{ text_confirm }}') ? $('#form-product').submit() : false;"><i class="fa fa-trash-o"></i></button></a>
                    </td>

                    <!-- Modal -->
                      <div class="modal fade" id="modal_Edit_{{ value.id }}" role="dialog">
                        <div class="modal-dialog">
                        
                          <!-- Modal content-->
                          <div class="modal-content">
                            <div class="modal-header">
                              <button type="button" class="close" data-dismiss="modal">&times;</button>
                              <h4 class="modal-title">Cập nhật phòng ban</h4>
                            </div>
                            <div class="modal-body">
                              <form action="{{ action_edit }}{{ value.id }}" method="post">
                                  <input type="text" name="id" style="display: none" value="{{ value.id }}">
                              <div class="form-group">
                              <label for="ma">Tên phòng ban:</label>
                              <input type="text" class="form-control" id="ma" name="ten" value="{{ value.department_name }}">
                            </div>
                            <div class="form-group">
                              <label for="ten">Ghi chú:</label>
                              <input type="text" class="form-control" id="ten" name="ghi-chu" value="{{ value.note }}">
                            </div>
                            <button type="submit" class="btn btn-primary" name="update">Cập nhật</button>
                            </form>
                            </div>
                          </div>
                          
                        </div>
                    </div> <!-- end modal -->
                  </tr>
                  {% if (i % 10 == 0) and (i != valueList) %}
                    {% set pagi = pagi + 1  %}
                  {% endif %}
                  {% set i = i + 1 %}
                  {% endfor %}
                  {% else %}
                  <tr>
                    <td class="text-center" colspan="4"> Không có dữ liệu </td>
                  </tr>
                  {% endif %}
                    </tbody>
                  
                </table>
              </div>
            </form>
            <div class="row">
              <div class="col-sm-6 text-left">
                {% for i in 1..pagi %}
                  <a href="#" data-toggle="modal" data-target="#modal_Edit_{{ value.id }}" class="btn btn-primary" onclick="xu_ly_pagi(this)">{{ i }}</a>
                {% endfor %}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script>
    var pagi = {{ pagi }};
    window.onload = function() {
      for(var i=2; i <= pagi; i++) {
        var tr = document.getElementsByClassName("tr_" + i);
        for(var j = 0; j < tr.length; j++) {
          tr[j].style.display = 'none';
        }
      }
    }

    function xu_ly_pagi(element) {
      console.log(element.textContent);
      for(var i=1; i <= pagi; i++) {
        if( i == element.textContent) {      
          var tr = document.getElementsByClassName("tr_" + i);
          for(var j = 0; j < tr.length; j++) {
            tr[j].style.display = 'table-row';
          }
        } else {
          var tr = document.getElementsByClassName("tr_" + i);
          for(var j = 0; j < tr.length; j++) {
            tr[j].style.display = 'none';
          }
        }
      }
    }
  </script>
  <script type="text/javascript"><!--
$('#button-filter').on('click', function() {
	var url = '';

	var filter_name = $('input[name=\'filter_name\']').val();

	if (filter_name) {
		url += '&filter_name=' + encodeURIComponent(filter_name);
	}

	var filter_model = $('input[name=\'filter_model\']').val();

	if (filter_model) {
		url += '&filter_model=' + encodeURIComponent(filter_model);
	}

	var filter_price = $('input[name=\'filter_price\']').val();

	if (filter_price) {
		url += '&filter_price=' + encodeURIComponent(filter_price);
	}

	var filter_quantity = $('input[name=\'filter_quantity\']').val();

	if (filter_quantity) {
		url += '&filter_quantity=' + encodeURIComponent(filter_quantity);
	}

	var filter_status = $('select[name=\'filter_status\']').val();

	if (filter_status !== '') {
		url += '&filter_status=' + encodeURIComponent(filter_status);
	}

	location = 'index.php?route=catalog/product&user_token={{ user_token }}' + url;
});
//--></script> 
  <script type="text/javascript"><!--
// IE and Edge fix!
$('button[form=\'form-product\']').on('click', function(e) {
	$('#form-product').attr('action', $(this).attr('formaction'));
});
  
$('input[name=\'filter_name\']').autocomplete({
	'source': function(request, response) {
		$.ajax({
			url: 'index.php?route=catalog/product/autocomplete&user_token={{ user_token }}&filter_name=' +  encodeURIComponent(request),
			dataType: 'json',
			success: function(json) {
				response($.map(json, function(item) {
					return {
						label: item['name'],
						value: item['product_id']
					}
				}));
			}
		});
	},
	'select': function(item) {
		$('input[name=\'filter_name\']').val(item['label']);
	}
});

$('input[name=\'filter_model\']').autocomplete({
	'source': function(request, response) {
		$.ajax({
			url: 'index.php?route=catalog/product/autocomplete&user_token={{ user_token }}&filter_model=' +  encodeURIComponent(request),
			dataType: 'json',
			success: function(json) {
				response($.map(json, function(item) {
					return {
						label: item['model'],
						value: item['product_id']
					}
				}));
			}
		});
	},
	'select': function(item) {
		$('input[name=\'filter_model\']').val(item['label']);
	}
});
//--></script></div>
{{ footer }} 

7. Model

7.1 Get all

public function md_getAll() {
  $query = $this->db->query("select * from ". DB_PREFIX . "department");
  return $query->rows;
}

7.2 Get by id

public function md_getByMa( $id ) {
  $query = $this->db->query("select * from ". DB_PREFIX . "department where id = '". $id ."'");
  return $query->rows;
}

7.3 Insert

public function md_add( $ten, $ghiChu ) {
  try{
    $query = $this->db->query("insert into ". DB_PREFIX . "department(department_name, note) values(N'".$ten."', '".$ghiChu."')");
    return true;
  } catch( Exception $ex) {
    return false;
  }
}

7.4 Update

public function md_update( $id, $ten, $ghiChu ) {
  try{
    $query = $this->db->query("update ". DB_PREFIX . "department set department_name='". $ten ."', note = '". $ghiChu ."' where id='". $id ."'");
    return true;
  } catch( Exception $ex) {
    return false;
  }
}

7.5 Delete

public function md_delete( $id ) {
  try{
    $query = $this->db->query("delete from ". DB_PREFIX . "department where id = '". $id ."'");
    return true;
  } catch( Exception $ex) {
    return false;
  }
}

7.6 Lấy giá trị của query trả về

$data = $this->db->query("select * from ". DB_PREFIX . "department order by id DESC");
$id = $data->row["id"];

8. Cách đặt tên

  • Tên module: nên có tiền tố phía trước để dễ tìm kiếm, vì module có khá nhiều kiếm sẽ mất thời gian.
    Ví dụ: dự án mình làm “Quản lý nhân sự”
    => QLNS Phòng Ban, QLNS Chi Lương,…
  • Tên bảng csdl: oc_tiền tố_tên bảng. Như vậy sẽ dễ kiếm database hơn. Do nó có quá nhiều bảng.
    Ví dụ: oc_qlns_phong_ban, oc_qlns_chi_luong,…

9. Lấy các ngày của tháng

public function get_day_of_month() {
  $date = date('Y-m')."-01";
  $end = date('Y-m-d');
  // $end = date('Y-m-') . date('t', strtotime($date)); //get end date of month

  $data_day_of_month = [];
  while(strtotime($date) <= strtotime($end)) {
    $day_num = date('d', strtotime($date));
    $day_name = date('l', strtotime($date));
    $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
    $date_tam = [];
    $date_tam["day_num"] = $day_num;
    $date_tam["day_name"] = $this->change_string_day_of_week($day_name);
    $data_day_of_month[] = $date_tam;
  }
  return $data_day_of_month;
}

10. Twig

10.1 Echo

{{ dữ liệu }}

10.2 For

{# for #}
{% for i in 1..pagi %}

{% endfor %}

{# hoặc #}
{% for i in range(low=1, high=10, step=2) %}
    {{ i }},
{% endfor %}

{# foreach #}
{% for breadcrumb in breadcrumbs %}
	<li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
{% endfor %}

10.3 If else

{% if (i % 10 == 0) and (i != valueList) %}

{% elseif i == 10 %}

{% else %}

{% endif %}

10.4 Tạo biến, gán giá trị

{% set pagi = 1 %}

10.4 Lấy chiều dài mảng

{% set valueList = list|length %}

10.5 Kiểm tra tồn tại – giống isset

{% if (info is defined) %}
  
{% endif %}

10.5 Format number

{{ item_luong.luong|number_format(0, '.', ',') }}

10.6 Include

{{ include('sections/articles/sidebar.html') }}

10.7 Ghi chú

{# note: disabled template because we no longer use this

#}

10.8 Truy xuất phần tử của mảng, đối tượng

Chỉ với dấu (.), chúng ta có thể lấy các giá trị của Object hoặc Array.

{{ foo.bar }}
{{ foo['bar'] }}

Trong trường hợp có kí tự đặc biệt, hàm attribute() có thể hỗ trợ chúng ta.

{{ attribute(foo, 'data-foo') }}

Với biến Global, chúng ta có thể sử dụng ở bất kì chỗ nào

  • _self : tham chiếu đến template hiện tại
  • _context : tham chiếu đến context hiện tại
  • _charset : tham chiếu đến charset hiện tại

10.9 Sắp xếp mảng

{% for number in numbers|sort %}
   {{ number }}
{% endfor %}

10.10 utf8

{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}

{# versus #}

{{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}

10.11 Date

{# the first argument is the date format, which defaults to the global date format if null is passed #}
{{ "now"|date(null, "Europe/Paris") }}

{# or skip the format value by using a named argument for the time zone #}
{{ "now"|date(timezone="Europe/Paris") }}
  
{# Hoặc gộp cả hai #}
{{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}

10.12 Debug – giống print_r

<pre>
    {{ dump(user) }}
</pre>

10.13 Macro – giống function tái sử dụng

Macro có thể được so sánh với functions trong các ngôn ngữ lập trình, nó được dùng để tái sử dụng các đoạn HTML mà tránh sự lặp lại không đáng có. Một macro được định nghĩa qua macro tag.

Ví dụ đơn giản macro:

{% macro input(name, value, type, size) %} 
	<input type="{{ type|default('text') }}" 
           name="{{ name }}" 
           value="{{ value|e }}" 
           size="{{ size|default(20) }}" /> 
{% endmacro %}

Chúng ta cũng có thể thiết lập các giá trị mặc định của tham số trong macro

{% macro input(name, value = "", type = "text", size = 20) %} 
	<input type="{{ type }}" 
           name="{{ name }}" 
           value="{{ value|e }}" 
           size="{{ size }}" /> 
{% endmacro %}

Để sử dụng Macro thì chỉ cần import vào là xong

{% import "forms.html" as forms %} 
<p>{{ forms.input('username') }}</p>

Bạn cũng có thể đổi tên cho macro đó khi import

{% from 'forms.html' import input as input_field %} 
<dl> 
  <dt>Username</dt> 
  <dd>{{ input_field('username') }}</dd> 
  <dt>Password</dt> 
  <dd>{{ input_field('password', '', 'password') }}</dd> 
</dl>

Còn express và template, bạn xem thêm tại đây. https://viblo.asia/p/twig-trong-template-DZrGNNLjGVB

11. Lỗi thiếu mCrypt khi cài đặt

Bạn download file này về máy: https://drive.google.com/file/
Hoặc truy cập link sau để tải về đúng phiên bản php của bạn: https://pecl.php.net/package/mcrypt/1.0.3/windows

Bạn giải nén và chép tập tin đó vào thư mục cài xampp\php\ext

Bạn mở file php.ini

Sau đó dán dòng này vào dòng trống bất kỳ.

extension=mcrypt

12. vqmod

12.1 Cài vqmod

Để cài đặt VQMOD cho opencart ta thực hiện các bước sau.

Bước 1: Tải bản VQMOD mới nhất tại đây: http://code.google.com/
Bước 2: Giải nén ra thư mục vqmod
Bước 3: Upload thư mục vqmod vừa giải nén lên ngang hàng với thư mục gốc


Bước 4: chạy đường dẫn http://domain.com/vqmod/install có thông báo VQMOD HAS BEEN INSTALLED ON YOUR SYSTEM! là xong

12.2 Cấu trúc vqmod

Bài viết rất chi tiết tại đây: https://code.tutsplus.com/

<?xml version="1.0" encoding="UTF-8"?>
<modification>
   <id>Example of the vQmod</id>
   <version>1.0</version>
   <vqmver>2.X</vqmver>
   <author>Tuts+</author>
   <file name="targetfile.php">
       <operation info="Example of the vQmod">
           <search position="replace"><![CDATA[
           I am original content.
           ]]></search>
           <add><![CDATA[
           I am replaced content!!
           ]]></add>
       </operation>
   </file>
</modification>
  • thẻ id, version, author: bạn có thể thay đổi.
  • thẻ vqmver: không nên thay đổi, nó chỉ ra phiên bản của vQmod
  • name: tên tập tin được tác động
  • info: giống như mô tả
  • search: tìm kiếm
  • add: phần thay đổi

Các tùy chọn của postion search:

  • before: chèn trước kết quả tìm
  • after: chèn sau kết quả tìm
  • top: chèn đầu file, không cần thẻ search
  • bottom: chèn cuối file, không cần thẻ search
  • ibefore: chèn trước trên cùng dòng
  • iafter: chèn sau trên cùng dòng.

Các thuộc tính của thẻ search:

  • offset: giống như đè phím shift rồi chọn. Dùng lấy nhiều dòng
  • index: xác định những kết quả nào được thay đổi.
  • regex: chưa rõ ??

12.3 Viết vqmod

Tạo file xml tại vqmod\xml

<?xml version="1.0" encoding="UTF-8"?>
<modification>
  <id>VQMOD CORE</id>
  <version>1.4.x and 1.5.x</version>
  <vqmver required="true">2.4.0</vqmver>
  <author>vqmod.com</author>
  
  <file name="catalog/view/theme/default/template/common/header.tpl">
    <operation error="skip">
      <search position="replace" offset="5"><![CDATA[
        <?php if ($logo) { ?>
        ]]></search>
      <add><![CDATA[
          Trọng Hảo đang test
        ]]></add>
    </operation>
  </file>

</modification>

12.4 Controller vqmod

<file name="catalog/controller/account/edit.php">
    <operation error="skip">
      <search position="before" offset="1"><![CDATA[
       ......
        ]]></search>
      <add><![CDATA[
          ......
        ]]></add>
    </operation>
  </file>

12.5 View vqmod

<file name="catalog/view/theme/default/template/account/edit.tpl">
    <operation error="skip">
      <search position="after"><![CDATA[
       ......
        ]]></search>
      <add><![CDATA[
          ......
        ]]></add>
    </operation>
  </file>

12.6 Model vqmod

<file name="catalog/model/account/customer.php">
    <operation error="skip">
      <search position="replace"><![CDATA[
		......
        ]]></search>
      <add><![CDATA[
            ......
        ]]></add>
    </operation>
  </file>

Related posts:

  1. Kinh nghiệm Angular
  2. Kinh nghiệm ASP.NET + LINQ
  3. Kinh nghiệm DataTable
  4. Kinh nghiệm React

Post navigation

Previous Post:

Lộ trình học web Javascript

Next Post:

Ôn thi olympic 2020

Trả lời Hủy

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Ẩn sidebar

Tìm kiếm

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Blog Công Nghệ

Bài viết mới

  • Master typescript
  • Sendmail trong Laravel sử dụng dịch vụ SES, SQS của Amazon
  • Install SSL in Nginx Ubuntu
  • Docker study
  • Bảo vệ: Hướng dẫn code bot Telegram easy game

Lượng truy cập

0074584
Visit Today : 180
Visit Yesterday : 178
This Month : 855
Who's Online : 6
© 2025 Blog Công Nghệ | WordPress Theme by Superbthemes