ZF2: how to get options for dropdown from db - php

I followed the tutorial. But I can find no way to populate a form select from a database like this:
// Blog/src/Blog/Form/BlogItemForm.php
$blogCategoryTable = new Model\BlogCategoryTable;
$this->add(new Element\Select('category_id',
array('label' => 'Category', 'value_options' => $blogCategoryTable->getFormChoices())
));
Does anyone have any ideas?

I use a function to retrieve the data and set it to the form:
From my factory:
$option_for_select = $this->model->getWhatEver();
$this->add($factory->createElement(array(
'name' => 'what_ever',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => $option_for_select,
),
'options' => array(
'label' => 'What ever:',
),
)));
From the model:
public function getWhatEver()
{
$sql = "SELECT something";
$statement = $this->adapter->query($sql);
$res = $statement->execute();
// set the first option
$rows[0] = array (
'value' => '0',
'label' => 'Top',
'selected' => TRUE,
'disabled' => FALSE
);
foreach ($res as $row) {
$rows[$row['triplet_id']] = array (
'value' => $row['col1'],
'label' => $row['col2'],
);
}
return $rows;
}

Related

Wordpress Metabox populate select from array

I'm trying to populate a select with the registered users (contributors) from an array to use it in the frontend, but for some reason I can't get it done.
Here's my code:
$user_query = new WP_User_Query(array('role' => 'Contributor'));
if (!empty($user_query->results))
{
$index = 0;
$contributors = array();
foreach ($user_query->results as $user)
{
$contributors[$index] = $user->ID;
$index++;
}
}
array(
'name' => esc_html__('Select', 'your-prefix'),
'id' => "{$prefix}tecnico",
'type' => 'select',
// Array of 'value' => 'Label' pairs for select box
'options' => $contributors,
// Select multiple values, optional. Default is false.
'multiple' => false,
'std' => 'value2',
'placeholder' => esc_html__('Select an Item', 'your-prefix'),
),

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
}

How to get posted data from from to email in SocialEngine?

I edited standard contact form in SocialEngine. Added new 4 fields to it - BirthDate, address, country & postal code field.
First question - how to properly set the default value of Country Select = "USA"?
Second question - how to get posted data from new form's fields (BirthDate, address, country & postal code) to user's email? How need to edit my controller?
My code:
class Pagecontact_Form_Contact extends Engine_Form
{
private $page_id;
public function __construct($page_id)
{
$this->page_id = $page_id;
parent::__construct();
}
public function init()
{
parent::init();
$this
->setTitle('Send Message to Apply for Sponsorship')
->setAttrib('id', 'page_edit_form_contact')
->setAttrib('class', 'global_form');
$topicsTbl = Engine_Api::_()->getDbTable('topics', 'pagecontact');
$topics = $topicsTbl->getTopics($this->page_id);
$viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity();
$options[0] = '';
foreach($topics as $topic)
{
$options[$topic['topic_id']] = $topic['topic_name'];
}
$this->addElement('Date', 'birthdate', array('label' => 'Birthdate:',
'class' => 'date_class', 'name' => 'birthdate'));
$this->addElement('Text', 'address', array('label' => 'Address:',
'class' => 'address_class', 'name' => 'address'));
$this->addElement('Select', 'country', array('label' => 'Country:',
'class' => 'country_class', 'name' => 'country')); //->setValue("USA");
$this->addElement('Text', 'postal', array('label' => 'Postal Code:',
'class' => 'postal_class', 'name' => 'postal'));
$this->addElement('Select', 'topic', array(
'label' => 'PAGECONTACT_Topic',
'class' => 'topic_class',
'multiOptions' => $options,
));
$this->getElement('topic')->getDecorator('label')->setOption('class','element_label_class topic_label_class');
$this->addElement('Hidden', 'visitor', array(
'value' => 0,
'order' => 3,
));
if ($viewer_id == 0)
{
$this->addElement('Text', 'sender_name', array(
'label' => 'PAGECONTACT_Full name',
'class' => 'subject_class',
'allowEmpty' => false,
'size' => 37,
'validators' => array(
array('NotEmpty', true),
array('StringLength', false, array(1, 64)),
),
'filters' => array(
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_EnableLinks(),
),
));
$this->getElement('sender_name')->getDecorator('label')->setOption('class','element_label_class sender_name_label_class');
$this->addElement('Text', 'sender_email', array(
'label' => 'PAGECONTACT_Email',
'class' => 'subject_class',
'allowEmpty' => false,
'size' => 37,
'validators' => array(
array('NotEmpty', true),
array('StringLength', false, array(1, 64)),
),
'filters' => array(
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_EnableLinks(),
),
));
$this->getElement('sender_email')->getDecorator('label')->setOption('class','element_label_class sender_email_label_class');
$this->addElement('Hidden', 'visitor', array(
'value' => 1,
'order' => 3,
));
}
$this->addElement('Text', 'subject', array(
'label' => 'PAGECONTACT_Subject',
'class' => 'subject_class',
'allowEmpty' => false,
'size' => 37,
'validators' => array(
array('NotEmpty', true),
array('StringLength', false, array(1, 64)),
),
'filters' => array(
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_EnableLinks(),
),
));
$this->getElement('subject')->getDecorator('label')->setOption('class','element_label_class subject_label_class');
$this->addElement('Textarea', 'message', array(
'label' => 'PAGECONTACT_Message',
'maxlength' => '512',
'class' => 'message_class',
'filters' => array(
new Engine_Filter_Censor(),
new Engine_Filter_Html(array('AllowedTags' => 'a'))
),
));
$this->getElement('message')->getDecorator('label')->setOption('class','element_label_class message_label_class');
$this->addElement('Hidden', 'page_id', array(
'value' => $this->page_id,
'order' => 7,
));
$this->addElement('Button', 'send', array(
'label' => 'Send',
'type' => 'button',
'class' => 'btn_send_class',
'name' => 'submitted'
));
}
}
Controller:
public function sendAction()
{
$page_id = $this->_getParam('page_id');
$topic_id = $this->_getParam('topic_id');
$subject = $this->_getParam('subject');
$message = $this->_getParam('message');
$senderName = $this->_getParam('sender_name');
$senderEmail = $this->_getParam('sender_email');
$birthDate = $this->getRequest()->getPost('birthdate'); // Empty set
$address = $this->getRequest()->getPost('adress'); // Empty set
$country = "USA"; // Works
$postal = $this->getRequest()->getPost('postal'); // Empty set
$pagesTbl = Engine_Api::_()->getDbTable('pages', 'page');
$select = $pagesTbl->select()
->from(array($pagesTbl->info('name')), array('displayname'))
->where('page_id = ?', $page_id);
$query = $select->query();
$result = $query->fetchAll();
$pageName = $result[0]['displayname'];
$viewer = $this->_helper->api()->user()->getViewer();
$user_id = $viewer->getIdentity();
$topicsTbl = Engine_Api::_()->getDbTable('topics', 'pagecontact');
$emails = $topicsTbl->getEmails($page_id, $topic_id);
$i = 0;
$emails = explode(',',$emails);
foreach($emails as $email) {
$emails[$i] = trim($email);
$i++;
}
if ($user_id != 0) {
$senderName = $viewer['displayname'];
$senderEmail = $viewer['email'];
}
foreach($emails as $email) {
// Make params
$mail_settings = array(
'date' => time(),
'page_name' => $pageName,
'sender_name' => $senderName,
'sender_email' => $senderEmail,
'subject' => $subject,
'message' => $message." ".$birthDate." ".$address." ".$country." ".$postal,
);
// send email
Engine_Api::_()->getApi('mail', 'core')->sendSystem(
$email,
'pagecontact_template',
$mail_settings
);
};
}
}
Eugene,
There is not country field in the your form. But you can do in controller where you are calling the form function like.
{
$form->getElement('country')->setvalue('USA');
}
Please feel free to ask your questions.

filtering cakedc search results

i'm using cakeDC's search plugin in my app. can;t seem to figure out why the results are empty if i pass no value in the username field i'm searching but have the account type filter set to either admin or user For the record, having the filter set to all with the username field empty will output all the users in the system trying to replicate the behavior of searches having the account type filter set to all with an empty username search field for having the account type filter set to either 2 user types
here's the relevant code if needed:
controller
public $components = array('Paginator', 'Session','Search.Prg');
public $presetVars = array(
array('field' => 'username', 'type' => 'value'),
array('field' => 'account_type', 'type' => 'value'));
public function admin_index() {
$this->Prg->commonProcess();
$this->paginate = array(
'conditions' => $this->User->parseCriteria($this->passedArgs));
$this->set('users', $this->Paginator->paginate(),'session',$this->Session);
model
public $actsAs = array('Search.Searchable');
public $filterArgs = array( array('name' => 'username', 'type' => 'query', 'method' => 'filterName'),
array('name' => 'account_type', 'type' => 'value'),
);
public function filterName($data, $field = null) {
$nameField = '%' . $data['username'] . '%';
return array(
'OR' => array(
$this->alias . '.username LIKE' => $nameField,
));
}
view search form
<div><?php echo $this->Form->create('User', array(
'novalidate' =>true,'url' => array_merge(array('action' => 'index','admin'=> true), $this->params['pass'])
)); ?>
<?php
$account_types = array(
'' => __('All', true),
0 => __('admin', true),
1 => __('user', true),);
echo $this->Form->input('username', array('div' => false, 'empty' => true)); // empty creates blank option.
echo $this->Form->input('account_type', array('label' => 'account_type', 'options' => $account_types));
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
?></div>
Try to put 'empty' and allowEmpty in username and account_type like this:
public $filterArgs = array( array('name' => 'username', 'type' => 'query', 'method' => 'filterName', 'empty'=>true, 'allowEmpty'=>true),
array('name' => 'account_type', 'type' => 'value','empty'=>true, 'allowEmpty'=>true),
);
I had this kind of behavior as well from CakeDC/search and this two configs saved me, hope it will do for you as well.
It's a good idea to check the queries being executed as well using DebugKit.Toolbar.

Why is my SQL query running twice?

I am using the Zend Framework 2 and notice my sql queries are running twice when pulling values from the database to use in my Forms. I can see in the developertool that it is running twice (two different run times). It only happens with the form elements (not when I echo query results into a table)
I used the below link as a guide:
http://samminds.com/2013/03/zendformelementselect-and-database-values/
Thanks
M
Controller Action
public function indexAction() //Display the pro greetings page
{
$this->layout()->setVariable('menu', 'verified');
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$form = new ProLicenceForm($dbAdapter);
$form->get('submit')->setValue('Submit');
$pro_id='22';
$proBackEnd = new ProSide($dbAdapter);
$form->get('pro_id')->setValue($pro_id);
// $user_id=$this->zfcUserAuthentication()->getIdentity()->getId(); //causes error if not register need to block or add logic to redirect
// $form->get('user_id')->setValue($user_id); //pass the user id from the user module
$request = $this->getRequest();
if ($request->isPost()) {
$proLicence = new ProLicence();
$form->setInputFilter($proLicence->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$proLicence->exchangeArray($form->getData());
$this->getProLicenceTable()->saveProLicence($proLicence);
// return $this->redirect()->toRoute('pro', array('action'=>'proVerification')); //redirect to next step
}
else {
echo "ERROR HOMMIE";
}
}
return array(
'form' => $form,
'proLicences' => $proBackEnd->getProSideLicence($pro_id),
);
}
Form
<?php
namespace Pro\Form;
use Zend\Form\Form;
use Zend\Db\Adapter\AdapterInterface;
class ProLicenceForm extends Form
{
public function __construct(AdapterInterface $dbAdapter)
{
// $this->setDbAdapter($dbAdapter);
$this->adapter =$dbAdapter;
// we want to ignore the name passed
parent::__construct('pro-licence-form');
$this->add(array(
'name' => 'pro_id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'licence_id',
'type' => 'Hidden',
'options' => array(
),
'attributes' => array(
//'required' => 'required'
)
));
$this->add(array(
'name' => 'licence_name_id',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Licence',
'value_options' => $this->getLicenceOptions(),
'empty_option' => '--- please choose ---'
),
'attributes' => array(
'placeholder' => 'Choose all that apply'
)
));
$this->add(array(
'name' => 'licence_number',
'type' => 'Text',
'options' => array(
'label' => 'Licence Number'
)
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'options' => array(
'label'=> 'Primary Button',
),
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
/*
* SQL statements used to bring in optiosn
*/
public function getLicenceOptions()
{
$dbAdapter = $this->adapter;
$sql = 'SELECT licence_name_id,licence_name FROM licence_name_table ORDER BY licence_name';
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[$res['licence_name_id']] = $res['licence_name'];
}
return $selectData;
}
}

Categories