Domanda

I have created a custom module : Ved_Mymodule
File structure of the module is as follows:

Ved
└───Mymodule
    │   registration.php
    │
    ├───etc
    │       module.xml
    │
    ├───Model
    │   │   News.php
    │   │
    │   └───Resource
    │       │   News.php
    │       │
    │       └───News
    │               Collection.php
    │
    ├───Setup
    │       InstallSchema.php
    │       UpdateSchema.php
    │
    └───view
        └───frontend
            │   requirejs-config.js
            │
            ├───layout
            │       deafult.xml
            │
            └───web
                ├───css
                └───js
                        customCatalogAddToCart.js
                        InstallSchema.php


Using this module, one table with name ved_mymodule is created. 'id' is the primary key in that column.

Here are the files :

Ved\Mymodule\Model\News.php :

<?php

namespace Ved\Mymodule\Model;

use Magento\Framework\Model\AbstractModel;

class News extends AbstractModel
{
    /**
         * Define resource model
         */
        protected function _construct()
        {
            $this->_init('Ved\Mymodule\Model\Resource\News');
        }
    }


Ved\Mymodule\Model\Resource\News.php:

<?php

namespace Ved\Mymodule\Model\Resource;

use Magento\Framework\Model\Resource\Db\AbstractDb;

class News extends AbstractDb
{
    /**
         * Define main table
         */
        protected function _construct()
        {
            $this->_init('ved_mymodule', 'id');
        }
    }


Ved\Mymodule\Model\Resource\News\Collection.php:

<?php

namespace Ved\Mymodule\Model\Resource\News;

use Magento\Framework\Model\Resource\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection
{
/**
     * Define model & resource model
     */
    protected function _construct()
    {
        $this->_init(
            'Ved\Mymodule\Model\News',
            'Ved\Mymodule\Model\Resource\News'
        );
    }
}
È stato utile?

Soluzione

You can load the Data by following below steps.

  1. Create a Block file or if you already created a block for your template use below code in the block in your module.

  2. Add below code to block

     public function __construct(
        Context $context,
        \Ved\Mymodule\Model\NewsFactory $modelNameFactory,
        array $data = array()
    ) {
        $this->_modelFactory = $modelFactory;
        parent::__construct($context, $data);
    }
    public function getCollection(){
        return $this->_modelFactory->create()->getCollection();
    }
    
  3. use get getCollection in your template ( $block->getCollection() )

  4. Loop through each of the collection result.
  5. Assume you know how to create Block and template.

Hope this answer help you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top