How to populate multi array in zend form - zend-framework

I am trying to populate all the result from DB to zend form but cannot work.
This is my form
$configsForm= new Zend_Dojo_Form_SubForm();
$configsForm->setAttribs(array(
'name' => 'mandatory',
'legend' => 'mandatory',
'dijitParams' => array(
'title' => $this-> view -> __ ( 'Configs' ),
)
));
$configsForm->addElement(
'FilteringSelect',
'group_id',
array(
'label' => $this-> view -> __ ( 'Configs_Group Key' ),
'required' => true,
'value' => '',
'multiOptions' => $this->_getConfigOptions(),
'id' => 'group_id',
)
);
$configsForm->addElement(
'ValidationTextBox',
'option_type',
array(
'label' => $this-> view -> __ ( 'Configs_Option Type If Exist' ),
'trim' => true,
'required' => false,
'name' => 'option_type',
'id' => 'option_type',
'class' => 'lablvalue jstalgntop',
)
);
$configsForm->addElement(
'ValidationTextBox',
'option_title',
array(
'label' => $this-> view -> __ ( 'Configs_Option Title' ),
'trim' => true,
'required' => true,
'class' => 'lablvalue jstalgntop',
)
);
$configsForm->addElement(
'ValidationTextBox',
'option_value',
array(
'label' => $this-> view -> __ ( 'Configs_Option Value' ),
'trim' => true,
'required' => true,
'class' => 'lablvalue jstalgntop',
)
);
$configsForm->addElement(
'select',
'option_status',
array(
'label' => $this-> view -> __('Configs_Option Status'),
'required' => true,
'value' => '',
'multiOptions' => array('' => $this -> view -> __('Root'), 0 => 'Disabel', 1 => 'Enabel'),
)
);
$configsForm->addElement(
'FilteringSelect',
'locale_id',
array(
'label' => $this-> view -> __ ( 'Configs_Locale' ),
'class' => 'lablvalue jstalgntop',
'autocomplete'=>false,
'required' => true,
'multiOptions' => $this->_getLocaleOptions(),
'id' => 'locale_id',
)
);
$configsForm->addElement(
'ValidationTextBox',
'option_hint',
array(
'label' => $this-> view -> __ ( 'Configs_Option Hint' ),
'trim' => true,
'required' => false,
'class' => 'lablvalue jstalgntop',
)
);
$configsForm->addElement(
'ValidationTextBox',
'option_description',
array(
'label' => $this-> view -> __ ( 'Configs_Option Description' ),
'trim' => true,
'required' => false,
'class' => 'lablvalue jstalgntop',
)
);
$configsForm->addElement(
'ValidationTextBox',
'comments',
array(
'label' => $this-> view -> __ ( 'Configs_Option Comments' ),
'trim' => true,
'class' => 'lablvalue jstalgntop',
)
);
$configsForm->addElement(
'hidden',
'id'
);
$configsForm->addElement(
'SubmitButton',
'submit',
array(
'value' => 'submit',
'label' => $this-> view -> __ ( 'Object_Save' ),
'type' => 'Submit',
'ignore' => true,
'onclick' => 'dijit.byId("add-edit").submit()',
)
);
$configsForm->addElement(
'reset',
'reset',
array(
'label' => 'Reset',
'id' => 'reset',
'ignore'=> true,
)
);
$configsForm ->setDecorators ( array ('FormElements', array ('HtmlTag', array ('tag' => 'table', 'class'=>'formlist' ) ), 'ContentPane' ) );
$configsForm->setElementDecorators(array(
'DijitElement',
'Errors',
array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'lable jstalgntop')),
array('Label', array('tag' => 'td', 'class' => 'lable jstalgntop')),
array(array('row' => 'HtmlTag'), array('tag' => 'tr')),
));
$this->addSubForm($configsForm, 'configs');
}
And the code in my controller looks like
$form -> populate($configsObjResults);
The $configsObjResults containes
Array
(
[0] => Array
(
[id] => 11
[group_id] => 2
[group_key] => advanced
[option_title] => advanced.iptable.status
)
[1] => Array
(
[id] => 12
[group_id] => 2
[group_key] => advanced
[option_title] => advanced.memchache.iptable
)
)

Put your subform code in a method called addConfigSubForm() within your form code, like so:
class myForm extends Zend_Dojo_Form
{
...
// $number - 1st, 2nd, 3rd... subform
// $data - data to populate
public function addConfigSubForm($number, $data)
{
[ Create your subform here ]
// populate it with $data
$configsForm->populate($data);
// add it to the form
$this->addSubForm($configsForm, 'configs' . $i);
}
}
Then in your controller, do the following:
$myform = new myForm();
foreach ($configsObjResults as $i=>$config) {
$myform->addConfigSubForm($i, $config);
}
This will add a subform for each configs object in your array.

Related

Prestashop HelperFrom/List - messy layout

I'm new to prestashop and I worked the whole day on creating a back office interface that allows the user to write, edit, and delete articles. It is sort of a blog. I used Prestashop's Helpers (Form and List) and everything works great. I also added a new tab in the back office to access this tool.
The problem is that the layout is messy and doesn't look like the other forms and listing pages. The layout is really not sexy. Maybe I should look at some css file, or add any function in my controller ? You'll find the source code of the latter here (I can't insert images, not enough reputation --'):
<?php
class Article extends ObjectModel
{
/** #var string Name */
public $id_article;
public $titre;
public $contenu;
public $url_photo;
/**
* #see ObjectModel::$definition
*/
public static $definition = array(
'table' => 'article',
'primary' => 'id_article',
'fields' => array(
'titre' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true,
'class' => 'lg'
),
'contenu' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true
),
'url_photo' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => false,
),
),
);
}
class AdminBlogController extends AdminController{
public function initContent(){
parent::initContent();
}
public function __construct(){
$this->table = 'article';
$this->className = 'Article';
$this->lang = false;
// Building the list of records stored within the "article" table
$this->fields_list = array(
'id_article' => array(
'title' => 'ID',
'align' => 'center',
'width' => 25
),
'titre' => array(
'title' => 'Titre',
'width' => 'auto'
),
'contenu' => array(
'title' => 'Contenu',
'width' => 'auto'
)
);
// This adds a multiple deletion button
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?')
)
);
parent::__construct();
}
// This method generates the list of results
public function renderList(){
// Adds an Edit button for each result
$this->addRowAction('edit');
// Adds a Delete button for each result
$this->addRowAction('delete');
return parent::renderList();
}
// This method generates the Add/Edit form
public function renderForm(){
// Building the Add/Edit form
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => 'Article'
),
'input' => array(
array(
'type' => 'text',
'label' => 'Titre',
'name' => 'titre',
'class' => 'lg',
'required' => true,
//'desc' => 'Nom de l\'article',
),
array(
'type' => 'textarea',
'label' => 'Contenu',
'name' => 'contenu',
'class' => 'lg',
'required' => true,
'autoload_rte' => true,
//'desc' => 'Contenu de l\'article',
),
array(
'type' => 'file',
'label' => 'Photo',
'name' => 'url_photo',
'class' => 'lg',
'required' => true,
//'desc' => 'Contenu de l\'article',
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
return parent::renderForm();
}
}
?>
Thank you.
I just needed to set $this->bootstrap = true

How to get paramaters in controller function action in Zend 2?

this is my code:
public function registerAction(){
$this->redirect()->toRoute(null, array(
'controller' => 'user',
'action' => 'confirm',
'param1' =>'email',//$request->getPost('mail'),
'param2'=>$request->getPost('name')
));
}
public function confirmAction(){
$params = $this->params()->fromRoute('param1');
var_dump($params); exit();
return new ViewModel();
}
and this is the code from the config:
.....
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '[:controller[/:action]][/:param1][/:param2]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*'
),
'defaults' => array(
'action' => 'index',
'__NAMESPACE__' => 'Application\Controller'
)
)
)
)
....
I am trying to send 2 parameters in a redirect, to receive in the confirmAction function and send it tot view. But i get in the var_dump always the null value. I tried all of this:
$this->params()->fromPost('paramname'); // From POST
$this->params()->fromQuery('paramname'); // From GET
$this->params()->fromRoute('paramname'); // From RouteMatch
$this->params()->fromHeader('paramname'); // From header
$this->params()->fromFiles('paramname'); // From file being uploaded
but with no result. Can anyone help me with this ? thx
you have to set in the config the parameter name, which is in my case : param1
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '[:controller[/:action]][/:param1]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*'
),
'defaults' => array(
'action' => 'index',
'__NAMESPACE__' => 'Application\Controller',
'param1' => 'tralala'
)
)
)
)
After that in the controller when you do a redirect:
public function registerAction(){
$this->redirect()->toRoute(null, array(
'controller' => 'user',
'action' => 'confirm',
'param1' =>'my_email'
));
}
public function confirmAction(){
$params = $this->params()->fromRoute('param1');
var_dump($params); exit();
return new ViewModel();
}
You will receive the my_email string

ZF2 - Binding Nested Fieldsets/Collections

I have two entities (Metaproduct and Options) that have Many-To-Many Unidirectional relation with entity Specification.
The relation between Metaproduct and Option is One-To-Many.
The code for the Fieldsets and Forms for Metaproduct is the following:
MetaproductFieldset.php
namespace Bundle\Fieldset;
class MetaproductFieldset extends EntityUsingFieldset implements InputFilterProviderInterface{
...
public function __construct(ObjectManager $objectManager)
{
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'options',
'options' => array(
'label' => 'Options',
'count' => 1,
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => true,
'target_element' => new OptionFieldset($objectManager),
),
'attributes' => array(
'id' => 'options',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'specifications',
'options' => array(
'label' => 'Specifications',
'count' => 1,
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => true,
'target_element' => new SpecificationFieldset($objectManager),
),
'attributes' => array(
'id' => 'specifications',
),
));
OptionFieldset.php
namespace Bundle\Fieldset;
class OptionFieldset extends EntityUsingFieldset implements InputFilterProviderInterface{
public function __construct(ObjectManager $objectManager)
{
$this->setObjectManager($objectManager);
parent::__construct('option');
$this->setHydrator(new DoctrineHydrator($objectManager))->setObject(new \Bundle\Entity\Option());
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'specifications',
'options' => array(
'label' => 'Specifications',
'count' => 1,
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => true,
'target_element' => new SpecificationFieldset($objectManager),
),
'attributes' => array(
'id' => 'specifications',
),
));
SpecificationFieldset.php
namespace Bundle\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\InputFilter\InputFilterProviderInterface;
class SpecificationFieldset extends EntityUsingFieldset implements InputFilterProviderInterface{
public function __construct(ObjectManager $objectManager)
{
$this->setObjectManager($objectManager);
parent::__construct('specification');
$this->setHydrator(new DoctrineHydrator($objectManager))->setObject(new \Bundle\Entity\Specification());
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'label',
'options' => array(
'label' => 'Label',
'object_manager' => $objectManager,
'target_class' => 'Bundle\Entity\Label',
'property' => 'value',
'empty_option' => '--- please choose ---'
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'value',
'options' => array(
'label' => 'Value'
)
));
}
Metaproduct.php
namespace Bundle\Form;
...
class Metaproduct extends Form {
public function __construct(ObjectManager $objectManager){
parent::__construct('metaproduct-form');
$this->setHydrator(new DoctrineHydrator($objectManager));
$mpFieldset = new MetaproductFieldset($objectManager);
$mpFieldset->setUseAsBaseFieldset(true);
...
But when I try to print bind an object on that form, the following Expection is throwed:
File
zendframework\library\Zend\Form\Fieldset.php:439
Message
Zend\Form\Fieldset::setObject expects an object argument; received "Array"
Trace
#0 C:\projects\acuradoria-zend\vendor\zendframework\zendframework\library\Zend\Form\Element\Collection.php(549): Zend\Form\Fieldset->setObject(Array)
#1 C:\projects\acuradoria-zend\vendor\zendframework\zendframework\library\Zend\Form\Fieldset.php(601): Zend\Form\Element\Collection->extract()
#2 C:\projects\acuradoria-zend\vendor\zendframework\zendframework\library\Zend\Form\Form.php(854): Zend\Form\Fieldset->extract()
#3 C:\projects\acuradoria-zend\vendor\zendframework\zendframework\library\Zend\Form\Form.php(292): Zend\Form\Form->extract()
#4 C:\projects\acuradoria-zend\module\Bundle\src\Bundle\Controller\Plugin\FormService.php(42): Zend\Form\Form->bind(Object(Bundle\Entity\Metaproduct))
Please see this issue:
Problems in nested collections and fieldsets
https://github.com/zendframework/zf2/issues/5640

Creating drupal form with wrappers

I have created a form in drupal programmatically. How could i wrap each elements of the form with div. Below is my sample code
function emailusers_compose_form($context, $account) {
$form['to'] = array(
'#type' => 'value',
'#value' => $account,
);
$form['message']['subject'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#size' => 50,
'#maxlengh' => 255,
'#description' => t('The subject of the email message.'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Send Mail'),
);
return $form;
}
Here is the answer
function emailusers_compose_form($context, $account) {
$form['to'] = array(
'#type' => 'value',
'#value' => $account,
);
$form['message']['subject'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#size' => 50,
'#maxlengh' => 255,
'#description' => t('The subject of the email message.'),
'#prefix' => '<div id="elementid">',
'#suffix' => '</div>'
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Send Mail'),
);
return $form;
}

Drupal7 Custom Form Submit Handler Not Working

I am writing a custom module which has a form but the submit handler is just not working, the form just submits back to itself?
Any help much appreciated.
I have an add guest custom form and that is working fine.
The URL on my site is: /user/booking_editguest/LBD0413/1
The code is below:
function uUserBookings_editGuestForm($form, &$form_state, $ManageBooking) {
//var_dump($ManageBooking);
$guestSeq = arg(3);
$masterEventCode = $ManageBooking->Contact->{'MasterEventCode'};
$eventCode = $ManageBooking->Contact->{'EventCode'};
$attendeeContact = $ManageBooking->Contact->{'AttendeeContact'};
global $user;
$account = user_load($user->uid);
$memberCode = $account->name;
// booking
$form['booking'] = array(
//'#type' => 'vertical_tabs',
);
foreach($ManageBooking->guests as $Guest)
{
if ($guestSeq == $Guest->{'GuestSeq'} )
{
$form['guest_form']['FirstName'] = array(
'#required' => TRUE,
'#type' => 'textfield',
'#title' => t('GUEST FIRST NAME'),
'#default_value' => $Guest->{'Guest FirstName'}
);
$form['guest_form']['Surname'] = array(
'#required' => TRUE,
'#type' => 'textfield',
'#title' => t('GUEST LAST NAME'),
'#default_value' => $Guest->{'Guest Surname'}
);
$form['guest_form']['DietaryRequirements'] = array(
'#required' => FALSE,
'#type' => 'textfield',
'#title' => t('SPECIAL DIETARY REQUIREMENTS'),
'#default_value' => $Guest->{'Dietary Requirements'}
);
$form['guest_form']['CompanyName'] = array(
'#required' => TRUE,
'#type' => 'textfield',
'#title' => t('GUEST COMPANY NAME'),
'#default_value' => $Guest->{'Company Name'}
);
$form['guest_form']['Position'] = array(
'#required' => TRUE,
'#type' => 'textfield',
'#title' => t('GUEST POSITION'),
'#default_value' => $Guest->{'Attendee Position'}
);
$form['guest_form']['Email'] = array(
'#required' => TRUE,
'#type' => 'textfield',
'#title' => t('GUEST EMAIL'),
'#default_value' => $Guest->{'Guest Email'}
);
//MasterEventCode
$form['guest_form']['masterEventCode'] = array(
'#required' => TRUE,
'#type' => 'hidden',
'#default_value' => $masterEventCode
);
//EventCode
$form['guest_form']['eventCode'] = array(
'#required' => TRUE,
'#type' => 'hidden',
'#default_value' => $eventCode
);
//Member_code
$form['guest_form']['memberCode'] = array(
'#required' => TRUE,
'#type' => 'hidden',
'#default_value' => $memberCode
);
//Attendee_Contact
$form['guest_form']['Attendee_Contact'] = array(
'#required' => TRUE,
'#type' => 'hidden',
'#default_value' => $attendeeContact
);
//GuestSeq
$form['guest_form']['GuestSeq'] = array(
'#required' => TRUE,
'#type' => 'hidden',
'#default_value' => $Guest->{'GuestSeq'}
);
//GuestID
$form['guest_form']['GuestID'] = array(
'#required' => TRUE,
'#type' => 'hidden',
'#default_value' => $Guest->{'Guest Contact Counter'}
);
//EventNameDetailsID uniqueidentifier
$form['guest_form']['EventNameDetailsID'] = array(
'#required' => TRUE,
'#type' => 'hidden',
'#default_value' => $Guest->{'EventNameDetailsID'}
);
//ID uniqueidentifier
$form['guest_form']['ID'] = array(
'#required' => TRUE,
'#type' => 'hidden',
'#default_value' => $Guest->{'ID'}
);
$form['guest_form']['Submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#submit' => array('tmsUserBookings_editGuestForm_submit')
);
}
}
return $form;}
function userBookings_editGuestForm_validate($form, &$form_state) {
// Validation logic.
// Don't custom-validate if previous validation errors (still) exist
if (form_get_errors()) return;
// .. Otherwise, process custom form validation goes here }
function userBookings_editGuestForm_submit($form, &$form_state) {
//Get Form variables
$guestFirstname = $form_state['input']['FirstName'];
$guestSurname = $form_state['input']['Surname'];
$guestDietary = $form_state['input']['DietaryRequirements'];
$guestCompany = $form_state['input']['CompanyName'];
$guestPosition = $form_state['input']['Position'];
$guestEmail = $form_state['input']['Email'];
$memberCode = $form_state['input']['Member_code'];
$masterEventCode = $form_state['input']['MasterEventCode'];
$eventCode = $form_state['input']['EventCode'];
$bookerContactCounter = $form_state['input']['Attendee_Contact'];
$guestSeq = $form_state['input']['GuestSeq'];
$guestTitle = $form_state['input']['Title'];
$guestContactCounter = $form_state['input']['GuestID'];
$eventNameDetailsId = $form_state['input']['EventNameDetailsID'];
$id = $form_state['input']['ID'];
//Redirect back to the Booking.
$form_state['redirect'] = '/user/booking_guestupdated';}
For those using hidden textfields and have them set as required, make sure you check the values being entered!