Drupal: Modifying a User at Registration - drupal

I needed to create a custom select list for the user registration page that pulls a SQL query from nodes I need to link to users. I have successfully accomplished this task.. :)
However, when I submit the value, I can't seem to control where the value is stored. In fact, I can't store the value at all. I have created a custom field for my value, but only the new field name is stored, and it is serialized and stored in the Data column of the user table.
Below is my code, I've commented my issues in it. Any help would be appreciated!
<?php
// $Id$
//create the additional user form field, a select list named "account_name"
//then calls the next function to populate it.
function accountselect_user($op, &$edit, &$account, $category = NULL) {
if ($op == 'register' || 'edit')
$fields['Information']['account_name'] = array(
'#type' => 'select',
'#title' => 'Account',
'#description' => t('Select the account to which the contact belongs'),
'#options' => accountselect_getclubs() ,
);
return $fields;
}
//contains query to pull results to select list...this part is working
function accountselect_getclubs() {
$return = array();
$sql = 'SELECT DISTINCT `title` FROM node WHERE type = \'accounts\' ';
$result = db_query($sql);
while ($row = db_fetch_array($result)) {
$return[] = $row['title'];
}
return $return;
}
//CAN'T GET THIS PART TO WORK - query to update the row - the uid = 29 is for
//testing puposes. Once I get the test value to work
//the test value I will worry about updating the correct user.
function accountselect_submitaccount() {
$sql = "UPDATE users SET account = \'value\' WHERE uid = \'29\'";
db_query($sql);
drupal_set_message(t('The field has been updated.'));
}
//I SUSPECT THE PROBLEM IS HERE...call the submitaccount function.
//I have tried hook_form_alter as well...
function accountselect_submit(&$form, &$form_state) {
if($form_id == 'user-register')
drupal_execute('accountselect_submitaccount');
}

Have you checked Drupal's logs? It should be throwing errors, as this is not a valid query.
$sql = "UPDATE users SET account = \'value\' WHERE uid = \'29\'";
Should be:
$sql = "UPDATE users SET account = 'value' WHERE uid = '29'";
Additionally, in:
function accountselect_submit(&$form, &$form_state) {
if($form_id == 'user-register')
drupal_execute('accountselect_submitaccount');
}
$form_id is never defined.
You say you've created the field in the database, but it must match the name of the Drupal field to be automatically handled. You've got two different names for it - account_name in the Drupal field, but account in the database. Make them consistent and it should be automatically handled, no submit functions required.

Related

How to add / update a field collection without updating parent node/entity drupal 7

I needed to to add / update field collections to node entities without updating the node entities. I tried two ways listed in https://www.drupal.org/node/1842304 and http://alexrayu.com/blog/saveupdate-field-collection-without-nodesave but none of them seems to be working exactly the way I want.
I tried as follows:
$node = node_load($nid);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_college_rating_data'));
$field_collection_item->setHostEntity('node', $node);
$field_collection_item->field_text1['und'][0]['tid'] = $form_state['input']['field_text1']['und'];
$field_collection_item->field_text2['und'][0]['value'] = $form_state['input']['field_text2']['und'];
$field_collection_item->save();
It added a field collection but it updates the node.
I also tried to alter the field collection form submit and used custom submit handler as follows:
function own_custom_field_collection_submit($form,$form_state) {
$field_collection_item = field_collection_item_form_submit_build_field_collection($form, $form_state);
$field_collection_item->save(TRUE);
drupal_set_message(t('The changes have been saved.'));
$form_state['redirect'] = $field_collection_item->path();
}
I have copied this code from core field collection module to change the default argument to "TRUE" in the save function. It added the field collection but didn't associated with the parent node.
I need to save the field collection separately since my node entity form is very large with 50 to 60 fields and field collections and I don't want to update it as many times as I add / update any field collections to the node.
Any help will be much appreciated.
Thanks
You have to pragmatically relate your field collection to the host entity by the following code.
$field_collection_item = field_collection_item_form_submit_build_field_collection($form, $form_state);
$field_collection_item->save(TRUE);
$host_entity = $field_collection_item->hostEntity();
$lang = 'und';
if (isset($host_entity->nid) && isset($host_entity->vid) && isset($lang) && isset($field_collection_item->item_id) && isset($field_collection_item->revision_id)) {
$query = db_select('field_data_field_text1', 'fd');
$query->addExpression('max(fd.delta)', 'total_row');
$query->condition('fd.entity_id', $host_entity->nid);
$max_delta = $query->execute()->fetchField();
if (isset($max_delta)) {
$max_delta = $max_delta + 1;
} else {
$max_delta = 0;
}
db_insert('field_data_{field_collection}')->fields(array(
'entity_type' => 'node',
'bundle' => '{node_type}',
'entity_id' => $host_entity->nid,
'revision_id' => $host_entity->vid,
'language' => $lang,
'delta' => $max_delta,
'field_text' => $field_collection_item->item_id,
'field_text_revision_id' => $field_collection_item->revision_id
))
->execute();
}
Replace your content type and field type in { } and then you just have your field collection relate to your host entity.
Thanks

Catchable fatal error: Object of class WP_User could not be converted to string in /directory/ on line 139

I'm currently trying to get the username of whomever submitted a form, to be stored in a database along with the value they submitted.
This is line 139 from my function:
$retval = $newdb->query("SELECT * FROM $table WHERE user = '$hf_username' ");
add_action("init", "ref_access");
function ref_access() {
global $error;
if ( is_user_logged_in() ) {
global $quanid;
global $newdb;
$hf_username = wp_get_current_user();
$inputValue = isset($_POST['$quanid']);
$newdb = new wpdb( 'user', 'password', 'db', 'localhost' );
$retval = $newdb->query("SELECT * FROM $table WHERE user = '$hf_username' ");
if( mysqli_num_rows($retval) > 0)
{
$newdb->query("UPDATE table SET user = '$hf_username' "); //If user exists, update
}
else
{
global $table;
global $newdb;
$newdb->insert(
$table,
array(
'ItemID' => $quanid,
'Price' => $inputValue,
'user' => $hf_username
)
);
}
} else {
$error = "Error: You must be logged in to submit prices";
return;
}
}
wp_get_current_user returns a WP_User object, not the username as a string. The username is stored in the user_login property of the WP_User object.
$hf_user = wp_get_current_user();
$hf_username = $hf_user->user_login;
That said, there are a couple of things that seem a bit off with your code:
You seem to be mixing the WordPress database functions with the built in mysqli_ functions. $newdb->query will already return the number of selected rows, there is no need to call mysqli_num_rows and it will not work the way you expect it.
You're declaring a new instance of wpdb instead of using the existing database object via global $wpdb. This is not necessary if you're accessing the same database that WordPress is installed on.

Autocomplete drupal

It's not a problem but i would like to learn how to get some other value.
function search_autocomplete($string) {
$matches = array();
$temp= array();
$query = db_select('user','s');
$return = $query
->fields('s')
->condition('lastname', '%' . db_like($string) . '%', 'LIKE')
->range(0, 10)
->execute();
foreach ($return as $row) {
$matches[$row->user_id] = check_plain($row->lastname).' '.($row->firstname);
}
drupal_json_output($matches);
}
Now when search box appears when i start typing by last name i get user lets say Doe John. But when i press search button i get his user_id.
I know when i change user_id to lets say last name i get the last name when i search.
Now my question is how to get last and first name when search is clicked, but send the user_ID.
The entity reference module handles it by putting the uid in brackets after the name:
foreach ($return as $row) {
$key = check_plain($row->lastname).' '.($row->firstname).' ('.$row->user_id].')';
$matches[$key] = check_plain($row->lastname).' '.($row->firstname);
}
Another (but more complex) option would be to create a hidden field to store the uid in.

How can I query for required fields in a Drupal 7 Database?

I am trying to write a function that will get me the names of the required fields from the drupal database. Then, so I can write one validation function for alerting the user that he/she has not entered in a required field.
You can get this quite easily using the field_info_instances() function:
$instances = field_info_instances('node', 'invoice');
$required = array();
foreach ($instances as $field_name => $instance) {
if ($instance['required'] == 1) {
$required[] = $field_name;
}
}
To get the field type you need to query for the field not the instance. In the loop you can call:
$field = field_info_field($field_name);
$type = $field['type'];

How to get drupal custom profile values?

There is a checkbox added in user profile form, subscribe to daily newsletter. I want to get list of users who have subscribed (checkbox ON) and send them daily newsletter. How can I do this in drupal-6. (1) to get list of all subscribed users (2) Send them Email.
If you can explain at code level, I 'll really appreciate that.
If your profile field is profile_newsletter, your :
<?php
function mymodule_get_subscribers() {
$query = 'select * from {profile_fields} where `name`="%s";';
$result = db_query($query,'profile_newsletter');
$field = db_fetch_object($result);
$user_query = 'select * from {profile_values} where `fid`=%d and `value`=1;';
$result = db_query($user_query,$field->fid);
$subscribers = array();
while($subscriber = db_fetch_object($result)) {
$subscribers[] = $subscriber->uid;
}
return $subscribers; // Your array of subscriber user IDs
}
?>
This code was quick, is untested and should probably contain a few sanity-checks. But it should work.
For the sending of newsletters and such I'd recommend using a pre-rolled module. I haven't tried any for Drupal, but Simplenews seems to do the trick. http://drupal.org/project/simplenews
If nothing else it probably contains a good sending-function. Otherwise just use PHP mail()-function.
function your_custom_function ($user_id, "Field you want to get") {
$result = db_query("SELECT t2.value FROM profile_fields t1, profile_values t2 where
t1.title='Field you want to get' and t2.uid=".$user_id." and t1.fid=t2.fid");
$field = db_fetch_object($result);
$profile_type =$field->value;
return $profile_type;
}

Resources