How know if an attribute in Magento use options - magento

I want to know programmatically if a magento attribute use options or not to know if I must displayed this options.
For example a Text attribute don't use it and a Dropdown attributes have option. But how make programmatically this distinction ?

$product = Mage::getModel('catalog/product')->load($product_id);if($product->hasOptions){
$optionsArr = $product->getOptions();
foreach($optionsArr as $optionKey => $optionVal)
{
$options=array();
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$options[]=array("key"=>$valuesVal->getId(), "val"=>$valuesVal->getTitle());
}
$custom_option["titles"][]=array("title"=>$optionVal->getTitle(),"title_id"=>$optionVal->getId(),"options"=>$options);
//$optStr.= "</select>";
}

$attributeCode = 'code_here';
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attributeCode);
if ($attribute->getSourceModel()) {
//it has options
} else {
//it does not have options
}

$attributeModel = Mage::getModel ( 'eav/entity_attribute' )->loadByCode ( 'catalog_product', 'attribute_code' );
if ($attributeModel->getData ( 'frontend_input' ) == 'select') {
$attribute = Mage::getSingleton ( 'eav/config' )->getAttribute ( 'catalog_product', 'attribute_code' );
if ($attribute->usesSource ()) {
$options = $attribute->getSource ()->getAllOptions ( false );
$ifoptionfound = false;
if($options)
$ifoptionfound = true;
}
}

Related

render data from array to select option laravel

function getAllYears()
{
$year_array = array();
$posts_dates = Entries::orderBy( 'created_at', 'ASC' )->pluck( 'created_at' );
$posts_dates = json_decode( $posts_dates );
if ( ! empty( $posts_dates ) )
{
foreach ( $posts_dates as $unformatted_date )
{
$date = new \DateTime( $unformatted_date->date );
$year_value = $date->format( 'Y' );
$year_val = $date->format( 'y' );
//$year_array[$year_val ] = $year_value;
$year_array[] = $year_value;
}
} //return $year_array;
$array = $year_array;
// Deleting the duplicate items
$unique_years = array_unique($array);
return view('welcome',compact($unique_years));
<select name="YearFrom" id="YearFrom_input"">
<option selected="selected">Choose Year</option>
#foreach($unique_years as $years)
<option value='{{$years}}'> {{$years['years']}} </option>
#endforeach
</select>
!!getting error!!
compact(): Undefined variable: 2009
compact thinks the values of your array are the variables names, because you've passed it the actual array, not the name of the variable. See http://php.net/compact for details on how compact() works. Instead, you need:
return view('welcome',compact('unique_years'));
That said, I hate the compact approach for this reason. This is much more readable:
return view('welcome')->with('unique_years', $unique_years);
Your variabel name was incorrect in compact() - should be a string like 'variable_name' rather than $variable_name
function getAllYears()
{
$year_array = array();
$posts_dates = Entries::orderBy( 'created_at', 'ASC' )->pluck( 'created_at' );
$posts_dates = json_decode( $posts_dates );
if ( ! empty( $posts_dates ) ) {
foreach ( $posts_dates as $unformatted_date ) {
$date = new \DateTime( $unformatted_date->date );
$year_value = $date->format( 'Y' );
$year_val = $date->format( 'y' );
//$year_array[$year_val ] = $year_value;
$year_array[] = $year_value;
}
} //return $year_array;
$array = $year_array;
// Deleting the duplicate items
$unique_years = array_unique($array);
return view('welcome',compact('unique_years'));
}

Magento remove item from cart from observer

Is there any way that we can remove the Items from the cart. Actually I have dynamic Grouped products were I need to allow the user to buy the item inside the grouped product. Now when someone only select the Item under the grouped product then it allow to buy that and need to stop or remove the group product from the cart.
I had tried with checkout_cart_product_add_after Observer and used below logic, but it is not working
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $productId) {
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
}
}
return;
Please help me guys.
Thanks in advance.
Standalone example:
$oCheckout = Mage::getSingleton( 'checkout/session' );
$oQuote = $oCheckout->getQuote();
var_dump( $oQuote );
$oCart = $oQuote->getAllItems();
if( !empty( $oCart ) )
{
foreach ( $oCart as $oItem )
{
// Specify conditionals
if( $oItem->getProduct()->getSku() == 1 )
{
// Note to use Shopping cart id not product id.
$oQuote->removeItem( $oItem->getId() )
->save();
}
}
}
var_dump( $oQuote );
Try this in your observer:
$product = $observer->getEvent()->getProduct();
$cart = Mage::getSingleton('checkout/cart');
foreach ($cart->getQuote()->getItemsCollection() as $_item) {
if ($_item->getProductId() == $product->getId()) {
$_item->isDeleted(true);
}
}
}

add bundle products items qty to cart programatically Magento

HI i need to add a bundle product with its items qty to cart programaticaaly. For this i am using the below code
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = $this->getRequest()->getParams();
$productId = 3801 ;//3857;
$product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($productId);
if($product->getTypeId() == "bundle"){
$bundled_items = array();
$optionCollection = $product->getTypeInstance()->getOptionsCollection();
$selectionCollection = $product->getTypeInstance()->getSelectionsCollection($product->getTypeInstance()->getOptionsIds());
$options = $optionCollection->appendSelections($selectionCollection);
$childsku = array('testing','staging');
foreach($options as $option) {
$_selections = $option->getSelections();
foreach($_selections as $selection) {
//print_r($selection);
$bundled_items[$option->getOptionId()][] = $selection->getSelectionId();
$bundled_qty[$selection->getSelectionId()][] = 2;
}
}
print_r($bundled_items);
print_r($bundled_qty);
$params = array('bundle_option' => $bundled_items,
'bundle_option_qty'=>$bundled_qty,
'qty' => 1,'product'=>$productId);
}
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = new Mage_Catalog_Model_Product();
$product->load($productId);
$cart->addProduct($product, $params);
$cart->save();
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
this code add the product to cart properly with all its items i
need to sprcify the each option qty
but it sets all options qty to 1
.
can you please suggest me where i am doing the mistake or what i should try.
thanks
ok i have fix the issue by doing some changes in the script
$cart = Mage::getModel('checkout/cart');
$cart->init();
$bundled_items = array();
$optionCollection = $_product->getTypeInstance()->getOptionsCollection();
$selectionCollection = $_product->getTypeInstance()->getSelectionsCollection($_product->getTypeInstance()->getOptionsIds());
$options = $optionCollection->appendSelections($selectionCollection);
foreach($options as $option) {
$_selections = $option->getSelections();
foreach($_selections as $selection) {
foreach($cusarray as $cusarraykey=> $cusarrayvalue) {
if($selection->getSku()== $cusarrayvalue){
print_r($selection->getSku());
echo $selection->getSku()."<br/>";
$bundled_items[$option->getOptionId()][] = $selection->getSelectionId();
$bundled_qty[$option->getOptionId()] = $cusqtyarray[$cusarraykey];
}
}
}
}
$params = array('bundle_option' => $bundled_items,
'bundle_option_qty' => $bundled_qty,
'qty' => $proqty,'product'=>$_productId);
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$_product = new Mage_Catalog_Model_Product();
$_product->load($_productId);
$cart->addProduct($_product, $params);
$cart->save();
thanks
"$bundled_qty[$option->getOptionId()] = $cusqtyarray[$cusarraykey];"
is this how you fixed.

How can i save attributes values against product ids in magetno

How can I add Products attributes value against product ids's. I want to add attributes values for specific product id using code.My code for products attribute is
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
//Load the particular attribute by id
//Here 73 is the id of 'manufacturer' attribute
$attr_model->load(73);
//Create an array to store the attribute data
$data = array();
//Create options array
$values = array(
//15 is the option_id of the option in 'eav_attribute_option_value' table
15 => array(
0 => 'Apple' //0 is current store id, Apple is the new label for the option
),
16 => array(
0 => 'HTC'
),
17 => array(
0 => 'Microsoft'
),
);
//Add the option values to the data
$data['option']['value'] = $values;
//Add data to our attribute model
$attr_model->addData($data);
//Save the updated model
try {
$attr_model->save();
$session = Mage::getSingleton('adminhtml/session');
$session->addSuccess(
Mage::helper('catalog')->__('The product attribute has been saved.'));
/**
* Clear translation cache because attribute labels are stored in translation
*/
Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
$session->setAttributeData(false);
return;
} catch (Exception $e) {
$session->addError($e->getMessage());
$session->setAttributeData($data);
return;
}
Hi after search i find some code that save my attribute values and than i store them against products.This is my code :
public static function getAttributeOptionId($arg_attribute, $arg_value,$id)
{
$id = $id;
//load the attribute by attribute code
$entityTypeID = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
$type = $attribute->getBackendType();
foreach($options as $option) {
if ($option['label'] == $arg_value) {
$arrk[] = $option['label'];
}
}
$optiont = self::getAttributeOptionValue($arg_attribute, $arg_value);
if(!$optiont){
$value['option'] = array($arg_value,$arg_value);
$result = array('value' => $value);
$attribute->setData('option',$result);
$attribute->save();
$product = Mage::getModel('catalog/product')->load($id);
$product->setMyAttribute($arg_attribute)->save();
}
return 0;
}
public function getAttributeOptionValue($arg_attribute, $arg_value) {
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option) {
if ($option['label'] == $arg_value) {
return $option['value'];
}
}
return false;
}.
Where $arg_attribute is the attriubte code and $arg_value is his value.Id is product id for specific sku.I am saving records in my custom module.If anyone know issue with this code please inform me.Thanks

Exporting and Importing Attributes in Magento

I would love a script or magento extension to allow me to export all the product attributes including values for drop down attributes. Importing would be good too, I've had a look but can't seem to find anything does anyone know how this can be done?
Update: I found a working script in stackexchange and the script worked exactly as it should. All credits to the original poster. I am just copy pasting his reply here for future reference. Link to the original thread: is here.
I've done this to export all attributes and their options (if it is a dropdown attribute) from the source website:
exportAttributes.php in root directory of source website:
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
Mage::app();
$entity_type_id = Mage::getModel('catalog/product')->getResource()->getTypeId();
prepareCollection($entity_type_id);
function prepareCollection($ent_type_id){
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_read');
$select_attribs = $connection->select()
->from(array('ea'=>$resource->getTableName('eav/attribute')))
->join(array('c_ea'=>$resource->getTableName('catalog/eav_attribute')), 'ea.attribute_id = c_ea.attribute_id');
// ->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
// ->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
$select_prod_attribs = $select_attribs->where('ea.entity_type_id = '.$ent_type_id)
->order('ea.attribute_id ASC');
$product_attributes = $connection->fetchAll($select_prod_attribs);
$select_attrib_option = $select_attribs
->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
->order('e_ao.attribute_id ASC');
$product_attribute_options = $connection->fetchAll($select_attrib_option);
$attributesCollection = mergeCollections($product_attributes, $product_attribute_options);
prepareCsv($attributesCollection);
}
function mergeCollections($product_attributes, $product_attribute_options){
foreach($product_attributes as $key => $_prodAttrib){
$values = array();
$attribId = $_prodAttrib['attribute_id'];
foreach($product_attribute_options as $pao){
if($pao['attribute_id'] == $attribId){
$values[] = $pao['value'];
}
}
if(count($values) > 0){
$values = implode(";", $values);
$product_attributes[$key]['_options'] = $values;
}
else{
$product_attributes[$key]['_options'] = "";
}
/*
temp
*/
$product_attributes[$key]['attribute_code'] = $product_attributes[$key]['attribute_code'];
}
return $product_attributes;
}
function prepareCsv($attributesCollection, $filename = "importAttrib.csv", $delimiter = '|', $enclosure = '"'){
$f = fopen('php://memory', 'w');
$first = true;
foreach ($attributesCollection as $line) {
if($first){
$titles = array();
foreach($line as $field => $val){
$titles[] = $field;
}
fputcsv($f, $titles, $delimiter, $enclosure);
$first = false;
}
fputcsv($f, $line, $delimiter, $enclosure);
}
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="'.$filename.'"');
fpassthru($f);
}
This will give a csv file [actually i used "|" to separate ;)]
paste this csv file in MAGENTO_ROOT/attribImport directory of the destination website, i.e. website to which attributes need to be imported:
now put the following code in MAGENTO_ROOT/attribImport** directory
of the destination website
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php';
Mage::app();
// $fileName = MAGENTO . '/var/import/importAttrib.csv';
$fileName = 'importAttrib.csv';
// getCsv($fileName);
getAttributeCsv($fileName);
function getAttributeCsv($fileName){
// $csv = array_map("str_getcsv", file($fileName,FILE_SKIP_EMPTY_LINES));
$file = fopen($fileName,"r");
while(!feof($file)){
$csv[] = fgetcsv($file, 0, '|');
}
$keys = array_shift($csv);
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}
foreach($csv as $row){
$labelText = $row['frontend_label'];
$attributeCode = $row['attribute_code'];
if($row['_options'] != "")
$options = explode(";", $row['_options']); // add this to createAttribute parameters and call "addAttributeValue" function.
else
$options = -1;
if($row['apply_to'] != "")
$productTypes = explode(",", $row['apply_to']);
else
$productTypes = -1;
unset($row['frontend_label'], $row['attribute_code'], $row['_options'], $row['apply_to'], $row['attribute_id'], $row['entity_type_id'], $row['search_weight']);
createAttribute($labelText, $attributeCode, $row, $productTypes, -1, $options);
}
}
/**
* Create an attribute.
*
* For reference, see Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
*
* #return int|false
*/
function createAttribute($labelText, $attributeCode, $values = -1, $productTypes = -1, $setInfo = -1, $options = -1)
{
$labelText = trim($labelText);
$attributeCode = trim($attributeCode);
if($labelText == '' || $attributeCode == '')
{
echo "Can't import the attribute with an empty label or code. LABEL= [$labelText] CODE= [$attributeCode]"."<br/>";
return false;
}
if($values === -1)
$values = array();
if($productTypes === -1)
$productTypes = array();
if($setInfo !== -1 && (isset($setInfo['SetID']) == false || isset($setInfo['GroupID']) == false))
{
echo "Please provide both the set-ID and the group-ID of the attribute-set if you'd like to subscribe to one."."<br/>";
return false;
}
echo "Creating attribute [$labelText] with code [$attributeCode]."."<br/>";
//>>>> Build the data structure that will define the attribute. See
// Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
$data = array(
'is_global' => '0',
'frontend_input' => 'text',
'default_value_text' => '',
'default_value_yesno' => '0',
'default_value_date' => '',
'default_value_textarea' => '',
'is_unique' => '0',
'is_required' => '0',
'frontend_class' => '',
'is_searchable' => '1',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
'used_for_sort_by' => '0',
'is_configurable' => '0',
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'backend_type' => 'varchar',
'default_value' => '',
'is_user_defined' => '0',
'is_visible' => '1',
'is_used_for_price_rules' => '0',
'position' => '0',
'is_wysiwyg_enabled' => '0',
'backend_model' => '',
'attribute_model' => '',
'backend_table' => '',
'frontend_model' => '',
'source_model' => '',
'note' => '',
'frontend_input_renderer' => '',
);
// Now, overlay the incoming values on to the defaults.
foreach($values as $key => $newValue)
if(isset($data[$key]) == false)
{
echo "Attribute feature [$key] is not valid."."<br/>";
return false;
}
else
$data[$key] = $newValue;
// Valid product types: simple, grouped, configurable, virtual, bundle, downloadable, giftcard
$data['apply_to'] = $productTypes;
$data['attribute_code'] = $attributeCode;
$data['frontend_label'] = array(
0 => $labelText,
1 => '',
3 => '',
2 => '',
4 => '',
);
//<<<<
//>>>> Build the model.
$model = Mage::getModel('catalog/resource_eav_attribute');
$model->addData($data);
if($setInfo !== -1)
{
$model->setAttributeSetId($setInfo['SetID']);
$model->setAttributeGroupId($setInfo['GroupID']);
}
$entityTypeID = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
$model->setEntityTypeId($entityTypeID);
$model->setIsUserDefined(1);
//<<<<
// Save.
try
{
$model->save();
}
catch(Exception $ex)
{
echo "Attribute [$labelText] could not be saved: " . $ex->getMessage()."<br/>";
return false;
}
if(is_array($options)){
foreach($options as $_opt){
addAttributeValue($attributeCode, $_opt);
}
}
$id = $model->getId();
echo "Attribute [$labelText] has been saved as ID ($id).<br/>";
// return $id;
}
function addAttributeValue($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
if(!attributeValueExists($arg_attribute, $arg_value))
{
$value['option'] = array($arg_value,$arg_value);
$result = array('value' => $value);
$attribute->setData('option',$result);
$attribute->save();
}
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
function attributeValueExists($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
NOTE: Allthough exceptions have been handled, Backup your Database
before you import these attributes, to be on safer side. Happy
Importing!
Thanks to :
Programatically create attribute in Magento, useful for the “on the fly” import system
programmatically_adding_attributes_and_attribute_sets
Magento – Programmatically insert new attribute option
I would recommend Boris's uRapidFlow: http://www.unirgy.com/products/urapidflow/ It's one of the better Data Flow Import/Export modules available. Be aware however it does require IonCube Loader, but it is well worth it if you are moving data around a lot.

Resources