Im trying to programmatically create an order. I created a model with the following structure:
<?php
class Pricebinc_App_Model_OrderCreate extends Mage_Core_Model_Abstract
{
const CUSTOMER_RANDOM = null;
protected $_shippingMethod = 'freeshipping_freeshipping';
protected $_paymentMethod = 'cashondelivery';
protected $_subTotal = 0;
protected $_order;
protected $_storeId;
public function setShippingMethod($methodName)
{
$this->_shippingMethod = $methodName;
}
public function setPaymentMethod($methodName)
{
$this->_paymentMethod = $methodName;
}
public function setCustomer($customer)
{
if ($customer instanceof Mage_Customer_Model_Customer) {
$this->_customer = $customer;
}
if (is_numeric($customer)) {
$this->_customer = Mage::getModel('customer/customer')->load($customer);
} else if ($customer === self::CUSTOMER_RANDOM) {
$customers = Mage::getResourceModel('customer/customer_collection');
$customers
->getSelect()
->limit(1)
->order('RAND()');
$id = $customers->getFirstItem()->getId();
$this->_customer = Mage::getModel('customer/customer')->load($id);
}
}
public function createOrder($products)
{
if (!($this->_customer instanceof Mage_Customer_Model_Customer)) {
$this->setCustomer(self::CUSTOMER_RANDOM);
}
$transaction = Mage::getModel('core/resource_transaction');
$this->_storeId = Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$reservedOrderId = Mage::getSingleton('eav/config')
->getEntityType('order')
->fetchNewIncrementId($this->_storeId);
$currencyCode = Mage::app()->getBaseCurrencyCode();
$this->_order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($this->_storeId)
->setQuoteId(0)
->setGlobalCurrencyCode($currencyCode)
->setBaseCurrencyCode($currencyCode)
->setStoreCurrencyCode($currencyCode)
->setOrderCurrencyCode($currencyCode);
$this->_order->setCustomerEmail($this->_customer->getEmail())
->setCustomerFirstname($this->_customer->getFirstname())
->setCustomerLastname($this->_customer->getLastname())
->setCustomerGroupId($this->_customer->getGroupId())
->setCustomerIsGuest(0)
->setCustomer($this->_customer);
$billing = $this->_customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($this->_storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($this->_customer->getId())
->setCustomerAddressId($this->_customer->getDefaultBilling())
->setCustomerAddress_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$this->_order->setBillingAddress($billingAddress);
$shipping = $this->_customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($this->_storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($this->_customer->getId())
->setCustomerAddressId($this->_customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());
$this->_order->setShippingAddress($shippingAddress)
->setShippingMethod($this->_shippingMethod);
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($this->_storeId)
->setCustomerPaymentId(0)
->setMethod($this->_paymentMethod)
->setPoNumber(' – ');
$this->_order->setPayment($orderPayment);
$this->_addProducts($products);
$this->_order->setSubtotal($this->_subTotal)
->setBaseSubtotal($this->_subTotal)
->setGrandTotal($this->_subTotal)
->setBaseGrandTotal($this->_subTotal);
$transaction->addObject($this->_order);
$transaction->addCommitCallback(array($this->_order, 'place'));
$transaction->addCommitCallback(array($this->_order, 'save'));
$transaction->save();
}
protected function _addProducts($products)
{
$this->_subTotal = 0;
foreach ($products as $productRequest) {
if ($productRequest['product'] == 'rand') {
$productsCollection = Mage::getResourceModel('catalog/product_collection');
$productsCollection->addFieldToFilter('type_id', 'simple');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productsCollection);
$productsCollection->getSelect()
->order('RAND()')
->limit(rand($productRequest['min'], $productRequest['max']));
foreach ($productsCollection as $product) {
$this->_addProduct(array(
'product' => $product->getId(),
'qty' => rand(1, 2)
));
}
} else {
$this->_addProduct($productRequest);
}
}
}
protected function _addProduct($requestData)
{
$request = new Varien_Object();
$request->setData($requestData);
$product = Mage::getModel('catalog/product')->load($request['product']);
$cartCandidates = $product->getTypeInstance(true)
->prepareForCartAdvanced($request, $product);
if (is_string($cartCandidates)) {
throw new Exception($cartCandidates);
}
if (!is_array($cartCandidates)) {
$cartCandidates = array($cartCandidates);
}
$parentItem = null;
$errors = array();
$items = array();
foreach ($cartCandidates as $candidate) {
$item = $this->_productToOrderItem($candidate, $candidate->getCartQty());
$items[] = $item;
/**
* As parent item we should always use the item of first added product
*/
if (!$parentItem) {
$parentItem = $item;
}
if ($parentItem && $candidate->getParentProductId()) {
$item->setParentItem($parentItem);
}
/**
* We specify qty after we know about parent (for stock)
*/
$item->setQty($item->getQty() + $candidate->getCartQty());
// collect errors instead of throwing first one
if ($item->getHasError()) {
$message = $item->getMessage();
if (!in_array($message, $errors)) { // filter duplicate messages
$errors[] = $message;
}
}
}
if (!empty($errors)) {
Mage::throwException(implode("\n", $errors));
}
foreach ($items as $item) {
$this->_order->addItem($item);
}
return $items;
}
function _productToOrderItem(Mage_Catalog_Model_Product $product, $qty = 1)
{
$rowTotal = $product->getFinalPrice() * $qty;
$options = $product->getCustomOptions();
$optionsByCode = array();
foreach ($options as $option) {
$quoteOption = Mage::getModel('sales/quote_item_option')->setData($option->getData())
->setProduct($option->getProduct());
$optionsByCode[$quoteOption->getCode()] = $quoteOption;
}
$product->setCustomOptions($optionsByCode);
$options = $product->getTypeInstance(true)->getOrderOptions($product);
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($this->_storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($product->getId())
->setProductType($product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($product->getName())
->setSku($product->getSku())
->setPrice($product->getFinalPrice())
->setBasePrice($product->getFinalPrice())
->setOriginalPrice($product->getFinalPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal)
->setWeeeTaxApplied(serialize(array()))
->setBaseWeeeTaxDisposition(0)
->setWeeeTaxDisposition(0)
->setBaseWeeeTaxRowDisposition(0)
->setWeeeTaxRowDisposition(0)
->setBaseWeeeTaxAppliedAmount(0)
->setBaseWeeeTaxAppliedRowAmount(0)
->setWeeeTaxAppliedAmount(0)
->setWeeeTaxAppliedRowAmount(0)
->setProductOptions($options);
$this->_subTotal += $rowTotal;
return $orderItem;
}
}
Then I include the following statement in the controller:
$orderGenerator = Mage::getModel('app/ordercreate');
$orderGenerator->createOrder(array(
array(
'product' => 24, //product id
'qty' => 1
)
));
But I constantly receive error 500.
including Zend_Debug::dump($orderGenerator); creates the following output.
object(Pricebinc_App_Model_OrderCreate)#230 (21) {
["_shippingMethod":protected] => string(25) "freeshipping_freeshipping"
["_paymentMethod":protected] => string(14) "cashondelivery"
["_customer":protected] => NULL
["_subTotal":protected] => int(0)
["_order":protected] => NULL
["_storeId":protected] => NULL
["_eventPrefix":protected] => string(13) "core_abstract"
["_eventObject":protected] => string(6) "object"
["_resourceName":protected] => string(15) "app/ordercreate"
["_resource":protected] => NULL
["_resourceCollectionName":protected] => string(26) "app/ordercreate_collection"
["_cacheTag":protected] => bool(false)
["_dataSaveAllowed":protected] => bool(true)
["_isObjectNew":protected] => NULL
["_data":protected] => array(0) {
}
["_hasDataChanges":protected] => bool(false)
["_origData":protected] => NULL
["_idFieldName":protected] => NULL
["_isDeleted":protected] => bool(false)
["_oldFieldsMap":protected] => array(0) {
}
["_syncFieldsMap":protected] => array(0) {
}
}
I took that code from amasty https://blog.amasty.com/creating-magento-order-programmatically/
UPDATE-------------------------------------------------------------------
current errors display customer is not set. example are Fatal error: Call to a member function getEmail() on a non-object in C:\Zend\Apache2\htdocs\company\app\code\community\Pricebinc\App\Model\OrderCreate.php on line 56 ->$this->_order->setCustomerEmail($this->_customer->getEmail())
finally this is the code if you need to create an order programmatically in magento 1.9.
<?php
class NameApp_App_Model_OrderCreate extends Mage_Core_Model_Abstract
{
const CUSTOMER_RANDOM = null;
protected $_shippingMethod = 'freeshipping_freeshipping';
protected $_paymentMethod = 'cashondelivery';
protected $_subTotal = 0;
protected $_order;
protected $_storeId = '0';
public function _construct()
{
parent::_construct();
$this->_init('app/ordercreate');
}
public function setShippingMethod($methodName)
{
$this->_shippingMethod = $methodName;
}
public function setPaymentMethod($methodName)
{
$this->_paymentMethod = $methodName;
}
public function createOrder($products)
{
$transaction = Mage::getModel('core/resource_transaction');
$this->_storeId = Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$this->_customer = Mage::getSingleton('customer/session')->getCustomer();
$reservedOrderId = Mage::getSingleton('eav/config')
->getEntityType('order')
->fetchNewIncrementId($this->_storeId);
$currencyCode = Mage::app()->getBaseCurrencyCode();
$this->_order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($this->_storeId)
->setQuoteId(0)
->setGlobalCurrencyCode($currencyCode)
->setBaseCurrencyCode($currencyCode)
->setStoreCurrencyCode($currencyCode)
->setOrderCurrencyCode($currencyCode);
$this->_order->setCustomerEmail($this->_customer->getEmail())
->setCustomerFirstname($this->_customer->getFirstname())
->setCustomerLastname($this->_customer->getLastname())
->setCustomerGroupId($this->_customer->getGroupId())
->setCustomerIsGuest(0)
->setCustomer($this->_customer);
$billing = $this->_customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($this->_storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($this->_customer->getId())
->setCustomerAddressId($this->_customer->getDefaultBilling())
->setCustomerAddress_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$this->_order->setBillingAddress($billingAddress);
$shipping = $this->_customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($this->_storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($this->_customer->getId())
->setCustomerAddressId($this->_customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());
$this->_order->setShippingAddress($shippingAddress)
->setShippingMethod($this->_shippingMethod);
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($this->_storeId)
->setCustomerPaymentId(0)
->setMethod($this->_paymentMethod)
->setPoNumber(' – ');
$this->_order->setPayment($orderPayment);
$this->_addProducts($products);
$this->_order->setSubtotal($this->_subTotal)
->setBaseSubtotal($this->_subTotal)
->setGrandTotal($this->_subTotal)
->setBaseGrandTotal($this->_subTotal);
$transaction->addObject($this->_order);
$transaction->addCommitCallback(array($this->_order, 'place'));
$transaction->addCommitCallback(array($this->_order, 'save'));
$transaction->save();
}
protected function _addProducts($products)
{
$this->_subTotal = 0;
foreach ($products as $productRequest) {
if ($productRequest['product'] == 'rand') {
$productsCollection = Mage::getResourceModel('catalog/product_collection');
$productsCollection->addFieldToFilter('type_id', 'simple');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productsCollection);
$productsCollection->getSelect()
->order('RAND()')
->limit(rand($productRequest['min'], $productRequest['max']));
foreach ($productsCollection as $product) {
$this->_addProduct(array(
'product' => $product->getId(),
'qty' => rand(1, 2)
));
}
} else {
$this->_addProduct($productRequest);
}
}
}
protected function _addProduct($requestData)
{
$request = new Varien_Object();
$request->setData($requestData);
$product = Mage::getModel('catalog/product')->load($request['product']);
$cartCandidates = $product->getTypeInstance(true)
->prepareForCartAdvanced($request, $product);
if (is_string($cartCandidates)) {
throw new Exception($cartCandidates);
}
if (!is_array($cartCandidates)) {
$cartCandidates = array($cartCandidates);
}
$parentItem = null;
$errors = array();
$items = array();
foreach ($cartCandidates as $candidate) {
$item = $this->_productToOrderItem($candidate, $candidate->getCartQty());
$items[] = $item;
/**
* As parent item we should always use the item of first added product
*/
if (!$parentItem) {
$parentItem = $item;
}
if ($parentItem && $candidate->getParentProductId()) {
$item->setParentItem($parentItem);
}
/**
* We specify qty after we know about parent (for stock)
*/
$item->setQty($item->getQty() + $candidate->getCartQty());
// collect errors instead of throwing first one
if ($item->getHasError()) {
$message = $item->getMessage();
if (!in_array($message, $errors)) { // filter duplicate messages
$errors[] = $message;
}
}
}
if (!empty($errors)) {
Mage::throwException(implode("\n", $errors));
}
foreach ($items as $item) {
$this->_order->addItem($item);
}
return $items;
}
function _productToOrderItem(Mage_Catalog_Model_Product $product, $qty = 1)
{
$rowTotal = $product->getFinalPrice() * $qty;
$options = $product->getCustomOptions();
$optionsByCode = array();
foreach ($options as $option) {
$quoteOption = Mage::getModel('sales/quote_item_option')->setData($option->getData())
->setProduct($option->getProduct());
$optionsByCode[$quoteOption->getCode()] = $quoteOption;
}
$product->setCustomOptions($optionsByCode);
$options = $product->getTypeInstance(true)->getOrderOptions($product);
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($this->_storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($product->getId())
->setProductType($product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($product->getName())
->setSku($product->getSku())
->setPrice($product->getFinalPrice())
->setBasePrice($product->getFinalPrice())
->setOriginalPrice($product->getFinalPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal)
->setWeeeTaxApplied(serialize(array()))
->setBaseWeeeTaxDisposition(0)
->setWeeeTaxDisposition(0)
->setBaseWeeeTaxRowDisposition(0)
->setWeeeTaxRowDisposition(0)
->setBaseWeeeTaxAppliedAmount(0)
->setBaseWeeeTaxAppliedRowAmount(0)
->setWeeeTaxAppliedAmount(0)
->setWeeeTaxAppliedRowAmount(0)
->setProductOptions($options);
$this->_subTotal += $rowTotal;
return $orderItem;
}
}
Then you can call it from controller:
$orderGenerator = Mage::getModel('app/ordercreate');
$orderGenerator->createOrder(array(
array(
'product' => 41, //product id
'qty' => 1
)
));
thats it. you can make product => 41 dynamic instead of static. its your choice.
Related
I have dynamic data that will be exported into excel using maatwebsite. I have a case where I need to merge the same data. How can I do it from a collection?
From This:
To This:
class PerencanaanExport implements
FromCollection,
WithCustomStartCell,
WithEvents,
ShouldAutoSize,
WithStyles
{
/**
* #return \Illuminate\Support\Collection
*/
public function __construct(string $tahun)
{
$this->tahun = $tahun;
}
public function startCell(): string
{
return "A3";
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
/** #var Sheet $sheet */
$tahun =
$this->tahun == "null"
? ""
: ($this->tahun == "all"
? ""
: $this->tahun);
$sheet = $event->sheet;
$sheet->mergeCells("A1:E1");
$sheet->setCellValue("A1", "Kode");
$sheet->setCellValue("A2", "Urusan");
$sheet->setCellValue("B2", "Bidang Urusan");
$sheet->setCellValue("C2", "Program");
$sheet->setCellValue("D2", "Kegiatan");
$sheet->setCellValue("E2", "Sub Kegiatan");
$sheet->mergeCells("F1:F2");
$sheet->setCellValue(
"F1",
"Urusan/ Bidang Urusan Pemerintahan Daerah dan Program Kegiatan"
);
$sheet->mergeCells("G1:G2");
$sheet->setCellValue(
"G1",
"Indikator Kinerja Program/ Kegiatan"
);
$sheet->mergeCells("H1:K1");
$sheet->setCellValue("H1", "Rencana Tahun " . $tahun);
$sheet->setCellValue("H2", "LOKASI");
$sheet->setCellValue("I2", "TARGET KINERJA");
$sheet->setCellValue("J2", "ANGGARAN");
$sheet->setCellValue("K2", "SUMBER DANA");
$styleArray = [
"borders" => [
"allBorders" => [
"borderStyle" =>
\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
"color" => ["argb" => "000000"],
],
],
];
$cellRange = "A1:K" . $sheet->getHighestRow(); // All headers
$event->sheet
->getDelegate()
->getStyle($cellRange)
->applyFromArray($styleArray);
$event->sheet
->getStyle("A1:K2")
->getAlignment()
->setVertical(StyleAlignment::VERTICAL_TOP)
->setHorizontal(StyleAlignment::VERTICAL_CENTER)
->setWrapText(true);
},
];
}
public function collection()
{
$arr = [];
$tahun = $this->tahun;
$jointahun = "";
if ($tahun) {
$jointahun = " AND d.tahun =" . $tahun;
}
$query = "XXXXX";
$query .= "XXXXX";
$data = DB::select($query);
$oldProgram = "";
$oldKegiatan = "";
foreach ($data as $key => $value) {
if ($key != 0) {
$oldProgram = $data[$key - 1]->program;
$oldKegiatan = $data[$key - 1]->kegiatan;
}
if ($oldProgram != $value->program) {
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
"",
"",
$value->program,
]);
}
if ($oldKegiatan != $value->kegiatan) {
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
$value->kode_kegiatan,
"",
$value->kegiatan,
$value->indikator_kegiatan,
]);
}
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
$value->kode_kegiatan,
$value->kode_sub_kegiatan,
$value->sub_kegiatan,
$value->indikator_perencanaan,
$value->lokasi,
$value->target_kinerja,
$value->anggaran,
$value->sumber_dana,
]);
}
return collect($arr);
}
public function styles(Worksheet $sheet)
{
$sheet
->getStyle("1:2")
->getFont()
->setBold(true);
}
I'm a total newbie to Wordpress and having a hard time figuring things out.
I'm using plugin called "WP-Pro-Quiz", a quiz plugin, and within the plugin there's an option to show "Leaderboard" of all users who completed the quiz. In the leaderboard on the frontend, there's user id, time, points and user's Display Name, etc for each user..
What I want to achieve is to make Display name clickable (and then to go to author's profile once clicked). That is, to connect Display Name with author profile who took the quiz, to create hyperlink from Display Name.
This is from controller WpProQuiz_Controller_Toplist.php :
<?php
class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller
{
public function route()
{
$quizId = $_GET['id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
default:
$this->showAdminToplist($quizId);
break;
}
}
private function showAdminToplist($quizId)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
$view = new WpProQuiz_View_AdminToplist();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$view->quiz = $quiz;
$view->show();
}
public function getAddToplist(WpProQuiz_Model_Quiz $quiz)
{
$userId = get_current_user_id();
if (!$quiz->isToplistActivated()) {
return null;
}
$data = array(
'userId' => $userId,
'token' => wp_create_nonce('wpProQuiz_toplist'),
'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId),
);
if ($quiz->isToplistDataCaptcha() && $userId == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$data['captcha']['code'] = $captcha->getPrefix();
}
}
return $data;
}
private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz)
{
if (!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$quizId = $quiz->getId();
$userId = get_current_user_id();
$points = (int)$this->_post['points'];
$totalPoints = (int)$this->_post['totalPoints'];
$name = !empty($this->_post['name']) ? trim($this->_post['name']) : '';
$email = !empty($this->_post['email']) ? trim($this->_post['email']) : '';
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : '';
$prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
if ($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$numPoints = $quizMapper->sumQuestionPoints($quizId);
if ($totalPoints > $numPoints || $points > $numPoints) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$clearTime = null;
if ($quiz->isToplistDataAddMultiple()) {
$clearTime = $quiz->getToplistDataAddBlock() * 60;
}
if ($userId > 0) {
if ($toplistMapper->countUser($quizId, $userId, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
$user = wp_get_current_user();
$email = $user->user_email;
$name = $user->display_name;
} else {
if ($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
if (empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return array('text' => __('No name or e-mail entered.', 'wp-pro-quiz'), 'clear' => false);
}
if (strlen($name) > 15) {
return array('text' => __('Your name can not exceed 15 characters.', 'wp-pro-quiz'), 'clear' => false);
}
if ($quiz->isToplistDataCaptcha()) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
if (!$captcha->check($prefix, $captchaAnswer)) {
return array('text' => __('You entered wrong captcha code.', 'wp-pro-quiz'), 'clear' => false);
}
}
}
}
$toplist = new WpProQuiz_Model_Toplist();
$toplist->setQuizId($quizId)
->setUserId($userId)
->setDate(time())
->setName($name)
->setEmail($email)
->setPoints($points)
->setResult(round($points / $totalPoints * 100, 2))
->setIp($ip);
$toplistMapper->save($toplist);
return true;
}
private function preCheck($type, $userId)
{
switch ($type) {
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL:
return true;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM:
return $userId == 0;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER:
return $userId > 0;
}
return false;
}
public static function ajaxAdminToplist($data)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
return json_encode(array());
}
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$j = array('data' => array());
$limit = (int)$data['limit'];
$start = $limit * ($data['page'] - 1);
$isNav = isset($data['nav']);
$quizId = $data['quizId'];
if (isset($data['a'])) {
switch ($data['a']) {
case 'deleteAll':
$toplistMapper->delete($quizId);
break;
case 'delete':
if (!empty($data['toplistIds'])) {
$toplistMapper->delete($quizId, $data['toplistIds']);
}
break;
}
$start = 0;
$isNav = true;
}
$toplist = $toplistMapper->fetch($quizId, $limit, $data['sort'], $start);
foreach ($toplist as $tp) {
$j['data'][] = array(
'id' => $tp->getToplistId(),
'name' => $tp->getName(),
'email' => $tp->getEmail(),
'type' => $tp->getUserId() ? 'R' : 'UR',
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
if ($isNav) {
$count = $toplistMapper->count($quizId);
$pages = ceil($count / $limit);
$j['nav'] = array(
'count' => $count,
'pages' => $pages ? $pages : 1
);
}
return json_encode($j);
}
public static function ajaxAddInToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$ctn = new WpProQuiz_Controller_Toplist();
$quizId = isset($data['quizId']) ? $data['quizId'] : 0;
$prefix = !empty($data['prefix']) ? trim($data['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$r = $ctn->handleAddInToplist($quiz);
if ($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$captcha->remove($prefix);
$captcha->cleanup();
if ($r !== true) {
$r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$r['captcha']['code'] = $captcha->getPrefix();
}
}
}
if ($r === true) {
$r = array('text' => __('You signed up successfully.', 'wp-pro-quiz'), 'clear' => true);
}
return json_encode($r);
}
public static function ajaxShowFrontToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$quizIds = empty($data['quizIds']) ? array() : array_unique((array)$data['quizIds']);
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$j = array();
foreach ($quizIds as $quizId) {
$quiz = $quizMapper->fetch($quizId);
if ($quiz == null || $quiz->getId() == 0) {
continue;
}
$toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort());
foreach ($toplist as $tp) {
$j[$quizId][] = array(
'name' => $tp->getName(),
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
}
return json_encode($j);
}
}
and from model WpProQuiz_Model_Toplist.php:
<?php
class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model
{
protected $_toplistId;
protected $_quizId;
protected $_userId;
protected $_date;
protected $_name;
protected $_email;
protected $_points;
protected $_result;
protected $_ip;
public function setToplistId($_toplistId)
{
$this->_toplistId = (int)$_toplistId;
return $this;
}
public function getToplistId()
{
return $this->_toplistId;
}
public function setQuizId($_quizId)
{
$this->_quizId = (int)$_quizId;
return $this;
}
public function getQuizId()
{
return $this->_quizId;
}
public function setUserId($_userId)
{
$this->_userId = (int)$_userId;
return $this;
}
public function getUserId()
{
return $this->_userId;
}
public function setDate($_date)
{
$this->_date = (int)$_date;
return $this;
}
public function getDate()
{
return $this->_date;
}
public function setName($_name)
{
$this->_name = (string)$_name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setEmail($_email)
{
$this->_email = (string)$_email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setPoints($_points)
{
$this->_points = (int)$_points;
return $this;
}
public function getPoints()
{
return $this->_points;
}
public function setResult($_result)
{
$this->_result = (float)$_result;
return $this;
}
public function getResult()
{
return $this->_result;
}
public function setIp($_ip)
{
$this->_ip = (string)$_ip;
return $this;
}
public function getIp()
{
return $this->_ip;
}
}
I'm trying to generate a JSON API using PHP to be used as remote server interface for my Android application database.
I managed to generate JSON like this:
{
products: [
{
product_name: "Samsung",
product_category: "phones",
shop_name: "Gadget Store",
user_id: "1",
price: "1999",
date: "2015-04-05",
time: "11:14:44"
},
{
product_name: "Samsung",
product_category: "phones",
shop_name: "IT Store",
user_id: "1",
price: "1899",
date: "2015-04-01",
time: "13:00:00"
},
{
product_name: "Motorola",
product_category: "phones",
shop_name: "IT Store",
user_id: "1",
price: "1499",
date: "2015-04-02",
time: "10:31:29"
}
]
}
But I guess I need a nested JSON which is something like this:
{
products: [
{
product_name: "Samsung",
product_category: "phones",
shops: [
{
shop_name: "Gadget Store",
user_id: "1",
price: "1999",
date: "2015-04-05",
time: "11:14:44"
},
{
shop_name: "IT Store",
user_id: "1",
price: "1899",
date: "2015-04-01",
time: "13:00:00"
}
],
},
{
product_name: "Motorola",
product_category: "phones",
shops: [
shop_name: "IT Store",,
user_id: "1",
price: "199",
date: "2015-04-02",,
time: "10:31:29"
],
}
]
}
How can I achive this result?
The sql query is from 3 different table.
Below is my current code:
class productDB
{
public $product_name = "";
public $product_category = "";
public $shop_name = "";
public $user_id = "";
public $price;
public $date = "";
public $time = "";
function __construct($product_name, $product_category, $shop_name, $user_id, $price, $date, $time)
{
$this->product_name = $product_name;
$this->product_category = $product_category;
$this->shop_name = $shop_name;
$this->user_id = $user_id;
$this->price = $price;
$this->date = $date;
$this->time = $time;
}
class Shop
{
public $shop_name = "";
public $user_id = "";
public $price;
public $date = "";
public $time = "";
function __construct($shop_name, $user_id, $price, $date, $time)
{
$this->shop_name = $shop_name;
$this->user_id = $user_id;
$this->price = $price;
$this->date = $date;
$this->time = $time;
}
}
class product
{
public $product_name = "";
public $product_category = "";
public $shop = "";
function __construct($product_name, $product_category, $shop_name, $user_id, $price, $date, $time)
{
$this->product_name = $product_name;
$this->product_category = $product_category;
$this->shop = new Shop($shop_name, $user_id, $price, $date, $time);
}
}
$query = "SELECT a.product_name, a.product_category,
b.shop_name,
c.user_user_id, c.price, c.date, c.time
FROM price c, item a, shop b
WHERE c.product_product_id = a.product_id AND c.shop_shop_id = b.shop_id";
$product_array = array();
if ($result = $dbc->query($query)) {
while ($obj = $result->fetch_object()) {
$temp_product[] = new ProductDB(
$obj->product_name,
$obj->product_category,
$obj->shop_name,
$obj->user_id,
$obj->price,
$obj->date,
$obj->time);
$product_array = $temp_product;
}
//Give a name to the array
$array_name = 'products';
$product_array = (array($array_name=>$product_array));
$product_object = json_encode($product_array);
echo $product_object;
Here you have a solution which does not require subqueries.
It looks like at least in this example you do not need the ProductDB so we will use directly Product class
To keep the shops in the Product object we need the holder there. We will change $shop into $shops which will hold an array with Shop objects.
Product class:
class Product
{
public $product_name = "";
public $product_category = "";
public $shops = null;
function __construct($product_name, $product_category, $shop_name, $user_id, $price, $date, $time)
{
$this->product_name = $product_name;
$this->product_category = $product_category;
$this->shops = array(new Shop($shop_name, $user_id, $price, $date, $time));
}
public function addShop($shop_name, $user_id, $price, $date, $time)
{
// because $shops is a public property we can check if it still is an array
if (!is_array($this->shops)) {
$this->shops = array();
}
$this->shops[] = new Shop($shop_name, $user_id, $price, $date, $time);
}
}
Ass you can see there is a new function which adds new shops to the array.
Now the part which will group the shops into the products.
$product_array = array();
$currProduct = null;
if ($result = $dbc->query($query)) {
while ($obj = $result->fetch_object()) {
// check if it is a first product or if we have encountered product with different name or category
if ($currProduct === null
|| $currProduct->product_name !== $obj->product_name
|| $currProduct->product_category !== $obj->product_category) {
// create new Product with one position in the shops array
$product = new Product(
$obj->product_name,
$obj->product_category,
$obj->shop_name,
$obj->user_id,
$obj->price,
$obj->date,
$obj->time);
$product_array[] = $product;
// set created product as a currently used
$currProduct = $product;
} else {
// if name and category is the same add shop data to the current product
$currProduct->addShop(
$obj->shop_name,
$obj->user_id,
$obj->price,
$obj->date,
$obj->time);
}
}
$product_array = array('products' => $product_array);
$product_json = json_encode($product_array);
echo $product_json;
}
TO group the data properly it is necessary to sort the products data. So add at the end of the query ORDER BY a.product_name, a.product_category.
That's it :) Let me know how if it worked (if you will use it)
Also if you would like to declare the class properties private and still use json_encode to get the JSON representation of your classes, you can use JsonSerializable interface.
Shop class
class Shop implements \JsonSerializable
{
private $shop_name = "";
private $user_id = "";
private $price;
private $date = "";
private $time = "";
function __construct($shop_name, $user_id, $price, $date, $time)
{
$this->shop_name = $shop_name;
$this->user_id = $user_id;
$this->price = $price;
$this->date = $date;
$this->time = $time;
}
public function JsonSerialize()
{
return get_object_vars($this);
}
}
Product class
class Product implements \JsonSerializable
{
private $product_name = "";
private $product_category = "";
private $shops = null;
function __construct($product_name, $product_category, $shop_name, $user_id, $price, $date, $time)
{
$this->product_name = $product_name;
$this->product_category = $product_category;
$this->shops = array(new Shop($shop_name, $user_id, $price, $date, $time));
}
public function addShop($shop_name, $user_id, $price, $date, $time)
{
$this->shops[] = new Shop($shop_name, $user_id, $price, $date, $time);
}
function getName()
{
return $this->product_name;
}
function getCategory()
{
return $this->product_category;
}
public function JsonSerialize()
{
return get_object_vars($this);
}
}
Main code
[...]
if ($currProduct === null
|| $currProduct->getName() !== $obj->product_name
|| $currProduct->getCategory() !== $obj->product_category) {
[...]
Have fun :)
To keep a consistent JSON structure, the second part would look like this:
{
product_name: "Motorola",
product_category: "phones",
shops: [
shop_name: "IT Store",
user_id: "1",
price: "1499",
date: "2015-04-02",
time: "10:31:29"
]
}
How about something like this:
$queryStr_products = "Select * FROM item";
$queryStr_price = "Select b.shop_name, c.user_user_id, c.price, c.date, c.time FROM price c, shop b WHERE b.shop_id = c.product_product_id and c.product_product_id =";
$product_array = array();
if ($result = $dbc->query($queryStr_products)) {
//Iterate over all products returned
while ($obj = $result->fetch_object()) {
$product_array[] = array (
'product_name' => $obj->product_name,
'product_category' => $obj->product_category,
'shops' => getPricesForProducts($obj->product_id)
);
}
$result->close();
}
echo json_encode(array('products'=>$product_array));
/**
* For clarity purposes
* This returns an array of all product prices for a particular productID
*/
function getPricesForProducts ($productID) {
//You may need to get a new DB connection
if ($result = $dbc2->query($queryStr_price.$productID)) {
$price_array = array();
while($obj = $result->fetch_object()) {
$price_array[] = array (
'shop_name' => $obj->b.shop_name,
'user_id' => $obj->c.user_user.id,
'price' => $obj->c.price,
'date' => $obj->c.date,
'time' => $obj->c.time,
);
}
$result->close();
return $price_array;
} else {
//Maybe you want to set shop_name to "No Prices Found" and user_id = 0;
return array();
}
}
I have some function which I use in my cart application:
session_start();
if(!isset($_SESSION['products'], $_SESSION['price'], $_SESSION['product_names'],$_SESSION['product_id'])) {
$_SESSION['products'] = 0;
$_SESSION['price'] = 0;
$_SESSION['product_names'] = array();
$_SESSION['product_id'] = array();
}
if(isset($_POST['add'])) {
$_SESSION['product_names'][] = $_POST['product_name'];
$_SESSION['products']++;
$_SESSION['price'] += $_POST['price'];
}
if(isset($_POST['empty'])) {
session_destroy();
header('Location:index.php');
}
The question is, how can I add this into a class and call it in my view page?
I mean it will still work as <?php echo $_SESSION['price']?>. How can I make this work?
Try this class you're doing in a wrong way.
session_start();
class Shopping {
public function __construct()
{
}
//get cart products
public function getCartProducts()
{
$cart = array();
if(isset($_SESSION['cart'])) {
$cart = unserialize($_SESSION['cart']);
}
return $cart;
}
//add product to cart
public function addToCart($product_details)
{
$cart = $this->getCartProducts();
$product_id = $product_details['product_id'];
$is_quantity = $this->addQuantity($product_id); //check if product already exists in session if then increase the quantity
if(!$is_quantity) {
$product_details = array(
'qty' => $product_details['qty'],
'price' => $product_details['price'],
'product_name' => $product_details['name'],
'product_id' => $product_id
);
array_push($cart, $product_details);
$_SESSION['cart'] = serialize($cart);
}
}
//add quantity if product already exists
private function addQuantity($product_id)
{
$cart = $this->getCartProducts();
$i = 0;
foreach ($cart as $product) {
if($product['product_id'] == $product_id)
{
$product['qty'] += 1;
$cart[$i] = $product;
$_SESSION['cart'] = serialize($cart);
return true;
}
$i++;
}
return false;
}
public function clearCart()
{
unset($_SESSION['cart']);
}
public function removeProduct($product_id)
{
$cart = $this->getCartProducts();
$new_cart = array();
foreach ($cart as $product) {
if($product['product_id'] != $product_id)
array_push($new_cart, $product);
}
$_SESSION['cart'] = serialize($new_cart);
}
}
$shop = new Shopping();
$shop->addToCart(array('product_id'=>1,'name'=>'test 1','price'=>'120.00','qty'=>1));
$shop->addToCart(array('product_id'=>3,'name'=>'test 2','price'=>'120.00','qty'=>1));
This is an example of my approach using session in class. References work pretty well.
class Cart {
private $container ;
public function __construct(&$container){
if (!isset($container) || !is_array($container))
$session['cart'] = array() ;
$this->container = &$container ;
}
public function productExists($id){
return (isset($this->container[$id])) ;
}
}
$cart = new Cart($_SESSION['cart']) ;
At this point all changes in container can be performed in $_SESSION['cart'] . The rest of session array is not affected, that should be safe.
I noticed laravel re-preform the insertion action when the timeout occurs
How can I shop it from retiring to insert the data again when timeout error fires ?
loop
foreach ($comments_data as $comment_data)
{
if ( ! empty($comment_data['date']))
{
$total_rating[] = $this->check_rating_value($comment_data['rating']);
$comment_id = ( new Comment() )->saveComments($shop, $comment_data, $product_id, $urls, $shop_options);
( new Comments_images() )->save_images($comment_id, $shop, $comment_data['images']);
}
}
inserting code
public function saveComments($shop, $comments_data, $product_id, $url, $shop_options)
{
$date = Carbon::parse($comments_data['date']);
if ($shop_options->filter_status == 1)
{
$comments = str_replace(explode(',', $shop_options->filter_find_words), explode(',', $shop_options->filter_alter_words), $comments_data['comment']);
} else
{
$comments = $comments_data['comment'];
}
$faker = Factory::create();
$this->shop_name = $shop;
$this->comment = $comments;
$this->rating = $this->check_rating_value($comments_data['rating']);
$this->product_id = $product_id;
$this->user_name = $faker->userName;
$this->product_url = $url;
$this->created_at = $date->toDateTimeString();
$this->country = $comments_data['country'] == 'IL' ? 'PS' : $comments_data['country'];
$this->view = 1;
$this->save();
return $this->id;
}