Magento Observer - Getting Newsletter Subscribtion from Order Object - magento

What can I call from an $observer object to determine if the guest or customer clicked the subscribe checkbox on checkout? So far I have this:
public function collectCustomerData($observer)
{
$this->observer = $observer;
$this->_order = $this->observer->getEvent()->getOrder();
$this->_address = $this->_order->getShippingAddress();
$this->data['first_name'] = $this->_address->getFirstname();
$this->data['last_name'] = $this->_address->getLastname();
$this->data['city'] = $this->_address->getCity();
$this->data['email'] = $this->_order->getCustomerEmail();
}
but I need to add $this->data['is_newsletter'] from either $this->_order(Mage_Sales_Model_Order) or $this->_address(Mage_Sales_Model_Order_Address), or pull in another model that has that information through static factory methods such as Mage::getModel() if I need to

I figured it out, I had to bring the newsletter/subscriber model into the equation. The following code returned either 1 or null:
$email = $this->_order->getCustomerEmail();
$isNewsletter = Mage::getModel('newsletter/subscriber')
->loadByEmail($email)
->getSubscriberStatus();
Based on that I was able to set the opt in flag appropriately:
$this->data['is_newsletter'] = $isNewsletter;

Related

Laravel model is updating multiple models instead of single

I am trying to update my model using multiple where conditions.
my code is
public function UpdateEducationData(Request $request)
{
$user = app('user');
// return $request;
$education = eduinfo::where("id", $user->id)->where("exam", $request->type)->first();
// dump sql query for debugging
// $education->rawSql();
// dd($education);
$education->board = $request->board;
// $education->degree = $request->degree;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
// update education based on exam
$education->save();
return redirect()->back()->with("message", "Education Information Updated Successfully");
return "Update Education Data";
}
My code is updating a eduinfo table based on id and exam. But whenever this function is called it updates all eduinfo records related to that user id.
I tried to update eduinfo table single record but multiple records are being update at once. I dumped eduinfo after retriving the model and yes it's retrieving the single model using first() method but still when save() is called it updates all records of that user id in eduinfo.
I think Your conditions to make a unique record are not.
But if you wanna Just run one time! I have an offer to you.
$flag=true;
if($flag){
$user = \Auth::user();
$education = eduinfo::where('id','=', $user->id)->where('exam','=', $request->type)->first();
$education->board = $request->board;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
$education->save();
$flag=false;
}
It's depends on my answer.

Laravel easier way to save multiple input fields to database

I am trying to save a long form data to database. Till now i am getting the form value from request object and setting it to database model.
This works perfectly fine. But I want to know if there is another way to initialise the model efficiently without need to set each value. My model has one to one relation.
I have been doing like this. But i don't think this is the right way to do
//Student details
$studentDetail->student_first_name = $request->input('studentFirstName');
$studentDetail->student_last_name = $request->input('studentLastName');
$studentDetail->student_phone_number = $request->input('studentPhoneNumber');
$studentDetail->student_date_of_birth = $request->input('studentDOB');
$studentDetail->student_email = $request->input('studentEmail');
$studentDetail->save();
$studentAddress = new Address();
$studentAddress->address_1 = $request->input('studentAddress1');
$studentAddress->address_2 = $request->input('studentAddress2');
$studentAddress->city = $request->input('studentCity');
$studentAddress->state = $request->input('studentState');
$studentAddress->country = $request->input('studentCountry');
$studentAddress->post_code = $request->input('studentPostCode');
$studentDetail->addresses()->save($studentAddress);
$visaDetails = new Visa();
$visaDetails->passport_number = $request->input("visaPassportNumber");
$visaDetails->visa_number = $request->input("visaVisaNumber");
$visaDetails->visa_class = $request->input("visaVisaClass");
$visaDetails->visa_grant_date = $request->input("visaVisaGrantDate");
$visaDetails->visa_expiry_date = $request->input("visaVisaExpiryDate");
$studentDetail->visaDetails()->save($visaDetails);
//
$instituteDetails = new Institute();
$instituteDetails->institute_name = $request->input("instituteName");
$instituteDetails->institute_location = $request->input("instituteLocation");
$instituteDetails->institute_phone1 = $request->input("institutePhone1");
$instituteDetails->institute_phone2 = $request->input("institutePhone2");
$instituteDetails->institute_email = $request->input("instituteEmail");
// dd($instituteDetails->courses);
$courseDetails = new Course();
$courseDetails->course_level = $request->input("courseLevel");
$courseDetails->course_name = $request->input("courseName");
$courseDetails->course_fee = $request->input("courseFee");
$courseDetails->course_concession_fee = $request->input("courseConcessionFee");
$courseDetails->course_duration = $request->input("courseDuration");
$courseDetails->course_commencement_date = $request->input("courseCommencementDate");
$studentDetail->instituteDetails()->save($instituteDetails);
$instituteDetails->courses()->save($courseDetails);
Any idea on making this process faster??
Simply set create your models using mass assignment, so:
So in your model StudentDetail:
class StudentDetail{
protected $fillable = [
'student_first_name',
'student_last_name',
'student_phone_number',
'student_date_of_birth',
'student_email',
];
//...
//... rest of your model
}
Then tweak your HTML inputs to have in their names the user array like so for example:
<input type="text" id="foo" name="student[student_first_name]">
<input type="text" id="foo" name="student[student_last_name]">
.....
Tip: for validation, you have to treat it with dot notation, so your rule could be:
'student.student_first_name' => 'required|humanName|string|max:255',
Now simply do the following in your controller:
$studentDetail = StudentDetail::create($request->input('student'));
Now you made do the same for your address and other models.
The GIST: After mass assignment enabled for your models you could end up having ONLY the following couple lines of code doing it all for you and it's way more fun and full of dynamism ;) IMHO!
$relatedModels = ['Address', 'Visa', 'Institute', 'Course'];
foreach ($relatedModels as $relatedModel) {
$relatedModelClass = 'App\\'.$relatedModel; //adjust the namespace of your models here.
$ormRelatedModel = $relatedModelClass::create(strtolower($request->input($relatedModel)));
$studentDetail->{strtolower(str_plural($relatedModel)) . 'Details'}()->save($ormRelatedModel);
}
please note that in this case your relations names should be changed a bit like addresses function within your StudentDetail class/model should be changed to addressesDetails or just remove the .'Details' from my sample code above and remove it from your other relations names, i.e: change instituteDetails() to institute(). and make the relation names plural please!
I just tested it and it's working,
Cheers!

Get post data from CustomField in django rest framework

To make it short:
I have a serializer (django rest framework) that has two custom fields which do not directly correspond to a field of my model and also have a different name. The to_internal_value() method (probably) works, but I don't know how to access the post data of these fields.
And in case you need more details on my case:
I have a django model that looks like this:
class Requirement(models.Model):
job = models.ForeignKey('Job', related_name = 'requirements')
description = models.CharField(max_length = 140)
is_must_have = models.BooleanField() # otherwise is of type b
class Job(models.Model):
...
I want to serialize it in a manner that a job object will look like this:
{ "must_have": [must have requirements], "nice:to_have": [nice to have requirements] }
Therefore, I have custom fields in my serializer for jobs:
class JobSerializer(serializers.Serializer):
nice_to_have = NiceToHaveField(source = 'requirements', allow_null = True)
must_have = MustHaveField(source = 'requirements', allow_null = True)
The NiceToHaveField and the MustHaveField classes simpy override the to_representation() and the to_internal_value() methods, the to_representation also sorts the requirements after type.
But the validated_data in JobSerializer.create never contain these cutom fields. I know the to_internal_value gets called and does its work, but the results are not accessable.
What is the way to solve this?
I found a solution I don't like, there is probably a better way to do this. Anyways, the data is available in the view.request.data. So I used the perform_create hook like this:
def perform_create(self, serializer):
nice_to_have = None
must_have = None
if 'nice_to_have' in self.request.data and self.request.data['nice_to_have'] != None:
field = NiceToHaveField()
nice_to_have = field.to_internal_value(self.request.data['nice_to_have'])
if 'must_have' in self.request.data and self.request.data['must_have'] != None:
field = MustHaveField()
must_have = field.to_internal_value(self.request.data['must_have'])
serializer.save(owner = self.request.user, nice_to_have = nice_to_have, must_have = must_have)

Update Message (CrmService) Dynamics 4.0

I want to update the fields like "cs_hv_additionnalparticularities", "cs_hv_smscope" and so on, but the function srv.Update(de);updates all the form records, I mean it triggers a workflow that I don't want it to happen.
here is my code:
// Retrieve the DynamicEntity that goes with target
RetrieveRequest retrieve = new RetrieveRequest();
retrieve.Target = target;
retrieve.ColumnSet = new AllColumns();
retrieve.ReturnDynamicEntities = true;
// Create a response reference and execute the retrieve request.
RetrieveResponse response1 = (RetrieveResponse)srv.Execute(retrieve);
DynamicEntity de = (DynamicEntity)response1.BusinessEntity;
if (opp.Properties.Contains("cs_hv_additionnalparticularities"))
de["cs_hv_additionnalparticularities"] = opp["cs_hv_additionnalparticularities"];
if (opp.Properties.Contains("cs_hv_smscope"))
de["cs_hv_smscope"] = opp["cs_hv_smscope"];
if (opp.Properties.Contains("cs_hv_ugscope"))
de["cs_hv_ugscope"] = opp["cs_hv_ugscope"];
if (opp.Properties.Contains("cs_hv_acdc"))
de["cs_hv_acdc"] = opp["cs_hv_acdc"];
if (opp.Properties.Contains("cs_hv_smmv"))
de["cs_hv_smmv"] = opp["cs_hv_smmv"];
if (opp.Properties.Contains("cs_hv_smhv"))
de["cs_hv_smhv"] = opp["cs_hv_smhv"];
if (opp.Properties.Contains("cs_hv_ughv"))
de["cs_hv_ughv"] = opp["cs_hv_ughv"];
if (opp.Properties.Contains("cs_hvid"))
de["cs_hvid"] = opp["cs_hvid"];
de["cs_generercable"] = new CrmBoolean(true);
srv.Update(de);
I don't want to use this function srv.Update(de); to update the fields.
Can somebody please give me the update function code that can do this work ??
If you don't want to update additional columns, just retrieve the specific columns (property ColumnSet) instead of the new AllColumns().
You can use only the update the record with the Update method, make sure that your workflow triggers only for the requested fields, and not for additional fields.

Web API parameter filtering

This must be simple and I'm being incredibly dense but I can't find an example to help me figure it out. I want to filter my list of tblAsset items by their assessmentId which is passed in through a parameter. I'm able to get the parameter value ok, but I'm not sure how to write the query.
My model is built from an existing Database using the Model creation wizard.
Thanks for any help!
public IEnumerable<tblAsset> GettblAssets()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
var assessmentId = nvc["aid"];
//limit the assets by assessmentId somehow and return
}
You could use the .Where extension method on the IQueryable<tblAsset> instance returned by your database:
public IEnumerable<tblAsset> GettblAssets()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
var assessmentId = nvc["aid"];
// TODO: you might need to adjust the property names of your model accordingly
// Also if the assessmentId property is an integer on your model type
// you will need to parse the value you read from the request to an integer
// using the int.Parse method
return db.tblAsset.Where(a => a.assessmentId == assessmentId);
}

Resources