Pergunta

Eu adicionei uma grade na conta do cliente e também obtive a coleta. Mas quando quero adicionar um pager nessa grade, recebo um erro como:

SQLSTATE[42S22]:Coluna não encontrada:1054 Coluna desconhecida 'main_table.attribute_id' em 'field list', a consulta foi:SELECIONE CONTAGEM(DISTINCT tabela_principal.attribute_id) DE custommodule_test COMO main_table ONDE (customer_id='2') {"is_exception":false} []

Na verdade, não há nenhum campo de atributo_id na minha tabela nem estou filtrando esse nome de arquivo como você está vendo.

Por favor, dê uma olhada :

teste.phtml

<?php if ($block->getPagerHtml()): ?>
    <div class="order-products-toolbar toolbar bottom"><?php echo $block->getPagerHtml(); ?></div>
<?php endif; ?>

bloco/teste.php

protected function _prepareLayout()
{
    parent::_prepareLayout();
    if ($this->getCollection()) {
        $pager = $this->getLayout()->createBlock(
            'Magento\Theme\Block\Html\Pager',
            'custom.collection.test'
        )->setCollection(
            $this->getCollection()
        );
        $this->setChild('pager', $pager);
        $this->getCollection()->load();
    }
    return $this;
}
public function getPagerHtml()
{
    return $this->getChildHtml('pager');
}

public function getCollection()
{
    if (!$this->getData('collection')) {
        $this->setCollection(
            $this->_objectMangaer->get('Namespace\Modulename\Model\Test')->getCollection()->addFieldToFilter('customer_id',2)
        );
    }
    return $this->getData('collection');
}

Observe :Se eu ligar diretamente

 $this->getCollection() ;
do arquivo phtml, obtive uma coleção correta.

Foi útil?

Solução

Para cumprir o requisito, passamos por várias abordagens e encontramos a melhor solução para paginação na coleção personalizada Magento2.Aqui vamos explicar a melhor abordagem, siga as etapas.

Observação:Supondo que você tenha criado um módulo básico no Magento2.Aqui o Ipragmatech é o nosso pacote e o Ipreward é o nosso módulo.Por favor, altere o nome da sua turma de acordo.

Passo 1:Crie um controlador chamado Myrewad, action Index (Myreward/Index.php) e adicione o seguinte código para executar o método

<?php
  namespace Ipragmatech\Ipreward\Controller\Myreward;
  class Index extends \Magento\Framework\App\Action\Action
     {
        public function execute()
           {
               $this->_view->loadLayout();
               $this->_view->renderLayout();
           }
    }

Passo 2:Crie um bloco (supondo que você já tenha criado um modelo para sua tabela.Aqui temos uma tabela customizada e criamos o modelo como recompensa) nomeie Reward.php e adicione o seguinte código.Neste código, adicionamos o pager em nossa coleção personalizada.

<?php
namespace Ipragmatech\Ipreward\Block\Myreward;

use Ipragmatech\Ipreward\Block\BaseBlock;

class Reward extends BaseBlock
  {
/**
 * @var \Ipragmatech\Ipreward\Model\Reward
 */
protected $_rewardCollection;

/**
 * Reward constructor.
 * @param \Magento\Framework\App\Action\Context $context
 * @param \Ipragmatech\Ipreward\Model\Reward $rewardCollection
 */
public function __construct(
    \Ipragmatech\Ipreward\Block\Context $context,
    \Ipragmatech\Ipreward\Model\Reward $rewardCollection,
){
    $this->_rewardCollection = $rewardCollection;
    parent::__construct($context);
}

protected function _prepareLayout()
{

    parent::_prepareLayout();
    $this->pageConfig->getTitle()->set(__('My Reward History'));

    if ($this->getRewardHistory()) {
        $pager = $this->getLayout()->createBlock(
            'Magento\Theme\Block\Html\Pager',
            'reward.history.pager'
        )->setAvailableLimit(array(5=>5,10=>10,15=>15,20=>20))
            ->setShowPerPage(true)->setCollection(
            $this->getRewardHistory()
        );
        $this->setChild('pager', $pager);
        $this->getRewardHistory()->load();
    }
    return $this;
}

public function getPagerHtml()
{
    return $this->getChildHtml('pager');
}
/**
 * function to get rewards point transaction of customer
 *
 * @return reward transaction collection
 */
Public function getRewardHistory()
{
    //get values of current page
    $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
    //get values of current limit
    $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest
    ()->getParam('limit') : 5;


    $collection = $this->_rewardCollection->getCollection();
    $collection->setPageSize($pageSize);
    $collection->setCurPage($page);
    $logger->info("Here reward collection: ".$collection->getSelect());
    $logger->info("Here reward collection: Page:".$page." Page size :"
        .$pageSize);
    return $collection;
}

} Etapa 3:Adicionado/modificar o seguinte código no arquivo de layout app/code/Ipragmatech/Ipreward/view/frontend/layout/ipreward_myreward_index.xml

  <?xml version="1.0"?>
  <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"               layout="2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="customer_account"/>
      <body>
        <referenceContainer name="content">          
        <block class="Ipragmatech\Ipreward\Block\Myreward\Reward" name="myreward_reward" template="myreward/reward.phtml">
        </block>
       </referenceContainer>      
   </body>
 </page>

Passo 4:Adicione seu arquivo phtml como app/code/Ipragmatech/Ipreward/view/frontend/templates/myreward/reward.phtml e adicione o seguinte código

enter image description here

e a saída será parecida com esta

enter image description here

Às vezes, enfrentamos alguns problemas de CSS em que o limite de páginas não é exibido, então use o seguinte CSS se você tiver o mesmo problema.

 .custom-pager .limiter{
      display: block !important;
  }

Espero que isso ajude você muito.Por favor, deixe-nos saber se você tiver algum problema em relação à personalização do Magento.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top