Inserting node field value programmatically in drupal 7 - drupal-7

I'm trying to insert values for a node field from a custom module. The value will only be inserted from that module and then no operation for that node will be performed, so hook is not in my consideration. I've tried to directly insert values to the field_data_... and field_revision_... tables. but I've found that drupal also saves the values (serialized) in field_config and field_config_instance tables as blob. since I'm only inserting values in two tables drupal is not reading values I've inserted for nodes. I couldn't understand the serialization stored in DB. so I'm searching for a method that will help me to insert values through API or any other neat way.
any help on the thing I'm trying to accomplish would be great. Thank you
EDIT:
after taking look at serialized content of field_config table I understood that the serialized data is just field configuration and get inserted into the table on first save. My problem solved by saving the first value through admin/content and now my direct DB inserted data is available to the node. this is the serialized data I've got:
a:7:
{s:12:"translatable";
s:1:"0";
s:12:"entity_types";
a:0:{}
s:8:"settings";
a:3:
{s:9:"precision";
s:2:"10";s:5:"scale";
s:1:"2";
s:17:"decimal_separator";
s:1:",";
}
s:7:"storage";
a:5:
{s:4:"type";
s:17:"field_sql_storage";
s:8:"settings";
a:0:{}
s:6:"module";
s:17:"field_sql_storage";
s:6:"active";
s:1:"1";
s:7:"details";
a:1:
{s:3:"sql";
a:2:
{s:18:"FIELD_LOAD_CURRENT";
a:1:
{s:22:"field_data_field_total";
a:1:
{s:5:"value";
s:17:"field_total_value";
}
}
s:19:"FIELD_LOAD_REVISION";
a:1:
{s:26:"field_revision_field_total";
a:1:
{s:5:"value";
s:17:"field_total_value";
}
}
}
}
}
s:12:"foreign keys";
a:0:{}
s:7:"indexes";
a:0:{}
s:2:"id";
s:2:"34";
}

Hope this will help you.
$node = new stdClass();
$node->uid = 1;
$node->name = 'admin';
$node->type = 'page';
$node->language = 'und';
$node->title = 'Your title';
$node->status = 1;
$node->promote = 0;
$node->sticky = 0;
$node->created = timestamp;
$node->field_description = array(
'und' => array(
array(
'value' => 'asdasd'
)
)
);
$node->nid = 1; // define nid if you wish to update existing node
// if you wouldn't define $node->nid then new node would be created,
// otherwise node would be updated with you data provided for all
// fields which you'll list here.
...
// other node's fields
node_save_action($node);

Related

Storing single data values in the database

I wanted to know what the best way is to store single data values in a database. Values you only need one field of.
I have a couple of ideas.
Storing all fields in a single_data_table with a id, key and value column.
Storing it as a json object in the database.
Storing it as an array in the database.
Which one is the best way? Or might there even be better ways?
Or is it just easier to keep single data values as static data on the webpage?
At my current job we use a separate settings table for that, with two columns: key and value. And then there's a simple function to retrieve or save a setting:
function setting($key, $value = null){
$setting = DB::table('settings')->where('key', $key)->first();
if(is_null($value)){
return $setting->value ?? null;
}
if(isset($setting)){
$setting->value = $value;
}else{
$setting = $setting ?: new stdClass();
$setting->key = $key;
$setting->value = $value;
}
DB::table('settings')->insertOrReplace((array) $setting);
return true;
}
It is used like so:
$phone = setting('phone'); // Get the phone setting
$url = setting('url', 'http://example.com'); // Set url setting

Cakephp2. save data is adding two more rows

public function index($tin=null) {
$this->layout = 'index_1';
$this->loadModel('Insurance');
$this->loadModel('Verification');
$this->loadModel('Insurance_price');
$date = date('Y-m-d');
$verification_fee=$this->Insurance_price->findByInsurance_type("Third Party Auto Insurance");
$ver = $verification_fee['Insurance_price']['verification_amount'];
if(!empty($tin)) {
$this->request->data['tin'] = $tin;
$this->request->data['amount'] = $ver;
$this->request->data['date'] = date('Y-m-d');
$this->Verification->save($this->request->data);
$this->Verification->clear($this->request->data);
}
}
That's my controller. I am trying to save those data once the page loads.
But when I check the database table instead of seeing only 1 new record I see 3 new rows with the same data as 'amount' and 'date', except for tin column which will have 'image'.
What could I be doing wrong?
try inserting
$this->Verification->create();
before
$this->Verification->save($this->request->data);
And check

drupal_write_record doesn't take object

In drupal 6 i used to do something like this:
<?php
/*
* CLASS Example
*/
class example {
var $id = NULL;
var $title;
var $body;
.....
// Save
function save() {
$primary_key = ($this->id == NULL ? NULL : 'id');
if (drupal_write_record('mytabble', $this, $primary_key)) {
return TRUE;
} else {
return FALSE;
}
}
}
?>
This worked quite well. But in Drupal 7, the drupal_write_record only takes an array and no longer the object $this. The new db_merge also only takes an array.
Since i want to save the properties of my object to the database, the above code was very handy and generic for all kinds of classes.
Is there an alternative way to write an object to database, or a method to place objectproperties into a an array?
Any help will be appreciated!
Robert
drupal_write_record does take an object or an array. Guess your problem is caused somewhere else.
drupal_write_record($table, &$record, $primary_keys = array())
$record: An object or array representing the record to write, passed in by reference. If inserting a new record, values not provided in $record will be populated in $record and in the database with the default values from the schema, as well as a single serial (auto-increment) field (if present). If updating an existing record, only provided values are updated in the database, and $record is not modified.
More info on drupal_write_record for D7.

Drupal 7 pull content type fields with db api

What am I doing wrong. I can't seem to pull based upon content type fields in drupal 7.
function ycs_list($number) {
$query = db_select('field_data_field_active_image', 'a')
->fields('a', array('field_active_image_value', 'entity_id'))
->condition('a.field_active_image_value', 1);
$query->join('node', 'n', 'n.nid = a.entity_id');
$query
->fields('n', array('nid', 'title', 'uid'))
->range(0, $number)
->addTag('node_access')
->execute();
print $query;
return $query;
}
This is how the query prints:
SELECT a.field_active_image_value AS field_active_image_value, a.entity_id AS entity_id, n.nid AS nid, n.title AS title, n.uid AS uid FROM {field_data_field_active_image} a INNER JOIN {node} n ON n.nid = a.entity_id WHERE (a.field_active_image_value = :db_condition_placeholder_0) LIMIT 3 OFFSET 0
It looks right and does work directly in mysql. I have to change :db_conditon_placehoder_0 to 1 and it works doing a direct sql query. I want to pull an array of nodes based upon a condition in the active_image field. Any help would be much appreciated.
Without knowing the actual error you're getting it's a bit tricky to debug your existing code, but I'd advise using the EntityFieldQuery class to do this instead:
function ycs_list($number) {
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'name_of_node_type') // Remove this line if you don't want to specify a particular node type for the query.
->fieldCondition('field_active_image', 'value', 1)
->range(0, $number)
->addTag('node_access');
// Execute the query and check for results.
$results = $query->execute();
$nodes = array();
if ($results && isset($results['node'])) {
// Load the node objects based on the node ids returned from the query.
$nodes = node_load_multiple(array_keys($results['node']));
}
// If nodes matching your conditions were found you now have an array of fully loaded node objects in $nodes.
}

Model won't update

Using cakephp:
I am trying to update customer information and the address the customer is linked to.
such that Customer.address_id = Address.id, and
Customer Model
$belongsTo = 'Address';
From the customers_controller
function profile($id = null)
{
if (empty($this->data['Customer']))
{
$this->Customer->id = $id;
$this->data = $this->Customer->read();
}
else
{
$this->Customer->id = $this->data['Customer']['id'];
$this->Customer->read();
$this->Customer->save($this->data['Customer']);
$this->Customer->Address->save($this->data['Address']);
}
}
Customer correctly updates, but Address always inserts a new row. How do I get this address to update?
first of all, take away lines 11 and 12. those serve no purpose. make sure your view contains form elements for Customer.id and Address.id. If you are just updating the Address you dont need line 13 either. The short answer is that Cakephp will insert row instead of update if the primary key is missing. In your case this means [Address][id].

Resources