How can you put a user profile item in a category on the user's account information page? My attempt is:

function mymodule_user($op, &$edit, &$account, $category = NULL)
{
  switch($op)
  {
   (...)
      case "view":
         $account->content['my_cat']['plant_1'] = array(
                    '#type' => 'user_profile_item',
                    '#title' => 'Plant 1',
                    '#value' => '42',
                    );
  }

But that doesn't work as the 'Plant 1" form element appears at the top of the page without a category. The categories seem not to be derived from $op = "categories" where I defined 'my_cat'. So how can I tell Drupal that "Plant 1" should be in the my_cat category on the user account information pages?

In the meantime I've figured it out. The categories are also defined in the 'view' operation by using the type 'user_profile_category'. For example:

$account->content['my_cat'] = array(
          '#type' => 'user_profile_category',
          '#title' => 'Plants Summary',
         );


View to show user relationships with different fields I am using the User Relationships module to allow users to forge relations between themselves. The relationship is 1 way of type Following. I have been able to do so. Now i want to create a view for the logged in user which would show him or her their pending relation request, the people they are following, and the people who follow them I tried to do so using Views and contextual filters and adding different fields but was unable to successfully do so. My use case is :  http://i.imgur.com/oYEQzUa.jpg

Thanks

You need to first add a users view and then you add a contextual filter to the view using the user field that the relation will have now exposed in the contextual admin selection. Then add a default value of currently logged in user to the contextual filter and with that it will expose the relevant fields.

Add new view of type users
Add contextual filter of type user relationships: User who accepted the relationship
Add default value of logged in user
(optional but will expose even further info) add views relations to expose further data
profit


Field widget do not save values in database! I have a strange problem. I'm designing a new field type using field-API with a widget of course.
My widget display is ok but when I save a node the field do not save the value entered in the widget..

This is the hook_field_schema()

function MODULE_field_schema($field) {
  $columns = array(
    'streamtype' => array('type' => 'varchar', 'length' => 25, 'not null' => FALSE),
    'streamtag' => array('type' => 'varchar', 'length' => 25, 'not null' => FALSE)
  );
  return array(
    'columns' => $columns,
  );
}

And this in the hook_field_widget_form()

function MODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

      switch ($instance['widget']['type']) {

        case 'MODULE_default_widget':
          $item = $items[$delta];

          $element += array(
            '#type' => 'fieldset',
            '#delta' => $delta,
            '#element_validate' => 'MODULE_field_basic_widget_validate'
          );

          $element['streamtype'] = array(
            '#type' => 'radios',
            '#title' => t('Stream type.'),
            '#description' => t('Search images by:'),
            '#options' => array('author' => t('Author name'), 'tag' => t('Tag')),
            '#weight' => isset($element['#weight']) ? $element['#weight'] : 0,
            '#delta' => $delta,
            '#default_value' => isset($item['streamtype']) ? $item['streamtype'] : NULL
          );

          $element['streamtag'] = array(
            '#type' => 'textfield',
            '#title' => t('Stream tag'),
            '#description' => t('Insert author name or tag depending to the selected steam type'),
            '#required' => $instance['required'],
            '#weight' => isset($element['#weight']) ? ($element['#weight'] + 1) : 0,
            '#delta' => $delta,
            '#default_value' => isset($item['streamtag']) ? $item['streamtag'] : NULL
          );

          break;

      }

      return $element;
    }

The basic fieldset have a validation function and, in this one i can see the correct value in the $item.
An example from watchdog()

Array ( [0] => Array ( [streamtype] => tag [streamtag] => tag1, tag2, tag3 ) )

Where can i search the error?
Please help me, this problem is driving me crazy T____T

So it turns out Shyghar ran into an issue that I've run into more than I care to tell – which is that hook_field_is_empty() was returning FALSE by checking the wrong data (or something along those lines).


array_flip() error while creating a menu item with form My aim is to create a new menu item and display the user profile form on that page.

Here is the code I am using.

/**
 * Implements hook_menu().
 *
 */
function profile_preferences_menu(){
    $items['user/%/edit/profile-preferences'] = array(
        'title' => t('Profile Preferences'),
        'page callback' => '_profile_preference_display_preference',
        'page arguments' => array(1),
        'access arguments' => array('access profile preferences'),
        'type' => MENU_LOCAL_TASK,
        'weight' => '0'
    );
    return $items;
}

/**
 * Implementation of hook_permission().
 */
function profile_preferences_permission() {
    return array(
        'access profile preferences' =>  array(
            'title' => t('Access List of profile preferences'),
            'description' => t('Access permission to view all the profile preferences.')
        ),
    );
}

/**
 * Function to fetch and display preferences form.
 */
function _profile_preference_display_preference() {
    global $user;
    module_load_include('inc', 'user', 'user.pages');
    $form = drupal_get_form('user_profile_form', $user, 'account');
    unset($form['account']);
    return $form;
}

When I access it using the administrator account, it works perfectly; when I access using another user account (who has the required permission) it gives me the following error.

I wonder if there is any issue with the implementation of hook_menu().

The code that is causing the error is the following one, executed from DrupalDefaultEntityController::load().

  // Create a new variable which is either a prepared version of the $ids
  // array for later comparison with the entity cache, or FALSE if no $ids
  // were passed. The $ids array is reduced as items are loaded from cache,
  // and we need to know if it's empty for this reason to avoid querying the
  // database when all requested entities are loaded from cache.
  $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;

I could not track down which function is calling user_load() or a similar function to load a user entity. As far as I can see, the form validation and form submission handlers added to the form use $form['#user'] or $form_state['user'] (which is set from the $account parameter passed to user_profile_form()). Keep in mind that $form and $form_state are used when saving the entity, such as in the following function call done from user_profile_form_submit().

entity_form_submit_build_entity('user', $account, $form, $form_state);

It is always a bad idea to unset a form item, as that would be causing problems with the code that expects those form items to be present.
Removing them, you are also avoiding that the corresponding items in $form_state['values'] are present. This is probably causing the error you see.

As side note, your page callback is getting a parameter, but that is not used. Instead, your code is using the global user object, which means the shown form is for the currently logged in user, not for the user whose ID is passed in the URL.

I would also change user/%/edit/profile-preferences with user/%user/edit/profile-preferences. The latter automatically validates the user ID and loads the user object, which is then passed to the page callback.


DOMPDF not showing images and writing empty tmp files via print module I recently moved a Drupal 7 website from my development server to my pre-production server, and the rendering of the images from both the Body field and various images fields stopped working.

I now see "Image not found" and the URL of the image (which is working when I click on it by the way) on the generated PDFs.

The URLs from the Body field look like this "/mywebsite/sites/default/files/myimage.jpg" and the URLs of the "Image" fields are complete URLs with "http://mydomainname.com/mywebsite/……".

www-data has access to the images files and can also write in /tmp.
And it does, actually, every time I generate a PDF with images. But the files are empty:

$> find /tmp -name "*dompdf*" -ctime -1 | xargs ls -lArth
-rw------- 1 www-data www-data 0 janv.  4 15:30 /tmp/ca_dompdf_img_0DlQ4V
-rw------- 1 www-data www-data 0 janv.  4 16:01 /tmp/ca_dompdf_img_Tyvv8w
-rw------- 1 www-data www-data 0 janv.  4 16:27 /tmp/ca_dompdf_img_pa4m4V
-rw------- 1 www-data www-data 0 janv.  4 16:27 /tmp/ca_dompdf_img_5RzNHk
-rw------- 1 www-data www-data 0 janv.  4 16:28 /tmp/ca_dompdf_img_T21gUJ
-rw------- 1 www-data www-data 0 janv.  4 16:29 /tmp/ca_dompdf_img_OmWxt2
-rw------- 1 www-data www-data 0 janv.  4 16:33 /tmp/ca_dompdf_img_SmA57m

I tried checking "Access images via local file access" in the "print" configuration page, but with no luck.

This may be an issue related to the server configuration, since it was working before on the development server, but I'm running out of ideas…

It's because your permission is -rw------- which only has read and write, there is no execute.

Use chmod -R 0775 sites/default/files


syntax error, unexpected '[' I am tring to get DRUSH (drush-master) up and running on a CentOS release 6.8 (Final) virtual server using PHP version 5.6.22. I will copy the php & DRUSH outputs below including the final error message:

Looking through the forums there is mention of the cause being an outdated version of PHP. However, I've checked the requirements and am pretty sure these versions should be compatible.

[server2 drush]# which drush
/usr/bin/drush
[server2 drush]# ls -lart /usr/bin/drush
lrwxrwxrwx 1 root root 35 Sep  2 16:05 /usr/bin/drush -> /usr/local/drush/drush-master/drush*
[server2 drush]# /usr/bin/php56 --version
PHP 5.6.22 (cli) (built: Jul  5 2016 15:31:36)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
[server2 drush]# /usr/bin/php56 /usr/bin/drush

  Parse error: syntax error, unexpected '[' in /usr/local/drush/drush-master/includes/preflight.inc on line 248

The syntax error you are seeing implies that you are actually running php 5.3.  I can see that /usr/bin/php56 is version 5.6.22, but does $(which php) really point to /usr/bin/php56? Double-check your $PATH.


How do I display highly customized content? What is the correct way to display parts of a highly customized application? For example my website only consists of a friendlist with user name as well as images and a live chat frame.

Is this the right approach?

Create Theme with 2 regions (friend_list, chat_frame)
Develop custom Blocks for each feature (friend_list Block and chat_frame Block)
Assign Blocks to the regions
Style each Block individually to fit my requirements
Add javascript for each block for chat and asynchronous updating of the friendlist (ajax)

Is it better to place all features in one module? Can one module have multiple blocks?

Looks like this is a job better suited for a JavaScript web app (Angular, React, etc.) than using Drupal to render the UI. You can create a dummy module whose only job is to load the JavaScript for your webapp. Then it's all JS from there.

For the back end, assuming Drupal is also powering the data layer, you can use the REST API features of the Views module to send and retrieve data.

Additionally, I wouldn't use block layout for the layout of the site since it's a global layout. This hampers further customization of the layout of the site. Consider using Panels to create dedicated pages that have their own layout. Imagine block layout, but only for a specific page or set of pages.


Given a form, how do I find the fields present in them? How do I get the list of fields present in a certain form, I know the form id, I just need the names of the fields present in that form ?

go to your template "template.php for example" or your module, and use

hook_form_alter(&$form, &$form_state, $form_id){
  var_dump($form);exit();
}

and you will get very detailed look at your form


RSS feeds: How to reformat/rewrite/restyle? Using views? e.g. convert youtube text list of videos into thumbnails? How can a RSS feed be reformatted/rewritten/restyled to be more useful?

For example Youtube RSS feeds from the video uploads of a youtube user appear as a plain text list by default.

Are there drupal module(s) or a solution out there that parses this content to be able to transform it into something more useful? E.g. in the case of youtube, make it show the list as thumbnail stills of the videos uploaded.

Yes Views will be the perfect module choice for you, there are many ways to tweak the output with Views & it has built in Feeds support.  Google about drupal views rss feeds, you'll find a ton of info.  When you install views there is an example rss feed view you can enable and take a look at to see how its done.  As for the thumbnails if your using emfield you should have the option to display thumbnail when tweaking the field output from within the View.

Good luck!


How to hook "/system/ajax" with javascript in Drupal 7 When a field accepts multiple values, the admin form adds a button "Add another item". Mousedown submits a POST to /system/ajax to get another field (i'm using multifield here).

I'd like to hook into the javascript completed event to do some custom handling on those additional fields.

How can I most easily hook these ajax calls for javascript callback and reference to the block being added? Is it possible without PHP?

You can use hook_menu_alter and define your own custom callback function like below.

function demo_pane_menu_alter(&$items) {
  $items['system/ajax']['page callback'] = 'demo_pane_taxonomy_autocomplete';
}


Error when submit a Webform with Ajax using Jquery I am having a webform in my drupal. I am using the jquery Ajax submit method to submit it.

This is the code I am using.

$("#webform-client-form-59--3").ajaxForm(function() {

$(".talk-region").html("
Thankyou,
 Our representative will be contacting you soon.
Close")

});

$("#webform-client-form-59--3").validate();

But when I check in firebug.. Its posting, but the response am getting is

302 Moved Temporarily
        5.2s

If you want to submit a webform, or any form for that matter, with jquery try calling the .click() event for the submit button or call the .submit() function for the form object.  If it's properly 'ajaxified' by drupal (using the use-ajax class) the click on the submit button should def submit the form.

jquery .click()

jquery .submit()


How to update 8.0.x to 8.1.x with composer? This is excerpt from my composer.json file (trimmed for readability). It was created by running composer create-project drupal/drupal my_site_name 8.0.* as described on drupal.org:

{
  "name": "drupal/drupal",
  "type": "project",
  "require": {
    "composer/installers": "^1.0.21",
    "wikimedia/composer-merge-plugin": "^1.3.0"
  },
  "replace": {
    "drupal/core": "~8.0"
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
  "extra": {
    "merge-plugin": {
      "include": [
        "core/composer.json"
      ],
      "recurse": false,
      "replace": false,
      "merge-extra": false
    }
  }
}

If I just do composer update - core is not updated, only packages inside vendor dir.
If in addition to the above, I update my composer.json file and replace core version with ~8.1 - still core not affected.

The only thing that worked for me was to:

Remove core dir, vendor and composer.lock.
Edit composer.json and:

Remove replace section.
Add "drupal/core": "~8.1" to require section.

Run composer install.

That worked however every installed package complained that:

  Class Drupal\Core\Composer\Composer is not autoloadable, can not call post-package-install script

So I'm not sure if the whole process completed flawlessly. Also removing core directory seems like a desperate move.

What is the recommended procedure of updating core to the next minor version with composer (for example 8.0 => 8.1)?
Note that I am not using drupal-composer as suggested in this answer.

Update 1

After trying to use composer require --update-with-dependencies "drupal/core:8.1.*" I got no results:

$ composer create-project drupal/drupal my_site_name 8.0.*
Installing drupal/drupal (8.0.6)
  - Installing drupal/drupal (8.0.6)
    Cloning c5afca05cde0c94ef4d7aff5b078be27024670d2

Created project in my_site_name
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess
Do you want to remove the existing VCS (.git, .svn..) history? [Y,n]? Y
$ cd my_site_name/
$ composer require --update-with-dependencies "drupal/core:8.1.*"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

I'm using composer version 1.1-dev.

I see, you directly get drupal/drupal. I don't think that's actually supported, you still get a vendor folder from git and the composer.json isn't properly set up. I'm using composer command from this site:

composer create-project drupal-composer/drupal-project:8.x-dev myproject --stability dev --no-interaction

Regarding update, the trick seems to be the following argument to composer require:

composer require --update-with-dependencies "drupal/core:8.1.*"

That updated drupal/core and all dependencies it has.


HTML code to PHP code mapping does not work I am trying to include the timeline API, and install the timline files on my webserver. The timeline-api.js gives an example of an HTML page that contain the following code.

<script>
var Timeline_ajax_url="http://YOUR_SERVER/apis/timeline/ajax/simile-ajax-api.js";
var Timeline_urlPrefix='http://YOUR_SERVER/apis/timeline/';
</script>
<script src="http://YOUR_SERVER/javascripts/timeline/timeline-api.js"
type="text/javascript">
</script>

It also contain the following comment.

   /*
    * Eg the two next lines pass the same parameters:
    * Timeline_parameters='bundle=true';                    // pass parameter via js variable
    * <script src="http://....timeline-api.js?bundle=true"  // pass parameter via url
    */

I am trying to do the same thing in Drupal using the following code.

$timeline_lib_path = $base_path . libraries_get_path('simile_timeline');
// Set some global js variables that the library is going to need for proper inclusion and functionality.
$timeline_inline_js = "
var Timeline_ajax_url = '$timeline_lib_path/timeline_ajax/simile-ajax-api.js',
Timeline_urlPrefix = '$timeline_lib_path/timeline_js/',
Timeline_parameters = 'bundle=true';
";
drupal_add_js('similetimeline',$timeline_inline_js);
drupal_add_js('similetimeline','$timeline_lib_path/timeline_js/timeline-api.js');

I have an uncaught reference error: Timeline is not defined.

You have the smallest of errors in your code; in the very last line you're trying to interpolate a variable into a string using single quotes. You need to use double quotes instead:

drupal_add_js('similetimeline',"$timeline_lib_path/timeline_js/timeline-api.js");

Have a peek at the PHP Strings Documentation for more information.

I've just noticed another problem actually; you don't seem to be using drupal_add_js() properly. The first argument should be the name of a file or an inline string, in which case you should specify that it's inline:

drupal_add_js($timeline_inline_js, 'inline');
drupal_add_js("$timeline_lib_path/timeline_js/timeline-api.js");


Adding rel=canonical meta tag in comment paginated node pages in Drupal 7 This question is same as that of Drupal 6 question: Adding rel=canonical meta tag in comment paginated node pages but for Drupal 7.

How can I add rel=canonical tag in the paged urls ( like ?page=1) pointing to the main version one?

I could find the feature in the Nodewords module in Drupal 6. But the Metatag counterpart in Drupal 7 does not seem to have any such option.

Answer to the original suggests Nodewords. And D7 replacement of Nodewords  module is Metatag module, that supports canonical links.

  Meta tags have additional uses like the Open Graph Protocol used by Facebook, specifying the canonical location of content across multiple URLs or domains.


How to get ordered list display for Top Emails in Forward Module? I'm using the Forward module for keeping track of article content being emailed thru my site. I've been looking thru the module files to see where it is rendering the top5 (I modified it to Top10, instead) entries as an unordered list and have been unable to locate where this is.

Can anyone help with this?

Below is a sample of a basic unordered list showing from the Forward module block (I need this to render as an ordered list, instead):

Found Go to forward.module

search for this "function forward_top5_list(" and change

"$query->range(0, 5);" from 5 to 10

this will work


How to incorporate the body field back into a content type from which it has been previously deleted? I am on D7. In the past, I have deleted the body field from a certain content type in my project. Now, the problem is that I want the body field back into this same content type, but cannot find it in the list of existing fields in my project to be added to the content type. How can I add the deleted body field back into the content type? Is it possible? It is important to say that I don't want its content back. I just want the regular Body field with the original ID body, instead of creating a "field_body". Thanks.

In a hook_update_n(), module_install(), module_enable(), or devel module eval php code:

$types = node_type_get_types();
node_add_body_field($types['my_content_type_name']);

giving it the machine name of your content type, and optionally you may provide a label for what you want the human readable label for the field to be (defaults to 'Body'). see node_add_body_field() API documentation


db_select throws PDOException Trying to do a simple query from a table called 'raffles' under the drupal database.

It is not a complex query, Just trying to get all sets from drupal.raffles

$query = db_select('raffles');
$query->execute();
$result = $query->fetchAssoc();
dpm($result);

The error

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM raffles raffles' at line 1: SELECT FROM {raffles} raffles; Array ( ) in raffle_create_form() (line 8

From the error, the query has the table name twice, and is probably what is causing the error. maybe im doing something wrong? There is not much information related to this on the api page.

Any help would be gladly appreciated.

Thanks.

You haven't selected any fields:

$result = db_select('raffles', 'r')
  ->fields('r', array('foo', 'bar'))
  ->execute()
  ->fetchAll();

If you want to select all the fields, then use the following code.

$result = db_select('raffles', 'r')
  ->fields('r')
  ->execute()
  ->fetchAll();

Incidentally, the second raffles is a valid alias and not related to the problem.


default_content import error field content_translation_source is unknown I've exported a custom block content using default content module, when trying to import, I'm getting error

[ERROR] Field content_translation_source is unknown.

I've all 4 language modules enabled.

Content translation module was enabled but content translation was not enabled for custom block. Enabling it fixed the error.


Trying to get property of non-object in simplenews_scheduler_node_page() I am using simplenews_scheduler in Drupal 7 to set up a weekly digest of new content. I am getting the following error on the screen and scheduled newsletters aren't going out, even after running cron. When I send it right away or send it as a test, it goes out and renders just fine.

  Notice: Trying to get property of non-object in
  simplenews_scheduler_node_page() (line 600
  sites/all/modules/simplenews_scheduler/simplenews_scheduler.module)

For reference, here is lines 598-601, referenced in the error:

foreach ($result as $row) {
    $node = node_load($row->eid);
    $rows[] = array(l($node->title, 'node/' . $row->eid), format_date($row->date_issued, 'custom', 'Y-m-d H:i'));
  }

I'm not sure this error is related as it seems to go only to loading editions already sent.

Drupal 7.65, simplenews 7.x-1.1, simplenews_scheduler 7.x-1.0-beta2

Does anyone know what could be causing this error or an alternative to sending a scheduled mailing? The module makes a copy of a base node each for each edition so it's kind of nice.

This issue was solved by deleting the node (master newsletter) and creating a new one. I had probably deleted a previous test edition, which caused it to start delivering the error. If there is only one test edition, don't delete it even if the master is preserved.


AJAX loading of a view on click of a button? I want to switch between two methods of sorting and displaying items in Views by toggling a button. My exposed filters are in the URL so I want to include the query in the path in order to keep the exposed filter results. Both displays of the view have "use ajax" set to "yes".

My link is :

$link_path = ($display_data->display_options['path'] . '/nojs');
$query = drupal_get_query_parameters();
$toggle_link = l($toggle_icon, $link_path, array('html' => true, 'query' => $query, 'attributes' => array('class' => array('use-ajax'))));

Which outputs something like:

[omitted SVG path for brevity]

In a js file in my theme, I have:

    /**
     * Toggle button and ajax views
     */
    var viewId = settings.mytheme_toggle_view.view;
    var viewDisplayId = settings.mytheme_toggle_view.current_display;
    var viewOtherDisplayId = settings.mytheme_toggle_view.other_display;
    $.ajax({
        url: settings.basePath + 'views/ajax/' + settings.mytheme_toggle_view.query,
        type: 'post',
        data: {
          view_name: viewId,
          view_display_id: viewOtherDisplayId,
          view_args: {}, // your views arguments
        },
        dataType: 'json',
        success: function (response) {
            var newView = ($(response[1].data));
            $(".view-display-id-" + viewDisplayId).replaceWith($(newView));
        }
    });
    /* End views ajax stuff. */

What happens now:

I go to my view and select my exposed filters and hit "apply"
I arrive at my view's default display page
Before I can click anything, AJAX fires and replaces the view content with the alternative view content.
If I click the toggle, it is a link (with full page reload, not AJAX) to the default display page again.
Step 3 repeats.

What I want is for the view to

Not change on pageload, but wait until the toggle button is clicked
Be able to be toggled back and forth rather than only toggling once and then becoming a regular, page-reloading link.
Preserve the exposed filters
Have the pager still work (currently is a link to some JSON output of the settings object).

Views Modes

  A Drupal Views display plugin which provides alternate display modes
  that can be switched to for a single View. This allows exposed filter
  parameters or contextual filters to be kept active while switching
  display mode.

Sounds like this module does what you're trying to do. There's only a dev version, but might be worth a look.


How to track IP addresses I want to track IP address of visitors in my site using statistics module.

A log of which is attached here( 3 day log). I can't figure out if an IP address is used by a bot or human being. For example when I checked the 2nd and 3rd IP address, they turned out to be that of Google and Microsoft( Bing). But I've no idea about the first ip address with 900 visits in 3 days.

I want to track malicious user ip address for Adsense invalid clicks.

What module are you using to get the list of IPs ? You need a Reverse DNS lookup to integrate with your module, I wasn't able to find such module on drupal.org but there's a lot of sites that provides such service like Domain tools: lookup for 203.153.44.130 .


Display number of tagged nodes for each term in a view? I have a view of all of the terms in a vocabulary. How can I in the same view list the number of tagged nodes for each term? Thanks

First you have to make sure you can get the nodes tagged with each term to display, and then we'll get them so their COUNT is listed.

Add the 'Taxonomy term: Content with term' Relationship to your terms view (under the 'Advanced' section)
Now you should be able to see, in the list of fields, things such as Content: Title, etc.  Add the content title, and make sure it's set to use your newly created relationship.

This should get all the nodes tagged with each of your terms to be displayed under the term.  But how to count them??

The way you can do that is by enabling the use of aggregation for your view!  Under the 'Advanced' section of your view, locate the 'Use aggregation' setting and make sure you enable it.  It's disabled by default:

Once you've done that, you'll see by all of your fields a new 'Aggregation settings' field, which you can set to be 'Count' for the node title that relate to each taxonomy term.

That should do it!  Let us know if you get it working!  :-)


hook_menu, display a form at the top and table at the bottom I'm a bit lost trying to create a page with hook_menu that displays a form and a table below it. Preferably the table should only be displayed after the form has been submitted, but that's not the main issue.

I don't have any issue with displaying the table or the form, but I can't get it to be displayed at the same time on the same page.

I have a my_module_table() function that ends with

...
return theme('table', array( 'header' => $header,  'rows'=> $rows  ) );

I then have a function for the form my_module_form($form, &$form_state)

I then have this function to put both of these functions in an array

function my_module_page() {
  $output = array();
  $output['form'] = drupal_get_form('my_module_form');
  $output['table'] = 'my_module_table';
  return $output;
}

Than last I try to create the page and get both the form and the table to render on the page using hook_menu

function my_module_menu() {
  $items = array();

  $items['mymodule'] = array(
    'title' => 'My module',
    'access callback' => TRUE,
    'page callback' => 'mymodule_page',
  );
  return $items;
}

I don't have any issues with the form or table functions, they work fine if I don't try to render both at ones.

Can anybody tel me what I'm doing wrong?

Here's an implementation of my earlier suggestion to append the table as a form markup and rendering the form with table in the menu callback

/**
 * Form builder function
 */
function mymodule_form() {
  $form = array();
  $form['sometext'] = array(
    '#type' => 'textfield',
    '#title' => t('Some random textfield'),
    '#default_value' => 'Hello world',
  );
  $form['tablemarkup'] = array(
    '#markup' => my_module_table(),
  );
  return system_settings_form($form);
}

/**
 * Callback function for returning form with themed table
 */
function mymodule_page() {
  $output = array();
  $form_data = drupal_get_form('my_module_form');
  $output = drupal_render($form_data);
  return $output;
}

/**
 * Function to return themed table.
 */
function my_module_table() {
  $header = array(
    'data' => 'Table title',
  );
  $rows[] = array(
    'Table data value',
  );
  return theme('table', array('header' => $header, 'rows'=> $rows));
}


How to create a sort features In Drupal? I'm new to Drupal and want to create a sort option (to sort some Forum topics) so that a user can select any topic and apply it.

Here is an image to better illustrate this:

How to make such sort option?

Use advanced_forum module.
See the image attached, it provides sort option.


How to change the html of threaded comments? I want to display the comments on a node in a thread.

Not sure if I should use views or a template.
I want to change the html so that it matches boostrap markup
By using comment-wrapper.tpl I can change some of the html,
but I cant change the indent class.

Could you give a little more info on what you are trying to do?

If you want to add your view for displaying comments to a specific thread, please take a look at using panel from contrib (https://drupal.org/project/panels).

This module allows you to add views (and other components as well) to specific pages, other panels (when using mini panels) etc...


drush coder-review in specified folder How can i perform code review with coder_review command in a specified folder?
I see that i can give it contrib or core directives, but i would like to only check a folder in my modules folder like

/modules/dev

/modules/contrib/

/modules/custom/

How should i instruct coder-review command to check those modules (custom) only?

Tried drush coder-review <folder-path> that doesnt seem to work, is there any other option, or should i patch the module to accept my 'custom' directive?

This was solved with a patch to coder module(7.x-1.2), introducing my custom command argument, "custom" which selects the modules i want form the database using a machine name query.

Coder review will never work on a file-system basis, since it grabs the module info from the database not the file-system.


Fatal error: Class 'Browser' not found : After Updating drupal 6.20 to 6.26 As i am update my durpal version 6.20 to 6.26 and it gives these error after updating.

   1) Fatal error: Class 'Browser' not found in /opt/lampp/htdocs/mydrupal/includes/common.inc(1731) : eval()'d code on line 4

   2) warning: include(Browser.php) [function.include]: failed to open stream: No such file or directory in /opt/lampp/htdocs//opt/lampp/htdocs/uls/includes/mydrupal/includes/common.inc(1731) : eval()'d code on line 3.

I checked the common.inc file and there is no code for "including browser.php"

The error message says eval()'d code on line 4. You have a PHP block, node or something similar that tries to include a file called Browser.php. That is not a file supplied with Drupal core. What you can do... just before line 1731 add something like if(strpos($code, 'Browser.php')) { file_put_contents('/tmp/log', print_r(debug_backtrace(), TRUE)); exit;} and then study the log to see where it's called from to figure it out. If it's called from block, the backtrace will contain the module and delta, if it's a node, the nid will be there and so on.


How do I put the copyright / name site in footer In the four themes I tried before choosing the one I have now, the name of my website was always featured with the copyright in the footer of my webpages, but now all it says is "Copyright © 2013, ."

Is there an easy way for me to adjust the code so it does credit the site after that comma and before the period? I'm not very familiar with code so I'd be ever so grateful for an easy way. I tried searching for the copyright sign and the year in a few pages but they didn't show up so I suspect there are other ways to describe those in code, right? :)

First, make sure your site name is stil configured correctly. You can do this by going to yoursite.com/admin/config/system/site-information.

If the site name is there and still does not show up, then the theme you've selected is likely not working correctly. Head over to yoursite.com/admin/appearance and click on 'Settings' next to the theme you're using. Browse around and see whether there are any options to set the copyright message.

Failing that, modify the message directly in the template files. You will have likely installed your theme to /sites/all/themes/theme_name or /sites/default/themes/theme_name. Browse to this folder and look for a file called page.tpl.php (it may be in a subdirectory). This file will likely contain the copyright message which you can change right then and there. Alternatively, the copyright message maybe in the html.tpl.php file, which should be in the same location as page.tpl.php.


Change mailsystem used on webforms on a per email basis I'm using the mailsystem module to send webform notification emails using mandrill.

However, for some of our webforms we need to use mandrill for the notification email sent to the users, but send the admin notifications without mandrill, using normal text based emails.

From what I can tell you can only change the mailsystem on a per module or per-key basis, and it seems like all webform emails use the same key -- "submission".

Is there any way to achieve what I want here?

Thanks,

I think you can do this via hook_mail_alter you'll need to write your own implementation but should be possible.

From what I can see in webform.submissions.inc inside webform_submission_send_mail()

// Build the e-mail headers.
    $email['headers'] = theme(array('webform_mail_headers_' . $node->nid, 'webform_mail_headers'), array('node' => $node, 'submission' => $submission, 'email' => $email));

It should be possible to use hook_mail_alter to choose the right submission and also the e-mail address it's being sent to.


i18n-Frontpage: inconsistent links to non-default language I am running across some inconsistent behaviour regarding the links to the  frontpage of my multilingual site. The following is happening:

mysite.com -> English frontpage, correct

mysite.com/en -> English frontpage, correct

mysite.com/en/node -> English frontpage, correct

mysite.com/de/node -> German frontpage, correct

mysite.com/de -> English content but language switcher says it's German, should display German content

Did anyone experience something similar? I have an idea why this is happening but no clue how to fix it.

I didn't find anything here. The closest one was this, but I already have a working link to the German frontpage, so it doesn't really apply to me. https://stackoverflow.com/questions/5168289/multiple-frontpages-in-mutiple-languages.

Best regards,
Christoph

P.S.: All my images with relative links in Blocks or Pages get the language tag set in front of them. Is this a corresponding thing or default i18n behaviour? I just hotfixed it with softlinks from en/images and de/images to images.

What eventually worked for me:

Disable the module "admin_language"

I tried many different configurations of this module but it just kept on giving me English content on the German Frontpage. Views however displayed the correct language.

Should I report this bug to the module maintainers?


How to automatically populate /node/add/ form fields via simple logic? I have created a content type and the form looks like this:

Home team: Reds
Away team: Blues
Batted first: Reds
Batted second:
Fielded first:
Fielded second:

If Reds batted first, I know the Blues batted second, fielded first and that the Reds fielded second. How can I get Drupal (7) to populate these fields automatically via some simple logic?

I'm thinking the Computed Field module, but the values are not in the database yet: the form hasn't been submitted. So, I'm not sure I can access the Batted first value. Perhaps only via the &$form_state array? - but can the Computed Field module access this array?

Anyway, how can I acheive this? Any suggestions are welcome. Thanks.

Module Conditional Fields does the job.

It lets you assing values, visibility etc. of fields depending on other fields in the same form.

https://www.drupal.org/project/conditional_fields


Fatal error after subtheming Commerce Kickstart Admin Theme I am trying to subtheme Commerce Kickstart Admin Theme. I have copied all the folders and files to sites/all/themes/my__admin_subtheme, and changed the appropriate lines in my_admin_subtheme.info.

When I go to /admin/appearance, and change the section Administration theme to My Admin Theme, I get an error in template.php telling that the function commerce_kickstart_admin_preprocess_maintenance_page is declared twice.

How to solve this issue?

Edit:

When I change the name of preprocess function in template.php from commerce_kickstart_admin_preprocess_maintenance_page to my_admin_subtheme_preprocess_maintenance_page or delete template.php the fatal error disappear but I lose the formated html present in that function.

To make things more clear, the template.php is

<?php

/**
 * Override or insert variables into the maintenance page template.
 */
function livraria_acervo_admin_preprocess_maintenance_page(&$vars) {
  // While markup for normal pages is split into page.tpl.php and html.tpl.php,
  // the markup for the maintenance page is all in the single
  // maintenance-page.tpl.php template. So, to have what's done in
  // shiny_preprocess_html() also happen on the maintenance page, it has to be
  // called here.
  shiny_preprocess_html($vars);
  if (variable_get('install_task') != 'done') {
    $footer_markup =  '
' . t('Proudly built by') . '
';
    $footer_markup .=  '
' . t('Commerce Guys', array('@url' => 'http://www.commerceguys.com')) . '
';
    $vars['footer'] = array(
      '#prefix' => '
',
      '#markup' => $footer_markup,
      '#suffix' => '
',
    );
  }
}

I searched for that function in all file tree in root Drupal installation and didn't find any call for that function.

I see the function is related to the maintenance mode, the mode that I'm working now. Well, as I told above the fatal error disappeared but how to know where the function is called. I think the function is called somewhere and I would have to change the name in the file(s) that it's called, although I don't think this would the better way to solve the problem.

So some piece is missing in subtheming Commerce Kickstart 2 admin theme, and is related to the call of that function commerce_kickstart_admin_preprocess_maintenance_page.

I'm new to Drupal and have not practiced php very much, so I hope I have been cleared. If more information is needed please tell me. And sorry about my English too.

Thanks in advance!

PHP requires all function names to be unique*, you'll need to rename the functions in your sub-theme to my_admin_subtheme_FUNCTION_NAME, e.g. my_admin_subtheme__preprocess_page(&$vars).

You might want to consider clearing the template.php file completely and only copying the functions you need when you find you need them.

That is unique in a namespace, but that is another subject - see http://php.net/manual/en/language.namespaces.php.


How to alter the default font displayed INSIDE CKeditor I would like to be able to alter the font in the CKeditor (version 7.x-1.15) module so that it does not show Times New Roman, but rather the font that the rest of the site uses, Helvetica. I'm using Drupal 7.30.

When CKeditor loads when content is edited it always shows Times New Roman!

I have altered 'Custom Javascript configuration' in:

admin/config/content/ckeditor > Advanced options to read:

config.extraCss += "body{font-family:Helvetica, serif;}";

Cleared all Drupal caches AND browser caches - nothing.

I've also altered:

ckeditor.config.js - line 36:

config.extraCss = 'font-family:Helvetica;color:#726F6F;';

Again, cleared all caches - nothing!

Please could someone explain what I'm doing wrong!

The font is set in ckeditor/ckeditor/contents.css, although it is generally inadvisable to alter a module, it can be done safely so long as you document the changes (in the event that updates are required and would overwrite your work).


Contextual filter on entity reference field in indexed view I have two pages: jobs and offices.

My jobs page is an indexed view (with Search API) which displays jobs that have an entity reference field to the office it belongs to.

I want to put a link on my office page that links to the job page which only shows the jobs belonging to that particular office.

I've followed a few examples but none of them seem to work with my indexed view. Has somebody done something similar?

This is what I did: https://www.drupal.org/node/1841004 but it doesn't seem to work.

Thanks!

If you want to show the jobs for that particular office on your job page, you might want to use a parameter. you need to pass the nid of that office to the url.

Create a link similar to this:

  $nid = arg(1);
<?php
    $l = l( t('More Jobs'), 'list-of-jobs',   array('query' => array('field_office' => $nid)  ));
    echo $l;
        ?>

your entity reference field is "office" right? use that field for your contextual filter. then use Views Contextual Filter Query module to get the parameter from the URL. In my example, it's field_office.

Hope this helps!


Use of a global variable ('submission counter') I'm trying to construct a registration form (of a node) wich stores serial (ascending) values in a hidden field.
The form is open to unregistered users.
I made it with rules and variable (every time a node of type xxx is saved, the global variable is +=1 and stored in the correct field), but... If two nodes are submitted at the same time, this variable can be dupplicated.
Any ideas on how avoid this behaviour?
Thank you.

I would recommend implementing the Serial Module:

  This module provides an auto-increment (serial) field.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.

  The allocation of serial numbers by this module is atomic. In other
  words, the serial values are unique even when multiple instances of
  the same content type / entity are created simultaneously.


How to remove empty div created by routing.yml file by specified routes? I have 2 routes

games.one:
  path: '/math/one'
  defaults:
    _controller: '\Drupal\games\Controller\GamesController::one'
    _title: 'My Title'
  requirements:
    _permission: 'access content'

games.two:
  path: '/math/two'
  defaults:
    _controller: '\Drupal\games\Controller\GamesController::two'
  requirements:
    _permission: 'access content'

Route games.one has _title and Route games.two does not have. Now the issue is When I access route game.two, It shows an empty div for title.

How to remove this empty div?

You can do this by overriding the page.html.twig for that page and stripping out the title.

To override the template for that specific page you should probably alter the hook suggestions:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  if ($node = \Drupal::routeMatch()->getRouteName() == 'games.two') {
    $suggestions[] = 'page__no_title';
  }
}

Now you can copy the page.html.twig template to  your theme folder, rename it to page--no-title.html.twig and strip out the title tag.

Hope this helps


How to link a view row to a node? I'm using the Message module to notify users when someone reacted on their nodes. I'm now trying to theme the messages, which are displayed in a view, called 'Message'.

I'd like to link a message to the content that's commented on. In other words: when a user clicks a message, he/she should be linked to the corresponding node's page. I don't simply want the message text to be a link, but the whole message (i.e. also including the other fields) should function as some kind of 'button'.

I think the easiest way to do this is to create a views-view-unformatted--message.tpl.php file and use

<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
   <a href="<?php print url('$url'); ?>">
    <?php print $row; ?>
   </a>
  </div>
<?php endforeach; ?>

The problem is that I don't know how to define $url. I can store the needed nid in the message and add it hidden to the view, but I can't find a way to grab that information.

How can I do that?

I stored the nid from the node that's commented on in a message field and used the information in a views-view-unformatted--message.tpl.php file.

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php $message = message_load($view->result[$id]->mid); ?>
  <div <?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
   <a href="<?php if (isset ($message->field_nid['und'][0]['value'])) {
                      print url('node/'.$message->field_nid['und'][0]['value']);} ?>">
    <?php print $row; ?>

<?php endforeach; ?>


Google indexes the page using the domain alias I have a Drupal 8 page which is indexed from Google without any error. The front page is a node configured as a front page in the Basic site settings (admin/config/system/site-information) using the path alias /front or de/heim.

The point is that the path alias for the front page should be the root (e.g. example.com) which is it. So, everything is working fine if I navigate the page.

Why is the path alias shown in Google search results, and not the root domain?  It shows example.com/en/front or example.com/de/heim, not example.com.

I have never seen this problem before using Drupal 6 or Drupal 7.

It really depends on what page Google finds first, I guess. So, I do now know.

  Why is the alias shown in Google search results, and not the root domain?

However in order to overcome this, you would have used the global redirect in Drupal 7, which has been merged with Redirect. I have not tried it, but if it an exact port it should still be able to.

  Checks if the current URL is the same as the site_frontpage and
  redirects to the frontpage if there is a match.


How do I Improve Drupal 7 Forum Performance? I am working on a website that has 60k+ forum topics and it is extremelly slow. The problem is that the core forum module uses the following query

SELECT ncs.last_comment_timestamp AS last_comment_timestamp
, ncs.last_comment_uid AS last_comment_uid
, CASE ncs.last_comment_uid WHEN 0 THEN ncs.last_comment_name ELSE u2.name END AS last_comment_name FROM node n
INNER JOIN users u1 ON n.uid = u1.uid
INNER JOIN forum f ON n.vid = f.vid AND f.tid = '22'
INNER JOIN node_comment_statistics ncs ON n.nid = ncs.nid
INNER JOIN users u2 ON ncs.last_comment_uid = u2.uid WHERE  (n.status = '1') ORDER BY last_comment_timestamp DESC LIMIT 1 OFFSET 0

I saw that this query was the problem because after running the top command I saw that mysql was consuming 150%+ CPU so I ran a show full processlist that showed that the query above was always in the following state

Copying to tmp table    SELECT ncs.last_comment_timestamp AS last_comment_timestamp, ncs.last_comment_uid AS last_comment_uid, CASE ncs.last_comment_uid WHEN 0 THEN ncs.last_comment_name ELSE u2.name END AS last_comment_name\nFROM \nnode n\nINNER JOIN users u1 ON n.uid = u1.uid\nINNER JOIN forum f ON n.vid = f.vid AND f.tid = '22'\nINNER JOIN node_comment_statistics ncs ON n.nid = ncs.nid\nINNER JOIN users u2 ON ncs.last_comment_uid = u2.uid\nWHERE  (n.status = '1') \nORDER BY last_comment_timestamp DESC\nLIMIT 1 OFFSET 0

The result of the explain command is

id      select_type     table   type    possible_keys   key     key_len ref     rows    Extra
1       SIMPLE  f       ref     PRIMARY,tid     tid     4       const   30030   Using index; Using temporary; Using filesort
1       SIMPLE  n       eq_ref  PRIMARY,vid,node_status_type,uid        vid     4       drupal.f.vid    1       Using where
1       SIMPLE  ncs     eq_ref  PRIMARY,last_comment_uid        PRIMARY 4       drupal.n.nid    1
1       SIMPLE  u2      eq_ref  PRIMARY PRIMARY 4       drupal.ncs.last_comment_uid     1       Using where
1       SIMPLE  u1      eq_ref  PRIMARY PRIMARY 4       drupal.n.uid    1       Using where; Using index

Any ideas what to do to improve the performance here ?

Thanks

If you remove statistics then things should fly.   From my understanding drupal statistics does not scale well


Using Test Mail Collector to avoid sending emails to users during testing This page offers some documentation on how to avoid sending emails to actual users during testing or in test environments:

https://www.drupal.org/docs/develop/local-server-setup/managing-mail-handling-for-development-or-testing

The simplest way appears to be modifying your settings.local.php:

$config['system.mail']['interface']['default'] = 'test_mail_collector';

If you use drush, you can then check the emails sent by running:
drush sget system.test_mail_collector

However after adding that line to my settings.local.php, I still received the actual emails. They were not "collected".

In looking at the source code in Drupal\Core\Mail\Plugin\Mail\TestMailCollector.php line 24

 $captured_emails = \Drupal::state()->get('system.test_mail_collector') ?: [];

It seems to me that the correct syntax for setting the test mail collector would be

$config['system.test_mail_collector'] = TRUE;

But that didn't work either.

I haven't been able to find documentation that helps me reverse-engineer the setting based on the retrievable of the state variable.

After my attempt to use Devel module for  DevelMailLog also failed using the configuration setting

$config['system.mail']['interface']['default'] = 'devel_mail_log';

I concluded there must be something in my environment that is blocking these features.

After uninstalling the module "MailSystem", then either of the two approaches worked as intended while mail was still received when the configuration setting was omitted.


how detect form is submitted? I use Drupal 7 and the Webform module.

How can I know if a form is submitted or not? I need this to show either error messages or success message after form submission in form page.

I prefer not to write a module because I think it is unnecessary to write a module for a very small task.

Some more info to further explain my question:

I already know about the setting for Webform per form. This setting is located "Content > Webforms(tab) > Edit(your form) > Webform(tab) > Form settings" (where you can add the confirmation message or redirect to a Custom URL).
Actually I render my webform in my node--contact.tpl.php and I use the Webform Validation module for my form validations. And with the form_get_errors function I get errors and loop through them and show them. And if submission is successful I show form successful submission message. I just don't know how to detect whether form is submitted or not.

There a setting for Webform per form. This setting is located "Content > Webforms(tab) > Edit(your form) > Webform(tab) > Form settings". You can add the confirmation message or redirect to a Custom URL.


Use read-only database user to minimize security risks I want to phase out an old, unmaintained Drupal 6 page. The website should still stay online, but should be read-only.
I want to change the database user so that it only has read privileges. I don't want the website to be exploitable due to any security issue in Drupal 6 or any of the modules.
Is it possible to give Drupal 6 a read-only database user? On which table is write access necessary?

You can make make read only tables, except: semaphor, watchdog, cache, cache_[ANOTHERS], sessions, and another tables, depend on installed modules, that can modify tables on guests visiting, login or form submissions, like statistics, flag and so on.
But I strongly DO NOT recommend this, because instead of showing read only site you may show white or errors screen.
Better is use Read only mode module, that make site read only (prevent form submissions and so on).
Another solution - make backup, then restore 1 per day via bash script. Samples.


Change Bootstrap column classes based on the result of a view I have a D8 site with a Bootstrap 3 subtheme and two columns with one region and a block inside each.

I need to change the first column width (col-md-12) to take 100% width when the view block in the second column is empty, and to take just 50% (col-md-6) when it has something to display.

An easy way to achieve this without custom modules?

With this solution I can hide the second region, but how to make the regions talk together and change the first accordingly?
Should I make one single region with two blocks within and then change column classes in the region twig template? Is it possible?

Thanx for your attention

One way to solve your problem is to implement an hook_preprocess() in your custom themes' .theme file, where you check whether your second block is empty or not and use this information to apply the appropriate (Bootstrap grid) class (to your block in the first column).

Although above suggestion is not using a custom module (it's in your sub-theme), however, I can imagine that this might not be the answer you're looking for.

As you suggest you can also put this logic in your Twig template, but checking whether your block is empty can be a bit troublesome (due to the fact that blocks can be lazy loaded using placeholders, see e.g. Drupal 8 regions with and empty blocks).


How to prevent certain users from adding (for example, a Node) to bookmarks with Flag Module Flag Module >>> https://www.drupal.org/project/flag

How to disable/prevent some Users (NOT Roles) from adding (for example a Node) to bookmarks? Maybe showing a message after clicking on the Boomark button (You are not authorized to make this choice or something like that).

I assume you use Drupal 8:

Flag action handled by \Drupal\flag\Controller\ActionLinkController::flag so i think you should override this to check on your user and prevent to flag bookmarks nodes:

Override ActionLinkController controller using RouteSubscriber like the following:
Add the following to YOUR_MODULE_NAME.services.yml

services:
  YOUR_MODULE_NAME.route_subscriber:
    class: Drupal\YOUR_MODULE_NAME\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Create YOUR_MODULE_NAME/src/Routing/RouteSubscriber.php

<?php
namespace Drupal\YOUR_MODULE_NAME\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change the route associated with /flag/flag/{flag}/{entity_id}.
    if ($route = $collection->get('flag.action_link_flag')) {
      $route->setDefault('_controller', '\Drupal\YOUR_MODULE_NAME\Controller\MyCustomActionLinkController::flag');
    }
  }

}

Create your new Controller YOUR_MODULE_NAME/src/Controller/MyCustomActionLinkController.php like the following:

namespace Drupal\YOUR_MODULE_NAME\Controller;

use Drupal\Component\Utility\Html;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Entity\EntityInterface;
use Drupal\flag\Ajax\ActionLinkFlashCommand;
use Drupal\flag\Controller\ActionLinkController;
use Drupal\flag\FlagInterface;

class MyCustomActionLinkController extends ActionLinkController {

  /**
   * Performs a flagging when called via a route.
   *
   * @param \Drupal\flag\FlagInterface $flag
   *   The flag entity.
   * @param int $entity_id
   *   The flaggable entity ID.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|null
   *   The response object, only if successful.
   *
   * @see \Drupal\flag\Plugin\Reload
   */
  public function flag(FlagInterface $flag, $entity_id) {
    /* @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $this->flagService->getFlaggableById($flag, $entity_id);
    $uid = \Drupal::currentUser()->id();
    // Do your check here i just test with the user admin.
    if ($uid == 1) {
      // Change the message you want to show
      $flag->setFlagMessage("Sorry you don't have right to bookmark this");
      return $this->generateResponse($flag, $entity, $flag->getMessage('flag'));
    }
    else {
      try {
        $this->flagService->flag($flag, $entity);
      } catch (\LogicException $e) {
        // Fail silently so we return to the entity, which will show an updated
        // link for the existing state of the flag.
      }
      return $this->generateResponse($flag, $entity, $flag->getMessage('flag'));
    }
  }

  /**
   * Generates a response after the flag has been updated.
   *
   * @param \Drupal\flag\FlagInterface $flag
   *   The flag entity.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   * @param string $message
   *   (optional) The message to flash.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The response object.
   */
  private function generateResponse(FlagInterface $flag, EntityInterface $entity, $message) {
    // Create a new AJAX response.
    $response = new AjaxResponse();

    // Get the link type plugin.
    $link_type = $flag->getLinkTypePlugin();

    // Generate the link render array.
    $link = $link_type->getAsFlagLink($flag, $entity);

    // Generate a CSS selector to use in a JQuery Replace command.
    $selector = '.js-flag-' . Html::cleanCssIdentifier($flag->id()) . '-' . $entity->id();

    // Create a new JQuery Replace command to update the link display.
    $replace = new ReplaceCommand($selector, $this->renderer->renderPlain($link));
    $response->addCommand($replace);

    // Push a message pulsing command onto the stack.
    $pulse = new ActionLinkFlashCommand($selector, $message);
    $response->addCommand($pulse);

    return $response;
  }
}

Notes:

You may need to do the same the route flag.action_link_flag_nojs.
I reimplement the method generateResponse because it has a private visibility.


The path_processor_outbound service only work after clearing the cache I tried overwrite all links from my site in Drupal 8 in accordance with a URL parameter.

I use the service path_processor_outbound and implemented the processOutbound() method, extending the OutboundPathProcessorInterface interface.

services.yml

services:
   test_concept.test_concept_sayHelloService:
   class: Drupal\test_concept\Services\TestConceptRepeater
   tags:
      - { name: 'path_processor_inbound', priority: 100 }
      - { name: 'path_processor_outbound', priority: 300 }

Method of my class

public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
  $current_uri = \Drupal::request()->getRequestUri();
  $path_args = explode('/', $current_uri);
  $sede = $path_args[1];
  $path = "/" . $sede . $path;
  return $path;
}

This work very good when reloading the site alter flushing the cache, but when I change the URL parameter and reload the site again, the URLs don't change, even if processOutbound() runs again.

Is a problem with the cache?

That's because those links get cached and Drupal doesn't know by what to vary those caches.

That's why you receive that additional argument, $bubbleable_metadata. You need to use it to specify that our changes depend on a certain url parameter. See https://www.drupal.org/docs/8/api/cache-api/cache-contexts and https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays.

You need something like this:

if ($bubbleable_metadata) {
  $bubbleable_metadata->addCacheContexts(['url.query_args:your_parameter']);
}


In the OG API, which hooks are available when a group admin adds or removes a user from a group? Question:

In the context of Organic Groups API, is there a hook that fires when an group administrator adds or removes a user from the group (or when a user self joins or self-removes their account)?

Ultimately, I was hoping for a hook that was fired around og_group() and og_ungroup() as that's how I best understand the API so far.

You can find all OG hooks here.

You already mentioned two of them, but for the sake of a complete answer here are the hooks fired on membership add/edit/delete:

hook_og_membership_insert
hook_og_membership_presave
hook_og_membership_delete

Also, as memberships actually are entities you can also use all hooks used for saving and deleting entities, like hook_entity_update and hook_entity_delete. You can find them in this list.


AJAX post on node edit page I am trying to perform an AJAX post on node edit pages in a new module I created Proofread Bot. This module adds a button and clicking it performs an AJAX post to a URL for processing text. When I do this on node edit, it seems the whole page gets submitted.
I tried adding an event.preventdefault call, but also returning false for the button doesn't work.
Let me add the same code works like magic on node view.
Here is the code:

function proofread_bot_node_prepare($node)  {

drupal_add_js('
    jQuery(document).ready(function(){
    jQuery("#edit-body").before(\'
<button type="button"  id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</button>
\');
    jQuery("#proofread_bot-submit").click(function(event){
      event.preventDefault();
      jQuery.ajax({
         type: "POST",
         url: "proofread_bot/check",
         dataType: "html",
         data: {"text": jQuery("#edit-' . variable_get('proofread_bot_field') . '").html()
          },
         success: function(proofread_result){
            jQuery("#proofread_bot-submit").after(proofread_result);
         }
        });
      });
    });
    ', 'inline');

}

The Drupal Ajax call is not affected by event.preventDefault in the above code, as neither the Click() or on('click') Jquery function gets executed on Drupal Ajax call.
Please refer the link below

Jquery gobal ajax events

In the above code the ajaxSend()
 function can be used to stop the Ajax call even before getting started. And use event.preventDefault in the function to stop the Drupal Ajax Call before getting executed.

For Example:

$( document ).ajaxSend(function() {
  event.preventDefault();
//add you code here.
});

Please check if this code will work in the function your calling, i am not sure (may work) or else call this code directly in you attached JS file.


Drupal 6 Add Webform Programmatically I'm trying to add a new component or populate an existing hidden component on a web form programmatically.  I found this:

http://drupalcontrib.org/api/drupal/contributions!webform!webform.module/function/_webform_client_form_add_component/6

However I have not found any hooks, which would be the preferred way to do this.  I'm essentially just checking to see if there is a hook or how to access that function in a custom module if no hook exists.

A webform is simply a node so the rough process of doing this would be to node_load() your particular node, add your components array to the $node->components[] array and then execute a node_save(). There is some documentation here that fleshes out how to programmatically add a webform, your code would look something like this:

$node = node_load(YOUR NODE ID);
$components = $components = array(); #YOUR COMPONENTS ARRAY
$node->webform = array(
      'components' => $components,
);
node_save($node);


Integrate print styles in Omega 4 What is the right or omega way of integrating print styles in omega 4?

I've found no references in the docs.

Like for any css file, add it into the theme's info file, but rather than 'all', just specify it to be only for print.

stylesheets[all][] = css/everytime.css
stylesheets[screen][] = css/screen-only.css
stylesheets[print][] = css/print-only.css


2 Drupal Multisites, Separate Databases, Changing 1 Also Changes the Other I have a very weird issue. Been doing Multisites in Drupal 7 for a while now without any hitches... until last week. I have 2 multisites both with separate databases, however when I change content on 1 of them it also changes content on the other.

I have Multisite01 pointing to Database01 and Multisite02 pointing to Database02 (copy of 01). I should be able to change 1 multisite and not have it effect the other. I'm not sharing databases or anything. This has always worked for me before.

What I did different in this instance was when I copied Database01, Database01-Copy, to create 02. I was in a hurry and meant to click on 01-Copy to rename but instead, I clicked on 01. No matter, or so I thought... I just renamed Database01 to Database02 and then I renamed Database01-Copy to Database01.

Now Drupal has them permanetly linked... even if I link Multisite01 or 02 to another database (ie Database03 or 04, etc). So I know that the change is outside of each Multisite's database. Wondering if this can be fixed without reinstalling Drupal...

/*Misc. Info
Multisite01 Settings.PHP (Multisite02 is same but connects to database02)*/

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database01',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

You've been doing Multisites for awhile now, so this seems like an obvious question -- but did you clear the drupal cache?

... and after doing so, restart Apache.  Many of my "unexplainable" errors have come down to that.


How-To call a module when a user clicks a node title or read more link if($page) I would like to call a module from node.tpl.php like so (based on node id):

//This is my node--job_post.tpl.php

   <pre>

   <?php
         if ($page):
    $nid = $node->nid;
  switch($nid){
  case 4:  CALL A MODULE FOR NODE ID 4
  case 5:  CALL A MODULE FOR NODE ID 5
  break;
 }
  endif;
  ?>
 </pre>

If there is a better way to accomplish this , please let me know. Thank you in advance.

That's not how it works in Drupal.

You need to use Hook_node_view() in a custom module .module file, NOT in the template.tpl.php file. Which executes the code inside it whenever a node is viewed.

Ex:

hello_world.module

hello_world_node_view($node, $view_mode, $langcode){

  //code to run when node is viewed goes here.

}


Context - no reaction I just installed context 3 on my drupal 6 site. I updated ctools to latest version (1.9) as suggested. Everything looks fine and I can enter conditions and reactions. The problem is that nothing happens. I see no reaction at all on the behavior of my site. Any hits to where I should start looking for the source of the problem?

Start with a sanity check - make sure your rules "make sense" and that you set them up correctly. Try to apply the same context rules on a clean install.

If it works there and not in your existing site (with content, other modules and customized configuration), clone that site and try disabling modules one by one to see where the conflict is. It's hardly possible to say where the problem is without knowing any details about your existing installation.


Restore backup solution for busy sites Today one of my users went and deleted the root of an Organic Group and wiped out all of the child nodes from that group and it's associated menu entries.

I have a backup, so I can restore, but in the time between I was informed of the problem and when it occured, other people were making updates to the site - so it wouldn't be as simple as just falling back to the last backup.

Happily, it was a simple group which is easily re-creatable - but I know one day, someone is going to delete a node which isn't trivial to re-create.

We've all had a colleage (or done it ourselves) who has called the local sysadmin and said "I accidentally deleted e-mail xxx - please restore it" - and the sysadmin goes and does it. My question is: How can I do this for a Drupal site? Ie. I want to be able to restore a node, or a set of nodes without completely rolling back.

Any ideas? Would love to hear from people with experience in dealing with this kind of problem. I can see there are modules such as "Feeds" and "Node Import" but I'm looking for peoples opinions on best solutions based on their experience.

One answer in this situation is never to permit deletions in the first place.  Use the publish flag or some other mechanism to remove the content from view, but retain it in the database.  An admin would be able to restore any content simply by 'publishing' it again.


Rules send email on entityform submission with current node field content I have a rule which sends an email on saving an entityform. The entityform appears on several nodes.

I would like to 'grab' field content specific to these nodes and include this data in the email message body.

I think I might need a rule component but I'm unsure how to build a relationship between the node content and the entityform.

Can anyone help?

Add an entity reference field to the entityform in question and - using Entityreference Current module - check the option to reference current. This gives you access to current page data.

It's at this point you may want to install the Hidden Fields Widget module which will allow you to set the entity reference widget to hidden. Do this if you don't want the field to be visible on your entityform.

At the time of writing this, you also need to patch the Hidden Fields Widget module with https://www.drupal.org/node/1821008 to support the entity reference field type.

Next, create your rule with Event: After saving a new entityform submission, Conditions: Entity has field (select the entity reference field) and Actions: Send mail.

Now all you need to do is add another condition relating to the field token you want to use in your email body. Use the previous entity reference field condition as your data selector, then select the relevant field. This will now be available as a token in the Send mail action.

You can do this as many times as you want to get each field out.

I'm sure there's a more efficient way of doing this, but this worked for me.


Views - Wrapper Fields in DIV after ROW class Have this:

And need this:

If you start editing your view, on the right side under the advanced options you will find Theme: information. You will see the currently used template files and the candidate files.
My solution would be to overwrite the default template files with your own. That way you could simply add a wrapper around $rows.


Error reindexing attachments in Drupal 7 using Apache Solr Attachments module I've installed Solr 3.4.0 and Tika .10 on my Windows 2003/IIS6 server.  I have loaded the Apache Solr Attachments module and configured so I can search on documents attached to pages in my Drupal 7 web site.  When I reindex on the Apache Solr search configuration page I'm getting 5 of these notices:

Notice: Undefined index: filepath in apachesolr_attachments_add_documents() (line 133 of W:\www\drupal-7.8\sites\all\modules\apachesolr_attachments\apachesolr_attachments.index.inc).

The search index page indicates the attachments have been submitted for reindexing (message on the page -> "There are 0 items remaining to be examined for attachments out of 23 total.  The search index is generated by running cron. 100% of the site content has been sent to the server. There are 0 items left to send. " and "Number of documents in index: 23 (0 sent but not yet processed)").  On the Search settings page I see "100% of the site has been indexed. There are 0 items left to index." under Indexing Status.

Search is working for web site content but search for content in attachments is not working.    If I got into Solr admin and query I can see web site content but searches for words in attachments return no results.  So the attachments are not getting into Solr.  Any ideas about what this error means or how I can debug it?

So I figured this out in case anybody else runs into this issue.

In the 7.x-1.x version of Apache Solr Attachments, there is a line of code in apachesolr_attachments.index.inc that uses the PHP function mb_detect_encoding.  That command relies on the PHP EXIF extension being installed and it is not by default.  Once I modified my PHP installation to include it, it was able to process the files.  I ran into some other issues though but finally got it all working.  Details are posted here -> http://drupal.org/node/1377416


How to prevent users from being registered when their username contains a space? I'm trying to prevent a user from being saved with Rules when he/she tries to use a username that contains a whitespace. I've already read How can I disallow spaces in usernames? and used the User restrictions module to achieve this, but I'd like to use Rules to do some other stuff (e.g. checking that the username doesn't have more than 20 characters).

So, what I'd like to do is showing an error message on the page and keep all the filled in information in the form without saving it. Is it possible to do this?

This is the Rule I'm currently using:

Event: Before saving a user account.
Conditions: NOT Execute custom PHP code. <?php preg_match('/\s/',$account->name) == 1; ?>
Actions: Show a message on the site.

@Jeroen,
Then I would suggest to do just one custom form alter to the user registration form and add a validation function that will validate each case for you.

/**
 * Implements hook_form_FORM_ID_alter().
 */
// Alter the registration form
function CUSTOM_MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Add your own function to the array of validation callbacks
  $form['#validate'][] = 'CUSTOM_MODULE_user_validation';
}

/**
 * Custom function to validate the user creations.
 */
function CUSTOM_MODULE_user_validation(&$form, &$form_state) {
  $name = $form_state['values']['name'];
  if (preg_match('/\s/',$name)) {
     form_set_error('name', t('Name should not contain white spaces.'));
  }
}

Its easier to use and doesn't invoke rules API every time. I also think this is much effective for performance.


How to edit and delete drupal 8 custom block content? I am not getting any option to edit my custom block body content and not able to delete also.

Please suggest me.

Thanks

Visit your block library, there's a tab on blocks page.

Block library can be found here:
/admin/structure/block/block-content


Uploading and deleting unused images I have a custom form with manage file input where users can upload their profile images. Upload looks like this:

 $acc = user_load($state['user_id'], TRUE);

 // upload profile image
 if ($state['values']['image'] != '0') {

   //check if this file is already in use, if not, save new file
   $res = db_select('users', 'u')
       ->condition('uid', $state['user_id'], '=')
       ->fields('u', array('picture'))
       ->execute()
       ->fetchAssoc();

   if ($res['picture'] != $state['values']['image']) {

     $img = file_load($state['values']['image']);

     file_usage_add($img, 'user', 'user', $state['user_id']);

     $img->status = FILE_STATUS_PERMANENT;
     $acc->picture = $img;
     file_save($img);

   }

 } else {
   $acc->picture = NULL;
 }

 user_save($acc);

This approach is piling up unused files if user's change their images multiple times. It is because of file_usage_add function that is logging  files in database, therefore drupal won't delete files that are logged in file_managed database.

I think I could manually change old file status in database before new log is inserted by file_usage_add and let Drupal automatically remove this unused file. Is this statement right?

Even if it is true, I have strong feeling this is not optimal Drupal way of managing files. Is there a better way?

You can achieve your requirement by using Audit Files module.

  Audit files is designed to perform audits of your upload directory and
  the corresponding database records. It will cross check that all files
  in the database have a corresponding physical file, or it will check
  that all files in the upload directory have a corresponding entry in
  the database.


Redirect to login page if login block fails If you fail to log in correctly from a login block, I would like the user to be directed to the login page to log in from there.  How can this be accomplished?

I guess altering the user login form and override the user_login_final_validate() with a custom custom_user_login_final_validate() with all codes copy from existing to custom and adding redirecting codes to login page with a check that current page is not user login page, should work.


Add multichoice question to quiz node programmatically I'm using the latest version of drupal and quiz module. In my custom module, I have created a quiz by using below code

 $quiz = new stdClass();
  $quiz->title = 'Testing Quiz';
  $quiz->type = 'quiz';
  $quiz->language = LANGUAGE_NONE;
  $quiz->uid = 1;
  $quiz->status = 1;
  node_object_prepare($quiz);
  $quiz = node_submit($quiz);
  node_save($quiz);

However, the quiz is created successfully. I have a list of multichoice question, which is imported using feeds module. Now what I want is assign those multichoice question to this custom quiz node.

How can I do this?

Finally, I got the solution. The below code is used to add the multichoice question node to quiz node.

  $multichoice_node = node_load($nid); //load multichoice question nid
  $multichoice_node->add_directly = array(
    'latest' => array(
      $quiz->nid. '-'. $quiz->vid => $quiz->nid. '-'. $quiz->vid
    )
  );
  node_save($multichoice_node);


Create relationship between node and menu link I would like to create a node with a menu link programmatically.  When the operation is complete, I would like the user to see the relationship between the node and the menu link under "Menu Settings" of the node.

I am aware of this post:

Programmatically create a node with a menu link

This shows the mechanics of creating a node and creating a menu link.  It does not show how to build the relationship between the node and menu link so it is available in "Menu Settings" of the node for a user working with the Drupal GUI.  How can I build this relationship?

To create a menu link for a node programmatically and to see it in the node edit form you have to connect the link uri to the node entity:

$item = \Drupal\menu_link_content\Entity\MenuLinkContent::create([
  'link' => ['uri' => 'entity:node/' . $node->id()],
  'title' => 'Menu item for node ' . $node->id(),
  'menu_name' => 'main',
]);
$item->save();


I'm looking for a way to force the migration to process entries with identical keys The full scenario is as follows:

We have two entities (Foo and Bar). Foo has a multi-value entity reference field to Bar entities.

The migration source outputs each Foo-Bar pair in a single CSV line (manual aggregation is not possible because there are thousands of entries).

My plan was to put several entries with identical keys and using the --update flag and a custom process plugin, update the entry's entity by adding the Bar entity to the existing Bar entities instead of replacing them.

When I tried to put two entries with identical keys in a single CSV file, the migration module processed the first entry and ignored the second.

My understanding of the migration module is that each entry is assigned a key and that that key is mapped to the entity that was created by the migration.

Is there a way force the migration module to process multiple entries with identical keys?

I've asked the question on drupal.org as well

You can do this with drush migrate-import --update. See the migrate_tools module.


My Superfish menu is being repeated 4 times. Why? My superfish menu is being displayed 4 times. In the header. I originally selected 4 from the dropdown menu, but have since changed it to 1. Even after clearing the cache, the menu is being repeated 4 times. How do I fix this?

Fixed. I did all sorts of things but it looks like it was just being cached.


Sheetnode Multisite Javascript error message: 'Unknow line type '' ' I'm using sheetnode in a multisite configuration and I'm trying to refer data from an other sheetnode into the current sheetnode.

My issue is very similar to this one https://www.drupal.org/node/1386114 except that clean url are working correctly:

Formula: '=mapping!A1'
Javascript error message: 'Unknow line type '' '

I've been looking at the network tab in chrome and I realize that the difference between a working version and my multisite are few white line at the top of the load/sheetnode call.

I believe that this is part of my problem but I don't know how to resolve it.

Any idea of what's going on ?

Thanks.

SOLUTION:

It seems obvious now but... if you have the same problem with any other module, just look at the source code.

If you see a lot of white space at the beginning, it's a clue.

Someone might have inadvertently left a closing php tag ('?>') somewhere in his code.

Someone doing copy/paste from online example/sources....

Anyway..I pulled my hair but learned some knowledge. No hard feeling to my colleagues ! ;)


Access CCK Fields on Content Type EntityFieldQuery() Okay, I've spent two days banging my head against the wall, so I'm finally going out for help...

I have a custom content type "eod_report" with a CCK field called "rfqs_received" which stores an integer.

I need to access the value of "rfqs_received" (previous 5 entries per user), but all I get is a list of the nodes themselves. What I want is an array of the queried field values.

How can I get access to the field values? Any help is MUCH appreciated.

    <?php

global $user;
$uid = $user->uid;

$query = new EntityFieldQuery();
$entities = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'eod_report')
  ->propertyCondition('uid', $uid)
  ->propertyCondition('status', 1);

  //->fieldCondition('field_rfqs_received', 'value', '6', '<');

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = node_load_multiple($nids);
$output = node_view_multiple($nodes);

print render($output);
?>

The answer below solved it. To clarify, this was a portion of an attempt to create a custom action that would calculate the average of field values for the last five pieces of content created by a user. The action occurs when content is saved/updated and saves values to the current user's profile. It's a bit sloppy, I think, but it works. I'm still learning... Here's the full code of the action:

    <?php

global $user;
$uid = $user->uid;

// query the database to get the previous 5 eod_reports
$query = new EntityFieldQuery();
$entities = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'eod_report')
  ->propertyCondition('uid', 50)
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC')
  ->range(0,5);

$result = $query->execute();

// Collect the $nids of the nodes returned by the query

$nids = array_keys($result['node']);

// Declare an empty array to store the rfq results
$rfqs = array();
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // Get the field items
  $items = field_get_items('node', $node, 'field_rfqs_received');

  // loop through items, extract rfq values and store to array.
  foreach ($items as $item) {
    // Add to the output array.
   $rfqs[] = field_view_value('node', $node, 'field_rfqs_received', $item);
  }
}

// Declare an empty array to store the order results
$orders = array();
foreach ($nodes as $node) {
    // Get the field items
    $oitems = field_get_items('node', $node, 'field_orders_received');

    // Loop through items, extract order values and store to array.
    foreach ($oitems as $oitem) {
    $orders[] = field_view_value('node', $node, 'field_orders_received', $oitem);
    }
}

// Prepare the loop to sum the rfq results

$rfqSum = 0;
$i = 0;
// Loop through the results and collect a sum
while ($i < 5) {
    $rfqSum = $rfqSum + render($rfqs[$i]);
    $i = $i + 1;
}

// Prepare the loop to sum the order results

$orderSum = 0;
$x = 0;
// Loop through the order array to collect sum
while ($x < 5) {
    $orderSum = $orderSum + render($orders[$x]);
    $x = $x + 1;
}

// Print the Sums

print "
RFQ Sum: " . $rfqSum . "
";
print "
Order Sum: " . $orderSum . "
";

// Calculate the average

$rfqAvg = $rfqSum/5;
$orderAvg = $orderSum/5;

// Print the average
print "
RFQ Avg: " . $rfqAvg . "
";
print "
Order Avg: " . $orderAvg . "
";

// collect the current user information and store the calculated value in the user->field

$existing = user_load($uid);
$edit = (array) $existing;
$edit['field_rfq_average']['und'][0]['value'] = $rfqAvg;
$edit['field_order_average']['und'][0]['value'] = $orderAvg;
user_save($existing, $edit);

?>

EntityFieldQuerys are for querying entities, with the option to filter on their field values. They don't have the capacity to return any field data.

What you might be looking for is something like this, using field_get_items() and field_view_value()

...
$output = [];
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // Get the field items
  $items = field_get_items('node', $node, 'field_rfqs_received');

  // Truncate to the necessary number (your logic will probably change here)
  foreach (array_slice($items, 0, 5) as $item) {
    // Add to the output array.
    $output[] = field_view_value('node', $node, 'field_rfqs_received', $item);
  }
}

print render($output);


Having multiple Drush instances for different core versions So in my environment, I have some websites on Drupal 7 and some on Drupal 8, and since the latest Drush 9 works with Drupal 8.4+ I was wondering if there's a way to be able to have both Drush 9 and (put another version here) to work on both major Drupal versions.

I'd like to be able to just use drush as my main alias and not define different aliases for different Drupal versions.

Ideal way would be to use Composer to set up your projects. I'd recommend Composer templates for Drupal projects. Then add Drush to your project: composer require drush/drush.
Now install Drush Launcher on your machine, globally. Drush Launcher provides a drush command that always finds and uses the locally installed Drush from the /vendor folder.
$ cd MYDRUPAL
$ drush --version
Drush Launcher Version: 0.6.0
Drush Commandline Tool 9.3.0

But probably you can not simply rebuild your projects. Then you may want to install two different global Drush versions. See https://github.com/drush-ops/drush/releases for all available versions.
drush8
$ sudo git clone https://github.com/drush-ops/drush.git /usr/local/src/drush8

$ cd /usr/local/src/drush8

# Check the latest Drush 8 version at https://github.com/drush-ops/drush/releases
$ sudo git checkout 8.4.6

# Linux:
$ sudo ln -s /usr/local/src/drush8/drush /usr/bin/drush8

# Mac:
$ sudo ln -s /usr/local/src/drush8/drush /usr/local/bin/drush8

$ sudo composer install

$ drush8 --version
Drush Version   :  8.4.6

drush9
$ sudo git clone https://github.com/drush-ops/drush.git /usr/local/src/drush9

$ cd /usr/local/src/drush9

# Check the latest Drush 9 version at https://github.com/drush-ops/drush/releases
$ sudo git checkout 9.3.0

# Linux:
$ sudo ln -s /usr/local/src/drush9/drush /usr/bin/drush9

# Mac:
$ sudo ln -s /usr/local/src/drush9/drush /usr/local/bin/drush9

$ sudo composer install

$ drush9 --version
Drush Version   :  9.3.0

Source: Installing & Using Drupal Drush on Debian 7 (Bookmark this!)


Translation for webform error message I using drupal 7 for my website. I created one feedback form using  webform and Internationalization for both English and Japan version.

It works fine, but the error message for Feedback is required. is showing 「ご意見・ご感想」は必須項目です。 where translation for Feedback is ご意見・ご感想. Here I need to show the error message 「本文メッセージ」は必須項目です。.

How can I do this? Is there any way to do this? Please help me.

By default, Drupal (and Webform) show the error message as Field_name is required, so if you want to show an error message that uses something other than field_name, you will have to override/write your own validation function.

The Webform Validation module may be of assistance here, particularly the code examples for custom validation hooks.

P.S. "本文メッセージ" is probably a mistranslation; it most likely should be flipped ("メッセージ本文", "message body").


Book navigation - how to customize outline to show progress and enforce serial navigation I have a task to customize Book outline to:

force the pages of the book to be read from start to finish.  Once a page has been read it can be revisited.
show the progress through the book.

I was thinking of using the outline links to do this.  For pages that have not been read the outline item would not be a link.  Once the page has been read it becomes a link.

I am fairly new to Drupal and have some experience creating and modifying modules.  It would seem that this could be accomplished by extending the Book module but I have not looked at the code yet.

Does this seem like the best way to go or is there an existing module that would help?

The Course module has the facilities needed to implement these features.  With a few code and css tweaks and otherwise standard Drupal content and block configurations I was able to satisfy these requirements to a large degree.

I should have explained in the original post that my site is actually a series of training modules.  I had originally planned to make this a book with the pages being the training modules.  With the Course module I instead created a book for the top level container and then added the courses (using the course content type) to this book.  Inside each course was another book that held the actual content pages.  I forced the user to navigate the pages of the course using the navigation links at the bottom of each page by hiding the outline until they had finished each course.  They could also see their progress by navigating through the courses to see which ones they had completed (with a large green check mark).  This is not a perfect solution but it works.


Twitter follow Drupal I want to show a list of Twitter users who is following a post, with a button that allows the users to follow them. The list should appear as in the following screenshot.

I have tried using the Twitter, and oAuth modules but I had no luck, so far.

It looks like from the output image above you are trying to create a widget that would show a select number of twitter users from either your own followers or from a specific list, etc. I would suggest that this is not a Drupal issue or at least you shouldn't try and treat it as one. You could do this by creating a content type and outputting it as a view using a view template, etc. but thats a lot of database overhead for data that will likely be changing frequently.

The better way to do this is to use a jQuery / javascript plugin that will pull the data as a json file from your source (either a followers feed or your list feed from twitter) and output it directly. You can use any number of existing plugins and widgets available online for this, ex. this one:

http://twittercounter.com/pages/buttons

or roll your own, but further details would be out of scope for this site.

Finally, I'd recommend that you take a look at the site you got that image from first and see if you can figure out what widget it is using, I'd bet that they are using an open widget / plugin that you can then just copy for your own site.


Creat new menu items link in menu like create new Content Type does When create a new Content Type, several new menu links will created and show in the management menu, such as node/add/article and admin/structure/types/manage/article.

Add content
    -- Article
    -- Page

How can I implement similar functionality within my custom module?

Sites
  -- Site Name A  (link to site/1)
  -- Site Name B  (link to site/2)

My hook_menu() implements code:

$items['site/%'] = array(
  // ...
  'page callback' => 'mymodule_site_view',
  // ...
);

I have tried to use _load() and _to_arg(), but doesn't work or maybe I just not use them correctly.

function mymodule_menu() {
    $items['site/%mymodule_site'] = array(
        // ...
        'page callback' => 'mymodule_site_view',
        // ...
    );
}

function mymodule_site_load($sid) {
    // load site object from database
    $site = ...
    return $site;
}

function mymodule_site_to_arg($site) {
    // I guess here I can use site object, but just get %
    return $site->name;
}

Can anybody give me on example?

I know I can create/delete menu links when create/delete my site object manually. I just want to know if I can user _load(), _to_arg() or others to implement it.

You do not need to use php code just to create a menu with menu links. You can do it with Drupal Core itself.

See below detailed tutorials that may help you.

How to create a menu and add links to it in Drupal 7

Advanced Drupal 7 menu settings, how to create parent child menu links

Create Drop Down Menus in Drupal 7 Using Nice Menus module

If you want to do it specifically using Custom Code then your callback function should call drupal_goto with link as an argument.


“Some files and directories in your install are writable by the server.” I’m running a Drupal 8.5.3 site and the module: Security Review. One od the “red” results was:  Some files and directories in your install are writable by the server.

Details:
“It is dangerous to allow the web server to write to files inside the document root of your server. Doing so could allow Drupal to write files that could then be executed. An attacker might use such a vulnerability to take control of your site. An exception is the Drupal files, private files, and temporary directories which Drupal needs permission to write to in order to provide features like file attachments.
In addition to inspecting existing directories, this test attempts to create and write to your file system. Look in your security_review module directory on the server for files named file_write_test.YYYYMMDDHHMMSS and for a file called IGNOREME.txt which gets a timestamp appended to it if it is writeable.
Read more about file system permissions in the handbooks.
The following files and directories appear to be writeable by your web server. In most cases you can fix this by simply altering the file permissions or ownership. If you have command-line access to your host try running "chmod 644 [file path]" where [file path] is one of the following paths (relative to your webroot). For more information consult the Drupal.org handbooks on file permissions.”
(long list of files, including those of /core, /modules, /themes, etc)

Nevertheless if I set the permissions of the core directory to 644 the site does not work.
How can I solve this reported warning?

6/4/4 means read+write/read/read - this is OK for files but not for directories. Directories must be executeable, so set them to something like 755 (read+write+execute / read+execute / read+execute).