Rathilesh C
Rathilesh C

Reputation: 131

How to call a controller function inside the form in zend 2

i am new in zend framework

i need to add dynamic values inside the form selection elements

$this->add(array(
        'type' => 'Zend\Form\Element\Select',
        'name' => 'SECTOR_ID',
        'attributes' => array(
            'class' => 'form-control select2drop',
            'id' => 'Sector_ID'
        ),
        'options' => array(
            'value_options' => $this->getOptionsForSectorSelect(),
        ),
        'disable_inarray_validator' => true
    ));

above code help me to get dynamic values

but i need to call a controller function for getting value , now i wrote getOptionsForSectorSelect inside the form Please help me

Upvotes: 0

Views: 306

Answers (1)

melledijkstra
melledijkstra

Reputation: 359

You could make the method inside your Controller static

class IndexController extends AbstractActionController {

    public static function getOptionsForSectorSelect() {
        // Building dynamic array ...
        return $dynamicArray;
    }      

    // More code ...
}

Or you could pass the array with your form when creating it in your action like so:

public function indexAction() {
    $dynamicArray = $this->getOptionsForSectorSelect();
    $myForm = new YourForm($dynamicArray);
    // more action code...
}

And then in your form:

class YourForm extends Form {

    private $dynamicArray;

    public function __construct(array $dynamicArray) {
        $this->dynamicArray = $dynamicArray;
    }

    $this->add(array(
        'type' => 'Zend\Form\Element\Select',
        'name' => 'SECTOR_ID',
        'attributes' => array(
            'class' => 'form-control select2drop',
            'id' => 'Sector_ID'
        ),
        'options' => array(
            'value_options' => $this->dynamicArray,
        ),
        'disable_inarray_validator' => true,
    ));

}

Hope it helps! :)

Upvotes: 1

Related Questions