Magento 1.9 – How to Create Image/Avatar Uploader for Admin User

adminadminhtmlimage-uploadmagento-1.9

I want to add a avatar image upload field for admin users.

I want when you go to system > permissions > users, and click the "Add New User" button, a image upload section is within the add new user form.enter image description here

My plan is to use the following code to create a new column in the "admin_user" database table, to store the image link.

$installer = $this;
$installer->startSetup();
$installer->getConnection()->addColumn($installer->getTable('admin_user'),'avatar', 'varchar(255) NOT NULL DEFAULT "0"');

This would then make it easy to call and display said image wherever i need to.

$this->getUser()->getAvatar()

The issue is, i dont know how to add a image uploader and have it generate a link and place it in the database field.

Please provide as much info as possible. Any help will be greatly appreciated.

UPDATE 26/07/2015:
With the help provided in the accepted answer, I was able to create a module that provide some of the features I need. I see that the image uploader is now shown in the form, the image name is saved to the database, but unfortunately, I don't see the image in the media folder. Could someone help me to solve this last section please?

Please find the code used in accepted answer below.

Best Answer

You Need to override core magento code here -
here we have generated a custom module which will do this and override the core functionality -
Namespace - "A2bizz"

Generate below Directory Paths and their corresponding files and put the given code in it -

/app/etc/modules/A2bizz_All.xml
<config>
    <modules>        
         <A2bizz_Adminhtml>
            <active>true</active>
            <codePool>local</codePool>            
        </A2bizz_Adminhtml>                
    </modules>
</config>
/app/code/local/a2bizz/Adminhtml/etc/config.xml
<config>
    <modules>
        <A2bizz_Adminhtml>
            <version>0.1.0</version>
        </A2bizz_Adminhtml>
    </modules>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <a2bizz_adminhtml before="Mage_Adminhtml">A2bizz_Adminhtml</a2bizz_adminhtml>
                    </modules>
                </args>
            </adminhtml>
        </routers>         
    </admin>
    <global>
        <blocks>
            <adminhtml>
                <rewrite>
                    <permissions_user_edit_tab_main>A2bizz_Adminhtml_Block_Permissions_User_Edit_Tab_Main</permissions_user_edit_tab_main>
                    <permissions_user_edit_form>A2bizz_Adminhtml_Block_Permissions_User_Edit_Form</permissions_user_edit_form>
                </rewrite>
            </adminhtml>
        </blocks>
    </global>    
</config>
/app/code/local/a2bizz/Adminhtml/Block/Permissions/User/Edit/Tab/Main.php
<?php

class A2bizz_Adminhtml_Block_Permissions_User_Edit_Tab_Main extends Mage_Adminhtml_Block_Widget_Form
{

    protected function _prepareForm()
    {
        $model = Mage::registry('permissions_user');

        $form = new Varien_Data_Form();

        $form->setHtmlIdPrefix('user_');

        $fieldset = $form->addFieldset('base_fieldset', array('legend'=>Mage::helper('adminhtml')->__('Account Information')));

        if ($model->getUserId()) {
            $fieldset->addField('user_id', 'hidden', array(
                'name' => 'user_id',
            ));
        } else {
            if (! $model->hasData('is_active')) {
                $model->setIsActive(1);
            }
        }

        $fieldset->addField('username', 'text', array(
            'name'  => 'username',
            'label' => Mage::helper('adminhtml')->__('User Name'),
            'id'    => 'username',
            'title' => Mage::helper('adminhtml')->__('User Name'),
            'required' => true,
        ));

        $fieldset->addField('firstname', 'text', array(
            'name'  => 'firstname',
            'label' => Mage::helper('adminhtml')->__('First Name'),
            'id'    => 'firstname',
            'title' => Mage::helper('adminhtml')->__('First Name'),
            'required' => true,
        ));

        $fieldset->addField('lastname', 'text', array(
            'name'  => 'lastname',
            'label' => Mage::helper('adminhtml')->__('Last Name'),
            'id'    => 'lastname',
            'title' => Mage::helper('adminhtml')->__('Last Name'),
            'required' => true,
        ));

        $fieldset->addField('email', 'text', array(
            'name'  => 'email',
            'label' => Mage::helper('adminhtml')->__('Email'),
            'id'    => 'customer_email',
            'title' => Mage::helper('adminhtml')->__('User Email'),
            'class' => 'required-entry validate-email',
            'required' => true,
        ));

        // ========================= Additional Field ========================
        $fieldset->addField('avatar', 'file', array(
            'name'  => 'avatar',
            'label' => Mage::helper('adminhtml')->__('Avatar'),
            'id'    => 'customer_avatar',
            'title' => Mage::helper('adminhtml')->__('User Avatar'),            
            'required' => false,
        ));

        // ========================= Additional Field ========================

        $fieldset->addField('current_password', 'obscure', array(
            'name'  => 'current_password',
            'label' => Mage::helper('adminhtml')->__('Current Admin Password'),
            'id'    => 'current_password',
            'title' => Mage::helper('adminhtml')->__('Current Admin Password'),
            'class' => 'input-text',
            'required' => true,
        ));

        if ($model->getUserId()) {
            $fieldset->addField('password', 'password', array(
                'name'  => 'new_password',
                'label' => Mage::helper('adminhtml')->__('New Password'),
                'id'    => 'new_pass',
                'title' => Mage::helper('adminhtml')->__('New Password'),
                'class' => 'input-text validate-admin-password',
            ));

            $fieldset->addField('confirmation', 'password', array(
                'name'  => 'password_confirmation',
                'label' => Mage::helper('adminhtml')->__('Password Confirmation'),
                'id'    => 'confirmation',
                'class' => 'input-text validate-cpassword',
            ));
        }
        else {
           $fieldset->addField('password', 'password', array(
                'name'  => 'password',
                'label' => Mage::helper('adminhtml')->__('Password'),
                'id'    => 'customer_pass',
                'title' => Mage::helper('adminhtml')->__('Password'),
                'class' => 'input-text required-entry validate-admin-password',
                'required' => true,
            ));
           $fieldset->addField('confirmation', 'password', array(
                'name'  => 'password_confirmation',
                'label' => Mage::helper('adminhtml')->__('Password Confirmation'),
                'id'    => 'confirmation',
                'title' => Mage::helper('adminhtml')->__('Password Confirmation'),
                'class' => 'input-text required-entry validate-cpassword',
                'required' => true,
            ));
        }

        if (Mage::getSingleton('admin/session')->getUser()->getId() != $model->getUserId()) {
            $fieldset->addField('is_active', 'select', array(
                'name'      => 'is_active',
                'label'     => Mage::helper('adminhtml')->__('This account is'),
                'id'        => 'is_active',
                'title'     => Mage::helper('adminhtml')->__('Account Status'),
                'class'     => 'input-select',
                'style'        => 'width: 80px',
                'options'    => array('1' => Mage::helper('adminhtml')->__('Active'), '0' => Mage::helper('adminhtml')->__('Inactive')),
            ));
        }

        $fieldset->addField('user_roles', 'hidden', array(
            'name' => 'user_roles',
            'id'   => '_user_roles',
        ));

        $data = $model->getData();

        unset($data['password']);

        $form->setValues($data);

        $this->setForm($form);

        return parent::_prepareForm();
    }
}
/app/code/local/a2bizz/Adminhtml/controllers/Permissions/UserController.php
<?php
require_once Mage::getModuleDir('controllers', 'Mage_Adminhtml').DS.'Permissions'.DS.'UserController.php'; 
class A2bizz_Adminhtml_Permissions_UserController extends Mage_Adminhtml_Controller_Action
{
    public function saveAction()
    {        
        if ($data = $this->getRequest()->getPost()) {

            //================== Avatar Save Code ======================
            if(isset($_FILES['avatar']['name']) && $_FILES['avatar']['name'] != '') {
                try {   
                    /* Starting upload */   
                    $uploader = new Varien_File_Uploader('avatar');

                    // Any extention would work
                    $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                    $uploader->setAllowRenameFiles(false);

                    // Set the file upload mode 
                    // false -> get the file directly in the specified folder
                    // true -> get the file in the product like folders 
                    //  (file.jpg will go in something like /media/f/i/file.jpg)
                    $uploader->setFilesDispersion(false);

                    // We set media as the upload dir
                    $path = Mage::getBaseDir('media') . DS . 'avatar' .DS;
                    $uploader->save($path, $_FILES['avatar']['name'] );

                } catch (Exception $e) {

                }

                //this way the name is saved in DB
                $data['avatar'] = $_FILES['avatar']['name'];
            }

            //================== Avatar Save Code ==END====================


            $id = $this->getRequest()->getParam('user_id');
            $model = Mage::getModel('admin/user')->load($id);
            if (!$model->getId() && $id) {
                Mage::getSingleton('adminhtml/session')->addError($this->__('This user no longer exists.'));
                $this->_redirect('*/*/');
                return;
            }

            //Validate current admin password
            $currentPassword = $this->getRequest()->getParam('current_password', null);
            $this->getRequest()->setParam('current_password', null);
            unset($data['current_password']);
            $result = $this->_validateCurrentPassword($currentPassword);

            $model->setData($data);

            /*
             * Unsetting new password and password confirmation if they are blank
             */
            if ($model->hasNewPassword() && $model->getNewPassword() === '') {
                $model->unsNewPassword();
            }
            if ($model->hasPasswordConfirmation() && $model->getPasswordConfirmation() === '') {
                $model->unsPasswordConfirmation();
            }

            if (!is_array($result)) {
                $result = $model->validate();
            }
            if (is_array($result)) {
                Mage::getSingleton('adminhtml/session')->setUserData($data);
                foreach ($result as $message) {
                    Mage::getSingleton('adminhtml/session')->addError($message);
                }
                $this->_redirect('*/*/edit', array('_current' => true));
                return $this;
            }

            try {
                $model->save();
                if ( $uRoles = $this->getRequest()->getParam('roles', false) ) {
                    /*parse_str($uRoles, $uRoles);
                    $uRoles = array_keys($uRoles);*/
                    if ( 1 == sizeof($uRoles) ) {
                        $model->setRoleIds($uRoles)
                            ->setRoleUserId($model->getUserId())
                            ->saveRelations();
                    } else if ( sizeof($uRoles) > 1 ) {
                        //@FIXME: stupid fix of previous multi-roles logic.
                        //@TODO:  make proper DB upgrade in the future revisions.
                        $rs = array();
                        $rs[0] = $uRoles[0];
                        $model->setRoleIds( $rs )->setRoleUserId( $model->getUserId() )->saveRelations();
                    }
                }
                Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The user has been saved.'));
                Mage::getSingleton('adminhtml/session')->setUserData(false);
                $this->_redirect('*/*/');
                return;
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setUserData($data);
                $this->_redirect('*/*/edit', array('user_id' => $model->getUserId()));
                return;
            }
        }
        $this->_redirect('*/*/');
    }
}

Now create a directory named 'avatar' inside media folder and continue with your installer to generate field to your desired place.

Hope it will work for you.

[EDITED]

/app/code/local/a2bizz/Adminhtml/Block/Permissions/User/Edit/Form.php
<?php
class A2bizz_Adminhtml_Block_Permissions_User_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{

    protected function _prepareForm()
    {
        $form = new Varien_Data_Form(array('id' => 'edit_form', 
                                           'action' => $this->getData('action'), 
                                           'method' => 'post',
                                           'enctype' => 'multipart/form-data'
                                           )
                                     );
        $form->setUseContainer(true);
        $this->setForm($form);
        return parent::_prepareForm();
    }

}
Related Topic