Zend Framework 2 - How to keep value in form fields ? on multiple record update?

315 views Asked by At

I am working on zend framwork 2

I have created one module with two fields 1) Test1 2) Test2

Database structure for this :

  1. db name : zend_test_db
  2. db fields : config_key , config_value

I want to store like config_key = test1key and config_value : textbox enter value

Multiple records store at a time.

below is my controller function :

public function indexAction()
    {
       $form = new ConfigurationForm();
       $form->get('submit')->setValue('Save Settings');
       $form->get('test1key')->setValue('test1key');
       $form->get('test2key')->setValue('test2key');

 $request = $this->getRequest();
         if ($request->isPost()) {
             $configuration = new Configuration();
             $form->setInputFilter($configuration->getInputFilter());
             $form->setData($request->getPost());

             if ($form->isValid()) {
                 $configuration->exchangeArray($form->getData());     
                 $this->getConfigurationTable()->saveConfiguration($configuration);

                 // Redirect to list of configuration
                 return $this->redirect()->toRoute('configuration');
             }
         }
         return array('form' => $form);
    }

Above code works fine on Add fields . I am able to insert those fields and stored as key and value

But i am not able to update this.

Hope its clear

Where do i make mistake ?

1

There are 1 answers

1
Pardeep Kumar On BEST ANSWER

I am not able to comment as I have reputation less then 50. I think you are trying to say that you are able to insert the data in database but you are not able to update it.

This is happening because you are creating new model every time.

$configuration = new Configuration();

You should initialize it using id params.

$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
         return $this->redirect()->toRoute('configuration', array(
                 'action' => 'add'
             ));
}


try {
     $configuration = $this->getConfigurationTable()->getConfiguration($id);
 }
  catch (\Exception $ex) {
       return $this->redirect()->toRoute('configuration', array(
                'action' => 'index'
          ));
  }

Using this you will be able to update the data as well. For more reference you can check zend framework Album module. Here is the link https://framework.zend.com/manual/2.2/en/user-guide/forms-and-actions.html

If this was not the problem then please let me know so that I can help you in this concern.