Add custom options to dropdown via code in Magento - magento

i had to add custom options automatically when a product is added , the code works fine but i need to create a drop down menu with options and i dont know how to add options to the drop down created ,
my code is
public function Add_CustomOptions_Automatically($observer) {
$product = $observer->getEvent()->getProduct();
$save = false; if (!$product->getOptions()) $save = true;
$optionData = array(
'previous_group' => 'text',
'title' => 'Size',
'type' => 'drop_down',
'is_require' => 0,
'sort_order' => 0,
'price' => 0,
'price_type' => 'fixed');
if($save):
$product->setHasOptions(1)->save();
$option = Mage::getModel('catalog/product_option')
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($optionData);
$option->save();
$product->addOption($option);
endif;
}
}
I've created 'type' => 'drop_down' but how can I add options? I have no idea how to add the options, and any help would be very much appreciated.
thanks,

You can supply an array of values to the option array, this will then be added
to the option. as below :-)
$product = Mage::getModel('catalog/product');
$product->load(200); // product id here
$opt = array(
'is_delete' => 0,
'is_require' => false,
'previous_group' => '',
'title' => 'New Example Option',
'type' => 'drop_down',
'price_type' => 'fixed',
'price' => '20.0000',
'sort_order' => 0,
/** array of values for this option **/
'values' => array(
array(
'is_delete' => 0,
'title' => 'Option One Here',
'price_type' => 'fixed',
'price' => 999,
'sku' => 'test-sku-here',
'option_type_id'=> -1,
),
array(
'is_delete' => 0,
'title' => 'Another Option',
'price_type' => 'fixed',
'price' => 999,
'sku' => 'another-sku-here',
'option_type_id'=> -1,
)),
);
$option = Mage::getModel('catalog/product_option')
->setProduct($product)
->addOption($opt)
->saveOptions();

public function Add_CustomOptions_Automatically($observer) {
$product = $observer->getEvent()->getProduct();
$optionData = array(
'previous_group' => 'text',
'title' => 'Size',
'type' => 'drop_down',
'is_require' => 0,
'sort_order' => 0,
'price' => 0,
'price_type' => 'fixed');
if(!(bool)$product->getOptions()):
$product->setHasOptions(true)->save();
$option = Mage::getModel('catalog/product_option')
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($optionData);
// Answer starts here
$value = Mage::getModel('catalog/product_option_value');
$value->setOption($option)
->setTitle('Hello world!');
$option->addValue($value);
// Answer ends here
$option->save();
$product->addOption($option);
endif;
}
As you can see you are adding a Mage_Catalog_Model_Product_Option_Value with a title and associating it with the $option you created. It can also have an SKU, price and sort order. Create as many values as you want in this way.

<!DOCTYPE html PUBLIC "-W3CDTD XHTML 1.0 TransitionalEN" "http:www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http:www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<pre>
<?php
$res = mysql_pconnect('localhost', 'your data base name', 'passward');
mysql_select_db('your database name');
mysql_query("SET NAMES 'utf8';", $res);
mysql_query("SET CHARACTER SET 'utf8';", $res);
$query = 'select entity_id from catalog_product_entity';
$res = mysql_query($query);
$products=array();
while ($ret = mysql_fetch_array($res)) {
$products[]=$ret[0];
$query = "UPDATE catalog_product_entity set has_options=1 where entity_id=$ret[0]";
//echo "$query<br>";
//$res1 = mysql_query($query);
}
echo "Set all products for has_options in catalog_product_entity.<br>";
//$res = mysql_query('DELETE from catalog_product_option');
//$res = mysql_query('DELETE from catalog_product_option_title');
//$res = mysql_query('DELETE from catalog_product_option_type_price');
//$res = mysql_query('DELETE from catalog_product_option_type_title');
//$res = mysql_query('DELETE from catalog_product_option_type_value');
echo "Deleted all rows from catalog_product_option* tables.<br>";
$ress=array();
foreach ($products as $product){
$query = "insert into catalog_product_option (product_id,type,is_require,image_size_x,image_size_y,sort_order) values ($product,'drop_down',0,0,0,0)";
echo "$query<br>";
$res1 = mysql_query($query);
$ress[] = array("option_id" => mysql_insert_id());
}
echo '<pre>';
print_r($ress);
echo "Populated catalog_product_option.<br>";
$option_titles=array('en_US'=> 'Warrenty' );// here change title of option titles #Optional Coating
$res = mysql_query('SELECT * FROM `core_config_data` WHERE path="general/locale/code"');
while ($ret = mysql_fetch_array($res)) {
$stores[$ret['value']][]=$ret['scope_id'];
}
$res = mysql_query('select * from catalog_product_option');// get all product here which agains data inserted
$sort_orders=array(
1,
2,
3,
4);
//while ($ret = mysql_fetch_array($res)) {
foreach ($ress as $key => $ret)
{
//echo '<br>'.$ret[$key]["option_id"];
foreach($stores as $locale=>$scopes){
foreach($scopes as $scope){
$query = "insert into catalog_product_option_title (option_id,store_id,title) values ($ret[option_id],$scope,'$option_titles[$locale]')";
echo "$query<br>";
$res1 = mysql_query($query);
}
}
foreach($sort_orders as $order){
$query = "insert into catalog_product_option_type_value (option_id,sort_order) values ($ret[option_id],$order)";
echo "$query<br>";
$res1 = mysql_query($query);
}
}
echo "Populated catalog_product_option_title.<br>";
echo "Populated catalog_product_option_type_value.<br>";
$prices=array(
0.00,//Standard (12 months)
29.95,//Silver (12 months +loan phone + pic up)
59.95,//Gold(12 months)
89.95//Platinum (24 months +loan phone + pic up)
);
$option_type_titles=array('en_US'=>array(
'Standard (12 months).',
'Silver (12 months +loan phone + pic up).',
'Gold(12 months).',
'Platinum (24 months +loan phone + pic up).'
)
);
$res = mysql_query('select * from catalog_product_option_type_value');
$i = 0;
$j = count($prices)-1;
while ($ret = mysql_fetch_array($res)) {
foreach($stores as $locale=>$scopes){
foreach($scopes as $scope){
$query = "insert into catalog_product_option_type_price (option_type_id,store_id,price,price_type) values ($ret[0],$scope,$prices[$i],'fixed')";
echo "$query<br>";
$res1 = mysql_query($query);
$query = "insert into catalog_product_option_type_title (option_type_id,store_id,title) values ($ret[0],$scope,'{$option_type_titles[$locale][$i]}')";
echo "$query<br>";
$res1 = mysql_query($query);
}
}
($j==$i) ? $i= 0 : $i++ ;
}
echo "<br>Populated catalog_product_option_type_price.<br>";
echo "<br>Populated catalog_product_option_type_title.<br>";
?>
</pre>
</body>
</html>
dear this code is work and i check it . but this code when excute it will add this custom option with all products in your shop. you can change sort ordar and price and option values and also dropdown name . i think its work better.

Try this, its working for me...
$eavSetup->addAttribute(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,$attributeCode, [
'type' => 'varchar',
'label' => 'My Code',
'input' => 'select',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Table',
'required' => false,
'visible' => true,
'user_defined' => true,
'sort_order' => 101,
'position' => 101,
'system' => 0,
'option' =>
array (
'values' =>
array(
0 => 'January',
1 => 'February',
2 => 'March',
3 => 'April',
4 => 'May',
5 => 'June',
6 => 'July',
7 => 'August',
8 => 'September',
9 => 'October',
10 => 'November',
11 => 'December'
),
),
]);

Related

insert batch codelgniter Unknown column 'Array' in 'field list'

I am beginner in CI. I am getting an error in insert_batch function in CodeIgniter. When I insert array into insert_batch I get this error
Unknown column 'Array' in 'field list'
and
Array to string conversion
I've done many solutions but still get this error,
Can anyone give me an idea?
thanks in advance
in my views
<input type="text" name="companionship[]"> and so forth.
controller
public function addstatistics()
{
$i =0;
foreach($_POST['companionship_id'] as $companionship_id):
$value1[$i++] = array(
'companionship_id'=> $companionship_id
);
endforeach;
foreach($_POST['zone_id'] as $zone_id):
$value2[$i++] = array(
'zone_id'=> $zone_id
);
endforeach;
foreach($_POST['district_id'] as $district_id):
$value3[$i++] = array(
'district_id'=> $district_id
);
endforeach;
foreach($_POST['area_id'] as $area_id):
$value4[$i++] = array(
'area_id'=> $area_id
);
endforeach;
foreach($_POST['baptism'] as $baptism):
$value5[$i++] = array(
'baptism'=> $baptism
);
endforeach;
foreach($_POST['confirm'] as $confirm):
$value6[$i++] = array(
'confirm'=> $confirm
);
endforeach;
foreach($_POST['ibd'] as $ibd):
$value7[$i++] = array(
'ibd'=> $ibd
);
endforeach;
foreach($_POST['iasm'] as $iasm):
$value8[$i++] = array(
'iasm'=>$iasm
);
endforeach;
foreach($_POST['ni'] as $ni):
$value9[$i++] = array(
'ni'=>$ni
);
endforeach;
foreach($_POST['ph'] as $ph):
$value10[$i++] = array(
'ph'=>$ph
);
endforeach;
foreach($_POST['wh'] as $wh):
$value11[$i++] = array(
'wh'=>$wh
);
endforeach;
$this->my_model->addstatistics($value1,$value2,$value3,$value4, $value5,$value6,$value7,$value8,$value9,$value10,$value11);
}
MODEL function
addstatistics($value1,$value2,$value3,$value4,$value5, $value6,$value7,$value8,$value9,$value10,$value11)
{
$data = array(
'companionship_id' => $value1,
'zone_id' => $value2,
'district_id' => $value3,
'area_id' => $value4,
'baptism' => $value5,
'confirm' => $value6,
'ibd' => $value7,
'iasm' => $value8,
'ni' => $value9,
'ph' => $value10,
'wh' => $value11
);
$row = array();
$columns = array();
for($x=0; $x<count($data); $x++)
{
$row = array(
'companionship_id'=> $value1,
'zone_id'=> $value2,
'district_id'=> $value3,
'area_id'=> $value4,
'baptism'=> $value5,
'confirm'=> $value6,
'ibd'=> $value7,
'iasm'=> $value8,
'ni'=> $value9,
'ph'=> $value10,
'wh'=> $value11,
'year'=> date('Y'),
'month'=> date('M'),
'week' => weekdate(),
'created_by'=> $this->session->userdata('login_id')
);
array_push($columns, $row);
$rows = array();
}
//printA($columns);
$query= $this->db->insert_batch('monthly_statistics', $columns);
}
Can anybody give me idea on how can i solve this problem?
Try this.
public function addstatistics($value1,$value2,$value3,$value4,$value5, $value6,$value7,$value8,$value9,$value10,$value11)
{
$data = array(
'companionship_id' => $value1,
'zone_id' => $value2,
'district_id' => $value3,
'area_id' => $value4,
'baptism' => $value5,
'confirm' => $value6,
'ibd' => $value7,
'iasm' => $value8,
'ni' => $value9,
'ph' => $value10,
'wh' => $value11
);
$row = array();
$columns = array();
for($x=0; $x<count($data); $x++)
{
$row = array(
'companionship_id'=> $data['companionship_id'][$x]['companionship_id'],
'zone_id'=> $data['zone_id'][$x]['zone_id'],
'district_id'=> $data['district_id'][$x]['district_id'],
'area_id'=> $data['area_id'][$x]['area_id'],
'baptism'=> $data['baptism'][$x]['baptism'],
'confirm'=> $data['confirm'][$x]['confirm'],
'ibd'=> $data['ibd'][$x]['ibd'],
'iasm'=> $data['iasm'][$x]['iasm'],
'ni'=> $data['ni'][$x]['ni'],
'ph'=> $data['ph'][$x]['ph'],
'wh'=> $data['wh'][$x]['wh'],
'year'=> date('Y'),
'month'=> date('M'),
'week' => weekdate(),
'created_by'=> $this->session->userdata('login_id')
);
array_push($columns, $row);
$rows = array();
}
//printA($columns);
$query= $this->db->insert_batch('monthly_statistics', $columns);
}
after a few hours of pondering, I already fix the errors
and now it working fine
here is the code
public function mymethod()
{
$companionship_id = $this->input->post('companionship_id[]');
$zone_id = $this->input->post('zone_id[]');
$district_id = $this->input->post('district_id[]');
$area_id = $this->input->post('area_id[]');
$baptism = $this->input->post('baptism[]');
$confirm = $this->input->post('confirm[]');
$ibd = $this->input->post('ibd[]');
$iasm = $this->input->post('iasm[]');
$ni = $this->input->post('ni[]');
$ph = $this->input->post('ph[]');
$wh = $this->input->post('wh[]');
$value = array();
for($i=0; $i<count($companionship_id); $i++)
{
$value[$i] = array(
'companionship_id' => $companionship_id[$i],
'zone_id' => $zone_id[$i],
'district_id' => $district_id[$i],
'area_id' => $area_id[$i],
'baptism' => $baptism[$i],
'confirm' => $confirm[$i],
'ibd' => $ibd[$i],
'iasm' => $iasm[$i],
'ni' => $ni[$i],
'ph' => $ph[$i],
'wh' => $wh[$i]
);
}
$this->db->insert_batch('monthly_statistics',$value);
$this->session->set_flashdata("success",alert("alert-success","Successfully Inserted"));
redirect(base_url('to_url'));
exit();
}

Integrity constraint violation for key 'UNQ_CATALOG_PRODUCT_SUPER_ATTRIBUTE_PRODUCT_ID_ATTRIBUTE_ID'

I am creating simple products and then configurable product followed by associating simple products with configurable product. When I run the code for the first time, it works smoothly creating all simple products, configurable product and also an association. But, when I run that code again it says constraint violation. The ID that shows duplicated is the same product ID that was created the last time, when all process were ok.
My code is the following one.
$product_collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
$toinsertId = $product_collection->getLastItem()->getId() + 1;
$configurable_attribute = "art_print_sizes";
$attr_id = 133;
$simpleProducts = array();
$lowestPrice = 999999;
$attributes = Mage::getModel('catalogsearch/advanced')->getAttributes();
$attributeArray = array();
foreach ($attributes as $a) {
if ($a->getAttributeCode() == 'art_print_sizes') {
$count = 0;
foreach ($a->getSource()->getAllOptions(false) as $option) {
$option_id = $this->getOptionId("art_print_sizes", $option['label']);
$sku = 'SK_' . '500' . '_' . strval($count);
$sProduct = Mage::getModel('catalog/product');
$sProduct
->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
->setWebsiteIds(array(1))
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)
->setTaxClassId(5)
->setAttributeSetId(9)
->setSku($sku)
// $main_product_data is an array created as part of a wider foreach loop, which this code is inside of
->setName($wholedata['name'] . " - " . $option['label'])
->setShortDescription($wholedata['short_description'])
->setDescription($wholedata['description'])
->setPrice(sprintf("%0.2f", $wholedata['attr_val'][$count]))
->setData($configurable_attribute, $option_id);
$sProduct->save();
array_push(
$simpleProducts,
array(
"id" => $sProduct->getId(),
"price" => $sProduct->getPrice(),
"attr_code" => 'art_print_sizes',
"attr_id" => $attr_id,
"value" => $option_id,
"label" => $option['label']
)
);
$count++;
}
}
}
$cProduct = Mage::getModel('catalog/product');
$productData = array(
'name' => 'Main configurable Tshirt',
'sku' => 'tshirt_sku',
'description' => 'Clear description about your Tshirt that explains its features',
'short_description' => 'One liner',
'weight' => 1,
'status' => '1',
'visibility' => '4',
'attribute_set_id' => 9,
'type_id' => 'configurable',
'price' => 1200,
'tax_class_id' => 0
);
foreach ($productData as $key => $value) {
$cProduct->setData($key, $value);
}
$cProduct->setStockData(
array(
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 0,
'use_config_manage_stock' => 0
)
);
$cProductTypeInstance = $cProduct->getTypeInstance();
$attribute_ids = array(133);
$cProductTypeInstance->setUsedProductAttributeIds($attribute_ids);
$attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
foreach ($attributes_array as $key => $attribute_array) {
$attributes_array[$key]['use_default'] = 1;
$attributes_array[$key]['position'] = 0;
if (isset($attribute_array['frontend_label'])) {
$attributes_array[$key]['label'] = $attribute_array['frontend_label'];
} else {
$attributes_array[$key]['label'] = $attribute_array['attribute_code'];
}
}
$cProduct->setConfigurableAttributesData($attributes_array);
$dataArray = array();
foreach ($simpleProducts as $simpleArray) {
$dataArray[$simpleArray['id']] = array();
foreach ($attributes_array as $key => $attrArray) {
array_push(
$dataArray[$simpleArray['id']],
array(
"attribute_id" => $simpleArray['attr_id'][$key],
"label" => $simpleArray['label'][$key],
"is_percent" => 0,
"pricing_value" => $simpleArray['pricing_value'][$key]
)
);
}
}
$cProduct->setConfigurableProductsData($dataArray);
$cProduct->setCanSaveConfigurableAttributes(true);
$cProduct->setCanSaveCustomOptions(true);
$cProduct->save();
The Error is like this
Product ID 126 is already added in database in previous session. And previous session went well adding all necessary products.
Magento will not allow you to update configurable products. So for resolve it just add below code
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
before
$cProduct->setConfigurableAttributesData($attributes_array);
So your final code will be
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
$cProduct->setConfigurableAttributesData($attributes_array);
Note: Change $productId variable according to your code. You have to pass product id here.

Creating a bundled product with Magento

I've been following along with this example: Magento programmaticaly create bundle Product
and the code is working when I create a new product, however, I can't get it to work when I load a product either bundled or simple. [EDIT] I can load a bundled product that I created programmatically through the code below and add products to the bundle. A bundled product I created through the GUI I cannot add products too.
Any idea how I can load a product up then bundle it with another a product?
Here is my current code:
$items = array();
$items[] = array(
'title' => 'Bundle Option',
'option_id' => '',
'delete' => '',
'type' => 'radio',
'required' => 1,
'position' => 0,
);
$selectionRawData = array();
$selectionRawData[0] = array();
$selectionRawData[0][] = array(
'selection_id' => '',
'option_id' => '',
'product_id' => 3,
'delete' => '',
'selection_price_value' => 0,
'selection_price_type' => 0,
'selection_qty' => 1,
'selection_can_change_qty' => 0,
'position' => 0,
'is_default' => 1,
);
$selections = $selectionRawData;
$websiteIDs = array(1);
$cats = array(4);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
// load product
// NOT WORKING
$product = Mage::getModel('catalog/product');
$product->load(127);
// new product
/******
* THIS WORKS
$p = array(
'sku_type' => 1,
'sku' => '123321',
'name' => "BarProduct",
'description' => 'Foo',
'short_description' => 'Bar',
'type_id' => 'bundle',
'attribute_set_id' => 4,
'weight_type' => 0,
'visibility' => 4,
'price_type' => 1,
'price_view' => 0,
'price' => 1.99,
'has_options' => 1,
'required_options' => 1,
'status' => 1,
'created_at' => strtotime('now'),
'category_ids' => $cats,
'store_id' => 0,
'website_ids' => $websiteIDs,
'weight' => 0,
'weight_type' => 1,
'delivery_time' => '',
'generate_meta' => 1,
'tax_class_id' => 1, //19%
);
$product->setData($p);
*****/
Mage::register('product', $product);
Mage::register('current_product', $product);
$product->setCanSaveConfigurableAttributes(false);
$product->setCanSaveCustomOptions(true);
$product->setBundleOptionsData($items);
$product->setBundleSelectionsData($selections);
$product->setCanSaveCustomOptions(true);
$product->setCanSaveBundleSelections(true);
$product->setAffectBundleProductSelections(true);
$product->save();
$result['product_name'] = $product->getId();
return $result;
This is important for bundled products:
$product->setData("price_type", 0);
You must set this attribute to 0 (Dynamic price) before saving.
Reindexing is then necessary of course.
I had some funky stuff going on with my product index. I deleted all my products and fixed my index and this now works, albeit not well.
So here is what I gleaned from the process:
If you want to take two simple products and bundle them, you'll need to create a new bundled bundled product via the $p = array code above, then add both simple products.
Otherwise, you'll need a bundled product that is premade via the magento gui. then you'll have bring up that product using the $product->load(product_id) command, then add your simple products to that.
Just delete all unneeded options like this:
$optionsselectionsmap = array();
$options = Mage::getModel("bundle/option")->getCollection()->setProductIdFilter($product->getId());
foreach($options as $option){
$selection = Mage::getModel("bundle/selection")->getCollection()->setOptionIdsFilter($option->getId())->getFirstItem();
$tmp = array();
$tmp['option_id'] = $option->getId();
$tmp['selection_id'] = $selection->getData('selection_id');
$optionsselectionsmap[$selection->getData('sku')] = $tmp;
}
$deleteoptionids = array();
foreach($optionsselectionsmap as $k=>$v) $deleteoptionids[] = $v['option_id'];
foreach($product->getTypeInstance(true)->getOptionsCollection($product) as $deleteitem){
$deleteitem = $deleteitem->getData();
$deleteitem['delete'] = 1;
$bundleOptions[] = $deleteitem;
}

drupal measure author's publication efficiensy drupal 7

I have made a drupal 7 site.
I'm looking for a solution for measuring the authors (blog writers, article writers) efficiensy.
I would like to see someweher, how many nodes are created by a user (author) per month and how many letters do these nodes contain.
Can you suggest me a modul or something else?
Thanks,
Tamás
Here is my solution:
<?php
/**
* Implements hook_menu().
*/
function authors_efficiency_menu() {
$items = array();
$items['admin/config/authors_efficiency'] = array(
'title' => 'Own Settings',
'description' => 'Parent item',
'position' => 'left',
'weight' => -100,
'page callback' => 'system_admin_menu_block_page',
'page arguments' => array(),
'access arguments' => array('access administration pages'),
'file' => 'system.admin.inc',
'file path' => drupal_get_path('module', 'system'),
);
// Need at least one child item before your section will appear.
$items['admin/config/authors_efficiency/efficiency'] = array(
'title' => 'Authors efficiency',
'description' => 'Authors efficiency',
'page callback' => 'authors_efficiency_page_callback',
'page arguments' => array(),
'access arguments' => array('access administration pages'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function authors_efficiency_page_callback($para=array()){
$output= '';
// define number of results per page
$num_per_page = 50;
$header = array('User','Month','Count','Length sum','Avarage length');
// define sql to fetch results
$query= db_select('node','n');
$query->condition('n.status', '1');
$query->condition('n.created', (time()-(120*24*60*60)), '>');
$query->join('field_data_body', 'b', 'n.nid = b.entity_id');
$query->join('users', 'u', 'n.uid = u.uid');
$query->condition('b.entity_type', 'node');
$query->addExpression('CONCAT(YEAR(FROM_UNIXTIME(n.created)),\'-\',LPAD(MONTH(FROM_UNIXTIME(n.created)), 2, \'0\'))', 'node_month');
$query->addExpression('SUM(CHAR_LENGTH(b.body_value))', 'node_char_length');
$query->addExpression('COUNT(*)', 'node_count');
$query->fields('n', array('uid'));
$query->fields('u', array('name'));
$query->groupBy('CONCAT(n.uid, \'#\', node_month)');
$query->orderBy('node_month', 'DESC');
$query->orderBy('u.name', 'ASC');
$count_query= db_select('node','n');
$count_query->condition('n.status', '1');
$count_query->condition('n.created', (time()-(120*24*60*60)), '>');
$count_query->addExpression('COUNT(*)', 'node_count');
$count_query->fields('n', array('uid'));
$count_query->groupBy('CONCAT(n.uid, \'#\', CONCAT(YEAR(FROM_UNIXTIME(n.created)),\'-\',LPAD(MONTH(FROM_UNIXTIME(n.created)), 2, \'0\')))');
$count_query = $count_query->countQuery();
$maxCount = $count_query->execute()->fetchField();;
$page = pager_default_initialize($maxCount, $num_per_page);
$offset = $num_per_page * $page;
$query->range($offset, $num_per_page);
$result= $query->execute()->fetchAll();
$rows = array();
foreach($result as $record){
$row = array(
$record->name,
$record->node_month,
$record->node_count,
$record->node_char_length,
round($record->node_char_length/$record->node_count),
);
$rows[] = $row;
}
// Depending on the context there may be a better choice than this
$output.= theme('table', array('header' => $header, 'rows' => $rows));
$output.= theme('pager');
return($output);
}
?>

Add a checkbox to product image gallery (like "Disable/Exclude")

I'm trying to code a new checkbox to be appended to the columns in the image gallery, beside "Disable". Its behavior would be the same as "Disable/Exclude" = Yes/No with entry in the database.
The idea is to add a "Use as page" checkbox for each image in the image gallery. The goal being to make a JS carousel with all pictures checked as "Use as page".
I have a few things done but I cannot :
update data in the database => set 0 or 1 to the "page" field (see below)
retrieve data from the database and then check/uncheck the checkbox depending on the "page" field.
--> So my question is : how to update data in the database and retrieve it in the checkbox (0 or 1 depending on the field value) ?
Thanks all for your very precious help.
Here is what I've done (1.4.1.0) :
1- Update table catalog_product_entity_media_gallery_value
Added a new field (which name is "page") :
page tinyint(4) UNSIGNED No 0
2- Made the following changes to class Mage_Catalog_Model_Product_Attribute_Backend_Media
Line 49 :
from
$localAttributes = array('label', 'position', 'disabled');
to
$localAttributes = array('label', 'position', 'disabled', 'page');
Line 223 :
from
$data['disabled'] = (int) $image['disabled'];
to
$data['disabled'] = (int) $image['disabled'];
$data['page'] = (int) $image['page'];
Line 301
from
$mediaGalleryData['images'][] = array(
'file' => $fileName,
'position' => $position,
'label' => '',
'disabled' => (int) $exclude
);
to
$mediaGalleryData['images'][] = array(
'file' => $fileName,
'position' => $position,
'label' => '',
'disabled' => (int) $exclude,
'page' => (int) $exclude,
);
Line 328
from
$fieldsMap = array(
'label' => 'label',
'position' => 'position',
'disabled' => 'disabled',
'exclude' => 'disabled',
);
to
$fieldsMap = array(
'label' => 'label',
'position' => 'position',
'disabled' => 'disabled',
'exclude' => 'disabled',
'page' => 'disabled',
);
3- Made the following changes to template adminhtml/default/default/template/catalog/product/helper/gallery.phtml
Line 64
from
<th><?php echo Mage::helper('catalog')->__('Exclude') ?></th>
to
<th><?php echo Mage::helper('catalog')->__('Exclude') ?></th>
<th><?php echo Mage::helper('catalog')->__('Is Page') ?></th>
Line 77
from
<td class="cell-disable a-center"><input type="checkbox" <?php if($_block->getElement()->getReadonly()):?> disabled="disabled"<?php endif;?> onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')" /></td>
to
<td class="cell-disable a-center"><input type="checkbox" <?php if($_block->getElement()->getReadonly()):?> disabled="disabled"<?php endif;?> onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')" /></td>
<td class="cell-page a-center"><input type="checkbox" <?php if($_block->getElement()->getReadonly()):?> disabled="disabled"<?php endif;?> onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')" /></td>
Line 105
from
to
<td class="cell-disable"><input type="hidden" /> </td>
<td class="cell-page last"><input type="hidden" /> </td>
This is how I solved the problem and is working perfectly. Beside your changes make these too.
1. In Mage_Catalog_Model_Product_Attribute_Backend_Media
change
public function addImage(Mage_Catalog_Model_Product $product, $file,
$mediaAttribute = null, $move = false, $exclude = true)
to
public function addImage(Mage_Catalog_Model_Product $product, $file,
$mediaAttribute = null, $move = false, $exclude = true, $page = false)
change
public function addImagesWithDifferentMediaAttributes(Mage_Catalog_Model_Product $product,
$fileAndAttributesArray, $filePath = '', $move = false, $exclude = true)
to
public function addImagesWithDifferentMediaAttributes(Mage_Catalog_Model_Product $product,
$fileAndAttributesArray, $filePath = '', $move = false, $exclude = true, $page = true)
change
$savedFileName = $this->addImage($product, $filePath . $value['file'], null, $move, $exclude);
to
$savedFileName = $this->addImage($product, $filePath . $value['file'], null, $move, $exclude, $page );
2. Go to Mage_Catalog_Model_Resource_Product_Attribute_Backend_Media
change
array('label','position','disabled')
to
array('label','position','disabled','page')
change
array(
'label_default' => 'label',
'position_default' => 'position',
'disabled_default' => 'disabled',
)
to
array(
'label_default' => 'label',
'position_default' => 'position',
'disabled_default' => 'disabled',
'page_default' => 'page'
)
3. In js/mage/adminhtml/product.js
change
this.getFileElement(file, 'cell-label input').value = image.label;
this.getFileElement(file, 'cell-position input').value = image.position;
this.getFileElement(file, 'cell-remove input').checked = (image.removed == 1);
this.getFileElement(file, 'cell-disable input').checked = (image.disabled == 1);
to
this.getFileElement(file, 'cell-label input').value = image.label;
this.getFileElement(file, 'cell-position input').value = image.position;
this.getFileElement(file, 'cell-remove input').checked = (image.removed == 1);
this.getFileElement(file, 'cell-disable input').checked = (image.disabled == 1);
this.getFileElement(file, 'cell-page input').checked = (image.page == 1);
change
this.images[index].label = this
.getFileElement(file, 'cell-label input').value;
this.images[index].position = this.getFileElement(file,
'cell-position input').value;
this.images[index].removed = (this.getFileElement(file,
'cell-remove input').checked ? 1 : 0);
this.images[index].disabled = (this.getFileElement(file,
'cell-disable input').checked ? 1 : 0);
to
this.images[index].label = this
.getFileElement(file, 'cell-label input').value;
this.images[index].position = this.getFileElement(file,
'cell-position input').value;
this.images[index].removed = (this.getFileElement(file,
'cell-remove input').checked ? 1 : 0);
this.images[index].page = (this.getFileElement(file,
'cell-page input').checked ? 1 : 0);
this.images[index].disabled = (this.getFileElement(file,
'cell-disable input').checked ? 1 : 0);
Simply use search text to find where to change the code. Hope this helped.
After much toil I discovered that in addition to the original post and the 2nd poster's recommendations, you also need to open up /app/code/core/Mage/Catalog/sql/catalog_setup/mysql4-upgrade-1.5.9.9-1.6.0.0.php, go to around line 2023 where it starts with this:
$installer->getTable('catalog/product_attribute_media_gallery_value') => array(
Change this:
'disabled' => array(
'type' => Varien_Db_Ddl_Table::TYPE_SMALLINT,
'unsigned' => true,
'nullable' => false,
'default' => '0',
'comment' => 'Is Disabled'
)
To this:
'disabled' => array(
'type' => Varien_Db_Ddl_Table::TYPE_SMALLINT,
'unsigned' => true,
'nullable' => false,
'default' => '0',
'comment' => 'Is Disabled'
),
'page' => array(
'type' => Varien_Db_Ddl_Table::TYPE_SMALLINT,
'unsigned' => true,
'nullable' => false,
'default' => '0',
'comment' => 'Page'
)
When Magento saves it checks this file to make sure the fields getting passed match the values in these arrays.
I got the error
Notice: Undefined index 'page'
in the class
Mage_Catalog_Model_Product_Attribute_Backend_Media
in the line 224.
I had to change
js/mage/adminhtml/product.js
newImage.position = this.getNextPosition();
to
newImage.position = this.getNextPosition();
newImage.page = 0;
It works great now.
Thanks.
I was working on something similar recently, and found that this piece of code was part of the solution:
$fieldset->addField('entire_range', 'checkbox', array(
'checked' => $this->getEntireRange()==1 ? 'true' : 'false',
'onclick' => 'this.value = this.checked ? 1 : 0;'
));
I couldn't get it to save the value to the database either. It's something to with the Varien_Data_Form_Element_Checkbox class.
Hope this helps, please post your solution if you find it!
Cheers,
JD

Resources