Loading custom attribute value in controller in Magento2 - attributes

I'm trying to load custom attribute value in my controller but it always returns null. Here is my code:
public function execute()
{
$product_id = $this->getRequest()->getParam('id');
if(isset($product_id)){
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
$colorGriding = $_product->getCustomAttribute('color_griding'); // returns null
echo json_encode(array('message'=>'found', 'colors' => $colorGriding->getValue()));
}
else
echo json_encode(array('message'=>'empty'));
What is wrong here?

Related

ReferenceError - Context is not defined (Netsuite)

I am trying to hide a field when a checkbox is checked in an Opportunity but the script I have is throwing a ReferenceError - Context is not defined.
Here is my code:
define(['N/currentRecord','N/search', 'N/format'],
function(currentRecord, search, format) {
function pageInit_disableMyText(scriptContext) {
console.log('START : here you will be able see logs via console (F12 on browser)');
var recCurrent = context.currentRecord; //This represents your current loaded record, you can get the values of the fields here
var myCheckbox = recCurrent.getValue('custbody7'); //This is the code for getting the value of your field
console.log('myCheckbox Value is : ' + myCheckbox);
if(myCheckbox == true)
{
//get the field and disable it
fld1 = recCurrent.getField('custbody3');
fld1.isDisabled = true;
}
else
{
//if you didn't set the field to be disabled by default, then you don't need the code to enable it here
//since it runs only once when the page loads
}
}
function fieldChanged_toggleBox(scriptContext) {
//Different function that triggers on change of a field value, can use this to toggle the checkbox
var currentFieldID = context.fieldId;
console.log('context.fieldId : '+ currentFieldID);
//Check which field is toggled
if(currentFieldID == 'custbody7')
{
//Essentially do the same as above
var recCurrent = context.currentRecord;
var myCheckbox = recCurrent.getValue('custbody7');
if(myCheckbox == true)
{
//get the field and disable it
fld1 = recCurrent.getField('custbody3');
fld1.isDisabled = true;
}
else
{
//Now you need code to enable it as you are toggling the disabling and enabling it realtime
fld1 = recCurrent.getField('custbody3');
fld1.isDisabled = false;
}
}
}
//this is the retrun statement where we declare the script type to implement
return {
pageInit: pageInit_disableMyText,
fieldChanged: fieldChanged_toggleBox
};
});
When I use devtools in Chrome it shows the error on this line:
var recCurrent = context.currentRecord; //This represents your current loaded record, you can get the values of the fields here
But I cannot see what the problem is.
Any help is appreciated.
Thanks!
The parameter name in your function is scriptContext , change it to context
function pageInit_disableMyText(scriptContext) { // <---- Change this parameter to context
Basically you can call it whatever you like, but then you have to use the same variable.

How to add existing attribute to an attribute set programmatically in Magento 2

How can I add some existing attributes to a new attribute set programmatically in Magento 2?
in magento 2, there is color & manufactor attribute already created, but by defaultly this two attribute is not assigned to default attribute set. so, we can do like this. then it will assign this two attribute to default attribute when module installing.
<?php
namespace Vendor\Module\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
private $categorySetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory, \Magento\Catalog\Setup\CategorySetupFactory $categorySetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
try {
/**
* #var \Magento\Eav\Setup\EavSetup
*/
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
/**
* #var \Magento\Catalog\Setup\CategorySetup
*/
$categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
$entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
$attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId); // get default attribute set id
$attrGroupId = $categorySetup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId); // get default attribute group id (in my case, it returns id of 'Product Details' group)
$colorAttr = $eavSetup->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'color');
if($colorAttr) {
$eavSetup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attrGroupId,
'color',
null
);
}
$manufacturerAttr = $eavSetup->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'manufacturer');
if($manufacturerAttr) {
$eavSetup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attrGroupId,
'manufacturer',
null
);
}
} catch (NoSuchEntityException $e) {
return;
} catch (\Exception $e) {
return;
}
}

Get all attributes of an attribute set that is not present in default attribute set

How can I get the list of attributes of an attribute set that are not present in the default attribute set?
I tried the following codes:
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->load($_product->getAttributeSetId())->getId();
$attributes = Mage::getModel('catalog/product_attribute_api')
->items($attributeSetId);
echo '<pre>';
print_r($attributes);
die();
But this returned an array with all the attributes including the attributes of default attribute set whereas I just needed the attributes that only belonged to my custom attribute set.
This is the solution I came up with
public function getSpecificAttributes($product) {
//get ids of all the attributes in the default attribute set
$entityTypeId = Mage::getModel('eav/entity')
->setType('catalog_product')
->getTypeId();
$attributeSetName = 'Default';
$defaultAttributeSetId = Mage::getModel('eav/entity_attribute_set')
->getCollection()
->setEntityTypeFilter($entityTypeId)
->addFieldToFilter('attribute_set_name', $attributeSetName)
->getFirstItem()
->getAttributeSetId();
$defaultAttributes = Mage::getModel('catalog/product_attribute_api')->items($defaultAttributeSetId);
$defaultAttributeCodes = array();
foreach ($defaultAttributes as $attributes) {
$defaultAttributeCodes[] = $attributes['code'];
}
//get ids of all the attributes in the attribute set specific to the current product
$attributeSetId = $product->getAttributeSetId();
$specificAttributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);
$attributeCodes = array();
foreach ($specificAttributes as $attributes) {
$attributeCodes[] = $attributes['code'];
}
$currentAttributes = array_diff($attributeCodes, $defaultAttributeCodes);
return $currentAttributes;
}

Moq callback method with object parameter

In my scenario I want to mock 1 of the service framework method which takes object parameter and reset it with strongly typed class object.
public void Updatedata(object pvm)
{
var vm = new datamodel()
{
name = "test",
age = 100
};
pvm = vm;
}
It gives compilation error "Invalid callback. Setup on method with parameters (Object) cannot invoke callback with parameters (datamodel)." with below code for mocking.
mockderived.Setup(p => p.Updatedata(It.IsAny<datamodel>()))
.Callback<datamodel>(p =>
{
p.name ="My name is test";
});
The mock works fine if I change my updatedata method to accepts datamodel as parameter instead of object type. To avoid compilation errors I changed code by passing object as parameter:
mockderived.Setup(p => p.Updatedata(It.IsAny<object>()))
.Callback<object>(p =>
{
p = new datamodel() {name = "My name is test"};
});
Code get executed by it did not reulted in change of values of datamodel as expected.
After using reflection to set properties of the object parameter in the callback method, I am able to mock method proerly.
mockderived.Setup(p => p.Updatedata(It.IsAny<object>()))
.Callback<object>(p =>
{
var temp = new datamodel();
var t = temp.GetType();
var nameprop = "no name";
var prop = t.GetProperties();
prop[0].SetValue(p, nameprop, null);
});

Convert to view model, EF Partial Class calculated property using related entities returns 0

I am using EF 5 and have a new property that I've defined in a partial class to extend the base database fields. It requires summing data from a related table.
[Display(Name = "Qty Allocated")]
public decimal QtyAllocated
{
get { return this.AllocatedContainers == null ? 1 : this.AllocatedContainers.Sum(a => a.AllocatedQty); }
//get { return 2;}
}
This property returns the correct value....BUT, if I then use the following method to convert this to a view model, the returned value is 0. Note the view model inherits from the class:
public class InventoryContainerDetailListViewModel : InventoryContainerDetail
Method:
public IEnumerable<InventoryContainerDetailListViewModel> ConvertClassToViewModel(IEnumerable<InventoryContainerDetail> entityList)
{
IEnumerable<InventoryContainerDetailListViewModel> itemGrid =
from l in entityList.ToList()
select new InventoryContainerDetailListViewModel()
{
Id = l.Id,
InventoryContainerHeaderId = l.InventoryContainerHeaderId,
PONbr = l.ReceiptDetail == null ? (int?)null : l.ReceiptDetail.PODetail.POHeaderId,
ReceiptDetailId = l.ReceiptDetailId,
ItemId = l.ItemId,
ItemDescription = l.Item.ShortDescription,
QtyInContainer = l.QtyInContainer,
//QtyAllocated = l.AllocatedContainers == null ? 0 : l.AllocatedContainers.Sum(a => a.AllocatedQty),
Location = l.InventoryContainerHeader.Location.DisplayLocation
};
return itemGrid;
}
In this method, the input parameter entityList does show each item with the correct calculated values, but after the conversion, the value is always 0.
I assume this has something to do with the fact that I am inheriting from the base class, but can someone shed some light on this?
I don't think that the reason is inheritance. The more probable reason is that AllocatedContainers is empty collection (you don't assign it when creating instance of your view model).

Resources