0

I have a Marketplace Module I want to send a mail after save Product

Controller.php

public function newpostAction()
{
    /**
     *  Check license key
     */
    Mage::helper('marketplace')->checkMarketplaceKey();
    /**
     *  Initilize customer and seller group id
     */
    $customerGroupId = $sellerGroupId = $customerStatus = '';
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    $customerGroupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
    $sellerGroupId = Mage::helper('marketplace')->getGroupId();
    $customerStatus = Mage::getSingleton('customer/session')->getCustomer()->getCustomerstatus();
    if (!$this->_getSession()->isLoggedIn() && $customerGroupId != $sellerGroupId) {
        Mage::getSingleton('core/session')->addError($this->__('You must have a Seller Account to access this page'));
        $this->_redirect('marketplace/seller/login');
        return;
    }
    /**
     *  Checking whether customer approved or not
     */
    if ($customerStatus != 1) {
        Mage::getSingleton('core/session')->addError($this->__('Admin Approval is required. Please wait until admin confirms your Seller Account'));
        $this->_redirect('marketplace/seller/login');
        return;
    }
    /**
     *  Initializing variables
     */
    $productNameTrim = $set = $setbase = $type = $store = $sellerId = '';
    /**
     *  Getting  product values
     */
    $type = $this->getRequest()->getPost('type');
    /**
     *  Attribute set
     */
    $set = $this->getRequest()->getPost('set');
    $setbase = $this->getRequest()->getPost('setbase');
    $store = $this->getRequest()->getPost('store');
    if (Mage::getSingleton('customer/session')->isLoggedIn()) {
        $sellerId = Mage::getSingleton('customer/session')->getCustomer()->getId();
    }
    /**
     *  Getting group id
     */
    $groupId = Mage::helper('marketplace')->getGroupId();
    /**
     *  Getting product data from product array
     */
    $productData = $this->getRequest()->getPost('product');

    $silkType = $productData['silktype'];

    /**
     *  Getting product categories from category_ids array
     */
    $categoryIds = $this->getRequest()->getPost('category_ids');
    if (!empty($productData['name']) && !empty($productData['description']) && isset($productData['price']) && isset($productData['stock_data']['qty']) && !empty($type)) {
        /**
         *  Initilize product weight
         */
        if ($type == 'simple') {
            if (!isset($productData['weight'])) {
                $productData['weight'] = 0;
            }
        }
        /**
         *  Assing product short description
         */
        if (!empty($productData['short_description'])) {
            $productData['short_description'] = $productData['short_description'];
        }
        /**
         *  Assign create at time
         */
        $createdAt = Mage::getModel('core/date')->gmtDate();

        /**
         *  Getting instance for catalog product collection
         */
        $product = Mage::getModel('catalog/product');
        /**
         *  Initialize product sku
         */

        if (isset($productData['sku'])) {
            $skuProductId = Mage::getModel('catalog/product')
                ->getIdBySku(trim($productData['sku']));
            if (!empty($skuProductId)) {
                /**
                 *  Error message redirect to create new product page
                 */
                Mage::getSingleton('core/session')->addError($this->__('SKU Not Available'));
                $this->_redirect('marketplace/product/new/');
                return;
            }
        }


        /**
         *  Initialize product attribute set id
         */
        if (!empty($set)) {
            $product->setAttributeSetId($set);
        } else {
            $sDefaultAttributeSetId = Mage::getSingleton('eav/config')
                ->getEntityType(Mage_Catalog_Model_Product::ENTITY)
                ->getDefaultAttributeSetId();
            $product->setAttributeSetId($sDefaultAttributeSetId);
        }

        /**
         *  Initialize product type
         */
        if (isset($type)) {
            $product->setTypeId($type);
        }


        /**
         *  Initialize product categories
         */
        if (isset($categoryIds)) {
            $product->setCategoryIds($categoryIds);
        }
        $product->setSilktype($silkType);

        /**
         *  Storing product data's to all store view
         */
        $product->setStoreId(0);

        /**
         *  Initialize product create at time
         */
        if (isset($createdAt)) {
            $product->setCreatedAt($createdAt);
        }
        /**
         *  Initialize seller id
         */
        if (isset($sellerId)) {
            $product->setSellerId($sellerId);
        }

        /**
         *  Initialize group id
         */
        if (isset($groupId)) {
            $product->setGroupId($groupId);
        }

        /**
         * Set is assign product
         */
        $product->setIsAssignProduct(0);

        $uploadsData = new Zend_File_Transfer_Adapter_Http();
        $filesDataArray = $uploadsData->getFileInfo();

        /**
         *  Checking whether image exist or not
         */
        if (!empty($filesDataArray)) {
            foreach ($filesDataArray as $key => $value) {
                /**
                 *  Initilize file name
                 */
                $filename = $key;

                if (substr($key, 0, 5) == 'image') {
                    if (isset($filesDataArray[$filename]['name']) && (file_exists($filesDataArray[$filename]['tmp_name']))) {
                        try {
                            $imagesPath[] = Mage::helper('marketplace/marketplace')->uploadImage($filename, $filesDataArray);
                        } catch (Exception $e) {
                            /**
                             *  Display error message for images upload
                             */
                            Mage::getSingleton('core/session')->addError($this->__($e->getMessage()));
                        }
                    }
                }
            }
        }

        /**
         *  Adding Product images
         */
        if (!empty($imagesPath)) {
            $product->setMediaGallery(array('images' => array(), 'values' => array()));
            foreach ($imagesPath as $value) {
                $product->addImageToMediaGallery($value, array('image', 'small_image', 'thumbnail'), false, false);
            }
        }


        /**
         *   Initialize dispatch event for product prepare
         */
        Mage::dispatchEvent(
            'catalog_product_prepare_save', array('product' => $product, 'request' => $this->getRequest())
        );

        /**
         *  Assign configurable product data
         */
        if ($type == 'configurable') {
            $attributeIds = $this->getRequest()->getPost('attributes');
            $isInStock = 1;
            if (isset($productData['stock_data']['is_in_stock'])) {
                $isInStock = $productData['stock_data']['is_in_stock'];
            }
            $productData['stock_data'] = array();
            if (count($attributeIds) >= 1) {
                $attributeIds = array_unique($attributeIds);
                $product->getTypeInstance()->setUsedProductAttributeIds($attributeIds);
                $configurableAttributesData = $product->getTypeInstance()->getConfigurableAttributesAsArray();
                $product->setCanSaveConfigurableAttributes(true);
                $product->setConfigurableAttributesData($configurableAttributesData);
                $product->setConfigurableProductsData(array());
            }
        }

        /**
         *  Adding data to product instanse
         */
        if (!empty($productData)) {
            $product->addData($productData);
        }
        /**
         *  Saving new product
         */
        try {
            $product->save();

            if ($type == 'configurable') {
                $stockItem = Mage::getModel('cataloginventory/stock_item');
                $stockItem->assignProduct($product);
                $stockItem->setData('stock_id', 1);
                if (isset($productData['stock_data']['qty'])) {
                    $stockItem->setData('qty', $productData['stock_data']['qty']);
                } else {
                    $stockItem->setData('qty', 0);
                }
                $stockItem->setData('use_config_min_qty', 1);
                $stockItem->setData('use_config_backorders', 1);
                $stockItem->setData('min_sale_qty', 1);
                $stockItem->setData('use_config_min_sale_qty', 1);
                $stockItem->setData('use_config_max_sale_qty', 1);
                $stockItem->setData('is_in_stock', $isInStock);
                $stockItem->setData('use_config_notify_stock_qty', 1);
                $stockItem->setData('manage_stock', 1);
                $stockItem->save();

                //This section is what was required.
                $stockStatus = Mage::getModel('cataloginventory/stock_status');
                $stockStatus->assignProduct($product);
                $stockStatus->saveProductStatus($product->getId(), 1);
            }

            $productId = $product->getId();

            /**
             * Load the product
             */
            $product = Mage::getModel('catalog/product')->load($productId);
            /**
             * Get all images
             */
            $mediaGallery = $product->getMediaGallery();
            /**
             * If there are images
             */
            if (isset($mediaGallery['images']) && !empty($store)) {
                /**
                 * Loop through the images
                 */
                $increment = 0;
                foreach ($mediaGallery['images'] as $image) {
                    /**
                     * Set the first image as the base image
                     */
                    if ($increment == $setbase) {
                        $product->setStoreId($store)
                            ->setImage($image['file'])
                            ->setSmallImage($image['file'])
                            ->setThumbnail($image['file']);

                        $product->save();
                    }
                    $increment++;
                    /**
                     * Stop
                     */

                }

            }

            /**
             *   Initialize product options
             */
            if (!empty($productData['options'])) {
                $product->setProductOptions($productData['options']);
                $product->setCanSaveCustomOptions(1);
                $product->save();
            }

            /**
             *  Checking whether image or not
             */
            if (!empty($imagesPath)) {
                foreach ($imagesPath as $deleteImage) {
                    /**
                     *  Checking whether image exist or not
                     */
                    if (file_exists($deleteImage)) {
                        /**
                         *  Delete images from temporary folder
                         */
                        unlink($deleteImage);
                    }
                }
            }

            /**
             *  Function for adding downloadable product sample and link data
             */
            $downloadProductId = $product->getId();
            if ($type == 'downloadable' && isset($downloadProductId) && isset($store)) {
                $this->addDownloadableProductData($downloadProductId, $store);
            }

            /**
             *  Success message redirect to manage product page
             */
            if (Mage::helper('marketplace')->getProductApproval() == 1) {
                Mage::getSingleton('core/session')->addSuccess($this->__('Your product is added successfully'));
                $mail = Mage::getModel('core/email');
                /*$mail = Mage::getModel('core/email');
                $mail->setToName('User');
                $mail->setToEmail('[email protected]');
                $mail->setBody('Send Test mail to you.....');
                $mail->setSubject('Test Mail');
                $mail->setFromEmail('[email protected]');
                $mail->setFromName("Send Test mail to you.....");
                $mail->setType('html');// YOu can use Html or text as Mail format
                $mail->send(); */

                $sellerData = Mage::getSingleton('customer/session')->getCustomer();
                $sellerIdss = $sellerData->getId();
                $seller_mail = $sellerData->getEmail();

                $collectionss = Mage::getModel('followup/followup')->getCollection()
                    ->addFieldToFilter('seller_id', $sellerIdss)
                    ->addFieldToFilter('seller_email', $seller_mail);

                foreach ($collectionss as $item) {
                    $mycustomer_email = $item->getCustomerEmail();
                    $mycustomer_name = $item->getCustomerName();

                    $template_id = 'customer_update';
                    $email_to = $mycustomer_email;
                    $customer_name = $cus_name;
                    $email_template = Mage::getModel('core/email_template')->loadDefault($template_id);
                    $custom_variable = $mycustomer_name;
                    //$custom_variable1 = $cus_email;
                    $custom_variable1 = $this->getRequest()->getPost('store_name');
                    $email_template_variables = array(
                        'custom_variable' => $custom_variable,
                        'custom_variable1' => $custom_variable1);
                    //'custom_variable2' => $custom_variable2);
                    $sender_name = Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_STORE_STORE_NAME);
                    $sender_email = Mage::getStoreConfig('trans_email/ident_general/email');
                    $email_template->setSenderName($sender_name);
                    $email_template->setSenderEmail($sender_email);
                    $email_template->send($email_to, $customer_name, $email_template_variables);

                }

                if (Mage::getStoreConfig('marketplace/product/addproductemailnotification') == 1) {
                    /**
                     *  Sending email for added new product
                     */
                    $templateId = (int)Mage::getStoreConfig('marketplace/product/addproductemailnotificationtemplate');
                    $adminEmailId = Mage::getStoreConfig('marketplace/marketplace/admin_email_id');
                    $toMailId = Mage::getStoreConfig("trans_email/ident_$adminEmailId/email");
                    $toName = Mage::getStoreConfig("trans_email/ident_$adminEmailId/name");

                    /**
                     *  Selecting template id
                     */
                    if ($templateId) {
                        $emailTemplate = Mage::getModel('core/email_template')->load($templateId);
                    } else {
                        $emailTemplate = Mage::getModel('core/email_template')
                            ->loadDefault('marketplace_product_addproductemailnotificationtemplate');
                    }
                    $customer = Mage::getModel('customer/customer')->load($sellerId);
                    $selleremail = $customer->getEmail();
                    $recipient = $toMailId;
                    $sellername = $customer->getName();
                    $productname = $product->getName();
                    $producturl = $product->getProductUrl();
                    $emailTemplate->setSenderName($sellername);
                    $emailTemplate->setSenderEmail($selleremail);
                    $emailTemplateVariables = (array('ownername' => $toName, 'sellername' => $sellername, 'selleremail' => $selleremail, 'productname' => $productname, 'producturl' => $producturl));
                    $emailTemplate->setDesignConfig(array('area' => 'frontend'));
                    $processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
                    $emailTemplate->send($recipient, $sellername, $emailTemplateVariables);


                }
            } else {
                Mage::getSingleton('core/session')->addSuccess($this->__('Your product is awaiting moderation'));
                /*$mail = Mage::getModel('core/email');
                $mail->setToName('User');
                $mail->setToEmail('[email protected]');
                $mail->setBody('Send Test mail to you.....');
                $mail->setSubject('Test Mail');
                $mail->setFromEmail('[email protected]');
                $mail->setFromName("Send Test mail to you.....");
                $mail->setType('html');// YOu can use Html or text as Mail format
                $mail->send(); */

                foreach ($collectionss as $item) {
                    $mycustomer_email = $item->getCustomerEmail();
                    $mycustomer_name = $item->getCustomerName();

                    $template_id = 'customer_update';
                    $email_to = $mycustomer_email;
                    $customer_name = $cus_name;
                    $email_template = Mage::getModel('core/email_template')->loadDefault($template_id);
                    $custom_variable = $mycustomer_name;
                    //$custom_variable1 = $cus_email;
                    $custom_variable1 = $this->getRequest()->getPost('store_name');
                    $email_template_variables = array(
                        'custom_variable' => $custom_variable,
                        'custom_variable1' => $custom_variable1);
                    //'custom_variable2' => $custom_variable2);
                    $sender_name = Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_STORE_STORE_NAME);
                    $sender_email = Mage::getStoreConfig('trans_email/ident_general/email');
                    $email_template->setSenderName($sender_name);
                    $email_template->setSenderEmail($sender_email);
                    $email_template->send($email_to, $customer_name, $email_template_variables);

                }

                if (Mage::getStoreConfig('marketplace/product/addproductemailnotification') == 1) {
                    /**
                     *  Sending email for added new product
                     */
                    $templateId = (int)Mage::getStoreConfig('marketplace/product/addproductapprovalemailnotificationtemplate');
                    $adminEmailId = Mage::getStoreConfig('marketplace/marketplace/admin_email_id');
                    $toMailId = Mage::getStoreConfig("trans_email/ident_$adminEmailId/email");
                    $toName = Mage::getStoreConfig("trans_email/ident_$adminEmailId/name");

                    if ($templateId) {
                        $emailTemplate = Mage::getModel('core/email_template')->load($templateId);
                    } else {
                        $emailTemplate = Mage::getModel('core/email_template')
                            ->loadDefault('marketplace_product_addproductapprovalemailnotificationtemplate');
                    }
                    $customer = Mage::getModel('customer/customer')->load($sellerId);
                    $selleremail = $customer->getEmail();
                    $recipient = $toMailId;
                    $sellername = $customer->getName();
                    $productname = $product->getName();
                    $producturl = Mage::helper('adminhtml')->getUrl('adminhtml/catalog_product/edit', array('id' => $product->getId()));

                    $emailTemplate->setSenderName($sellername);
                    $emailTemplate->setSenderEmail($selleremail);
                    $emailTemplateVariables = (array('ownername' => $toName, 'sellername' => $sellername, 'selleremail' => $selleremail, 'productname' => $productname, 'producturl' => $producturl));
                    $emailTemplate->setDesignConfig(array('area' => 'frontend'));
                    $processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
                    $emailTemplate->send($recipient, $sellername, $emailTemplateVariables);


                }
            }

            if ($type == 'configurable') {
                $this->_redirect('marketplace/product/configurable/', array('id' => $productId, 'set' => $set));
                return;
            }

            $this->_redirect('marketplace/product/manage/');
        } catch (Mage_Core_Exception $e) {
            /**
             *  Error message redirect to create new product page
             */
            Mage::getSingleton('core/session')->addError($this->__($e->getMessage()));
            $this->_redirect('marketplace/product/create/');
        } catch (Exception $e) {
            /**
             *  Error message redirect to create new product page
             */
            Mage::getSingleton('core/session')->addError($this->__($e->getMessage()));
            $this->_redirect('marketplace/product/create/');
        }
    } else {
        Mage::getSingleton('core/session')->addError($this->__('Please enter all required fields'));
        if ($type == 'configurable') {
            $this->_redirect('marketplace/product/selectattributes/', array('set' => $set));
            return;
        }
        $this->_redirect('marketplace/product/new');
    }
}    

config.xml

<catalog_product_save_after>
    <observers>
        <marketplace>
            <class>marketplace/observer</class>
            <method>sendme</method>
        </marketplace>
    </observers>
</catalog_product_save_after>

Observer.php

public function sendme($observer)
{
    $mail = Mage::getModel('core/email');
    $mail->setToName('User');
    $mail->setToEmail('[email protected]');
    $mail->setBody('Send Test mail to you.....');
    $mail->setSubject('Test Mail');
    $mail->setFromEmail('[email protected]');
    $mail->setFromName("Send Test mail to you.....");
    $mail->setType('html');// YOu can use Html or text as Mail format
    $mail->send();
}

Error

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '16958-1' for key 'UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID', query was: INSERT INTO cataloginventory_stock_item (product_id, stock_id, qty, is_in_stock, low_stock_date, stock_status_changed_auto) VALUES (?, ?, ?, ?, ?, ?)

is it right or Suggest me

1 Answer 1

1

The error has nothing to do with your observer.
The error says that you are trying to add an other record in the table cataloginventory_stock_item for a product that already has a stock item.
This should not happen if you call save from the admin panel, so I assume this happens when you call $product->save from your custom code.
Make sure you call save only if you called load prior to that. Also, never call save from a product that you get from iterating a collection.

4
  • Sorry i am not getting i save product in controller and send mail through observer
    – Magento 2
    Commented May 17, 2016 at 16:22
  • show the code from your controller. is it the admin product controller?
    – Marius
    Commented May 17, 2016 at 16:23
  • Check my updated question it's seller save product front not admin product controller
    – Magento 2
    Commented May 17, 2016 at 16:26
  • mmm... are you sure you want to manage stock with your configurable products? Commented May 18, 2016 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.