Catalog Price Rule Magento 2 - magento2

I have created a custom module in Magento 2. In which i want to show some banners, Countdown timer and extra details on product page, also label or text on category page. for this i extended the catalog sales rule module. Added some extra field according to my requirements. Now i want to show get all those products ids on which sale rule has applied with all other details like Top Banner, Countdown timer according to sale etc.
my Block Code is
<?php
namespace Custom\Sales\Block;
class Flash extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\CatalogRule\Model\ResourceModel\Rule\CollectionFactory $ruleFactory,
array $data = []
) {
$this->_ruleFactory = $ruleFactory;
parent::__construct($context, $data);
}
public function getCatalogeRuleId()
{
$catalogRuleCollection = $this->_ruleFactory->create()
->addFieldToFilter('is_active',1);
// return $catalogRuleCollection;
$resultProductIds = [];
foreach ($catalogRuleCollection as $catalogRule) {
$productIdsAccToRule = $catalogRule->getMatchingProductIds();
// echo json_encode($productIdsAccToRule); exit;
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
foreach ($productIdsAccToRule as $productId => $ruleProductArray) {
if (!empty($ruleProductArray[$websiteId])) {
$resultProductIds[$productId] = $catalogRule->getData();
}
}
return $resultProductIds;
}
}
}
Now when i print my array i get only one sale rule data , however i have created 3 different sales

Related

How can I get a subtotal by looping. Using SugarCRM CE 6.5.13

I am trying to get a total from the rows returned for the selected opportunity.
When a opportunity is selected each product they have purchased and its price is listed. I am trying to use the price for each purchased product to get a subtotal for all sales made with that opportunity.
Here is the code I have:
function total(&$focus, $event, $arguments)
{
$total = 0;
foreach ($this->bean->Product_Sales['sales_price_c'] as $entry) {
$total += unformat_number($entry['sales_price_c']);
}
$this->bean->ss->assign('total_sales_c', format_number($total));
}
Example of how rows are returned:
[Product_Name_Field] [Product_Price_Field] [Sales_Person_Field] [Etc_Field]
Only qty(1) Product sold per returned row.
What am I doing wrong?
Thanks in advance.
Okay I figured it out!!!!
This is File view.detail.php in Custom/Module/Opportunities/Views/
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('include/MVC/View/views/view.detail.php');
class OpportunitiesViewDetail extends ViewDetail {
function OpportunitiesViewDetail(){
parent::ViewDetail();
}
function display() {
$account = new Opportunity();//var = new ModuleName() in singular form
$account->retrieve($_REQUEST['record']);//This grabs the record
$contacts = $account->get_linked_beans('opportunities_op_ps_product_sales_1','Contact');
//this uses the get_linked_beans(Param 1 is the linked var name found in the vardefs ,Param 2 is the name of the object you are creating. The name can be anything you like.)
// loop through the created associations to get fields.
foreach ( $contacts as $contact ) {
$total += $contact->sales_price_c;//add the value of each sale to the variable
}
//populate the field you want with the value in the $total var
echo "
<script>
var total = '$total';
$(document).ready(function(){
$('#total_sales_c').after(total); });
</script>";
parent::display();
}
}
?>
Hopefully this will help others.

sf 1.4 Access & customize embededObject() in root form

I got a problem to save custom values for embededforms in root form.
I can actually edit a "manifestation" and i can add as much as i want "commande_wifi".
Everything is good saved.
I need to customize the process for every "commande_wifi" ( there is a 'puht' value depending on other values of the object() ). I have already lost a few hours only to do that.
save() is only called on the root form
That’s right! Only the root form has save() called. So if there’s other logic you want to run, you will want to override the saveEmbeddedForm method and call that code before. Oversimplification ahead: when you save a form with embedded forms, it calls $this->getObject()->save(), then it calls saveEmbeddedForms, which, for each embedded form, calls $form->saveEmbeddedForms() and then calls $form->getObject()->save(). This is critical to know, as it will save you a lot of headaches later on.
http://jmather.com/2011/01/29/6-things-to-know-about-embedded-forms-in-symfony/
I've tried to overwrite the saveembededForms() but fail at this point.
class manifestationForm extends BasemanifestationForm
{
public function configure()
{
$this->embedRelation('commande_wifi');
}
public function addNewFields($number){
$new_commandes = new BaseForm();
for($i=0; $i <= $number; $i+=1){
$commande = new Commande_wifi();
$commande->setManifestation($this->getObject());
$commande_form = new commande_wifiForm($commande);
$new_commandes->embedForm($i,$commande_form);
}
$this->embedForm('new', $new_commandes);
}
public function bind(array $taintedValues = null, array $taintedFiles = null){
$new_commandes = new BaseForm();
foreach($taintedValues['new'] as $key => $new_commande){
$commande = new Commande_wifi();
$commande->setManifestation($this->getObject());
$commande_form = new commande_wifiForm($commande);
$new_commandes->embedForm($key,$commande_form);
}
$this->embedForm('new',$new_commandes);
parent::bind($taintedValues, $taintedFiles);
}
public function saveEmbeddedForm($con = null, $forms = null)
{
if ($con === NULL)
{
$con = $this->getConnection();
}
if ($forms === NULL)
{
$forms = $this->getEmbeddedForms();
}
foreach ($forms as $form)
{
if ($form instanceof sfFormObject)
{
$form->saveEmbeddedForms($con);
$form->getObject()->setPuht(99);
$form->getObject()->save($con);
}
else
{
$this->saveEmbeddedForms($con, $form->getEmbeddedForms());
}
//$form->getObject()->setPuht(99)->save();
}
}
}
It's won ASAP i can access the embedForm Object().
Any suggestion?

Creating cumulative pdf of orders in magento

I want to create a pdf of first 300 orders in magento. I want a functionality in which i will get first 300 orders and print their images(each order has different image) in a pdf. So how can i implement this functionality in magento. Is there any extension for that?
Take a look at /app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
public function pdfinvoicesAction(){
$orderIds = $this->getRequest()->getPost('order_ids');
$flag = false;
if (!empty($orderIds)) {
foreach ($orderIds as $orderId) {
$invoices = Mage::getResourceModel('sales/order_invoice_collection')
->setOrderFilter($orderId)
->load();
if ($invoices->getSize() > 0) {
$flag = true;
if (!isset($pdf)){
$pdf = Mage::getModel('sales/order_pdf_invoice')->getPdf($invoices);
} else {
$pages = Mage::getModel('sales/order_pdf_invoice')->getPdf($invoices);
$pdf->pages = array_merge ($pdf->pages, $pages->pages);
}
}
}
if ($flag) {
return $this->_prepareDownloadResponse(
'invoice'.Mage::getSingleton('core/date')->date('Y-m-d_H-i-s').'.pdf', $pdf->render(),
'application/pdf'
);
} else {
$this->_getSession()->addError($this->__('There are no printable documents related to selected orders.'));
$this->_redirect('*/*/');
}
}
$this->_redirect('*/*/');
}
From the above function you could assign the first 300 order ids to $orderIds (or modify Mage::getResourceModel('sales/order_invoice_collection to get the first 300 records)
See magento orders list query
Changes :
public function pdfinvoicesAction(){
$orderIds = $this->getRequest()->getPost('order_ids');
To (something like)
public function pdfinvoices($orderIds){
$orderIds = (array) $orderIds; // first 300 record ids
Change line to save pdf to file
return $this->_prepareDownloadResponse(
'invoice'.Mage::getSingleton('core/date')->date('Y-m-d_H-i-s').'.pdf', $pdf->render(),
'application/pdf'
);
To
$pdf->render();
// use the order_id for the pdf name like
$pdf->save("{$orderId}.pdf");
see Error in generated pdf file using zend_pdf under Magento
You could also delete the $this->_redirect('//')

Need Help with Zend Form dropdown menu validation

I'm working on a zend framework project and I needed the user to select school and then it goes to the next form then select the grade.
Eg User select ABC High School and then select "Grade 8"
Both School and Grade dropdown menu is soft coded fetching the data from the database.
My problem is that when the user selected a school and then on the next grade form if they don't select any values and click onto "submit" it return a validation error "Value is required and can't be empty" which is correct but the dropdown menu then goes empty.
I wanted to know how to repopulate the values back to the grade dropdown menu if the form doesn't validate.
Thanks so much
Here is my code
Here is the function i generate the grade values (Fetching from the database)
public function processSchoolSelectionAction()
{
$form = $this->getSchoolSelectionForm();
if ($form->isValid($_POST))
{
// getting the values
$schoolId = $form->getValue('school');
$schoolYear = new Application_Model_DbTable_SchoolYear();
$schoolYearValues = $schoolYear->getYearValues($schoolId);
array_unshift($schoolYearValues, array ('key' =>'' , 'value' =>'Please Specify'));
$form = $this->getYearSelectionForm();
$form->year->addMultiOptions($schoolYearValues);
$form->schoolId->setValue($schoolId);
$this->view->form = $form;
}
else
{
$data = $form->getValues();
$form->populate($data);
$this->view->form = $form;
}
}
Code processing the year selection form
public function processYearSelectionAction()
{
$form = $this->getYearSelectionForm();
if ($form->isValid($_POST))
{
// getting the values
$schoolId = $form->getValue('schoolId');
$yearId = $form->getValue('year');
$textbookList = new Application_Model_DbTable_TextbookList();
if ($textbookList->checkTextbookExist($schoolId, $yearId))
{ // check if textbookExist
}
else
{
$this->view->message = "Sorry, But the list you requested is currently not available for ordering online.";
}
}
else
{
$data = $form->getValues();
$form->populate($data);
$this->view->form = $form;
}
}
School selection form
<?php
class Application_Form_SchoolSelection extends ZendX_JQuery_Form
{
public function init()
{
$this->setName('schoolSelection');
$school = new Application_Model_DbTable_School;
$schoolValues = $school->getSchoolValues();
array_unshift($schoolValues, array ('key' =>'' , 'value' =>'Please Specify'));
$schoolElement = new Zend_Form_Element_Select('school');
$schoolElement->addMultiOptions($schoolValues);
$schoolElement->setLabel('School');
$schoolElement->setRequired(true);
$schoolElement->setRegisterInArrayValidator(false);
$submitElement = new Zend_Form_Element_Submit('submit');
$submitElement->setLabel("Next");
$this->addElements(array(
$schoolElement,
$submitElement
));
}
}
?>
Grade (Year) selection form
<?php
class Application_Form_YearSelection extends ZendX_JQuery_Form
{
public function init()
{
$this->setName('yearSelection');
$yearElement = new Zend_Form_Element_Select('year');
$yearElement->setLabel('Year');
$yearElement->setRequired(true);
$yearElement->setRegisterInArrayValidator(false);
$schoolIdElement = new Zend_Form_Element_Hidden('schoolId');
$submitElement = new Zend_Form_Element_Submit('submit');
$submitElement->setLabel("Next");
$this->addElements(array(
$yearElement,
$schoolIdElement,
$submitElement
));
}
}
?>
This is how I done that:
In Controller when form is creating, pass data from request:
$some_selected_data = $this->_getParam('param_from_request'); // you need to validate this
$form = new Application_Form_SchoolSelection( array('some_data' => $some_selected_data) );
Then, in Form Class get that value like this:
$data = $this->getAttrib('some_data'); // the key value of array above
and just ask
if($data) {
// get value from DB and
//SET VALUE TO Zend_Form_Element
}
Obviously, you need to repopulate the options of your Select field.
In your processYearSelectionAction, on the validation failure part just grab the schoolId you stored in the hidden field and use it the same way as you did in your processSchoolSelectionAction to populate your field options.

Symfony: exclude empty values from form save

I have a many to many relation between Product and Properties. I'm using embedRelation() in my Product form to edit a Product and it's Properties. Properties includes images which causes my issue. Every time I save the form the updated_at column is updated for file properties even when no file is uploaded.
Therefore, I want to exclude empty properties when saving my form.
I'm using Symfony 1.4 and Doctrine 1.2.
I'm thinking something like this in my ProductForm.class.php, but I need some input on how to make this work.
Thanks
class ProductForm extends BaseProductForm
{
public function configure()
{
unset($this['created_at'], $this['updated_at'], $this['id'], $this['slug']);
$this->embedRelation('ProductProperties');
}
public function saveEmbeddedForms($con = null, $forms = null)
{
if (null === $forms)
{
$properties = $this->getValue('ProductProperties');
$forms = $this->embeddedForms;
foreach($properties as $p)
{
// If property value is empty, unset from $forms['ProductProperties']
}
}
}
}
I ended up avoiding Symfony's forms and saving models instead of saving forms. It can be easier when playing with embedded forms. http://arialdomartini.wordpress.com/2011/04/01/how-to-kill-symfony%E2%80%99s-forms-and-live-well/
Solved it by checking if posted value is a file, and if both filename and value_delete is null I unset from the array. It might not be best practice, but it works for now.
Solution based on http://www.symfony-project.org/more-with-symfony/1_4/en/06-Advanced-Forms
class ProductPropertyValidatorSchema extends sfValidatorSchema
{
protected function configure($options = array(), $messages = array())
{
// N0thing to configure
}
protected function doClean($values)
{
$errorSchema = new sfValidatorErrorSchema($this);
foreach($values as $key => $value)
{
$errorSchemaLocal = new sfValidatorErrorSchema($this);
if(array_key_exists('value_delete', $values))
{
if(!$value && !$values['value_delete'])
{
unset($values[$key]);
}
}
// Some error for this embedded-form
if (count($errorSchemaLocal))
{
$errorSchema->addError($errorSchemaLocal, (string) $key);
}
}
// Throws the error for the main form
if (count($errorSchema))
{
throw new sfValidatorErrorSchema($this, $errorSchema);
}
return $values;
}
}