0

What is the minimum configuration needed to build a custom module factory?

I have this and it is still not working:

table: custommodule_products which looks like:

| file_id    | int(10) unsigned     | NO   | PRI | NULL    | auto_increment |
| store_id   | smallint(5) unsigned | NO   |     | NULL    |                |
| name       | varchar(255)         | NO   | MUL | NULL    |                |
| logs       | varchar(255)         | NO   |     | NULL   

//Example/Model/Example.php:

class Example extends AbstractModel
{

    protected function _construct()
    {
        $this->_init("Vendor\Example\Model\ResourceModel\Example");
    }

//Example/Model/ResourceModel/Example.php:

class Example extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('custommodule_products', 'file_id');
    }

//Example/Model/ResourceModel/Example/Collection.php:

class Collection extends AbstractCollection
{
    protected function _construct()
    {
        $this->_init(
            'Vendor\Example\Model\Example',
            'Vendor\Example\Model\ResourceModel\Example'
        );
    }

And then when I create my factory and try to save some data on a new row I get Fatal error: Uncaught Error: Call to undefined method \Collection::setName():

use Vendor\Example\Model\ResourceModel\Example\CollectionFactory as FileFactory;
..constructor..

$newFileRow = $this->fileFactory->create();
$newFileRow->setName("test");

I don't understand what else does it need or how can I further debug it. I've checked var/generation/Module...CollectionFactory.php and the file is there. Does it need something else to be able to set data?

Thanks!

1

The main problem i think is that you are using incorrect factory. If you want to save a model, you need to get factory for the model, not the collection.

Eg instead of using:

use Vendor\Example\Model\ResourceModel\Example\CollectionFactory as FileFactory;

you probably want to use:

use Vendor\Example\Model\ExampleFactory as FileFactory;

In general i think it is wise to learn and use repository pattern. Depending on your magento version, you can notice that models save,delete,load methods are deprecated and may become problematic in future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.