View author field (image) in a node view I have created a image field in the user account. How can I add the image of the author to the display of each node?

You may do that using a Views Block and place it in the Main Content block region, right after the content block. Also, you'll need to create a relationship between the node and it's author, so only the correct user will be displayed. Below is a screenshot of a work I've done using Views for Drupal 7.42 that I think is close to what you're looking for:

1 - Create a new Block View to view Users (not Content)

2 - Filter Criteria should say User: Active (Yes)

3 - There is a default sort Criteria item. Remove it since it doesn't matter.

4 - Add a Relationship: Choose "User: Content authored"

5 - Add a Contextual Filter: Chose "Content: Nid"

6 - In the configuration options for the newly added Content: Nid, choose these options:
WHEN THE FILTER VALUE IS NOT AVAILABLE:
Provide default value
In the Select box, choose Content ID From URL.

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
Specify validation criteria
Validator select box: Content
Content Types: choose the content types you want the view to work with.
Filter Value Format: Node ID
Action to take if the filter value does not validate: Hide View

7 - Save the View.

8 - Go to Structure -> Blocks and configure the block to show on the types of content you want it to show on and position it wherever you want it to appear.

9 - Done.


How to use latest jquery version on specific page or code? i am using D7. i want to use jquery1.9 on a specific block. so at where that block visible, only load jquery with it. how it wil??? any help?

There are several ways to do it. If you want to update  jquery, you can use jquery update moudle.

Second thing is you can use, drupal_add_js() function to include the jquery file to particular node.

Third thing is you can use the js, that is used in all the page in template.php or in theme.info file. I hope you are looking for second method. Also, this question will help you much.

Updating jquery


How do I print the node title and body? This is the code which I have put in node.html.twig. It doesn't print the body and title of the node, whose bundle is Basic page.

How do I print node title and body of a node?

{%
  set classes = [
'node',
'node--type-' ~ node.bundle|clean_class,
node.isPromoted() ? 'node--promoted',
node.isSticky() ? 'node--sticky',
not node.isPublished() ? 'node--unpublished',
view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
'clearfix',
  ]
%}
{{ attach_library('classy/node') }}

{{ title_prefix }}
{% if not page %}

    {{ label }}

{% endif %}
{{ title_suffix }}
{% if display_submitted %}

    {{ author_picture }}

      {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

    {{ metadata }}

{% endif %}

     {{ content }}

You can print the node

Title as

  {{ label }}

Body

  {{ content.body }}

Try this,

  {{ content.body| raw }}

It will be used to remove the markup in the content.


How to to write Computed_field code? I'm testing the computed_field module on a taxonomy field. I want to get the number of nodes that have a term reference to the current term:

$tid = 1;
$entity_field[0]['value'] =  db_query("
SELECT count(*)
FROM node n INNER JOIN taxonomy_index t on n.nid = t.nid
WHERE n.type = 'discussion'
and n.status = 1
and t.tid=$tid")->fetchField();

How can I get the tid of the term? Is there a better way of writing the query?

A query like that should do the trick, but if you want something more elegant, I recommend EntityFieldQuery.


Drupal 8 rewrite a hook I want to rewrite a hook comment_node_links_alter. How can I do it? I created a file THEME.theme in my theme, placed there THEME_comment_node_links_alter but it is not called. I cannot find any distinct information how to rewrite hooks. I observed bartik.theme and saw that all hooks are prepended with a theme name. I did the same. Did clear the cache. My funciton is included, I checked with xdebug. But it is never called.

I think you're getting confused about how Drupal hooks work. You don't overwrite the existing function you instead create your own function that is called when the relevant part of the site is loaded. (So in this case node links)

So there is no THEME_comment_node_links_alter hook. There is HOOK_node_links_alter. So I'm guessing you looked in the comment module and saw comment_node_links_alter which is actually the comment module implementing HOOK_node_links_alter

In your theme/module you'd want to replicate what the comment module is doing so something like

THEME_node_links_alter(

With THEME being your theme machine name. THen that will mean your function is called and you can amend the variables

https://api.drupal.org/api/drupal/core%21modules%21node%21node.api.php/function/hook_node_links_alter/8.4.x


Content type which contains a content creation as a slip form I'm quite new to Drupal and I've encountered a quite complicated problem.

I've created a role called "Event coordinator" authorized to create a content type entitle "Events" that has a title and and a description, and for which comments are disabled. Here is a sample of it:

Title: "Join Our Club".
Description: "It will be fun".

I've also created another role called "Audience" which will be used by the user who will attempt to join the event detailed in the content created by the "Event coordinator".

The "Audience" should create a "Slip" content which will have a request message. And it should be sent to the targetted "Events".

A "Slip" that gets created will be put (somehow) in another content which is the "Events". The "Event coordinator" then will choose whom will join an event based on the "Slips" that were created.

Only the "Event coordinator" and the owner of a slip (created by "audience") will be able to see a "Slip".

I've tried to use the "entity-registration" but it's not that flexible. I mean as an "Event coordinator" I'm not able to see all the "Slips" from all "Events" I created. It will just show the "Slips" when you view the content of a single "Event".

Any suggestions about which module(s) I could use to implement this?

You may use Organic groups module

  Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.

"event-coordinator" will be group administrator and he will create and edit any content in the group. "audience" will be usual group member and he will edit only own content in the group


How to check Drush version? How can I identify what version of Drush is installed on a given system?

Assuming you have Drush installed and working properly, just type drush status in your command prompt. It will give you drush version as well as Drupal version info. If you have aliases set up for remote (or local) sites, you can run drush @alias status and it will give you the status info for that remote system.


Multiple Image Upload and Rename - avoiding multiupload image field I'm looking to provide the following functionality on my Drupal site:

I'd like to make an easy to use content type that allows users to upload multiple photos easily. The uploader needs to allow them to dump in files, rename them and upload them. I'm currently using the multiupload image field which I've found to do the job of uploading well but, I don't like the thought of increasing my php upload limit to allow users to upload a whole load of photos at once. I wondered whether there was an uploader that allows users to drop in their photos and, providing an individual photo isn't over the upload limit, will handle the upload of all of the photos?

An added bonus would be the ability to rename photos, once they've been uploaded.

Thanks in advance for your help!

Plupload has a variety of upload widgets that should allow you to upload without increasing the php limit. You can view examples of the widgets here. You can pick one of the [modules that integrate pulpload on its project page at https://www.drupal.org/project/plupload.


How can I programmatically unselect "View published content" checkbox for anonymous users? I am using Drupal 8. I want to programmatically unselect the View published content checkbox for anonymous users.

How can I achieve this?

You have to insert this code in a hook_install() or hook_update() :

$role = \Drupal\user\Entity\Role::load('anonymous');
$role->revokePermission('your_permission');
$role->save();


Run code when a session ends Is there a hook or something similar that triggers when a PHP session ends?

When a user signs in, I'm writing a few things to the cache, and I need to delete them from the cache when the user exists the site. If the user manually logs out, that's no problem, but I still need to clear that data when users close the browser.

Drupal doesn't have hooks that are invoked when a session ends, probably also because the code would not be able to understand if the session cookie is not present because it expired (which means the session ended) or because the browser has not been used to log in on a Drupal site.

Drupal invokes a hook when the user is logged out, either because the user clicked on the Log out link, or because the user was forced to log out, which is what happens when the site is in maintenance mode and the account isn't exempted from being automatically logged-out.
Drupal 7 and Drupal 8 invoke hook_user_logout() when the user is logged-out, and the code invoking the hook also destroys the user session.

Since you are talking of cache to clear, if you are using Drupal 8, you can also investigate if there are cache tags or contexts that tell Drupal to invalidate the data when the session is destroyed.
Cache contexts lists session.exists as context that can be associated to cache data. I didn't test it, but from the context name, I take it invalidates the cache data when the session doesn't exist, which is what you are trying to achieve. (See also Cache API for more information on cache tags and cache contexts in Drupal 8.)

As side note, a Drupal session doesn't normally end when users close their browser. It would happen when using an incognito window with Google Chrome, or the equivalent of other browsers, but when you are not using that, the session doesn't end when the browser is closed, or when the browser tab is closed. (If that were to happen, it would mean logging off the users.)


Create a block with a list of all pages tagged with a taxonomy vocabulary I'm new to drupal, so please be gentle with your answers, and I apologize in advance if this is something I could have found elsewhere, but I've been searching for several hours now...

I'm using Drupal 7.

I want to create a block (based on a view, I am assuming) that will display all of the pages that are tagged with a particular taxonomy vocabulary. Here's what my taxonomy looks like right now:

Main Menu
-Fruit
--Apples
--Oranges
--Bananas

I want a block that displays all the stories tagged with "Apples." I thought this would be easy, but for the life of me I cannot figure out how.

I've been trying to create a view, based on Taxonomy Terms, that filters to "people" but when I set the filter criteria, what I get is the word "apple," which when clicked, leads me to the page that shows all the pages (nodes?) tagged with "apple" I want that in a block format to begin with!

In other words, I want the information on the page that right now I can get to by going to /taxonomy/term/# to display as a block, showing only the title fields in a list. HOW?

Thanks for your help on this. I'm sure I'm missing something simple.

I want to create a block (based on a view, I am assuming) that will display all of the pages that are tagged with a particular taxonomy vocabulary.

You are absolutely correct that your problem can be solved with a view.

From the way you worded it, though, I sense that you don't understand the difference between nodes and page, and between taxonomy vocabularies and their terms. So let's address that first.

The difference between nodes and pages

A node in Drupal is a single bundle of content. I use the word bundle in the sense that there are multiple pieces of information which all describe the same object. So, for example, the pieces of information "red", "180 horse power", and "manual transmission" could be bundled together to describe a particular car, and then stored as a node in Drupal. Nodes are most commonly used to store information that describes a Web page, which is where the confusion comes from.

A page in Drupal is, well, trickier to explain. Drupal, being a CMS, doesn't really deal with pages so much as it deals with programmatic functions which create pages on demand that are then sent to an user's browser. When you click on a menu link (or, more correctly, when you request a URL) in Drupal, you're not asking for a page, you're actually asking to run a particular programmatic pathway in the gigantic, dynamic program that Drupal really is.

So, we'll be talking about nodes from here on out. We want to create a view of nodes, including links to the URLs which cause Drupal to run in a way that returns the "normal" web pages that we expect and use every day.

The difference between taxonomy vocabularies and taxonomy terms

This is easier to explain. Taxonomy terms are the "words" or "tags" you want to use categorize your nodes. Taxonomy vocabularies are the named containers that we put terms in. So, we could have a taxonomy vocabulary named "Fruit" that contained the terms "Apple", "Tomato", and so on.

Building your view

OK, so your view is going to list nodes. That means you need to set up your view to show "content". I'd show you a picture right here, but apparently I can only link to one.

Once you've got that, set up your view's filter. You want to add some filter criteria, using the "Content: Has taxonomy term" filter. You'll be asked what vocabulary you want this filter to use, so select the vocabulary that contains the terms you're interested in. You can also pick if you use a dropdown menu or an autocomplete text box for the filter to enter the filter's parameter into. I recommend using the dropdown.

Next, you can choose a logical operator and the taxonomy terms on which to apply it. If you want to show only nodes that are tagged with Apples, then you would choose the "Is one of" operator and select only the Apples term.

And there you go. The view is now showing you all content nodes on your site that are tagged with Apples in the vocabulary that Apples is in. You can finish customizing the rest of the view however you like now.


Redirect user to login page when they have to access to a view? I have a view which is only accessible to authenticated users. However, there are links to it on the site. Can I make it so that an unauthenticated user gets redirected to the login page, instead of the 403 they're seeing now?

The Redirect 403 to User Login module should do what you need.


Create styled image programmatically I have a module that create custom PDF with multiple selected nodes and I use the below function to create the link to styled images:

$file = File::load($img_id);
$imagesPath[] = ImageStyle::load('550x300')->buildUrl($file->uri->value);

Unfortunately, the image itself is not created, only the link, which is ok if I display it on a simple webpage because Drupal will create it on the fly when needed but on a PDF it cause errors because the image it not found before the PDF could be displayed.

Is there a programmatically way to create this image ?

Thanks.

You need to execute createDerivative() on ImageStyle.

$image_style = ImageStyle::load('550x300');

$file = File::load($img_id);
$image_uri = $file->getFileUri();
$destination_uri = $image_style->buildUri($file->uri->value);
$image_style->createDerivative($image_uri, $destination_uri);

For Drupal 7 there is image_style_create_derivative():

$style = image_style_load('550x300');

$file = file_load($img_id);
$image_uri = $file->uri;
$destination = image_style_path($style['name'], $image_uri);
image_style_create_derivative($style, $image_uri, $destination);


See data completeness in Drupal? I am using Drupal basically to store a ton of info on various topics. The problem is, we add data slowly over time.

I would like to get a report that shows which nodes have the least content. I.e. The most empty fields. This way, I can tackle those with the least amount of data first. Is this possible with Drupal?

It seems you're looking for the Content Complete module

  Content Complete is a CCK extension module that allows to tag CCK fields needed for completion (CCK Complete). The module checks the tagged fields against the content provided for those content types, and computes a complete percentage that can be shown to the user.

Image from the project page

Similar module is Field Complete

  In some situations you want to mark an entity field to indicate it should be completed but not enforce its completion at that time. This module extends the choice between Required and Not required to "desirable" completion.


How do I PUT update on a node using services 3 I have a node with field_order_status field(not required) in list(text) type and radio button widget and I want to update a node(nid:95) but my sample JSON PUT content(application/json) throws Status 406 Error:

{"form_errors":{"field_order_status][und":"An illegal choice has been detected. Please contact the site administrator."}}

my content is:

{
  "field_order_status":{
    "und":[
      {
        "value": "1"
      }
    ]
  }
}

sample url:

http://localhost/caesarschickencms/createorder/node/95

Services 3.4, Drupal 7.22

Notes:
When I tried replacing und with other values like 'en', it accepts but not updates, refer to drupal 7 + services 3 - inserting nodes with select fields

And Devel page vars dump:

What would be missing?

What Services version do you use?

Since Services 7.3.4 we deen to set Cookie & X-CSRF Token on header for every (PUT/POST) execution

Please check this comment too
https://drupal.org/comment/6491362#comment-6491362


Update fields to use a different FieldFormatter during an update hook I have a drupal.org module that has changed its fieldformatter ID in a later version and I need the update hook to update all isntance of the content to use the new formatter, but cant seem to figure out how to do this.

e.g.

/**
 * Plugin implementation of the 'field_example_simple_text' formatter.
 *
 * @FieldFormatter(
 *   id = "example_field_formatter",
 *   module = "example",
 *   label = @Translation("example"),
 *   field_types = {
 *     "example_field_type"
 *   }
 * )
 */

has changed to

/**
 * Plugin implementation of the 'field_example_simple_text' formatter.
 *
 * @FieldFormatter(
 *   id = "new_example_field_formatter",
 *   module = "example",
 *   label = @Translation("example"),
 *   field_types = {
 *     "new_example_field_type"
 *   }
 * )
 */

I need to update the content/fields to be using the new formatter as it overwrites the previous one.

The plugin definitions you've posted are for new fields to build the options when configuring a field formatter in UI. For existing fields you have to update the field formatter in config.

For example:

use Drupal\Core\Entity\Entity\EntityViewDisplay;

function mymodule_update_8001() {
  foreach (EntityViewDisplay::loadMultiple() as $display) {
    foreach ($display->getComponents() as $name => $options) {
      if (isset($options['type']) && $options['type'] == 'old_formatter') {
        $options['type'] = 'new_formatter';
        $display->setComponent($name, $options)
          ->save();
      }
    }
  }
}


Remove default › between breadcrumbs in panels breadcrumbs Is it possible to remove the › between the breadcrumbs in the panels breadcrumbs module?  I tried modifying the part of the .module file shown below (which I know is bad practice, but I just  wanted to try it out) but that did not work.

// Finally, render the breadcrumb
foreach ($breadcrumbs_info as $crumb) {
if (isset($crumb['href']) && $crumb['href'] == '<none>') {
  $crumb['localized_options'] += array('attributes' => array(), 'html' => TRUE);
  $breadcrumbs[] = '<span ' . drupal_attributes($crumb['localized_options']['attributes']) . '>' . ($crumb['localized_options']['html'] ? $crumb['title'] : check_plain($crumb['title'])) . '</span>';
}
else {
  $breadcrumbs[] = l($crumb['title'], $crumb['href'], $crumb['localized_options']);
}

}

If you have your own custom theme (or a sub-theme you can edit), you can override theme_breadcrumb(). Actually I'm not sure this is completely supported by panels_breadcrumbs but I assume it is.

THEMENAME_breadcrumb() {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '
' . t('You are here') . '
';

    $output .= '
' . implode(' CUSTOM SEPARATOR ', $breadcrumb) . '
';
    return $output;
  }
}

EDIT:
Alternatively, there are other breadcrumb-customizing modules that allow to specify a custom separator between the breadcrumb items.


How to add additional class to an imagecache preset? Tried:

function ruh_imagecache_formatter_default($element) {
  // Inside a view $element may contain NULL data. In that case, just return.
  if (empty($element['#item']['fid'])) {
    return '';
  }

  // Extract the preset name from the formatter name.
  $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  $style = 'linked';
  $style = 'default';

  $item = $element['#item'];
  $item['data']['alt'] = isset($item['data']['alt']) ? $item['data']['alt'] : '';
  $item['data']['title'] = isset($item['data']['title']) ? $item['data']['title'] : NULL;

  $class = "imagecache beautytips imagecache-$presetname imagecache-$style imagecache-{$element['#formatter']}";
  return theme('imagecache', $presetname, $item['filepath'], $item['data']['alt'], $item['data']['title'], array('class' => $class));
}

function ruh_imagecache_formatter_imagelink($element) {
  // Inside a view $element may contain NULL data. In that case, just return.
  if (empty($element['#item']['fid'])) {
    return '';
  }

  // Extract the preset name from the formatter name.
  $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  $style = 'imagelink';

  $item = $element['#item'];
  $item['data']['alt'] = isset($item['data']['alt']) ? $item['data']['alt'] : '';
  $item['data']['title'] = isset($item['data']['title']) ? $item['data']['title'] : NULL;

  $imagetag = theme('imagecache', $presetname, $item['filepath'], $item['data']['alt'], $item['data']['title']);
  $path = file_create_url($item['filepath']);
  $class = "imagecache beautytips imagecache-$presetname imagecache-$style imagecache-{$element['#formatter']}";
  return l($imagetag, $path, array('attributes' => array('class' => $class), 'html' => TRUE));
}

I've added class - beautytips - but its not appearing on when im firebugging and imagecache image.

Add it as an array,

$class = array('imagecache', 'beautytips', 'class3');


Determine if menu link is current/active When rendering a menu, in the twig file, you can set a class if item.in_active_trail is set:

  {% for item in items %}
    {%
      set classes = [
        item.in_active_trail ? 'is-active',
      ]
    %}

However this class is applied to each link in the trail - so if you are on the third level, three links get this class.

Is there anything I can see OOTB on item or add to it if the menu link is the current page? I need to highlight it and not just items in the trail itself.

Have you tried to combine it with item.below? I suppose (not tested) that this could be used to only apply the class to the deepest item within the active trail. The code could look something like this:

{% for item in items %}
  {% if item.in_active_trail and not item.below %}
    set classes = [
       'is-active',
    ]
  {% endif %}
{% endfor %}


When using the Omega Responsive theme, IE7 and IE8 load all stylesheets When I view a site that I'm currently working on in IE7 or IE8, there are tons of conflicting styles. The normal stylesheet is not taking precedence over the global and narrow stylesheets which is causing problems for the layout of the site. I have aggregated both css and js to see if this was an issue with the amount of files IE will load, to no avail. I have patched the omega-mediaqueries.js with the omega-ie7 patch, this did not resolve the issue either.

I'm at a loss and I'm under the gun for time. Has anyone else encountered this issue? How can I make sure that the normal stylesheet takes precedence over the other stylesheets?

Omega does not support responsive layouts for IE 8 & below. You will need to add respond.js or a similar javascript to your theme in order to make up for IE 8 & below's lack of support for CSS media queries.

There is an Omega issue on drupal.org related to this topic with more detailed information.


Drupal 7 vertical tabs like the ones in Drupal 8 Is there a way to move vertical tabs in node forms to a right side column like in Drupal 8? I know one option is Renderable Elements module but last commit was 1 year ago and it says it is an expiremental module.

EDIT: I want to transform vertical tabs into accordions (like the ones in Drupal 8) because once the vertical tabs are in the right column they look awful.

EDIT 2: I just found an interesting sandbox project that does what I want: Responsive Vertical Tabs. However, it's not stable and breaks my ckeditor fields.

Thank you!

You can use a combination of the Node form columns module and the Renderable elements modules.

Node Form cols separates the node forms into two columns and a footer.
This module alleviates some of the problems with the mile-long node forms in Drupal. Other than that it gives you the possibility to use different weights and collapsed states for your forms than for your presentation.

Renderable elements is more complicated to use but lets you split out the parts of the vertical tabs part of the node edit form. For example, after enabling these two modules, do the following for the article content type:

Visit node/add/article to add a new article content type
Click the new link at the top of the form which says "Manage Form Display"
Tick all the items you want to break out of the vertical tabs. As an example choose "Publishing options", "Published", "Promoted to front page" and "Stick at top of lists"
Click save
Goto Structure -> Content types -> Article -> Manage form
Set the "Publishing options (Field group)" and "Save" to be in the right region and press save. nb. I had to use the drop downs here, it didn't seem to rememebr my region choices if I used drag and drop.
Visit node/add/article and see the collapsing publishing options block on the right.


Edit field in contentType B when creating or editing node of contentType A I need to edit a field in contentType B when I create or edit nodes of contentType A.

I know it's possible to use rules for this but I need to have more control so I want to do it in my own module.

Tried this code without success:

function MYMODULE_node_presave($node) {
    MYMODULE_change_value($node);
}

function MYMODULE_change_value($node) {
    $node = node_load($node->nid);

    $referenced_nid = $node->referenced_node[LANGUAGE_NOE][0]['target_id']

    $referenced_node = node_load(referenced_nid);

    $referenced_node->my_field[LANGUAGE_NONE][0]['value'] = 12345.0;
    node_save($referenced_node);
}

Am I choosing the wrong hook?

Try the following:

/**
 * Implements hook_node_presave().
 */
function yourModule_node_presave($node) {
  if ($node->type == 'your_typeA') {
    yourModule_change_value($node);
  }
}

function yourModule_change_value($node) {
  if (isset($node->field_node_referenced[LANGUAGE_NONE][0]['target_id'])) {
    //- Get referenced node id
    $referenced_node_id = $node->field_node_referenced[LANGUAGE_NONE][0]['target_id'];
    //- Load referenced node
    $wrapper = entity_metadata_wrapper('node', $referenced_node_id);
    $wrapper->field_name->set(array(
      'value' => 'test new field value'
    ));
    $wrapper->save();
  }
}


How to write Custom Javascript in "drupal commerce" checkout page? In drupal 7, there is a common page in Templates folder i.e., "page.tpl.php". In this page if we write javascript, it works in all pages. Now I need to write custom javascript for "drupal commerce kickstart" checkout page. For Example, If I want to use onchange event function to "Full name" field. Even though If I just use "alert(document.getElementById('edit-customer-profile-billing-addressbook').value);", it is not working any where of the pages written. I tried javascript code in below pages.

profiles/commerce_kickstart/themes/commerce_kickstart_theme/template.php
profiles/commerce_kickstart/themes/commerce_kickstart_theme/templates/ {almost all pages}
profiles/commerce_kickstart/modules/contrib/commerce/modules/checkout/ {almost all related pages}

So please help.. where should I write Javascript code to work in checkout page. Thanks in advance.

As St0ik mentioned, you'll want to use drupal_add_js to add the JavaScript to the page. The real question is, where do you want it to go?

If you want it to show up on every checkout page, use the generic checkout form alter:

// Show on every page of checkout.
function MYMODULE_form_commerce_checkout_form_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

If you want it to only show up on certain pages within the checkout, you can use a more specific form alter to only add it to a certain page.

// Review before payment only.
function MYMODULE_form_commerce_checkout_form_review_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

or

// First page of checkout.
function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

You'll use MYMODULE_form_commerce_checkout_form_PAGE_alter where PAGE is the wanted checkout step.


Error message getting displayed but not getting highlighted fields in Drupal 7 Drupal 7 is not displaying highlighted fields on using form_set_error but error message is getting displayed. I have rendered my form hook_form in template. Could that be the cause for this issue?

Here is my code:

if(($form_state['values']['field1']=='' ){
 form_set_error('', t('one field is required'));

 }

First argument of form_set_error tells Drupal what element should get highlighted. Obviously empty string means "none", so your code works exactly as designed.

To make field required, you can go a simpler way: Use #required attribute and let Drupal take care for details.

To round it off, as Clive said, your code would be:

form_set_error('field1', t('one field is required'));

But if you're just checking for an empty field, use #required.


Creating node-based photo galleries with prev/next links within each taxonomy (specific gallery) I want to create a collection of photo galleries where each gallery has it's own main page with thumbnails, and clicking on each thumbnail takes you to the node for that thumbnail with the full-size version of the image as well as next/prev links to go to other node pages within that same gallery.  I don't want to use colorbox or lightbox, all node-based per image entry per gallery.

My current plan is to use taxonomy to specify the different galleries, use views to create the individual gallery homepage, and use a custom content type for each image's node.  I'm not sure how to get the next/previous links on the node page to only go to nodes within that specific gallery, and couldn't find a module upon my initial search.

I'll be using Drupal 7.  Are there any modules that would do this, or is there a better approach to achieving the result in a way other than what I'm planning?

Well, it looks like the Drupal 7 version of Node Gallery has everything I need. I installed it, and it took care of it without any custom configuration needed.


#upload_validators missing error message [Update]

Upon further investigation it seems that the message isn't appearing due to the following javascript error:

"Uncaught TypeError: Cannot read property 'length' of undefined"

I'm not sure how to resolve this error, but the following issues may be related:

[D7] Duplicate HTML IDs are created for file_managed_file fields
Duplicate HTML IDs are created for file_managed_file fields

Description

I'm trying to create a custom form with some number of file upload fields (for now I'm using the hard-coded value 3).

I have added an #upload_validators attribute to the managed_file element that calls file_validate_extensions and passes in "doc" as the only valid filetype.

When I try to upload a .jpg, an error appears -- which is what I want. However, the error doesn't contain any text.

Any idea what I'm doing wrong?

Code

function mymodule_example1_form($form_state) {
  $num_docs = 3;

  // Build the number of name fieldsets indicated by $form_state['num_docs'].
  for ($i = 1; $i <= $num_docs; $i++) {
    $form['managed_file'][$i] = array(
      '#type' => 'managed_file',
      '#title' => 'Managed File' . $i,
      '#progress_indicator' => 'throbber',
      '#progress_message' => 'Upload successful!',
      "#upload_validators"  => array("file_validate_extensions" => array("doc")),
      '#upload_location' => 'public://doc/',
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

Screeshot

Resources

Drupal Form API Reference - managed_file
Drupal API - function file_validate_extensions

I was able to resolve the issue using the solution posted here.

As I understand it, the issues is caused by an ID being used more than once. To fix this, you can implement an #after_build callback that ensures the upload fields will have unique IDs.

To summarize...

Add an #after_build callback to the managed_file field:

$num_docs = 3;

// Build the number of name fieldsets indicated by $form_state['num_docs'].
for ($i = 1; $i <= $num_docs; $i++) {
  $form['managed_file'][$i] = array(
    '#type' => 'managed_file',
    '#title' => 'Managed File' . $i,
    '#progress_indicator' => 'throbber',
    '#progress_message' => 'Upload successful!',
    "#upload_validators"  => array("file_validate_extensions" => array("doc")),
    '#upload_location' => 'public://doc/',
    '#after_build' => array("MODULE_file_managed_fix_duplicate_id"),
  );
}

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
);

Create the following callback:

function MODULE_file_managed_fix_duplicate_id($element) {
  if ($element['#id'] === $element['upload']['#id']) {
    $element['#id'] = drupal_html_id($element['#id']);
  }
  return $element;
}

Once I did that and cleared all my caches, the javascript errors went away and the error messages starting working.


Check if a user has a role How can I check if a user has a certain role?

I found this but it is for Drupal 6.

Since you already found that post, make sure you also read the comments. It clearly explains why checking for a permission is recommended over checking for a role. When you use permissions, you can assign that permission to multiple roles, which makes your system more flexible. Also, remember that roles can be renamed, which would break your code.

That said, if you want to check for a role, you can do this:

// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // do fancy stuff
}


Show WebForm Block through a link on a Page I have a WebForm Survey which I want to show in a page through LightBox.

The LighBox part is all sorted but I am stuck in getting a link to the WebForm Survey.

Here  is what I did:-

Created a WebForm Survey
Made it available as block (It can be seen in Structure>Block as Webform: Self - Assessment Survey)

Now on a Page (About Us), I have a link "Open Survey". What I want to do is, that when this link is clicked, my Survey should open in a LightBox.

I tried doing this
Open Survey, but this never opens my WebForm, and instead shows a 404.

What should I Do?

Many Thanks.

This isn't possible at present, not automatically any way.

You could write some javascript to find all "/contact" links and append "/lightbox2" to it so it's "/contact/lightbox2". You would also need to add a rel="lightframe" to the anchor link. This would open the contact form in a lightbox when the contact link is clicked, and you could style the form with a page-contact-lightbox2.tpl.php template file in your theme's directory.

However, this will open the form in a iframe, rather than treating it like modal content which is what is done to the login form. The disadvantage to using an iframe is that the form isn't closed upon form submission, like with the login form. The advantage is that the iframe will add a scrollbar to accommodate the size of the content. If you want, you can treat it as modal content (just use rel="lightmodal"), but you'll need to specify the height and width of the lightbox container (see lightbox2 docs).

I'm not adding it to lightbox2 module at this time because there are too many modules that modify the contact form content, e.g. advcontact, contact_forms, content_attach, captcha, mollom, etc. These potentially could modify the size of the content, making it difficult for lightbox2 to estimate the outputted form size.

If enough other people request it, then I'll add the ability for lightbox2 to open the default contact form in a lightbox, but for now, this feature won't be implemented for the reasons outlined above.


Loop through entity in a template I have a Site with a Twig Template. I have an multiple entity references which I want to loop trough and print out the name, description of each entity.

In my template I'm using the following code to loop through entities.

{% for item in node.field_workers %}
 {{ item.entity.field_name.value }}
{% endfor %}

This loops trough all my entities but won't output any value whatsoever.
I tried using kint() to debug the process. When I try kint(item.entity) it shows me the following structure:

protected fields --> field_name

When I try kint(item.entity.fields) it redirects me to 'drupal/install' page when I try to load the page.

What am I doing wrong?

As Kevin says in his comment, Drupal will do most of the work for you if you use view modes on the referenced content type:

/admin/structure/types/manage/{referenced-content-type}/display

In your case, you might want to modify the Teaser view mode so that it hides all fields except for Name and Description. (If you are already using the Teaser for something else, you can create a new view mode.)

Then, when you render the entity reference field, just use the format "Rendered Entity" and configure the view mode that you wish to render (e.g., Teaser).


Redirect visitor based upon geolocation On a Drupal website I want to redirect the visitor to a landing page based on the users location. I need this to be more specific than just the users country, but rather I need the province inside the country. When the user does not allow to be located, the user will go to the standard landing page...

Is there an (easy) way to achieve this? I am fairly new to the world of Drupal.

I've had pretty good results previously with SmartIP, and now there is Rules integration which can react to which country the user is in.

So you should be able to set a Rule similar to the following psuedo-rule:

  EVENT:

  Page is going to be viewed

  CONDITION:

  Page is: Front page
  IP Address is in country: whatever country you want

  ACTIONS:

  Go to page: YOUR COUNTRY SPECIFIC LANDING PAGE

I know you said you were new to Drupal, so you can find some really useful Rules tutorials at NodeOne: Learn the Rules Framework.

EDIT

I've just twigged you said you want it to the province level rather than country (sorry, that was glaringly obvious - my fault), so you might be looking at some custom code.

Last time I used it, I used SmartIP to get the latitude and longitude of the user, and then the Location API for the nitty gritty.

You should be able to combine this with hook_init() and drupal_goto() to redirect the user to the relevant page.


How to delete old obsolete terms after node's term field has been updated? Because the old version of the term is left in the vocabulary and not deleted or updated with the new term.

So what I mean is that vocabulary should contain only terms that exist on at least one node.

I need this because I'm using certain vocabulary on Views as exposed filter and old terms leftovers messes it up.

A better description of what you're looking for is "orphaned terms". There exists a module that addresses that use case, called Delete Orphaned Terms.

  This is a utility module for deleting "orphaned" taxonomy terms. By
  default, terms with zero nodes associated with them are considered
  orphans, though administrators can specify the number of nodes
  associated with a term in order for it to be considered an orphan.


Menu Token - roles issue I am using Menu Token to create a link to a customized profile edit page that uses the url "user/%uid/edit". I've set the title of the link to "My Account" and although it works for my (admin) account, for the other roles the title is "Edit" instead (the default Drupal tab name for the /user menu item) and futhermore it does not appear to be the active trail. My thinking is that it's something to do with permissions since it works in one role but I can't seem to figure this out. Any help?

I think I got the answer.. just check for the snapshot. It seems you were using the wrong value of token in menu path. Use user/[user:uid]/edit instead.


How to upload/insert images in content from module? $article = entity_create('node', array(
    'type' => 'article',
    'title' => generate_demo_content('lorem_ipsum_title'),
    'body' => array(
      'value' => generate_an_article(),
      'format' => 'full_html',
    ),
    // how attach here, a file or an image?
  ));
  $article->save();

I create an article from a .module file, and I would like know if I can link an image/file object to my article?

By example if I have an image inside /modules/my_module_name/images/img.jpg, how I can insert this image inside my article object from my .module file please?

Thanks.

I have tried the below code with node_save method but not with entity_create way. Check if it works.

$dir = 'public://';
if (file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {
  $file = file_save_upload('image', array(), $dir, FILE_EXISTS_RENAME);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  $attachment = array(
    'fid' => $file->fid,
    'display' => 1,
    'description' => $file->name,
    'title' => $values->tooltip
  );
}

$article = entity_create('node', array(
  'type' => 'article',
  'title' => generate_demo_content('lorem_ipsum_title'),
  'body' => array(
    'value' => generate_an_article(),
    'format' => 'full_html',
  ),
  'field_attachment' => $attachment, //may need to change here
));


Loose compression for all images directly from Drupal I need to do image loose-compressing usually done with GIMP/TinyPNG/GPI, but just inside Drupal, but also For all images, in a single process or several sporadic processes (say, for each content type).

This could save much time instead of download, compress, reupload, etc.

Is there a way to loose-compress all images in the application so that webpages containing them load faster?

If you don't know such a tool but does know a way to show all nodes that has images, please comment naming such a tool, so it could at least help in the alternative of downloading and manually loosely-compressing each image before re uploading it.

You're looking for this but in D8 - https://www.drupal.org/project/imageapi_optimize. You can still use the tools to do it manually.

PNG - Use https://pngquant.org/ first with these settings --speed=1 --quality=90-99 --force --ext .png and then https://github.com/subzey/zopfli-png
JPG - https://github.com/mozilla/mozjpeg and then https://stackoverflow.com/questions/5579183/jpegtran-optimize-without-changing-filename

EDIT: This new D8 project just appeared https://www.drupal.org/project/file_processor


How to show latest and high price value first using Views? I am using views to show products in my site. I need to filter my view with high price and latest product . Using expose filter not a sort criteria.

To achieve your requirement, you have to expose the sort criteria. Select checkbox Expose this sort to visitors, to allow them to change it under sort criterion configuration.

Note: When you add any field into SORT CRITERIA, then under this field configuration you can see this option.


How to create a custom Aegir Drupal interface I'm interested in using Aegir to deploy Drupal websites. I'm wondering if there is a way to customize the user experience of setting up a new site, while still maintaining the Aegir mechanism. Probably something more like the standard Drupal setup screen.

Yup, create a theme with all things you want, some custom modules to do more heavy lifting and there you have it and install both on your Aegir server. (working on similar idea i have for Aegir, including fcgi support, so i can jail sites to a user, sell them in a store and let the users fix their own sites.)

And / or you could use something like http://drupal.org/project/hosting_services to write something yourself. (and loads more)


Form API image upload form and File Entity; images not listed in admin/content/file I used Form API to create an image upload form, where images get uploaded via managed_file. The upload process works just fine, but the uploaded files don't get listed in the admin/content/file overview that is provided by the File Entity Module. The overview only shows those files that were uploaded via file/add, File Entity's own upload form.

My code is:

/**
 * Create an image upload form
 */

function upload_form_image_form($form, &$form_state) {

  // Image file
  $form['image'] = array(
    '#type' => 'managed_file',
    '#name' => 'image',
    '#title' => t('Image file'),
    '#size' => 40,
    '#description' => t("Image should be in JPG format."),
    '#upload_location' => 'public://',
    '#required' => TRUE,
  );

  // Submit
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  return $form;
}

/**
 * Submit the upload form and scale the image down to standard resolution
 */

function upload_form_image_form_submit($form, &$form_state) {
  if (isset($form_state['values']['image'])) {

    $image = file_load($form_state['values']['image']);

    $loadedimage = image_load($image->uri);
    list($width, $height) = getimagesize($image->uri);
    if ($width/$height >= 1) {
      image_scale($loadedimage, 900, null, $upscale = FALSE);
      }
    else {
      image_scale($loadedimage, null, 900, $upscale = FALSE);
      }

    image_save($loadedimage);
    $loadedimage->status = FILE_STATUS_PERMANENT;

  }
}

I think your problem is coming from calling image_save and not file_save. They are non synonymous so far as I can tell.

A managed_file is an uploaded file, and usually records an owner of the file with file_usage_add(). This is how drupal can manage whether the file is still needed by the system or can be unlinked or deleted when cron is run.

See this other drupal stackexchange answer on how to use the managed_file FAPI element. It should answer your question on how to get the (original) file saved. You could then create derivatives of the file with image processing as you've already successfully done; after the original file is saved.

I don't believe there is a streamlined solution for this in the file_entity module or in any image functions (I doubt it, as one thing is to upload and manage the file itself -- and another is to do proccessing on the image itself).


How can I create a Views field template per display? I successfully could create a template file for views field after reading this page.

https://api.drupal.org/api/views/theme!theme.inc/group/views_templates/6

However views-view-fields--myviewsname.tpl.php override all the displays in "myviewsname"

Is there any way I can make a template that overrides just one display in a View?

For example, a template that overrides just "display-1" in "myviewsname"

views-view-fields--myviewsname--display-1.tpl.php will do it, eg, views-view-fields--VIEWNAME--DISPLAYNAME.tpl.php.  (Along with changing any underscores in the names to single dashes)

On the api page you reference, you can see this in their example as the display mentioned there is called page.

These and other template names can be easily discerned from clicking on the Theme Information link in the Style Settings in the Views UI.


IE Stylesheets being ignored - only on production server though Production server - http://speysideleisure.com

Dev server - http://superallan.com/dev/speyside/

On IE the Dev site is referencing the css properly but the Production site isn't. The Prod is hosted on different servers with a different host - all the files are the same though. The only thing is that I noticed the problems once I'd uploaded it to the Prod server so then I made the changes. I've cleared the Cache a million times but that's the extent of my knowledge in how to solve it. The Dev site changed pretty much instantly.

Is it a setting somewhere on the Prod server?

Cheers for any help - it's appreciated.

IE chokes if you have more than 31 stylesheets, which most Drupal sites do if you create a zen subtheme. Turn on CSS aggregation in your performance settings to fix that.

There are potential (temporary or easily fixable) problems associated with migrating a Drupal site from http://example.com/dev/ to http://example2.com/ that you can avoid completely if you develop on a subdomain, ie. moving http://dev.example.com to http://example.com

check your database and theme files for paths starting with "dev/" and give your .htaccess files the once-over.


last insert ID of drupal_write_record I need to get the latest inserted id, this is the line im using for writing files to my db

drupal_write_record('file_managed', $file, 'fid');

any ideas?

I found the answer myself. Use $file->fid.


Give an individual cron task for each Feeds import Can I separate different import tasks? I have feeds module installed and it runs multiple import jobs per cron. So I would like to at least order them (give different weights to them).

You can indeed use Elysia and define a cron job for each of the feed imports like this:

/*
 * Feed import managed by Elysia
 */
function MYMODULE_cronapi($op, $job = NULL) {
  $items['fetch_MYFEED_cron'] = array(
    'description' => 'Fetch MYFEED',
    'rule' => '*/10 * * * *', // Every 10 minutes
    'callback' => 'MYMODULE_fetch_MYFEED_cron',
    'arguments' => array(array('MYFEED')),
  );
  return $items;
}
function MYMODULE_fetch_MYFEED_cron($feednames){
  if (function_exists('feeds_source')){
    foreach($feednames as $feedname){
      $source = feeds_source($feedname);
      $source->import();
    }
  }
}


How to print multi-value link image CCK field in template? I have a multi-value CCK field set up using the Link Image Field module, and I need to print all of the images (linked) on the content page. I used the code below to print the images themselves, but cannot figure out how to wrap each image's link around each image.

                <?php if ($node->field_day_option_buttons[0]['filepath']): ?>
             <?php
                foreach($node->field_day_option_buttons as $image) {
                 if (file_exists($image['filepath'])) {
                     print theme_imagecache('my image cache preset name', $image['filepath']);
                    }
                  }
              ?>
            <?php endif; ?>

Can anyone provide input on how to accomplish that?

Thanks!

EDIT
Here is the info placed on the page when I run a print(r) on that cck field:

Array (
  [0] => Array (
    [fid] => 347
    [uid] => 1
    [filename] => days-5.png
    [filepath] => sites/default/files/days-5_0.png
    [filemime] => image/png
    [filesize] => 440
    [status] => 1
    [timestamp] => 1366038083
    [list] => 1
    [data] => Array (
       [alt] => Alt Text
       [title] => Title Text
       [url] => http://www.mysite.com
       [target] => _self
    )
    [nid] => 18
  )
  [1] => Array (
    [fid] => 348
    [uid] => 1
    [filename] => days-20.png
    [filepath] => sites/default/files/days-20_0.png
    [filemime] => image/png
    [filesize] => 506
    [status] => 1
    [timestamp] => 1366038108
    [list] => 1
    [data] => Array (
       [alt] => Alt Text
       [title] => Title Text
       [url] => http://www.mysite.com
       [target] => _self
     )
    [nid] => 18
  )
)

You should be able to use the l() function (link function) to print out your link.

Typically, l() is used with the arguments l("My link text", $path), however, the first argument doesn't have to be text and can be just html.  You just have to specify that with the optional $options array argument at the end if you're including html.  :-)

Here is more documentation on using l(): http://api.drupal.org/api/drupal/includes!common.inc/function/l/7  The 6 & 7 versions should work similarly.

In your case, you can build your link like this:

Your first argument will be an image, rather than text as the link
Your second argument will be the path you want the image to link to, which should be $image['filepath']
Your third argument should specify that the first argument is html, and not just text

So, try something like:

<?php
print l(
    theme_imagecache('my image cache preset name', $image['filepath']),
    $image['data']['url'],
    array(
          'attributes' => array(   // Sample attributes you can apply to your anchor tag
            'id' => 'your-link-id',
            'class' => 'your-link-class',
            'target' => '_blank',  // open link in new window.
          ),
        'html' => true,
    )
);
?>

I haven't tested this yet, as I don't have a Drupal 6 site handy, but this should work.  Let us know if it works or if it needs some tweaking...


A way to choose a block title's format (HTML tag) What I would like to do is be able to choose what type of Headline HTML element (h2, h3, etc) to use for each block's title. The only way I can find to change a block's Title is in block.tpl.php.  But this forces every block on the site to all have the same Headline.

I've Google'd and searched Drupal.org for a module or manual way to do this but have not found one. Does anyone know of a module that does this?

I know you are asking about D7, but you are missing a key point about templates.  I'd take a gander at http://drupal.org/node/104319 which talks in great detail how D6 does it so you can how it can look at different block templates and then think about whether you need to create a module that has a configuration page for its blocks like what you have above or whether block location is enough.


Paragraphs Entity Type Causing Issues After Core Update I am getting this error whenever I try to create a node on Drupal 8.6.2.

  Drupal\Component\Plugin\Exception\PluginNotFoundException: The paragraph entity type does not exist. in Drupal\Core\Entity\EntityTypeManager line 133.

Right now, the paragraphs module is turned off. I have ran drupal updb to see if the database needed updating; nothing came back.

I tried drupal moi and drupal mou for paragraphs, but I get this error.

  [ERROR] Configuration objects (core.entity_view_mode.paragraph.preview) provided by paragraphs already exist in active configuration

How can I fix this error?

I figured this out, not sure if it is the best way, I ended up using a mysql command to delete the config manually:

DELETE FROM `config` WHERE name='core.entity_view_mode.paragraph.preview';

After, you can enable and disable the module. Which appears to have fixed the issue.


Is there any ideas on webform mutile values on same field? In webform select components, we can set multiple attributes but not for filed like textfield or numbers.
So I want to ask is there any ideas on that, so let user can add more value  on same field. Such as:
Telephone number, the web visitors may not have only one ,and we should allows multiple for that.
We found that the webform has store multiple  values in database which can come from in the form used like telephone[], but do not in the validation.
We do not want to changes the validation rules but we want to have a multiple attributes on textfied.
Is there any idea?
Thanks.

There is module for doing this: Try the Multivalue Settings module.

  This module adds some useful settings for fields that can contain multiple values. You can specify:

  Number of values allowed
  Number of values required
  Number of empty widgets to display initially (Drupal usually displays all fields for non-unlimited fields. This allows you to only display a few, followed by the 'Add More' button, which will disappear after the maximum number of fields has been filled.)
  Number of empty widgets to display on edit forms after the field contains some values (Drupal usually displays one extra.)


Why can't my module install a database table? I'm following the instructions on a module development training video. I try to install a table using the mysite/update.php page and everything goes well but no table is installed in the database. I'm lost for what might be wrong. Here's my code on a my_module1.install file:

/*
Implements hook_schema
*/
function my_module1_schema(){
    $schema = array();

    $schema['my_module1_node_views'] = array(
        'fields' => array(
            'nid' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
            ),
            'uid' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
            ),
            'view_count' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
            ),
        ),
        'primary key' => array('nid', 'uid'),
    );
    return $schema;
}

/*
Implements hook_update_N
*/
function my_module1_update_7000(){
    drupal_install_schema('my_module1_node_views');
}

The argument to drupal_install_schema() is the module name, not the table to install.

Generally speaking (and assuming you might have more than one table eventually), if you want to create all tables that are defined in hook_schema(), use:

drupal_install_schema('my_module1');

If you just want to create that one table:

$table = drupal_get_schema_unprocessed('my_module1', 'my_module1_node_views');
db_create_table('my_module1_node_views', $table);


Drupal 7 views - sort results after they have been retrieved from database just before they are rendered Drupal 7 views - sort results after they have been retrieved from database just before they are rendered.
Here what type of hook need to use.Is the below hook usefull?
hook_views_data_alter()

Thanks,
Ramesh Babu G.

You can implement hook_views_pre_render(&$view) within a custom module and manipulate the result array available in $view->result:

/**
 * Implementation of hook_views_pre_render()
 *
 * @param view $view
 */
function YourModuleName_views_pre_render(&$view) {
  // Check if this is the view and display you want to manipulate
  // NOTE: Adjust/Remove the display check, if you want to manipulate some/all displays of the view
  if ('YourViewName' == $view->name && 'YourDisplayName' == $view->current_display) {
    // EXAMPLE: Just reverse result order
    // TODO: Replace with your desired (re)ordering logic
    $view->result = array_reverse($view->result);
  }
}


How give users ability to change their blog pages theme? I am using Drupal7 and I am designing a blog engine site that any user can create a blog for him/herself and he/she can change the theme of his/her blog page. Is there any module to integrate with the core blog module and provides this ability for my site?

Take a look at the Switchtheme module.

  Adds a block to allow users to switch between enabled themes.

Read the readme.txt of the module for the instructions.

If you wish to have different themes according to roles, take a look at the Role Theme Switcher module.

  Useful Drupal module to assign separate themes for different roles (including anonymous) in your system.


Fields in page.tpl.php I want to display in my page.tpl.php 3 custom fields form the latest content type added to my website.

I have a custom content type called "Articles" with three custom fields, field_1, field_2, field_3.

How can I display on every page of my website those three fields from the latest content added to "articles"?
I want to do this without using views.

I don't have the exact answers for you, but I do have some directions to point you. Try something like this:

In template.php, in a THEMENAME_preprocess_page() function, construct a query to get the node ID of the most recently created node. Look up Drupal's Database API to see how to do this. (A more permanent solution would be to use a custom module for the query, but let's start at the theme layer to get this working.)
Do a node_load() to get the entire contents of that node, which will contain your three fields, and more.
Create variables (inside the $variables[] array) to hold the rendered content of your custom fields.
Use those new variables in page.tpl.php, or page-article.tpl.php


How does drupal set user cookie The following code, let's login any user programmatically.

global $user;
$user = user_load(<any_uid>);

My question is how does the above code triggers to set new user cookies on browser, at this point we are not even regenerating session.

The following code, let's login any user programmatically.

Not exactly; it sets the current global user object to an instance of a user, but it doesn't log the account in or touch the session. Many things that happen in that request that rely on the global user object will behave the same as if the account was logged in, but it won't be, and they won't have a session tied to the account (not yet anyway).

Cookies are added at the end of the request, in drupal_session_commit:

if (!drupal_session_started()) {
  drupal_session_start();
  if ($is_https && variable_get('https', FALSE)) {
    $insecure_session_name = substr(session_name(), 1);
    $params = session_get_cookie_params();
    $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
    setcookie($insecure_session_name, $_COOKIE[$insecure_session_name], $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);
  }
}

As a by-product of the way Drupal initialises sessions (lazily in an exit hook), if the call to $user = user_load(<any_uid>); happens before the first session has been initialised, the session will be initialised for that user and they will appear "logged in" for their next request, even if the user_load line doesn't execute.

But, hook_user_login won't have been invoked, the last login column in the user table won't be updated, and so on. It's not a full-on "login", just initialising the session for a particular user.

Incidentally, if you call $user = user_load(<any_uid>); when a session already exists for another user, the session for the next request will still be for that other user. It won't be overridden with a session for <any_uid>.


Watchdog errors with location = http://default/index.php Looking through recent log messages, I've got a number of errors with no referrer listed, and showing location as being http://default/index.php (instead of http://mysite.com/some/page). They all seem to be triggered by "Anonymous" from localhost (127.0.0.1). Example screenshots are below.

Anyone know what kind of sense I should make of these entries?

Example screenshots:

Here's one where location is not http://default, but http://localhost... again, why?

The first error seems to be due to a failing operation with the Backup & Migrate module. This module is probably configured to make a backup of your database on a scheduled (CRON) interval. As the error message suggests, increasing PHP's max_execution_time setting may help.

The second error you're seeing is due to a missing 'type' column in the file_managed database table. This field is usually added by the Media and/or File Entity modules. You likely updated these modules' code, but didn't run updates. Try running your update.php, or if that fails, disable, uninstall, and re-install the Media and File Entity modules.


Module-heavy site quits without error on W7 dev machine I have taken over development of a major Drupal 6 site (I'm not a Drupal newbie by any means) - I did quite a lot of the original work and never had the following problem, however there have been changes since then:

Any admin function which involves building large data structures from all modules causes the dev site to silently quit. There are no Apache or PHP errors, just:

Unable to load the webpage because the server sent no data.
Error code: ERR_EMPTY_RESPONSE

That's the result in Chrome, IE fails similarly. It's definitely happening in the code.

I can't rebuild menus, access the module page or enable the Update module. The rest of the site works fine.

I analysed the problem down to the point where I have established the crash definitely occurs when it's building big data structures. It has about 360 modules and when building the module page can get to 252 before it simply dies.

I running on WAMP over W7 with PHP 5.3.13 and Apache 2.2.22 Any ideas on what's causing it and if it's solvable?

(Any comment like "don't use windows" or "use fewer modules" are not very helpful at this point.)

EDIT: Additional data. I was wrong about the lack of Apache error messages, although it's not very helpful:

[Fri Aug 02 22:21:09 2013] [notice] Server built: May 13 2012 19:41:17
[Fri Aug 02 22:21:09 2013] [notice] Parent: Created child process 10076
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Child process is running
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Acquired the start mutex.
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Starting 64 worker threads.
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Starting thread to listen on port 80.
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Starting thread to listen on port 80.
>>>> ERROR MESSAGE NEXT
[Fri Aug 02 22:23:08 2013] [notice] Parent: child process exited with status 255 -- Restarting.
<<<<
[Fri Aug 02 22:23:08 2013] [notice] Apache/2.2.22 (Win64) PHP/5.3.13 configured -- resuming normal operations
[Fri Aug 02 22:23:08 2013] [notice] Server built: May 13 2012 19:41:17

Seems there are a multitude of possibilities for this and it may be related to this: What can cause Drupal to crash Apache?

Okay. I do not understand why but it seems the answer here actually is the answer in the other question. Here's what you do:

In Apache's httpd.conf find the line

# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf

And un-comment it so the httpd-mpm.conf file is run. Then load up that file and go to the bottom where you'll see this:

# WinNT MPM
# ThreadsPerChild: constant number of worker threads in the server process
# MaxRequestsPerChild: maximum  number of requests a server process serves
<IfModule mpm_winnt_module>
    ThreadStackSize      8388608
    ThreadsPerChild      150
    MaxRequestsPerChild    0
</IfModule>

Not including the ThreadStackSize - add that line with the nice big number. And the crash stops. Essentially I was right in my diagnosis - the data structure being built is too big but it's too big for the thread, not the overall memory allocation.

The reason I'm confused is that, as far as I can see, that module is not loaded and run in Apache, but maybe it's not configurable and always runs.

Anyway this works.


How can I create a single login page? I do not want to display a login block or link on every page. I would instead like to create a single login page accessible from  http://example.com/login. How can I do that?

/user/login exists by default; you could use that.


Restrict media files to other users once uploaded I'm using Media Entity Browser to let users add new or existing media files in a content type.

I have two groups. Business-A uploaded an image in a content. Business-A can re-use the image in writing other contents but Business-B should not be able to add it as an existing media for their own article.

I want that only a group can get access to its uploaded media. Because when I upload images using media browser, in default, all files get public accessed.

How can I restrict uploaded media files be added by other users.

If you have Groups on your site with grouped access permissions, I would recommend using the Group module for less complex group permissions like this and OG for configuring more involved group permissions.

Using the Group module you will be able to section off the media and other content like this.

EDIT:
I suggest you configure Group functionality / permissions directly on the File / media entity, rather than just the nodes they are added / used from. Failing that, I believe you will have to (clone and) override the view that the media entity browser uses and do some filtering based on group(s) of the media file author.

Then try using the user id of the author initially using static values to test your view. If the UI of the view does not provide what you are looking for, you might need to write your own Views Access Plugin. Here is one I wrote for Message Private module: InboxPermission.php. You could do similar.


How to set mysql port for Drupal and Drush My site was running fine with the following default setting in settings.php file:

'host' => 'localhost',
'port' => ''

Then I created a separate mysql instance on another port:

'host' => 'localhost',
'port' => '123'

But this does not affect drupal - it still connects to the old db on default port!

With the following settings drupal connects to the new db, but now I can`t make archive-dumps with drush. Drush reports an "Unknown MYSQL server host error".

'host' => 'localhost:123',
'port' => ''

For the port configuration in settings.php you can do by following(in example i used MYSQL in 33066) and the value of port is integer not string:

//D6 DB config
$db_url = 'mysqli://mysqluser:mysqlpassword@dbhost:33066/yourdb';

//D7 DB config
$databases = array('default' => array('default' => array(
  'driver' => 'mysql',
  'database' => 'yourdb',
  'username' => 'mysqluser',
  'password' => 'mysqlpassword',
  'host' => 'dbhost',
  'port' => 33066 )));


Add HTML to Ubercart's checkout table I have a product with an attribute called ID. This ID is a reference to an image the user has uploaded, its filename is id.jpg.

In the cart table where it lists attributes it has "ID: 4" for example but can I throw an img tag in there with src '...4.jpg'?

I'm a fairly competent developer however I haven't done any module development. Thanks!

I just wrote a quick test of this hook and got what I think you're looking for...

Here is your chance to write your first module. If you're up on PHP, creating a module and enabling it is a 10 minute task.

Once you have a module that your drupal installation recognizes as enabled, you're well on the way. I tested hook_cart_item and found the entire content of the cart...

Note that there are several invocations of this hook, you'll want to inject your changes at the appropriate stage.
In the example code below, I simply made a folder in sites/all/module/modcart
Then, created a module called modcard.module, (as wall as a modcard.info file).

/**
  * Implementation of hook_cart_item()
 */
 function modcard_cart_item($op, &$item) {
  global $user;
  $test = $op;
 }

Reference: http://www.ubercart.org/docs/api/hook_cart_item

Hope this helps.


I would like to create a view where I can add tags to content I am pretty new to Drupal and have not created a module yet. I think the solution I am looking for will have to be a custom module and would like some tips on how to get started. Basically I have a content type of beverages. In that content type I have a term reference field that points to a term called featured. Basically I can check the Featured check box and that content will be displayed in a featured slider. The featured beverages need to be changed periodically. I would like to create a view that lists all of the beverages and from within the view I can change which ones are featured. Can anyone help me with at least a starting point on how to accomplish this? I am using Drupal 7

First off, if all you need is a check box on your node form which toggles something as on or off - basically, a "Featured" state in this case - using taxonomy to achieve this is overkill. All you really need is an instance of a "Boolean" field.

Second, you can use Views Bulk Operations to operate on the results of a View. Basically, you can create a View with a column of check boxes much like the default content list in Drupal core. You can check a list of items - Beverage nodes in this case - and then select an operation to apply to the items you've checked. So yes, you'd need a custom module - a fairly simple one which would define "Make Featured/Unfeatured" actions, then implement callbacks to programmatically set/unset the "Featured" values on the selected nodes. See the VBO development guide for instructions on how to implement this.


CMS Vs Framework? Is Drupal A CMS, Framework, or CMF (Content Management Framework)? After Reading a Blog post: http://www.palantir.net/blog/drupal-not-cms  It made me curious about the current classification as CMS Vs Framework.

Please use Facts, where possible to justify your response.

CMS

A Content Management System (CMS)is a computer program that allows publishing, editing and modifying content as well as maintenance from a central interface. Such systems of content management provide procedures to manage workflow in a collaborative environment. These procedures can be manual steps or an automated cascade. CMSs have been available since the late 1990s.
CMSs are often used to run websites containing blogs, news, and shopping. Many corporate and marketing websites use CMSs. CMSs typically aim to avoid the need for hand coding, but may support it for specific elements or entire pages. Source: http://en.wikipedia.org/wiki/Content_management_system

Web Application Framework:

A web application framework (WAF) is a software framework that is designed to support the development of dynamic websites, web applications, web services and web resources. The framework aims to alleviate the overhead associated with common activities performed in web development. For example, many frameworks provide libraries for database access, templating frameworks and session management, and they often promote code reuse.

Source: http://en.wikipedia.org/wiki/Web_application_framework

If you would not consider Drupal 7 a Framework, do you think Drupal 8 would be?

Drupal is Content Management Framework (for Developers) as well as Content Management System (for Non-Programmers).

Drupal is a highly configurable open source and an application development framework providing the following features:

Drupal provides the structure for Web applications which is far more complex than a CMS such as:

Extend the functionality (using contributed or custom code).
Communicate with other Web applications.
Run applications written in PHP and other languages behind the scenes.
Provide responsive pages or integrate front-end languages.
Scale to handle large traffic numbers by making use of server technologies and provide the foundation for other as yet unthought of innovations.

Drupal is one of the most highly extensible frameworks available, and has the built-in ability to grow with your organization. Drupal was built from the ground up with a uniquely sophisticated granular level control system that provides unparalleled extensibility. With its vast feature-rich capabilities and growing community you’ll never outgrow Drupal.
Pre-made functionality in Drupal can be overridden through hooks, or you can find workarounds that Do Not require modifying other modules.
Drupal maintains a vigilant security community, providing security release updates on an ongoing basis to achieve maximum site security, which is one of the reasons even the U.S. Government and governments around the world use Drupal.
Drupal's modular architecture allows complex solutions to be "assembled" quickly and reliably. Over Fifteen thousand modules are available for Drupal.

CMS (Content Management System) features of Drupal:

Drupal comes with many tools to help you organize, structure, find and re-use your content. Categorize with taxonomy, automatically create friendly path urls, create custom lists, associate content with other content on your site, and create smart defaults for content creators.
Manage content with an easy-to-use web interface. Drupal's flexibility handles countless content types including video, text, blog, podcasts, and polls with robust user management, menu handling, real-time statistics and optional revision control.
Drupal comes with great options for new user accounts and user permissions. Users can be assigned one or more roles, and each role can be set up with fine-grained permissions allowing users view and create only what the administrator permits. The Drupal 7 admin theme makes administering a site easier than ever.
Drupal's focus on social publishing can help you create sites and applications to help your users express their opinions and engage with one another. You can have tight control over who can create, view, administer, publish and otherwise interact with content on your site.
Drupal's presentation layer allows designers to create highly usable, interactive experiences that engage users and increase traffic. Use an existing Drupal theme for your site, giving it an instant identity! If you can't find one you like, try designing your own which others can use, too.


Add custom fields to Ubercart orders I would like to add a few custom fields to Ubercart orders. These would be fields like "order assigned to" (which would allow an admin user to choose a user from the site's user list, or a simple text field where they can type a person's name). The fields would be updated via the order admin screen. Does anyone have any ideas on how this can be accomplished?

Thanks!

You can add custom fields to Ubercart orders the same way you add custom fields to content types. They can be added by going to Store -> Configuration -> Orders -> Manage Fields (admin/store/settings/orders/fields)

These fields would then be available on the order admin pages.

Hope that helps.


Drupal 7 Query database and display results same page in custom module template I want to see the results on the same scree after submit.

But my results php error:

  Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /var/www/html/includes/form.inc on line 368

I have tried to raise the memory limit in ini_set did not change.
I think that it is the cause the wrong my code.

My goal

Display the search results and input form on the same screen.
Search the external database with the value of the input form.
Keep the value of the input form.

Please help me with this.

Here is my code.

custom_search.module

function custom_search_menu() {
    $item['customsearch'] = array(
            'title'         => t('Form and Result'),
            'page callback' => 'custom_search_callback',
            'access arguments' => array('access content'),
            'type'          => MENU_CALLBACK,
    );
    return $item;
}

function custom_search_theme() {
    $path = drupal_get_path('module', 'custom_search');
    $rtn = array(
            'custom_search_template' => array(
                    'path' => $path,
                    'template' => 'node--customsearch',
            ),
    );
    return $rtn;
}

function custom_search_form($form, &$form_state) {
    $form = array();

    $form['my_checkbox']=array(
            '#type'=>'checkboxes',
            '#title'=>t('checkbox'),
            '#options'=>array(
                    '1'=>t('option1'),
                    '2'=>t('option2')
            ),
    );
    //There are some $ form[]

    $form['submit']=array(
            '#type'=>'submit',
            '#value'=>t('Submit')
    );

    return $form;
}

function custom_search_callback() {
    return theme('custom_search_template');
}

function custom_search_form_submit($form_id, &$form_state) {
ini_set('memory_limit', '512M');
    $options = $form_state['input']['my_checkbox'];
    //external database query use input options
    //The external database has already connected and got data
    $results[] = array('1','2','3'); //sample results
    $results[] = array('2','3','4'); //sample results
    return theme('custom_search_template',array('results' => $results));
}

node--customsearch.tpl.php

        <?php $form = drupal_get_form('custom_search_form') ?>
        <form role="form" id='<?php echo $form['#id'] ?>'
                            action="<?php echo $form['#action'] ?>"
                            method="<?php echo $form['#method'] ?>">

            <?php echo drupal_render($form['my_checkbox']) ?>
            <?php echo drupal_render($form['form_id']);?>
            <?php echo drupal_render($form['form_build_id']);?>
            <?php echo drupal_render($form['form_token']);?>
            <?php echo drupal_render($form['submit']); ?>

        </form>

results

      <!— I want results here —>
      <?php
      if(isset($results)) {
        foreach($results as $row) {
           echo "
";
           echo $row[0];
           echo "
";
        }
      }
      ?>

I got it.

    $form_state['storage']['results'] = $results;
    $form_state["rebuild"] = TRUE;

(I do not know whether this method is correct.)

Modified code.

custom_search.module

<?php
function custom_search_menu() {
    $item['customsearch'] = array(
            'title'         => t('Form and Result'),
            'page callback' => 'custom_search_callback',
            'access arguments' => array('access content'),
            'type'          => MENU_CALLBACK,
    );
    return $item;
}
function custom_search_theme() {
    $path = drupal_get_path('module', 'custom_search');
    $rtn = array(
            'custom_search_template' => array(
                    'path' => $path,
                    'template' => 'node--customsearch',
            ),
    );
    return $rtn;
}

function custom_search_form($form, &$form_state) {
    $form = array();

    $form['my_checkbox']=array(
            '#type'=>'checkboxes',
            '#title'=>t('checkbox'),
            '#options'=>array(
                    '1'=>t('option1'),
                    '2'=>t('option2')
            ),
    );

    $form['submit']=array(
            '#type'=>'submit',
            '#value'=>t('Submit')
    );
    if(isset($form_state['storage']['results']))
    {
            $form['results'] = array
            (
                    //'#value' => array('results' => $form_state['storage']['results']),
                    '#value' => $form_state['storage']['results'],
            );
    }

    return $form;
}

function custom_search_callback() {
    return theme('custom_search_template');
    //return theme('custom_search_template',array('results' => $results));
}

function custom_search_form_submit($form_id, &$form_state) {
    $options = $form_state['input']['my_checkbox'];
    //external database query use input options
    $results[] = array('1','2','3'); //sample results
    $results[] = array('2','3','4'); //sample results
    $form_state['storage']['results'] = $results;
    $form_state["rebuild"] = TRUE;

}

node--customsearch.tpl.php

        <?php $form = drupal_get_form('custom_search_form') ?>
        <form role="form" id='<?php echo $form['#id'] ?>'
                            action="<?php echo $form['#action'] ?>"
                            method="<?php echo $form['#method'] ?>">

            <?php echo drupal_render($form['my_checkbox']) ?>
            <?php echo drupal_render($form['form_id']);?>
            <?php echo drupal_render($form['form_build_id']);?>
            <?php echo drupal_render($form['form_token']);?>
            <?php echo drupal_render($form['submit']); ?>

        </form>
<?php
?>

results

      <!— I want results here —>
      <?php
      if(isset($form['results']['#value'])){
        $results = $form['results']['#value'];
        foreach($results as $row) {
           echo "
";
           echo $row[0];
           echo "
";
        }
      }
      ?>


How to stop Watchdog from logging "DEBUG" errors? I get this error in my logs a lot:

Deprecated function: Methods with the same name as their class will not be constructors in a future version of PHP; views_many_to_one_helper has a deprecated constructor in require_once() (line 127 of C:\...\sites\all\modules\contrib\ctools\ctools.module).

This is really not important to me and I don't want it filling up watchdog. Is there any easy way to tell Watchdog to not log these errors? Where can I change which errors get logged by watchdog?

The Drupal watchdog includes the errors raised by PHP, such as the one you mention.

It might be possible to use hook_watchdog to filter out certain errors. However, it seems easier to change the PHP error level on your settings.php file, so that PHP does not complain about your ctools module.

The list of possible PHP error levels is here: http://php.net/manual/en/errorfunc.constants.php
Some guidance about modifying the error levels on your settings.phpfile: https://www.drupal.org/docs/7/creating-custom-modules/show-all-errors-while-developing


SQL command to remove hypens from data value A commerce site that I am working on has products titles and skus in the format of DS-PC-CDJ2000.

The client wants the each hyphen removing and replacing with a space; DS PC CDJ2000

There are hundreds of products so I want to do this in the database if possible. What would be a suitable command to run on the relevant database tables?

To ensure caches are invalidated properly, and contrib modules get the chance to act on data changes, you should always make this kind of global change with the API.

If you've checked, and you're sure you won't suffer any ill-effects by not using the API, then:

UPDATE commerce_product SET sku = REPLACE('-', ' ', sku)
UPDATE commerce_product SET title = REPLACE('-', ' ', title)

And the same for the commerce_product_revision table. You may also need to run something like

UPDATE node SET title = REPLACE('-', ' ', title) WHERE type = 'product_display_type'

And the same for node_revision depending on how you have node revisions and product displays set up.

But direct DB access is not the recommended way to perform a task like this. Take a backup before trying anything just in case


Generate https image URL In order to generate full path of images(URL) on views for rest endpoint on my decoupled Drupal project I'm using Image Url Formatter module, everything works correctly until I decide to put the website on HTTPS, In console I see
Loading mixed (insecure) display content
“http://core.domain.com/sites/default/files/styles/874x492/public/gallery/2017-01/1-907331.JPG?itok=MKfQSWFh” on a secure page

it's because this formatter return HTTP Instead HTTPS for image URLs.

In the situation like this that the websites should work on HTTPS and HTTP both, I advise  my team using //domain.com  instead of http://domain.com or https://domain.com in all endpoint URLS

Now I looking for a solution to return all images URL from http://.... to //... . if I had few views I could benefit REWRITE feature of view but I have a lot of views rest export endpoint.

What is your solution for this requirement?

Doing a quick test, works fine with HTTPS

Views REST XML

Views REST Json

All of the above is using FULL URL

Perhaps someone set it to Absolute file path, which will give you /path/image.jpg (with out the $base_url). Then in some template file they did http://example.com{{ field.image.content }}

update

using template_preprocess_image_formatter() is another solution to change the template formatter of the image.


Printing out translated Views' variables I have a View, with its title translated to all enabled languages. When in tpl file I say: print $views->human_name, the title printed is stuck at the original language though. Any workaround for that, please?

$title = $view->get_title();

Views' human-readable name is just for developers and is not translated by i18nviews. You might want to get title.


Form fields still treated as required even after setting #required to false I'm using hook_form_alter to remove the "required" setting for a couple of fields, specifically the First name and Last Name fields on the Address form.

Here's my code, where I provide a callback function for #after_build to remove the required setting:

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'listing_edit_form') {
    $form['address']['widget'][0]['address']['#after_build'][] = '_mymodule_customize_address';
  }
}

function _mymodule_customize_address($element, $form_state) {
  $element['given_name']['#required'] = false;
  $element['family_name']['#required'] = false;
  return $element;
}

The problem is that after I submit the form, the fields are still treated as required, which means that if I don't enter any data for them the submit fails with an error message telling me that those fields are required.

Note that even if I hide the fields by setting #access to false, the form submit will still complain that they are required. So it seems to be a backend issue with the Address module.

I have:

Drupal                  8.7.1
drupal/address          1.6.0
commerceguys/addressing 1.0.3
commerceguys/enum       1.0
commerceguys/intl       1.0.4

I'd appreciate any help with this. Thanks!

Have you tried unset() on the #required element, rather than making it false?


PDOException Error upon saving node with computed field I have a node with three fields that I need to concatenate into a single computed field: title, icon, and track. Track is a term reference to a taxonomy term, and icon is a field attached to the taxonomy.

In my computed code, I'm using this:

$tmp = field_get_items('node', $entity, 'field_track_term');
$track_tax = taxonomy_term_load($tmp[0]['tid']);
$field_items = field_get_items('taxonomy_term', $track_tax, 'field_track_icon');
// Get the first item (fields can have multiple items so field_get_items always returns an array)
$first_item = array_shift($field_items);
// Get the URI
$uri = $first_item['uri'];

$icon_vars = array(
   'path' => file_create_url($uri),
   'attributes' => array(
      'class' => array('session_list_track_logo')
   )
);
$icon_img = theme_image($icon_vars);

$sess_num_tmp = field_get_items('node', $entity, 'field_session_number');
$sess_num = $sess_num_tmp[0]['safe_value'];
$sess_title =  $entity->title;

$entity_field[0]['value'] =  $icon_img . " " . $sess_num . " | " . $sess_title;

I've set it to save to the database, field type text, no size limit. What I'm trying to save to the database is a string that looks like this:

<img class="session_list_track_logo" src="http://example.com/sites/default/files/track_icon/shopper_marketing_best_practices.png"
 /> A22 | In-Home Insights that Drive In-Store Purchase Decisions

When I try to save a node, I get the following error:

  Notice: Undefined index: safe_value in eval() (line 18 of
  /home/www/expo/sites/all/modules/contrib/computed_field/computed_field.module(466)
  : eval()'d code).

  PDOException: SQLSTATE[22001]: String data, right truncated: 1406 Data
  too long for column 'field_computed_label_value' at row 1: INSERT INTO
  {field_revision_field_computed_label} (entity_type, entity_id,
  revision_id, bundle, delta, language, field_computed_label_value)
  VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5,
  :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => node
  [:db_insert_placeholder_1] => 163 [:db_insert_placeholder_2] => 163
  [:db_insert_placeholder_3] => session [:db_insert_placeholder_4] => 0
  [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] =>  | The Path to Purchase Begins At-Home: In-Home Insights that Drive
  In-Store Purchase Decisions ) in
  field_sql_storage_field_storage_write() (line 449 of
  /home/www/expo/modules/field/modules/field_sql_storage/field_sql_storage.module).
  The website encountered an unexpected error. Please try again later.

(Note that the image string is included in the query shown after the db_insert_placeholder_6 line; I just can't get SO to format it correctly inside a blockquote.)

I'm not too worried about the first part of the error; I'm obviously just not getting at the session number correctly. What I'm unsure of is what's causing the PDOException error. It says the data is too long for the column. I've double-checked in the database, and the column is definitely set to text with no size limit.

So why would the simple string that shows up later in the error be too long to save?

Just out of curiosity, I set the computed code to do nothing but this:

$entity_field[0]['value'] = $entity->title;

I got the same error.

I encountered a similar error on my current project and fixed it by adjusting the size of the related field.

Try using PhpMyAdmin to view the 'field_computed_label_value' table and then select the structure tab.  It will list the type as varchar(###) where ### = the character limit for the string.

Try increasing the size of the type for the field value by selecting the 'change' icon for the value row and then adjusting its length.

Remember to back-up before trying this in case it does not solve our problem.


Drupal 7 different urls with same information I have a new drupal site,it was built by other website designer.Now i got a problem for the url.There are some different url with same information.For example:
"/taxonomy/term/31/0" and "/projects/led-tunnel-lighting".I only need the url like "/projects/led-tunnel-lighting".
Please tell me how to fix this problem.Thank you very much!
I was a novice of drupal.

Whenever you need to link to a node or a term (or something else in which might have an URL-Alias), use the l() function. The link to the term will then be rewritten to the given URL-Alias (as long as there is one).


Voting a post several times by same user I have a case where authenticated users can Vote a content many times.

I want a button at the top of the Node saying Vote This and when the users click the button it'll ask for confirmation Do you really want to Vote ?. When confirmed, he'll be redirected back to the same page, and be able to click the button again. However, in the backside, I want to record the time of voting and the user who voted it. Not necessarily the vote count, but just date/time and person.

I tried this with the Flag and Global Flag modules, but the issue is: once flagged, it can only be unflagged.

I also tried Fivestar module, with just one star (which I can change it to a button via CSS), but it doesn't ask for confirmation. It doesn't record the date/time either (I might be wrong here, but playing around with Fivestar, I didn't find a configuration option).

There must be something with VotingAPI which might be useful in my case, but I am unable to identify how to satisfy these conditions. I am seeking guidance.

Update: In addition to @Adam Balsam's answer to have confirmation I did

Use jQuery to add id to the link like: (I only have one vote in node)

$('.plus1-link').attr('id', 'vote-plus');

Then added jQuery confirm dialog like:

$('#vote-plus').click(function(e) {
               var cnf = confirm('Do you really want to vote?');
               if(cnf === false) {
                   e.preventDefault();
               }
            });

It might not be the elegant solution, but this how I solved my confirmation dialog option.

Here's something you could try.

Create a content type, Vote.  Add an Entity Reference field (to link the vote to the relevant node).

Then, allow users to vote with flags.  When a user flags the content, use a Rule that goes something like this:

Event: Node is flagged
Action 1: Create an entity, a node of type vote (Author: logged-in user, also make sure to set the entity reference field value to the current node)
Action 2: Unflag the node

This way, the user will be able to flag the node multiple times and each time a vote node will be created that will include the date and time of each vote.


Broken/missing handler views 2 Drupal 6 Recently I created a new Content type and Added a bunch of CCK fiekds in it. After that I migrated some contents to the system using node_save() function.

Everything was fine until I cleared the cache then 3 of my existing views broke and started to say "Views Broken/missing handler" in some of the fields and in filters. Though the fields do exist as the CCK fields in the proper content type.

See the attached image
When I try to remove or modify the field then it says "An illegal choice has been detected. Please contact the site administrator." Also the field formats is not show. Refer to the below image.
These fields though exist in the CCK as per the below image.
To make the site working again I have to go to the Content type's Manage Fields page and click on save. Then it starts to show in proper way (Followed: https://drupal.org/node/624826). The problem is if I clear cache then again this happens.
I had backed up the database before the migration and once I saw this then I DROPPED the total database and again imported the sqldump in the blank database but then again once I cleared the cache it again showed Broken/missing handler.

I am totally confused here. Searched Google but didn't got a proper solution. After dumping the old database still its happening. Is it that Views and CCK is storing something while I created the CCK? We are using Memcache in the system, but I suppose that has nothing to do with it.

Please help me on this.

I have found that MAX OPEN FILES can have an impact along with maximum size of object, my understanding is this is the case with or without memcache but I have not proved that yet. I created a tool with cURL to log broken views when they occur and use Munin to monitor everything as it happens: https://drupal.org/node/89710#comment-8351855