How to upload multiple image into database in zend framework - php

I have some code that store multiple image into directory but not inserting into database .please help me out.
i am using table gateway. if anyone give me proper and easy way to insert multiple image into database.
this is my controller
StudentController.php
public function addAction() {
$form = new StudentForm();
$request = $this->getRequest();
if ($request->isPost()) {
$student = new Student();
$images=$this->convert_multi_array($request->getFiles()->toArray());
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
$student->exchangeArray($form->getData());
$this->getStudentTable()->saveStudent($student);
// return $this->redirect()->toRoute('student');
print_r($images);
// print_r($post);
echo "working";
}else{
echo "not working";
}
}
return array('form' => $form,);
}
And this is Model
Student.php
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add(
$factory->createInput(array(
'name' => 'image',
'required' => true,
))
);
$inputFilter->add(array(
'name' => 'name',
'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(array(
'name' => 'department',
'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(array(
'name' => 'marks',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
And
public function exchangeArray($data){
$this->id = (isset($data['id']))?$data['id']:null;
//// image////
if(!empty($data['image'])) {
if(is_array($data['image'])) {
$this->image = str_replace("./public/tmpuploads/", "",
$data['image']['tmp_name']);
} else {
$this->image = $data['image'];
}
} else {
$data['image'] = null;
}
$this->name = (isset($data['name']))?$data['name']:null;
$this->department = (isset($data['department']))?$data['department']:null;
$this->marks = (isset($data['marks']))?$data['marks']:null;
}
public function getArrayCopy() {
return get_object_vars($this);
}
my Student Form-
StudentForm.php
namespace Student\Form;
use Zend\InputFilter;
use Zend\Form\Form;
use Zend\Form\Element;
class StudentForm extends Form {
public function __construct($name = null, $options = array())
{
parent::__construct($name, $options);
$this->addElements();
$this->setInputFilter($this->createInputFilter());
}
public function addElements()
{
$image = new Element\File('image');
$image->setLabel('Avatar Image Upload')
->setAttribute('id', 'image-file')
->setAttribute('multiple', true);
$this->add($image);
$name = new Element\Text('name');
$name->setLabel('Name');
$this->add($name);
$department = new Element\Text('department');
$department->setLabel('Department');
$this->add($department);
$marks = new Element\Text('marks');
$marks->setLabel('Marks');
$this->add($marks);
}
public function createInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
// File Input
$image = new InputFilter\FileInput('image');
$image->setRequired(true);
$image->getFilterChain()->attachByName(
'filerenameupload',
array(
'target' => './public/tmpuploads/',
'overwrite' => true,
'use_upload_name' => true,
)
);
$inputFilter->add($image);
// Text Input
$name = new InputFilter\Input('name');
$name->setRequired(true);
$inputFilter->add($name);
// Text Input
$department = new InputFilter\Input('department');
$department->setRequired(true);
$inputFilter->add($department);
// Text Input
$marks = new InputFilter\Input('marks');
$marks->setRequired(true);
$inputFilter->add($marks);
return $inputFilter;
}
}
`````

As i understand your code you have to first upload image and then you have to make comma separated string like this
its only example code
$imageString = '';
for($i=0; $i<count($_FILES['file']['name']); $i++){
$extension = explode('.', basename( $_FILES['file']['name'][$i]));
$imageName = md5(uniqid()) . "." . $extension[count($extension)-1];
$path = $path . $imageName;
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $path )) {
$imageString .= $imageName.", ";
} else{
echo "Error in Upload";
}
}
$imageName = rtrim($imageName,", ");
// now you can use imageName in insert query.

Related

Problems adding a field to attachments form Prestashop 1.6

im trying to make a module for prestashop overriding some functions. I wanna add a field to the attachment form in the back office named "category". I make this modifications:
Attachments.php: (Added the new field in the object)
<?php
class Attachment extends AttachmentCore
{
public $category;
public static $definition = array(
'table' => 'attachment',
'primary' => 'id_attachment',
'multilang' => true,
'fields' => array(
'file' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 40),
'mime' => array('type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'required' => true, 'size' => 128),
'file_name' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 128),
'file_size' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
/* Lang fields */
'name' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 32),
'description' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCleanHtml'),
'category' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 128),
),
);
}
AdminProductsController.php: (integrating the field)
<?php
class AdminProductsController extends AdminProductsControllerCore
{
public function initFormAttachments($obj)
{
if (!$this->default_form_language) {
$this->getLanguages();
}
$data = $this->createTemplate($this->tpl_form);
$data->assign('default_form_language', $this->default_form_language);
if ((bool)$obj->id) {
if ($this->product_exists_in_shop) {
$attachment_name = array();
$attachment_description = array();
$attachment_category = array(); //variable
foreach ($this->_languages as $language) {
$attachment_name[$language['id_lang']] = '';
$attachment_description[$language['id_lang']] = '';
$attachment_category[$language['id_lang']] = '';
}
$iso_tiny_mce = $this->context->language->iso_code;
$iso_tiny_mce = (file_exists(_PS_JS_DIR_.'tiny_mce/langs/'.$iso_tiny_mce.'.js') ? $iso_tiny_mce : 'en');
$attachment_uploader = new HelperUploader('attachment_file');
$attachment_uploader->setMultiple(false)->setUseAjax(true)->setUrl(
Context::getContext()->link->getAdminLink('AdminProducts').'&ajax=1&id_product='.(int)$obj->id
.'&action=AddAttachment')->setPostMaxSize((Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024))
->setTemplate('attachment_ajax.tpl');
$data->assign(array(
'obj' => $obj,
'table' => $this->table,
'ad' => __PS_BASE_URI__.basename(_PS_ADMIN_DIR_),
'iso_tiny_mce' => $iso_tiny_mce,
'languages' => $this->_languages,
'id_lang' => $this->context->language->id,
'attach1' => Attachment::getAttachments($this->context-
>language->id, $obj->id, true),
'attach2' => Attachment::getAttachments($this->context->language->id, $obj->id, false),
'attch_cat' => Attachment::getAttachments($this->context->language->id, $obj->id, false),
'default_form_language' => (int)Configuration::get('PS_LANG_DEFAULT'),
'attachment_name' => $attachment_name,
'attachment_description' => $attachment_description,
'attachment_category' => $attachment_category,
'attachment_uploader' => $attachment_uploader->render()
));
} else {
$this->displayWarning($this->l('You must save the product in this shop before adding attachements.'));
}
} else {
$this->displayWarning($this->l('You must save this product before adding attachements.'));
}
$this->tpl_form_vars['custom_form'] = $data->fetch();
}
public function ajaxProcessAddAttachment()
{
if ($this->tabAccess['edit'] === '0') {
return die(Tools::jsonEncode(array('error' => $this->l('You do not have the right permission'))));
}
if (isset($_FILES['attachment_file'])) {
if ((int)$_FILES['attachment_file']['error'] === 1) {
$_FILES['attachment_file']['error'] = array();
$max_upload = (int)ini_get('upload_max_filesize');
$max_post = (int)ini_get('post_max_size');
$upload_mb = min($max_upload, $max_post);
$_FILES['attachment_file']['error'][] = sprintf(
$this->l('File %1$s exceeds the size allowed by the server. The limit is set to %2$d MB.'),
'<b>'.$_FILES['attachment_file']['name'].'</b> ',
'<b>'.$upload_mb.'</b>'
);
}
$_FILES['attachment_file']['error'] = array();
$is_attachment_name_valid = false;
$attachment_names = Tools::getValue('attachment_name');
$attachment_descriptions = Tools::getValue('attachment_description');
$attachment_categories = Tools::getValue('attachment_category');
echo '<script>console.log('.$attachment_categories.')</script>';
//var_dump($attachment_categories);
if (!isset($attachment_names) || !$attachment_names) {
$attachment_names = array();
}
if (!isset($attachment_descriptions) || !$attachment_descriptions) {
$attachment_descriptions = array();
}
if(!isset($attachment_categories) || !$attachment_categories){
$attachment_categories = array();
}
foreach ($attachment_names as $lang => $name) {
$language = Language::getLanguage((int)$lang);
if (Tools::strlen($name) > 0) {
$is_attachment_name_valid = true;
}
if (!Validate::isGenericName($name)) {
$_FILES['attachment_file']['error'][] = sprintf(Tools::displayError('Invalid name for %s language'), $language['name']);
} elseif (Tools::strlen($name) > 32) {
$_FILES['attachment_file']['error'][] = sprintf(Tools::displayError('The name for %1s language is too long (%2d chars max).'), $language['name'], 32);
}
}
foreach ($attachment_descriptions as $lang => $description) {
$language = Language::getLanguage((int)$lang);
if (!Validate::isCleanHtml($description)) {
$_FILES['attachment_file']['error'][] = sprintf(Tools::displayError('Invalid description for %s language'), $language['name']);
}
}
foreach ($attachment_categories as $lang => $category) {
$language = Language::getLanguage((int)$lang);
if (!Validate::isGenericName($category)) {
$_FILES['attachment_file']['error'][] = sprintf(Tools::displayError('Invalid category for %s language'), $language['name']);
}
}
if (!$is_attachment_name_valid) {
$_FILES['attachment_file']['error'][] = Tools::displayError('An attachment name is required.');
}
if (empty($_FILES['attachment_file']['error'])) {
if (is_uploaded_file($_FILES['attachment_file']['tmp_name'])) {
if ($_FILES['attachment_file']['size'] > (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024)) {
$_FILES['attachment_file']['error'][] = sprintf(
$this->l('The file is too large. Maximum size allowed is: %1$d kB. The file you are trying to upload is %2$d kB.'),
(Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024),
number_format(($_FILES['attachment_file']['size'] / 1024), 2, '.', '')
);
} else {
do {
$uniqid = sha1(microtime());
} while (file_exists(_PS_DOWNLOAD_DIR_.$uniqid));
if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_.$uniqid)) {
$_FILES['attachment_file']['error'][] = $this->l('File copy failed');
}
#unlink($_FILES['attachment_file']['tmp_name']);
}
} else {
$_FILES['attachment_file']['error'][] = Tools::displayError('The file is missing.');
}
if (empty($_FILES['attachment_file']['error']) && isset($uniqid)) {
$attachment = new Attachment();
foreach ($attachment_names as $lang => $name) {
$attachment->name[(int)$lang] = $name;
}
foreach ($attachment_descriptions as $lang => $description) {
$attachment->description[(int)$lang] = $description;
}
foreach ($attachment_categories as $lang => $category) {
$attachment->category[(int)$lang] = $category;
}
$attachment->file = $uniqid;
$attachment->mime = $_FILES['attachment_file']['type'];
$attachment->file_name = $_FILES['attachment_file']['name'];
if (empty($attachment->mime) || Tools::strlen($attachment->mime) > 128) {
$_FILES['attachment_file']['error'][] = Tools::displayError('Invalid file extension');
}
if (!Validate::isGenericName($attachment->file_name)) {
$_FILES['attachment_file']['error'][] = Tools::displayError('Invalid file name');
}
if (Tools::strlen($attachment->file_name) > 128) {
$_FILES['attachment_file']['error'][] = Tools::displayError('The file name is too long.');
}
if (empty($this->errors)) {
$res = $attachment->add();
if (!$res) {
$_FILES['attachment_file']['error'][] = Tools::displayError('This attachment was unable to be loaded into the database.');
} else {
$_FILES['attachment_file']['id_attachment'] = $attachment->id;
$_FILES['attachment_file']['filename'] = $attachment->name[$this->context->employee->id_lang];
$id_product = (int)Tools::getValue($this->identifier);
$res = $attachment->attachProduct($id_product);
if (!$res) {
$_FILES['attachment_file']['error'][] = Tools::displayError('We were unable to associate this attachment to a product.');
}
}
} else {
$_FILES['attachment_file']['error'][] = Tools::displayError('Invalid file');
}
}
}
die(Tools::jsonEncode($_FILES));
}
}
}
AdminAttachmentsController:
class AdminAttachmentsController extends AdminAttachmentsControllerCore
{
public function renderForm()
{
if (($obj = $this->loadObject(true)) && Validate::isLoadedObject($obj)) {
/** #var Attachment $obj */
$link = $this->context->link->getPageLink('attachment', true, null, 'id_attachment='.$obj->id);
if (file_exists(_PS_DOWNLOAD_DIR_.$obj->file)) {
$size = round(filesize(_PS_DOWNLOAD_DIR_.$obj->file) / 1024);
}
}
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Attachment'),
'icon' => 'icon-paper-clip'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Filename'),
'name' => 'name',
'required' => true,
'lang' => true,
'col' => 4
),
array(
'type' => 'textarea',
'label' => $this->l('Description'),
'name' => 'description',
'lang' => true,
'col' => 6
),
array(
'type' => 'text',
'label' => $this->l('Attachment category'),
'name' => 'category',
'required' => false,
'col' => 4,
'hint' => $this->l('Add a category')
),
array(
'type' => 'file',
'file' => isset($link) ? $link : null,
'size' => isset($size) ? $size : null,
'label' => $this->l('File'),
'name' => 'file',
'required' => true,
'col' => 6
),
),
'submit' => array(
'title' => $this->l('Save'),
)
);
return AdminController::renderForm();
}
}
Attachments.tpl:(only the category part)
<div class="form-group">
<label class="control-label col-lg-3 required" for="attch_category_{$id_lang}">
{l s='Create category'}
</label>
<div class="col-lg-9">
{include
file="controllers/products/textarea_lang.tpl"
languages=$languages
input_name="attachment_category"
input_value=$attachment_category
}
</div>
The problem is when I try to upload the file, i recieve this error:
Unexpected token < in JSON at position 0
And in the chrome inspect network tab I have Property Attachment->category is empty
Any Idea of what is the problem?

PrestaShop: How to remove 'new' button from my backoffice controller

I want to remove the add button from the bo list view toolbar in prestashop is there any way ,(only for my page which I created as a seperate module
or atleast when I click the add button it must not do anything .
require_once(_PS_MODULE_DIR_.'addsocialmedia/addsocialmedia.php');
require_once(_PS_MODULE_DIR_.'addsocialmedia/classes/SocialMedia.php');
class AdminAddSocialMediaController extends ModuleAdminController
{
public $module;
public $html;
public $tabName = 'renderForm';
public function __construct()
{
$this->tab = 'socialmedia';
$this->module = new addsocialmedia();
$this->addRowAction('edit');
$this->explicitSelect = false;
$this->context = Context::getContext();
$this->id_lang = $this->context->language->id;
$this->lang = false;
$this->ajax = 1;
$this->path = _MODULE_DIR_.'addsocialmedia';
$this->default_form_language = $this->context->language->id;
$this->table = _DB_KITS_PREFIX_.'social_media';
$this->className = 'SocialMedia';
$this->identifier = 'id_social_media';
$this->allow_export = true;
$this->_select = '
id_social_media,
name_social_media,
social_media_url,
status
';
$this->name = 'SocialMedia';
$this->bootstrap = true;
$this->initList();
parent::__construct();
}
private function initList()
{
$this->fields_list =
array(
'id_social_media' => array(
'title' => $this->l('Social Media ID'),
'width' => 25,
'type' => 'text',
),
'name_social_media' => array(
'title' => $this->l('Social Media Name'),
'width' => 140,
'type' => 'text',
),
'social_media_url' => array(
'title' => $this->l('Social Media Url'),
'width' => 140,
'type' => 'text',
),
'status' => array(
'title' => $this->l('Enabled'),
'align' => 'text-center',
'status' => 'status',
'type' => 'bool',
'orderby' => false,
'callback' => 'changeStatus',
),
);
$helper = new HelperList();
$helper->shopLinkType = '';
$helper->simple_header = true;
// Actions to be displayed in the "Actions" column
$helper->actions = array('edit');
$helper->identifier = 'code';
$helper->show_toolbar = true;
$helper->title = 'HelperList';
$helper->table = $this->name.'check';
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
return $helper;
}
public function initPageHeaderToolbar()
{
$this->page_header_toolbar_title = $this->l('Edit Social Media Image and url/link');
parent::initPageHeaderToolbar();
}
public function initToolbar()
{
parent::initToolbar();
$this->context->smarty->assign('toolbar_scroll', 1);
$this->context->smarty->assign('show_toolbar', 1);
$this->context->smarty->assign('toolbar_btn', $this->toolbar_btn);
}
public function postProcess()
{
parent::postProcess();
$id = (int)Tools::getValue('id_social_media');
$file = Tools::fileAttachment('social_media_image_name');
if (!empty($file['name']) && $id > 0)
{
if (ImageManager::validateUpload($file, Tools::convertBytes(ini_get('upload_max_filesize'))))
die('Image size exceeds limit in your Bigticket Back Office settings');
if (!is_dir('../modules/addsocialmedia/social_media_img'))
#mkdir('../modules/addsocialmedia/social_media_img', 0777, true);
if (!is_dir('../modules/addsocialmedia/social_media_img/'.$id))
#mkdir('../modules/addsocialmedia/social_media_img/'.$id, 0777, true);
$path = '../modules/addsocialmedia/social_media_img/'.$id.'/';
$absolute_path = $path.$file['name'];
move_uploaded_file($file['tmp_name'], $absolute_path);
$imgPath = 'social_media_img/'.$id.'/'.$file['name'];
//Save in DB if needed
Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.''._DB_KITS_PREFIX_.'social_media`
SET `social_media_image_name` = "'.pSQL($imgPath).'"
WHERE `id_social_media` = '.(int)$id);
}
if (Tools::isSubmit('changeStatusVal') && $this->id_object) {
if ($this->tabAccess['edit'] === '1') {
$this->action = 'change_status_val';
d("chnage");
} else {
$this->errors[] = Tools::displayError('You do not have permission to change this.');
}
}
}
//Call back for change status
public function changeStatus($value, $socialMedia)
{
return '<a class="list-action-enable '.($value ? 'action-enabled' : 'action-disabled').'" href="index.php?'.htmlspecialchars('tab=AdminAddSocialMedia&id_social_media='
.(int)$socialMedia['id_social_media'].'&changeStatusVal&token='.Tools::getAdminTokenLite('AdminAddSocialMedia')).'">
'.($value ? '<i class="icon-check"></i>' : '<i class="icon-remove"></i>').
'</a>';
}
/**
* Toggle the Social media to Enabled or Disabled flag- Here the update action occurs
*/
public function processChangeStatusVal()
{
d("hii");
$socialMedia = new SocialMedia($this->id_object);
if (!Validate::isLoadedObject($socialMedia)) {
$this->errors[] = Tools::displayError('An error occurred while updating the Status .');
}
d("going to change");
$socialMedia->status = $socialMedia->status ? 0 : 1;
if (!$socialMedia->update()) {
$this->errors[] = Tools::displayError('An error occurred while updating Social Media Status .');
}
Tools::redirectAdmin(self::$currentIndex.'&token='.$this->token);
}
//When a winner is deleted , delete the image
public function processDelete()
{
$ob=parent::processDelete();
PrestaShopLogger::addLog(sprintf($this->l('%s DELETED social media IMAGE', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$id, true, (int)$this->context->employee->id);
if ($ob->deleted==1){
$id = (int)Tools::getValue('id_social_media');
$unlink_path = '../modules/addsocialmedia/social_media_img/'.$id.'/';
unlink($unlink_path); // this must delete the img folder from the winners module dir
//log the delete
PrestaShopLogger::addLog(sprintf($this->l('%s DELETED social media IMAGE', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$id, true, (int)$this->context->employee->id);
}
}
//If the user updates the image delete the old image from server
public function processUpdate(){
//d("updating..");
$id = (int)Tools::getValue('id_social_media');
$file = Tools::fileAttachment('social_media_image_name');
if (!empty($file['name']) && $id > 0)
{
$get_previous_image_sql = 'SELECT social_media_image_name FROM `'._DB_PREFIX_._DB_KITS_PREFIX_.'social_media`
where id_social_media='.$id.'';
$get_previous_image_path = Db::getInstance()->getValue($get_previous_image_sql) ;
//d($get_previous_image_path);
$unlink_path = '../modules/addsocialmedia/'.$get_previous_image_path.'';
unlink($unlink_path); // this must delete the img folder from the winners module dir
//log the delete when deleting
PrestaShopLogger::addLog(sprintf($this->l('%s DELETED social media IMAGE while updating new image', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$id, true, (int)$this->context->employee->id);
}
}
// This form is populated when add or edit is clicked
public function renderForm()
{
$firstArray =
array(array(
'type' => 'text',
'label' => $this->l('Name'),
'name' => 'name_social_media',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()##"°{}_$%:'
),
array(
'type' => 'text',
'label' => $this->l('Social Media URL'),
'name' => 'social_media_url',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()##"°{}_$%:'
),
array(
'type' => 'file',
'label' => $this->l('Social Media Image'),
'name' => 'social_media_image_name',
'display_image' => true,
'required' => false,
'desc' => $this->l('Add .JPG or .PNG File Format.Prefered Width:381 pixels and Height 285 pixels.Prefered File size -50KB .'),
'hint' => array(
$this->l('Add .JPG or .PNG File Format.Prefered Width:381 pixels and Height 285 pixels.Prefered File size -50KB .')
)
),
array(
'type' => 'switch',
'label' => $this->l('Enable Or Disable this Social Media'),
'name' => 'status',
'required' => false,
'class' => 't',
'is_bool' => true,
'values' => array(
array(
'id' => 'status_on',
'value' => 1,
'label' => $this->l('Enabled')
),
array(
'id' => 'status_off',
'value' => 0,
'label' => $this->l('Disabled')
)
),
'hint' => $this->l('Enable or disable this Social Media From front END.')
),
);
if (Tools::getIsset('addkits_social_media') ){
$secondArray = array(
array(
'type' => 'hidden',
'label' => $this->l('Add Date'),
'name' => 'date_add',
'col' => '4',
'values'=>date("Y-m-d H:i:s"),
'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()##"°{}_$%:'
),
array(
'type' => 'hidden',
'label' => $this->l('Winner Image Name'),
'name' => 'social_media_image_name',
'col' => '4',
'values'=>"default_value"
)
);
$mainArray = array_merge($firstArray,$secondArray);
}
if (Tools::getIsset('updatekits_social_media') ){
$thirdArray = array(
array(
'type' => 'hidden',
'label' => $this->l('Update Date'),
'name' => 'date_upd',
'col' => '4',
'values'=>date("Y-m-d H:i:s"),
'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()##"°{}_$%:'
),
array(
'type' => 'hidden',
'label' => $this->l('Winner Image Name'),
'name' => 'social_media_image_name',
'col' => '4',
'values'=>"default_value"
));
$mainArray = array_merge($firstArray,$thirdArray);
}
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => $this->l('Configure your Social Media Image and URL'),
'icon' => 'icon-user'
),
'input' => $mainArray
);
//Assign value to hidden
$this->fields_value['date_add'] = $date = date("Y-m-d H:i:s");
$this->fields_value['social_media_image_name'] ="default_image.jpg";
$this->fields_form['submit'] = array(
'title' => $this->l('Save'),
);
$date = date("Y-m-d H:i:s");
$this->addJqueryUI('ui.datepicker');
return parent::renderForm();
}
You have to override the initToolbar method:
public function initToolbar() {
parent::initToolbar();
unset( $this->toolbar_btn['new'] );
}
Cheers ;)
Yes it is at the helper of your module. Could you put the code of the page so I am indicating or remove. Otherwise solution less "clean" applied CSS to hide this button.
Regards,

Zend framework 2 - make form fields sticky when there is error submitting form

I am working on Zend framework 2. I have one form for saving shop information. I have validated the form using Zend's input filters. My issue is when I enter wrong data into the field or keep a mandatory field blank then it properly displays the error but entire form gets blank again.
I want the previously entered values as it is when the form shows errors.
Following is the function that renders the form.
public function settingsAction()
{
try {
$message = '';
$error = '';
$id = 0;
try {
$shop = $this->_getShop();
} catch (\Exception $ex) {
AppLogger::log($ex);
$error = $ex->getMessage();
}
if ($shop) {
$id = $shop->id;
}
else {
//redirect to login page
return $this->redirect()->toUrl($this->_getDomainUrl());
}
$form = new ShopForm($this->serviceLocator);
$config = $this->serviceLocator->get('config');
$apiUrls = $config['apiUrls'];
$request = $this->getRequest();
if ($request->isPost())
{
if (!$shop)
$shop = new Shop();
$form->setInputFilter($shop->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$url = $shop->url;
$token = $shop->token;
$config_id = $shop->config_id;
$password = $shop->password;
$shop->exchangeArray($form->getData(),false);
$shop->url = $url;
$shop->token = $token;
$shop->config_id = $config_id;
DAL::getShopTable($this->serviceLocator)->saveShop($shop);
$message = "Your settings has been saved successfully.";
}
else {
$error = 'There are values that need to be completed before you can save/update your preferences.';
foreach($form->getMessages() as $msg) {
$error = $error . $msg;
}
}
}
if ($shop)
{
echo "<pre>";print_r($shop);
$shop->selected_countries = unserialize($shop->selected_countries);
$form->bind($shop);
$form->get('return_address_country')->setAttribute('value', $shop->return_address_country);
}
$form->get('submit')->setAttribute('value', 'Save');
return array(
'id' => $id,
'form' => $form,
'apiUrls' => $apiUrls,
'message' => $message,
'uri' => $this->_selfURL(),
"error" => $error
);
}
catch (\Exception $ex) {
AppLogger::log($ex);
throw $ex;
}
}
I have used $form->setInputFilter($shop->getInputFilter()); for validations. A snippet from getInputFilter() is as follows:
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'ship_to_code',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 0,
'max' => 50,
),
),
),
));
$inputFilter->add(array(
'name' => 'default_phone',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 0,
'max' => 50,
),
),
),
));
$inputFilter->add(array(
'name' => 'max_records_per_file',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
}
And the form is
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'ship_to_code',
'type' => 'Text',
'options' => array(
'label' => 'Ship-To Code',
),
));
$this->add(array(
'name' => 'default_phone',
'type' => 'Text',
'options' => array(
'label' => 'Default Phone',
),
));
You can use the setdata() method of form in your setting action.
Here's updated code
if ($shop)
{
// echo "<pre>";print_r($shop);
// $shop->selected_countries = unserialize($shop->selected_countries);
$form->bind($shop);
$form->setData($request->getPost()); // set post data to form
}

ZendFramework 2 - How to edit form data with fieldsets?

I'm trying to learn ZF2, and I am not able to edit the data in the edit form. I have two classes Pessoa and Endereco and I have a form to edit the data, but it only changes the data related to Pessoa, those about the Endereco is stored as blank.
And when trying to add a new record (add action) i get the following error:
Fatal error: Cannot use object of type Pessoa\Model\Pessoa as array in /opt/lampp/htdocs/cad/module/Pessoa/src/Pessoa/Model/Pessoa.php on line 23
Pessoa.php
class Pessoa
{
public $id;
public $nome;
public $dtNasc;
public $endereco;
protected $inputFilter;
public function __construct()
{
$this->endereco = new Endereco();
}
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->nome = (!empty($data['nome'])) ? $data['nome'] : null;
$this->dtNasc = (!empty($data['dtNasc'])) ? $data['dtNasc'] : null;
//$this->getEndercoInstance();
$this->endereco->exchangeArray($data);
/*if (isset($data["endereco"]))
{
if (!is_object($this->endereco)) $this->endereco = new Endereco();
$this->endereco->exchangeArray($data["endereco"]);
}*/
}
public function getArrayCopy()
{
$data = get_object_vars($this);
if (is_object($this->endereco)) {
$data["endereco"] = $this->endereco->getArrayCopy();
}
return $data;
}
public function setEndereco($end)
{
$this->endereco = $end;
}
private function getEndercoInstance()
{
$di = new Zend\Di;
$config = new Zend\Di\Configuration(array(
'instance' => array(
'Pessoa' => array(
// letting Zend\Di find out there's a $bar to inject where possible
'parameters' => array('endereco' => 'Endereco\Model\Endereco'),
)
)
));
$config->configure($di);
$pessoa = $di->get('Pessoa');
$this->endereco = $pessoa->endereco;
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'nome',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
Endereco.php
class Endereco
{
public $rua;
public $bairro;
public function exchangeArray($data)
{
$this->rua = (!empty($data["rua"])) ? $data["rua"] : null;
$this->bairro = (!empty($data["bairro"])) ? $data["bairro"] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
PessoaController.php add e edit actions
public function addAction()
{
$form = new PessoaForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost()) {
$pessoa = new Pessoa();
//$form->setInputFilter($pessoa->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$pessoa->exchangeArray($form->getData());
$this->getPessoaTable()->savePessoa($pessoa);
// Redirect to list of pessoa
return $this->redirect()->toRoute('pessoa');
}
}
return array('form' => $form);
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('pessoa', array(
'action' => 'add'
));
}
try {
$pessoa = $this->getPessoaTable()->getPessoa($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('pessoa', array(
'action' => 'index'
));
}
$form = new PessoaForm();
$form->bind($pessoa);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
//$form->setInputFilter($pessoa->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getPessoaTable()->savePessoa($pessoa);
// Redirect to list of pessoa
return $this->redirect()->toRoute('pessoa');
}else{
echo "not valid";
}
}
return array(
'id' => $id,
'form' => $form,
);
}
EnderecoFieldSet.php
class EnderecoFieldSet extends Fieldset
{
public function __construct($name = null)
{
parent::__construct('endereco');
$this->setHydrator(new ArraySerializableHydrator())
->setObject(new Endereco());
$this->add(array(
'name' => 'rua',
'option' => array(
'label' => 'Rua: ',
),
));
$this->add(array(
'name' => 'bairro',
'option' => array(
'label' => 'Bairro: ',
),
));
}
}
PessoaFieldSet.php
class PessoaFieldSet extends Fieldset
{
//public $endereco;
public function __construct()
{
//$this->endereco = new Endereco()
$this->init();
}
public function init()
{
parent::__construct('pessoa');
$this->setHydrator(new ArraySerializableHydrator())
->setObject(new Pessoa());
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'nome',
'type' => 'Text',
'options' => array(
'label' => 'Nome:',
),
'attributes' => array(
'required' => 'required',
),
));
$this->add(array(
'name' => 'dtNasc',
'type' => 'Text',
'options' => array(
'label' => 'Data Nascimento:',
),
));
$this->add(array(
'type' => 'Pessoa\Form\EnderecoFieldSet',
'name' => 'endereco',
'options' => array(
'label' => 'endereco',
),
));
}
PessoaForm.php
class PessoaForm extends Form
{
public function __construct()
{
$this->init();
}
public function init()
{
// we want to ignore the name passed
parent::__construct('pessoa_form');
$this->setHydrator(new ArraySerializableHydrator());
//->setInputFilter(new InputFilter());
$this->add(array(
'type' => 'Pessoa\Form\PessoaFieldSet',
'options' => array(
'use_as_base_fieldset' => true
)
));
$this->add(array(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf'
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
And trying to add a new record (add action) i get the following error:
Fatal error: Cannot use object of type Pessoa\Model\Pessoa as array in /opt/lampp/htdocs/cad/module/Pessoa/src/Pessoa/Model/Pessoa.php on line 23
Please, can anyone help me?
So let me explain better my self,
You are sending an array to the method
exchangeArray($data);
but $data is not an array;
Example of Array:
$data['username'] = 'someuser';
$data['email'] = 'someuser#someuser.com';
$data['phone'] = '235346346';
print_r($data);die;
//output:
//Array ( [username] => someuser [email] => someuser#someuser.com [phone] => 235346346 )
Example Object:
$data['username'] = 'someuser';
$data['email'] = 'someuser#someuser.com';
$data['phone'] = '235346346';
$object = (object)$data;
print_r($object);die;
//Output
//stdClass Object ( [username] => someuser [email] => someuser#someuser.com [phone] => 235346346 )
So i reproduce part of the code you have above and i gave to the method exchangeArray($data); of type Array and i got no errors then i gave to the method exchangeArray($object); and the result was
Fatal error: Cannot use object of type stdClass as array in /blah/blah/... on line 39
So Basically in your method you are passing $data of type object and not Array

Adapter Db\NoRecordExists Error [Zend 2]

Catchable fatal error: Argument 1 passed to
Zend\Validator\Db\AbstractDb::setAdapter() must be an instance of
Zend\Db\Adapter\Adapter, null given, called in
/home2/mapasgua/vendor/zendframework/zendframework/library/Zend/Validator/AbstractValidator.php
on line 142 and defined in
/home2/mapasgua/vendor/zendframework/zendframework/library/Zend/Validator/Db/AbstractDb.php
on line 168
Module.php
<?php
namespace User;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\ModuleRouteListener;
use User\Model\UsersTable;
use User\Model\Users;
class Module
{
public function onBootstrap(MvcEvent $e)
{
ini_set('date.timezone', 'America/Sao_Paulo');
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controllerClass = get_class($controller);
$moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
$config = $e->getApplication()->getServiceManager()->get('config');
if (isset($config['module_layouts'][$moduleNamespace])) {
$controller->layout($config['module_layouts'][$moduleNamespace]);
}
}, 100);
}
public function getAutoloaderConfig()
{
return array(
// 'Zend\Loader\ClassMapAutoloader' => array(
// __DIR__ . '/autoload_classmap.php',
// ),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'User\Model\UsersTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new UsersTable($dbAdapter);
return $table;
},
'User\Model\Users' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$users = new Users();
$users->setDbAdapter($dbAdapter);
return $users;
},
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
}
Users.php
<?php
namespace User\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\Db\Adapter\Adapter;
use Zend\Validator\Db\AbstractDb;
class Users implements InputFilterAwareInterface
{
public $id;
public $name;
public $username;
public $password;
protected $inputFilter;
public $_dbAdapter;
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->name = (isset($data['name'])) ? $data['name'] : null;
$this->username = (isset($data['username'])) ? $data['username'] : null;
$this->password = (isset($data['password'])) ? $data['password'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function setDbAdapter($dbAdapter)
{
$this->_dbAdapter = $dbAdapter;
}
public function getDbAdapter()
{
return $this->_dbAdapter;
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
'message' => 'Endereço de e-mail invalido',
),
),
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'users',
'field' => 'username',
'adapter' => $this->getDbAdapter(),
'exclude' => array(
'field' => 'id',
'value' => !is_null( $this->id ) && !empty( $this->id ) ? $this->id : 0,
),
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'retype-password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
),
),
array(
'name' => 'Identical',
'options' => array(
'token' => 'password', //I have tried $_POST['password'], but it doesnt work either
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
UserController.php
namespace User\Controller;
<?php
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
use Zend\Authentication\Result as Result;
use Zend\Mail;
use User\Form\LoginForm;
use User\Form\RegisterForm;
use User\Form\RecuperarForm;
use User\Model\Users;
class UserController extends AbstractActionController
{
protected $usersTable;
public function configAction()
{
$auth = new AuthenticationService();
$form = new RegisterForm();
$identity = null;
if ($auth->hasIdentity()) {
$dados = $this->getUsersTable()->getUser($auth->getIdentity());
$request = $this->getRequest();
if ($request->isPost()) {
$users = new Users();
$post = $request->getPost();
$form->setInputFilter($users->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$users->exchangeArray($post);
$this->getUsersTable()->saveUsers($users);
$this->flashMessenger()->addMessage("Configurações atualizadas com sucesso.");
return $this->redirect()->toRoute('painel');
}
} else {
$post = array(
'id' => $dados->id,
'name' => $dados->name,
'username' => $dados->username,
);
$form->setData($post);
}
} else {
return $this->redirect()->toRoute('login');
}
return array(
'form' => $form,
);
}
Your problem is you have defined a factory for Users but you don't use it. The line $users = new Users(); directly instantiates the object without using your factory.
Change it to
$users = $this->getServiceLocator()->get('User\Model\Users');
As your object relies on Zend\Db\Adapter\Adapter you need your factory to inject this for you.

Categories