ZendFramework 2 - 如何使用fieldsets编辑表单数据?

时间:2014-07-30 19:46:58

标签: php forms zend-framework2 fieldset

我正在尝试学习ZF2,但我无法编辑编辑表单中的数据。我有两个类Pessoa和Endereco,我有一个表格来编辑数据,但它只更改了与Pessoa相关的数据,那些关于Endereco的数据被存储为空白。

当尝试添加新记录(添加操作)时,我收到以下错误:

致命错误:不能在第23行的/opt/lampp/htdocs/cad/module/Pessoa/src/Pessoa/Model/Pessoa.php中使用Pessoa \ Model \ Pessoa类型的对象作为数组

Pessoa.php

class Pessoa
{
 public $id;
 public $nome;
 public $dtNasc;
 public $endereco;
 protected $inputFilter;

 public function __construct()
 {
  $this->endereco = new Endereco();
 }
 public function exchangeArray($data)
 {
  $this->id      = (!empty($data['id'])) ? $data['id'] : null;
  $this->nome    = (!empty($data['nome'])) ? $data['nome'] : null;
  $this->dtNasc  = (!empty($data['dtNasc'])) ? $data['dtNasc'] : null;
  //$this->getEndercoInstance();
  $this->endereco->exchangeArray($data);
  /*if (isset($data["endereco"]))
  {
    if (!is_object($this->endereco)) $this->endereco = new Endereco();
    $this->endereco->exchangeArray($data["endereco"]);
   }*/
 }

 public function getArrayCopy()
 {
  $data = get_object_vars($this);

    if (is_object($this->endereco)) {
        $data["endereco"] = $this->endereco->getArrayCopy();
    }

    return $data;
 }

 public function setEndereco($end)
 {
  $this->endereco = $end;   
 }
private function getEndercoInstance()
{
 $di     = new Zend\Di;
 $config = new Zend\Di\Configuration(array(
 'instance' => array(                
    'Pessoa' => array(
        // letting Zend\Di find out there's a $bar to inject where possible
        'parameters' => array('endereco' => 'Endereco\Model\Endereco'),
    )
 )
));
$config->configure($di);

$pessoa = $di->get('Pessoa');
$this->endereco = $pessoa->endereco;
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
 throw new \Exception("Not used");
}

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'     => 'nome',
            'required' => true,
            'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
            ),
            'validators' => array(
                    array(
                            'name'    => 'StringLength',
                            'options' => array(
                                    'encoding' => 'UTF-8',
                                    'min'      => 1,
                                    'max'      => 100,
                            ),
                    ),
            ),
    ));

    $this->inputFilter = $inputFilter;
 }

  return $this->inputFilter;
 }


}

Endereco.php

class Endereco
{
 public $rua;
 public $bairro;

public function exchangeArray($data)
{
 $this->rua = (!empty($data["rua"])) ? $data["rua"] : null;
 $this->bairro = (!empty($data["bairro"])) ? $data["bairro"] : null;
}

public function getArrayCopy()
{
 return get_object_vars($this);
}
}

PessoaController.php添加电子编辑动作

public function addAction()
 {
    $form = new PessoaForm();
    $form->get('submit')->setValue('Add');

    $request = $this->getRequest();
    if ($request->isPost()) {
        $pessoa = new Pessoa();
        //$form->setInputFilter($pessoa->getInputFilter());
        $form->setData($request->getPost());
        if ($form->isValid()) {
            $pessoa->exchangeArray($form->getData());
            $this->getPessoaTable()->savePessoa($pessoa);

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

 }

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

    try {
        $pessoa = $this->getPessoaTable()->getPessoa($id);
    }
    catch (\Exception $ex) {
        return $this->redirect()->toRoute('pessoa', array(
                'action' => 'index'
        ));
    }
    $form  = new PessoaForm();  
    $form->bind($pessoa);
    $form->get('submit')->setAttribute('value', 'Edit');
    $request = $this->getRequest();
    if ($request->isPost()) {
        //$form->setInputFilter($pessoa->getInputFilter());
        $form->setData($request->getPost());
        if ($form->isValid()) {
            $this->getPessoaTable()->savePessoa($pessoa);
            // Redirect to list of pessoa
            return $this->redirect()->toRoute('pessoa');
        }else{
            echo "not valid";
        }
    }

    return array(
            'id' => $id,
            'form' => $form,
    );
 }

EnderecoFieldSet.php

class EnderecoFieldSet extends Fieldset
{
public function __construct($name = null)
{
    parent::__construct('endereco');
    $this->setHydrator(new ArraySerializableHydrator())
          ->setObject(new Endereco());

    $this->add(array(
        'name' => 'rua',
        'option' => array(
          'label' => 'Rua: ',
       ),
    ));
    $this->add(array(
            'name' => 'bairro',
            'option' => array(
                    'label' => 'Bairro: ',
            ),
    ));
 }
}

PessoaFieldSet.php

class PessoaFieldSet extends Fieldset
{
//public $endereco;
public function __construct()
{
    //$this->endereco = new Endereco()
    $this->init();
}
public function init()
{
    parent::__construct('pessoa');
    $this->setHydrator(new ArraySerializableHydrator())
    ->setObject(new Pessoa());
    $this->add(array(
            'name' => 'id',
            'type' => 'Hidden',
    ));
    $this->add(array(
            'name' => 'nome',
            'type' => 'Text',
            'options' => array(
                    'label' => 'Nome:',
            ),
            'attributes' => array(
                    'required' => 'required',
            ),
    ));
    $this->add(array(
            'name' => 'dtNasc',
            'type' => 'Text',
            'options' => array(
                    'label' => 'Data Nascimento:',
            ),
    ));
    $this->add(array(
            'type' => 'Pessoa\Form\EnderecoFieldSet',
            'name' => 'endereco',
            'options' => array(
                    'label' => 'endereco',
            ),
    ));
 }

PessoaForm.php

class PessoaForm extends Form
{

public function __construct()
{
    $this->init();
}
public function init()
{
    // we want to ignore the name passed
    parent::__construct('pessoa_form');

    $this->setHydrator(new ArraySerializableHydrator());
         //->setInputFilter(new InputFilter());

    $this->add(array(
            'type' => 'Pessoa\Form\PessoaFieldSet',
            'options' => array(
                    'use_as_base_fieldset' => true
            )
    ));

    $this->add(array(
            'type' => 'Zend\Form\Element\Csrf',
            'name' => 'csrf'
    ));

    $this->add(array(
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => array(
                    'value' => 'Go',
                    'id' => 'submitbutton',
            ),
    ));
 }
}

尝试添加新记录(添加操作)后,我收到以下错误:

致命错误:不能在第23行的/opt/lampp/htdocs/cad/module/Pessoa/src/Pessoa/Model/Pessoa.php中使用Pessoa \ Model \ Pessoa类型的对象作为数组

拜托,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

所以让我更好地解释一下自己,

您正在向方法发送数组

  

exchangeArray($数据);

但$ data 数组;

数组示例:

$data['username'] = 'someuser'; 
$data['email'] = 'someuser@someuser.com'; 
$data['phone'] = '235346346';
print_r($data);die;

//output:
//Array ( [username] => someuser [email] => someuser@someuser.com [phone] => 235346346 )

示例对象:

$data['username'] = 'someuser'; 
$data['email'] = 'someuser@someuser.com'; 
$data['phone'] = '235346346';

$object = (object)$data;
print_r($object);die;
//Output
//stdClass Object ( [username] => someuser [email] => someuser@someuser.com [phone] => 235346346 ) 

所以我重现了你上面的部分代码,我给了方法exchangeArray($ data);类型数组,我没有错误,然后我给方法exchangeArray($ object);结果是 致命错误:不能在第39行的/ blah / blah / ...中使用stdClass类型的对象作为数组

所以基本上在你的方法中,你传递的是object类型的$ data而不是Array