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

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'];

Related

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.

Get gravity forms fields

I am using the gravity form on my site. I am working on create the custom report for this I have need gravity form fields name and id based on specific form id.Please let me know how I can do it.
I am using the following function but it is showing all forms info based on it. it is looking very hard to parse it. Please let me know any function so I can get fields name easily.
$forms = RGFormsModel::get_forms_by_id(13);
try this
function get_all_form_fields($form_id){
$form = RGFormsModel::get_form_meta($form_id);
$fields = array();
if(is_array($form["fields"])){
foreach($form["fields"] as $field){
if(isset($field["inputs"]) && is_array($field["inputs"])){
foreach($field["inputs"] as $input)
$fields[] = array($input["id"], GFCommon::get_label($field, $input["id"]));
}
else if(!rgar($field, 'displayOnly')){
$fields[] = array($field["id"], GFCommon::get_label($field));
}
}
}
//echo "<pre>";
//print_r($fields);
//echo "</pre>";
return $fields;
}
It's not that hard to parse:
$fields=array();
foreach ( $forms['fields'] as $field ) {
$fields[]=array($field['id'] => $field['inputName']);
}
P.S. I'm assuming you use Gravity Forms < 1.7 as RGFormsModel::get_forms_by_id is a deprecated function since 1.7
// Get the Form fields
$form = RGFormsModel::get_form_meta($form_id);
// Run through the fields to grab an object of the desired field
$field = RGFormsModel::get_field( $form, $field_id );
I use the above to get a specific field I want to filter the value of. The $field contains an object with all the properties you want.
echo $field->label // Gets the label
echo $field->inputName // Gets the name
echo $field->type // Gets the type
echo $field->cssClass // Gets the CSS Classes as a string
You are able to get the entered value/content of a field by using rgpost() and by referencing the id ($field->id).
// Check the entered value of every field
foreach( $form['fields'] as &$field ) {
// Get the content for the specific field
$fieldContent = rgpost( "input_".$field->id );
// Check the content
if ( $fieldContent == ... ){}
}

wordpress contact form 7 unique id

i am currently using contact form 7 for wordpress. i would like a unique id for every form filled in and sent.
i have had a look around the internet but cant find anything, although i did find the following:
http://contactform7.com/special-mail-tags/
would there be any easy way to make my own function to do something similar to the above tags? i would need it to be a function to go into my themes function file, so that plugin updates wont affect it.
Cheers Dan
[_serial_number] field is an auto-incremented form submission ID. You just have to have Flamingo plugin installed as well. See http://contactform7.com/special-mail-tags/
(It's the same link as in the question, I guess the field wasn't there when the question was asked).
To generate ID for the Contactform7 you need to hook the 'wpcf7_posted_data'.
However, to generate incremental ID you need to save the forms in database so you can retrieve which ID should be next on next Form submit. For this you will need CFDB plugin (https://cfdbplugin.com/).
If you dont want to put the code inside theme functions.php file, you can use this plugin instead: https://wordpress.org/plugins/add-actions-and-filters/
Example code:
function pk_generate_ID($formName, $fieldName) {
//Retrieve highest ID from all records for given form stored by CFDB, increment by 1 and return.
require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php');
$start = '001';
$exp = new CFDBFormIterator();
$atts = array();
$atts['show'] = $fieldName;
$atts['filter'] = "$fieldName>=$start&&$fieldName<999999999999"; //is_numeric() is not permitted by default for CFDB filter
$atts['limit'] = '1';
$atts['orderby'] = "$fieldName DESC";
$atts['unbuffered'] = 'true';
$exp->export($formName, $atts);
$found = $start;
while ($row = $exp->nextRow()) {
$row2 = $row[$fieldName];
$row2 += 1;
$found = max($found,$row2);
}
return $found;
}
function pk_modify_data( $posted_data){
$formName = 'Form1'; // change this to your form's name
$fieldName = 'ID-1'; // change this to your field ID name
//Get title of the form from private property.
$cf_sub = (array) WPCF7_Submission::get_instance();
$cf = (array) $cf_sub["\0WPCF7_Submission\0contact_form"];
$title = (string) $cf["\0WPCF7_ContactForm\0title"];
if ( $posted_data && $title == $formName) ) { //formName match
$posted_data[$fieldName] = pk_generate_ID($formName, $fieldName);
}
return $posted_data;
}
add_filter('wpcf7_posted_data', 'pk_modify_data');

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;
}

Drupal: Modifying a User at Registration

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.

Resources