Prestashop - Add additional fields on product combination - prestashop

I'm trying to add additional fields on my product combinations in order to have custom meta titles for the combinations.
So I created this module:
My module definition:
class CombinationCustomFields extends Module
{
public function __construct()
{
$this->name = 'combinationcustomfields';
$this->tab = 'administration';
$this->author = '';
$this->version = '1.0';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Combination Custom Fields');
$this->description = $this->l('Add additional fields on combinations');
$this->ps_versions_compliancy = array('min' => '1.7.1', 'max' => _PS_VERSION_);
}
public function install()
{
if (!parent::install() || !$this->_installSql()
|| !$this->registerHook('displayAdminProductsCombinationBottom')
|| !$this->registerHook('actionAttributeCombinationSave')
) {
return false;
}
return true;
}
public function uninstall()
{
return parent::uninstall() && $this->_unInstallSql();
}
/**
* Add database fields
* #return boolean
*/
protected function _installSql()
{
$sqlInstall = "ALTER TABLE " . _DB_PREFIX_ . "product_attribute "
. "ADD meta_title_fr VARCHAR(255) NULL, "
. "ADD meta_title_en VARCHAR(255) NULL;";
$returnSql = Db::getInstance()->execute($sqlInstall);
return $returnSql;
}
/**
* Remove database fields
* #return boolean
*/
protected function _unInstallSql()
{
$sqlInstall = "ALTER TABLE " . _DB_PREFIX_ . "product_attribute "
. "DROP meta_title_fr, "
. "DROP meta_title_en";
$returnSql = Db::getInstance()->execute($sqlInstall);
return $returnSql;
}
public function hookDisplayAdminProductsCombinationBottom($params)
{
$combination = new Combination($params['id_product_attribute']);
$this->context->smarty->assign(array(
'id_product_attribute' => $params['id_product_attribute'],
'meta_title_fr' => $combination->meta_title_fr,
'meta_title_en' => $combination->meta_title_en,
)
);
return $this->display(__FILE__, 'views/templates/hook/combinationfields.tpl');
}
public function hookActionAttributeCombinationSave($params)
{
$combination = new Combination($params['id_product_attribute']);
$this->context->smarty->assign(array(
'id_product_attribute' => $params['id_product_attribute'],
'meta_title_fr' => $combination->meta_title_fr,
'meta_title_en' => $combination->meta_title_en,
)
);
$combination->meta_title_fr = Tools::getValue('meta_title_fr');
$combination->meta_title_en = Tools::getValue('meta_title_en');
$combination->save();
return $this->display(__FILE__, 'views/templates/hook/combinationfields.tpl');
}
}
My HTML for the admin hook:
<div class="m-b-1 m-t-1">
<h2>{l s='Combination Custom Fields' mod='combinationcustomfields'}</h2>
<fieldset class="form-group">
<div class="col-lg-12 col-xl-4">
<label class="form-control-label" for="combination_{$id_product_attribute}_attribute_meta_title_fr">{l s='Meta title FR' mod='combinationcustomfields'}</label>
<input class="form-control" name="combination_{$id_product_attribute}[attribute_meta_title_fr]" id="combination_{$id_product_attribute}_attribute_meta_title_fr" type="text" value="{if $meta_title_fr != ''}{$meta_title_fr}{/if}">
<br />
</div>
<div class="col-lg-12 col-xl-4">
<label class="form-control-label" for="combination_{$id_product_attribute}_attribute_meta_title_en">{l s='Meta title EN' mod='cmp_combination_customfields'}</label>
<input class="form-control" name="combination_{$id_product_attribute}[attribute_meta_title_en]" id="combination_{$id_product_attribute}_attribute_meta_title_en" type="text" value="{if $meta_title_en != ''}{$meta_title_en}{/if}">
<br />
</div>
</fieldset>
<div class="clearfix"></div>
</div>
My override of the combination class:
class Combination extends CombinationCore
{
public $meta_title_fr;
public $meta_title_en;
/**
* #see ObjectModel::$definition
*/
public static $definition = [
'table' => 'product_attribute',
'primary' => 'id_product_attribute',
'fields' => [
'id_product' => ['type' => self::TYPE_INT, 'shop' => 'both', 'validate' => 'isUnsignedId', 'required' => true],
'location' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 64],
'ean13' => ['type' => self::TYPE_STRING, 'validate' => 'isEan13', 'size' => 13],
'isbn' => ['type' => self::TYPE_STRING, 'validate' => 'isIsbn', 'size' => 32],
'upc' => ['type' => self::TYPE_STRING, 'validate' => 'isUpc', 'size' => 12],
'mpn' => ['type' => self::TYPE_STRING, 'validate' => 'isMpn', 'size' => 40],
'quantity' => ['type' => self::TYPE_INT, 'validate' => 'isInt', 'size' => 10],
'reference' => ['type' => self::TYPE_STRING, 'size' => 64],
'supplier_reference' => ['type' => self::TYPE_STRING, 'size' => 64],
'meta_title_fr' => ['type' => self::TYPE_STRING, 'size' => 64],
'meta_title_en' => ['type' => self::TYPE_STRING, 'size' => 64],
/* Shop fields */
'wholesale_price' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice', 'size' => 27],
'price' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isNegativePrice', 'size' => 20],
'ecotax' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice', 'size' => 20],
'weight' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isFloat'],
'unit_price_impact' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isNegativePrice', 'size' => 20],
'minimal_quantity' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId', 'required' => true],
'low_stock_threshold' => ['type' => self::TYPE_INT, 'shop' => true, 'allow_null' => true, 'validate' => 'isInt'],
'low_stock_alert' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
'default_on' => ['type' => self::TYPE_BOOL, 'allow_null' => true, 'shop' => true, 'validate' => 'isBool'],
'available_date' => ['type' => self::TYPE_DATE, 'shop' => true, 'validate' => 'isDateFormat'],
],
];
}
But when I save the product, the fields are in the request:
But I have a 400 Error:
Any idea of my mistake here ?
All the best and thanks in advance for you help :)

You can override the combination class using an override controler:
class Combination extends CombinationCore
{
public $newVariableName;
public function __construct($id = null, $id_lang = null, $id_shop = null)
{
Combination::$definition['fields']['newVariableName'] = array('type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => false);
parent::__construct($id, $id_lang, $id_shop);
}
}
You will also need to override product.php
public function updateProductAttribute($id_product_attribute, ..., $newVariableName = null){
public function addCombinationEntity($wholesale_price, ..., $newVariableName = null){
and so on...

I would do so:
HTML:
Change all attributes combination_ to custom_
<div class="m-b-1 m-t-1">
<h2>{l s='Combination Custom Fields' mod='combinationcustomfields'}</h2>
<fieldset class="form-group">
<div class="col-lg-12 col-xl-4">
<label class="form-control-label" for="custom_{$id_product_attribute}_attribute_meta_title_fr">{l s='Meta title FR' mod='combinationcustomfields'}</label>
<input class="form-control" name="custom_{$id_product_attribute}[attribute_meta_title_fr]" id="custom_{$id_product_attribute}_attribute_meta_title_fr" type="text" value="{if $meta_title_fr != ''}{$meta_title_fr}{/if}">
<br />
</div>
<div class="col-lg-12 col-xl-4">
<label class="form-control-label" for="custom_{$id_product_attribute}_attribute_meta_title_en">{l s='Meta title EN' mod='cmp_combination_customfields'}</label>
<input class="form-control" name="custom_{$id_product_attribute}[attribute_meta_title_en]" id="custom_{$id_product_attribute}_attribute_meta_title_en" type="text" value="{if $meta_title_en != ''}{$meta_title_en}{/if}">
<br />
</div>
</fieldset>
<div class="clearfix"></div>
Next step:
public function hookActionAttributeCombinationSave($params)
{
$id_product_attribute = $params['id_product_attribute'];
$custom = $_POST['custom_' . $id_product_attribute];
....
}

Related

Change the url associated with cancel button

I want to change the URL of cancel button presently on canceling the page it is showing me the list but I want to redirect the user on the cancel button.
public function renderForm() {
$this->fields_form = array(
'legend' => array('title' => $this->l('Additional Service'), 'icon' => 'icon-cogs'),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('id_citydelivery'),
'name' => 'id_citydelivery',
'size' => 255),
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' => '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')),
);
return parent::renderForm();
}
After Diving into the code I came to know back button URL is set it by $_post['Back']
So I have overridden it; you have to change # with your URL
public function postProcess() {
if (Tools::getIsset('submitAddadditional_service')) {
$this->redirect_after = Context::getContext()->link->getAdminLink('AdminGCardeliverycity', true) . '&updatecitydelivery&id_citydelivery=' . Tools::getValue('id_citydelivery');
} else {
$_POST['back'] = '#'; //For Cancel button url on form which is genrated by renderform()
}
parent::postProcess();
}

yii2 :why $model->image is empty after upload image with FileUploadUI

this is my _form.php :
<?php
use dosamigos\fileupload\FileUploadUI;
// with UI
?>
<?=
FileUploadUI::widget([
'model' => $model,
'attribute' => 'image',
'url' => ['media/upload', 'id' => 'image'],
'gallery' => false,
'fieldOptions' => [
'accept' => 'image/*'
],
'clientOptions' => [
'maxFileSize' => 200000
],
// ...
'clientEvents' => [
'fileuploaddone' => 'function(e, data) {
console.log(e);
console.log(data);
}',
'fileuploadfail' => 'function(e, data) {
console.log(e);
console.log(data);
}',
],
]);
?>
my file uploaded in my host but i need that url
this is my product controller and image is empty :
public function actionCreate()
{
$request = Yii::$app->request;
$model = new Product();
$idCon = Yii::$app->user->id;
$model->user_id = $idCon;
if ($request->isAjax)
{
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet)
{
return [
'title' => "Create new Product",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
else if ($model->load($request->post()) && $model->save())
{
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new Product",
'content' => '<span class="text-success">Create Product success</span>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
}
else
{
return [
'title' => "Create new Product",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
}
else
{
/*
* Process for non-ajax request
*/
if ($model->load($request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
}
}
and this is my model :
use Yii;
use yii\web\UploadedFile;
use yii\base\Model;
/**
* This is the model class for table "product".
*
* #property integer $id
* #property string $name
* #property string $price
* #property string $image
* #property string $url
* #property integer $user_id
*
* #property ConProduct[] $conProducts
* #property User $user
* #property Sales[] $sales
*/
class Product extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'product';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['price'], 'number'],
[['user_id'], 'integer'],
[['name', 'image'], 'string', 'max' => 300],
[['url'], 'string', 'max' => 255],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
how can i get image url with $model->image in controller !?
Have you tried to use yii\web\UploadedFile::getInstance()?
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->upload()) {
// do some stuff with file
}
http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html#wiring-up

How add one more button to yii2-widget-fileinput?

I want more button in yii2-fileinput-widget.
My current code is like this:
$allPics = \common\models\Picture::getPictures($album->id);
$images = [];
$imagesOptions = [];
if($allPics){
foreach ($allPics as $pic){
$key = $pic->id;
$url = Url::to(['set-pic-status', 'id'=>$key, 'pid'=>$model->id, 'do'=>'remove']);
$images[] = Yii::$app->urlManagerFront->createAbsoluteUrl(['image/index', 'id'=>$pic->id, 'width'=>300, 'height'=>300]);
$imagesOptions[] = ['caption' => $pic->name, 'size' => $pic->size , 'url'=>$url, 'key'=>$key];
}
}
echo FileInput::widget([
'name' => 'pic',
'language'=>'fa',
'options'=>[
'multiple'=>true
],
'pluginOptions' => [
'uploadUrl' => Url::to(['pic-upload', 'id'=>$model->id]),
'initialPreview'=>$images,
'initialPreviewAsData'=>true,
'initialCaption'=>"تصاویر محصول",
'initialPreviewConfig' => $imagesOptions,
'overwriteInitial'=>false,
'maxFileSize'=>2800,
]
]);
And result of top code is:
Now I need add one more button near remove button to send some data to server and set selected picture as cover or change status of picture in db.
How can I do that?
try this:
$initialPreview = [];
$initialPreviewConfig = [];
foreach($model->images as $image){
$initialPreview[] = Html::img($image->imagePath,['width' =>200]);
$initialPreviewConfig[] = [
'url' => \yii\helpers\Url::to(['/admin/portfolio/portfolio/image-delete']),
'key' => $image->ID,
];
}
?>
<br>
<div class="row">
<div class="col-md-12">
<?php
echo FileInput::widget([
'name' => 'ProductImages[]',
'options'=>['accept'=>'image/*','multiple' => true],
'pluginOptions' => [
'otherActionButtons' => '<button class="set-main" type="button" {dataKey} ><i class="glyphicon glyphicon-star"></i></button>',
'overwriteInitial'=>false,
'maxFileSize'=>2800,
'fileActionSettings' => [
'fileActionSettings' => [
'showZoom' => false,
'showDelete' => true,
],
],
'browseClass' => 'btn btn-success',
'uploadClass' => 'btn btn-info',
'removeClass' => 'btn btn-danger',
'showRemove' => false,
'showUpload' => false,
'initialPreview' => $initialPreview,
'initialPreviewConfig' => $initialPreviewConfig,
],
]);
$this->registerJs("
$('.set-main').on('click',function(){
$.get('" . \yii\helpers\Url::to(['/admin/portfolio/portfolio/set-main-image/']) . "', {id:$(this).attr('data-key')});
});
");
?>
</div></div>
<div>
'otherActionButtons' => '...';

how to remove the view button and list buttons from fields_list in prestashop 1.6.3

I want to remove the view button and list buttons such as Export ,Add button from fields_list in prestashop 1.6
Below is my render listview code, This list is populated when the view button is clicked from the main list view page
public function renderView()
{
if(Tools::getValue('id_query_dr')){
$id_query_dr =Tools::getValue('id_query_dr');
$this->module = new QueryDrDetail();
$this->context = Context::getContext();
$this->id_lang = $this->context->language->id;
$this->lang = false;
$this->ajax = 1;
$this->path = _MODULE_DIR_.'querydrdetail';
$this->default_form_language = $this->context->language->id;
$this->table = 'kits_query_dr_detail';
$this->className = 'querydrdetail';
$this->identifier = 'id_query_dr_detail';
$this->allow_export = true;
$this->explicitSelect = false;
$this->_select = ' id_query_dr_detail,
id_query_dr,
order_no,
ni_online_ref_id,
transaction_type,
response,
status,
error_code,
error_msg,
date_add,
date_upd';
$this->_where.= 'AND id_query_dr='.$id_query_dr.' ';
$this->_orderBy = 'id_query_dr_detail';
$this->_orderWay = 'DESC';
//Field list -
$this->fields_list = array(
'id_query_dr_detail' => array(
'title' =>$this->l('Detail Id'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'id_query_dr' => array(
'title' => $this->l('Query Dr Id'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'order_no' => array(
'title' => $this->l('Cart Id'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'ni_online_ref_id' => array(
'title' => $this->l('Online Reference ID '),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'transaction_type' => array(
'title' => $this->l('Trx type'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'status' => array(
'title' => $this->l('Status'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'error_code' => array(
'title' => $this->l('Error Code'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'error_msg' => array(
'title' => $this->l('Error Message'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'response' => array(
'title' => $this->l('Response'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'date_add' => array(
'title' => $this->l('Date Added'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'date_upd' => array(
'title' => $this->l('Date Updated'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
'query_dr_method' => array(
'title' => $this->l('Query Dr Method'),
'align' => 'text-center',
'remove_onclick' => true,
'search' => false,
),
);
}
$this->initTabModuleList();
$this->initToolbar();
$this->initPageHeaderToolbar();
parent::__construct();
return parent::renderForm();
}
public function initContent()
{
if($this->action!='view'){
$this->initTabModuleList();
$this->initToolbar();
$this->initPageHeaderToolbar();
$this->content .= $this->initFormToCallQueryDR();
$this->table = _DB_KITS_PREFIX_.'query_dr';
$this->toolbar_title = $this->l('Query Dr Logs');
$this->content .= $this->renderList();
$this->context->smarty->assign(array(
'content' => $this->content,
'url_post' => self::$currentIndex.'&token='.$this->token,
'show_page_header_toolbar' => $this->show_page_header_toolbar,
'page_header_toolbar_title' => $this->page_header_toolbar_title,
'page_header_toolbar_btn' => $this->page_header_toolbar_btn
));
}
//If its view the display another list here
if($this->action=='view'){
$this->initTabModuleList();
$this->initToolbar();
$this->initPageHeaderToolbar();
$this->content = $this->renderView();
$this->table = _DB_KITS_PREFIX_.'query_dr_detail';
$this->toolbar_title = sprintf($this->l('Query Dr Detail Logs of Query Dr ID: %d'),Tools::getValue('id_query_dr'));
$this->content .= $this->renderList();
$this->context->smarty->assign(array(
'content' => $this->content,
'url_post' => self::$currentIndex.'&token='.$this->token,
'show_page_header_toolbar' => $this->show_page_header_toolbar,
'page_header_toolbar_title' => $this->page_header_toolbar_title,
'page_header_toolbar_btn' => $this->page_header_toolbar_btn
));
}
}
In quella classe dovresti cercare la funzione renderlist e commentare la riga
$this->addRowAction('view');

Populating Form Data in ZF2 when using Fieldsets

I am currently playing around with ZF2 beta 4 and I seem to be stuck when i try to use fieldsets within a form and getting the data back into the form when the form is submitted. I am not sure if I am not setting the input filters right for fieldsets or I am missing something. For example, I have the following (simplified to make it clear):
Controller
public function indexAction(){
$form = new MyForm();
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->post());
if ($form->isValid()) {
//Do something
print_r($form->getData()); //for debug
}
}
return array('form' => $form);
}
MyForm.php
class MyForm extends Form
{
public function __construct()
{
parent::__construct();
$this->setName('myForm');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'title',
'attributes' => array(
'type' => 'text',
'label' => 'Title',
),
));
$this->add(new MyFieldset('myfieldset'));
//setting InputFilters here
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'title',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
)));
//Now add fieldset Input filter
foreach($this->getFieldsets() as $fieldset){
$fieldsetInputFilter = $factory->createInputFilter($fieldset->getInputFilterSpecification());
$inputFilter->add($fieldsetInputFilter,$fieldset->getName());
}
//Set InputFilter
$this->setInputFilter($inputFilter);
}
}
MyFieldset.php
class MyFieldset extends Fieldset implements InputFilterProviderInterface{
public function __construct($name)
{
parent::__construct($name);
$factory = new Factory();
$this->add($factory->createElement(array(
'name' => $name . 'foo',
'attributes' => array(
'type' => 'text',
'label' => 'Foo',
),
)));
}
public function getInputFilterSpecification(){
return array(
'foo' => array(
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
),
);
}
}
I am able to output the form as expected and I end up with two input elements named 'title' and 'myfieldsetfoo' (the name given when outputing with the ViewHelper). So of course when I submit the raw post will show values for 'title' and 'myfieldsetfoo'. However, when I use SetData() the values for the field set are not being populated (although I can see the values in the raw post object). Instead, examining the output of '$form->getData()' I receive:
Array(
[title] => Test,
[myfieldset] => Array(
[foo] =>
)
)
What am I missing? What do I need to do so that ZF2 understands how to populate the fieldset?
Thanks for any help, this is driving me crazy.
Why I do is concatenate InputFilter so I could handle the whole HTML form array posted.
<form method="POST">
<input type="text" name="main[name]" />
<input type="text" name="main[location]" />
<input type="text" name="contact[telephone]" />
<input type="submit" value="Send" />
</form>
This will create an array posted like
post["main"]["name"]
post["main"]["location"]
post["contact"]["telephone"]
Filtered and validated with:
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
$post = $this->request->getPost();
$inputFilter = new InputFilter();
$factory = new InputFactory();
// $post["main"]
$mainFilter = new InputFilter();
$mainFilter->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' => 1,
'max' => 100,
),
),
),
)));
$mainFilter->add($factory->createInput(array(
'name' => 'location',
'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($mainFilter, "main");
// $post["contact"]
$contactFilter = new InputFilter();
$contactFilter->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' => 1,
'max' => 100,
),
),
),
)));
$contactFilter->add($mainFilter, "contact");
//Set posted data to InputFilter
$inputFilter->setData($post->toArray());
http://www.unexpectedit.com/zf2/inputfilter-validate-and-filter-a-form-data-with-fieldsets
I think you forgot to prepare your form in the controller:
return array('form' => $form->prepare());
This will rename the "name" field of your fieldset to "myfieldset[foo]", so you don't have to prepend the fieldsets name on your own.
Just use
'name' => 'foo'
instead of
'name' => $name . 'foo'
in your fieldset class.
I think the problem is that you declare a new form in your controller. And that clear the previous form.
$form = new MyForm();
I use the Service Manager to declare the form and filters.
And then in the controller I do:
$form = $this->getServiceLocator()->get('my_form');
That way I always get the object I want
Update
I no longer use service manager to call forms. I just call a new form and issue $form->setData($data);
The source for the data can also be entity though then I would issue: $form->bind($entity)