Show All Product in Magento 2 - magento2

I want to show all product if it is enable or disabled doesn't matter.
with this
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
return $collection;
I only get enabled product please help me with that to get disabled product also.

Found two solution on this, please try first one, if it does not work for you, then you can try 2nd one.
You can use disable stock check on your collection by this:
$productCollection = $this->_productFactory->create()->getCollection();
$productCollection->setFlag('has_stock_status_filter', false);
Or else you can use this:
$collection = $this->_productCollectionFactory->create()
->addAttributeToSelect('*')
->load();
// Patch to alter load and get disabled products too
$collection->clear();
$where = $collection->getSelect()->getPart('where');
foreach ($where as $key => $condition)
{
if(strpos($condition, 'stock_status_index.stock_status = 1') !== false){
$updatedWhere[] = 'AND (stock_status_index.stock_status IN (1,0))';
} else {
$updatedWhere[] = $condition;
}
}
$collection->getSelect()->setPart('where', $updatedWhere);
$collection->load();

Related

Magento2 : How to add multiple product in cart using single form submission?

I am new in magento2 and using version 2.1.
I have to add multiple product in cart, the product can be any type and I want to add ajax validation as well with this functionality.
Can any one has idea to achieve this?
Thanks,
Chandan
Hi I got solution for adding multiple products in cart in for loop:
Please refer below code to implement this functionality in MAGENTO 2
if ($product_id) {
$storeId = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
try {
if(isset($params['super_attribute'][$product_id])){
$params_post = array();
$params_post['form_key'] = $this->formKey->getFormKey();
$params_post['qty'] = 1;
$params_post['super_attribute'] = $params['super_attribute'][$product_id];
$finalproduct = $this->productRepository->getById($product_id, false, $storeId);
$this->cart->addProduct($finalproduct, $params_post);
} else {
$params_post = array();
$params_post['form_key'] = $this->formKey->getFormKey();
$params_post['qty'] = 1;
$finalproduct = $this->productRepository->getById($product_id, false, $storeId);
$this->cart->addProduct($finalproduct, $params_post);
}
} catch (NoSuchEntityException $e) {
}
}

Fields getting removed when updatating mongodb document

I'm new to mongoDB and I have stumbled over some update issues when using Save().
When I click the save-button in my html-page I run the following code:
<?php
$action = (!empty($_POST['btn_submit']) &&
($_POST['btn_submit'] === 'Save')) ? 'save_article' : 'show_form';
$id = $_REQUEST['id'];
try {
$mongodb = new Mongo();
$articleCollection = $mongodb->myblogsite->articles;
} catch (MongoConnectionException $e) {
die('Failed to connect to MongoDB ' . $e->getMessage());
}
switch ($action) {
case 'save_article':
$article = array();
if (!empty($id)) {
$article['_id'] = new MongoId($id);
} else {
$article['_id'] = new MongoId();
}
$article['title'] = $_POST['title'];
$article['content'] = $_POST['content'];
$article['tags'] = $_POST['tags'];
if (!empty($id)) {
$article['updated_at'] = new MongoDate();
} else {
$article['saved_at'] = new MongoDate();
}
$articleCollection->save($article);
break;
case 'show_form':
default:
if (!empty($id)) {
$article = $articleCollection->findOne(array('_id' => new MongoId($id)));
}
}
?>
The idea is that if $id is not empty I update the document or else I insert.
I use save() to mange that.
I want two date-fields. One that hold the date the document was made and a new one for when it was last updated.
The “save_at” can not be updated. The “updated_at” change every time an update is made.
My problem now is that when I try to add the “updated_at” the “save_at” gets removed.
I also update the “saved_at”-field.
My questions is:
How do I insert an new field ('updated_at') without removing the “saved_at”-field?
How do I keep the date in “saved_at”-field as it is without updating its value?
use can done it with update command
$collection->update(array('id' => id),array('$set' => array('updated_at' =>$article['updated_at'])));

Is this a valid way to check if db_row exists?

I am working with Zend and I needed to check whether a row in the DB already exists (A simple solution to get rid of the duplicate key error I was getting). I tried several things but nothing seemed to work... (for example the Zend_Validate_Db_NoRecordExists method)
So I wrote the following the code and I was wondering if this is a valid way to do it, or if I should do things differently:
In the model:
$where = $condition = array(
'user_id = ' . $user_id,
'page_id = ' . $page_id
);
$check = $this->fetchRow($where);
if(count($check) > 0) {
return null;
}else{
// Here I create a new row, fill it with data, save and return it.
}
And then in my view:
if($this->result != null) { /* do stuff */ }else{ /* do other stuff */ }
It does work but it does seem to take more time (duh, because of the extra query) and I am a bit unsure whether I should stick with this..
Any recommendation is welcome :)
Assuming you have coded your function in your controller
$row = $this->fetchRow($where); //If no row is found then $row is null .
if(!$row)
{
$row = $dbTb->createNew($insert); //$insert an associative array where it keys map cols of table
$row->save();
$this->view->row_not_found = true;
}
return $row;
In your view you can do this
if($this->row_not_found)
{
}else {
}

How can I improve the performance of this Zend_Search_Lucene query?

How can I improve the query as seen below?
My index is fully optimized and all fields are unstored except for item_id which is a keyword field.
The problem is in the "if ($auth) {" section. If this section is removed search times are always under 1 sec but when this section is added in search times are 5 sec or more. Obviously it's a more complex query but I can't live without it. I need the logic in that section to get only search results that the user is authorized to view. I know the slowdown is in the search effort itself because if I remove the line "if ($authQuery) { $query->addSubquery($authQuery, true); }" the search is quite fast.
I'm trying to basically effect the following logic in the "if ($auth) {" section:
lucene fields gi_aro, gc_aro, i_access and c_access all consist of nothing more than a single integer each
if ((array_in({gi_aro}, $gmid) OR {i_access} <= $gid)
AND (array_in({gc_aro}, $gmid) {OR c_access} <= $gid)) {
include in search results
}
{} = lucene fields
// keywords query
$keywords = explode(' ', $keyword);
$keywordQuery = new Zend_Search_Lucene_Search_Query_Multiterm();
foreach ($keywords as $term) {
$keywordQuery->addTerm(new Zend_Search_Lucene_Index_Term($term, 'content'));
$keywordQuery->addTerm(new Zend_Search_Lucene_Index_Term($term, 'search_display_name'));
}
// topcat query
if (!empty($topcat)) {
$term = new Zend_Search_Lucene_Index_Term($topcat, 'topcats');
$topcatQuery = new Zend_Search_Lucene_Search_Query_Term($term);
}
// cat query
if (!empty($cat)) {
$term = new Zend_Search_Lucene_Index_Term($cat, 'cats');
$catQuery = new Zend_Search_Lucene_Search_Query_Term($term);
}
// only authorized items query
if ($auth) {
$user = JFactory::getUser();
$gid = (int)$user->get('aid');
$gmid = explode(',', $user->gmid);
// flexicontent cat auth
$gcQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach ($gmid as $g) {
$gcQuery->addTerm(new Zend_Search_Lucene_Index_Term($g, 'gc_aro'));
}
// stock joomla cat auth
$lowCAccessTerm = new Zend_Search_Lucene_Index_Term(0, 'c_access');
$highCAccessTerm = new Zend_Search_Lucene_Index_Term($gid, 'c_access');
$cAccessQuery = new Zend_Search_Lucene_Search_Query_Range($lowCAccessTerm, $highCAccessTerm, true);
// ORed flexicontent cat auth & stock joomla cat auth
$catAuthQuery = new Zend_Search_Lucene_Search_Query_Boolean();
$catAuthQuery->addSubquery($gcQuery);
$catAuthQuery->addSubquery($cAccessQuery);
// flexicontent itm auth
$giQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach ($gmid as $g) {
$giQuery->addTerm(new Zend_Search_Lucene_Index_Term($g, 'gi_aro'));
}
// stock joomla itm auth
$lowIAccessTerm = new Zend_Search_Lucene_Index_Term(0, 'i_access');
$highIAccessTerm = new Zend_Search_Lucene_Index_Term($gid, 'i_access');
$iAccessQuery = new Zend_Search_Lucene_Search_Query_Range($lowIAccessTerm, $highIAccessTerm, true);
// ORed flexicontent itm auth & stock joomla itm auth
$itmAuthQuery = new Zend_Search_Lucene_Search_Query_Boolean();
$itmAuthQuery->addSubquery($giQuery);
$itmAuthQuery->addSubquery($iAccessQuery);
// ANDed itmAuthQuery & catAuthQuery
$authQuery = new Zend_Search_Lucene_Search_Query_Boolean();
$authQuery->addSubquery($catAuthQuery, true);
$authQuery->addSubquery($itmAuthQuery, true);
}
// composite query
$query = new Zend_Search_Lucene_Search_Query_Boolean();
$query->addSubquery($keywordQuery, true);
// if cat query is set we don't need topcat to restrict result set
if ($catQuery) {
$query->addSubquery($catQuery, true);
} elseif ($topcatQuery) {
$query->addSubquery($topcatQuery, true);
}
if ($authQuery) { $query->addSubquery($authQuery, true); }
// search
$execTime = new JProfiler();
$this->hits = $index->find($query);
echo $execTime->mark('executed');
What about checking only the results not inside the index? Save some sort of key into the index (db primary key, guid, practically anything). Then fetch the results and remove those which the user is not allowed to see.
$allowedArray = $acl->getAllowedIds();
// check happens when echoing the content to prevent double cycling (filtering and echoing in view)
foreach ($result as $item) {
if (in_array($item->keyVaue, $allowedArray)) {
//echo
}
}
Edit: Note it depends on the result of most queries. If there are say <50 result in regular query, then doing it in PHP is OK. But if common query returns like 10,000 results, it might not be a good idea ;)

Symfony form with doctrine table other than getTable()->find() is not working

I get a really anoying error when I try to edit an entry from a table, in tutorial they always use getTable()->find(), but I need to verify that the person logged in is the owner of that entry here what I did:
In the action:
public function executeEdit(sfWebRequest $request)
{
$id = $request->getParameter('id');
$userid = $this->getUser()->getGuardUser()->getId();
$ad = Doctrine_Core::getTable('BambinbazarArticles')->getMyAd($id, $userid);
$this->forward404Unless($ad, sprintf('Object bambinbazar_articles does not exist (%s).', $request->getParameter('id')));
$this->form = new BambinbazarArticlesForm($ad);
}
In the model:
public function getMyAd($id, $userid)
{
$q = $this->createQuery('c')
->where('c.id = ? ', $id)
->addWhere('c.userid = ? ', $userid);
return $q->execute();
}
I tried it with and without the ->execute(), did doctrine clean, cleared cache, rebuilded model,
Always get the same error 'The "%s" form only accepts a "%s" object.
If I use the Doctrine_Core::getTable('BambinbazarArticles')->find() it work, but of course, i need more than that..
I am becoming crazy over this.
execute() can return multiple rows; effectively you're getting a recordset back, rather than the individual object that your form is expecting. Try fetching a single object, using, e.g.:
return $q->execute()->getFirst();
or
return $q->fetchOne();
Its probably because your query is returning a Doctrine_Collection, not the actual Doctrine_Record youre expecting. Instead of execute use fetchOne.
public function getMyAd($id, $userid)
{
$q = $this->createQuery('c')
->where('c.id = ? ', $id)
->addWhere('c.userid = ? ', $userid)
->limit(1);
return $q->fetchOne();
}