FullCalendar does not display events except in the current month I successfully got FullCalendar to work on a local test site (D7.26).  It worked great with events of this month, and I can even go to next month and return back in my view and now I don't get errors.  BUT when I make events for next month, the calendar will not show them when advancing to that month.  I don't get any errors as others reported, but I just get a totally blank month.  I can search for the events and sure-nuff, they're there in the database or list of events. It doesn't make any difference if I gave it an end date/time or not.  They all just will not show when I go forward to next month in my view.  Any help would be greatly appreciated.  I'm near the time that this site needs to go live.

Dave N

My solution,
I switch in the view the 'contextual filter' the value 'when the filter values is NOT in the URL' from 'Provide default value' Type 'Current date' to 'Display all results for the specified field'.


Can't access specific admin pages I have a Drupal 8 site set up in Docksal. It was version 8.6.15, and needed updates to core and several modules. Bear with me - I don't have complete notes, because I thought everything had worked. I'm more than happy to debug... I just don't know where/how/what to look for in this case.

I would just roll back to a backed up version of the site. But that is missing ( My own fault)

The first problem I encountered, was not being able to update with Drush anymore. So I used composer to to attempt updating, with "composer require drupal/core --update-with-all-dependencies" - this was my first time doing so.

It didn't work. I had to update composer in order to continue on. After using "composer prohibits Drupal/core:8.7.3," I got several results, so I went ahead and updated them. I would tell you all I uploaded, but that was yesterday and I did not save those notes. Sorry. I also did an update of composer itself, all the packages. that appeared out of date. There were a couple that would not update, rejected by constraints.

Updated composer, and Drupal is now 8.7.3. I also did a bunch of module updates on the site as well.

I have an issue where the admin area shows I'm still on Drupal 8.6.15, even though Composer shows the latest version. I assumed this was a separate issue, but maybe it's related. There is an issue with this site being set up with drupal/drupal and not drupal/core. Something to do with the composer json.

Everything seemed fine, but when I tried to navigate to some of the admin pages (Content, Configuration or People page), I get an error:

  Fatal error: require(): Failed opening required '/var/www/docroot/vendor/composer/../doctrine/common/lib/Doctrine/Common/Reflection/ClassFinderInterface.php'
  (include_path='.:/usr/local/lib/php') in
  /var/www/docroot/vendor/symfony/class-loader/ApcClassLoader.php on
  line 112

Not even sure what first steps might be on this. When I type composer outdated, I don't see anything called class-loader or classfinder

Looking at ApcClassLoader.php, I see 'require $file;' on line 112:

 public function loadClass($class)
    {
        if ($file = $this->findFile($class)) {
            require $file;

            return true;
        }
    }

Not sure whether or not this will actually fix your issue, but I'd try:

update the drupal/core version to in composer.json to be ^8.7.0
if you're using webflo/drupal-core-require-dev, update that to ^8.7.0 as per https://www.drupal.org/docs/8/update/update-core-via-composer
run composer update drupal/core webflo/drupal-core-require-dev --with-dependencies
run your database updates, drush updb or site.com/update.php

If that still doesn't work, try:

deleting your vendor directory, core directory, and composer.lock
run composer install


In D7 how can I append an element to the DOM via ajax on an arbitrary event (not forms and not links)? There are many Form and Link related examples for D7's new Ajax features.  I'm looking for something a little less involved but haven't got it working yet.

Using ajax-reload-of-block-on-an-event

I've modeled the following contrived example:

I'm tring to request and receive a tag and then nest it within an existing one:

function MY_MOD_menu(){
    $items['ajax/insert'] = array(
            'page callback' => 'ajax_return_tag',
            'type' => MENU_CALLBACK,
            'access callback' => TRUE,
    );
    return $items;
}

function ajax_return_tag(){
    $tag = "<h1>";
    $tag .= "HERE";
    $tag .= "</h1>\n";
    return $tag;
}

Here is the js:

(attach:function ($) {Drupal.behaviors.MY_MOD = {function (context){
    var insert = function(response){
            $('.field-name-field-').html(response);
    };
    $.post('/q=ajax/insert',
            {},
            insert,
            'html',
    );

}};})(jQuery);

It does not appear that my event is firing. Do I need to do something in addition to get the js to load on document ready?  Have I made a mistake with the way I've attached the behavior?

Thanks in advance.

EDIT:  Thank's for the responses.  The typos are a result of me creating this example on the spot.  I'm not so interested in getting this specific example to run but I am interested in a example that will update/Insert a DOM element that is not a Form or Link.

FYI I don't believe the event is firing. I assume that means that it is not registered with D7's included jQuery?

First visit example.com/ajax/insert to verify your content is being printed out.

Your overall JS structure looks odd, plus you have a lot of typos. This .field-name-field- is probably not a real class since it ends in a trailing dash. /q= is not a HTTP query, you probably want /?q=.

Try this:

(function ($) {

  Drupal.behaviors.my_mod = {
    attach: function (context, settings) {

      $.ajax({
        type: 'GET',
        url: Drupal.settings.basePath + '?q=ajax/insert',
        dataType: 'html',
        success: function(response) {
          $('.field-my-field-class').html(response.data);
        }
      });

    }
  };

})(jQuery);


Profile2 not editable for new users I have two different profile2 profiles, the usual stuff.
I just found out that creating new profiles of type a makes it impossible for the user to edit his profile.

How it should be:

The user registers and goes to his empty profile, sees edit buttons and links.

How it is:

The profile is empty. you see the frame for where an image belongs, but no text at all, no buttons, no links.

I took over the project with very little documentation, already existing users have full and right functionality.
I did a permission rebuild, checked them and tweaked them without any success.

The users have permission to view, edit and delete own content.

Where should I look for the problem? What could cause such behaviour?

It turned out to be a CTools problem, I simply applied the patch mentioned in this comment:

https://www.drupal.org/node/2336985#comment-9748735 (#16)

diff --git a/plugins/content_types/entity_context/entity_field.inc b/plugins/content_types/entity_context/entity_field.inc
index 5861d1c..070266e 100644
--- a/plugins/content_types/entity_context/entity_field.inc
+++ b/plugins/content_types/entity_context/entity_field.inc
@@ -129,8 +129,7 @@ function ctools_entity_field_content_type_render($subtype, $conf, $panel_args, $

   $all_values = field_get_items($entity_type, $entity, $field_name, $language);
   if (!is_array($all_values)) {
-    // Do not render if the field is empty.
-    return;
+    $all_values = array();
   }

   // Reverse values.


How to hide menu item from high level roles but show for low level I have 3 roles on site:

anonymous user
authenticated user
admin

I created a new page:

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

    $items['learning'] = array(
        'page callback'    => 'learning_output',
        'access callback' => 'learning_access',
        'type' => MENU_CALLBACK,
        );

    return $items;
}

I manually created a menu item for this page in the top menu. This item should be displayed only for authenticated users, but not admins. Unfortunately, admin as also an authenticated user. So I had to use a trick to disallow access to this page to admins using this access callback:

function learning_access()
{
    global $user;

    $n = count($user->roles);
    if ($n === 1)
    {
        $data = array_values($user->roles);
        if ($data[0] === 'authenticated user')
        {
            return true;
        }
    }

    return false;
}

It works but when I uploaded this module to server, I was unable to manually add a menu item for this page. Because admin doesn't have access to it.

How can I allow an admin to access this page? In the same time the menu item shouldn't be shown for him.

As per the discussion above,

Remove 'access callback' => 'learning_access', add drupal_access_denied() in page call back

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

  $items['learning'] = array(
    'page callback' => 'learning_output',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function learning_output() {
  global $user;

  $n = count($user->roles);
  if ($n === 1) {
    $data = array_values($user->roles);
    if ($data[0] === 'authenticated user') {
      drupal_access_denied();
    } else {
      //YOUR code Here
    }
  }
}

And Use Roles for Menu module to hide the learning menu.

  This module allows you to restrict access to menu items based on user
  roles. It is used when you don't want to copy your whole menu just
  because for one specific role you want to hide one menu item.

  The module will add a fieldset with options for restricting access or
  gaining access to menu link for a specific role/roles


Add js file in .info theme file. And set it to load first I added this line in my-theme.info

scripts[] = js/my-file.js

The files is loads but in last place. I need it to be loaded before all modules js files.

How can I set the weight?

I also tried (same results) in template.php with:

function MY-THEME_preprocess_page(&$variables) {

  $file =  path_to_theme() . '/js/my-file.js';
  $options = array('weight' => -1000);

  drupal_add_js($file, $options);

}

You can add the scope (header/footer) where to load the JS and also add a weight.

Example options:

$options = array('type' => 'file', 'scope' => 'header', 'weight' => 5));

Play around with these to get the file loaded on the right position that suits your needs. For more detailed information check the documentation.


Theming user pictures Trying to theme user pictures, in the following statement:

 print '';

How do I replace the "width="32px" by the "thumbnail" image style?

Thanks. :)

You need to (really should) use a render array.  You can use theme_image_style:

// first, make a render array for your image, as a thumbnail...
$image_ra = array(
    '#theme' => 'image_style',
    '#path' => _drupal_wall_user_profile_picture($friend_id),
    '#alt' => 'Some alt value',
    '#title' => 'Some image title value',
    '#style' => 'thumbnail'
);

// now make your link render array...
$ra = array(
    '#theme' => 'link',
    '#text' => drupal_render($image_ra),
    '#path' => $base_url . '/user/' . $friend_id,
    '#options' => array(
        'html' => TRUE,      // this says the #text value is HTML markup
    )
);

// now you can render your image link into markup...
$image_markup = drupal_render($ra);

I took the long way to show you that you need to handle the image first, and then render it as #text in the link.  I also did this to make the case that you really, really, really, really should use render arrays and stay away from writing the HTML.  Let Drupal do that work.  Just build a render array, pass it to drupal_render, and be done with it.


How to export comments? I have two Drupal website setups. One is development and another one is live. In my live setup lot of comments are there. I want to export all comments and import to development setup.
How can I do that?

The best way to migrate content is the Migrate module, in the module page you can find many Case studies with code inside and in the documentation page you will find all the information that you need.

Inside the Migrate module folder you can find the Beer.inc file, which is an example of how you can do simple mappings. For more complicated migrations you can look into Wine.inc.


How to display all links of the Answers module on a single page? I using the Answers module, which provide the various set of views as shown in the image below. But it does not provide anything where we can provide these views as a link. I mean I want all these four views in one line as a menu tabs on page,

So, it should be like this:

Main menu tab: Q&A
When this Q&A tab is clicked, it should show all these 4 tabs with first tab as default:

  All Questions | Unanswered Questions | Search Questions | Search & Add Page

I am surprised this option is not available by default.

The Panels module allows you to create "pages" of blended content at an URL or URL with a context argument (like a node ID). For example an arbitrary node, 4 views, a custom text panel and a block. It's extremely flexible and fairly easy to learn. Once you've learned the basics you'll never build a site without it.

Panels module


Get path/url/uri of Entity reference field to content in a Twig template? I have a Entity reference field which links to internal content/node.

I can get the title with {{ node.field_related_project_internal.entity.label }}

But how can I get the raw path/url/uri of the linked content/node?
The soloutions for a Link Field to not work here:
How to get the valid URL of a Link field from within a Twig template?

The url is not an entity field, so you can't access it directly. Also the entity methods to generate url/links are not accessible in Twig because of the sandbox policies. You can build a path though, if you have the id of the referenced node:

{% if not node.field_ref.isempty %}
  {{ path('entity.node.canonical', {'node':  node.field_ref.entity.id}) }}
{% endif %}

Reference: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates


How to execute request-specific tasks after page response is returned. Does hook_exit() actaully do this? I'm trying to figure out if it's possible to "hide" the perceived execution time of some end-of-request logging tasks that are page specific and depend on the availability of the Drupal DB API. Essentially I'd like to run these tasks after the page response is returned in full to the browser. I've always just assumed that hook_exit() was the right choice for this kind of thing but after looking at its invocation within drupal_page_footer() in some detail, I'm not so sure. Here's the notable snippet from drupal_page_footer():

module_invoke_all('exit');

// Commit the user session, if needed.
drupal_session_commit();

if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
drupal_serve_page_from_cache($cache);
}
else {
  ob_flush();
}

So it looks like both cached and un-cached responses are not sent to the browser until after all hook_exit() implementations run (flushing the buffer and executing drupal_serve_page_from_cache() both happen after module_invoke_all('exit')). This seems a bit contrary to the hook_exit() documentation which states that, "This hook MUST NOT print anything because by the time it runs the response is already sent to the browser."

Am I perhaps misinterpreting the way hook_exit() implementations work in relation to the response delivery? If not, is there some alternative way to trigger custom logging logic later in the response (while DB access is still available)? Perhaps by registering a shutdown function or something to that effect?

You're looking for fastcgi_finish_request(). Recommend using it inside of a shutdown function. If you need something else the HTTPRL module should be able to do what you need with threading.


public files config in settings.php creates .htaccess file I had multisite previously, two sites sharing same codebase like but having their own files system: -

site1 -> sites/site1/files/FILES_HERE
site2 -> sites/site2/files/FILES_HERE

Now I am trying to separate the sites to its own sites and separate codebase to use the normal Drupal structure like: -

site1 -> sites/default/files/FILES_HERE
site2 -> sites/default/files/FILES_HERE

but somehow whenever I clear the cache, it creates folder like: -

site1 -> sites/site1/files

and uses this instead of /sites/default/files

To overcome that I added some config in settings.php file

$conf['file_public_path'] = 'sites/default/files/';
$conf['file_temporary_path'] = '/tmp';

Now, the site1 uses proper file i.e. /sites/default/files but it creates .htaccess files inside sites/default/files/ folder. The .htaccess file contains:

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

The images in the website doesn't load properly because of this file. If I delete this file the Images load properly, but while clearing the cache the file is auto generated and again the image doesn't load.

File permission is not an issue here as its 775 universal except for settings.php file.

The main culprit was extra trailing / in the files path in settings.php file. Which I changed to

$conf['file_public_path'] = 'sites/default/files';
$conf['file_temporary_path'] = '/tmp';

And deleted the .htaccess file, now the files inside sites/default/files are readbale by server even after clearing the cache.


Pass positional arguments to drush via drushrc.php? drush allows you to pass default arguments in a drushrc.php-file like:

    $command_specific['command'] = array(
      'argument' => 'value',
      …
    );

This seems only to work for named options. Is there a way to also pass positional arguments via drushrc.php (like the installation-profile for drush site-install)?

I tried to use $command_specific['site-install'][0] = 'profile'; but that didn't work.

Alas, there is no command-specific argument feature in Drush.  You can't even use a pre-command hook to fill in the arguments, as Drush will check for required arguments before calling any command hooks.

Another option would be to define a shell alias, and define your argument there:

$options['shell-aliases']['myis'] = 'site-install xyzzy';

Then you can use this as drush myis [other options], and your profile name will be inserted.


Can a Panel be converted to a Mini-Panel? I have a panel.  I have my link to the panel.  What I can't do is put that page as a block.  Honestly, I'm not sure the purpose of a panel if you can't put it anywhere other than link to it.

I read you can use mini-panels to make a block.  Is this accurate?  If it is can I convert a Panel that I already have into a Mini-Panel so that when I go to the blocks, I will see that Mini-Panel and be able to assign it to a region?

Am I misunderstanding things?

Thanks.

Yes and no.  Panels is a module with a whack of facets.  Based upon the context of your question it sounds like you created a page via the panels interface.  So.  That's a page and that's why you can only really link to it ( or override another drupal generated page.

Mini panels are exposed as blocks and also as elements usable in other panel facets (like pages or other mini blocks).

You'll have to create a new mini panel from scratch but all the elements you used to create that custom page are available to you.  If you made custom elements just check the make reusable and then they'll be available to your mini panel.


How can I create newsletter template by Simplenews I have Drupal v7 and installed the Simplenews module, but now when I send a newsletter, I need to edit the HTML format.

Where can I edit this template?

from this tutorial website I found after a quick google search:
http://www.wdtutorials.com/2012/07/06/drupal-7-how-create-newsletters-simplenews#.VCEqY_l_uVM

Using templates
First select the theme you like to use to render the emails in

/#overlay=admin/config/system/mailsystem

There are 4 template files you can override in sites/all/modules/simplenews/theme:

simplenews-block.tpl.php
simplenews-multi-block.tpl.php
simplenews-newsletter-body.tpl.php
simplenews-newsletter-footer.tpl.php

Just copy them to your theme templates folder (like themes/bartik/templates) and edit them.


Zen theme not writing source maps I have made a subtheme of zen and started making some changes to it's SASS files.
However now I have some layouts that aren't working as I expected, so I went to the chrome devtools, but that only tells me what CSS file the particular thing is in.

What I want is what SASS file it is in. Now, when I read the config.rb file it says it has some support for FireSass, but that plugin has been removed by the author, so no luck there.

I do have the environment set to :development and the firesass = true, therefore the sass_options :debug_info => true.

So I go to the root in the theme file /sites/all/themes/mytheme and run compass watch, but there are never any source maps.

I think this issue: https://www.drupal.org/node/2295227 addresses your question.

Though haven't tried it myself, but the current dev-version of Zen should contain the 'fix' (i.e., using FireCompass instead of FireSass) to debug SASS-code in an easy way.


Migrate nodes from D7 to custom entity defined in D8 I have defined custom entity using Drupal console. the entity have extra columns defined to store field data from D7 nodes migrated instead of having entity fields.

I am using Migrate tools and Migrate plus modules and created migration group defined as below:

id: phases
label: Phases nodes migration
migration_group: phases
deriver: Drupal\taxonomy\Plugin\migrate\D7NodeDeriver

source:
  plugin: d7_node
  node_type: phase

destination:
  plugin: entity:phase_entity

process:
  id: nid
  type:
plugin: default_value
default_value: phase
langcode: language
name: title
user_id: uid
changed: changed
created: created

migration_dependencies: { }

The migration group listed under admin/structure/migrate But no import action execute.

I have tried to import with basic fields only but nothing happens.

I searched a lot but no results even examples, I did created destination plugin to save the entity but I don't know how to.

Do I have write some code? where to write it or where docs for that part?

Does Drupal migration not work for custom entities at all so I have to look for another solution?

Any help will be appreciated, Thanks in advance.

It looks like you're very close. Is your entity called "phase" or "phase_entity"? If it is "phase", then you should adjust that under destination. Here is what I would recommend:

id: phases
label: Phases nodes migration
migration_group: phases
source:
  plugin: d7_node
  node_type: phase
destination:
  plugin: entity:phase
process:
  id: nid
  type:
    plugin: default_value
    default_value: phase
    langcode: language
  name: title
  user_id: uid
  changed: changed
  created: created
migration_dependencies: { }


How can I export webform analysis data to excel sheet? Screenshot:

Problem:
I want to export all Analysis datas to excel sheet.

I am using drupal 7.53 and webform 7.x-4.14.

I wrote a module for this. You can find it here: drupal.org/project/webform_analysis_export


How to reference external JS callback in custom module So I apologize if I mess the terms here up, I'm relatively new to using jQuery in Drupal. I'm trying to implement a custom Google Map application with the V3 API. When I started mocking the module up I had no problem invoking the google maps function callback without my JS being wrapped in a closure. However, needing to use jQuery functions pointed me to wrapping my JS in a closure and referencing jquery, as well as attaching my js to the Drupal.behaviors object. The problem that I have is that now it seems that the callback on my Google Maps script tag is out of scope. I'm not sure if this is due to the closure, due to how I'm loading the script, or something else that I haven't come across yet. The specific JS error I get is

Uncaught (in promise) message: "initMap is not a function"

My module JS is

(function ($) {
Drupal.behaviors.gmap_json = {
attach : function (context, settings){
var map, alumLayer, chapterLayer, assocLayer, userLayer;
  function initMap() {
    map = new google.maps.Map(document.getElementById('json-map'), {
      zoom: 4,
      center: {lat: 38.43, lng: -90}
    });
  alumLayer.setStyle({
    icon: 'purple.png',

  });
}
}
};
      alert('it works');
}(jQuery));

And my module php is

function gmap_json_block_info() {
    $blocks = array();

    $blocks['gmap_json'] = array(
      'info' => t('Google Maps with GeoJSON'),
    );

    return $blocks;
  }

  function gmap_json_block_view($delta = '') {
    $block = array();
    if ($delta == 'gmap_json') {
      $block['subject'] = '';
      $block['content'] = '

';
    }
    $path = drupal_get_path('module', 'gmap_json');
    drupal_add_js('https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap', 'external');
    drupal_add_js($path. '/gmap_json.js', 'file');

    return $block;
  }

So, what am I doing wrong and how can I either bring my callback into scope? Or what's the right way to set this up.

EDIT:
I have attempted to implement both the answer as well as one of the comments.

drupal_add_js('https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap', array('type' => 'external', 'defer' => 'defer'));

Adding a "defer" via array doesn't produce any changes, and changing the order of my calls to the js only changes where the error gets called.

You could/should add the defer tag to your maps drupal_add_js as recommended by google (https://developers.google.com/maps/documentation/javascript/tutorial)

You'll get abit better page performance and should get rid of your issue you're facing as the google maps code will always be loaded after your scripts

Here's how you can add the defer tag:
How to drupal_add_js an external and defer script


Change Product price based on discount set by site owners for different domain - Drupal Commerce I am working on a website that uses the following modules to create products.

Domain Module to create different domains for different store owners.
Drupal Commerce to create products and ecommerce facility.

The idea is each store admin will have a different domain in the website so that they can setup there stores. Also they are able to create the products for their own.
The product types have a field called "Commission", which stores a value in it. It is used to pay back some commission to the store owners if that product is purchased from the site owner's store.

Each site owner has a admin page where a custom module sets a variable called "Discount" which will denote the percentage of discount to apply in each product globally only to that domain.

As an example, suppose a domain store has a product with $100 and that product has a Commission 25% the upon selling that product the domain's site owner will get $25.
But if that site owner sets the global Discount variable as 50% then the buying user will have a discount on $100 product of 12.5% as $87.50 and the site owner will get commission as 12.5% as $12.50.

Is there any way or HOOK that I could use to alter the price once it goes to the Checkout page?

The easiest thing is to hook into rules, as there is a rules event, for when the price for a product is being calculated: commerce_product_calculate_sell_price. This event is designed to hook into, in order to change price for discounts and the like.

You can create your own custom action to provide the discount, or try to use the Rules interface to setup the logic there.


Render link elements in blocks? I'm trying to create a simple block that have some link fields. those links have some predefined values and after get any new values from the admin replace with values and then render that values to the theme:
my_module\src\Plugin\Block\MyBlock.php:

<?php

namespace Drupal\my_modules\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block"),
 *   category = @Translation("My Block")
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    // set default link field value.
    return array(
      'default_LinkA_url' => ('http://www.LinkA.com/'),
      'default_LinkB_url' => ('http://www.LinkB.com/'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    // Add a form field to the existing block configuration form.

  $form['block_LinkA_url'] = array(
    '#type' => 'url',
    '#title' => t('Link A:'),
    '#size' => 60,
    '#default_value' => $this->configuration['default_LinkA_url'],
  );
  $form['block_LinkB_url'] = array(
    '#type' => 'url',
    '#title' => t('Link B:'),
    '#size' => 60,
    '#default_value' => $this->configuration['default_LinkB_url'],
  );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->configuration['default_LinkA_url'] = $form_state->getValue('block_LinkA_url');
    $this->configuration['default_LinkB_url'] = $form_state->getValue('block_LinkB_url');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => $this->configuration['default_LinkA_url'],
      '#markup' => $this->configuration['default_LinkB_url'],
    ];
  }
}

Whatsoever I try I can't get any result, and this code only show one link like below:
http://www.LinkA.com (a plain text only)

but what I want to achieve is some think like This:
Link A
This Link has Some CSS Style and Open in new page rater than being a plain text like above link.
I would be happy to hear what the problem is.

You have to build a render array like this:

   public function build() {
     $build = [];
     $build['linkA'] = [
       '#type' => 'link',
       '#title' => 'Link A',
       '#attributes' => [
         'class' => 'link-class',
         'target' => '_blank',
       ],
       '#url' => Url::fromUri($this->configuration['default_LinkA_url']),
     ];
     $build['linkB'] = [
       // ...
     ];

     return $build;
   }

You can add attributes to the link, classes for css or a target to open it in a new tab.


Drupal 6 Apache Solr Search Problems with result ordering & fields As I am implementing a website made in Drupal 6 and using Apache Solr search as the search application in the website.

Drupal Version 6.22
Apache Solr Version : 3.6
Apache Solr Module: 6.1.x

Below are the two problems I am facing.

While searching a particular content the business requirement is to search only in the Title field, Body field and in the Terms attached in a node. How can I achieve that?
I have used the HOOK_apachesolr_modify_query() in some other purposes. Do I have to mention all the filters here again? like,

mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
   $query->add_filter('title', $keyword);
   $params['fl'] = 'title';
}

The second is that once the contents are being searched as per the requirement I should get the result based on the following algorithm.

1st result = (Match in Title + Match in Body + Match in Terms names) (Keyword present in all)

2nd result = (Match in Title + Match in Terms names) (Keyword only present in title & term names)

3rd result = (Match in Title + Match in Body) (Keyword present in Title & Body)

So I added a boost factor from the Apache Solr admin section as
Title = 1.0
Term = 0.50
Body = 0.25

But the ordering is not maintained.

I even also mentioned

function mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
   $params['qf'] = array('taxonomy_names^0.50', 'title^1.00', 'body^0.25');
}

But no effect. Please suggest any ideas.
Help me on these issues, I am really stuck here :(

I would suggest you look into the Views module and/or Apache Solr Views. This blog post http://blog.hsl.virginia.edu/drupalpress/apachesolr-views-drupal-6/ might also be useful.


How to insert value to taxonomy on custom form submission I have a page where admin can add a new hospital name to the site, search for the hosiptals and view all the hospitals in a tabular format. This is done by writing custom module and form.

What I now need is to add the value of the newly created hospital to a taxonomy term "hospital". So that I can use this taxonomy term reference in multiple content types.

If admin adds hospital-1 and hospital-2 to the site using custom form, on form submission these should automatically get added to the taxonomy term.

To add taxonomy term in form submission, get all inputted term values and those to Vocabulary you need.

use Drupal\taxonomy\Entity\Term;
$categories_vocabulary = 'EXAMPLE'; // Vocabulary machine name
$categories = ['test 1', 'test 2', 'test 3', 'test 4']; // List of test terms
foreach ($categories as $category) {
  $term = Term::create(array(
    'parent' => array(),
    'name' => $category,
    'vid' => $categories_vocabulary,
))->save();


CKEditor not showing toolbar in Drupal I want to use CKEditor to edit page contents in my Drupal web site. The problem is after installing the newest version of CKEditor toolbar is not showing when I want to edit certain Block body. Is this a bug or editor itself requires more configuring ?

Installed Wysiwyg profile module (if is not exists)
If installed configuration->content authoring -> wysiwyg profiles

select editor  drop down list

Full HTML -> ckeditor

click "Install Instruction Tab"

check ckeditor


Is this the correct way to add a page with hook_menu()? I'm trying to create a page through hook_menu() so I can add my custom block with context instead.
function my_module_menu() {
    $items['my_page'] = array(
        'title' => 'my_page',
        'description' => 'my_page',
        'page callback' => 'my_function',
        'access callback' => true,
    );
    $items['my_page2'] = array(
        'title' => 'my_page2',
        'description' => 'my_page2',
        'page callback' => 'my_function',
        'access callback' => true,
    );
    return $items;
}

function my_function() {
    return '';
}

Is it the right way to do it?
I have some bug from time to time, like the block goes missing on those pages. Could it be related to that?

No, the menu items are fine. The problem seems with your block display configuration settings.
There is no permission with these menu items; give some loosely coupled permission (such as access content) to these callbacks. Function names should be prefixed with the module name to avoid clashes with other modules.
function my_module_menu() {
  $items['my_page'] = array(
    'title' => 'my_page',
    'description' => 'my_page',
    'page callback' => 'my_module_my_function',
    'access arguments' => 'access content',
  );

  $items['my_page2'] = array(
    'title' => 'my_page2',
    'description' => 'my_page2',
    'page callback' => 'my_module_my_function',
    'access arguments' => 'access content',
  );

  return $items;
}

function my_module_my_function() {
  return '';
}


Paginate views by first letter of Node title I'm creating a View of staff profiles. It's a simple list of Node's Title filed (which happens to be the person's name. Instead of paging by number of items, I want to group them by first letter of first name. How should I start this?

Views comes with a nice default glossary view out of the box. Go to /structure/views/view/glossary/edit, enable it and set it to filter for your content type. viola.

And in case you are  wondering where the Magic happens then you would find it in the contextual filter MORE options.


How to change the size of the avatar in Drupal 7? When i visualize user avatar in Drupal 7 using this code:

$account = user_load(2);
print theme('user_picture', array('account' => $account));

The following image is generated:

How can i control such parameters as size of the image, title, alt?
And how can i get rid of the link (or change the path) which is generated automatically with the image?

...

You should use theme_image_style instead.

**Update:

Example setting width/height attributes by hand (until it's resolved in Drupal core):

global $user;
$user = user_load($user->uid);
print theme('image_style', array( 'path' =>  $user->picture->uri, 'style_name' => 'thumbnail', 'width' => '150', 'height' => '162'));

Remember to change your image style 'thumbnail' in this case to your desired width/height. Now that I think about it you don't necessarily need to use theme_image_style, you could just edit the image style thumbnail presets and get the desired results. If you want width/height HTML attributes, use the example above.


Pass data from a hook to (be used in another hook) So in a hook hook_commerce_cart_order_refresh() I make some calculations that I would later like to use in a different hook hook_form_alter, how can I pass these data/object and use later on?

In that first hook, I have a EntityMetadataWrapper but it seems I can only give it data that actually is persisted, and mine should only exist for the request.

Again, I could use $_SESSION but that storage is used for persistent storage through multiple requests. And I'm not looking for that.

Any suggestions?

You can't, there's no mechanism to pass data from one arbitrary function to another (which is what two separate hooks essentially are). You'll have to make the data available another way.

Drupal uses a pattern like this all over the place:

function MYMODULE_get_data() {
  $data = &drupal_static(__FUNCTION__, NULL);

  if (!$data) {
    $data = some_function_to_build_data();
  }

  return $data;
}

function MYMODULE_commerce_cart_order_refresh(...) {
  // Get the data, populating it if it doesn't already exist.
  $data = MYMODULE_get_data();
}

function MYMODULE_form_alter(...) {
  // Retrieve the data.
  $data = MYMODULE_get_data();
}

That's a contrived example, it'll make more sense when you plug your own requirements into it.


How can i use taxonomy name in url page using a view I have a taxonomy terms like:

christmas
wedding

How can I build a view with url page like this: www.site.com/%
being % christmas or wedding,

If users go to  www.site.com/christmas just display nodes with christmas taxonomy.

If users go to  www.site.com/wedding just display nodes with wedding taxonomy.

I have to do n views with same fields that why I want to do just one generic view.

The PathAuto module allows you to easily change the URLs for the default taxonomy listings (which do what you describe).

Install the module and go to Administration > Configuration > Search and metadata > URL aliases.

You can set a pattern for your vocabulary that is just [term:name] BUT there are good reasons not to do that (for example if a category overlaps with a default path).  Something like holiday/[term:name] is likely a better choice.

For more options on PathAuto see the recipes from Drupal.org.

If you need more control over the display you can override the view that generates term pages.


Absolute urls in Simplenews Newsletters Is there a way to automatically convert the relative urls to absolute? For example, when uploading an image it is automaticlaly included as a relative url, so it doesn't appear in the html email when received. Is there an automated way to change this or does one need to go in the source of the newsletter and change the url for all image/link instances?

Pathologic input filter will do that for you.

  Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.

Download and install the module, and then enable it for the text format you're using. It also supports the feature to bulk update your existing paths.


Add custom views options I am trying to add some custom view options. I am not even sure if what I'm trying to do is possible.

Basically I want to put a custom option under the Other category.

It would look like:

My custom options: disabled

When the user clicks on "disabled", it should show a custom form where the user can set some settings for that view.

I have looked into this, but couldn't find anything that would let me add custom options here.

What you're actually looking to do is to implement a custom Views Display Extender plugin (https://api.drupal.org/api/views/views.api.php/group/views_plugins/7.x-3.x).

It's not particularly trivial and I got most of my information from this wonderful tutorial here: How to write a Views Plugin Display Extender (D7) by Bryan Ollendyke

Here's a basic outline:

-create a custom module (let's call it mymodule) and implement hook_views_api().

/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule'),
  );
}

-Create a mymodule.views.inc file (remembering to add the file to your mymodule.info file) and implement hook_views_plugins(). It should look something like this:

/**
* Implements hook_views_plugins().
 */
function mymodule_views_plugins() {
  $path = drupal_get_path('module', 'my_module');
  $plugins = array();

  $plugins['display_extender'] = array(
    'mymodule' => array(
      'title' => t('Some Setting'),
      'help' => t('A description of the setting.'),
      'path' => $path,
      'handler' => 'mymodule_views_plugin_display_extender',
    ),
  );

  return $plugins;
}

-Note the "handler" index in the above array. You'll need to implement that in a file called mymodule_views_plugin_display_extender.inc (again, remembering to add that in your mymodule.info file). The implementation should look something like this:

class mymodule_views_plugin_display_extender extends views_plugin_display_extender {
  /**
   * Provide a form to edit options for this plugin.
   */
  function options_definition_alter(&$options) {
    $options['my_setting'] = array(
      'default' => 0,
    );
  }

  /**
   * Provide a form to edit options for this plugin.
   */
  function options_form(&$form, &$form_state) {
      parent::options_form($form, $form_state);

      if ($form_state['section'] === 'mymodule') {
        $form['my_setting'] = array(
          '#type' => 'checkbox',
          '#title' => t('Some Setting'),
          '#description' => t('A sample checkbox.'),
          '#default_value' => $this->display->get_option('my_setting'),
        );
      }
  }

  /**
   * Handle any special handling on the validate form.
   */
  function options_submit(&$form, &$form_state) {
    $this->display->set_option('my_setting', $form_state['values']['my_setting']);
  }

  /**
   * Provide the default summary for options in the views UI.
   *
   * This output is returned as an array.
   */
  function options_summary(&$categories, &$options) {
    $options['mymodule'] = array(
      'category' => 'other',
      'title' => t('Some Setting'),
      'value' => ($this->display->get_option('my_setting')) ? 'Yes' : 'No',
      'desc' => t('Set a setting.'),
    );
  }

}

After all that your mymodule.info file should look something like this:

name = My Module
description = Sample views display extender
core = 7.x
version = 7.x-1.0

dependencies[] = views

files[] = mymodule.views.inc
files[] = mymodule_views_plugin_display_extender.inc

If that all works out, you should see a setting show up under "Other" (you can change that using the 'category' in the options_summary implementation in mymodule_views_plugin_display_extender.inc.

After that, in your module, you can access the option from the view using something like:

$view->display_handler->get_option('my_setting');

For instance, if you were implementing `hook_views_post_execute().

/**
 * Implements hook_views_post_execute().
 */
function mymodule_views_post_execute(&$view) {
  $my_setting = $view->display_handler->get_option('my_setting');
}


Restrict pagination using entity field query I have pagination using entity field query:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'content_type');
$query->pager(3,0);
$result = $query->execute();
$pager=theme('pager');
print render ($pager);

and it is successfully displayed like below,

I need to restrict them to display to number 6 then ... like below:
1,2,3,4,5,6....next,last

It's very easy. Just use

$pager=theme('pager', array('quantity' => 6));


Field is not removed from 'field_config_instance' Possible Duplicate:
  Clean Deleted Field from Database

Why the record about deleted field still exists in  'field_config_instance' only status 'deleted' = 1 ? But from 'field_config' records about field removed completely.

function mymodule_uninstall() {

  field_attach_delete_bundle('spproduct' , 'spproduct' );
  field_delete_field('field_spproduct_image');
  field_purge_batch(10);
}

I wont to remove field from all entity types wherevere it is used and from tables.

If you've got a fair amount of data, you'll need to allow cron to run a few times, or else do a larger batch purge

field_purge_batch(10)

Will only delete 10 records.

  $batch_size: The maximum number of field data records to purge before
  returning.


Migrate multilingual Drupal 7 users to Drupal 8 I have Drupal 7 users that uses Profile module and has fields for individual languages i.e. presentation_sv, presentation_en that I would like to migrate to a proper Entity translated Drupal 8.

First migration file:

id: custom_user
label: "Custom User accounts"
migration_group: custom
migration_tags:
  - Custom D7
class: Drupal\user\Plugin\migrate\User
source:
  plugin: d7_user
process:
  langcode:
    plugin: default_value
    default_value: sv
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  presentation: profile_presentation_sv
destination:
  plugin: entity:user

Here is the translations migration file:

id: custom_user_translations
label: "Translated Custom User accounts"
migration_group: custom
migration_tags:
  - Custom D7
class: Drupal\user\Plugin\migrate\User
source:
  plugin: d7_user
  translations: true
process:
  uid:
    plugin: migration
    source: uid
    migration: custom_user
  langcode:
    plugin: default_value
    default_value: en
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  presentation: profile_presentation_en
destination:
  plugin: entity:user
  translations: true
migration_dependencies:
  required:
    - custom_user

The error I get:

Next Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'map.destid2' in 'field list': SELECT map.sourceid1 AS sourceid1, map.destid1 AS destid1, map.destid2 AS destid2
FROM
{migrate_map_custom_user_translations} map
ORDER BY destid1 ASC; Array

Looks like your migration configuration needs to be re-installed. When I had that issue I deleted the map table (in your case migrate_map_custom_user_translations) and then re-installed the config (I used the config_devel module).


Webform formatting question I'm running Drupal 7.34 and Webform 7.x-4.9/Webform Layout 7.x-2.2.

I've put together a webform to be used for customers to fill out their data. If I select Label Display "Above", it disappears and no labels show. If I set it to "Inline" it works better, but the spacing is goofy (see link).

How do I set it so that the "Above" label display works, and how do I control setting up the spacing (so that I can have only one on a line)?

Thanks in advance for any help you can provide.

This looks like a CSS issue with your template rather than a Webform/Drupal issue.

The webform module adds a default ".form-item" class to the wrapper DIV around each form element.

Try adding "clear:both;" to that class to force the form elements to vertically stack. Something like this:

.form-item {
   clear: both;
}


feedback for duplicate registration attempt if a user tries to register with a username or email that is already in use, there is no feedback telling them this, it just highlights the form field red, this is quite a bad UX.

How can I add translatable text to the effect of "that email is already in use, have you forgotten your password?" ?

I would really like to do this without adding a module.

Here you can see there is validation feedback, but it's not relevant, as my username meets its criteria, it should highlight the duplicate account problem. The user would just get frustrated at this point as they are told to do something which makes no difference.

It sounds like your theme is missing  from the page template, which will usually show a description of the error at the top of the page.

I know you said no modules but I would recommend looking at Username originality AJAX check which is very small and does an ajax lookup before the form is submitted.


How to hide a views result item based on role? I have a View based on taxonomy vocabularies and terms. The view only contains 2 fields, taxonomy vocabulary and taxonomy term and the output is HTML list.

How can I hide one of the terms in one of the vocabs in the view result based on the role of the logged in user?

UPDATE:
With the help from No Sssweat below, this is how the final snippet looks like:

function mytheme_preprocess_views_view_fields($vars){
  global $user;
  if ($vars['view']->name == "view name" && strip_tags($vars['fields']{rendered_entity}->raw) == tid && in_array('user role', array_values($user->roles))){
    $vars['fields']{rendered_entity}->content = NULL;
  }
}

... in case anyone else need something like this snippet.

Assuming you added Taxonomy term: Name as the field, which you want to hide.

Add this to your theme's template.php file.

function mytheme_preprocess_views_view_fields($vars){

  $global user;

  if ($vars['view']->name == "name_of_view" && strip_tags($vars['fields']['name']->content) == "Term Name" && in_array('role name', array_values($user->roles))){
    $vars['fields']['name']->content = NULL;
  }

}

change mytheme to your actual  theme name.
change name_of_view to your view name.
change Term Name to the name of the term.
change Role Name to the specific role name.


Tree with linked structure and node leafs I am working with Drupal 6 and i need to create a 3 level tree with 2 levels of links(topic and subtopic) and a third level of faqs.
Example:

Topic1
--Subtopic1
----FaqA
----FaqB
--Subtopic2
----FaqC
----FaqD
----FaqE
--Subtopic3
----FaqF
----FaqG
Topic2
--Subtopic4
----FaqH
----FaqI
----FaqJ
--Subtopic5
----FaqK
----FaqL
--Subtopic6
----FaqM
----FaqN
----FaqO

The thing important to me is that:
I am in the root(home)-> I need to see all the topics and subtopics;
I click on a topic -> I need to see all the subtopics of that topic;
I click on a subtopic -> I need to see all titles of the faqs of that subtopic;
I click on a faq title -> I need to see the full faq node;

Each page need to have a breadcrumb that shows where the user is.
The topic and subtopic pages have just a list of links to childrens, so i don't know if they have to be nodes, so maybe i just need the Faqs to be node, but i don't know how to build the topic and subtopic structure and from my tests i didn't find anything fitting (i have checked "book" content, cck, custom breadcrumb, node hierarchy and many other)
Can anyone help me?

Solved!

I have used this piece of code, palced on the "header" of the view, to obtain my goal:

$term = taxonomy_get_term(arg(1));
$parent = current(taxonomy_get_parents(arg(1)));
$name = $term->name;
echo "
".$parent->name."
"; //topic
echo "
".$name."
"; //subtopic
$breadcrumb = array();
$breadcrumb[] = l('Home', '<front>');
$breadcrumb[] = l('Topic', 'Topicview');
$breadcrumb[] = l(drupal_get_title(), base_path() . request_uri());
drupal_set_breadcrumb($breadcrumb);


Views timestamp not recognized as date? I have an INT field with a Unix timestamp.  When I add this field to a view, I do not get any date formatting options.  I just get options for the thousands market (non, comma, etc).  How do I get Drupal to recognize that this is a date field?

I am using the Date modules.

I have an INT field that's the problem. You need to use a Date field and not an integer field. As INT fields are not meant/designed to hold dates. Drupal cannot know that your INT it's actually a time stamp and not a number.

As per my Q here: Unix timestamp time is not saving to DB, I was never able to figure out how to save unix time to the DB.

So you could stick with the INT field and use jQuery to convert your unix time to what ever time you need. The big downside is that if you will not be able to sort or filter by a certain month or year.

The better solution is to  use Date field, but transform your Unix time stamp to some format accepted by the Date field. By using PHP, with hook_node_presave or using jQuery.

In conclusion, use a date field.


How to create a Size field on Commerce product content fields? I am new to Drupal Commerce and I have set up a store. But the problem is that adding variations for each product is a pain, especially when the product has more than 5 colors and 4 sizes.

What I want to do is to have a size Field in Content type instead of product type's fields so that I add the sizes only once (like choosing the categories or collection).

And then customers can select a radio button or so to be able to add the item to the Shopping Cart.

How can I make it work or is there another solution for it?

I'd go for another solution/approach, as detailed below ...

Commerce Bulk Product Creation

You may want to use the Commerce Bulk Product Creation module. Excerpt from its project page:

  ... facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.

Attention: this module doesn't have an official release yet (only an RC6), though with over 1.200 reported installs, it seems it is pretty stable / trustworthy.

Commerce Backoffice

Another option is to use the Commerce Backoffice module, e.g. because of the auto creation of product display nodes. It provides the backoffice functionality present in Commerce Kickstart (V2), and contains these sub-modules:

Commerce Backoffice Product (commerce_backoffice_product).
Commerce Backoffice Order (commerce_backoffice_order).
Commerce Backoffice Content (commerce_backoffice_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular (and prevents that you have to install the entire Commerce Kickstart distribution). And there is a great video introduction about it also.

Note: if you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).


Comment approval permission to non-admin user I have three accounts in my Drupal 6 site:

admin (which is admin)
moderator
moderator2 (which is authenticated role defined)

Now I want to give permission to the moderator2 to approve comments just like I did from admin account by only going to /admin/content/comment. How can I do that?

I take that "moderator2" is a username name used for a user account. In that case, if you want to give to moderator2 the permission to administer comments, then you have to associate the user account with a role you only give to those users you want to be able to administer comments, then you visit the page on admin/user/permissions, and select "administer comments" for that role.

In this case, I called the role "comments moderator" but I could have chosen another name.

If "moderator2" is a role name, then on the page at admin/user/permissions you see something similar to what shown in the following screenshot.

The permission is the same as before.

P.S. The only permission for which you are interested is "administer comments." The other permissions don't influence that one, and users with a specific role would be able to approve comments, even without to have (for example) the permission to access comments.
The only permission associated with the page at admin/content/comment is "administer comments."

  $items['admin/content/comment'] = array(
    'title' => 'Comments',
    'description' => 'List and edit site comments and the comment moderation queue.',
    'page callback' => 'comment_admin',
    'access arguments' => array('administer comments'),
    'file' => 'comment.admin.inc',
  );


How to pass taxonomy reference field data into a views reference contextual filter arguement with PHP code? My content type has a taxonomy reference and a view reference field. I currently want to pass the Term ID as an argument into my referenced View via a Contextual filter Taxonomy Term. If someone can provide me with an example of how to write the PHP code in the contextual section of my view that would be great.

As the help text puts it, you just need to return the value. Of course, your actual question might be to access the term id but you have not specified that.

For example, if you want to show the view as a block on a regular node page, and the node contains the tid, you would use code like this:

// Lets assume that this view will always be shown on a node page.
$node = arg(1);
$tid = $node->field_term_reference[0][LANGUAGE_NONE]['value'];
return $tid;

This code could be improved a lot but it gives the basic idea.

As a side note, if your scenario is as per above, then consider using Panels and pass in the term id using contextual arguments.

Side note 2: Your screenshot shows filter dialog for Term Name whereas your question asks for term ID. I have given the example for the latter. I hope it helps get you started.


How can I programmatically alter Webform "To Email Address"? I want to change email addresses based on postal codes entered by users.
My code looks like below.
function my_webform_tracker_webform_submission_render_alter(&$renderable) {
  $node_id = (int)$renderable['#node']->nid;
  if ($node_id == 257) {
    $postal_code = (int)$renderable['#submission']->data[5][0];
    if($postal_code >= 14000 && $postal_code <= 14990) {
      $renderable['#email'][email] = "thisemailid@mydomain.com";
      $renderable['#node']->webform['emails'][1]['email'] = "thisemailid@mydomain.com";
      $renderable['#node']->webform['emails'][2]['email'] = "thisemailid@mydomain.com";
      //print "<pre>"; print_r($renderable); exit;
    }
  }
}

I tried a lot but the email id seems to be not changed. Please help me figure this out.

I think a more apt place to alter the destination email would be hook_mail_alter() where Drupal lets you alter an email before sending it out. The webform module includes all the submission data in the $message['params']['submission'] object.

You can do something like this in your module:

/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {

  //Catch Webform submissions when we have a valid postal code
  if($message['id'] == 'webform_submission') {
    $postal_code_component = 5;
    if(isset($message['params']['submission']->data[$postal_code_component][0])) {
      $postal_code = (int) $message['params']['submission']->data[$postal_code_component][0];

      //Find right addressee to switch to
      if(0 <= $postal_code && $postal_code <= 13999 ) {
        $message['to'] = 'addressee.1@example.com';
      } elseif(14000 <= $postal_code && $postal_code <= 14990) { //Etc...
        $message['to'] = 'addressee.2@example.com';
      } else { //Catchall
        $message['to'] = 'addressee.3@example.com';
      }
    }
  }
}


this hook_uninstall isn't deleting fields in my module! I've trying to make a simple module that creates a node-type and adds a few custom fields to it with the Field API.

Here is my module's .install

Here is my module's .module

The module installs just fine. After changing some things in my hook_install_fields, I disabled the module and uninstalled. When I try to re-enable the module, drush prompts me that one of the fields already exists and is active. My problem is that hook_uninstall doesn't seem to be deleting the fields from the database. If I manually delete the field tables from the database, I'm able to re-enable the module without error.

Can anyone point me in the right direction on this?

It looks like your uninstall hook is incorrectly named and not invoked.

Current (line 137):

function _customer_testimony_uninstall() {

Try change it to:

function customer_testimony_uninstall() {

(No underscore in the beginning)


Add (create) content access control with Reference from URL I have created a node photo gallery. The display of the images is provided by an EVA view.
Two content types were created: One photo gallery and one image upload node. To the image node were added an image field (for uploads) and one node reference from URL field that references back to the photo gallery. The result being that when someone is viewing the gallery, there is a visible link to add an image. Clicking the link brings up the image upload widget. The user is returned to the gallery after uploading and saving the image. That works well.

All authenticated users have a photo gallery, and they can all visit the galleries belonging to others. But as it stands now, all can see the add image links on all galleries and use it to upload images to someone else's account. The reason for this being that the link is not part of the view but part of the content type (even when the view is deleted, the link still shows.) So the contextual filters in the view do not work in this case.

The link to the referenced node can be disabled in the Reference from URL field settings and could most likely be replaced by a direct link to the image upload node. But this does not prevent a smart user to upload an image to someone else's account directly from the URL.

Is there a way to implement a variety of access controls on the creation of content? All the access control modules I have seen use roles and/or view/edit/delete permission only. Core allows control of node creation but on a role basis only. The ideal would be a filter like in a view that only allows the author of the gallery to add new pictures but unfortunately the Reference from URL link is not part of a view.

Any pointer on how to solve this riddle?

Thanks. :)

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

This means that you can set the Enter own value for the add image field for the authenticated user only.

The image below shows the settings screen in the module for a field named Nationality.


Members in organic group module I am using OG module for creating a group. Based on the group we made the functionality of adding a member, discussion based on the created group. I have a link with subscribing a member for my created group. I have doubt with how to show the added member in the front end group list. Please suggest me some ideas.

Thank you,
Sathish

I think for that purpose, if I understood well, you need to use Views module with a user view you will be able to do create list or whatever you want.


Views - Conditionally rewrite title link attribute based on field empty value I have a Resource content type that has a Title, Link or File Attachment.  The first is required, the latter two are optional.  The goal is for the administrator to create a new piece of content and link to either an internal (or external) page OR a PDF/Word file.

What I would like is have the Title be a link to either the page link or file location based on whichever is empty.

Right now, in the view, I have Title, Link and File Attachment fields exposed but hidden.  The Title field has Rewrite Output enabled, but how do I set it to link to either a web page or file path based on the empty value for the field?

Inside Rewrite Output, I can add either [file_link] or [file_attachment], but this is not conditional.

From what I understand, either the "Link" OR the "File Attachment" fields will be filled in, but never both. If that is correct the solution is pretty simple.

You need to "Exclude from view" the title field.

Then, you need to Rewrite both the File Attachment and Link fields via the "Rewrite the output of this field" and put the [title] (or wahtever the field name is) in the rewrite field.

Then also for each of those 2 fields, check the "Output as link" and put the link field into the link path for the link, and put the file attachment field into the link path for the file attachment.

Now you only need to open the "No Results Behavior" fieldset for each of those fields and check "Hide if Empty" and "Hide rewriting if empty".

Now either one or the other will be output with the title as a link to either the page or the file attachment depending on what you filled in on the node edit screen.


Drupal 8: Template suggestion for form-element in a views exposed filter is not working In Drupal 8 I am trying to add in a suggestion via hook_theme_suggestions_alter() like so:

function ua_sc_theme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  print '<!-- hook: ' . $hook . '-->';
  if (in_array($hook, ['input', 'form_element']) && $variables['element']['#attributes']['id'] == 'edit-keys') {
    $suggestions[] = $hook . '__custom';
  }
}

...and then I give my template a name of form-element__custom.html.twig and put it in my theme it doesn't get used an instead the default form-element.html.twig template is used. Any thoughts on what is going on?

Ok, looks like I was too tired. The problem was that the template should be called form-element--custom.html.twig.

Notice the '--' (double dash) instead of the __ (double underscore).

I also ended up using the more specific hook alter:

hook_theme_suggestions_HOOK_alter

...where HOOK for me was form_element.


How to show different view templates for different taxonomy terms? I'm using Drupal 7, and I had a vocabulary "Destinations". Under this vocabulary, I had terms with 2 levels. For example:

ASEAN
-- Brunei
-- Indonesia
-- Laos
EUROPE
-- Spain
-- Greence
-- Portugal

For all 1st level taxonomy terms of this vocabulary (ASEAN, EUROPE), I want to display them as a view, with child taxonomy. Eg:

ASEAN
-- Brunei  (term name & description)
-- Indonesia  (term name & description)
-- Laos (term name & description)
EUROPE
-- Spain  (term name & description)
-- Greence  (term name & description)
-- Portugal (term name & description)

For all 2nd level taxonomy terms, I want to display nodes which have the term. Eg:

Brunei
-- Package 1
-- Package 2
Spain
-- Package 3
-- Package 4

Is there any way I can configure the views to display result as above?
It might have something to do with contextual filter, but I don't know how to configure the parameters.

Any idea on how to achieve this?

in child tpl of views taxonomy term check the parent of tid. if parent value is 0 then show data like "Brunei (term name & description)"
And if parent not 0 then show like "Package 1"


Contextual filter by node reference ID Since good 10 years I work with Views in Drupal. Seems I am just to stupid to get it :)
I tried really every combination but I am not able to put out a working block view with articles, which are referenced to the current node.

We have two node types:

- Articles
  -  field (relationship to product node)
- Products

Some articles have a relationship (node reference field) to products. When on the node page the view blog should output every 'article', that has a relationship to the current node (product).

I tried to add a contextual filter (node id from url) and a relationship (field_node_reference).
The contextual filter uses then this relationship. However, I know this is not enough.

Results are 0
Which steps are involved? What have I forgotten?

Thanks

Try first with a hardcoded node id. Once that is working, check if the node id in URL is working.


How to cache custom controller markup for logged-in users? How do we set up a controller so the rendered output is cached?

Blocks are cached for logged in users by default, and the build function doesn't even run once the block is cached for logged in users.

I have some custom controllers for landing pages where I would like to cache the output for logged-in users.

I guess I could put everything within those controllers in a block or in several blocks, but is there a relatively simple way to make a controller behave like a block and not even run the build function once it is rendered for a logged in user?

One thing that you can do is the same as the entity view builder is doing, use a #pre_render callback.

If you look at \Drupal\Core\Entity\EntityViewBuilder::viewMultiple(), you can see it doesn't really do anything except prepare the render array and add a #pre_render callback to the whole thing.

The reason for that is that the pre_render callback will only be called on a cache miss. So you return your array with the cache keys/tags/contexts/max-age, the renderer service will attempt to load from the render cache. On a cache hit, it will return the previously cached HTML, on a miss, it will call the pre_render callback and you can do the things you want to do there.


Programmatically submit user reset password form I have a register form that I am able to submit programmatically without any problems.

However when I try to do the same with the user reset password form, it doesn't send me any emails, nor does it do any validation.

Here's the code I'm using:

$form_state = array();
$form_state['values']['name'] = $_POST['username'];
$form_state['values']['submit'] = t('E-mail me new password');

drupal_form_submit('user_pass_form', $form_state);

Note: I've tried using user_pass instead of user_pass_form.

What am I doing wrong?

An alternative approach is this:

global $language;
$account = user_load_by_name($username);
if ($account) {
// Mail one time login URL and instructions using current language.
$mail = _user_mail_notify('password_reset', $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
  }
}

Essentially all you need is:

_user_mail_notify('password_reset', $account, $language);

More info: user_pass_submit


How to create display page depending on role? I have a role of shopkeeper who is able to update the product info. But I want to create a different page for specific role of user. How to do this

Try Front Page Module
Features

The Front Page module allows for customised home pages dependant on role. The pages can be of the following types:

Alias (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
Redirect - Allows you to redirect users to a local or remote URL.
Themed - Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
Full - Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

Hope this will help you..


Can't open these tabs in my Browser I'm working with my college on a drupal website. However, we're both logged in as Admin, but I can't open these tabs.

He says he has no problem with it and told me it could be a Java problem. I reinstalled Java and checked in mutiple browsers, but I still can't open them. Do you guys have any clue why?
I run on windows 8.1, I have the latest Java and Flash installed.
Thanks in advance.

As Clive pointed out,

  You have javascript errors, the most common cause of that in the admin
  theme is using the jQuery Update module with its default settings. If
  you do have that module installed, just go to its config page, and
  select the default Drupal jQuery for the admin theme

The Jquery Update Module cause the problem. I configured the module and set my Jquery version to 1.10. This solved my problem


Add a class to panel page body element How do I add a class to a panel page's body element without having to add it manually in the variant configuration section?  I want all panel pages to have a body element with the class 'panel-page'.  Is there some kind of hook like hook_panel_page()?

You can use menu_get_item() to inspect what generated the page and add a class to the body element in template_preprocess_html(). I saw the code first in the Zen theme, where they also add a class if the page was generated by Views. Link to Zen template.php

    function MYTHEME_preprocess_html(&$variables, $hook) {
      // Store the menu item.
      $variables['menu_item'] = menu_get_item();
      if ($variables['menu_item']) {
        switch ($variables['menu_item']['page_callback']) {
          case 'page_manager_blog':
          case 'page_manager_blog_user':
          case 'page_manager_contact_site':
          case 'page_manager_contact_user':
          case 'page_manager_node_add':
          case 'page_manager_node_edit':
          case 'page_manager_node_view_page':
          case 'page_manager_page_execute':
          case 'page_manager_poll':
          case 'page_manager_search_page':
          case 'page_manager_term_view_page':
          case 'page_manager_user_edit_page':
          case 'page_manager_user_view_page':
            // Is this a Panels page?
            $variables['classes_array'][] = 'page-panels';
            break;
        }
      }
    }


Conditional display of CCK field for certain profiles values I have created a content type with CCK on Drupal 7, and I would like to display only a few fields according to certain values in their profile2 type.

Concretely, I have a profile2 field to specify if the member is VAT registered or not. When the members are submitting their invoices, I want to display specific fields if they are VAT registered.

for this you have to create a field on your content type called vat registered or not. Autofill that field from profile 2 field for the specific users. Then use conditional module. If that field is filled by default show some fields otherwise do not show that fields.


What is the difference between the various log messaging severity levels? There are several types of log messaging severity levels - emergency, critical, error, alert, info, notice, warning, debug. What does each level mean? Example, emergency and critical sound similar, what's the difference? Also, info and notice sound similar.

The levels are mostly arbitrary below alert, and just represent a general priority of "badness".

In theory, a minimum log level could be set up in core, so that you could enable logging on a live site, but only have certain levels logged (say, emergency, critical, error, and alert) and the rest ignored.  To my knowledge, this hasn't been implemented (I would love to be shown wrong about this).

The current usage has more to do with filtering on the recent log messages page (admin/reports/dblog).


Fill filter between (min, max) field programmatically drupal I have created the view. It displays all comments from a certain time period. So I need filter created date and between option, isn't it?

But also I need to get these MIN and MAX options from node: MIN - created node time and MAX - node`s filed "to_date".

So, How can I pass these parameters to view? Is here some solution?

Edit:

Case: I should create contest module(contest for most popular comments).

Process: Admin creates a node of type Contest. There he must specify contest "To date" and add the description. So in order to determine contest winners, I have created view, that must sort all comments by total views and filter by range date(node created and "To date" field) from node on which page view is displaying.
I need to display this view under node: I do it in this way:

$page['content']['winners'] = array('#markup' => views_embed_view('contest_winners_one', 'block'));

But how to change view filter for every view instance?

If the comments starting from the publication of the node are valid, you do not need a start date.  You only need to make sure you load all comments for that single node and an end date.

Since your view lists comments, I suggest you start by adding a contextual filter for the Comment: nid. This limits all the comments to those on that specific node only. For this to work in your use case, you need to update views_embed_view to also send the node id along (all parameters after the second parameter are sent as arguments (contextual filters)):

views_embed_view('contest_winners_one', 'block', $nid);

Now the results are limited to those on this node only, you need to compare the post date. If the To date is formatted properly (Drupal supports multiple date formats and out of my head I do not know the right one, but my guess is that the date needs to be stored as a timestamp), you can do a field comparison.

For this you have to add the fields to compare to the Fields section of the View (if there is no option to add fields, you can force enable in the dialog you get when clicking settings behind Format. These are the Comment: creation date and the Content: To date fields. Display format does not matter and you can select Exclude from display.

Then in the Filter section add the Field comparison filter. Then make sure the comment date is smaller or equal to the to date.

If you fail to get the contextual filter working, you can also use this approach for the content creation date and the comment creation date, but without node filtering, comments would get mixed up if two contests run at the same time.

Additionally you can probably use Rules and the Rules scheduler sub-module to disable comments on the node once the to date is reached. Refer to How do I create a rule that closes comments on node after 30 days? for reference on how to achieve this. If the comments are closed on the correct date, you can safely show all comments as they could only have been created in the defined period. (You wouldn't need any filtering)


How i can use entity_metadata_wrapper for new database entry and update data in Drupal 7 How i can use entity_metadata_wrapper for database entry and update data in Drupal 7

I am using below code to save entry in database but not finding logic to update existing entry

    $node = new stdClass();
    $node->type = "event";
    $node->uid = $user_id;
    $entity_wrapper = entity_metadata_wrapper('node',$node);
    $entity_wrapper->title->set($row->title);
    $entity_wrapper->body->set($row->description);
    $entity_wrapper->status->set(0);
    $entity_wrapper->promote->set(0);
    $entity_wrapper->comment->set(0);
    $entity_wrapper->field_eventbrite->set($row->eid);
    $entity_wrapper->field_venue->set($row->name);
    $entity_wrapper->field_eventbrite_city->set($row->city);
    $entity_wrapper->field_privacy->set($row->privacy);
    $entity_wrapper->field_repeats->set($row->repeats);
    $entity_wrapper->field_date_period->set(array(
        'value' => str_replace(' ', 'T',$row->start_date),
        'value2' => str_replace(' ', 'T', $row->end_date),
    ));
    $entity_wrapper->field_eventbrite_url->set(array(
        'url' => $row->url,
    ));
    $entity_wrapper->save();

Please help. Please let me know if require more information is needed.Thanks..

Its simple

// $nid - nid of node you want to udate
$node = node_load($nid);
$entity_wrapper = entity_metadata_wrapper('node',$node);
...
$entity_wrapper->field_eventbrite->set($row->eid);
$entity_wrapper->field_venue->set($row->name);
$entity_wrapper->save();


Dragboxes in a page (Dashboard kind of display which is clickable) I'm creating a new site and is fairly new to Drupal.
I had some research into sites and liked "http://churchofengland.org/" front page.

They have aligned the front-page with dragboxes.
How can I do similar in Drupal?

I would check into jQuery UI/Drag & Drop.
http://jqueryui.com/demos/

After you get the hang of this, create a template file for your homepage.
Create blocks with different content and render them in your homepage template file.
Apply the drag and drop interface to the blocks you rendered on your homepage.

This is just a quick look on your question, but it should get you in the right direction.


Custom PHP Unit test trait for a custom module cannot be found I have created a new Trait for testing my custom module and placed it in my_module/tests/src/Traits with the namespace Drupal\Test\my_module\Traits, the same as core modules do.
When I try to use this in my PHP Unit kernel test I just get the following error:
Fatal error: Trait 'Drupal\Test\my_module\Traits\CustomTrait' not found

Is there something special that needs to be included to allow custom traits in testing?

The namespace should Drupal\Tests\my_module\Traits - notice this is Tests with an s at the end, not Test


GA Virtual pageview on Webform reload: is there an easier way? I can't believe it was so difficult.

I have Webform and Google Analytics installed. I want to track submissions of my webform, but since it's set to reload current page on submission, I must make use of either Virtual Pageviews or Events. I went with the former.

At first I thought it'll be as easy as using hook_webform_submission_insert()1 and invoking GA code via drupal_add_js() from there, but somehow it didn't work: the hook itself was executed, but JS was never added to the page.

Now I reached the bottom of Google and haven't found any help on this specific case (everybody seems to be using separate "thank you" pages). Fast forward a couple hours, dozen approaches and hundreds of pages, I finally arrived at this working code:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  //add custom submit callback
  if ($form_id == 'webform_client_form_[node id here]') {
    $form['#submit'][] = 'mymodule_submit_ga';
  }

  //add GA tracking upon successful submission
  if (isset($_SESSION['mymodule_submission_successful']) &&
      $_SESSION['mymodule_submission_successful'] == TRUE) {
    //reset temporary variable
    unset($_SESSION['mymodule_submission_successful']);
    //build JS
    $script = '(function() {';
    $script .= '_gaq.push(["_trackPageview","[virtual page path here]"]);';
    $script .= '})();';
    //add JS somewhere in the end
    drupal_add_js($script, array("type"=>"inline","group"=>JS_THEME,"weight"=>20));
  }
}

function mymodule_submit_ga($form,&$form_state) {
  //set temporary variable for the code above
  $_SESSION['mymodule_submission_successful'] = TRUE;
}

I'm sharing this in case it helps anybody, but as I'm not a PHP expert, I can't help the feeling that I missed something really simple.

Is there an easier way of doing this?

An easier method (that requires no coding) would be to set the webform's "Redirection location" setting to "Custom URL" and enter 'node/%nid?f=my_webform_success'.

This will post the form to itself and also allow you to add some unique key/value to the URL.

Then within Google Analytics you can set a Goal with the Goal URL set to 'f=my_webform_success' and the Match Type set to "Regular Expression Match".


What is the access record "content_access: all"? This is overriding my taxonomy access module I have had problems with my permissions ever since I last rebuilt my permissions.  (I did this after working on user reference permissions.  This field has no user reference on it)

The taxonomy permissions have the same priority of 0.  In fact all access modules have the priority of zero.  When I go to the page that can be seen even though it should not be seen, it shows the following as granting access to view the page:

I think that I have to give people access to see pages by default and then take it away if taxonomy is assigned.  I had this working before and I don't understand why it stopped working.

What can I do to figure this out? I'm a few hours into the issue and am a bit stumped.

I have the following modules installed regarding permissions:

Content Access
Node access user reference
Taxonomy Access Control

I'm not sure if it is relevant or not but I also get a message when I hover over delete that says:

  DNA and Core seem to disagree on this
  item. This is a bug in either one of
  them and should be fixed! Try to look
  at this node as this user and check
  whether there is still disagreement.

The access record you are seeing could be the default access that Drupal uses and that, as far as I can say looking at the code, is only used when no module implements node access rights.
node_access_rebuild() and node_access_acquire_grants() both add that access record if no module implements any node access hook, or no module returns any access record.

function node_access_rebuild($batch_mode = FALSE) {
  db_query("DELETE FROM {node_access}");
  // Only recalculate if the site is using a node_access module.
  if (count(module_implements('node_grants'))) {
    // …
  else {
    // Not using any node_access modules. Add the default grant.
    db_query("INSERT INTO {node_access} VALUES (0, 0, 'all', 1, 0, 0)");
  }

  if (!isset($batch)) {
    drupal_set_message(t('Content permissions have been rebuilt.'));
    node_access_needs_rebuild(FALSE);
    cache_clear_all();
  }
}

I would not suggest to remove that access record from the node access table, otherwise users without specific permissions would not be able to view any node for which a module doesn't have a node access record. In Drupal, it is default to deny the access to a node; in fact, the node module writes in the node access table only the records that allow to access a node.

Update: As you reported that you are using also Content Access, you could be interested in this issue report: Do not hijack the 'all' realm.
The access record you are noticing is probably the record added by Content Access; the short name of the module is content_access, and it is probable the module is using that as grant realm.

  I think that I have to give people access to see pages by default and then take it away if taxonomy is assigned.

As Drupal node access works, the access is denied by default, and it is granted for nodes for which a module grants it; it is exactly the opposite of what you are doing.
Access is still allowed for users who have specific permissions, which in Drupal 6 means users with the administer nodes permission, and is not allowed for users without a specific permission, which in Drupal 6 means users without the access content permission.


How can I assign users different profile pictures upon registration based on gender? My setup: I am on Drupal 7 but not using the default user profile pictures; instead, I have a custom image field, profile_picture, which is attached to the user profile.  When users register, they must select their gender (Male/Female/Prefer not to say).

I would like to assign a different default picture to this profile_picture field based on the value each user selects for gender.  I tried using Set a data value with Rules but I can't figure out how to get these three specific pictures (one for each gender choice) to be options.

If it helps, each user also has a role based on their gender.  I'm not committed to using Rules for this; I will accept any solution that allows me to reliably set the picture based on the value of the field in their profile.  There is no opportunity for users to change their gender so this needs only be set once.

EDIT: Users are later able to replace this with their own custom profile picture, so I need to keep this as an Image field.

A simple approach might be to retheme the gender field itself so that it displays an image based upon its value, eg, instead of displaying male, it displays an image with path sites/default/files/male.png.

In D6, this would mean copying CCK's content-field.tpl.php to your theme directory and then creating content-field-field_gender.tpl.php and jiggering things up in there, eg...

print theme('image', 'sites/default/files/' . $item['view'] . '.png')

...instead of just print $item['view'].

My quick look at D7 here suggests that copying Field's field.tpl.php to field--gender--profile.tpl.php in your theme's directory would be basic starting point there and instead of render()ing $item, doing something similar with its value.

Then, in either version, just make sure you have three images in your files directory called male.png, female.png and unknown.png (or files based upon whatever the values of your gender field are.)

With this approach, you only have three files to deal with instead of a file uploaded and stored for each and every user.  Another side benefit is that they will be easily cached by your users' browsers.

ADDITION:

Based upon new info from comments and other answers, you could do something like this in your user-picture.tpl.php template:

if (!empty($account->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($account->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file->uri));
} else {

  $file_path = 'sites/default/files/' . $account->field_gender[LANGUAGE_NONE][0]['value'] . '.png';
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file_path));

}

where the new stuff is the else .... Pardon my D6ism if sites/default/files is wrong in D7, but basically you just want a path on your system to where you've stuck male.png, female.png and unknown.png and you display them when your profile_picture field is not set.


Why is my Forena report parameter not displaying as a textbox? I created a Forena report using a data block that has one parameter in it, i.e. ":year".

When creating the report, the parameter is detected and added to the report definition. When previewing the report a textbox is shown to let me enter a value and test the report. However after saving the report no text box displays to allow data entry for this parameter. I have checked the settings for the parameter and the "Input Control Type" is set to Textbox. I have tried both Yes and No settings for the "require" setting.

Have a look at the tutorial about Forena report parameters. In the end, they are technically stored (saved) as part of the so called .frx files (which contains all of your report specification details). Here is a (partial) example of such frx-file:
<head id="frxsrc">
  <title>My Report Title</title>
  <frx:parameters>
    <frx:parm id="state" label="State" require="1"
      desc="Select a state from the list."
      data_source="sampledb/states" data_field="" type="select">
      WA
    </frx:parm>
  </frx:parameters>
</head>

So when you're creating ("writing") a report specification (eg using the WYSIWYG report writer), part of what you actually do is saving a special kind of "content" in XHTML format. And that's where the typical "text formats" get involved (just like any kind of content you'd save in Drupal).
However, because of the way Forena does certain things to process these XHTML files (report specifications that Forena massages in reports/charts that match your specifications), it's important that as part of the Forena installation/configuration, you "Prepare a text format to be used by Forena", as explained in the Forena Setup Guide. Here is the crucial part of it:

Regardless as to which Input Format you choose to use with forena, make sure these entries are turned of for the chosen text format :

Limit allowed HTML tags.
Display any HTML as plain text.
Convert line breaks into HTML.
Correct faulty and chopped off HTML.

Anybody who starts using Forena without completing (or knowing about) this crucial configuration step, will typically run in this first-time configuration error ... Same happened to me when I first tried to use Forena some years ago.


How to set manual crop to be compulsory for image? I searched a lot for this problem but not getting any solution.
Any help is very appreciate.

I am using Manual Crop (7.x-1.5) module for cropping the images.
But problem is that I want to set cropping to be compulsory for image. I did not find any option in manual crop setting to set it as required.

I resolved my problem by using hook_node_validate.


How can I alter the title of a node upon save? I want to automatically set the title of nodes with content type ABC to the node ID.  (I want to hide the title field from the form in the UI, and I don't care about titles for this content type.)

For now, I am putting in dummy data (Title and Body) to test this.

At first I tried hook_ENTITY_TYPE_presave():

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'ABC') {
    $entity->setTitle($entity->id());
  }
}

However, this fails because the entity ID has not yet been assigned.  So next I tried hook_ENTITY_TYPE_insert():

/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function mymodule_node_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'ABC') {
    $entity->setTitle($entity->id());
  }
}

This does not result in an error, and I get the status message ABC 23 has been created. However, the node title shows the dummy title I entered, not the node ID.  I tried to fix this by adding $entity->save() to the insert() hook, but this results in a duplicate key error.

How can I change the node title to the node ID upon saving the node for the first time?

I'm not sure why exactly you need the ID, if you don't care about it, wouldn't the date or something like that suffice too?

If you really want the ID, then you need both hooks, because you can't save the node without a title. So you need to set a dummy title in presave and update it again in insert. I'm not sure why saving there didn't work for you, it should, I've done similar things. If you provide the full exception message and stack trace, maybe I can help figure it out. Note that by default the sql content entity storage catches the thrown exception and re-throws a different one and our exception handling can't handle that. You need to print out the original exception stack trace where that happens, with print $e->getTraceAsString().


Any way to convert a page of type X into page of type Y? I inserted a webform on a Basic Page. Now, I decided I should have created a dedicated content type to hold that webform.

So now - is there an easy, non-risky way to "migrate" that page to a new content type without the need to recreate it?

I would like to save myself a couple of moments redefining the webform from scratch, but if the db dependencies are too complex, I would rather take that cost rather than risk screwing up the db.

The Node Convert module allows you to convert individual nodes (it adds a convert tab to the node) and bulk convert. It also handles moving over values in CCK fields from one node type to another.


View of users-profile who had flagged me "subscribe" Using Drupal7 Views 3 and Flag 3, I have been able to display users-profile I have flagged "subscribe" but no luck to display users-profiles that flagged me "subscribe".

Below is what I currently have but the result is still displaying users that the given url has flagged.

I used filter"user ID from url" and for relationships, I used "flags:subscribe(by any user) and checked/unchecked include only flagged content.

Please help.

Create view with type "User"
Add Relationships "Flags: User's flaggings". Choose your flag name and set checkbox "Include only users who have flagged content."
Add Contextual filter "Flags: Entity ID". Choose in the filter settings "Provide default value" -> "User ID from URL"


Field that links to a path/url defined with Tokens, is it possible? I would like to create a few fields in a content type that will link to certain paths defined with Tokens, in my particular case the node author uid. I am using a number of user related modules including Flag, User Relationships, Heartbeat etc which define user specific paths for a number of tasks that users can do (eg. view their flagged content, manage their relationsships etc). Hence my need to use Tokens to define the paths as oppose to just writing the static path myself. The paths would need to be auto generated for each node based on the Tokens, like Pathauto except for field links.

The Link module would be perfect for this, but in my experience, it does not fully support Tokens for the url. Are there any alternatives?

The Link field module DOES support tokens in Drupal 7, both in the link title and the link url field. You might be confused by the fact that the token drop down menu is at the top of the link edit form so it looks like it's not for the url field at the bottom of the page. I was confused by this before myself. Also make sure you have the right input field focused on first before you start clicking to add tokens.