Skip to content

Instantly share code, notes, and snippets.

@NiltonMorais
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save NiltonMorais/bae262759fbf9d3d865c to your computer and use it in GitHub Desktop.

Select an option

Save NiltonMorais/bae262759fbf9d3d865c to your computer and use it in GitHub Desktop.
Catchable fatal error: Argument 1 passed to Zend\Form\Element\Select::setValueOptions() must be of the type array, null given, called in C:\Users\Nilton\Google Drive\localhost\AutoEscola\src\module\Aluno\src\Aluno\Form\Contrato.php on line 42
<?php
namespace Aluno\Model;
use Zend\Db\TableGateway\TableGateway;
use \Exception;
// import for fetchPaginator
use Zend\Db\Sql\Select,
Zend\Db\ResultSet\HydratingResultSet,
Zend\Stdlib\Hydrator\Reflection,
Zend\Paginator\Adapter\DbSelect,
Zend\Paginator\Paginator;
class AlunoTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
public function fetchAll(){
return $this->tableGateway->select();
}
public function fetchPairs(){
$todos = $this->fetchAll();
$array = array();
foreach($todos as $aluno){
$array[$aluno->id] = $aluno->nome;
}
return $array;
}
public function find($id){
$id = (int)$id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if(!$row){
throw new Exception("Não foi encontrado aluno de id = {$id}");
}
return $row;
}
public function save(Aluno $aluno)
{
$timeNow = new \DateTime();
$data = [
'nome' => $aluno->nome,
'email' => $aluno->email,
'sexo' => $aluno->sexo,
'telefone' => $aluno->telefone,
'telefone2' => $aluno->telefone2,
'data_nascimento' => $aluno->data_nascimento,
'data_cadastro' => $timeNow->format('Y-m-d H:i:s'),
'data_alteracao' => $timeNow->format('Y-m-d H:i:s'), # data de criação igual a de atualização
];
return $this->tableGateway->insert($data);
}
public function update(Aluno $aluno)
{
$timeNow = new \DateTime();
$data = [
'nome' => $aluno->nome,
'email' => $aluno->email,
'sexo' => $aluno->sexo,
'telefone' => $aluno->telefone,
'telefone2' => $aluno->telefone2,
'data_nascimento' => $aluno->data_nascimento,
'data_alteracao' => $timeNow->format('Y-m-d H:i:s'), # data de criação igual a de atualização
];
$id = (int) $aluno->id;
if ($this->find($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new Exception("Aluno #{$id} inexistente");
}
}
public function delete($id)
{
$this->tableGateway->delete(array('id' => (int) $id));
}
/**
* Localizar itens por paginação
*
* @param type $pagina
* @param type $itensPagina
* @param type $ordem
* @param type $like
* @param type $itensPaginacao
* @return type Paginator
*/
public function fetchPaginator($pagina = 1, $itensPagina = 10, $ordem = 'nome ASC', $like = null, $itensPaginacao = 5)
{
$select = (new Select('alunos'))->order($ordem);
if (isset($like)) {
$select
->where
->like('id', "%{$like}%")
->or
->like('nome', "%{$like}%")
->or
->like('telefone', "%{$like}%")
->or
->like('data_cadastro', "%{$like}%")
->or
;
}
$resultSet = new HydratingResultSet(new Reflection(), new Aluno());
$paginatorAdapter = new DbSelect(
$select,
$this->tableGateway->getAdapter(),
$resultSet
);
return (new Paginator($paginatorAdapter))
// pagina a ser buscada
->setCurrentPageNumber((int) $pagina)
// quantidade de itens na página
->setItemCountPerPage((int) $itensPagina)
->setPageRange((int) $itensPaginacao);
}
}
<?php
namespace Aluno\Form;
use Zend\Form\Form,
Zend\Form\Element\Select,
Zend\Form\Element;
class Contrato extends Form{
protected $alunos;
public function __construct($name = null, array $alunos = null)
{
parent::__construct('contrato');
$this->alunos = $alunos;
$this->setInputFilter(new ContratoFilter);
$this->setAttributes(array(
'method' => 'post',
'class' => 'form-horizontal',
));
$this->add(array(
'type' => 'Hidden',
'name' => 'id',
));
$aluno = new Select();
$aluno->setName("aluno_id")
->setAttributes(array(
'class' => 'form-control',
'id' => 'aluno_id',
'placeholder' => 'Alunos',
'required' => true,
))
->setValueOptions($this->alunos)
->setEmptyOption('Insira um aluno')
->setDisableInArrayValidator(true);
$this->add($aluno);
$this->add(array(
'name' => 'valor',
'options' => array(
'type' => 'text',
'label' => 'Valor',
),
'attributes' => array(
'class' => 'form-control',
'id' => 'nome',
'placeholder' => 'Valor',
'required' => true,
),
));
$this->add(array(
'type' => 'text',
'name' => 'quant_meses',
'attributes' => array(
'class' => 'form-control',
'id' => 'quant_meses',
'placeholder' => 'Quantidade Meses',
'required' => true,
),
));
$this->add(array(
'type' => 'Date',
'name' => 'data_inicio',
'attributes' => array(
'class' => 'form-control',
'id' => 'data_inicio',
'placeholder' => 'Data de Início',
'required' => true,
),
));
$this->add(array(
'type' => 'Date',
'name' => 'data_fim',
'attributes' => array(
'class' => 'form-control',
'id' => 'data_fim',
'placeholder' => 'Data de Fim',
'required' => true,
),
));
// elemento para evitar ataques Cross-Site Request Forgery
$this->add(new Element\Csrf('security'));
}
}
// coloquei só a action Novo e Adicionar (que é a action que o formulário está enviando)
public function novoAction()
{
$alunos = $this->getServiceLocator()->get("ModelAluno")->fetchPairs();
return ['form' => new $this->form(null, $alunos)];
}
public function adicionarAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
$form = new $this->form();
$form->setData($request->getPost());
$model = new $this->model();
if ($form->isValid()) {
$model->exchangeArray($form->getData());
$this->getServiceTable()->save($model);
$this->flashMessenger()->addSuccessMessage("Cadastro criado com sucesso");
return $this->redirect()->toRoute($this->route);
} else {
$this->flashMessenger()->addErrorMessage("Erro ao criar cadastro");
return (new ViewModel())
->setVariable('form', $form)
->setTemplate($this->caminhoViews.'novo');
}
}
<?php
namespace Aluno\Form;
use Zend\Form\Form,
Zend\Form\Element\Select,
Zend\Form\Element;
class Contrato extends Form{
protected $alunos;
public function __construct($name = null, array $alunos = null)
{
parent::__construct('contrato');
$this->alunos = $alunos;
$this->setInputFilter(new ContratoFilter);
$this->setAttributes(array(
'method' => 'post',
'class' => 'form-horizontal',
));
$this->add(array(
'type' => 'Hidden',
'name' => 'id',
));
$aluno = new Select();
$aluno->setName("aluno_id")
->setAttributes(array(
'class' => 'form-control',
'id' => 'aluno_id',
'placeholder' => 'Alunos',
'required' => true,
))
->setValueOptions($this->alunos)
->setEmptyOption('Insira um aluno')
->setDisableInArrayValidator(true);
$this->add($aluno);
$this->add(array(
'name' => 'valor',
'options' => array(
'type' => 'text',
'label' => 'Valor',
),
'attributes' => array(
'class' => 'form-control',
'id' => 'nome',
'placeholder' => 'Valor',
'required' => true,
),
));
$this->add(array(
'type' => 'text',
'name' => 'quant_meses',
'attributes' => array(
'class' => 'form-control',
'id' => 'quant_meses',
'placeholder' => 'Quantidade Meses',
'required' => true,
),
));
$this->add(array(
'type' => 'Date',
'name' => 'data_inicio',
'attributes' => array(
'class' => 'form-control',
'id' => 'data_inicio',
'placeholder' => 'Data de Início',
'required' => true,
),
));
$this->add(array(
'type' => 'Date',
'name' => 'data_fim',
'attributes' => array(
'class' => 'form-control',
'id' => 'data_fim',
'placeholder' => 'Data de Fim',
'required' => true,
),
));
// elemento para evitar ataques Cross-Site Request Forgery
$this->add(new Element\Csrf('security'));
}
}
<div class="panel panel-primary">
<div class="panel-heading">
<div class="panel-title">
Novo Contrato
</div>
</div>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('contratos', array('action' => 'adicionar')));
$form->prepare();
echo $this->form()->openTag($form);
?>
<form class="form-horizontal" role="form" method="POST" action="<?php echo $this->url('contratos', array('action' => 'adicionar')); ?>">
<div class="panel-body">
<div class="form-group">
<label for="aluno_id" class="col-lg-3 col-md-3 control-label">Aluno:</label>
<div class="col-lg-9 col-md-9">
<?php echo $this->formRow($form->get('aluno_id'));
// renderiza elemento de erro
echo $this->formElementErrors()
->setMessageOpenFormat('<small class="text-danger">')
->setMessageSeparatorString('</small><br/><small class="text-danger">')
->setMessageCloseString('</small>')
->render($form->get('aluno_id'));
?>
</div>
</div>
<div class="form-group">
<label for="valor" class="col-lg-3 col-md-3 control-label">Valor:</label>
<div class="col-lg-9 col-md-9">
<?php echo $this->formInput($form->get('valor'));
// renderiza elemento de erro
echo $this->formElementErrors()
->setMessageOpenFormat('<small class="text-danger">')
->setMessageSeparatorString('</small><br/><small class="text-danger">')
->setMessageCloseString('</small>')
->render($form->get('valor'));
?>
</div>
</div>
<div class="form-group">
<label for="quant_meses" class="col-lg-3 col-md-3 control-label">Quantidade de Meses:</label>
<div class="col-lg-9 col-md-9">
<?php echo $this->formInput($form->get('quant_meses'));
// renderiza elemento de erro
echo $this->formElementErrors()
->setMessageOpenFormat('<small class="text-danger">')
->setMessageSeparatorString('</small><br/><small class="text-danger">')
->setMessageCloseString('</small>')
->render($form->get('quant_meses'));
?>
</div>
</div>
<div class="form-group">
<label for="data_inicio" class="col-lg-3 col-md-3 control-label">Data Inicial:</label>
<div class="col-lg-9 col-md-9">
<?php echo $this->formInput($form->get('data_inicio'));
// renderiza elemento de erro
echo $this->formElementErrors()
->setMessageOpenFormat('<small class="text-danger">')
->setMessageSeparatorString('</small><br/><small class="text-danger">')
->setMessageCloseString('</small>')
->render($form->get('data_inicio'));
?>
</div>
</div>
<div class="form-group">
<label for="data_fim" class="col-lg-3 col-md-3 control-label">Data Final:</label>
<div class="col-lg-9 col-md-9">
<?php echo $this->formInput($form->get('data_fim'));
// renderiza elemento de erro
echo $this->formElementErrors()
->setMessageOpenFormat('<small class="text-danger">')
->setMessageSeparatorString('</small><br/><small class="text-danger">')
->setMessageCloseString('</small>')
->render($form->get('data_fim'));
?>
</div>
</div>
</div>
<div class="panel-footer">
<?php
echo $this->formHidden($form->get('id'));
echo $this->formElement($form->get('security'));
?>
<button type="submit" class="btn btn-primary">Salvar Contato</button>
<a href="<?php echo $this->url('contratos'); ?>" class="btn btn-default">Voltar</a>
</div>
<?php echo $this->form()->closeTag() ?>
</div>
@NiltonMorais
Copy link
Author

Erro na linha 42 do Contrato.php: ->setValueOptions($this->alunos) , o array $this->alunos vem do método fetchPairs() na linha 26 do AlunoTable.php

@NiltonMorais
Copy link
Author

Acho que o erro está no fetchPais() , estou criando o array certo?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment