I am trying to programatically add products to my drupal commerce store. So far I have been able to add products that contain basic information ( such as sku, title, and price ). How would I be able to add field data, such as images and other field types, using drupal's api.
The code I used to add the products is derived from the commerce_examples/product_example module.
<?php
/**
* #file product_example.module
* Demonstrates pricing hooks, etc.
*/
/**
* Implements hook_menu().
*
* Simply presents a page that will explain what this module is for.
* hook_menu() has nothing to do with the checkout page functionality.
*/
function product_example_menu() {
$items['commerce_examples/product_example'] = array(
'title' => 'Product Example',
'page callback' => 'drupal_get_form',
'page arguments' => array('product_example_info_page'),
'access callback' => TRUE,
);
return $items;
}
/**
* This form provides a way to interact with some of the example functions
* provided here.
*/
function product_example_info_page($form, &$form_state) {
$form['explanation'] = array(
'#type' => 'item',
'#markup' => t('This example demonstrates product creation and manipulation.'),
);
$form['product_creation'] = array(
'#type' => 'fieldset',
'#title' => t('Please create a product for use with this example'),
);
$types = commerce_product_types();
$form['product_creation']['product_type'] = array(
'#type' => 'select',
'#title' => t('Product type for product to be created'),
'#options' => drupal_map_assoc(array_keys($types)),
);
$form['product_creation']['title'] = array(
'#title' => t('Product title'),
'#type' => 'textfield',
'#default_value' => t('A dummy product for use with product_example'),
);
$form['product_creation']['price'] = array(
'#title' => t('Product price'),
'#type' => 'textfield',
'#description' => t('A price in decimal format, without a currency symbol'),
'#default_value' => '100.00',
);
$form['product_creation']['product_creation_submit'] = array(
'#type' => 'submit',
'#value' => t('Create product'),
'#submit' => array('product_example_product_creation_submit')
);
return $form;
}
/**
* Submit handler for creating a product.
*/
function product_example_product_creation_submit($form, &$form_state) {
$extras = array(
'sku' => 'product_example_' . drupal_hash_base64(microtime()),
'status' => TRUE,
'uid' => $GLOBALS['user']->uid,
'title' => $form_state['values']['title'],
);
// Use the product example's creation function to create a product.
$product_id = product_example_create_product($form_state['values']['product_type'], $form_state['values']['price'], $extras);
drupal_set_message(t('Created sample product with title !title and sku !sku', array('!title' => l($extras['title'], 'admin/commerce/products/' . $product_id), '!sku' => $extras['sku'])));
}
/**
* Create a product programmatically.
*
* This is stolen shamelessly from commerce_bpc. Thanks for the help here!
*
* #param $product_type
* (string) The name of the product type for which products should be created.
* #param $price
* Decimal amount of price. If additional fields need to be populated they
* can be populated in exactly the same way as the commerce_price field.
* #param $extras
* An array for the values of 'extra fields' defined for the product type
* entity, or patterns for these. Recognized keys are:
* - status
* - uid
* - sku
* - title
* Note that the values do NOT come in the form of complex arrays (as they
* are not translatable, and can only have single values).
* #return
* The ID of the created product.
*/
function product_example_create_product($product_type, $price, $extras) {
$form_state = array();
$form_state['values'] = array();
$form = array();
$form['#parents'] = array();
// Generate a new product object
$new_product = commerce_product_new($product_type);
$new_product->status = $extras['status'];
$new_product->uid = $extras['uid'];
$new_product->sku = $extras['sku'];
$new_product->title = $extras['title'];
$new_product->created = $new_product->changed = time();
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
'amount' => $price * 100,
'currency_code' => commerce_default_currency(),
)));
$form_state['values']['commerce_price'] = $price;
// Notify field widgets to save their field data
field_attach_submit('commerce_product', $new_product, $form, $form_state);
commerce_product_save($new_product);
return $new_product->product_id;
}
Using the same format the examples uses to add price data:
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
'amount' => $price * 100,
'currency_code' => commerce_default_currency(),
)));
I was able to add other field data, however I am still having trouble adding data to the field_productimage field that all commerce products come with by default.
I can suggest you about other fields data such as extra info related to product. You can add these fields to the product type from the UI or if you are creating product type programmatically then also you can do the same.
Add fields in your form to collect the data e.g -
$form['product_creation']['values'] = array(
'#title' => t('Some data'),
'#type' => 'textfield',
'#description' => t('Dummy data'),
);
Get those data in your function product_example_create_product() by $form_state().
Add them to $new_product object like
$new_product->field_name['und'][0]['value'] = $extras['values'];
Save the product, just like you are doing.
For the image, you will have to follow the method of file attachment. Like -
$file_path = drupal_realpath('image/product_image.png');
$file = (object) array(
'uid' => 1,
'uri' => $file_path,
'filemime' => file_get_mimetype($file_path),
'status' => 1,
);
// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');
$new_product->product_image[LANGUAGE_NONE][0] = (array)$file;
Related
I need to create the customer profile image attribute. Anyone can please help how can I create the customer profile image attribute. I need to create the custom attribute in the custom module and I'm using the data patch file.
public function apply()
{
$this->moduleDataSetup->getConnection()->startSetup();
/** #var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
/** #var $attributeSet Set */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(
Customer::ENTITY,
'profile_image',
[
'label' => 'Profile Image',
'input' => 'text',
'type' => 'file',
'source' => '',
'required' => true,
'position' => 333,
'visible' => true,
'system' => false,
'is_used_in_grid' => true,
'is_visible_in_grid' => true,
'is_filterable_in_grid' => true,
'is_searchable_in_grid' => false,
'backend' => ''
]
);
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'profile_image');
$attribute->addData([
'used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]
]);
$attribute->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId
]);
$attribute->save();
$this->moduleDataSetup->getConnection()->endSetup();
}
When I'm executing the s:up command then it's showing the "Invalid column data type file"
error. Please let me know how can I fix this.
The 'type' parameter must be one of the following:
datetime, decimal, int, text or varchar
Those options corresponds to the customer_entity_* database tables.
Also, there is no standard file 'input' field for customer attributes. You'll need to implement that field input type.
I am using the hook_form_FORM_ID_alter in Drupal 7 to create a custom form so that the user can enter and edit data which is then attached to a custom node type.
For a new node the default number of input boxes in a group is 10, this can then be added to in groups of 5. When the node is reloaded for editing the saved data is used to create the form with whatever number of inputs have been saved previously and also the ability to add more fields in the same manner as required.
I have managed to get both the initial version of the form and the editing version to work using the following code however when the 'add five' button is pressed and the AJAX called (in both cases), any values which have been entered without saving are removed.
<?php
/**
* Implements hook_form_FORM_ID_alter().
*/
function entries_form_form_entries_node_form_alter(&$form, &$form_state, $form_id) {
$node = $form['#node'];
// fieldset
$form["section"] = array(
'#type' => 'fieldset',
'#title'=> 'Section 1',
);
$form["section"]["termwrapper"] = array(
"#type" => 'container',
"#attributes" => array(
"id" => 'groupWrapper',
),
);
$form["section"]["termwrapper"]["terms"]["#tree"] = TRUE;
if(!isset($form_state['fired'])){
$form_state['terms'] = $node->entries_form['term'];
}
foreach ($form_state['terms'] as $key => $values) {
$form["section"]["termwrapper"]["terms"][$key] = array(
'#type' => 'textfield',
'#size' => 20,
'#attributes' => array(
'class' => array('left'),
),
'#value' => $values,
);
}
$form['section']['addFive_button'] = array(
'#type' => 'submit',
'#value' => t('+5'),
'#submit' => array('entries_form_add_five_submit'),
'#ajax' => array(
'callback' => 'entries_form_commands_add_callback',
'wrapper' => 'groupWrapper',
),
'#prefix' => "<div class='clear'></div>",
);
dpm($form_state);
}
function entries_form_commands_add_callback($form, $form_state) {
return $form["section"]["termwrapper"];
}
function entries_form_add_five_submit($form, &$form_state){
$form_state['rebuild'] = TRUE;
$form_state['fired'] = 1;
$values = $form_state['values'];
$form_state['terms'] = $values['terms'];
$numterms = count($values['terms']);
$addfivearray = array_fill($numterms,5,'');
$form_state['terms'] = array_merge($values['terms'],$addfivearray);
}
/**
* Implements hook_node_submit().
*/
function entries_form_node_submit($node, $form, &$form_state) {
$values = $form_state['values'];
$node->entries_form['term'] = $values['term'];
}
/**
* Implements hook_node_prepare().
*/
function entries_form_node_prepare($node) {
if (empty($node->entries_form)){
$node->entries_form['term'] = array_fill(0, 10, '');
}
}
/**
* Implements hook_node_load().
*/
function entries_form_node_load($nodes, $types) {
if($types[0] == 'entries'){
$result = db_query('SELECT * FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)))->fetchAllAssoc('nid');
foreach ($nodes as &$node) {
$node->entries_form['term'] = json_decode($result[$node->nid]->term);
}
}
}
/**
* Implements hook_node_insert().
*/
function entries_form_node_insert($node) {
if (isset($node->entries_form)) {
db_insert('mytable')
->fields(array(
'nid' => $node->nid,
'term' => json_encode($node->entries_form['term']),
))
->execute();
}
}
How can I keep the values which have been typed in and retain the ajax functionality?
Any help or pointers much appreciated. This is my first dip into Drupal so I'm sure there is something which hopefully is quite obvious that I'm missing.
Ok, I think I finally have the answer.
Within the foreach that builds the form input boxes I had set '#value' => $values, when it seems that '#default_value' => $values, should have been set instead.
The updated section of the code that is now working for me is as follows
foreach ($form_state['terms'] as $key => $values) {
$form["section"]["termwrapper"]["terms"][$key] = array(
'#type' => 'textfield',
'#size' => 20,
'#attributes' => array(
'class' => array('left'),
),
'#default_value' => $values,
);
}
Seems to be as simple as that. Hope this helps someone else.
I have been successful creating orders with a Custom controller and all works well. My issue is i need to add the ability to create orders with downloadable product. I would just like to be pointed on where to start.
Controller is handling all the set up and the order save. Is there a Action or something I need to hit for the customer to be able to access his/her downloads?
Try the below Code, please go threw comments.
<?php
require_once 'app/Mage.php';
Mage::app();
$customer = Mage::getModel("customer/customer")
->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
->loadByEmail($data['email']);
if(!$customer->getId()) {
$customer->setEmail($email); //enter Email here
$customer->setFirstname($fname); //enter Lirstname here
$customer->setLastname($lname); //enter Lastnamre here
$customer->setPassword(password); //enter password here
$customer->save();
}
$storeId = $customer->getStoreId();
$quote = Mage::getModel('sales/quote')
->setStoreId($storeId);
$quote->assignCustomer($customer);
// add product(s)
$product = Mage::getModel('catalog/product')->load(186); //product id
/*$buyInfo = array(
'qty' => 1,
'price'=>0
// custom option id => value id
// or
// configurable attribute id => value id
);*/
$params = array();
$links = Mage::getModel('downloadable/product_type')->getLinks( $product );
$linkId = 0;
foreach ($links as $link) {
$linkId = $link->getId();
}
//$params['product'] = $product;
$params['qty'] = 1;
$params['links'] = array($linkId);
$request = new Varien_Object();
$request->setData($params);
//$quoteObj->addProduct($productObj , $request);
/* Bundled product options would look like this:
$buyInfo = array(
"qty" => 1,
"bundle_option" = array(
"123" => array(456), //optionid => array( selectionid )
"124" => array(235)
)
); */
//$class_name = get_class($quote);
//Zend_Debug::dump($class_name);
$quote->addProduct($product, $request);
$addressData = array(
'firstname' => 'Vagelis', //you can also give variables here
'lastname' => 'Bakas',
'street' => 'Sample Street 10',
'city' => 'Somewhere',
'postcode' => '123456',
'telephone' => '123456',
'country_id' => 'US',
'region_id' => 12, // id from directory_country_region table if it Country ID is IN (India) region id is not required
);
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
/*$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('flatrate_flatrate')
->setPaymentMethod('checkmo');*/
/* Free shipping would look like this: */
$shippingAddress->setFreeShipping( true )
->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping')
->setPaymentMethod('checkmo'); /* shipping details is not required for downloadable product */
$quote->setCouponCode('ABCD'); // if required
/* Make Sure Your Check Money Order Method Is Enable */
/*if the product value is zero i mean free product then the payment method is free array('method' => 'free')*/
$quote->getPayment()->importData(array('method' => 'checkmo'));
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Order Created Successfully %s\n", $order->getIncrementId());
I'm creating a custom user settings page. I have one field: zip_code that get's it's initial value from a custom user field. I have a custom function that pulls external data using the value of the zip_code.
I currently have the default value of the field set to the custom user field (if it's available). This is working as designed; however, I want to give the user the ability to change their zip code via an Ajax callback. This would replace the already populated radio buttons with new ones. I can't seem to wrap my head around this. Here's my code:
function settings_shopping_form($form, &$form_state) {
include_once "external.inc";
// Get user fields
global $user;
$user_fields = user_load($user->uid);
$zipcode = $user_fields->zip_code['und']['0']['value'];
if(isset($zipcode)) {
$form['zip_code'] = array(
'#title' => t('Zip Code'),
'#type' => 'textfield',
'#required' => TRUE,
'#default_value' => $zipcode,
'#ajax' => array(
'callback' => 'settings_form_callback',
'wrapper' => 'textfields',
),
);
$storename = getmystorename($zipcode);
if(count($storename) > 0) {
$form['textfields'] = array(
'#prefix' => '<div id="textfields">',
'#suffix' => '</div>',
'#type' => 'fieldset' );
$form['textfields']['stores'] = array(
'#type' => 'radios',
'#title' => t('Choose your store:'),
'#options' => $storename,
'#default_value' => $storename[1], );
} else {
$form['textfields']['incorrect'] = array(
'#title' => t('Sorry, there are no stores available near you. Check back later'),
'#type' => 'fieldset', );
}
}
My callback function is very simple:
function settings_form_callback($form, $form_state) {
return $form['textfields'];
}
To reiterate: I want to add the ability to replace the populated radio buttons with new buttons generated by the getmystorename function when the zip_code field is changed.
I ended up taking an example from the examples module (love it!):
$defaults = !empty($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $zipcode;
$storename = getmystorename($defaults);
I put this before the start of my form so that the values load before the form builder.
How do I add custom options to a product like you can in the backend, using the API.
Im using C# but if you know how do to this in Php, that would be helpful too.
I noticed that product has this:
var product = new catalogProductCreateEntity();
product.options_container = "blah";
And there is this:
catalogAttributeOptionEntity optionEntity = new catalogAttributeOptionEntity();
optionEntity.value = "sds";
optionEntity.label = "ere";
But I cant see a way of utilizing them, im not sure how to make a container, and the catalogAttributeOptionEntity does not have all the properties needed to make a custom option.
Look at the admin product controller. Yes it is possible.
/**
* Initialize data for configurable product
*/
if (($data = $this->getRequest()->getPost('configurable_products_data')) && !$product->getConfigurableReadonly()) {
$product->setConfigurableProductsData(Zend_Json::decode($data));
}
if (($data = $this->getRequest()->getPost('configurable_attributes_data')) && !$product->getConfigurableReadonly()) {
$product->setConfigurableAttributesData(Zend_Json::decode($data));
}
$product->setCanSaveConfigurableAttributes((bool)$this->getRequest()->getPost('affect_configurable_product_attributes') && !$product->getConfigurableReadonly());
/**
* Initialize product options
*/
if (isset($productData['options']) && !$product->getOptionsReadonly()) {
$product->setProductOptions($productData['options']);
}
This is not documented anywhere (else), but at least in Magento 1.6 one can find the appropriate API methods for product options in the source code. (I don 't know since which version that feature exists.)
The API itself is defined in: app/code/core/Mage/Catalog/etc/api.xml
<catalog_product_custom_option translate="title" module="catalog">
<title>Catalog product custom options API</title>
<model>catalog/product_option_api</model>
<acl>catalog/product/option</acl>
<methods>
<add translate="title" module="catalog">
<title>Add new custom option into product</title>
<acl>catalog/product/option/add</acl>
</add>
<update translate="title" module="catalog">
<title>Update custom option of product</title>
<acl>catalog/product/option/update</acl>
</update>
<types translate="title" module="catalog">
<title>Get list of available custom option types</title>
<acl>catalog/product/option/types</acl>
</types>
<info translate="title" module="catalog">
<title>Get full information about custom option in product</title>
<acl>catalog/product/option/info</acl>
</info>
<list translate="title" module="catalog">
<title>Retrieve list of product custom options</title>
<acl>catalog/product/option/list</acl>
<method>items</method>
</list>
<remove translate="title" module="catalog">
<title>Remove custom option</title>
<acl>catalog/product/option/remove</acl>
</remove>
</methods>
</catalog_product_custom_option>
The called functions are defined in: app/code/core/Mage/Catalog/Model/Product/Option/Api.php
class Mage_Catalog_Model_Product_Option_Api extends Mage_Catalog_Model_Api_Resource
{
/**
* Add custom option to product
*
* #param string $productId
* #param array $data
* #param int|string|null $store
* #return bool $isAdded
*/
public function add( $productId, $data, $store = null )
/**
* Update product custom option data
*
* #param string $optionId
* #param array $data
* #param int|string|null $store
* #return bool
*/
public function update( $optionId, $data, $store = null )
/**
* Read list of possible custom option types from module config
*
* #return array
*/
public function types()
/**
* Get full information about custom option in product
*
* #param int|string $optionId
* #param int|string|null $store
* #return array
*/
public function info( $optionId, $store = null )
/**
* Retrieve list of product custom options
*
* #param string $productId
* #param int|string|null $store
* #return array
*/
public function items( $productId, $store = null )
/**
* Remove product custom option
*
* #param string $optionId
* #return boolean
*/
public function remove( $optionId )
/**
* Check is type in allowed set
*
* #param string $type
* #return bool
*/
protected function _isTypeAllowed( $type )
}
The $data-array also is a bit tricky, since it's keys partly depend on the selected option type. The basic $data-array looks like:
$data = array (
'is_delete' => 0,
'title' => 'Custom Option Label',
'type' => 'text',
'is_require' => 0,
'sort_order' => 1,
'additional_fields' => array (
0 => array (
'price' => '10.0000',
'price_type' => 'fixed', // 'fixed' or 'percent'
'sku' => '',
),
),
);
The additional_fields always conatin at least one row with at least the columns price, price_type and sku. More additional fields (maf: …) may be added depending on the type. The types in the group select may have more than one row specified in additional_fields. The custom option types/type-groups are:
text (maf: 'max_characters')
field
area
file (maf: 'file_extension', 'image_size_x', 'image_size_y')
file
select (maf: 'value_id', 'title', 'sort_order')
drop_down
radio
checkbox
multiple
date
date
date_time
time
Examples for complete option data arrays:
// type-group: select, type: checkbox
$data = array (
'is_delete' => 0,
'title' => 'extra Option for that product',
'type' => 'checkbox',
'is_require' => 0,
'sort_order' => 1,
'additional_fields' => array (
0 => array (
'value_id' => '3',
'title' => 'Yes',
'price' => 10.00,
'price_type' => 'fixed',
'sku' => NULL,
'sort_order' => 1,
),
1 => array (
'value_id' => 3,
'title' => 'No',
'price' => 0.00,
'price_type' => 'fixed',
'sku' => NULL,
'sort_order' => 2,
),
),
);
// type-group: text, type: field
$data = array (
'is_delete' => 0,
'title' => 'Custom Option Label',
'type' => 'text',
'is_require' => 0,
'sort_order' => 1,
'additional_fields' => array (
0 => array (
'price' => 10.00,
'price_type' => 'fixed',
'sku' => NULL,
'max_characters' => 150,
),
),
);
In the end I decided it cant be done via the API and went to the database directly.