Skip to content

Instantly share code, notes, and snippets.

@samsonasik
Created September 20, 2012 04:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save samsonasik/3753984 to your computer and use it in GitHub Desktop.
Save samsonasik/3753984 to your computer and use it in GitHub Desktop.
Form Select in ZF2
namespace SampleModule\Form;
use Zend\Form\Form;
class SampleForm extends Form
{
public function __construct($name = null)
{
parent::__construct('Sample Form');
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'gender',
'options' => array(
'label' => 'Gender',
'value_options' => array(
'1' => 'Select your gender',
'2' => 'Female',
'3' => 'Male'
),
),
'attributes' => array(
'value' => '1' //set selected to '1'
)
));
}
}
For inputfilter :
namespace SampleModule\Model;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Sample implements InputFilterAwareInterface
{
public $gender;
protected $inputFilter;
public function exchangeArray($data)
{
$this->gender = (isset($data['gender'])) ? $data['gender'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
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' => 'gender',
'validators' => array(
array(
'name' => 'InArray',
'options' => array(
'haystack' => array(2,3),
'messages' => array(
\Zend\Validator\InArray::NOT_IN_ARRAY => 'Please select your gender !'
),
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
@phanorcoll
Copy link

thanks for the example..really helpful...

@samsonasik
Copy link
Author

You're welcome ;)

@athidev
Copy link

athidev commented Sep 18, 2013

hi

how to populate a Zend\Form\Element\Select with data from the database.

@ilhuicaminaTenoch
Copy link

Hi
how to populate a Zend\Form\Element\Select with data from the database.

@SamirBenzenine
Copy link

This is more a hack than a real solution for the InArray Validator problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment