Can't filter data from database using getSelect()->where() Magento 2 - magento

I am currently working with magento 2.2.1 and I am having a weird problem. I am trying to get a set of data from database and display it on admin grid. I want to take records for a specific agent ID so i have a variable that has the value of the agent id. When i pass this variable as parameter to$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId); it wont display anything but if i replace $this->givenAgentId with it's value, for example with 4, it works perfectly!
This is my class:
<?php
namespace vendor\plugin\Ui\Component\Listing\DataProviders\Atisstats\Coupons;
use \vendor\plugin\Model\ResourceModel\Coupons\CollectionFactory;
use \Magento\Framework\Registry;
class Listing extends \Magento\Ui\DataProvider\AbstractDataProvider {
protected $_registry;
protected $givenAgentId = 0;
public function __construct(
Registry $registry,
$name,
$primaryFieldName,
$requestFieldName,
CollectionFactory $collectionFactory,
array $meta = [],
array $data = []
) {
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
$this->_registry = $registry;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$select = $connection->select()
->from(
['amasty_perm_dealer'],
['user_id']
);
$data = $connection->fetchAll($select);
foreach ($data as $dealerId) {
if ($dealerId['user_id'] == $this->_registry->registry('admin_session_id')) {
$this->givenAgentId = intval($this->_registry->registry('admin_session_id'));
}
}
if ($this->givenAgentId != 0) {
$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId);
} else {
$this->collection = $collectionFactory->create();
}
}
}
I have stuck here for hours!

I fixed this problem! First of all it was Registry class causing the problem so I used
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resourceUserId = $objectManager->get('\Magento\Backend\Model\Auth\Session');
to get the user id from session and used it below to check the user! For some reason the registry object was modifying the variable holding the current users id!
I post the answer just in case someone get stuck with this kind of problem !

Related

How to delete quantity and update in database using laravel?

When I am inserting quantity in database, I want to update the quantity in the another table. This is what I have tried so far,
public function insertData(Request $request)
{
$userProduct = new UserProduct();
$localStorageData = $request->input('localStorageData');
$productData = json_decode($localStorageData);
print_r($productData);
foreach ($productData as $value) {
$data_array['qty'] = $value->productQty;
$data_array['fk_p_id'] = $value->productId;
$data_array['fk_user_id'] = $request->fkUserId;
UserProduct::insert($data_array);
}
}
In product table I have "id","p_qty"
without updating it, you can get the total quantity by doing sum operation for the main object
$localStorageData = $request->input('localStorageData');
$productData = json_decode($localStorageData);
$userProduct = new UserProduct();
$userProduct->p_qty = collect($productData)->sum('productQty')
You can use two methods to accomplish this in Laravel, using model on created and observers:
<?php
namespace App\Observers;
use App\Models\Transaction;
use Illuminate\Support\Str;
class UserProductObserver
{
public function created(UserProduct $userProduct)
{
$product = $userProduct->product;
$product->p_qty= $product->p_qty+ $userProduct->qty
$product->save();
}
}

Laravel 5.1 Command empty table

I'm using a command to add products from an API to my database using the following code
class UpdateCatalog extends Command {
protected $name = 'catalog:update';
protected $description = 'Command description.';
public function __construct()
{
parent::__construct();
}
public function fire()
{
$products = Api::productsGetProducts();
foreach($products as $product)
{
$detail = Api::productsGetProduct($product['id']);
$product = new Product();
$product->id = $detail->getId();
$product->external_id = $detail->getExternalId();
$product->name = $detail->getName();
$product->description = $detail->getDescription();
$product->thumbnail = $detail->getThumbnail();
$product->price = $detail->getPrices()[0]['price_excl_vat'];
$product->vat = $detail->getVat();
$product->save();
}
}
}
Now I'm wondering if it's possible to empty the table prior to filling it again.
Thank you!
Do you mean you want to empty your Product database table?
This can be done with truncate like this:
Product::truncate();
Note: This will remove all rows and reset the auto-incrementing ID to zero

CakePHP serializing objects

I'm stuck with the following problem:
I have a class CartItem. I want to store array of objects of CartItem in session (actually i'm implementing a shopping cart).
class CartItem extends AppModel{
var $name = "CartItem";
var $useTable = false;
}
I tried this:
function addToCart(){
$this->loadModel("Cart");
$this->layout = false;
$this->render(false);
$cart = array();
$tempcart = unserialize($this->Session->read("cart"));
if(isset($tempcart)){
$cart = $tempcart;
}
$productId = $this->request->data("id");
if(!$this->existsInCart($cart, $productId)){
$cartItem = new Cart();
$cartItem->productId = $productId;
$cartItem->createdAt = date();
$cart[] = $cartItem;
$this->Session->write("cart", serialize($cart));
echo "added";
}
else
echo "duplicate";
}
I think I'm writing these lines wrong:
$tempcart = unserialize($this->Session->read("cart"));
$this->Session->write("cart", serialize($cart));
as I'm not getting data from the session.
You are trying to add the whole Cart object to the session.
You should just add an array, like
$cart[] = array(
'productId' => $productId,
'createdAt' => date('Y-m-d H:i:s')
);
If you need to add an object to a session, you can use __sleep and __wakeup magic functions but I think in this case it's better to just add only the product id and date to the session.

Magento. How to link store_id to the attribute in the custom EAV Model

I am using this tutorial on adding new EAV Model in Magento:
http://inchoo.net/ecommerce/magento/creating-an-eav-based-models-in-magento/
Everything works fine except all my attributes are saving with "store_id = 0" when I do this part of code:
$phonebookUser = Mage::getModel('inchoo_phonebook/user');
$phonebookUser->setFristname('John');
$phonebookUser->save();
I am wondering is there any clear way to set store ID on save EAV Entity Attributes.
Thanks.
You can only set values for a specific store only after you added the values for store id 0.
Here is an example.
//create default values
$phonebookUser = Mage::getModel('inchoo_phonebook/user');
$phonebookUser->setFristname('John');
$phonebookUser->save();
//remember the id of the entity just created
$id = $phonebookUser->getId();
//update the name for store id 1
$phonebookUser = Mage::getModel('inchoo_phonebook/user')
->setStoreId(1)
->load($id); //load the entity for a store id.
$phonebookUser->setFristname('Jack'); //change the name
$phonebookUser->save(); //save
I have override the functions in my resource model to work with store_id and it is worked for me but I suggest that this is not the best solution.
protected function _saveAttribute($object, $attribute, $value)
{
$table = $attribute->getBackend()->getTable();
if (!isset($this->_attributeValuesToSave[$table])) {
$this->_attributeValuesToSave[$table] = array();
}
$entityIdField = $attribute->getBackend()->getEntityIdField();
$data = array(
'entity_type_id' => $object->getEntityTypeId(),
$entityIdField => $object->getId(),
'attribute_id' => $attribute->getId(),
'store_id' => $object->getStoreId(), //added this
'value' => $this->_prepareValueForSave($value, $attribute)
);
$this->_attributeValuesToSave[$table][] = $data;
return $this;
}
protected function _getLoadAttributesSelect($object, $table)
{
$select = $this->_getReadAdapter()->select()
->from($table, array())
->where($this->getEntityIdField() . ' =?', $object->getId())
->where('store_id in (?)', array($object->getStoreId(), 0)); //added this
return $select;
}
also I have added this code to the constructor of my entity model:
if (Mage::app()->getStore()->isAdmin()) {
$this->setStoreId(Mage::app()->getRequest()->getParam('store', 0));
}
else{
$this->setStoreId(Mage::app()->getStore()->getId());
}
Override the _getDefaultAttributes() method in your resource model like this:
protected function _getDefaultAttributes()
{
$attributes = parent::_getDefaultAttributes();
$attributes[] = "store_id";
return $attributes;
}
This should work if you have only one value for store_id per your model's entity.

how to instantiate a class with result object in Codeigniter?

The documentation for result() says that we can pass the name of a class to instantiate for each result object: http://codeigniter.com/user_guide/database/results.html
I'm can't figure out correct way to do so.I need to pass few fields from the result object to the constructor.
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $user)
{
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
please let me know if there are better ways!
You can create a static Class method in your User class that creates a user or users instances. You will need to add the appropriate instance vars to the User class.
var $username = FALSE;
var $password = FALSE;
public static function get_user_by_id($id)
{
$CI =& get_instance();
$query = $CI->db->get_where('users', array('id' => $id));
$user = $query->row(0, 'User');
return $user;
}
In the example I'm getting a reference to the CodeIgniter instance to access the database. Since you can't access the database from a Class method since it is not an object instance.
You can't.
The object instantiated can't be passed any arguments, which means you need to create a method you can use to pass these fields to the object which is instantiated:
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $user)
{
$row->init_my_fields('field1', 'field2'); //instead of passing the fields through the __construct()
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
from codeigniter documentation
$query = $db->query("SELECT * FROM users LIMIT 1;");
$row = $query->getRow(0, 'User'); // or ->row(0, 'User') in CI 3
from codeigniter /system/database/DB_result.php
public function custom_result_object($class_name)
{
...
if ($_data !== NULL)
{
for ($i = 0; $i < $c; $i++)
{
$this->custom_result_object[$class_name][$i] = new $class_name();
foreach ($this->{$_data}[$i] as $key => $value)
{
$this->custom_result_object[$class_name][$i]->$key = $value;
}
}
return $this->custom_result_object[$class_name];
}
...
}
I believe this means that CI define new class with empty constructor from the wanted class "should be available to instantiate in the scope" , and tries to set its properties with the values from the row result and then returns it

Resources