zend-framework2zend-inputfilter

I need help about Input Filter


I have this method in Model TaiKhoan

public function getInputFilter()
{
   if (!$this->inputFilter) 
   {
      $inputFilter = new InputFilter();
      $factory     = new InputFactory();

      $inputFilter->add($factory->createInput(array(
            'name'     => 'TenTaiKhoan',
            'required' => true,
            'filters'  => array(
                  array('name' => 'StripTags'),
                  array('name' => 'StringTrim'),
            ),
      )));

      $inputFilter->add($factory->createInput(array(
            'name'     => 'MatKhau',
            'required' => true,
            'filters'  => array(
                  array('name' => 'StripTags'),
                  array('name' => 'StringTrim'),
            ),
      )));
   }

   return $this->$inputFilter;
}

Then i used it in my Controller like

$taikhoan = new TaiKhoan();

$form->setInputFilter($taikhoan->getInputFilter());

When i run, it show me this error

Catchable fatal error: Object of class Zend\InputFilter\InputFilter could not be converted to string in C:\wamp\www\ZF\module\CPanel\src\CPanel\Model\TaiKhoan.php on line 59

Solution

  • The problem is a typo in this statement:

    return $this->$inputFilter;
    

    PHP is interpreting this line as a dynamic property name, and this converting it to a string. The correct version is:

    return $this->inputFilter;
    

    Also you need to assign something to the input filter:

    public function getInputFilter()
    {
        if (!$this->inputFilter) 
        {
            // ...
            $this->inputFilter = $inputFilter;
        }
    
        return $this->inputFilter;
    }