Catchable fatal error: Argument 1 passed to
Zend\Validator\Db\AbstractDb::setAdapter() must be an instance of
Zend\Db\Adapter\Adapter, null given, called in
/home2/mapasgua/vendor/zendframework/zendframework/library/Zend/Validator/AbstractValidator.php
on line 142 and defined in
/home2/mapasgua/vendor/zendframework/zendframework/library/Zend/Validator/Db/AbstractDb.php
on line 168
Module.php
<?php
namespace User;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\ModuleRouteListener;
use User\Model\UsersTable;
use User\Model\Users;
class Module
{
public function onBootstrap(MvcEvent $e)
{
ini_set('date.timezone', 'America/Sao_Paulo');
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controllerClass = get_class($controller);
$moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
$config = $e->getApplication()->getServiceManager()->get('config');
if (isset($config['module_layouts'][$moduleNamespace])) {
$controller->layout($config['module_layouts'][$moduleNamespace]);
}
}, 100);
}
public function getAutoloaderConfig()
{
return array(
// 'Zend\Loader\ClassMapAutoloader' => array(
// __DIR__ . '/autoload_classmap.php',
// ),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'User\Model\UsersTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new UsersTable($dbAdapter);
return $table;
},
'User\Model\Users' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$users = new Users();
$users->setDbAdapter($dbAdapter);
return $users;
},
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
}
Users.php
<?php
namespace User\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\Db\Adapter\Adapter;
use Zend\Validator\Db\AbstractDb;
class Users implements InputFilterAwareInterface
{
public $id;
public $name;
public $username;
public $password;
protected $inputFilter;
public $_dbAdapter;
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->name = (isset($data['name'])) ? $data['name'] : null;
$this->username = (isset($data['username'])) ? $data['username'] : null;
$this->password = (isset($data['password'])) ? $data['password'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function setDbAdapter($dbAdapter)
{
$this->_dbAdapter = $dbAdapter;
}
public function getDbAdapter()
{
return $this->_dbAdapter;
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
'message' => 'Endereço de e-mail invalido',
),
),
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'users',
'field' => 'username',
'adapter' => $this->getDbAdapter(),
'exclude' => array(
'field' => 'id',
'value' => !is_null( $this->id ) && !empty( $this->id ) ? $this->id : 0,
),
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'retype-password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
),
),
array(
'name' => 'Identical',
'options' => array(
'token' => 'password', //I have tried $_POST['password'], but it doesnt work either
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
UserController.php
namespace User\Controller;
<?php
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
use Zend\Authentication\Result as Result;
use Zend\Mail;
use User\Form\LoginForm;
use User\Form\RegisterForm;
use User\Form\RecuperarForm;
use User\Model\Users;
class UserController extends AbstractActionController
{
protected $usersTable;
public function configAction()
{
$auth = new AuthenticationService();
$form = new RegisterForm();
$identity = null;
if ($auth->hasIdentity()) {
$dados = $this->getUsersTable()->getUser($auth->getIdentity());
$request = $this->getRequest();
if ($request->isPost()) {
$users = new Users();
$post = $request->getPost();
$form->setInputFilter($users->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$users->exchangeArray($post);
$this->getUsersTable()->saveUsers($users);
$this->flashMessenger()->addMessage("Configurações atualizadas com sucesso.");
return $this->redirect()->toRoute('painel');
}
} else {
$post = array(
'id' => $dados->id,
'name' => $dados->name,
'username' => $dados->username,
);
$form->setData($post);
}
} else {
return $this->redirect()->toRoute('login');
}
return array(
'form' => $form,
);
}
Your problem is you have defined a factory for Users but you don't use it. The line $users = new Users(); directly instantiates the object without using your factory.
Change it to
$users = $this->getServiceLocator()->get('User\Model\Users');
As your object relies on Zend\Db\Adapter\Adapter you need your factory to inject this for you.
Related
When I use my application from localhost it works fine, but when I deploy the application in the server I get the next error:
Fatal error: Class 'PFC\Model\GestoresPFC' not found in /var/www/html/pfpdi/module/PFC/Module.php on line 59
I'm using a module with the next tree structure
PFC/
Config/
src/
Controller/
Form/
Model/
gestoresPFC.php
gestoresPFCTable.php
PFC.php
PFCTable.php
view/
autoload_classmap.php
Module.php
Where gestoresPFC.php is like:
<?php
namespace PFC\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class GestoresPFC implements InputFilterAwareInterface
{
public $gestor_id;
public $plan_id;
protected $inputFilter; // <-- Add this variable
public function exchangeArray($data)
{
$this->gestor_id = (isset($data['gestor_id'])) ? $data['gestor_id'] : null;
$this->plan_id = (isset($data['plan_id'])) ? $data['plan_id'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
// Add content to these methods:
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'gestor_id',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$inputFilter->add(array(
'name' => 'plan_id',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 11,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
And Module.php is like:
<?php
namespace PFC;
use PFC\Model\PFC;
use PFC\Model\PFCTable;
use PFC\Model\GestoresPFC;
use PFC\Model\GestoresPFCTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return array(
'factories' => array(
'PFC\Model\PFCTable' => function($sm) {
$tableGateway = $sm->get('PFCTableGateway');
$table = new PFCTable($tableGateway);
return $table;
},
'PFCTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new PFC());
return new TableGateway('plan_formacion', $dbAdapter, null, $resultSetPrototype);
},
'PFC\Model\GestoresPFCTable' => function($sm) {
$tableGateway = $sm->get('GestoresPFCTableGateway');
$table = new GestoresPFCTable($tableGateway);
return $table;
},
'GestoresPFCTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new GestoresPFC());
return new TableGateway('gestores', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
gestoresPFC.php should be GestoresPFC.php. The filename needs to match the class name. I'm guessing you developed this site on a case-insensitive file system (e.g. Windows) where this wouldn't matter.
I have a problem in validating the array of value of an element. I search a lot find a callback function to validate that data.
Below is the validation code which i am using but it is not working
<?php
namespace Tutorials\Form;
use Zend\InputFilter\Factory as InputFactory; // <-- Add this import
use Zend\InputFilter\InputFilter; // <-- Add this import
use Zend\InputFilter\InputFilterAwareInterface; // <-- Add this import
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\Callback;
use Zend\I18n\Validator\Alpha;
class AddSubTopicFilterForm extends InputFilter implements InputFilterAwareInterface {
protected $inputFilter;
public $topicData;
public $subTopicData;
function __construct($data = array()) {
$articles = new \Zend\InputFilter\CollectionInputFilter();
$articlesInputFilter = new \Zend\InputFilter\InputFilter();
$articles->setInputFilter($articlesInputFilter);
$this->add(new \Zend\InputFilter\Input('title'));
$this->add($articles, 'articles');
if(!empty($data['data']['topic_name'])) {
$this->topicData = $data['data']['topic_name'];
}
if(!empty($data['data']['sub_topic_name'])) {
$this->subTopicData = $data['data']['sub_topic_name'];
}
}
public function setInputFilter(InputFilterInterface $inputFilter){
throw new \Exception("Not used");
}
public function getInputFilter(){
if (!$this->inputFilter) {
$dataTopic = $this->topicData;
$dataSubTopic = $this->subTopicData;
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'topic_name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Callback',
'options' => array(
'messages' => array(
\Zend\Validator\Callback::INVALID_VALUE => 'Seletec value is not valid',
),
"callback" => function() use ($dataTopic) {
$strip = new \Zend\I18n\Validator\IsInt();
foreach($dataTopic as $key => $tag) {
$tag = $strip->isValid((int)$tag);
$dataTopic[$key] = $tag;
}
return $dataTopic;
},
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'sub_topic_name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Callback',
'options' => array(
'messages' => array(
\Zend\Validator\Callback::INVALID_VALUE => 'Invalid Sub Topic Name',
),
"callback" => function() use ($dataSubTopic) {
$strip = new \Zend\Validator\StringLength(array('encoding' => 'UTF-8','min' => 1,'max' => 100));
foreach($dataSubTopic as $key => $tag) {
$tag = $strip->isValid($tag);
$dataSubTopic[$key] = $tag;
}
return $dataSubTopic;
},
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
In the above line of code the value of
$data['data']['topic_name']=array('0' => 1,'1' => 1)
and $data['data']['sub_topic_name']=array('0'=>'Testing','1'=>'Testing1');
and i am calling it
$form = new AddSubTopicForm();
$logFilterForm = new AddSubTopicFilterForm();
$form->setInputFilter($logFilterForm->getInputFilter());
$form->setData($request->getPost());
Below is the of the form class
<?php
namespace Tutorials\Form;
use Zend\Form\Element;
use Zend\Form\Form;
class AddSubTopicForm extends Form {
public function __construct($data = array()){
parent::__construct('AddSubTopic');
$this->setAttribute('class', 'form-horizontal');
$this->setAttribute('novalidate', 'novalidate');
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'topic_name[]',
'attributes' => array(
'id' => 'topic_name',
'class' => 'form-control',
),
'options' => array(
'label' => ' Topic Name',
'empty_option'=>'---None--- ',
'value_options' => array(
'1' => 'PHP'
),
),
));
$this->add(array(
'name' => 'sub_topic_name[]',
'attributes' => array(
'type' => 'text',
'id' => 'sub_topic_name',
'class' => 'form-control',
'value' => ''
),
'options' => array(
'label' => ' Sub Topic Name',
),
));
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
'id' => 'id'
)
));
$button = new Element('add_more_sub_topic');
$button->setValue('+AddMore');
$button->setAttributes(array(
'type' => 'button',
'id'=>'add_more',
'class'=>'btn btn-info'
));
$save = new Element('save');
$save->setValue('Save');
$save->setAttributes(array(
'type' => 'submit',
'id'=>'save',
'class'=>'btn btn-info'
));
$reset = new Element('reset');
$reset->setValue('Reset');
$reset->setAttributes(array(
'type' => 'reset',
'id'=>'reset',
'class'=>'btn'
));
$this->add($button);
$this->add($save);
$this->add($reset);
}//end of function_construct.
}//end of registration form class.
But it is not calling the filter callback function rather give me an error on first first form field that 'value is required ,can't be empty'
I don't why it is not validating data.Suggest me what where i am wrong and how can i overcome from this problem. Any help would be appreciated. Than.x
Fatal error: Call to a member function setAttribute() on null in \module\Admin\view\admin\index\login.phtml when trying to create form using Zend Framework
Can somebody help me with where am doing wrong. I pasted all the code.
\module\Admin\src\Admin\Controller\LoginController.php
class LoginController extends AbstractActionController
{
protected $usersTable = null;
public function indexAction()
{
return new ViewModel();
}
public function loginAction(){
$form = new LoginForm();
$form->get('submit')->setValue('Login');
$request = $this->getRequest();
if($request->isPost()){
$login = new Login();
$form->setInputFilter($login->getInputFilter());
$form->setData($request->getPost());
if($form->isValid()){
$login->exchangeArray($form->getData());
$this->getLoginDetails()->saveLoginForm($login);
// Redirect to list of albums
return $this->redirect()->toRoute('index');
}
}
return array('form' => $form);
}
}
\module\Admin\src\Admin\Form
namespace Admin\Form;
use Zend\Form\Form;
class LoginForm extends Form
{
public function _construct()
{
parent::_construct('admin');
$this->add(array(
'name' => 'username',
'type' => 'Text',
'options' => array(
'label' => 'Username',
'id' => 'txtUsername',
),
));
$this->add(array(
'name' => 'password',
'type' => 'password',
'options' => array(
'label' => 'Password',
'id' => 'txtPassword',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Login',
'id' => 'btnSubmit',
),
));
}
}
\module\Admin\src\Admin\Model
namespace Admin\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Login implements InputFilterAwareInterface{
public $username;
public $password;
protected $inputFilter;
public function exchangeArray($data)
{
$this->artist = (isset($data['username'])) ? $data['username'] : null;
$this->title = (isset($data['password'])) ? $data['password'] : null;
}
public function setInputFilter(InputFilterInterface $inputFilter){
throw new \Exception("not used");
}
public function getInputFilter(){
if(!$this->inputFilter){
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 50,
),
),
),
));
$inputFilter->add(array(
'name' => 'password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 50,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
\module\Admin\view\admin\index
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('admin', array('action' => 'login')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('username'));
echo $this->formRow($form->get('password'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
echo $this->$form;
What is $form = $this->form?
Is used in controller? Where do you pass anything on $this->form. Its null, like you see error. You can var_dump($form) to check it. You need to create your form first with:
$form = new \My\Form();
If $form is null inside login.phtml, thats mean you dont passed $form variable to phtml script (we dont see it in your code)
When you want to change element attribute you have to get that element by using getElement function then use zend form function. Try below code it will work for you.
$form = new LoginForm();
$form->getElement('submit')->setValue('get');
I'm trying to learn ZF2, and I am not able to edit the data in the edit form. I have two classes Pessoa and Endereco and I have a form to edit the data, but it only changes the data related to Pessoa, those about the Endereco is stored as blank.
And when trying to add a new record (add action) i get the following error:
Fatal error: Cannot use object of type Pessoa\Model\Pessoa as array in /opt/lampp/htdocs/cad/module/Pessoa/src/Pessoa/Model/Pessoa.php on line 23
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 add e edit actions
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',
),
));
}
}
And trying to add a new record (add action) i get the following error:
Fatal error: Cannot use object of type Pessoa\Model\Pessoa as array in /opt/lampp/htdocs/cad/module/Pessoa/src/Pessoa/Model/Pessoa.php on line 23
Please, can anyone help me?
So let me explain better my self,
You are sending an array to the method
exchangeArray($data);
but $data is not an array;
Example of Array:
$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 )
Example Object:
$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 )
So i reproduce part of the code you have above and i gave to the method exchangeArray($data); of type Array and i got no errors then i gave to the method exchangeArray($object); and the result was
Fatal error: Cannot use object of type stdClass as array in /blah/blah/... on line 39
So Basically in your method you are passing $data of type object and not Array
I am trying to create login page in zend framework2. I have created its view,controller,model and form. Even i m not getting any error.
following my code :
My model as Login.php is :
class Login implements InputFilterAwareInterface
{
public $id;
public $username;
public $password;
protected $inputFilter;
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->username = (!empty($data['username'])) ? $data['username'] : null;
$this->password = (!empty($data['password'])) ? $data['password'] : 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();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$inputFilter->add(array(
'name' => 'password',
'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;
}
}
My LoginForm is :
namespace Application\Form;
use Zend\Form\Form;
class LoginForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('tbluser');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'username',
'type' => 'Text',
'options' => array(
'label' => '',
),
'attributes' => array(
'id' => 'username',
'class'=>'',
'autocomplete'=>'OFF',
'max'=>'100',
),
));
$this->add(array(
'name' => 'password',
'type' => 'Text',
'options' => array(
'label' => '',
),
'attributes' => array(
'id' => 'password',
'class'=>'',
'autocomplete'=>'OFF',
'max'=>'100',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Login',
'id' => 'login',
'class'=>'btn btn-success',
),
));
}
}
and my controller action code is :
public function indexAction()
{
$form = new LoginForm();
$request = $this->getRequest();
$user=new LoginTable();
if ($request->isPost()) {
$login = new Login();
$form->setInputFilter($login->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$data=$login->exchangeArray($form->getData());
$user->getUser($this->$username,$this->$password);
if($user){
return $this->redirect()->toRoute('album', array(
'action' => 'album'));
}else{
return array('form' => $form);
}
}
}
return array('form' => $form);
}
my form is not validating at this statement "if ($form->isValid()){}" the exicution is not entering in this statement. I searched out every thing but not able to find solution what i m missing. Can any body help me to get out of this.
Looking at the form it looks as if you have an input filter attached to the hidden field id. If you are looking to register the user you obviously will not have their id before authentication.
You can test this by adding a else statement of your form and checking the forms messages (because the element is hidden you will not see it output otherwise)
if ($form->isValid()) {
// Is valid code here
} else {
print_r($form->getMessages());
}
This will probably output and array with the message "id - this element cannot be empty" or something similar.
The solution would be to remove the id input filter from the form (and probably the id form element as I can't see how this would be needed).