6

Controller file

Post.php

<?php

namespace QaisarSatti\HelloWorld\Controller\Index;

class Post extends \Magento\Framework\App\Action\Action

{

    protected $_objectManager;
    protected $hello;

    public function __construct(\Magento\Framework\App\Action\Context $context,
                                \Magento\Framework\ObjectManagerInterface $objectManager,
                                \QaisarSatti\HelloWorld\Model\HelloworldFactory $helloworld)
    {
        $this->hello = $helloworld;
        $this->_objectManager = $objectManager;
        parent::__construct($context);
    }
    public function execute()
    {
        $post = $this->getRequest()->getPostValue();
        $model = $this->_objectManager->create('QaisarSatti\HelloWorld\Model\Helloworld');
        $model->setData('post_id', $post['post_id']);
        $model->setData('title', $post['title']);
        $model->setData('content', $post['content']);
        $model->save();
        $this->_redirect('*/*/');
        $this->messageManager->addSuccess(__('Your values has beeen submitted successfully.'));
    }

}

Model file

QaisarSatti\HelloWorld\Model\Helloworld.php

<?php


namespace QaisarSatti\HelloWorld\Model;



    class Helloworld extends \Magento\Framework\Model\AbstractModel  
    {   
        protected function _construct()
        {
            $this->_init('QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld');
        }
    }

Resource Module: QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld.php

<?php

namespace QaisarSatti\HelloWorld\Model\ResourceModel;


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

class Helloworld extends AbstractDb

{

    protected function _construct()

    {

        $this->_init('sample_posts', 'post_id');

    }

}

Collection.php

QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld\Collection.php

<?php


namespace QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld;


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


class Collection extends AbstractCollection

{

    protected function _construct()
    {

        $this->_init(
        'QaisarSatti\HelloWorld\Model\Helloworld',
        'QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld');

    }

}

Setup\InstallSchema.php

<?php

namespace QaisarSatti\HelloWorld\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface {

    public function install( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
        $installer = $setup;

        $installer->startSetup();

        $table = $installer->getConnection()->newTable(
            $installer->getTable( 'sample_posts' )
        )->addColumn(
            'post_id',
            Table::TYPE_SMALLINT,
            null,
            [ 'identity' => true, 'nullable' => false, 'primary' => true ],
            'Post ID'
        )->addColumn(
            'title',
            Table::TYPE_TEXT,
            255,
            [ 'nullable' => false ],
            'Post Title'
        )->addColumn(
            'content',
            Table::TYPE_TEXT,
            '2M',
            [ ],
            'Post Content'
        )->setComment(
            'Sample Post Table'
        );

        $installer->getConnection()->createTable( $table );

        $installer->endSetup();
    }
}

I can able to get the values from frontend phtml file using the method getPostValue(). But I can't able to save it. I like to save the values which I get from getpostvalue() method to the database. Please help me.

5

Hi guys thanks for the support. Finally i found the solution after searching many sites.

In default Magento will try to update the database not insertion when we trying to save the data with the following code.

$_data = array('post_id'=>$data1,'title'=>$data2,'content'=>$data3);

$model->setData($_data);

$model->save();

Magento will check the Model to connect with the database. If the table has the primarykey column. And if we are trying to insert the value to the primary key field with the storefront value, Magento will look for update it won't create new column(insertion) in the table. At this time we need to use the Magento features in the Resource Model.

protected $_isPkAutoIncrement = false;

Then Magento will allow to store the value and create the new column in the table.

  • Hey! Thanks! Was wondering why the save method runs clean but no error – Gianni Di Falco Sep 26 at 10:36
4

Don't use the objectmanager follow this.

    $post = $this->getRequest()->getPostValue();
    $model = $this->hello->create();

    $data=array('title'=>$post['title'],'content'=>$post['content']);
    $id = $post['post_id']; //for updating the record
        if ($id) {
            $model->load($id);
        }
    $model->setData($data);
    $model->save();

Here is complete source

0

Try this:

    $data['post_id'] = $post['post_id'];
    $data['title'] = $post['title'];
    $data['content'] = $post['content'];*

$model = $this->_objectManager->create('QaisarSatti\HelloWorld\Model\Helloworld');

            $id = $this->getRequest()->getParam('post_id');
            if ($id) {
                $model->load($id);
            }

            $model->setData($data);
    $model->save();

Use this code in collection.php

<?php

namespace QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Store\Model\Store;

class Collection extends AbstractCollection
{
    /**
     * @var string
     */
    protected $_idFieldName = 'post_id';

    /**
     * @var \Magento\Framework\EntityManager\MetadataPool
     */
    protected $metadataPool;

    /**
     * @param \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection
     * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb|null $resource
     */
    public function __construct(
        \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Framework\EntityManager\MetadataPool $metadataPool,
        \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
    }

    /**
     * Define resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('QaisarSatti\HelloWorld\Model\Helloworld',
        'QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld');
    }

}
  • i did like you said.. but still values are not saving in the database. – Selva Kumar Nov 29 '17 at 12:48
  • Check your model, There is something wrong with it. – Ronak Chauhan Nov 29 '17 at 12:50
  • I have added my model in the post. please help me – Selva Kumar Nov 29 '17 at 12:57
  • Check updated answer – Ronak Chauhan Nov 29 '17 at 13:06
  • I have followed your code .. but this error as occurred when i di compile QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld\Collection Incompatible argument type: Required type: \Magento\Framework\DB\Adapter\AdapterInterface. Actual type: \Magento\Store\Model\StoreManagerInterface; File: /var/www/html/magento2/app/code/QaisarSatti/HelloWorld/Model/ResourceModel/Helloworld/Collection.php – Selva Kumar Nov 29 '17 at 13:19

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.