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 milokoz
      Basicamente eu estou com um leve problema:
      Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\_config\classes\class.MySQL.php on line 17
      Não foi possível encontrar o banco de dados "test".
      A DB está criada no PHP 
      http://prntscr.com/p5epzn

      e esta nomeada corretamente
      # Definições e conexão com à DATABASE
      define("DB_HOST", "localhost");
      define("DB_PORT", "3303");
      define("DB_USER", "root");
      define("DB_PASS", "");
      define("DB_NAME", "test");
    • By makioplayer
      A pressão da minha mesa não está funcionando apenas no Paint Tool SAI, alguém sabe o que pode ser?
       
      Ela é uma Genius mousepen i608x.
    • By darkside88
      Esse é meu código porém não está exibindo dentro dos inputs as informações recuperadas da página EDITAR nos campos! <?php //ini_set('display_errors', 0); include('conexao/connection.php'); session_start(); $cli_codigo = intval($_GET['usuario']); if(isset($_POST['confirma'])){     //Registrar Dados     if(!isset($_SESSION))         session_start();       foreach($_POST as $chave=>$valor)         $_SESSION[$chave] = $con->real_escape_string($valor);       //Validar     if (strlen($_SESSION['nome']) == 0)     $erro[] = "Preencha o campo Nome";            if (strlen($_SESSION['wpp']) == 0)     $erro[] = "Preencha o campo WhatsApp";       if (strtotime($_SESSION['dt1']) > strtotime($_SESSION['dt2']) || strtotime($_SESSION['dt1']) == strtotime($_SESSION['dt2']))     $erro[] = "A Data de Criação no IPTV deve ser menor que a Data de Vencimento no IPTV ou não podem ser iguais";           //Inserir       if(count($erro) == 0){         $sql_code = "UPDATE cadastrocliente set             nomecli = '$_SESSION[nome]',             email = '$_SESSION',             wpp = '$_SESSION[wpp]',             srv = '$_SESSION[srv]',              srv = '$_SESSION[dt1]',                         dataVI = '$_SESSION[dt2]',             app = '$_SESSION[app]'             WHERE nomecli = '$cli_codigo'";         $confirma = $con->query($sql_code) or die($con->error);         if($confirma){             unset(                 $_SESSION[nome],                 $_SESSION,                 $_SESSION[wpp],                 $_SESSION[srv],                 $_SESSION[dt1],                 $_SESSION[dt2],                 $_SESSION[app]                          );                         header("Location: index.php?p=listarcliente");         }else{             $erro[] = $confirma;         }     }else{         $sql_code = "SELECT * FROM cadastrocliente WHERE id_cliente= '$cli_codigo'";         $sql_query = $con->query($sql_code) or die($con->error);         $linha = $sql_query->fetch_assoc();           $_SESSION[nome] = $linha['nomeCli'];         $_SESSION = $linha['email'];         $_SESSION[wpp] = $linha['wpp'];         $_SESSION[srv] = $linha['srv'];         $_SESSION[srv] = $linha['dt1'];         $_SESSION[dt2] = $linha['dt2'];         $_SESSION[app]  = $linha['app'];     } }   ?> <?php   if (count($erro) > 0) {     echo "<div class='alert alert-danger'>";     foreach ($erro as $valor)         echo "$valor <br>";          echo "</div>";}  ?> <form class="container-fluid" action="index.php?p=editar&usuario=<?php echo $cli_codigo?>" method="POST">     <label for="nome">Nome do Cliente</label>     <input type="text" name="nome" value="<?php echo $_SESSION[nome]?>" class="form-control" placeholder="Nome Completo do Cliente">     <label for="email">Email</label>     <input type="email" name="email" value="<?php echo $_SESSION?>" class="form-control" placeholder="nome@exemplo.com">     <label for="mensagem">WhatsApp</label>     <input type="text" name="wpp" value="<?php echo $_SESSION[wpp]?>" class="form-control" placeholder="Digite o seu Whatsapp (DD) 9 XXXX-XXXX"         id="celular" name="mensagem">     <script type="text/javascript">     $("#telefone,#celular").mask("(00) 0 0000-0000");     </script>     <label for="srv">Servidor do Cliente</label>     <input type="text" name="srv" value="<?php echo $_SESSION[wpp]?>" class="form-control" placeholder="Servidor do Cliente">     <label for="dt1">Data de Criação no IPTV</label>     <input type="date" value="<?php echo $_SESSION[dt1]?>" data- provide="datepicker" name="dt1" class="form-control">     <label for="dt2">Data de Vencimento no IPTV</label>     <input type="date" name="dt2" value="<?php echo $_SESSION[dt2]?>" class="form-control">     <label for="app">App doCliente</label>     <input type="text" name="app" value="<?php echo $_SESSION[app]?>" class="form-control" placeholder="App do Cliente">     <input type="submit" name="confirma" class="form-control btn btn-dark mt-4 mb-4 " value="Cadastrar">   </form>
    • By asacap1000
      Galera estou com uma consulta que ainda não consegui entender o porque. gostaria que ela trouxesse em apenas uma linha mas não vem de forma alguma.
       
      SELECT BO.LAGER, BO.ID_OS, K.ID_KLIENT, K.SUCHBEGRIFF CNPJ_CPF, K.NAME, BI.DIV_1 LOTE, BI.DIV_10 DI_DDE, (SELECT DISTINCT DIS.ID_DISPATCHER FROM FISCAL.DOCHD DC, WMS_EADI.DISPATCHER DIS WHERE DC.DOCHD_DOC_ID = BO.NR_NF AND DC.DOCHD_RPS_DESP = DIS.SUCHBEGRIFF) COD_COMISSARIA, (SELECT DISTINCT DIS.BEZ FROM FISCAL.DOCHD DC, WMS_EADI.DISPATCHER DIS WHERE DC.DOCHD_DOC_ID = BO.NR_NF AND DC.DOCHD_RPS_DESP = DIS.SUCHBEGRIFF) COMISSARIA, BO.NR_NF, BO.DATE_BILL, BO.DATE_EMISS, --------ABAIXO OS TIPOS DE SERVIÇOS ONDE ESTÃO OCORRENDO CADA RESULTADO ELE CRIA UMA LINHA---------------- (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.DIV_1 = BI.DIV_1 --AND NVL(OSI.DIV_10, 'x') = NVL(BI.DIV_10, 'x') AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND WER.WERT = 'ARMAZ')) VLR_ARMAZ, (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.DIV_1 = BI.DIV_1 --AND NVL(OSI.DIV_10, 'x') = NVL(BI.DIV_10, 'x') AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND WER.WERT = 'GER.RISCO')) VLR_GER_RISCO, (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.DIV_1 = BI.DIV_1 --AND NVL(OSI.DIV_10, 'x') = NVL(BI.DIV_10, 'x') AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND WER.WERT = 'MOVIMENT')) VLR_MOVIMENTACAO, (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.DIV_1 = BI.DIV_1 --AND NVL(OSI.DIV_10, 'x') = NVL(BI.DIV_10, 'x') AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND WER.WERT = 'DESUNIT')) VLR_DESUNIT, (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.DIV_1 = BI.DIV_1 --AND NVL(OSI.DIV_10, 'x') = NVL(BI.DIV_10, 'x') AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND WER.WERT = 'PESAGEM')) VLR_PESAGEM, (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.DIV_1 = BI.DIV_1 --AND NVL(OSI.DIV_10, 'x') = NVL(BI.DIV_10, 'x') AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND WER.WERT LIKE 'AVERBA%')) VLR_AVERBACAO, (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND WER.WERT = 'FAT.MINIMO.')) VLR_FAT_MINIMO, (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.DIV_1 = BI.DIV_1 --AND NVL(OSI.DIV_10, 'x') = NVL(BI.DIV_10, 'x') AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND BLL.BILLITE NOT IN ('21.02', '21.03') AND WER.WERT = 'OUT.SERV.')) VLR_OUTROS_SERV, (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.DIV_1 = BI.DIV_1 --AND NVL(OSI.DIV_10, 'x') = NVL(BI.DIV_10, 'x') AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND BLL.BILLITE = '21.02' AND WER.WERT = 'OUT.SERV.')) TRANSF_IN, (SELECT SUM(ROUND(OSI.PREIS, 2)) FROM BILL_OS_ITEM OSI WHERE OSI.LAGER = BO.LAGER AND OSI.ID_KLIENT = K.ID_KLIENT AND OSI.ID_OS = BO.ID_OS AND OSI.BILLITE = BI.BILLITE AND OSI.DIV_1 = BI.DIV_1 --AND NVL(OSI.DIV_10, 'x') = NVL(BI.DIV_10, 'x') AND OSI.BILLITE IN (SELECT BLL.BILLITE FROM BILL_ITEM BLL, WERTE WER WHERE BLL.TIPO_FAT = WER.WERT AND WER.WERTE_BER = 'ITENSF' AND BLL.BILLITE = '21.03' AND WER.WERT = 'OUT.SERV.')) TRANSF_OUT FROM BILL_OS BO, BILL_OS_ITEM BI, KLIENTEN K WHERE BO.LAGER = BI.LAGER AND BO.ID_KLIENT = BI.ID_KLIENT AND BO.ID_OS = BI.ID_OS AND BO.LAGER = K.LAGER AND BO.ID_KLIENT = K.ID_KLIENT and k.id_klient = '3099' and BO.NR_NF = '121304' AND BO.STATUS = '90' AND TRUNC(BO.DATE_BILL) BETWEEN '28/08/2019' AND '28/08/2019' GROUP BY BO.LAGER, BO.ID_OS, K.ID_KLIENT, K.SUCHBEGRIFF, K.NAME, BO.DATE_EMISS, BO.NR_NF, BO.DATE_BILL, BI.BILLITE, BI.DIV_1, BI.DIV_10
       
      Alguem consegue identificar neste select porque ele vem assim?
    • By helcarib
      Estou desenvolvendo um sistema que sorteia 20 questoes em um banco mysql e exibe na tela, como se fosse uma prova. Como vou usar como ferramenta de estudo, as questões que o usuários acertarem vão  para o fim da fula e as que errar continua sendo sorteadas junto com as outras até todas serem exibidas em provas.
       
      Isso que descrevi acima ja está funcionando, porque criei um campo na tabela questao, que_estudada que vale 0 pra todas as questoes e quando o usuário  acerta ele passa a valer 1, quando tem menos de 20 registros iguais a 0 ele atualiza tudo pra 0 e recomeca as questões.
       
      Nesse momento queria que o sistema tivesse varios usuarios e que cada um tenha a sua "fila de questoes" e que as que ele acertar continue sendo exibidas para os outros, então criei mais duas tabelas: prova e item com os seguintes campos:
      prova (pro_cod, usu_cod, mat_cod,pro_data)
      item (pro_cod, ite_cod, que_cod)
      cada prova tem só  1 materia, mas tem 20 questões.
      Importante que essas questoes que forem acertadas nao podem se repetir enquanto o usuario não estudar todas elas em provas. Eu estou com dificuldade para fazer isso com multiplos usuários, se alguém puder dar uma luz inicial, aí vou tentar fazer e depois mando a solução. Desde já  muito agradecido!
×

Important Information

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