How to get Response of REST API in JSON format by Default in Magento - magento

In magento as we use the REST url to access the data,as http://localhost/magemto/api/rest/products it returns in XML format.
But as my team requirement, I should send the data in JSON format to access AJAX calls easily.. I have used REST client to include a header as 'Content-Type:appilcation/json'.. Then it returns in JSON format.. But I want it as defaultly by the magento API..

Hey, I do have a solution for this, I would like to share with you.
First go to your magento root folder then go to following path
\app\code\core\Mage\Api2\Model\Request.php
Go to the method getAccepTypes() and change with this code below it will fulfill your requirement.
public function getAcceptTypes()
{
$qualityToTypes = array();
$orderedTypes = array();
foreach (preg_split('/,\s*/', $this->getHeader('Accept')) as $definition) {
$typeWithQ = explode(';', $definition);
$mimeType = trim(array_shift($typeWithQ));
// check MIME type validity
if (!preg_match('~^([0-9a-z*+\-]+)(?:/([0-9a-z*+\-\.]+))?$~i', $mimeType)) {
continue;
}
$quality = '1.0'; // default value for quality
if ($typeWithQ) {
$qAndValue = explode('=', $typeWithQ[0]);
if (2 == count($qAndValue)) {
$quality = $qAndValue[1];
}
}
$qualityToTypes[$quality][$mimeType] = true;
}
krsort($qualityToTypes);
foreach ($qualityToTypes as $typeList) {
$orderedTypes += $typeList;
}
unset($orderedTypes);
$orderedTypes=Array
("application/json" => 1);
return array_keys($orderedTypes);
}
Hope this help you.

Related

How to update only one property of model?

I'm working on user consents. In my request I have these properties:
$newsLetters (bool|nullable),
$sms (bool|nullable),
$billEmail (bool|nullable),
I need update only one. So I need to find one which is not null and update it, if in my request is more than one properties with bool values i need to throw exception.
How can I achieve this?
My request extends spatie/laravel-data.
I don't understand why would you handle something like this on the backend (you can use radio button for this and always send only one value), you can use validation for requests or something like this:
$newsLetters = null;
$sms = true;
$billEmail = null;
$values = [$newsLetters, $sms, $billEmail];
$filter = sizeof(array_filter($values, function($el) { return $el === null;})) < 2;
if($filter) {
//return exception or whatever
} else {
//update values
}

Confirm email in Magento using the Web-forms

I am using an extension in Magento called web-forms to create all the forms on my website. What I need to do is add the email verification fields (user must enter email twice. Both emails must match) How can I do this? I looked thru the extension but did not see a way to do it.
It looks like the web-forms is using prototype.js for validation.
I got it in case someone in the future has the same problem and in using the web-forms extension here is how you do it.
Assign css class thru the back end in magento->web-forms-(your form name)->the confirm email field(which you should create if you don't have it all ready)design tab->CSS classes for the Input element(put your class name here and remember it you are going to use it later)
Next open up in your root directory of the magento installation the validation.js file. Which is located in js/prototype/
Open the file and paste the code below after the validate-email
['[your class name]', 'Please make sure your emails match.', function(v)
{
var conf = $$('.[your class name]')[0];
var pass = false;
if ($('email')) {
pass = $('email');
}
var emailElements = $$('.validate-email');
for (var i = 0; i < emailElements.size(); i++) {
var emailElement = emailElements[i];
if (emailElement.up('form').id == conf.up('form').id) {
pass = emailElement;
}
}
if ($$('.[your class name]').size()) {
pass = $$('.validate-email')[0];
}
return (pass.value == conf.value);
}],
save it and upload it
Hope that helps somebody you has the same problem.
Above code is not working correctly following part is creating issue
if ($$('.[your class name]').size()) {
pass = $$('.validate-email')[0];
}
at my end following code is working
if ($$('.validate-admin-email').size()) {
pass = $$('.validate-admin-email')[0];
}
so the complete working code can be:
['validate-cemail', 'Please make sure your emails match.', function(v) {
var conf = $$('.validate-cemail')[0];
var pass = false;
if ($('email')) {
pass = $('email');
}
var emailElements = $$('.validate-email');
for (var i = 0; i < emailElements.size(); i++) {
var emailElement = emailElements[i];
if (emailElement.up('form').id == conf.up('form').id) {
pass = emailElement;
}
}
if ($$('.validate-admin-email').size()) {
pass = $$('.validate-admin-email')[0];
}
return (pass.value == conf.value);
}],
.validate-cemail is your defined class in template.
like:
<input type="text" name="email-confirm" id="email-confirm" class="input-text required-entry validate-cemail"/>

Uploading images with redactor to MVC

This might be a bit too specific for here and I may need to contact redactor support but i've seen other questions about redactor here so i figured i'd give it a shot ...
Ok ...
So i'm trying to get get image uploading to work following the example here ...
http://imperavi.com/redactor/docs/images/
My client side code ...
$("textarea").redactor({
focus: true,
imageUpload: '/MyController/UploadImage'
});
My MVC controller action looks like this ...
public JsonResult UploadImage(object image)
{
// Do something with whatever that was i got from redactor
var result = new { filelink = "" };
return Json(result);
}
The problem is ... what did redactor actually give me?
Was it the whole file? a chunk? i can't seem to tell because the object has no type information at all and the raw post information seems way too little to actually be a whole image file.
Has anyone had any experience with this / actually done it before?
I don't really want to setup php on my server for this 1 function.
EDIT:
Ok a bit more digging reveals that if i pull the underlying Request object it has a files property which apparently contains my posted image file.
I think i might be able to figure it out from here.
Where I get a code block in place i'll post it as an answer.
You are receiving a HttpPostedFileBase object. Here is my implementation:
jQuery:
$('#blog-post').redactor(
{
imageUpload: '/blog/images/',
imageGetJson: '/images/locations/blogs/'
});
Then in the controller:
public ActionResult Images(HttpPostedFileBase file)
{
// Verify that the user selected a file
if( file != null && file.ContentLength > 0 )
{
// extract only the fielname
var fileName = Path.GetFileName( file.FileName );
// store the file
var path = Path.Combine( ImageLocation.BlogPicturePath, fileName );
file.SaveAs( path );
}
return Json( new { filelink = ImageLocation.BlogPictureUrl + "/" + file.FileName } );
}
ok um ... i think im there ...
This needs a bit of cleaning up and I don't expect you guys to understand what goes on under the bonnet of my custom DMS code but just assume it takes the stream and returns a FileInfo object and in theory this should work for you too ...
public ActionResult Upload()
{
// this object is specific to my system but all it does is
// stream the file to a path on the server (code not needed for this Q)
var dmsService = _kernel.Get<IDMSFileSystemService>();
List<FileInfo> savedFiles = new List<FileInfo>();
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
using (file.InputStream)
{
savedFiles.Add(dmsService.AddFromStream(file.InputStream, file.FileName);
}
}
var result = savedFiles.Select(f => new { filelink = f.Path}).ToArray();
return Json(result);
}
Suprisingly simple right ... :)

TYPO3 Extbase: How to render the pagetree from my model?

I want to create some kind of sitemap in extbase/fluid (based on the pagetree). I have loaded the pages table into a model:
config.tx_extbase.persistence.classes.Tx_MyExt_Domain_Model_Page.mapping.tableName = pages
I have created a controller and repository, but get stuck on the part wich can load the subpages as relation into my model.
For example:
$page = $this->pageRepository->findByPid($rootPid);
Returns my rootpage. But how can I extend my model that I can use $page->getSubpages() or $page->getNestedPages()?
Do I have to create some kind of query inside my model? Or do I have to resolve this with existing functions (like the object storage) and how?
I tried a lot of things but can simply figure out how this should work.
you have to overwrite your findByPid repository-method and add
public function findByPid($pid) {
$querySettings = $this->objectManager->create('Tx_Extbase_Persistence_Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$this->setDefaultQuerySettings($querySettings);
$query = $this->createQuery();
$query->matching($query->equals('pid', $pid));
$pages = $query->execute();
return $pages;
}
to get all pages. Than you can write your own getSubpages-method like
function getSubpages($currentPid) {
$subpages = $this->pagesRepository->findByPid($currentPid);
if (count($subpages) > 0) {
$i = 0;
foreach($subpages as $subpage) {
$subpageUid = $subpage->getUid();
$subpageArray[$i]['page'] = $subpage;
$subpageArray[$i]['subpages'] = $this->getSubpages($subpageUid);
$i++;
}
} else {
$subpageArray = Array();
}
return $subpageArray;
}
i didn't test this method, but it looks like this to get alle subpages.
i wonder that i couldĀ“t find a typo3 method that return the complete Page-Tree :( So i write a little function (you can use in an extbase extension), for sure not the best or fastes way, but easy to extend or customize ;)
first you need an instance of the PageRepository
$this->t3pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
this->t3pageRepository->init();
make the init, to set some basic confs, like "WHERE deletet = 0 AND hidden = 0..."
then with this function you get an array with the page data and subpages in. I implement yust up to three levels:
function getPageTree($pid,$deep=2){
$fields = '*';
$sortField = 'sorting';
$pages = $this->t3pageRepository->getMenu($pid,$fields,$sortField);
if($deep>=1){
foreach($pages as &$page) {
$subPages1 = $this->t3pageRepository->getMenu($page['uid'],$fields,$sortField);
if(count($subPages1)>0){
if($deep>=2){
foreach($subPages1 as &$subPage1){
$subPages2 = $this->t3pageRepository->getMenu($subPage1['uid'],$fields,$sortField);
if(count($subPages2>0)){
$subPage1['subpages'] = $subPages2;
}
}
}
$page['subpages'] = $subPages1;
}
}
}
return $pages;
}

Bringing in value of Coupon Code into "tax" calculation.php in magento

Im trying to pull in the name of the discount code currently applied to the cart into the calculation.php file. The name of the discount code is optionalTax but Im having trouble passing it through or retrieving it directly. Its appears to be referenced as $quote->getCouponCode() in mage/sales/model/quote.php and I want to use it in
mage/tax/model/calculation.php
Anyone have any idea on how to call it in as I've tried using the model as per (which I think is correct)
public function calcTaxAmount($price, $taxRate, $priceIncludeTax=false, $round=true)
{
$taxRate = $taxRate/100;
if ($priceIncludeTax) {
$amount = $price*(1-1/(1+$taxRate));
} else {
$cModel = Mage::getModel('catalog/sales');
$thisDiscountCode = $cModel->$quote->getCouponCode();
die($thisDiscountCode);
$amount = $price*$taxRate;
}
if ($round) {
return $this->round($amount);
} else {
return $amount;
}
}
Chris
you need to get the quote from right model i guess:
Mage::getSingleton('checkout/session')->getQuote();

Resources