Jump to content
Michel Kuguio

Erro de Select marcando mais de um check Zend Framwork 3

Recommended Posts

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

image.thumb.png.1a0dd2f737a3125906974abe1ba762a7.png

Imagem com problema

Spoiler

image.thumb.png.379a05a57fd20762d3262f680058a014.png

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;
    }

}

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By lanahwinchester
      Olá, estou com um problema no VS Code quando tento instalar algo pelo terminal dele, "token não reconhecido no texto de origem". 
      Estou tentando instalar o react-navigation/native mas ele não deixa .

    • By Public2004
      Boas. Gostaria da ajuda dos colegas para analisar a possibilidade de otimizar a seguinte situação: Tenho um "select" simples para trazer um registro específico e que atenda uma determinada condição (where) - Após este "select", recupero o "id" deste registro e utilizo para fazer mais dois "select", um para trazer o registro anterior e  outro para o próximo (id) utilizando MIN e MAX. Tem como fazer tudo isso em um único "select" ?
       
      Tks.
    • By unset
      Olá a todos, tenho uma aplicação pequena, que roda normalmente no php5 porém ao mudar a versão do php para 7 a mesma está apresentando a seguinte mensagem de erro
       
      Notice: Trying to access array offset on value of type null in
       
       
      <?php /* * APP CORE CLASS * Creates URL & Loads Core Controller * URL Format - /controller/method/param1/param2 */ class Core { // Set Defaults protected $currentController = 'Pages'; // Default controller protected $currentMethod = 'index'; // Default method protected $params = []; // Set initial empty params array public function __construct(){ $url = $this->getUrl(); // Look in controllers folder for controller if(file_exists('../app/controllers/'.ucwords($url[0]).'.php')){ // If exists, set as controller $this->currentController = ucwords($url[0]); // Unset 0 index unset($url[0]); } // Require the current controller require_once('../app/controllers/' . $this->currentController . '.php'); // Instantiate the current controller $this->currentController = new $this->currentController; // Check if second part of url is set (method) if(isset($url[1])){ // Check if method/function exists in current controller class if(method_exists($this->currentController, $url[1])){ // Set current method if it exsists $this->currentMethod = $url[1]; // Unset 1 index unset($url[1]); } } // Get params - Any values left over in url are params $this->params = $url ? array_values($url) : []; // Call a callback with an array of parameters call_user_func_array([$this->currentController, $this->currentMethod], $this->params); } // Construct URL From $_GET['url'] public function getUrl(){ if(isset($_GET['url'])){ $url = rtrim($_GET['url'], '/'); $url = filter_var($url, FILTER_SANITIZE_URL); $url = explode('/', $url); return $url; } } }  
      Alguém poderia dar uma força ai?
    • By danicarla
      Olá gente bom dia...
      tenho um select e gostaria de mudar o valor dele quando o botão do formulário for apertado para "Aguarde"

      Gostaria de fazer isso sem usar jquery
      Acho que é algo simples mas pela busca não achei nada..
       
      <script> function MudarSelect(){ // Mudar o select para AGUARDE } </script> <select name="conteudo" id="conteudo"> <option value="0" disabled selected>-- Selecione</option> <option value="Carros">Carros</option> <option value="Motos">Motos</option> </select> <input type="submit" value="Buscar" onclick="MudarSelect();" />  
    • By agness
      a imagem é uma parte de uma tabela extensa.
      como eu faço uma consulta por exemplo para jogador igual à 1, 3, 5 e liga igual à 1?
      isso é para uma verificação se existe uma liga com exatamente os jogadores 1, 3 e 5, nem mais nem menos
      espero ter sido claro
×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.