Drupal 7 set user picture (avatar) programmatically - drupal

I have form with file upload element. This file (image) must be user picture, but it not set.
form:
$form['f']['step4']['file_e'] = array(
'#title' => t('Image'),
'#type' => 'managed_file',
'#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
'#upload_location' => 'public://images/',
);
validate
function fill_up_profile_form_validate($form, &$form_state) {
global $user;
if (isset($form['f']['actions']['submit']['#value']) && $form_state['triggering_element']['#value'] == $form['f']['actions']['submit']['#value']) {
$file = file_load($form_state['values']['f']['step4']['file_e']);
$validators = array(
'file_validate_is_image' => array(),
'file_validate_size' => array(1 * 1024 * 1024),
);
$errors = file_validate($file, $validators);
if (!empty($errors)) {
$message = '';
foreach ($errors as $error)
$message .= $error . '<br/>';
form_set_error('Error!', $message);
} else {
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
$edit['picture'] = $file;
user_save($user, $edit);
}
}
}
Thank you for your help.

You should try with $form_state instead of $form. $form_state contains the submitted values! Also, with Drupal 7.x, you can not get the values by simply using $form_state['values']['f']['step4']['file_e']! Just do a echo "<pre>"; print_R($form_state); echo "</pre>"; to learn the correct structure of the array!
Also have a look at this code: http://ly2.in/hBMxPK

Related

How to wrap field in custom markup?

Situation
I have a custom module that is using hook_field_formatter_info() to add an "fancy" option to the image field in the manage display of a content type. When this option is chosen I want to be able to surround the ENTIRE field in custom divs and markup. I want the solution to be a hook in my custom module and not a template override.
Process
A user wants the display of an image field to be the "fancy" option. They check it in the drop down and click save from the content types Manage Display admin page. Now on that content type node there should be custom markup surrounding the entire field even if there are multiple images, the new markup should surround ALL the images and not each individual image.
hook_field_formatter_view
hook_field_formatter_view seems to demand it's output be an array and I can't seem to be able to wrap the output in a div.
Template overrides
I can't just make a field.tpl.php for the specific field because like I initially mentioned I need to be able to switch themes and the module still work like normal. Unless there is a way to get my module to override any field where said field has hook_field_formatter_info() set specifically.
/**
* Implements hook_field_formatter_view().
*/
function bootstrap_modal_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
foreach ($items as $delta => $item) {
if ($index === NULL || $index === $delta) {
$element[$delta] = array(
'#theme' => 'bootstrap_modal_image_formatter',
'#item' => $item,
'#entity_type' => $entity_type,
'#entity' => $entity,
'#node' => $entity, // Left for legacy support.
'#field' => $field,
'#display_settings' => $display['settings'],
'#delta' => $delta,
);
}
}
// $element = '<div id="CUSTOMDIVSTUFF">' . $element . '</div>';
return $element;
}
And here is the #theme function:
function theme_bootstrap_modal_image_formatter($variables) {
$item = $variables['item'];
$entity_type = $variables['entity_type'];
$entity = $variables['entity'];
$field = $variables['field'];
$settings = $variables['display_settings'];
$image = array(
'path' => $item['uri'],
'alt' => isset($item['alt']) ? $item['alt'] : '',
'title' => isset($item['title']) ? $item['title'] : '',
'style_name' => $settings['bootstrap_modal_node_style'],
);
if (isset($item['width']) && isset($item['height'])) {
$image['width'] = $item['width'];
$image['height'] = $item['height'];
}
if (isset($item['attributes'])) {
$image['attributes'] = $item['attributes'];
}
// Allow image attributes to be overridden.
if (isset($variables['item']['override']['attributes'])) {
foreach (array('width', 'height', 'alt', 'title') as $key) {
if (isset($variables['item']['override']['attributes'][$key])) {
$image[$key] = $variables['item']['override']['attributes'][$key];
unset($variables['item']['override']['attributes'][$key]);
}
}
if (isset($image['attributes'])) {
$image['attributes'] = $variables['item']['override']['attributes'] + $image['attributes'];
}
else {
$image['attributes'] = $variables['item']['override']['attributes'];
}
}
$entity_title = entity_label($entity_type, $entity);
if ($style_name = $settings['bootstrap_modal_image_style']) {
$path = image_style_url($style_name, $image['path']);
}
else {
$path = file_create_url($image['path']);
}
$caption = 'some value';
$gallery_id = 'some value';
return theme('bootstrap_modal_imagefield', array('image' => $image, 'path' => $path, 'title' => $caption, 'gid' => $gallery_id));
}
Been working on this for days, I'm drowning here.
This is possible via HOOK_process_field(). Use this hook to define a new template file for your field by adding it to theme_hook_suggestions array (place the template file in your module directory, because you wanted to change the theme -as you mentioned-). More info about field template suggestions.
Then, you will need to add the module path to drupal theme registry, so it picks up the template file. Demo.
I found out it was:
function bootstrap_modal_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array(
'#prefix' => '<div class="wrapper">',
'#suffix' => '</div>',
);

Gettin atrribute thumbnail from node from a wordpress rss feed

I've been trying to get this seemingly easy peace of code to work.
I'm loading rss from a wordpress site and it all works fine except for the thumbnails. Since in the XML they are set as an attribute instead of a nodeValue i can't seem to get import them. (i've really tried a lot)
$rss = new DOMDocument();
$rss->load('http://goalprogramme.wordpress.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
// in XML it looks like <media:thumbnail url="http://goalprogramme.files.wordpress.com/2014/01/dsc_0227.jpg?w=150"/>
//echo $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url');
//push items
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
'thumbnail' => $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url') // this line doesn't work !!!
);
array_push($feed, $item);
}
Any help would be greatly appreciated.
Thanks so much in advance!
Hours later i've created another piece of code that does work. If anyone needs it it, here it is:
$feed_array = array();
$feed = simplexml_load_file('http://goalprogramme.wordpress.com/feed/');
foreach ($feed->channel->item as $item) {
$title = (string) $item->title;
$description = (string) $item->description;
$link = (string) $item->link;
$date = (string) $item->date;
if ($media = $item->children('media', TRUE)) {
if ($media->thumbnail) {
$attributes = $media->thumbnail->attributes();
$thumbnail = (string)$attributes['url'];
}
}
$item = array (
'title' => $title ,
'desc' => $description,
'link' => $link,
'date' => $date,
'thumbnail' => $thumbnail
);
array_push($feed_array, $item);
}

Problems with Forms => Variables are not accepted in the form

Not sure where the problem is in the following form used in a template file in Drupal7. Help is highly appreciated. The problems are the following:
1. The variables $title and $surname are not passed over to the form's default value.
=> Error Message: Notice: Undefined variable: title in form_user_information()
=> Error Message: Notice: Undefined variable: surname in form_user_information()
2. There's a Warning: strpos() expects parameter 1 to be string, array given in drupal_strip_dangerous_protocols()
Thanks in advance.
<?php
//Load User data:
global $user;
$uid = $user->uid;
$account = user_load($uid);
//Get User data:
$title = 'Mrs.';
print $title . '<br><br>'; //Result: Value is printed and not empty!
$surname = check_plain($account->field_vorname['und']['0']['value']);
//$surname = 'Tom';
print $surname . '<br><br>'; //Result: Both values are printed and are not empty!
function form_user_information($form, &$form_state) {
//Form
$form['#action'][] = request_uri();
$form['#id'][] = 'form_user_information';
$form['#validate'][] = 'form_user_information_validators';
$form['#submit'][] = 'form_user_information_submit';
$form['#prefix'] = '<div id="form_user_information">';
$form['#suffix'] = '</div>';
//Select-Field: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#select
$form['Title'] = array(
'#type' => 'select',
'#title' => t('Title'),
'#options' => array(
'Frau' => t('Mr.'),
'Herr' => t('Mrs.'),
),
'#default_value' => $title,
);
$form['surname'] = array(
'#type' => 'textfield',
'#maxlength' => 50,
'#size' => 40,
'#required' => TRUE,
'#title' => t('Surname'),
//'#attributes' => array('placeholder' => $surname),
'#default_value' => $surname,
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => 'Confirm data');
return $form;
}
//print form
$form = drupal_get_form('form_user_information');
print drupal_render($form);
//Form Validation:
function form_user_information_validators($form, &$form_state) {
if ($form_state['values']['surname'] == '') {
form_set_error('surname', t('Please enter your surname.'));
}
}
//Form Submit:
function form_user_information_submit($form, &$form_state) {
//...
}
//get form information
echo "<pre>".print_r($form,true)."</pre>";
?>
1) Set the global variables $title and $surname with global scope:
//Get User data:
$global $title = ...
$global $surname = ...
Otherwise set all these variables (including $user) inside the function form_user_information which is the best practice.
I would also suggest not use $title as variable name because it may cause problems with already defined $title of the $page variable. Instead use something like $user_title.
2) Which line does this come from?
Guess this issue can be closed. See the 2 comments. Thanks Theodoros for your help.

With custom module, display result ,

function searchsong_block($op='list',$delta=0){
$block = array();
switch($op){
case "list":
$block[0][info] = t('Search song');
return $block;
case "view":
$block['subject']='THIS IS SONG SEARCH MODULE';
$block['content']=drupal_get_form('custom1_default_form');
return $block;
}
}
function custom1_default_form () {
$form = array();
$form['txt_name'] =
array('#type' => 'textfield',
'#title' => t('Please enter your name'),
'#default_value' => variable_get('webservice_user_url',''),
'#maxlength' => '40',
'#size' => '20',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save Details'),
);
return $form;
}
function custom1_default_form_validate (&$form, &$form_state) {
if(($form_state['values']['txt_name']) == '') {
form_set_error('user_webservice', t('Enter a name'));
}
}
function custom1_default_form_submit ($form_id, $form_values) {
$GET_TXT_VAL = $_POST['txt_name'];
$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'song', $GET_TXT_VAL);
$output='';
while ($row = db_fetch_object($result)) {
// drupal_set_message($row->title);----IF I ENABLE THIS LINE THEN MY SEARCH RESULT DISPLAYING IN THE GREEN BLOCK, YES I KNOW THIS FUNCTION SOMETHING LIKE ECHO JUST FOR TESTING PURPOSE WE SHOULD USE
$output .=$row->title;
}
$block['content'] = $output;
}
How to print my output ,
Above module does not display anything , even error also,
i thing i should use theme('itemlist') somthing , but i am not sure how to use this , and where i should use this ,
So what i want is , i want to display my search result , in the content region ,
Please find my question picture view below..
Validate and submit are not for outputting data.
You should show your results in custom1_default_form:
Add in submit $_SESSION['search_text'] or use multistep "storage" (learn drupal form api for this).
But let's look how to work via sessions:
Add in custom1_default_form:
// Here is your form code, so form will appear on the top
// ...
if (isset($_SESSION['search_text'])) {
//add here your code from submit that output searching result
$form['result'] = array(
'#type' => 'item',
'#value' => $output,
);
unset($_SESSION['search_text']); // don't forget clear session
}
Your submit function should be like this:
function custom1_default_form_submit($form, &$form_state) {
$_SESSION['search_text'] = $form_state['values']['txt_name'];
// this will store text field into session, then reload page,
// so you drupal_get_form will see entered values.
}
This is all.
Tips:
if(($form_state['values']['txt_name']) == '') {
form_set_error('user_webservice', t('Enter a name'));
}
This code is not needed, if you do:
$form['txt_name'] = array(
... // other properties
'#required' => true,
);
Read please about form api here: http://api.drupal.org
Other way to use block, just call function that output result and form via drupal_get_form, so:
...
$block['content']='custom1_default_result';
...
function custom1_default_result () {
$output .= drupal_get_form('custom1_default_form');
...
$output .= //search result if session filled/
}

Drupal: Checking to see if User Has Picture

I'm displaying the userpicture on a node with this code here:
<?php
$user_load = user_load($node->uid);
$imgtag = theme('imagecache', 'avatar_node', $user_load->picture, $user_load->name, $user_load->name);
$attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
print l($imgtag, 'u/'.$user_load->name, $attributes);
?>
This works great, except if the user doesn't have a picture, in which case it looks strange.
How do I load the default picture if the user doesn't have a picture.
I don't believe I have access to $picture in this block.
Thanks in advance.
$user_load = user_load($node->uid);
$picture = $user_load->picture ? $user_load->picture : variable_get('user_picture_default', ''); //
$imgtag = theme('imagecache', 'avatar_node', $picture, $user_load->name, $user_load->name);
$attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
print l($imgtag, 'u/'.$user_load->name, $attributes);
if you copy default picture to files directory, you can determine it via http://api.drupal.org/api/function/file_directory_path/6
This is what I'm using for a similar situation:
if (!empty($user->picture) && file_exists($user->picture)) {
$picture = file_create_url($user->picture);
}
else if (variable_get('user_picture_default', '')) {
$picture = variable_get('user_picture_default', '');
}
if (isset($picture)) {
$alt = t("#user's picture", array('#user' => $user->name ? $user->name : variable_get('anonymous', t('Anonymous'))));
$picture = theme('image', $picture, $alt, $alt, '', FALSE);
if (!empty($user->uid) && user_access('access user profiles')) {
$attributes = array(
'attributes' => array('title' => t('View user profile.')),
'html' => TRUE,
);
echo l($picture, "user/$user->uid", $attributes);
}
}
It is adapted from http://api.drupal.org/api/drupal/modules%21user%21user.module/function/template_preprocess_user_picture/6
In Drupal 7 I use:
global $user;
file_create_url( file_load($user->picture)->uri)

Resources