6
Thêm(insert) dữ liệu vào database trong ZF2 Xem 'Bài 9 - Upload file và Multi upload files trong ZF2' trước khi thực hành bài này - Trước khi chúng ta xây dựng chức năng thêm một dòng vào database trong Zend Framework 2.0. Chúng ta mở database ‘zfbasic’ trong localhost:8000/phpmyadmin/ thêm vào dòng lệnh sau để tạo ra một cột mới có tên ‘picture’. ALTER TABLE `picture` ADD `hehe` VARCHAR( 255 ) NULL DEFAULT NULL AFTER `username` ; - Ở trong phần này chúng ta sẽ phải có một FORM để người sử dụng nhập liệu và sau đó nhấn nút ‘Submit’ để gửi dữ liệu đến máy chủ vì vậy chúng ta cần tạo ra một đối tượng Zend\Form\Form. Lúc này chúng ta sẽ tạo ra một tập tin mới /module/Admin/src/Admin/Form/UserForm.php với nội dung sau: <?php namespace Admin\Form; use Zend\Form\Form; class UserForm extends Form { public function __construct($name = null) { parent::__construct('appForm'); //Khai báo phương thức sử dụng trong FORM $this->setAttribute('method', 'post'); //Khai báo kiểu dữ liệu được gửi lên server $this->setAttribute('enctype','multipart/form-data'); //Khai báo phần tử textbox 'username' $this->add(array( 'name' => 'username', 'attributes' => array( 'type' => 'text', 'required' => 'required',

Tài liệu Zend Framework 2 : Thêm dữ liệu vào database trong ZF2 - Bài 10

Embed Size (px)

DESCRIPTION

Tài liệu Zend Framework 2 : Thêm dữ liệu vào database trong ZF2 - Bài 10 Để tìm hiểu kỹ hơn các bạn hãy truy cập: Website: www.zend.vn Facebook: facebook.com/zendvngroup Youtube: youtube.com/user/luutruonghailan

Citation preview

Thêm(insert) dữ liệu vào database trong ZF2

Xem 'Bài 9 - Upload file và Multi upload files trong ZF2' trước khi thực hành bài này

- Trước khi chúng ta xây dựng chức năng thêm một dòng vào database trong Zend Framework 2.0. Chúng

ta mở database ‘zfbasic’ trong localhost:8000/phpmyadmin/ thêm vào dòng lệnh sau để tạo ra một cột

mới có tên ‘picture’.

ALTER TABLE `picture` ADD `hehe` VARCHAR( 255 ) NULL DEFAULT NULL AFTER `username` ;

- Ở trong phần này chúng ta sẽ phải có một FORM để người sử dụng nhập liệu và sau đó nhấn nút

‘Submit’ để gửi dữ liệu đến máy chủ vì vậy chúng ta cần tạo ra một đối tượng Zend\Form\Form. Lúc này

chúng ta sẽ tạo ra một tập tin mới /module/Admin/src/Admin/Form/UserForm.php với nội dung sau:

<?php

namespace Admin\Form;

use Zend\Form\Form;

class UserForm extends Form

{

public function __construct($name = null)

{

parent::__construct('appForm');

//Khai báo phương thức sử dụng trong FORM

$this->setAttribute('method', 'post');

//Khai báo kiểu dữ liệu được gửi lên server

$this->setAttribute('enctype','multipart/form-data');

//Khai báo phần tử textbox 'username'

$this->add(array(

'name' => 'username',

'attributes' => array(

'type' => 'text',

'required' => 'required',

'class' => 'txtInput txtMedium'

),

'options' => array(

'label' => 'Username:',

),

));

//Khai báo phần tử textbox 'username'

$this->add(array(

'name' => 'picture',

'attributes' => array(

'type' => 'file',

//'required' => 'required',

'class' => 'txtInput txtMedium'

),

'options' => array(

'label' => 'Avatar:',

),

));

//Khai báo phần tử textbox 'email'

$this->add(array(

'name' => 'email',

'attributes' => array(

'type' => 'text',

'required' => 'required',

'class' => 'txtInput txtMedium'

),

'options' => array(

'label' => 'Email:',

),

));

//Khai báo phần tử textbox 'password'

$this->add(array(

'name' => 'password',

'attributes' => array(

'type' => 'password',

'required' => 'required',

'class' => 'txtInput txtMedium'

),

'options' => array(

'label' => 'Password:',

),

));

//Khai báo phần tử selectbox 'group'

$this->add(array(

'name' => 'group',

'type' => 'Zend\Form\Element\Select',

'attributes' => array(

'class' => 'txtInput txtMedium',

),

'options' => array(

'label' => 'Group name:',

'value_options' => array(

'admin' => 'Admin group',

'member' => 'Member group',

),

),

));

//submit

$this->add(array(

'name' => 'submit',

'attributes' => array(

'type' => 'submit',

'value' => 'Send data'

),

));

}

}

- Tiếp theo chúng ta sẽ tạo một ACTION mới trong tập

tin /module/Admin/src/Admin/Controller/IndexController.php tên addAction() có nội dung như sau:

public function addAction(){

//Khởi tạo đối tượng UserForm

$form = new UserForm();

//Truyền đối tượng UserForm vào đối tượng ViewModel

$viewModel = new ViewModel(array('form' => $form));

//Đư đối tượng ViewModel ra ngoài VIEW

return $viewModel;

}

- Sau khi chúng ta có ACTION thì chúng ta sẽ tạo VIEW để hiển thị FORM của ACTION này. Tạo tập

tin /module/Admin/view/admin/index/add.phtml với nội dung sau:

<h1>Them mot thanh vien moi</h1>

<?php

//Lấy đối tượng Admin\Form\UserForm từ trong VIEW ra

$form = $this->form;

$form->prepare();

?>

<!-- Tạo thẻ <form...> và các giá trị thuộc tính của thẻ này -->

<?php echo $this->form()->openTag($form);?>

<ul>

<li>

<span><?php echo $this->formLabel($form->get('username')); ?></span>

<?php echo $this->formElement($form->get('username')); ?>

</li>

<li>

<span><?php echo $this->formLabel($form->get('picture')); ?></span>

<?php echo $this->formElement($form->get('picture')); ?>

</li>

<li>

<span><?php echo $this->formLabel($form->get('email')); ?></span>

<?php echo $this->formElement($form->get('email')); ?>

</li>

<li>

<span><?php echo $this->formLabel($form->get('password')); ?></span>

<?php echo $this->formElement($form->get('password')); ?>

</li>

<li>

<span><?php echo $this->formLabel($form->get('group')); ?></span>

<?php echo $this->formElement($form->get('group')); ?>

</li>

<li>

<!--Tạo nút Submit -->

<?php echo $this->formElement($form->get('submit'));?>

</li>

</ul>

<!-- Đóng thẻ </form> -->

<?php echo $this->form()->closeTag() ?>

- Bây giờ chúng ta hãy chạy thử đường dẫn sau: localhost:8000/zf2basic/public/admin/index/add/

- Chúng ta thấy trong FORM có một phần tử để upload file vì vậy chúng ta sẽ xây dựng một phương thức

trong tập tin /module/Admin/src/Admin/Form/UserForm.php để upload file lên máy chủ có nội dung như

sau:

public function upload($files = array(),$file_path = ''){

$fileName = '';

if(count($files) != 0 && $file_path != ''){

$fileName = $files['picture']['name'];

$uploadObj = new \Zend\File\Transfer\Adapter\Http();

$uploadObj->setDestination($file_path);

$uploadObj->receive($fileName);

}

return $fileName;

}

- Bây giờ chúng ta sẽ tạo ra thư mục mới tên /users trong thự mục /public/files để lưu trữ hình ảnh upload

lên từ FORM này

- Tiếp theo chúng ta sẽ xây dựng một phương thức tên saveData() trong tập tin MODEL để đưa dữ liệu

vào bảng ‘user’ của database . Mở tập tin /module/Admin/src/Admin/Model/UserTable.php với nội dung

sau:

public function saveData($arrParam = array(), $options = array()){

//Loại bỏ phần tử 'submit' trong mảng được POST qua

unset($arrParam['submit']);

//Nếu $options['task'] có giá trị 'add' thì thêm một record mới trong database

if($options['task'] == 'add'){

$this->tableGateway->insert($arrParam);

}

}

- Sau khi đã có phương thức saveData() trong MODEL bây giờ chúng ta sẽ hoàn thiện addAction() để đưa

gửi dữ liệu từ FORM vào database. Mở tập

tin /module/Admin/src/Admin/Controller/IndexController.php sửa lại addAction() như sau:

public function addAction(){

//Khởi tạo đối tượng UserForm

$form = new UserForm();

//Truyền đối tượng UserForm vào đối tượng ViewModel

$viewModel = new ViewModel(array('form' => $form));

//Lấy tất cả các giá trị được truyền qua từ FORM

$request = $this->getRequest();

if ($request->isPost()) {

//Lấy mảng thông tin được gửi từ FORM lên

$arrParam = $request->getPost()->toArray();

//Lấy mảng thông tin của file gửi lên

$files = $request->getFiles()->toArray();

//Tạo một phần tử 'picture' trong mảng $arrParam

$arrParam['picture'] = '';

//Trong trường hợp có tập tin gửi lên

//thì gọi đến phương thức upload trong đối tượng UserForm

if(!empty($files['picture']['name'])){

//Lấy tên của tập tin upload đưa vào phần tử 'picture' trong mảng $arrParam

$arrParam['picture'] = $form->upload($files,FILES_PATH . '/users');

}

//Gọi đối tượng UserTable đã khai báo trong đối tượng service

$userTable = $this->getServiceLocator()->get('Admin\Model\UserTable');

//Truyền mảng dự liệu $arrParam vào phương thức savaData

//của đối tượng Admin\Model\UserTable

$userTable->saveData($arrParam,array('task'=>'add'));

//Sau khi đưa dữ liệu vào datbase chúng trả nó về trang hiển thị dữ liệu

return $this->redirect()->toRoute('admin', array(

'controller' => 'index',

'action' => 'index'

));

}

//Đư đối tượng ViewModel ra ngoài VIEW

return $viewModel;

}

- Bây giờ chúng ta hãy chạy thử đường dẫn sau: localhost:8000/zf2basic/public/admin/index/add/ nhập

đầy đủ dữ liệu vào nhấn nút ‘Send data’ để hoàn tất quá trình lưu dữ liệu vào database và sau đó chúng ta

hãy kiểm tra xem tập tin hình đã có trong thư mục /public/files/users hay chưa

Download source here: http://www.zend.vn/download/pictures/zend-framework-2/07-zf-them-du-lieu-

vao-db/07-zf-them-du-lieu-vao-db.zip

Để tìm hiểu kỹ hơn các bạn hãy truy cập:

Website: www.zend.vn

Facebook: facebook.com/zendvngroup

Youtube: youtube.com/user/luutruonghailan