I am trying to create a custom form field naming as city. On select of country field, city field should populate options of all the provinces listed under the selected country.
Just exactly as the Joomla documentation.
I am following https://docs.joomla.org/Creating_a_custom_form_field_type documentation.
<?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
JFormHelper::loadFieldClass('list');
class JFormFieldCity extends JFormFieldList {
protected $type = 'City';
public function getOptions() {
$app = JFactory::getApplication();
//country is the dynamic value which is being used in the view
$country = $app->input->get('country');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('a.cityname')
->from('`#__tablename` AS a')
->where('a.country = "'.$country.'" ');
$rows = $db->setQuery($query)->loadObjectlist();
foreach($rows as $row){
$cities[] = $row->cityname;
}
// Merge any additional options in the XML definition.
$options = array_merge(parent::getOptions(), $cities);
return $options;
}
}
However, I can see $country = $app->input->get('country'); is not working.
At view, I have a country field.
I'm trying to do this to get the "floor" value of my node :
$type = "desk";
$floor = '2';
$nodes = node_load_multiple(array(), array('field_floor["und"][0]["value"]' => $floor, 'type' => $type));
I can get all my desk if I'm just doing $nodes = node_load_multiple(array(), array('type' => $type)); and I can find a deck with for exemple the title, but is it possible to go through the arrays to get the 'value' and check it in the query ?
Thank you for your answers.
To get value of a field you have multiple methods :
Field get item:
$nid = 2;
$node = node_load($nid);
$floor = field_get_items($node , 'node', 'field_floor');
$floor = reset($floor); // or loop on it, here take first value if multiple
echo $floor['value'];
https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_get_items/7.x
Entity metadata wrapper:
$nid = 2;
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$floor = $wrapper->field_floor->value();
echo $floor;
https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers
Direct way :
global $language; // take current language
$nid = 2;
$node = node_load($nid);
echo $node->field_floor[$language->language][0]['value'];
i am submitting the location from textbox and putting values in comma seprated form like ngp,akola,kanpur.
Now i want if i have 3 values in location textbox then it insert 3 rows in location table one for ngp,second for akola and third for kanpur.
but it also takes last inserted id of user table and post all values in location table.
my location table have fields id,name,user_id.
in user_id column i need the last inserted id of user table and in name column i need to insert all values in table..
please help me to do this..below is my code.
function add() {
if (!empty($this->request->data)) {
$this->User->set($this->data['User']);
$isValidated = $this->User->validates();
if ($isValidated) {
// Generating UUID
if (!empty($this->request->data['User']['company_name'])) {
$this->request->data['User']['is_business'] = 1;
}
if ($this->User->save($this->request->data, array('validate' => false))) {
$lastId = $this->User->id;
$location = implode(',',$this->request->data['User']['location']);
for(i=1;i<=$location;i++){
$this->Location->save($location);
}
}
}
}
}
$lastId = $this->User->id;
$location = explode(',',$this->request->data['User']['location']);
foreach($location as $value){
$data = array();
$data["name"] = $value;
$data["user_id"] = $lastId;
$this->Location->save($data,false);
$this->Location->id = false;
}
Model::saveAll(array $data = null, array $options = array())
$this->request->data['Location'] = explode(',',$this->request->data['User']['location']);
if ($this->User->saveAll($this->request->data, array('validate' => false))){ // ...}
I'am trying to add node programmatically with term reference Auto complete term widget (tagging) and add new tag my code not work
when I remove tag reference from code ,my node add successfully
I need add new tag each node
<?php
$bodytext = "body?";
$node = new stdClass(); // Create a new node object
$node->type = "programstvradio"; // Or page, or whatever content type you like
node_object_prepare($node); // Set some default values
// If you update an existing node instead of creating a new one,
// comment out the three lines above and uncomment the following:
// $node = node_load($nid); // ...where $nid is the node id
$node->title = "title";
$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
$node->uid = 1; // UID of the author of the node; or use $node->name
$node->body[$node->language][0]['value'] = $bodytext;
$node->body[$node->language][0]['format'] = 'filtered_html';
// I prefer using pathauto, which would override the below path
$path = 'node_created_on' . date('YmdHis');
$node->path = array('alias' => $path);
$node->field_tag_[$node->language][]['value'] ='tagggggggg';
$node->field_catprogram[$node->language][]['tid'] =12;
$file_path = drupal_realpath('C:\Users\Admin\Desktop\drupal.png'); // Create a File object'); // Create a File object
$file = (object) array(
'uid' => 1,
'uri' => $file_path,
'filemime' => file_get_mimetype($file_path),
'status' => 1,
);
$file = file_copy($file, 'public://images'); // Save the file to the root of the files directory. You can specify a subdirectory, for example, 'public://images'
$node->field_image[LANGUAGE_NONE][0] = (array)$file; //associate the file object with the image field:
if($node = node_submit($node)) { // Prepare node for saving
node_save($node);
echo "Node with nid " . $node->nid . " saved!\n";
}
?>``
i find solution
$my_term_name = 'gggg';
$term_array = taxonomy_get_term_by_name($my_term_name);
if($term_array == array()){
//empty term ..
$term->name = $my_term_name;
$term->vid = 1;
taxonomy_term_save($term);
$term_array = taxonomy_get_term_by_name($my_term_name);
}
//get the first index of the array .
foreach ($term_array as $tid => $term_object)break;
$node->field_progna['und'][$tid] = (array)$term_object;
I want to add a "field collection" dynamically. But I'm not familiar with Field API or Entity API. New Entity API in Drupal is very poorly documented.
Here is my code, until now:
$node = node_load(1);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_book_text'));
$field_collection_item->setHostEntity('node', $node);
// Adding fields to field_collection
$field_collection_item.save();
"Field Collection" module use function "entity_form_submit_build_entity" which I cannot use because there is no form in my case.
I would appreciate if you can tell me how can I add fields?
Based on some code I used in a live project:
// Create and save research field collection for node.
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_article_references'));
$field_collection_item->setHostEntity('node', $node);
$field_collection_item->field_reference_text[$node->language][]['value'] = 'ABCD';
$field_collection_item->field_reference_link[$node->language][]['value'] = 'link-val';
$field_collection_item->field_reference_order[$node->language][]['value'] = 1;
$field_collection_item->save();
Anyone using the above code samples should consider using the entity_metadata_wrapper function from the Entity API to set the values of fields on an entity instead of using an assignment operator. So, the code from the "more complete example" above would be:
if ($node->field_collection[LANGUAGE_NONE][0]) {
// update
$fc_item = reset(entity_load('field_collection_item', array($node->field_collection[LANGUAGE_NONE][0]['value'])));
}
else {
// create
$fc_item = entity_create('field_collection_item', array('field_name' => 'field_collection'));
$fc_item->setHostEntity('node', $node);
}
// Use the Entity API to "wrap" the field collection entity and make CRUD on the
// entity easier
$fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);
// ... set some values ...
$fc_wrapper->field_terms->set('lars-schroeter.com');
// save the wrapper and the node
// Note that the "true" is required due to a bug as of this time
$fc_wrapper->save(true);
node_save($node);
A more complete example:
if ($node->field_collection[LANGUAGE_NONE][0]) {
// update
$fc_item = reset(entity_load('field_collection_item', array($node->field_collection[LANGUAGE_NONE][0]['value'])));
}
else {
// create
$fc_item = entity_create('field_collection_item', array('field_name' => 'field_collection'));
$fc_item->setHostEntity('node', $node);
}
// ... set some values ...
$fc_item->field_terms[LANGUAGE_NONE][0]['value'] = 'lars-schroeter.com';
// save node and field-collection
$node->field_collection[LANGUAGE_NONE][0] = array('entity' => $fc_item);
node_save($node);
You don't need to call node_save($node) when using entity_metadata_wrapper. It will ensure that only the entity's data and the reference to the host are saved without triggering any node_save, which is a good performance boost.
However, you would still need node_save() if you have any node_save-triggered actions that use this field collection (e.g. a rule that sends emails when the node is edited).
use the wrappers, they are your friend:
// Create an Entity
$e = entity_create('node', array('type' => 'CONTENT_TYPE'));
// Specify the author.
$e->uid = 1;
// Create a Entity Wrapper of that new Entity
$entity = entity_metadata_wrapper('node',$e);
// Specify the title
$entity->title = 'Test node';
// Add field data... SO MUCH BETTER!
$entity->field_FIELD_NAME->set(1111);
// Save the node.
$entity->save();
You can find Entity API documented in Entity API Tutorial at Drupal.org.
There you can find some useful examples, especially check for Entity metadata wrappers page.
Here is example based on your variables:
$node = node_load(1);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_book_text')); // field_book_text is field collection
$field_collection_item->setHostEntity('node', $node);
$cwrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);
// Adding fields to field_collection
$cwrapper->field_foo_text->set("value");
$cwrapper->field_foo_multitext->set(array("value1", "value2"));
$cwrapper.save();
Here is another example using field collections from above docs page:
<?php
// Populate the fields.
$ewrapper = entity_metadata_wrapper('node', $node);
$ewrapper->field_lead_contact_name->set($contact_name);
$ewrapper->field_lead_contact_phone->set($contact_phone);
$ewrapper->field_lead_contact_email->set($contact_email);
// Create the collection entity and set it's "host".
$collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
$collection->setHostEntity('node', $node);
// Now define the collection parameters.
$cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
$cwrapper->field_facility->set(intval($offset));
$cwrapper->save();
// Save.
$ewrapper->save();
?>
Here is more advanced example of mine which for given entity it loads taxonomy term references from field_rs_property_features, then for each secondary term which has a parent term, adds its term name and its parent term name into field_feed_characteristics_value by grouping them together into title (parent) and value (child). It's probably more difficult to explain without seeing the code. So here it is:
/**
* Function to set taxonomy term names based on term references for given entity.
*/
function MYMODULE_refresh_property_characteristics(&$entity, $save = FALSE) {
try {
$w_node = entity_metadata_wrapper('node', $entity);
$collections = array();
foreach ($w_node->field_rs_property_features->getIterator() as $delta => $term_wrapper) {
if ($term_wrapper->parent->count() > 0) {
$name = $term_wrapper->name->value();
$pname = $term_wrapper->parent->get(0)->name->value();
if (array_key_exists($pname, $collections)) {
$collections[$pname]->field_feed_characteristics_value[] = $name;
} else {
// Create the collection entity, set field values and set it's "host".
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_feed_characteristics'));
$field_collection_item->setHostEntity('node', $w_node->value());
$collections[$pname] = entity_metadata_wrapper('field_collection_item', $field_collection_item);
$collections[$pname]->field_feed_characteristics_title = $pname;
$collections[$pname]->field_feed_characteristics_value = array($name);
}
}
}
if ($save) {
$w_node->save();
}
} catch (Exception $e) {
drupal_set_message(t('Error setting values for field collection: #title, message: #error.',
array('#title' => $w_node->title->value(), '#error' => $e->getMessage())), 'error');
watchdog_exception('MYMODULE', $e);
return FALSE;
}
return TRUE;
}