Erro de Select marcando mais de um check Zend Framwork 3
Estou com um problema somente em um form, tenho outras partes do codigo com mesmo tipo de forme porem com entidade diferente mas com o mesmo tipo re relacionamento e funciona normal, agora nesse caso o select está marcando mais de um option como selected.
Entidade Categoria:
Spoiler
<?php
namespace Admin\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\Hydrator;
/**
* Categoria
*
* @ORM\Table(name="categoria", uniqueConstraints={@ORM\UniqueConstraint(name="id_UNIQUE", columns={"id"})}, indexes={@ORM\Index(name="fk_categoria_categoria1_idx", columns={"categoria_id"})})
* @ORM\Entity
* @ORM\Entity(repositoryClass="Admin\Repository\CategoriaRepository")
*/
class Categoria
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nome", type="string", length=60, nullable=false)
*/
private $nome;
/**
* @var string
*
* @ORM\Column(name="slug", type="string", length=60, nullable=false)
*/
private $slug;
/**
* @var Categoria|null
*
* @ORM\ManyToOne(targetEntity="Categoria", inversedBy="children")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="categoria_id", referencedColumnName="id")
* })
*/
private $categoria;
/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\OneToMany(targetEntity="Categoria", mappedBy="categoria")
*/
private $children;
/**
* @var bool
*
* @ORM\Column(name="status", type="boolean", nullable=false)
*/
private $status;
/**
* Categoria constructor.
* @param array $options
*/
public function __construct(array $options = [])
{
(new Hydrator\ClassMethods())->hydrate($options,$this);
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString(): string
{
// TODO: Implement __toString() method.
return $this->nome;
}
/**
* @param array $cond
* @param int $type
* @return array
*/
public function toArray(array $cond = [], $type = 1)
{
$arr = (new Hydrator\ClassMethods())->extract($this);
if (sizeof($cond) > 0)
if ($type == 1) {
foreach ($arr as $k => $v) {
if (!in_array($k, $cond))
unset($arr[$k]);
}
} else {
foreach ($cond as $ust) {
unset($arr[$ust]);
}
}
return $arr;
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
* @return Categoria
*/
public function setId(int $id): Categoria
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getNome(): string
{
return $this->nome;
}
/**
* @param string $nome
* @return Categoria
*/
public function setNome(string $nome): Categoria
{
$this->nome = $nome;
return $this;
}
/**
* @return string
*/
public function getSlug(): string
{
return $this->slug;
}
/**
* @param string $slug
* @return Categoria
*/
public function setSlug(string $slug): Categoria
{
$this->slug = $slug;
return $this;
}
/**
* @return Categoria
*/
public function getCategoria()
{
return $this->categoria;
}
/**
* @param Categoria $categoria
* @return Categoria
*/
public function setCategoria($categoria)
{
$this->categoria = $categoria;
return $this;
}
/**
* @return \Doctrine\Common\Collections\Collection
*/
public function getChildren():\Doctrine\Common\Collections\Collection
{
return $this->children;
}
/**
* @param Categoria $children
* @return Categoria
*/
public function setChildren($children)
{
$this->children = $children;
return $this;
}
/**
* @return bool
*/
public function isStatus(): bool
{
return $this->status;
}
/**
* @return bool
*/
public function getStatus(): bool
{
return $this->status;
}
/**
* @param bool $status
* @return Categoria
*/
public function setStatus(bool $status): Categoria
{
$this->status = $status;
return $this;
}
}
Repositorio da Entidade:
Spoiler
<?php/**
* Created by PhpStorm.
* User: WebMaster
* Date: 28/03/2017
* Time: 00:02
*/
namespace Admin\Repository;
use AppBase\Repository\AbstractRepository;
class CategoriaRepository extends AbstractRepository
{
}
Extensão do Repository:
Spoiler
<?php
/**
* Created by PhpStorm.
* User: WebMaster
* Date: 11/08/2017
* Time: 17:43
*/
namespace AppBase\Repository;
use Doctrine\ORM\EntityRepository;
/**
* Class AbstractRepository
* @package AppBase\Repository
*/
abstract class AbstractRepository extends EntityRepository
{
/**
* @param array $filtro
* @param array $order
* @return array
*/
public function findFilter(array $filtro, $order = []){
$where = "1=1 ";
if(count($filtro))
foreach ($filtro as $id=>$val){
$cast = (int) $val;
switch ($val) {
case "IS NULL":
$where .="AND s.{$id} {$val} ";
break;
case "IS NOT NULL":
$where .="AND s.{$id} {$val} ";
break;
default:
if($cast==0)
$where .="AND s.{$id} LIKE '%{$val}%' ";
elseif ($cast>0)
$where .="AND s.{$id} = '{$val}' ";
break; }
}
$select = $this->createQueryBuilder('s');
if($where!="1=1 ")
$select->where($where);
if(count($order)>1)
foreach ($order as $OKey=>$OVal)
$select->addOrderBy($OKey,$OVal);
elseif (count($order))
$select->orderBy(key($order),current($order));
return $select->getQuery()->getResult();
}
/**
* @return array
*/
public function findPairs(){
$select = $this->createQueryBuilder('s');
$result = $select->getQuery()->getResult();
$arrResult = [];
if(count($result))
foreach ($result as $item)
$arrResult[$item->getId()]=$item->getNome();
return $arrResult;
}
/**
* @return array
*/
public function findParents($where = null){
$select = $this->createQueryBuilder('s');
if(!empty($where))
$select->where($where);
$result = $select->getQuery()->getResult();
$arrResult = [];
if(count($result))
foreach ($result as $item){
if(empty($where)) {
if($item->getChildren()->toArray())
$arrResult[$item->getId()] = $item->getNome();
}else
$arrResult[$item->getId()]=$item->getNome();
}
return $arrResult;
}
}
Service:
Spoiler
<?php/**
* Created by PhpStorm.
* User: WebMaster
* Date: 13/08/2017
* Time: 15:44
*/
namespace Admin\Service;
use AppBase\Service\AbstractService;
use Doctrine\ORM\EntityManager;
class CategoriaService extends AbstractService
{
public function __construct(EntityManager $em)
{
$this->entity = \Admin\Entity\Categoria::class;
parent::__construct($em);
}
public function insert(array $data)
{
if ($data['categoria']) {
$data['categoria'] = $this->em->getReference($this->entity, $data['categoria']);
} else {
unset($data['categoria']);
}
$data['slug'] = self::slugify($data['nome']);
return parent::insert($data); // TODO: Change the autogenerated stub
}
public function update(array $data)
{
if ($data['categoria']) {
$data['categoria'] = $this->em->getReference($this->entity, $data['categoria']);
} else {
unset($data['categoria']);
}
$data['slug'] = self::slugify($data['nome']);
return parent::update($data); // TODO: Change the autogenerated stub
}
}
Abstrac Service:
Spoiler
<?php/**
* Created by PhpStorm.
* User: WebMaster
* Date: 19/02/2017
* Time: 12:36
*/
namespace AppBase\Service;
use AppBase\Traits\Option;
use Doctrine\ORM\EntityManager;
use Zend\Hydrator;
/**
* Class AbstractService
*
* @package AppUser\Service
*/
abstract class AbstractService
{
/**
* @var EntityManager
*/
protected $em;
/**
* @var
*/
protected $entity;
/**
* AbstractService constructor.
*
* @param EntityManager $em
*/
use Option;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* @param array $data
*
* @return mixed
*/
public function insert(array $data)
{
$entity = new $this->entity($data);
$this->em->persist($entity);
$this->em->flush();
return $entity;
}
/**
* @param array $data
*
* @return bool|\Doctrine\Common\Proxy\Proxy|null|object
*/
public function update(array $data)
{
$entity = $this->em->getReference($this->entity,$data['id']);
(new Hydrator\ClassMethods())->hydrate($data,$entity);
$this->em->persist($entity);
$this->em->flush();
return $entity;
}
/**
* @param $id
*
* @return mixed
*/
public function delete($id)
{
$entity = $this->em->getReference($this->entity,$id);
if($entity){
$this->em->remove($entity);
$this->em->flush();
return $id;
}
}
}
Form:
Spoiler
<?php
/**
* Created by PhpStorm.
* User: WebMaster
* Date: 13/08/2017
* Time: 15:00
*/
namespace Admin\Form;
use Admin\Entity\Categoria;
use AppBase\Form\Form;
use Doctrine\ORM\EntityManager;
use Zend\Form\Element\Button;
use Zend\Form\Element\Select;
use Zend\Form\Element\Text;
use Zend\Form\Element\Hidden;
use Zend\Form\Element\Csrf;
use \Admin\Filter\CategoriaFilter;
class CategoriaForm extends Form
{
public function __construct(EntityManager $em, $name = 'form-categoria', array $options = [])
{
parent::__construct($em, $name, $options);
$this->setInputFilter(new CategoriaFilter());
$this->setAttribute('method', 'post');
$entityCategoria = $this->em->getRepository(Categoria::class);
$arrCategorias = [
0 => 'Categoria Principal'
];
$arrCategorias+=$entityCategoria->findPairs();
$parent = new Select('categoria');
$parent->setLabel('Categoria parentesco');
$parent->setAttributes([
'id' => 'categoria',
'class' => 'form-control js-select u-select--v3-select u-sibling w-100',
'options' => $arrCategorias,
]);
$this->add($parent);
$id = new Hidden('id');
$this->add($id);
$nome = new Text('nome');
$nome->setLabel('Nome');
$nome->setAttributes([
'id' => 'nome',
'class' => 'form-control form-control-md g-brd-gray-light-v7 g-brd-gray-light-v3--focus g-rounded-4 g-px-14 g-py-10'
]);
$this->add($nome);
$status = new Select('status');
$status->setLabel('Status');
$status->setAttributes([
'id' => 'status',
'class' => 'form-control js-select u-select--v3-select u-sibling w-100',
'options' => [
'' => 'Selecione',
1 => 'Ativo',
0 => 'Inativo',
],
]);
$this->add($status);
$csrf = new Csrf("security");
$this->add($csrf);
$this->add([
'name' => 'submit',
'type' => \Zend\Form\Element\Submit::class,
'attributes' => [
'value' => 'Salvar',
'class' => 'btn btn-md u-btn-3d u-btn-primary g-mr-10 g-mb-15'
]
]);
$voltar = new Button('voltar');
$voltar->setLabel('voltar');
$voltar->setAttributes([
'value' => 'voltar',
'class' => 'btn btn-danger btn-md u-btn-3d g-mr-10 g-mb-15',
'onClick'=>'document.location.href=\'/admin/categoria\'',
]);
$this->add($voltar);
}
}
Filter:
Spoiler
<?php/**
* Created by PhpStorm.
* User: WebMaster
* Date: 13/08/2017
* Time: 15:19
*/
namespace Admin\Filter;
use Zend\Filter\StringTrim;
use Zend\Filter\StripTags;
use Zend\InputFilter\InputFilter;
use Zend\Validator\NotEmpty;
/**
* Class CategoriaFilter
* @package Admin\Filter
*/
class CategoriaFilter extends InputFilter
{
/**
* CategoriaFilter constructor.
*/
public function __construct()
{
$this->add(
[
'name' => 'categoria',
'required' => false,
'validator' => [
['name' => NotEmpty::class]
]
]
);
$this->add(
[
'name' => 'nome',
'required' => true,
'filters' => [
['name' => StringTrim::class],
['name' => StripTags::class]
],
'validator' => [
['name' => NotEmpty::class]
]
]
);
$this->add(
[
'name' => 'status',
'required' => true,
'validator' => [
['name' => NotEmpty::class]
]
]
);
}
}
View:
Spoiler
<div class="media">
<div class="d-flex align-self-center">
<h1 class="g-font-weight-300 g-font-size-28 g-color-black mb-0"> Categoria (<?= ($action == "insert" ? "Novo" : "Editar") ?>)</h1>
</div>
</div>
<hr class="d-flex g-brd-gray-light-v7 g-my-30">
<div class="g-brd-around g-brd-gray-light-v7 g-rounded-4 g-pa-15 g-pa-20--md g-mb-30">
<?php
if ($id) {
$acaoRedir = ['action' => $action, 'controller' => $controller, 'id' => $id];
} else {
$acaoRedir = ['action' => $action, 'controller' => $controller];
}
$form->setAttribute('action', $this->url('admin/default', $acaoRedir));
$form->prepare();
?>
<?= $this->form()->openTag($form); ?>
<div class="form-group">
<?php $nome = $form->get('nome'); ?>
<label for="nome"><?= $this->formLabel($nome); ?></label>
<?= $this->formElement($nome); ?>
<?= $this->formElementErrors($nome); ?>
</div>
<div class="form-group ">
<?php $categoria = $form->get('categoria'); ?>
<label for="categoria"><?= $this->formLabel($categoria); ?></label>
<div class="u-select--v3 g-pos-rel g-brd-gray-light-v7 g-rounded-4 mb-0">
<?= $this->formElement($categoria); ?>
<?= $this->formElementErrors($categoria); ?>
<div class="d-flex align-items-center g-absolute-centered--y g-right-0 g-color-gray-light-v6 g-color-lightblue-v9--sibling-opened g-mr-15">
<i class="hs-admin-angle-down"></i>
</div>
</div>
</div>
<div class="form-group">
<?php $status = $form->get('status'); ?>
<label for="status"><?= $this->formLabel($status); ?></label>
<div class="u-select--v3 g-pos-rel g-brd-gray-light-v7 g-rounded-4 mb-0">
<?= $this->formElement($status); ?>
<?= $this->formElementErrors($status); ?>
<div class="d-flex align-items-center g-absolute-centered--y g-right-0 g-color-gray-light-v6 g-color-lightblue-v9--sibling-opened g-mr-15">
<i class="hs-admin-angle-down"></i>
</div>
</div>
</div>
<div class="form-group mb-0">
<?php $security = $form->get('security'); ?>
<?php $submit = $form->get('submit'); ?>
<?php $voltar = $form->get('voltar'); ?>
<?= $this->formElement($security); ?>
<?= $this->formHidden($form->get('id')); ?>
<?= $this->formSubmit($submit); ?>
<?= $this->formButton($voltar); ?>
</div>
<?= $this->form()->closeTag($form); ?>
</div>
Imagem Funcionando correto outro modulo
Spoiler

Imagem com problema
Spoiler

Controller
Spoiler
<?php/**
* Created by PhpStorm.
* User: WebMaster
* Date: 13/08/2017
* Time: 14:32
*/
namespace Admin\Controller;
use Admin\Entity\Categoria;
use Admin\Form\CategoriaForm;
use Admin\Form\CategoriaFormFilter;
use Admin\Service\CategoriaService;
use AppBase\Controller\AbstractCrudController;
use AppBase\Service\AbstractService;
use Doctrine\ORM\EntityManager;
class CategoriaController extends AbstractCrudController
{
public function __construct(EntityManager $em, AbstractService $svc)
{
$this->formFilter = CategoriaFormFilter::class;
$this->form = CategoriaForm::class;
$this->entity= Categoria::class;
$this->service= CategoriaService::class;
$this->controller = 'categoria';
$this->template = 'admin/categoria/form.phtml';
$this->order = ['s.nome'=>'DESC'];
$this->route = 'admin/default';
parent::__construct($em,$svc);
}
}
Abstrac controller
Spoiler
<?php
/**
* Created by PhpStorm.
* User: WebMaster
* Date: 11/08/2017
* Time: 16:28
*/
namespace AppBase\Controller;
use AppBase\Service\AbstractService;
use Doctrine\ORM\EntityManager;
use Zend\Session\Container;
use Zend\View\Model\ViewModel;
/**
* Class AbstractCrudController
* @package AppBase\Controller
*/
abstract class AbstractCrudController extends AbstractController
{
/**
* @var AbstractService
*/
protected $service;
/**
* @var
*/
protected $entity;
/**
* @var
*/
protected $form;
/**
* @var
*/
protected $formFilter;
/**
* @var array
*/
protected $filter = [];
/**
* @var array
*/
protected $where = [];
/**
* @var array
*/
protected $order = [];
/**
* @var
*/
protected $route;
/**
* @var
*/
protected $template;
/**
* @var
*/
protected $controller;
/**
* @var
*/
protected $module;
/**
* AbstractCrudController constructor.
* @param EntityManager $em
* @param AbstractService $svc
*/
public function __construct(EntityManager $em, AbstractService $svc)
{
$this->service = $svc;
parent::__construct($em);
}
/**
* @return ViewModel
*/
public function indexAction(array $option = [])
{
//INSTANCIANDO OS SERVICES
$serviceAuth = 1;
$formFilter = null;
if(isset($this->formFilter)&&!is_null($this->formFilter)) {
if (is_string($this->formFilter)) {
$formFilter = new $this->formFilter($this->em, null, $option);
} else {
$formFilter = $this->formFilter;
}
$request = $this->getRequest();
if ($request->isPost()) {
//AbstractValidator::setDefaultTranslator($this->sm->get('MvcTranslator'));
$formFilter->setData($request->getPost());//->toArray()
if ($formFilter->isValid()) {
$res = $request->getPost()->toArray();
unset($res["security"]);
unset($res["submit"]);
foreach ($res as $resK=>$resV){
if(empty($resV)&&$resV!='0')
unset($res[$resK]);
}
$where = $res;
}
}elseif ($request->isGet()){
$filter = $this->params()->fromQuery();
foreach ($filter as $resK=>$resV){
if(empty($resV)&&$resV!='0')
unset($filter[$resK]);
}
$formFilter->setData($filter);
unset($filter["security"]);
unset($filter["submit"]);
$this->setFilter($filter);
}
}
$page = $this->params()->fromRoute('page');
if(!isset($where))
$where = $this->getWhere(['page']);
$result = $this->em->getRepository($this->entity)->findFilter($where, $this->order);
$paginator = parent::paginator($result, $page);
return new ViewModel([
'data' => $paginator,
'page' => $page,
'formFilter' => $formFilter,
'controller' => $this->controller
]);
}
/**
* @param array $option
* @return \Zend\Http\Response|ViewModel
*/
public function insertAction(array $option = [])
{
if(is_string($this->form))
$form = new $this->form($this->em,null, $option);
else
$form = $this->form;
$page = $this->params()->fromRoute('page');
$request = $this->getRequest();
if ($request->isPost()) {
//AbstractValidator::setDefaultTranslator($this->sm->get('MvcTranslator'));
$form->setData($request->getPost());//->toArray()
//var_dump('oi',$request->getPost(),$form->isValid());exit();
if ($form->isValid()) {
$res = $request->getPost()->toArray();
if (isset($res['id']) && ($res['id'] == '' || is_null($res['id'])))
unset($res['id']);
if ($this->service->insert($res))
$this->flashmessenger()->addSuccessMessage('Cadastro efetuado com sucesso!');
else
$this->flashmessenger()->addErrorMessage('Houve um erro ao tentar cadastrar o seu registro!');
//return $this->redirect()->toUrl("/{$this->module}/{$this->controller}");
if (!empty($this->module) && $this->module)
return $this->redirect()->toRoute(
$this->route, ['controller' => $this->controller,'page'=>$page]
);
else
return $this->redirect()->toRoute(
$this->route, ['controller' => $this->controller]
);
}
}
$view = new ViewModel([
'form' => $form,
'controller' => $this->controller,
'action' => 'insert',
]);
$view->setTemplate($this->template);
return $view;
}
/**
* @param array $option
* @return \Zend\Http\Response|ViewModel
*/
public function updateAction(array $option = [], array $forceString = [])
{
if(is_string($this->form))
$form = new $this->form($this->em,null, $option);
else
$form = $this->form;
$page = $this->params()->fromRoute('page');
//$form = new $this->form(null, $option);
$request = $this->getRequest();
$repository = $this->em->getRepository($this->entity);
$id = (int)$this->params()->fromRoute('id', 0);
if ($id) {
try {
$entity = $repository->find($id);
} catch (\Exception $e) {
return $this->redirect()->toRoute(
$this->route, ['controller' => $this->controller]
);
}
//$form->bind($entity);
$form->setData($entity->toArray());
$form->get('submit')->setValue('Editar');
}
if ($request->isPost()) {
// AbstractValidator::setDefaultTranslator($this->sm->get('MvcTranslator'));
$form->setData($request->getPost());
if ($form->isValid()) {
$res = $request->getPost()->toArray();
if ($this->service->update($res, $id))
$this->flashmessenger()->addSuccessMessage('Dados atualizados com sucesso!');
else
$this->flashmessenger()->addErrorMessage('Houve um erro ao tentar atualizar o seu registro!');
if (!empty($this->module) && $this->module)
return $this->redirect()->toRoute(
$this->route, ['controller' => $this->controller,'page'=>$page]
);
else
return $this->redirect()->toRoute(
$this->route, ['controller' => $this->controller]
);
}
}
$view = new ViewModel([
'form' => $form,
'id' => $id,
'controller' => $this->controller,
'action' => 'update',
]);
$view->setTemplate($this->template);
return $view;
}
/**
* @return \Zend\Http\Response
*/
public function deleteAction()
{
$id = (int)$this->params()->fromRoute('id', 0);
$page = $this->params()->fromRoute('page');
if (!empty($id)) {
if ($this->service->delete($id)) {
$this->flashmessenger()->addSuccessMessage('Registro excluido com sucesso!');
if (!empty($this->module) && $this->module)
return $this->redirect()->toRoute(
$this->route, ['controller' => $this->controller,'page'=>$page]
);
else
return $this->redirect()->toRoute(
$this->route, ['controller' => $this->controller]
);
}else
$this->flashmessenger()->addErrorMessage('Houve um erro ao excluir o registro!');
}
}
/**
* @return mixed
*/
public function getFilter()
{
return $this->filter;
}
/**
* @param array $filter
* @return $this
*/
public function setFilter(array $filter)
{
if (count($filter))
$this->filter = ['params'=>$filter];
//CRIA UMA SESSÃO COM FILTROS
$container = new Container($this->controller);
$container->filtro = $this->filter;
return $this;
}
/**
* @param array $exceptionsFiltro
* @return mixed
*/
public function getWhere(array $exceptionsFiltro)
{
$where = $this->where;
$filtro = $this->filter;
if (isset($filtro['params']) && count($filtro['params']))
foreach ($filtro['params'] as $idFiltro => $valorFiltro)
if ((!empty($valorFiltro) || $idFiltro == 0) && !in_array($idFiltro, $exceptionsFiltro))
$where[$idFiltro] = $valorFiltro;
return $where;
}
/**
* @param array $where
*/
public function setWhere(array $where)
{
if (count($where))
foreach ($where as $indice => $valor)
$this->where[$indice] = $valor;
}
/**
* @return int
*/
public function getIdUsuario(){
return 1;
}
}Discussão (0)
Carregando comentários...