How to set custmer id for an quote in magento? - magento-1.7

I am adding product into cart and tried to map customer id,email to that quote
using the below code
$product_id = 123;
$qty = 1;
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$superAttributeArray = array('151' => '3');
$params = array(
'product' => $product_id,
'qty' => $qty,
'super_attribute' => $superAttributeArray
);
$cart->addProduct($product, $params);
$cart->save();
$currenQuoteId = Mage::getSingleton('checkout/session')->getQuoteId();
$store = Mage::getSingleton('core/store')->load(Mage::app()->getStore()->getId());
$quote = Mage::getModel('sales/quote')->setStore($store)->load($currenQuoteId);
$quote->setCustomerId('1')->setCustomerEmail('test#gmail.com')->setCustomerFirstname('firstname')->setCustomerLastname('lastname');
$quote->save();
When I try to set customerid,email,fname,lname am getting error as "Mage registry key "controller" already exists".
Can anyone help me in fixing this issue?

Something like this might work
$customerObj = Mage::getModel('customer/customer')->load($customerId);
$quoteObj = Mage::getModel('sales/quote')->assignCustomer($customerObj);
$storeId = Mage::app()->getStore()->getId();
$quoteObj->setStore(Mage::getSingleton('core/store')->load($storeId);
$productObj = Mage::getModel('catalog/product')->load($productId);
$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
$quoteItem->setQuote($quoteObj);
$quoteItem->setQty('1');
$quoteItem->setStoreId($storeId);
$quoteObj->addItem($quoteItem);
$quoteObj->setStoreId($storeId);
$quoteObj->collectTotals();
$quoteObj->save();

Related

Get custom stock product quantity

I use this code to retrieve product quantity by given id
$stockItem = $objectManager->get('\Magento\CatalogInventory\Model\Stock\StockItemRepository');
$productId = 10858;
$productStock = $stockItem->get($productId);
$productStock->getData();
This code work and return this results
array (
'item_id' => '10858',
'product_id' => '10962',
'stock_id' => '1',
'qty' => '0.0000',
'min_qty' => '0.0000',
...
)
But I need to retrieve information by stock_id = 2 instead of default stock (id: 1)
There's a way to do this, using this code?
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productId = 1;
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$product_qty = $StockState->getStockQty($productId);

How to consume 3rd Party wsdl in magento2

I need to fetch Customer Information from a third party http://91.209.142.215:2803/SXYMAGENTO/?wsdl. I can connect it using SOAPUI and get desired response, but I am not able to connect it via Magento2. So far I tried
$requestData = [
'pageSize' => 1,
'pageNumber' => 1
];
$webservice_url = 'http://xx.xxx.xxx.xx:xxxx/MAGENTO/?wsdl';
$token = 'm31oix12hh6dfthmfmgk7j5k5dpg8mel';
$opts = array(
'http'=>array(
'header' => 'Authorization: Bearer '.$token)
);
$context = stream_context_create($opts);
$soapClient = new \SoapClient($webservice_url, ['version' => SOAP_1_2, 'context' => $context]);
$collection = $soapClient->RetrieveCollection($requestData);
print_r($collection);
die();
but this outputs Product data(maybe this is set as default), not customer data. Can anyone please point me in the right direction?
Finally, I figure this out and posting the answer so that it may help anyone craving a solution or fighting with a deadline.
Extend SoapClient and you can change Action, Request, and location
namespace Namespace\SoapModule\Api;
class CustomSoap extends \SoapClient
{
public function __doRequest($request, $location, $action, $version, $one_way = 0)
{
$action = 'Your/Action/Obtainedfrom/SOAPAction';
$this->__last_request = $request; //Optional. You should do this if you dont want to get confused when print $request somewhere else in the module
return parent::__doRequest($request, $location, $action, $version, $one_way);
}
}
construct an object of above class wherever required
public function getCustomersDetails($page_size, $page_number)
{
$requestData = [
'pageSize' => $page_size,
'pageNumber' => $page_number
];
$data = $this->client->__soapCall('RetrieveCollection', [$requestData]);
return $this->client->__getLastResponse();
}
public function statementBalance()
{
$responsexml = $this->getCustomersDetails(1, 1);
$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $responsexml);
#$xml = simplexml_load_string($xml);
$json = json_encode($xml);
$responseArray = json_decode($json, true);
echo '<pre>';
print_r($responseArray);
}
Happy coding!

Zend_Db_Select : multiple from clause

Hy,
I have some problem vith Zend_Db_Select.
I have 2 variable : category and city. These 2 variables may have a value or they may be unset.
So I verify:
$status = '`p`.status = 1';
if($catID){
$catSQL = "`p`.parent = {$catID}";
}else{
$catSQL = '1=1';
}
if($city){
$citySQL = "`pm`.`meta_key` = 'oras' and `pm`.`meta_value` = {$city}";
$citySelect = array('pm' => 'postsmeta');
$condCity = "`p`.`ID` = `pm`.`parent_id`";
}else{
$citySQL = '1=1';
$citySelect = NULL;
$condCity = '1=1';
}
Now here is my query:
$select = $db->select()
->from( array('p' => 'posts'))
->from($citySelect)
->where($status)
->where($catSQL)
->where($condCity)
->where($citySQL)
;
The problem is that if city is empty I have something like
$select = $db->select()
->from( array('p' => 'posts'))
->from('')
->where(1=1)
->where(1=1)
->where(1=1)
->where(1=1)
;
The questions is how can I remove from('') from my query if city is empty.
Thank you!
Simply,
$select = $db->select()
->from( array('p' => 'posts'));
if($someConditionIsTrue) {
$select->join($table, $condition);
}
$select->where('field_value = ?', 'value1');
if($someConditionIsTrue) {
$select->where('another_field = ?', 'value 2');
}
Hope it helps.
Please use this syntax $select->where('another_field = ?', 'value 2'); for proper escaping values to prevent SQL injections.

getting an error param tags must be an array while tagging facebook users

I am creating the facebook app(php sdk) that uploads photo and tags users.But i am getting a strange below error
Uncaught OAuthException: (#100) param tags must be an array.
I used the following code
$argstag = array('to' => $user);
$argstag['x'] = 40;
$argstag['y'] = 40;
$data = json_encode($argstag);
$attachment = array(
'message' => $mes,
'tags' => $data
);
$facebook->setFileUploadSupport(true);
$attachment['image'] ='#'.realpath($filename);
$photo = $facebook->api('/'.$aid.'/photos', 'POST', $attachment);
please help me with this issue.
Try changing
$argstag = array('to' => $user);
to
$argstag = array('tag_uid' => $user);
EDIT:
If that doesn't work try changing
$argstag = array('to' => $user);
$argstag['x'] = 40;
$argstag['y'] = 40;
$data = json_encode($argstag);
to
$armstag = array();
$armstag['tag_uid'] = $user;
$armstag['x'] = 40;
$armstag['y'] = 40;
$data = json_encode($argstag);
Have you tried printing out the $argstag? It will show you the array you are encoding with json and it will look like this probably [[x:something],[y:something]] etc. use str_replace to replace those unwanted elements. Here is what i'm using when inviting users:
$torep=array("[","]",'"');//replace some chars. generetaded by json
$users=str_replace($torep,"", $encode);
The output is: UID, UID, UID, UID which is working instead of [[UID],[UID],[UID]] which gives me the same error.
Hope it helps ;)

Auditlogging functionality for zend db

I have a requirement to implement audit logging functionality in a zend project. The models are created using zend db and the update function is as follows.
public function updateGroup($data,$id)
{
$row = $this->find($id)->current();
// set the row data
$row->name = $data['name'];
$row->description = $data['description'];
$row->updatedBy = $data['updatedBy'];
$row->updatedOn = date('Y-m-d H:i:s');
$id = $row->save();
return $id;
}
I have to create a table with the auditlog information which includes the current userid. I have tried many methods and nothing is a good solution. What is the best practice for a good audit logging functionality for zend?
I just want to log only the modified data. and the log table schema is like
id,
table,
column,
rowId
oldvalue,
newvalue,
updatedon,
updatedbyuser
use Zend_Log_Writer_Db :
Zend_Log_Writer_Db writes log information to a database table using
Zend_Db. The constructor of Zend_Log_Writer_Db receives a
Zend_Db_Adapter instance, a table name, and a mapping of database
columns to event data items
for example :
$columnMapping = array('name' => 'name',
'desc' => 'desc',
'updatedBy' => 'userid',
'updatedOn' => 'date');
$writer = new Zend_Log_Writer_Db($db, 'auditlog_table', $columnMapping);
$logger = new Zend_Log($writer);
$logger->setEventItem('name', $data['name']);
$logger->setEventItem('desc', $data['name']);
$logger->setEventItem('updatedBy',$data['updatedBy']);
$logger->setEventItem('updatedOn',date('Y-m-d H:i:s'));
EDIT : to log only the modified data :
public function logUpdate(array $values)
{
$columnMapping = array('id' => 'id',
'table' => 'table',
'column' => 'column',
'rowId' => 'rowId',
'oldvalue' => 'oldvalue',
'newvalue' => 'newvalue',
'updatedon' => 'updatedon',
'updatedbyuser' => 'updatedbyuser');
$writer = new Zend_Log_Writer_Db($db, 'auditlog_table', $columnMapping);
$logger = new Zend_Log($writer);
$logger->setEventItem('id', $values['id']);
$logger->setEventItem('table', $values['table']);
$logger->setEventItem('column', $values['column']);
$logger->setEventItem('rowId', $values['rowId']);
$logger->setEventItem('oldvalue', $values['oldValue']);
$logger->setEventItem('newValue', $values['newValue']);
$logger->setEventItem('updatedon', $values['updatedon']);
$logger->setEventItem('updatedbyuser', $values['updatedbyuser']);
}
and in updateGroup :
public function updateGroup($data,$id)
{
$row = $this->find($id)->current();
$values = array('table' => $this->name);
$values = array('updatedon' => $data['updatedBy']);
$values = array('updatedbyuser' => date('Y-m-d H:i:s'));
//go through all data to log the modified columns
foreach($data as $key => $value){
//check if modified log the modification
if($row->$key != $value){
$values = array('column' => $key);
$values = array('oldValue' => $row->$key);
$values = array('newValue' => $value);
logUpdate($values);
}
}
// set the row data
$row->name = $data['name'];
$row->description = $data['description'];
$row->updatedBy = $data['updatedBy'];
$row->updatedOn = date('Y-m-d H:i:s');
$id = $row->save();
return $id;
}
Note that its better to implement logging for all your application and seperate logging from update , see this answer for that .