Get shipping address county in Magento 2 observer - magento

Hi I have a custom module . I want to get shipping country inside
public function execute(\Magento\Framework\Event\Observer $observer)
{
Please let me know how can i get this this ?
I have seen this code for postcode , but i am not sure his is working or not
$postCode = $this->_checkoutSession->getQuote()-getShippingAddress()->getPostcode();
I need shipping address country name in public function execute. Please help .

declare a public variable and intialize the variable like below ,then you will be able to use it in your execute method
class Example {
public $_checkOutSession;
public function __construct(\Magento\Customer\Model\Session $checkOUtSession)
{
$this->_checkOutSession = $checkOutSession;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$postCode = $this->_checkoutSession->getQuote()->getShippingAddress()->getPostcode();
}
}

It depends on which observer do you want to get it. Can you provide a more specific scenario?
In which checkout session currently has a quote. You can use the above solution from Reggie.
Or else you need to initialize quote/order to get it.

Related

Argument 1 passed to Spatie\Activitylog\ActivityLogger::performedOn() must be an instance of Illuminate\Database\Eloquent\Model, string given

I am using Spatie activity log package.
Within my controller, I am trying to pass the model name but I get the on my question's title.
See my Model below:
class Project extends Model
{
//
use SoftDeletes;
protected $softDelete = true;
protected static $logAttibutes = ['projectname','duedate','team_id','assignee_id',
,'projecttype_id'];
public static $logName = 'project';
public function getDescriptionForEvent(string $eventName): string
{
return "You have {$eventName} project" ;
}
The event logging for viewing a list happens in the controller. As shown below:
public function index()
{
//
$projects = Project::all();
activity()
->useLog('Projects')
->withProperties(['type'=>'view project list'])
->performedOn(Project::class)
->log('viewed the project list');
return view('projects.index',['projects'=>$projects]);
}
On performedOn, I also tried:
->performedOn('App/Project')
The documentation says
->performedOn($someContentModel)
This is just a variable and I know a variable needs to be populated with some data, but I think I'm struggling to understand the format of that data
Can you try this :
$project = new Project();
--
$activity()
->performedOn($project)
That means use the object of project as argument which we can also call, the instance of model.

Returning same variable to every controller in laravel

I need to send the same result to almost every view page, so I need to bind the variables and return with every controller.
My sample code
public function index()
{
$drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
$locations = Location::get();
return view('visitor.index', compact('drcategory','locations'));
}
public function contact()
{
$drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
$locations = Location::get();
return view('visitor.contact', compact('drcategory','locations'));
}
But as you see, I need to write same code over and over again. How can I write it once and include it any function whenever I need?
I thought about using a constructor, but I cannot figure out how I can implement this.
You are able to achieve this by using the View::share() function within the AppServicerProvider:
App\Providers\AppServiceProvider.php:
public function __construct()
{
use View::Share('variableName', $variableValue );
}
Then, within your controller, you call your view as normal:
public function myTestAction()
{
return view('view.name.here');
}
Now you can call your variable within the view:
<p>{{ variableName }}</p>
You can read more in the docs.
There are a few ways to implement this.
You can go with a service, a provider or, like you said, within the constructor.
I am guessing you will share this between more parts of your code, not just this controller and for such, I would do a service with static calls if the code is that short and focused.
If you are absolutely sure it is only a special case for this controller then you can do:
class YourController
{
protected $drcategory;
public function __construct()
{
$this->drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
}
// Your other functions here
}
In the end, I would still put your query under a Service or Provider and pass that to the controller instead of having it directly there. Maybe something extra to explore? :)
For this, you can use View Composer Binding feature of laravel
add this is in boot function of AppServiceProvider
View::composer('*', function ($view) {
$view->with('drcategory', DoctorCategory::orderBy('speciality', 'asc')->get());
$view->with('locations', Location::get());
}); //please import class...
when you visit on every page you can access drcategory and location object every time
and no need to send drcategory and location form every controller to view.
Edit your controller method
public function index()
{
return view('visitor.index');
}
#Sunil mentioned way View Composer Binding is the best way to achieve this.

Magento $this->__('Create an Account')

In Magento $this->__('Create an Account') How this echo Create an Account?
abstract class Mage_Core_Helper_Abstract{ public function __()
{
$args = func_get_args();
$expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getModuleName());
array_unshift($args, $expr);
return Mage::app()->getTranslator()->translate($args);
}
I saw that __ function in Mage_Core_Helper_Abstract Class.but i cant understand Mage::app()->getTranslator()->translate($args) what's happending in that getTranslator function.
public function getTranslator()
{
if (!$this->_translator) {
$this->_translator = Mage::getSingleton('core/translate');
}
return $this->_translator;
}
Mage::getSingleton('core/translate') what's happening there ? and why in this function call like core/translate which file its denote and how it Create an Account text?
You might search how the magento translator works
What ever text is written in $this->_('') will dynamically translated to the current locale which is loaded in your current store(That text must be specified in magento-root/app/locale//.csv)
I think the below answer might be helpfull
How does Magento translate works?

Unable to call custom methods within extended Magento model

I'm attempting to customize the way pricing / tiered pricing is displayed in Magento CE 1.6.0.0.
I've followed the instructions in the second post of the link below to override Mage_Catalog_Model_Product_Type_Price
http://www.magentocommerce.com/boards/viewthread/16829/
Following is my custom model class:
class PHC_Price_Model_Price extends Mage_Catalog_Model_Product_Type_Price {
public function getPrice() {
echo "overridden getPrice method called<br>";
}
public function getPHCDisplayPrice($product) {
echo "custom price function called<br>";
}
}
I'm able to successfully call the overridden getPrice() function from my template file as follows:
$product = Mage::getModel("catalog/product")->load($_product->entity_id);
$displayPrice = $product->getPrice();
However, when I try to call my custom price function with
$product = Mage::getModel("catalog/product")->load($_product->entity_id);
$displayPrice = $product->getPHCDisplayPrice();
I get absolutely nothing. Can anyone tell me what I'm missing?
It't normal that you don't get a result. I would be amazed if this worked.
You are overriding the class Mage_Catalog_Model_Product_Type_Price, but in your example the $product variable is an instance of Mage_Catalog_Model_Product. That class does not have the method getPHCDisplayPrice and it calls the __call method and returns null.
You get the expected result when calling getPrice by accident. It is because the getPrice method in Mage_Catalog_Model_Product looks like this:
public function getPrice()
{
if ($this->_calculatePrice || !$this->getData('price')) {
return $this->getPriceModel()->getPrice($this);
} else {
return $this->getData('price');
}
}
So when you call it, it calls $this->getPriceModel()->getPrice($this) and $this->getPriceModel() returns an instance of your class.

Accessing model through Varien_Event_Observer

I have a custom observer in Magento 1.6.2.0 that is called when a CMS page is saved or deleted (events cms_page_delete_before/cms_page_save_before). I have verified (using Mage::log()) that the observer is working, however when I try the following:
public function getCmsUrl(Varien_Event_Observer $observer)
{
$url = $observer->getEvent()->getPage()->getIdentifier();
return $url;
}
I get nothing returned (rather than "about-us" or "enable-cookies" or whatever URL path the CMS page has). The following code, however, works perfectly fine:
public function getProductUrl(Varien_Event_Observer $observer)
{
$baseUrl = $observer->getEvent()->getProduct()->getBaseUrl();
return $baseUrl;
}
Can someone let me know what the correct way of accessing a CMS page is when passed via an observer?
Thanks in advance for any help/tips/pointers :-)
The events cms_page_delete_before and cms_page_save_before are fired in Mage_Core_Model_Abstract. This it how it looks like in the beforeSave function:
Mage::dispatchEvent($this->_eventPrefix.'_save_before', $this->_getEventData());
As you can see, it uses a variable _eventPrefix to construct the event key. In the CMS page model, this is set to cms_page.
Also notice the part $this->_getEventData(). This is how the model, in this case the CMS page, is passed to the observer:
protected function _getEventData()
{
return array(
'data_object' => $this,
$this->_eventObject => $this,
);
}
As you can see, the object has two names, data_object and a name defined in a variable, _eventObject. In the product model, the name is set to product, but in the CMS page model, the variable is missing. Apparently the Magento team forgot to put this in, and as a result, the default name from the core model is used:
protected $_eventObject = 'object';
That means you can get the CMS page in your observer by using getObject:
public function myObserver(Varien_Event_Observer $observer)
{
$page = $observer->getEvent()->getObject();
}

Resources