Prestashop - fields_value added only single char - prestashop

I have problem with prestashop and form helper. I have form with two input text, i could add default value with fields_value. Unfortunately it doesn't work. My form:
public function displayForm()
{
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$fields_form = array();
$fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('My module settings')
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Box Description: '),
'name' => 'description',
'lang' => true,
),
array(
'type' => 'text',
'label' => $this->l('Box Description: '),
'name' => 'test_name',
'lang' => true,
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right'
)
);
$languages = Language::getLanguages();
$helper = new HelperForm();
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
$helper->languages = $this->context->controller->getLanguages();
$helper->title = $this->l('tester2');
$helper->show_toolbar = true; // false -> remove toolbar
$helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen.
$helper->submit_action = 'homepage_settings';
$helper->tpl_vars = array(
'fields_value' => array('description' => $this->l('hello'), 'test_name' => 'tester2'),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
return $helper->generateForm($fields_form);
}
When i install module, and go to module configuration then i see 2 form input text with single char instead my text
What am I doing wrong? Next question is what i can do, to my module to make my module work in multi store mode? In the final version, the data in the form will be supplemented from the database, but I want to find out why it does not complete the fields with the whole text.

Your fields are multi languages.
try this:
'fields_value' => array(
'description' => array(1 => $this->l('hello')), 'test_name' => array(1 => 'tester2')),

Related

Redirect user after saving data in admin controller Prestashop

I have an admin controller which displays the list of data on clicking edit on an entry or adding a new entry I am showing renderForm() but after saving the data (either by edit or add) I want to redirect the user to another controller in place of showing the same controller list.
Bellow is the code which I am currently using for example of my requirements I trying to do something which I have done below in initcontent() but that is not working so I want to know where should I call this in place of initcontent()
<?php
/**
* The file is controller. Do not modify the file if you want to upgrade the module in future
*
* #author Globo Jsc <contact#globosoftware.net>
* #copyright 2016 Globo., Jsc
* #link http://www.globosoftware.net
* #license please read license in file license.txt
*/
include_once(_PS_MODULE_DIR_ . 'cardelivery/classes/AdditionalServicesModel.php');
class AdminAdditionalServiceController extends ModuleAdminControllerCore {
public $name;
public function __construct() {
$this->name = 'AdminAdditionalService';
$this->className = 'AdditionalServicesModel';
$this->table = 'additional_service';
$this->meta_title = $this->l('Additional Services');
$this->deleted = false;
$this->explicitSelect = true;
$this->context = Context::getContext();
$this->bootstrap = true;
$this->_defaultOrderBy = 'id_additional_service';
$this->filter = true;
if (Shop::isFeatureActive()) {
Shop::addTableAssociation($this->table, array('type' => 'shop'));
}
$this->position_identifier = 'id_additional_service';
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->fields_list = array(
'id_additional_service' => array(
'title' => $this->l('ID'),
'type' => 'int',
'width' => 'auto',
'orderby' => false),
'service_name' => array(
'title' => $this->l('Icon'),
'width' => 'auto',
'orderby' => false,
),
'service_desc' => array(
'title' => $this->l('service_desc'),
'type' => 'text'
),
'active' => array(
'title' => $this->l('Status'),
'width' => 'auto',
'active' => 'status',
'type' => 'bool',
'orderby' => false),
);
parent::__construct();
}
function initContent() {
parent::initContent();
if (Tools::isSubmit('submit')) {
Tools::redirectAdmin(self::$currentIndex . '&token=' . Tools::getAdminTokenLite('AdminCategories') . '&conf=7');
}
}
public function initPageHeaderToolbar() {
$this->page_header_toolbar_btn['back_to_list'] = array(
'href' => Context::getContext()->link->getAdminLink('AdminGCardeliverycity', true),
'desc' => $this->l('Back to list', null, null, false),
'icon' => 'process-icon-back'
);
parent::initPageHeaderToolbar();
}
public function renderForm() {
$id_citydelivery = (int) Tools::getValue('id_citydelivery');
if ($id_citydelivery == 0) {
$addSerModObj = new AdditionalServicesModel((int) Tools::getValue('id_additional_service'));
$id_citydelivery = $addSerModObj->id_citydelivery;
}
$fields_form_1 = array(
'form' => array(
'legend' => array('title' => $this->l('Additional Service'), 'icon' => 'icon-cogs'),
'input' => array(
array(
'type' => 'hidden',
'name' => 'id_citydelivery'
),
array(
'type' => 'text',
'label' => $this->l('Service_name'),
'name' => 'service_name',
'size' => 255,
'required' => true,
'desc' => $this->l('Enter name of Arrival port')
),
array(
'type' => 'text',
'label' => $this->l('service_desc'),
'name' => 'service_desc',
'size' => 255,
'required' => true,
'desc' => $this->l('Enter name of Arrival port')
),
array(
'type' => 'text',
'label' => $this->l('charge'),
'name' => 'charge',
'size' => 255,
'required' => true,
'desc' => $this->l('Enter name of Arrival port')
),
array(
'type' => 'switch',
'label' => $this->l('Active'),
'name' => 'active',
'required' => false,
'is_bool' => true,
'values' => array(array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Active')), array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('Inactive')))),
),
'submit' => array('title' => $this->l('Save')),
'buttons' => array(
array(
'href' => Context::getContext()->link->getAdminLink('AdminGCardeliverycity', true) . '&updatecitydelivery&id_citydelivery=' . $id_citydelivery,
'title' => $this->l('Cancle'),
'icon' => 'process-icon-cancel'
)
)
)
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->toolbar_scroll = true;
$lang = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'submit';
$helper->currentIndex = AdminController::$currentIndex;
$helper->token = Tools::getAdminTokenLite($this->name);
$id_additional_service = (int) Tools::getValue('id_additional_service');
$additionalServiceObj = new AdditionalServicesModel($id_additional_service);
$helper->tpl_vars = array(
'fields_value' => $this->getFormValues($additionalServiceObj),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
$_1 = $helper->generateForm(array($fields_form_1));
$return = $_1;
return $return;
}
function getFormValues($additionalServiceObj) {
return array(
'service_name' => Tools::getValue('service_name ', $additionalServiceObj->service_name),
'service_desc' => Tools::getValue('service_desc', $additionalServiceObj->service_desc),
'charge' => Tools::getValue('charge', $additionalServiceObj->charge),
'active' => Tools::getValue('active', $additionalServiceObj->active)
);
}
}
First of all, it seems that you redirect your page to the same URL. Try to use this
Tools::redirectAdmin($this->context->link->getAdminLink('AdminHome'));
where
AdminHome
is a redirect URL, you need to replace it with yours.
And second, try to use
Tools::getIsset('yourButtonName')
instead of
Tools::isSubmit('yourButtonName')
and the last, if nothing mentioned above will not help, try to move
parent::initContent();
and put it after your condition
Probably redirect_after may be useful
$this->redirect_after = 'Your custom address';

Prestashop: HelperForm with multilang field

where I use Helperform. I want to make some fields translatable. I added the following form:
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Diplom hinzufügen'),
'icon' => 'icon-question'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Name'),
'name' => 'name',
'lang' => true,
),
),
'submit' => array('title' => $this->l('Save'))
)
);
$helper = new HelperForm();
$helper->submit_action = 'saveDiplom';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => array(
'name' => '',
),
);
return $helper->generateForm(array($fields_form));
I don't see the "name" field in the backoffice. What is wrong? If I delete 'lang' => true it shows up.
Is there any other setting needed (like in the constructor)?
This is a standard HelperForm initialization:
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitNameOfModuleModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
. '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs, in your case you have passed the array directly */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
I guess you forgot the 'languages' in the tpl_vars array and the id_language too.
Maybe this link should be helpful.

Additional fields in Prestashop module - changes not displaing, parse error & class missing

I'm usually working with WP, but I need to manipulate a module blockcontactinfos on Prestashop - just simply add two more fields which will be shown on the front end, but somehow it's not working.
I have carrefully copied one of the fields, changed it everywhere but I when trying to clear the cache (in the Performance menu):
2 errors
blockcontactinfos (parse error in /modules/blockcontactinfos/blockcontactinfos.php)
blockcontactinfos (class missing in /modules/blockcontactinfos/blockcontactinfos.php)
Could anybody help me out of this? Thanks a lot in advance. Prestashop is 1.6. Fields are displayed correctly in settings, values saved, but there is the error above and I just can't force the web page to load changed template file.
blockcontactinfos.php (added the ones with _url), lines 31-141, changes marked with // KV:
<?php
if (!defined('_CAN_LOAD_FILES_'))
exit;
class Blockcontactinfos extends Module
{
protected static $contact_fields = array(
'BLOCKCONTACTINFOS_COMPANY',
'BLOCKCONTACTINFOS_ADDRESS',
'BLOCKCONTACTINFOS_ADDRESS_URL',
'BLOCKCONTACTINFOS_PHONE',
'BLOCKCONTACTINFOS_PHONE_URL',
'BLOCKCONTACTINFOS_EMAIL',
);
public function __construct()
{
$this->name = 'blockcontactinfos';
$this->author = 'PrestaShop';
$this->tab = 'front_office_features';
$this->version = '1.2.0';
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Contact information block');
$this->description = $this->l('This module will allow you to display your e-store\'s contact information in a customizable block.');
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}
public function install()
{
Configuration::updateValue('BLOCKCONTACTINFOS_COMPANY', Configuration::get('PS_SHOP_NAME'));
Configuration::updateValue('BLOCKCONTACTINFOS_ADDRESS', trim(preg_replace('/ +/', ' ', Configuration::get('PS_SHOP_ADDR1').' '.Configuration::get('PS_SHOP_ADDR2')."\n".Configuration::get('PS_SHOP_CODE').' '.Configuration::get('PS_SHOP_CITY')."\n".Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), Configuration::get('PS_SHOP_COUNTRY_ID')))));
Configuration::updateValue('BLOCKCONTACTINFOS_ADDRESS_URL', Configuration::get('PS_SHOP_ADDRESS_URL'));
Configuration::updateValue('BLOCKCONTACTINFOS_PHONE', Configuration::get('PS_SHOP_PHONE'));
Configuration::updateValue('BLOCKCONTACTINFOS_PHONE_URL', Configuration::get('PS_SHOP_PHONE_URL'));
Configuration::updateValue('BLOCKCONTACTINFOS_EMAIL', Configuration::get('PS_SHOP_EMAIL'));
$this->_clearCache('blockcontactinfos.tpl');
return (parent::install() && $this->registerHook('header') && $this->registerHook('footer'));
}
public function uninstall()
{
foreach (Blockcontactinfos::$contact_fields as $field)
Configuration::deleteByName($field);
return (parent::uninstall());
}
public function getContent()
{
$html = '';
if (Tools::isSubmit('submitModule'))
{
foreach (Blockcontactinfos::$contact_fields as $field)
Configuration::updateValue($field, Tools::getValue($field));
$this->_clearCache('blockcontactinfos.tpl');
$html = $this->displayConfirmation($this->l('Configuration updated'));
}
return $html.$this->renderForm();
}
public function hookHeader()
{
$this->context->controller->addCSS(($this->_path).'blockcontactinfos.css', 'all');
}
public function hookFooter($params)
{
if (!$this->isCached('blockcontactinfos.tpl', $this->getCacheId()))
foreach (Blockcontactinfos::$contact_fields as $field)
$this->smarty->assign(strtolower($field), Configuration::get($field));
return $this->display(__FILE__, 'blockcontactinfos.tpl', $this->getCacheId());
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Company name'),
'name' => 'BLOCKCONTACTINFOS_COMPANY',
),
array(
'type' => 'textarea',
'label' => $this->l('Address'),
'name' => 'BLOCKCONTACTINFOS_ADDRESS',
),
array(
'type' => 'text',
'label' => $this->l('URL na Google mapy'),
'name' => 'BLOCKCONTACTINFOS_ADDRESS_URL',
),
array(
'type' => 'text',
'label' => $this->l('Phone number'),
'name' => 'BLOCKCONTACTINFOS_PHONE',
),
array(
'type' => 'text',
'label' => $this->l('Telefonní číslo bez mezer'),
'name' => 'BLOCKCONTACTINFOS_PHONE_URL',
),
array(
'type' => 'text',
'label' => $this->l('Email'),
'name' => 'BLOCKCONTACTINFOS_EMAIL',
),
),
'submit' => array(
'title' => $this->l('Save')
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => array(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
foreach (Blockcontactinfos::$contact_fields as $field)
$helper->tpl_vars['fields_value'][$field] = Tools::getValue($field, Configuration::get($field));
return $helper->generateForm(array($fields_form));
}
}
blockcontactinfos.tpl (added the ones with _url), lines 32-33:
{if $blockcontactinfos_address != ''}<li><pre> {$blockcontactinfos_address|escape:'html':'UTF-8'|nl2br}</pre></li>{/if}
{if $blockcontactinfos_phone != ''}<li>{l s='Tel' mod='blockcontactinfos'} {$blockcontactinfos_phone|escape:'html':'UTF-8'}</li>{/if}

Prestashop - Translatable form field fails with HelperForm

I'm trying to do a Prestashop module, but when trying to set a translatable form field at the configuration form, it fails.
This is the error I get, through the JS console:
[14:33:39.915] ReferenceError: defaultLanguage is not defined # http://localhost:8888/js/admin.js:173
I think that I have well configurated the languajes in the backoffice, so I'm not sure why is this happening.
This is how I try to create the form:
public function displayForm()
{
// Get default Language
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
// Init Fields form array
$fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Settings'),
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Título de la noticia'),
'name' => 'NOTICIA_TIT',
'size' => 30,
'required' => true,
'lang' => true
),
array(
'type' => 'text',
'label' => $this->l('Imagen de la noticia'),
'name' => 'NOTICIA_IMG',
'size' => 30,
'required' => true,
'enabled' => false
),
array(
'type' => 'file',
'label' => $this->l('Subir nueva imagen'),
'name' => 'NOTICIA_IMG_FILE',
'size' => 30
),
array(
'type' => 'textarea',
'label' => $this->l('Texto de la noticia'),
'name' => 'NOTICIA_TXT',
'required' => true,
'cols' => 30,
'rows' => 4,
'lang' => true
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// Title and toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true; // false -> remove toolbar
$helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen.
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $this->l('Save'),
'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Load current value
$helper->fields_value['NOTICIA_TXT'] = Configuration::get('NOTICIA_TXT');
$helper->fields_value['NOTICIA_TIT'] = Configuration::get('NOTICIA_TIT');
$helper->fields_value['NOTICIA_IMG'] = Configuration::get('NOTICIA_IMG');
return $helper->generateForm($fields_form);
}
EDIT: I've seen this in the code.
<script type="text/javascript">
var module_dir = '/modules/';
var id_language = 1;
var languages = new Array();
var vat_number = 1;
// Multilang field setup must happen before document is ready so that calls to displayFlags() to avoid
// precedence conflicts with other document.ready() blocks
// we need allowEmployeeFormLang var in ajax request
allowEmployeeFormLang = 1;
displayFlags(languages, id_language, allowEmployeeFormLang);
$(document).ready(function() {
if ($(".datepicker").length > 0)
$(".datepicker").datepicker({
prevText: '',
nextText: '',
dateFormat: 'yy-mm-dd'
});
});
</script>
languajes variable is created as an empty array. However, this is function displayFlags:
function displayFlags(languages, defaultLanguageID, employee_cookie)
{
if ($('.translatable'))
{
$('.translatable').each(function() {
if (!$(this).find('.displayed_flag').length > 0) {
$.each(languages, function(key, language) {
if (language['id_lang'] == defaultLanguageID)
{
defaultLanguage = language;
return false;
}
});
var displayFlags = $('<div></div>')
.addClass('displayed_flag')
.append($('<img>')
.addClass('language_current')
.addClass('pointer')
.attr('src', '../img/l/' + defaultLanguage['id_lang'] + '.jpg')
.attr('alt', defaultLanguage['name'])
.click(function() {
toggleLanguageFlags(this);
})
);
var languagesFlags = $('<div></div>')
.addClass('language_flags')
.html('Choose language:<br /><br />');
$.each(languages, function(key, language) {
var img = $('<img>')
.addClass('pointer')
.css('margin', '0 2px')
.attr('src', '../img/l/' + language['id_lang'] + '.jpg')
.attr('alt', language['name'])
.click(function() {
changeFormLanguage(language['id_lang'], language['iso_code'], employee_cookie);
});
languagesFlags.append(img);
});
if ($(this).find('p:last-child').hasClass('clear'))
$(this).find('p:last-child').before(displayFlags).before(languagesFlags);
else
$(this).append(displayFlags).append(languagesFlags);
}
});
}
}
I fix the same error that you got but I get another one.
In order to define defaultLanguage, you should fill languages attribute of the helperform. You can do it this way:
$languages = Language::getLanguages(true);
$helper->languages = $languages;
I'm not sure whether you should put true or false for getLanguages... I tired both and I still get this error :
Uncaught SyntaxError: Unexpected token ILLEGAL
It happens here:
languages[0] = {
id_lang: 1,
iso_code: 'en',
name: 'English',
is_default: '<br />
So now, there probably more to do in order to have the property is_default defined... Have you find a way fix your problem?
EDIT :
By setting is_default on your own, it works. But it's ugly...
// Languages
$languages = Language::getLanguages(true);
for($i=0; $i<count($languages); $i++){
if($languages[$i]['id_lang'] == $default_lang){
$languages[$i]['is_default'] = 1;
}else{
$languages[$i]['is_default'] = 0;
}
}
$helper->languages = $languages;
Get the languages from the module controller:
$languages = $this->context->controller->getLanguages();

Invalid type given. String expected - Zend Framework 2

Im working on Zend Framework 2 especially with Zend Forms. I have declared a Select dropdown box in
Form:
$selectElement = new Element\Select('selectElement');
$selectElement->setAttribute('title', 'Select a Value')
->setAttribute('id', 'id');
$data = array(
array(
//Fetching the values from database
),
);
$selectElement->setAttribute('multiple', 'multiple')
->setValueOptions($data);
$this->add($selectElement);
InputFilter:
$inputFilter->add($factory->createInput(array(
'name' => 'selectElement',
'required' => false,
'filters' => array(
array(
'name' => 'Int'
),
),
)));
I have used Zend Debug to get the values which are in the selectElement dropbox in this fashion:
$dataSelectElements = $this->getRequest()->getPost('selectElement');
\Zend\Debug\Debug::dump($dataSelectElements);
Debug Result:
array(4) {
[0] => string(2) "20"
[1] => string(2) "22"
[2] => string(2) "23"
[3] => string(2) "75"
}
Basically Im getting the id's from the selectElement form to store it in the database. Right now Im getting a notice and zend form error:
Notice Error:
Notice: Array to string conversion in ..\zendframework\zendframework\library\Zend\Filter\Int.php on line 29
And a form invalid error:
array(1) {
[0] => array(1) {
["selectElement "] => array(1) {
["explodeInvalid"] => string(35) "Invalid type given. String expected"
}
}
}
Is there a solution to over come this problem. Any help would be appreciated.
The Int filter will attempt to make an Integer out of your array of data, which is not going to work.
Previously I've used the Callback filter, which can be used to loop through the data and check if each value is an Int.
For example:
'filters' => array(
array(
'name' => 'Callback',
'options' => array(
'callback' => function($values) {
return array_filter($values, function($value) {
return ((int)$value == $value);
});
}
)
),
),
I did bit differently, something like this
form
class Companyform extends Form
{
public function __construct()
{
// we want to ignore the name passed
parent::__construct('company');
$this->setAttribute ('method', 'post');
$this->setAttribute ('class', 'form-horizontal');
$this->add ( array (
'name' => 'parentID',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'id' => 'parentID',
'type' => 'select',
'placeholder' => "Parent Company",
),
'options' => array(
'label' => 'Parent Company'
)
));
$this->add(array(
'name' => 'btnsubmit',
'attributes' => array(
'id' => 'btnsubmit',
'type' => 'submit',
'value' => 'Add',
'class' => 'btn btn-primary'
),
));
}
}
controller
public function addAction()
{
$request = $this->getRequest();
$companyList = $this->_getCompanyList();
$form = new Companyform();
$form->get('parentID')->setAttribute('options',$companyList);
if ($request->isPost())
{
$company = new Company();
$form->setInputFilter($company->getInputFilter());
$form->setData($request->getPost());
if ($form->isvalid())
{
}
}
}
public function _getCompanyList()
{
$companies = $this->Em()->getEntityManager()->getRepository('XXXX\Entity\Company')->findBy(array('isDeleted'=>'0'));
$companyIDList = array();
$companyIDList[0] = "No Parent";
foreach ($companies as $company)
{
$companyIDList[$company->id] = $company->companyName;
}
return $companyIDList;
}
Entity class
protected $inputFilter;
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' => 'companyName',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 255,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
You may need to add following library in entity
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
In ZendFramework 2, when you creating a (add) element from your Form file, Check the attribute: inarrayvalidator is true.
$this->add(array(
'name' => 'select_name',
'type' => 'select',
'id' => 'select_name',
'options' => array(
'label' => 'Select Name',
),
'attributes' => array(
'id' => 'select_id',
'inarrayvalidator' => true,
),
));
I hope, this works...