OctoberCMS - How to call a function inside a component - php

I am building an order form and I warn you in advance I am a noob with backend dev :)
So my first component takes all data from the order form and saves it to the database, then I use this same data to generate a quote. After this I have a thrird part which generates the invoice if the quote is accepted, so far my code looks like this:
// this runs when order is submitted on front end (runs from same component)
public function onAddOrder() {
$this->submitOrder();
$this->submitQuote();
Flash::success('Order successfully submitted!');
return Redirect::to('/home');
}
public function submitOrder() {
// Add it to the database
$order = new Order();
$order ->quote_no = $this->generateQuoteNo();
$order ->company_name = Input::get('company_name');
$order ->client_name = Input::get('client_name');
$order ->client_email = Input::get('client_email');
$order ->emergency_contact = Input::get('emergency_contact');
$order ->due_date = Input::get('due_date');
$order ->project_name = Input::get('project_name');
$order ->quote_query = Input::get('quote_query');
$order ->order_no = Input::get('order_no');
$order ->order_type = Input::get('order_type');
$order ->save();
}
}
public function submitQuote() {
$quote = new Quote();
$quote->quote_no = $this->generateQuoteNo();
$quote->customer = Input::get('company_name');
$quote->job_name = Input::get('project_name');
$quote->order_no = Input::get('order_no');
$quote->proof_price = $this->calculateProofPrice();
$quote->sub_total = $this->calculateSubTotal();
$quote->vat = $this->calculateVat();
$quote->total = $this->calculateTotal();
$quote->save();
}
This works fine but then I would like to run another function if a selection is made but this component is under a different class and I am not sure how to reference it.
if (Input::get('quote_query') === 'Order') {
$this->AcmeInvoice->onSubmitInvoice();
}
If someone could help me to fire the public function onSubmitInvoice() I will really appreciate it.

You can instantiate the object in the class & fire it off? eg: $invoice = new AcmeInvoice(); //add namespace if not in the name space; $invoice->onSubmitInvoice();
if (Input::get('query') === 'Invoice') {
$invoice = new AcmeInvoice();
$invoice->onSubmitInvoice('quote_no');
}

Related

How can I get the subscription back from a Recurly Purchase?

I am building a custom checkout with the Recurly PHP Client. Since we use our own gateway logic, we are forced to use the Create Purchase method, as opposed to Create Subscription (as Create Subscription doesn't accept gateway_code as a parameter). Create Subscription returns the created subscription - easy!
But Create Purchase returns an Invoice Collection. It's possible to tease this apart to find the newly-created $subscription object but this hardly seems like the intended process. Is there (hopefully) a cleaner way of going about it?
My method for purchasing is as follows - see code comments.
protected static function create_subscription( $user_id, $args ) {
$result = false;
$purchase = new Recurly_Purchase();
$purchase->currency = $args['currency'];
$purchase->collection_method = 'automatic';
$purchase->gateway_code = $args['gateway_code'];
$account = new Recurly_Account( $user_id );
$account->email = $args['email'];
$account->first_name = $args['billing_first_name'];
$account->last_name = $args['billing_last_name'];
$account->vat_number = $args['vat_number'];
$billing_info = new Recurly_BillingInfo();
$billing_info->token_id = $args['recurly_token'];
$account->billing_info = $billing_info;
$purchase->account = $account;
$subscription = new Recurly_Subscription();
$subscription->plan_code = $args['plan_code'];
$purchase->subscriptions = array( $subscription );
try {
// "invoice" is the method to transact a Recurly_Purchase.
$purchase = Recurly_Purchase::invoice( $purchase );
if( $purchase instanceof Recurly_InvoiceCollection ) {
// this seems incredibly janky and error-prone
$result = reset( $purchase->charge_invoice->line_items )->subscription->get();
}
} catch ( Exception $e ) {
$result = $e;
}
// I need this to return the $subscription object generated by the purchase
return $result;
}
When you create a subscription, a successful response will include the UUID for that subscription. I am not a PHP developer but it might look something like this:
$subscription = new Recurly_Subscription();
$subscription->plan_code = $args['plan_code'];
$subscription->account = $account;
$subscription->currency = $args['currency'];
$subscription->create();
$uuid = isset($subscription->uuid);
$result = Recurly_Subscription::get($uuid);
return $result;
Also, please note that as of Recurly API version 2.17+ you can now pass gateway_code as a body param to create subscription AND create purchase as you initially hoped to do. Here is a link to the Recurly API Release notes, which indicates when the change was made.

Variable usable in Service

I am a beginner in php. I have a WadoService service and a StudiesRestController controller. I want to use controller data in the service.
public function getPatientAction(Request $request, $studyUID)
{
$studyRepository = new StudyRepository(
$this->get('nexus_db'),
$this->get('logger'),
$this->get('translator')
);
$study = $studyRepository->getStudy($studyUID);
if (!$study) {
throw new NotFoundHttpException("No study found with studyuid $studyUID");
}
$patientInfo = new RestResponse(
SerializerBuilder::create()
->build()
->serialize($study->getPatient(), 'json')
);
return $patientInfo;
}
Is this possible? I have tried to put this in the function getPatientAction()without result:
/* #var $wadoService WadoService */
$wadoService = $this->container->get(WadoService::SERVICE_NAME);
$wadoService = new RestResponse(
SerializerBuilder::create()
->build()
->serialize($study->getPatient(), 'json')
);
To pass a variable from your controller to your service, you do it it like that :
$wadoService = $this->container->get(WadoService::SERVICE_NAME)->yourServiceMethod($yourVari);

Magento get quote id from observer

I'm trying to create order from admin (for telephonic order). In that I've a situation that I need to get quote id from observer. I tried below observer(s)
sales_quote_save_after
sales_model_service_quote_submit_success
sales_quote_product_add_after
I tried to get id using this,
$id = $observer->getQuoteId();
And
I tried to print that quote items but I'm getting empty values.
Can any one help me to sort this out ?
In the event sales_quote_product_add_after the quote_item is passed to the Observer.
To get the quote from this Observer and the id:
public function yourMethod($observer)
{
$quoteItem = $observer->getEvent()->getQuoteItem();
$quote = $quoteItem->getQuote();
$id = $quote->getId();
}
In the event sales_model_service_quote_submit_success you have passed the order and the quote
public function yourMethod($observer)
{
$order= $observer->getEvent()->getOrder();
$quote= $observer->getEvent()->getQuote();
$id = $quote->getId();
}
In the event sales_quote_save_after you have passed quote since in app/code/core/Mage/Sales/Model/Quote.php
protected $_eventObject = 'quote';
Then in your observer you can get it:
public function yourMethod($observer)
{
$quote= $observer->getEvent()->getQuote();
$id = $quote->getId();
}
I fixed this using below solution,
I used below event
sales_quote_item_set_product
Actually I tried to set price for configurable product corresponding associated product's price. And my observer is,
$event = $observer->getEvent();
$quote_item = $event->getQuoteItem();
$storeId = $quote_item->getStoreId();
if(Mage::app()->getStore()->isAdmin()) {
$item = $observer->getQuoteItem();
$product = $observer->getProduct();
$sku = $product->getSku();
$productDetails = Mage::getModel('catalog/product')
->setStoreId($storeId)
->loadByAttribute('sku',$sku);
$price = $productDetails->getPrice();
$sprice = $productDetails->getFinalPrice();
$item->setOriginalCustomPrice($sprice);
$item->setOriginalPrice($price);
}
$quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();

How to submit data to multiple tables in the same form

I have 2 tables: listings and listings_specifications
Listings table
id
type
status
location
specifications_id
Listings_specifications table
id
listing_id
swimming_pool
water_well
I need to select the specifications (checkboxes) on the same form with which I add a listing. I have created all the forms, views, models, controllers but I think I got some logic wrong.
Listing.php model
protected $table = 'listings';
public function contact()
{
return $this->BelongsTo('contacts');
}
public function specifications()
{
return $this->BelongsTo('listings_specifications');
}
Specification.php model
protected $table = 'listings_specifications';
public function listings()
{
return $this->BelongsTo('listings');
}
ListingsController.php (where the data gets saved in the database)
$listing = new Listing;
$contact = new Contact;
$listing->status = Input::get('status');
$listing->listingfor = Input::get('listingfor');
$listing->propertystatus = Input::get('propertystatus');
$listing->propertytype = Input::get('propertytype');
$listing->userid = Auth::user()->id;
$listing->location = Input::get('location');
$listing->contact_id = $contact_id;
$listing->save();
$specifications = Specification::find($id);
if( $listings->save() ) {
$specifications = new Specification;
$specifications->listing_id = $id;
$specifications->swimming_pool = Input::get('swimming_pool');
$specifications->water_front = Input::get('water_front');
$specifications->save();
}
I'm getting this error: Undefined variable: id
Where did I go wrong?
Thank you
It looks like you have some logic errors.
First of all, you are never setting $id anywhere, but that's okay because you really don't need it.
Remove the $specifications = Specification::find($id); line because that's not doing anything.
Then change your last section to something like this...
if( $listings->save() ) {
$specifications = new Specification;
$specifications->swimming_pool = Input::get('swimming_pool');
$specifications->water_front = Input::get('water_front');
$listing->specifications()->save($specifications);
}
$listing->specifications()->save($specifications); will automatically save the new specification with the correct listing_id for you.
Modify your Listing model's specifications relationship to...
public function specifications()
{
return $this->hasMany('Specification');
}
I'm assuming here one listing can have many specifications. If not, you can easily just change that to a hasOne.
You use $id in the line $specifications = Specification::find($id); but you don't define it before.

php passing object of an object: reference or value?

Hi all I'm using zend framework (but I think this is irrelevant) and php5 and I just want to modify an object of an object
public function saveSite($post) {
$form = new Diff_Form_Download();
$subform = new Diff_Form_DownloadSubform();
$form = $this->view->form;
$newSite = 0;
$sitesRecord = new Diff_Model_Sites();
$debugString = null;
if (is_array($post)) {
$subform = $this->getSubformByPost($post);
$debugString = $subform->getContent();
echo $debugString;
//new site instertion
if (is_null($subform)) {
$subform = $form->getSubForm('NewSite');
$newSite = 1;
}
$values = reset($subform->getValues());
$sitesRecord = Doctrine_Core::getTable('Diff_Model_Sites')->findOneBy('idSite', $values['idSite']);
if ($sitesRecord) {
$sitesRecord->idSite = $values['idSite']; //useless but necessary to make Doctrine understand to use update?
} else { //if the record is not present instantiate a new object (otherwise save() will not work
$sitesRecord = new Diff_Model_Sites();
}
$sitesRecord->content = $subform->getContent(); //$values['content'];
$sitesRecord->newHtml = $subform->getContent();
$sitesRecord->url = $values['url'];
$sitesRecord->shortName = $values['shortName'];
$sitesRecord->lastChanged = date("Y-m-d H:i:s");
$sitesRecord->pollingHours = $values['pollingHours'];
$sitesRecord->minLengthChange = $values['minLenghtChange'];
if (Zend_Auth::getInstance()->hasIdentity()) { //save the owner
$sitesRecord->idOwner = Zend_Auth::getInstance()->getIdentity()->idOwner; //retrieve the owner
$sitesRecord->save();
} else {
throw new Exception("your session have expired: \n please login again");
}
}
}
/**
* return the calling subform
* #param type $post
* #return type
*/
public function getSubformByPost($post) {
$form = new Diff_Form_Download();
$form = $this->view->form;
$subform = new Diff_Form_DownloadSubform();
$subformName = "site" . $post['idSite'];
$subform = $form->getSubForm($subformName);
return $subform;
}
public function refreshOneDiff($post) {
$debugString;
if (is_array($post)) {
$form = new Diff_Form_Download();
$form = $this->view->form;
$subform = new Diff_Form_DownloadSubform();
$subform = $this->getSubformByPost($post);
if (!$subform)
$subform = $this->view->form->getSubformByPost('NewSite');
$url = $subform->getUrl();
$idSite = $subform->getIdSite();
$crawler = new Crawler();
$newpageContent = $crawler->get_web_page($url);
$siteRecord = new Diff_Model_Sites();
$siteRecord = $subform->getSiteRecord();
if ($siteRecord) //check if the record is not null
$oldpageContent = $siteRecord->get('content');
else
$oldpageContent = null;
$differences = $this->getDiff($oldpageContent, $newpageContent);
if (!is_null($differences)) {
$siteRecord->content = $newpageContent;
$subform->setContent($newpageContent);
$subform->setContentDiff($differences);
$subform->setSiteRecord($siteRecord);
$subform = $this->getSubformByPost($post);
$debugString = $subform->getContent();
}
//echo $debugString;
$sitePresence = Doctrine_Core::getTable('Diff_Model_Sites')->findOneBy('idSite', $idSite);
if ($sitePresence) {
//$this->saveSite($post);
$this->debugtry($post);
}
} else {
}
}
Basically what I'm doing here is:
1) grab a the form from the view
2) grab a subform from the form (let's call it SubformX)
3) grab an object "siteRecordX" from SubformX
4) change a value of "siteRecordX"
5) call a function saveRecord()
6) In this function regrab the same SubformX and echoing the value of the object siteRecordX
Surprisingly if i change a variable of SubformX it will stay that way, if I change a variable of an object of SubformX it will remain unchanged (if I retrieve SubformX).
It looks like, even if SubformX is passed by reference it is not the same for it's subobjects, wich are passed by value and so they disappear changing the context of the function.
Can you please help me?
Thanks
EDIT
I still cannot solve this issue nor understand it:
This is the constructor of the subform:
public function __construct($site = null, $options = null) {
if ($site instanceof Diff_Model_Sites) {
$this->_shortName = $site->get('shortName');
$this->_url = $site->get('url');
$this->_content = $site->get('content');
$this->_idSite = $site->get('idSite');
$this->_siteRecord = $site;
$this->_lastChanged = $site->get('lastChanged');
}parent::__construct($options);}
while this is the function of SubformX i use to set the value.
public function setContent($contentText) {
$this->_siteRecord->content = $contentText;
$this->_content = $contentText;
}
and this is the function of the subform that I call to get the value
public function getContent() {
if (isset($this->_siteRecord)) {
//return $this->_content;
return $this->_siteRecord->content;
}
}
with the commented line I'm able to retrieve the updated value, not with the second.
This is a real mystery to me because i set and get them exactly the same way at exactly the same point and i cannot understand the difference.
Your _siteRecord property is an ORM object (Doctrine, it appears). So its data may have some behaviors that are not standard for a reference-type object. It surely has some override of __get and __set. It also employs caching. These things are necessary to keep the database-model interaction working properly, but they can confuse what should be a reference and value types. (See: http://www.codinghorror.com/blog/2006/06/object-relational-mapping-is-the-vietnam-of-computer-science.html)
P.S.: in your constructor you use:
$this->_content = $site->get('content');
$this->_siteRecord = $site;
but in your getContent() you use:
$this->_siteRecord->content;
That difference might be part of the problem.
Thank you all guys. It was Doctrine caching.
I have not investigated further the problem, but after getting rid of Doctrine everything works fine.
I have lost one entire day after this issue.
Moreover today I have lost another day for another curious problem related to Doctrine.
It seems that each time you gather data from your db Doctrine decode them for you (just like the php function utf8_decode($data).
Of course if you get the data and then put it back in the db again it will result in a total mayhem of coding and decoding.
This is enough. I still think that ORM are great programming tools but simply Doctrine is not.
I will not rest in peace since I'll have it eliminated from my program.
I will use Zend_Db library instead. Which I have mostly already done without regret and without facing the above-mentioned Doctrine's problems.
Again thanks to Seth Battin and Dave Random for the help and patience to understand my noob-coding.

Categories