calling user_save from within hook_init failing on Drupal6 - drupal

I have a module that implements hook_init.
Within that I have a case where I try to call user_save like save
user_save ('');
I figure this should work since I am not setting a uid, so it should create a new one. It also says that the $array should be allowed to be empty.
However, this always returns FALSE. ??
I have also tried setting these values in $array but this doesn't work either:
$foo = array(
'name' => 'the new user',
'mail' => 'the new user mail',
'pass' => user_password(),
'status' => 1,
);
$new_user = user_save ('', $foo);

Look at the documentation:
Parameters
$account The $user object for the user to modify or add. If $user->uid is omitted, a new user will be added.
$array (optional) An array of fields and values to save. For example, array('name' => 'My name'); Setting a field to NULL deletes it from the data column.
So when you call user_save() the first parameter must be a user object. If that user object doesn't have a uid, or is a string like in your case, a new user will be created. Here the 2nd parameter is necessary. It's not required to use the function, but as it holds all the values you want to save, you wont get far trying to create a user with no data at all. What use is a user without password, username etc. So a minimum of data is required as well, so Drupal will know what to save.

Related

Use VBO in Drupal to update custom user field

I want to perform bulk update of users with a Approved users, the table
field_user_status_value
-----------------------
entity_type, entity_id, field_user_status_value
The entity_id is the user id which does not exist in the table, below is the custom module I wrote to update the table:
function bulkapprove_action_info() {
return array(
'bulkapprove_action_callback_name' => array(
'type' => 'user', // Can be file, term, user, etc.
'label' => t('Approve User'),
'configurable' => FALSE, // Doesn't need config form
'behavior' => array('view_property'), // Uses view access rights ,
'pass rows' => TRUE,
'triggers' => array('any'), // Works always
),
);
}
function bulkapprove_action_callback_name($entity, $context)
{
db_update('field_data_field_user_status')->fields(array('field_user_status_value' => 'Approved'))->condition('entity_id', $context->entity_id)->execute();
}
But it is not inserting the values in this table
In Drupal you do not want to update the database fields directly unless you created the table. Drupal's internal APIs provide a collection of tools to ensure you update the values correctly and that all supporting modules get notified of changes as needed through the hook system.
In this case the callback gets the actual entity to run your action against (in this case the user object). You want to take action on that entity and then save the entity.
function bulkapprove_action_callback_name($entity, $context)
{
$entity->status = 1;
entity_save('user', $entity);
}

How to create Field Collection Item by code in Drupal 8

How to create a Field Collection item for a node by program in Drupal 8. I have tried with below code, but it doesn't work. 'field_abc_inside' is the field of the Field Collection 'field_abc'.
$field_collection_item = entity_create('field_collection_item', array(
'field_name' => 'field_abc',
'field_abc_inside' => array('value'=> 'Test data'),
));
$field_collection_item->setHostEntity($node);
$field_collection_item->save();
$user_id = \Drupal::currentUser()->getAccount()->id();
$user = User::load($user_id);
$fc = FieldCollectionItem::create(array(
"field_name" => "field_hobbies",
));
$fc->set('field_hobby_name', 'Watch TV');
$fc->setHostEntity($user);
That code helped me but I have one observation.
\Drupal::currentUser() is the user object, which is clear since it is using it to retrieve the id().
Therefore no need to User::load() it again in line 2, redundant processing that will cause the function to take longer to run.
// Get the current user object
$user = \Drupal::currentUser();
// Prepare the new Field Collection Item object
$fc = FieldCollectionItem::create(array(
"field_name" => "field_hobbies",
));
// Sets more field values
$fc->set('field_hobby_name', 'Watch TV');
// Sets the host record; where the field collection will be attached into
$fc->setHostEntity($user);
// Saves it into an actual field collection record
$fc->save();

Form tests: How to submit a collection to an existing form? [duplicate]

This question already has answers here:
Symfony2: Test on ArrayCollection gives "Unreachable field"
(4 answers)
Closed 6 years ago.
I use two ways to test my forms:
By using $form = …->form();
Then setting the values of the $form array (more precisely this is a \Symfony\Component\DomCrawler\Form object):
Full example from the documentation:
$form = $crawler->selectButton('submit')->form();
// set some values
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';
// submit the form
$crawler = $client->submit($form);
By sending the POST data directly:
The previous code doesn't work with forms which manage collections (relying on fields created by Javascript) because it throws an error if the field doesn't exist. That's why I also use this other way.
Full example from the documentation:
// Directly submit a form (but using the Crawler is easier!)
$client->request('POST', '/submit', array('name' => 'Fabien'));
This solution is the only way I know to test forms which manage collections with fields added by Javascript (see link to documentation above). But this second solution is harder to use because:
it doesn't check which fields exist, this is impractical when I have to submit a form with existing fields and a collection which relies on fields created dynamically with Javascript
it requires to add the form _token manually
My question
Is it possible to use the syntax from the first way to define the existing fields then add new dynamically created fields with the second syntax?
In other words, I would like to have something like this:
$form = $crawler->selectButton('submit')->form();
// set some values for the existing fields
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';
// submit the form with additional data
$crawler = $client->submit($form, array('name' => 'Fabien'));
But I get this error:
Unreachable field "name"
And $form->get('name')->setData('Fabien'); triggers the same error.
This example is not perfect because the form has no collection, but it's enough to show you my problem.
I'm looking for a way to avoid this validation when I add some fields to the existing form.
This can be done by calling slightly modified code from the submit() method:
// Get the form.
$form = $crawler->filter('button')->form();
// Merge existing values with new values.
$values = array_merge_recursive(
$form->getPhpValues(),
array(
// New values.
'FORM_NAME' => array(
'COLLECTION_NAME' => array(
array(
'FIELD_NAME_1' => 'a',
'FIELD_NAME_2' => '1',
)
)
)
)
);
// Submit the form with the existing and new values.
$crawler = $this->client->request($form->getMethod(), $form->getUri(), $values,
$form->getPhpFiles());
The array with the news values in this example correspond to a form where you have a fields with these names:
<input type="…" name="FORM_NAME[COLLECTION_NAME][A_NUMBER][FIELD_NAME_1]" />
<input type="…" name="FORM_NAME[COLLECTION_NAME][A_NUMBER][FIELD_NAME_2]" />
The number (index) of the fields is irrelevant, PHP will merge the arrays and submit the data, Symfony will transform this data in the corresponding fields.

how to populate text area with database value before form load in drupal 7?

I have used hook_form_FORM_ID_alter( ) function to alter a menu_edit_menu form to add few fields. I ve stored the values from those fields in a table when submit action is performed. what I need now is when the particular form entry is loaded again for editing. The fields should be populated with the data in the database before form loads. Can anyone tell me how this could be done.
I have tried using hook_validate ( ) function but the function is called when the submit action is performed which is of no use in this regard. I have to perform the database query before the form gets rendered to populate the text fields with data from tables. Kindly provide me some insight into how this could be accomplished.
I have a problem with the sql select query as well/
$query = db_select('menu_custom');
$query
->fields(array('menu_name','role1','role2','role3'))
->condition('check',1,'=')
->conditon('title',$form_state['values']['title'])
->execute();
foreach($query as $record)
{
$mname = $result ->menu_name;
$rl1 = $result -> role1;
$rl2 = $result -> role2;
$rl3 = $result -> role3;
dpm($mname." ".$rl1);
}
I am getting error that my field specification is wrong but I cant figure out the problem there.
This is a bit too long for a comment so I'll put it here:
The only error you've got in your query is that the first argument passed to the fields() function needs to be the name/alias of the table from which the fields are coming. So your query should probably look something like this:
$query = db_select('menu_custom')
->fields('menu_custom', array('menu_name','role1','role2','role3'))
->condition('check',1,'=')
->conditon('title',$form_state['values']['title'])
->execute();
You get the data from your database in your form function, and put them as default_value
$name = db_query(YOUR_SQL);
$form['first_name'] = array(
'#title' => t('First Name'),
'#type' => 'textfield',
'#default_value' => $name,
);
is this what you meant?

How to manually register a user in Drupal 6.x?

The website has a normal registration form which allows users to register and the likes.
I have created a new custom form in which I am capturing the username/password etc. How do I manually register the user in Drupal system?
Thank You
Check out hook_user and user_save().
http://api.drupal.org/api/function/hook_user
http://api.drupal.org/api/function/user_save/6
Just expanding on Kevin's suggestion of hook_user and user_save here, the code might look something like:
// store user name
$user_name = "user123";
// store user email
$email = "user123#gmail.com";
// set up the user fields, use user_password function for 8 character password
$fields = array(
'name' => $user_name,
'mail' => $email,
'pass' => user_password(8),
'status' => 1,
);
// give new user roles if needed, as shown below
$fields['roles'] = array('new_role');
// pass the fields to user_save() and leave first param empty to create new user
$account = user_save('', $fields);
It's not the answer you want, but you'd save yourself a lot of trouble by using hook_form_alter to change the current registration form:
http://www.lullabot.com/articles/modifying-forms-drupal-5-and-6

Resources