Selasa, 17 Februari 2015

Membuat Upload File dengan Doctrine 2 dan Zend Framework 2

Langkah pertama anda buatlah database terlebih dahulu dengan menggunakan doctrine, sebelumnya untuk membuat database pada doctrine telah dijelaskan. anda bisa lihat langsung pada tulisan saya sebelumnya. kemudian buatlah entity database anda, disini saya buat dengan nama user yang berada pada module/application/src/entity/ yang berisikan source seperti dibawah ini :

namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of User
 *
 * @author Candra
 */
/** @ORM\Entity */
class User {
    /**
     * @ORM\id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;
    
    /** @ORM\Column(type="string") 
     */
    protected $fullName;
    
    /** @ORM\Column(type="string") 
     */
    protected $upload;
    
    /** @ORM\Column(type="string") 
     */
    
    //protected $alamat;
    
    /** @ORM\Column(type="string")
     */
    //protected $email;

    /** @ORM\Column(type="string",length=1) 
     */
    //protected $jk;
    
    // getters/setters
    
    function getId() {
        return $this->id;
    }

    function getFullName() {
        return $this->fullName;
    }

    function getAlamat() {
        return $this->alamat;
    }

    function getEmail() {
        return $this->email;
    }

    function getJk() {
        return $this->jk;
    }

    function setId($id) {
        $this->id = $id;
    }

    function setFullName($fullName) {
        $this->fullName = $fullName;
    }

    function setAlamat($alamat) {
        $this->alamat = $alamat;
    }

    function setEmail($email) {
        $this->email = $email;
    }

    function setJk($jk) {
        $this->jk = $jk;
    }
    function getUpload() {
        return $this->upload;
    }

    function setUpload($upload) {
        $this->upload = $upload;
    }

}

Kemudian buka command prompt anda dan jalankan perintah 
vendor/bin/doctrine-module orm:validate-schema
vendor/bin/doctrine-module orm:schema-tool:update --force

Selanjutnya anda buat sebuah controller untuk upload pada application/controller disini saya menggunakan nama ProfileController.php dan tuliskan source dibawah ini :

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model\Profile;
use Application\Form\ProfileForm;
use Zend\Validator\File\Size;
use Application\Entity\User;

class ProfileController extends AbstractActionController
{
    protected $_objectmanager;
    
    public function viewAction()
    {
       $users = $this->getObjectManager()->getRepository('\Application\Entity\User')->findAll();
       return new ViewModel(array('users' => $users));
    }

    public function addAction()
    {
            
        $form = new ProfileForm();
        $request = $this->getRequest();
        if ($request->isPost()){
            
            $profile = new Profile();
            $form->setInputFilter($profile->getInputFilter());
            
            $nonFile = $request->getPost()->toArray();
            $File = $this->params()->fromFiles('fileupload');
            $data = array_merge(
                    $nonFile,
                    array('fileupload'=>$File['name'])
                    );
            //set data post and file..
            $form->setData($data);
            
            if ($form->isValid()) {
                // $profile->exchangeArray($form->getData());
                $size = new Size(array('min'=>'0.001MB'));
                //2MB
                $adapter = new \Zend\File\Transfer\Adapter\Http();
                $extensionvalidator = new \Zend\Validator\File\Extension(array('extension'=>array('jpg','png')));
                //$adapter->setValidators(array($extensionvalidator));
                $adapter->setValidators(array($size,$extensionvalidator), $File['name']);
                if (!$adapter->isValid()){
                    $dataError = $adapter->getMessages();
                    $error = array();
                    foreach ($dataError as $key=>$row)
                    {
                        $error[] = $row;
                    }
                    $form->setMessages(array('fileupload'=>$error));
                } else {
                $adapter->setDestination(getcwd().'/public/img/upload');
                if ($adapter->receive($File['name'])) {
                    $profile->exchangeArray($form->getData());
                    $upload = $profile->fileupload;
                    $user = new User();
                
                    $user->setFullName($this->getRequest()->getPost('profilename'));
                    $user->setUpload($File['name']);

                    $this->getObjectManager()->persist($user);
                    $this->getObjectManager()->flush();
                    $newId = $user->getId();


                    return $this->redirect()->toRoute('home');
                   //echo 'Profile Nama'.$profile->profilename.'upload'.$profile->fileupload;
                }
                }
                //$upload = $profile->fileupload;                var_dump($upload);die;
                if ($this->request->isPost()) {
                
            } 
            }
        }
        
        return array('form'=>$form);
                          
    }
    protected function  getObjectManager()
    {
        if (!$this->_objectmanager){
            $this->_objectmanager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
        }
        return $this->_objectmanager;
    }
}

Kemudian anda Form untuk upload ini pada application/src/application/form buat dengan nama ProfileForm.php dan tuliskan source dibawah ini :

namespace Application\Form;

use Zend\Form\Form;

class ProfileForm extends Form
{
    public function __construct($name = null) {
        parent::__construct('Profile');
        $this->setAttribute('method', 'post');
        $this->setAttribute('enctype', 'multipart/form-data');
        
        $this->add(array(
            'name'=>'profilename',
            'attributes'=> array(
                'type'=>'text',
            ),
            'options'=>array(
                'label'=>'Profile Name',
            ),
        ));
        
        $this->add(array(
            'name'=>'fileupload',
            'attributes'=>array(
                'type'=>'file',
            ),
            'options'=>array(
                'label'=>'File Upload1',
            ),
        ));
             
        $this->add(array(
            'name'=>'submit',
            'attributes'=>array(
                'type'=>'submit',
                'value'=>'Upload Now'
            ),
        ));
    }
}

Setelah itu buat model pada application/src/application/model dengan nama Profile.php dan tuliskan sorce code dibawah ini :

namespace Application\Model;

use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class Profile implements InputFilterAwareInterface
{
 public $profilename;
 public $fileupload;
 protected $inputFilter;
 public function exchangeArray($data)
 {
     $this->profilename = (isset($data['profilename']))?$data['profilename']:null;
     $this->fileupload = (isset($data['fileupload']))?$data['fileupload']:null;
 }
 public function setInputFilter(InputFilterInterface $inputFilter) 
 {
     throw new \Exception("Not used");
 }
 public function getInputFilter() 
 {
     if (!$this->inputFilter){
         $inputFilter = new InputFilter();
         $factory = new InputFactory();
         
         $inputFilter->add(
                 $factory->createInput(array(
                     'name'=>'profilename',
                     'required'=>true,
                     'filters'=>array(
                         array('name'=>'StripTags'),
                         array('name'=>'StringTrim'),
                     ),
                     'validators'=>array(
                         array(
                             'name'=>'StringLength',
                             'options'=>array(
                                 'encoding'=>'UTF-8',
                                 'min'=>1,
                                 'max'=>100,
                             ),
                         ),
                     ),
                 ))
             );
         $inputFilter->add(
                 $factory->createInput(array(
                     'name'=>'fileupload',
                     'required'=>true,
                 ))
            );
            $this->inputFilter = $inputFilter;
     }
     return $this->inputFilter;
 }
}

Selanjutnya buatlah view pada application/view/application/profile dengan nama add.phtml dan tuliskan source code berikut ini :

$form = $this->form;
$form->setAttribute('action',
        $this->url('profile',
                array('controller'=>'profile','action'=>'add')));
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formRow($form->get('profilename'));

echo $this->formRow($form->get('fileupload'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();

Selanjutnya buatlah routing untuk bisa diakses ketika dijalankan pada application/config/module.config.php dan tambahkan source code berikut ini didalamnya :

'profile' => array(
                    'type' => 'segment',
                    'options' => array(
                        'route' => '/profile[/][:action][/:id]',
                        'constraints' => array(
                            'action' => '[a-zA-Z][a-zA-Z0-9]*',
                            'id' => '[0-9]+',
                        ),
                        'defaults' => array(
                            'controller' => 'Application\Controller\Profile',
                            'action' => 'add',
                        ),
                    ),
                ),

Selanuntya anda buat folder upload  pada folder public/img. kemudian coba anda jalankan pada web browser dengan link localhost/testing/public/profile, disini nama project saya anda testing, maka tampilan akan seperti ini :


Untuk melihat gambar yang anda upload anda cukup tambahkan view satu lagi, disini saya gunakan nama viewnya adalah view yang terletak pada application/view/application/profile/view.phtml dan tulisakn source code berikut ini :

<?php if (isset($users)) : ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Full name</th>
                            <th>Image</th>
                            <th></th>
                        </tr>
                    </thead>
                    <?php foreach($users as $user): ?>
                    <tbody>
                        <tr>
                            <td><?php echo $user->getId(); ?></td>
                            <td><?php echo $user->getFullName(); ?></td>
                            <td>
                                <a href="<?php echo $this->basePath().'/img/upload/'.$user->getUpload(); ?>">
                                <img width="50" height="50" src="<?php echo $this->basePath().'/img/upload/'.$user->getUpload(); ?>">
                                </a>
                            </td>
                                
                            <td><a href="<?php echo $this->url('user',array('action'=>'edit','id'=>$user->getId()));?>" class="btn btn-success btn-sm"><i class="icon-prev"></i>Edit</a>
                                <a href="<?php echo $this->url('user',array('action'=>'delete','id'=>$user->getId()));?>" class="btn btn-danger btn-sm">Delete</a>
                            </td>
                        </tr>
                    </tbody>
                    <?php endforeach; ?>
                </table>
                <?php endif; ?>

Kemudian coba anda upload gambar anda dan lihat hasilnya nanti pada localhost/testing/public/profile/view maka hasilnya akan seperti berikut ini :


Maka upload file telah selesai..
Sumber : samsonasik

1 komentar: