How can I override the page title using contextual filters? I have 3 contextual filters in a view and I use them to override the views title. However, still, the page title (title in the browser tab) are still using the default title of the view. How can I make it use the title provided from the contextual filters?

Most themes output the main page title also into the <title> element in the HTML <head>, usually with the site name appended.

The title you see in the browser tab should be the same as the main title you see on the page, unless your theme does something different (unlikely) or you're using a module that changes the Page title (for example Metatag).

The Override title option is only activated When the filter value IS in the URL or a default is provided. If this option isn't kicking in when it seems it should (either in page title or in the browser tab) then there is no contextual filter or it doesn't validate in some way. This is most likely a problem with your contextual filter configuration.

If you're still having problems please post your Contextuals configuration and what steps you're taking to test it.


How to create a theme that handle articles in different categories? I am creating a theme that has many categories which have two types of handling articles.
For example:

Categories (A,B,C,D,E) will show articles in two column
Categories (F,G) will show articles in only one column
These articles will show in home page in a different manner

I had already created page.tpl.php as well as page--front.tpl.php, I also created a node--article.tpl.php. So am I able to do this with drupal theming? or it is not possible?

You will want to create different content types for each type article.

I would then use Views and Panels to create the page. Create a view for each subset of article types then place each view in your panels page.

You could also do it with a theme by creating what panels creates for you but you would still need a view with a block setting and then places the views block in the correct section of your site and set the block to only show on the home page.

The views+panels is a much cleaner implementation that is theme independent.


How to properly name tpl file for webform-submission-navigation.tpl.php? I am trying to theme the webform-submission-navigation.tpl.php template to add a link for a specific node but am having no success.

If I edit the main webform-submission-navigation.tpl.php file I can achieve what I require but for all of the webform nodes. What I want is to ONLY have this link for 1 specific webform (node 139).

What I have tried to do is name the file as follows, put them in the corresponding themes template folder and the reset cache but have no success:

webform--submission--navigation--139.tpl.php
webform-submission-navigation--node--139.tpl.php

Am I naming my file incorrectly?

Thanks for any help!

Copy webform-submission-navigation.tpl.php to your active theme templates directory
Clear Drupal Cache
Add a php condition in above tpl to render your link only for node 139

Code you need to use in above tpl...

<?php
 if ($node->nid == 139) {
    print l('You Link Title', 'link/path');
 }
?>


Are there any naming conventions for helper functions in modules? I'm writing a module and I need to create an auxiliary (helper) function, but I don't know which is the best name to my function.

Should I name my function like:

function _MODULE_my_function

or:

function MODULE_my_function()

I usually use _MODULE_my_function() but there is a standard for this?

There is not reference about this in the Drupal Coding Standards or in the Naming your modules, functions, and variables article.

How to name a function is described in Naming Conventions which says:

Functions should be named using lowercase, and words should be separated with an underscore. Functions should in addition have the grouping/module name as a prefix, to avoid name collisions between modules.

That is valid for hooks and other functions implemented from the module.
For functions that are not hooks, you could also prefix them with an underscore, right before the grouping/module name. If you do it, you are saying to the developers of other modules that the function is not supposed to be called from other modules, but it is private for the module defining it.
This is a practice followed from PHP which is also followed from Drupal. For example, theme() had been renamed _theme(), before being removed, to make clear it was a private functions modules should not call. It's described in theme() renamed to _theme() and should not be called directly.

The direct callability of theme() was removed in favor of building render arrays consistently. It has been renamed to _theme() and is for internal use only. Build render arrays instead of using _theme() in your code for the following reasons.
Calling the _theme() function directly raises several issues:

It circumvents caching.
It circumvents defaults of types defined in hook_element_info(), including attached assets
It circumvents the pre_render and post_render stages.
It circumvents Javascript states information.


How do I change the edit form layout for a custom field type I created an Address custom field type, with two text fields (street and city).

When I add a new Address field on a content type, I get this form inside the edit page.

How can I change the layout of the form above?

For example, I would like to add some space between the Street text line and the City label, or display both fields on the same line.

This is the code for the AddressDefaultWidget class.

/**
 * Field type widget implementation.
 *
 * @FieldWidget(
 *   id = "AddressDefaultWidget",
 *   label = @Translation("Address select"),
 *   field_types = {
 *     "Address"
 *   }
 * )
 */
class AddressDefaultWidget extends WidgetBase {

  /**
   * Define the form for the field type.
   */
  public function formElement(
    FieldItemListInterface $items,
    $delta,
    Array $element,
    Array &$form,
    FormStateInterface $formState
  ) {

    // Street

    $element['street'] = [
      '#type' => 'textfield',
      '#title' => t('Street'),
      '#default_value' => isset($items[$delta]->street) ?
          $items[$delta]->street : null,
      '#empty_value' => '',
      '#placeholder' => t('Street'),
    ];

    // City

    $element['city'] = [
      '#title' => t('City'),
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->city) ?
          $items[$delta]->city : null,
      '#empty_value' => '',
      '#placeholder' => t('City'),
    ];

    return $element;
  }

}

This is off the top of my head, so there might be a few kinks.
The way I would do it would be to:

Add a new class to each of the form elements that your module produces
Create some CSS to pad the top/bottom of elements with this class
Tell Drupal to include this CSS file whenever the form elements are on the page

In your Widget file add the following to each element to add an additional class to the form elements.

'#attributes' => [
  'class' => 'address_widget_class',
],

To add CSS styles to a custom module, you will need to create a few files and directories.

module/module.libraries.yml
module/css/style.css

In your CSS file, add the following to add 10 pixels above and below each item.

.address_widget_class {
  margin: 10px 0;
}

Next, you need to tell Drupal that the CSS file exists. In the module.libraries.yml file, add the following code.

style_name:
  version: 1.x
  css:
    component:
      css/style.css: {}

Finally, to include the library when the element is used, add the following to your Widget.

$element['street']['#attached']['library'][] = 'module/style_name';


How to add title attribute to views trimmed title field? The title field of a view is trimmed to 40 characters, and the Title field is linked to it's content. Since the Title field text is trimmed I need to add title attribute to the <a> tag of the Title field and the content of the title attribute must be the non-trimmed version of the Title field. So on mouseover event it should show the non-trimmed Title field text. How do I can do this?

I tried this

 function THEME_preprocess_link(&$vars) {
    // If title set and not empty dont do anything
    if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
        return;
    }

    // Use the link text as the title
    $vars['options']['attributes']['title'] = strip_tags($vars['text']);
 }

But it shows the trimmed version as the title attribute.

you can accomplish this by overriding the field tpl file for the field and view:

assuming a View called 'title_test', and a field named 'title'
under Advanced, Theme, it gives the following option for the field tpl file: views-view-field--title-test--title.tpl.php
copy the modules/views/theme/views-view-field.tpl.php to your themes template folder, and rename it to views-view-field--title-test--title.tpl.php
replace the existing $output code with:

<?php
    $field_output = l($field->last_render_text, $field->options['alter']['path'], array('attributes' => array('title' => $field->original_value)));
    print $field_output;
?>

clear the cache

BE AWARE that this is overriding the default output by manually creating the link, so any special classes, or formatting included in the View must be added to this or you get unexpected behaviour (like missing classes, or field styling, etc). All of the information is available in the $field variable, you just need to extract it, for which Devel and dpm($field); will prove invaluable:

  Devel Helper functions for Drupal developers and inquisitive admins.
  This module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries). Also a dprint_r($array) function is
  provided, which pretty prints arrays. Useful during development.
  Similarly, a ddebug_backtrace() is offerred.


notify user account creation? I can't seem to find documentation for notifying a user via email after their account has been created by a script.

$user = \Drupal\user\Entity\User::create();

$user->setPassword('xxx');
$user->enforceIsNew();
$user->setEmail('xxx+'.time().'@gmail.com');
$user->setUsername('xxx'.time());

$user->set('init', 'email');
$user->set('langcode', $language);
$user->set('preferred_langcode', $language);
$user->set('preferred_admin_langcode', $language);
$user->activate();

//$user->notify()? something?

$result = $user->save();

You can find the configuration on admin in the /admin/config/people/accounts but if you want to notify the user programmatically without taking care of what is the config you can use _user_mail_notify function.

_user_mail_notify documentation


Changing label of views exposed date filter select list Trying to change the label of a views exposed date filter based on Year granularity which is a select list. I have given date range to the filter thus it does not generate the "#options" array.

It creates a dropdown with year values and a "-Year" to display all values.

I want to rename this "-Year" label. Could not find any options within the view to change this label. So is there any hook or alter that can be used here ?

Yes i am using Better exposed filter and trying to use Date filter based on Content Post Date. After applying BEF i get a select list to the exposed date filter. I need to change the "-Year" label inside this dropdown. tried using hook_form_alter but not able to search this label and change it.

Attached a screenshot of the settings page for the Date filter. And under BEF settings I selected the Default select list option. Could not find any way to rename the "-Year" label.

Looks like this is something we have already on drupal issue-queue as https://www.drupal.org/node/2296607.

I was expecting the options to be alterable by any hook, unfortunately could not find any.

I explored the code in date module, and found the elements are processed by a function as date_parts_element, under which it appending '-' before the label.

Now, while the following will fix your issue but I would nor recommend it to you until it is approved by community. The hack is

In your date_api_elements.inc file(date/date_api) inside function date_parts_element add this line drupal_alter('date_process_element', $sub_element); in the bottom just before return $element; so it looks as

    .....
    if ($element['#date_label_position'] == 'within') {
      $sub_element['ampm']['#options'] = array('' => '-' . $label) + $sub_element['ampm']['#options'];
    }
  }
  drupal_alter('date_process_element', $sub_element);
  return $sub_element;
}

This will allow any custom module to alter the elements of date filter. Now in your custom module let's say named as my_module implement the hook we have added as following

/**
  * Implements hook_date_process_element_alter.
 */
function my_module_views_date_process_element_alter(&$element) {
  foreach($element['year']['#options'] as $key=>$value) {
    if($value == '-Year') {
        $element['year']['#options'][$key] = 'Year';// Or whatever you like to give.
    }
  }
}

I will be adding the same suggestion on drupal issue page.

Update

Indeed no patch required, date module provides the hooks out of the box, got to know from update mentioned issue feeds, didn't try the cpde myself but looks promising

function MYMODULE_date_select_process_alter(&$element, &$form_state, $context) {
  // Tweak the -Year filter to remove the -
  if (empty($element['year'])) return;
  foreach ($element['year']['#options'] as $key => $value) {
    if ($value == '-Year') {
      $element['year']['#options'][$key] = 'Select Year';
      break;
    }
  }
}


How can I inject relevant/filtered ads every 5th result in a view? I have a view that displays filtered results of Business Offers and Events as "cards". Now my boss wants to inject relevant custom ads into the results based on the user selected filters (basically, by city/region and business type)...
So, I created another custom content type called "Ads" with fields for multiple images (different sized ads), a click-through url, some tracking details, the type of business the ad is for (like Restaurant, or Venue, etc), and the "market location" (city/region) that the ad would be relevant to display in.
In the twig template file for this view, here are the relevant lines of code that basically inject an Ad placeholder every 5th row:
{% for row in rows %}
  {% if loop.index|trim|last == '5' or loop.index|trim|last == '0' %}

AD

ADVERTISEMENT

    {{- row.content -}}
  {% else %}
    {{- row.content -}}
  {% endif %}
  {#
 #}
{% endfor %}

And here's what that looks like:

My question is...what's the best way to for me to grab as many unique Ads as possible that are filtered by user selected filters (location and/or business type) of the main offers view...and how can I inject these ads like I have in this twig template?
Some approaches I thought of:

Have the view's content filter simply get two content types: The original offers...AND the ads. Problem: I don't know how to control the order of these results such that they will render 5 offers, 1 ad, 5 offers, 1 ad etc...
Possibly create another view just for the Ads and somehow render only one result of this view for every 5th row of the main view Problem: I don't know how to access and render this data via the twig template, or how to pass the filter values of the main view to the view for the ads via the twig template.
Perhaps I could create a attachment view for the ads with filter values inherited from the main view, initially hide all the ads from view via css, and then use Javascript to move the ad card nodes in between the offer cards every 5th card and then set their css to display again. Problem: My page is already rife with Javascript trickery...and this will be yet another computational expense that will slow down client side responsiveness...

OR...is there a much better approach that I'm just ignorant of (which is very likely, as I only just started using Drupal 8+ this summer)?
Thanks in advance for your help.

NOTE: I realize there are several questions similar to this one, but my question is slightly unique because I'd like to use a few of the user selectable filter parameters of the main view to filter the ads that I'd like to display/inject every 5th row so they are targeted ads

What you could do is

Create view only for ads:
Create preprocess function in your custom theme/module that is loaded before the template.
In this preprocess function call your view programmatically with the filters from the current page.
In Drupal 8 you can set filter programmatically like that:

ViewExecutable::setHandler($display_id, $type, $id, $item);

Order the results in the way you want and store them in an array variable that you can access from the twig.

Hopefully that helps.


How to calculate the average ratings for the post when the user submits 3 field ratings? I need to implement ratings in my site. I have user five star rating and voting API module, I created a content_type with "beach", and created some field in the manage field settings, name, id, etc. And also I configured the five star module with tags like location ratings, beachratings, facilites ratings and overall (average ratings) ratings. I display all the rating stars in the page by using the code.

$bid=explode("/",$_GET['q']);
$node = node_load($bid['1']);// we get the node id here//
$fivestar = field_view_field('node', $node, 'field_overall_ratings');
echo render($fivestar);
$beachrating=field_view_field('node', $node, 'field_beaches_ratings');
echo render($beachrating);
$locationrating=field_view_field('node', $node, 'field_location_ratings');
echo render($locationrating);
$easyrating=field_view_field('node', $node, 'field_easy_to_get');
echo render($easyrating);

When I submit the ratings, they are stored in the database but the average is not updating.
But I need to calculate the overall ratings when the user votes for the three section. Can anyone help me how can we implement this in my site?

Use fivestar_get_votes to get individual widgets average and get average of them to have average rating of the entire node.


How to make users get points when using Rate module to rate content? I'm using the Rate module to allow the visitors to rate content. I need the author of the contents get point based in the votes provided for the rate module.

There are plenty of modules to allow the author to get points but I'm looking for one which works fine with the Rate module.

You can try User Points module.

  This module provides an API for users to gain or lose points for
  performing certain actions on your site.


How to grant user points to the product creator after the product is sold? I would like to grant user points to a product owner in amount of 70% of product price after product is sold.
I have a rule and part of component

Rule

Events:
Completing the checkout process

Actions:
Loop (commerce-order:commerce-line-items)

Rules Component

Conditions:
Entity has field (Entity: commerce-line-item, Field: commerce_product)

In action I can not put the value for field POINTS and I'm not sure about the user. Now I have: commerce-line-item:commerce-product:creator

Actions:
Grant points to a user:

What should I do more for my purpose?
I have Drupal 7 installed.

It is complicated rule.

I can say that you need in rule or maybe in Rule component (I'm not sure) U need also add:

"Calculate a value" action to calculate the points which should be added to user balance.
commerce-price:amount * 0.7
(here will be created some new value. EX.: point_to_plus
After use "Calculate a value" action one more time to sum current points and new.
current points + point_to_plus = final result.

If you use the user points module first load user points.
Some thing like that.
Af course you need to loop over each line item of the order.
I do know how to do it correct.
Maybe some one will help you!
Good luck!


Disable Elysia Cron task programmatically I have a custom module where I create several cron tasks using HOOK_cronapi.
This is done when the user visits a page and has a form to create those tasks.

I also need that the user can disable those tasks but I can't find anything in the elysia cron documentation on how to disable a cron job.

After it is created I can't disable it programmatically? (I can do it via GUI)

Thanks.

I realize this is pretty old but if you are only concerned with one task and not a whole channel...

elysia_cron_set_job_disabled('mymodule_cron', true);

will disable a cron job. Not surprisingly,

elysia_cron_set_job_disabled('mymodule_cron', false);

enables it again.


How do I find all objects under an object? When I try to print out the possible options of Node::load(10)

I just get null. But I know that there are options as Node::load(10)->field_name->value gives the value of the field.

I have tried using dpm as well as json_encode.

examples:

dpm(Node::load(10)->getFieldDefinitions());
dpm(Node::load(10)->toArray());
json_encode(Node::load(10))

I tried the following command, and it returns the expected output.

drush php-eval 'var_export(\Drupal\node\Entity\Node::load(1));'

The only case where I get NULL as output is when I pass to Node::load() a node ID that doesn't exist.

The fact Node::load() loads the data from the database doesn't matter; in fact, the method still returns an object of the Node class.

Drupal\node\Entity\Node::__set_state(array(
   'in_preview' => NULL,
   'values' =>
  array (
    'vid' =>
    array (
      'x-default' => '1',
    ),
    'langcode' =>
    array (
      'x-default' => 'en',
    ),
    'revision_timestamp' =>
    array (
      'x-default' => '1465363710',
    ),
    'revision_uid' =>
    array (
      'x-default' => '1',
    ),
    'revision_log' =>
    array (
      'x-default' => NULL,
    ),
    'nid' =>
    array (
      'x-default' => '1',
    ),
    'type' =>
    array (
      'x-default' => 'page',
    ),
    'uuid' =>
    array (
      'x-default' => '88E2D589-473B-4FE9-9A5A-F1F768A5E4E8',
    ),
    'isDefaultRevision' =>
    array (
      'x-default' => '1',
    ),
    'title' =>
    array (
      'x-default' => 'Test',
    ),
    'uid' =>
    array (
      'x-default' => '1',
    ),
    'status' =>
    array (
      'x-default' => '1',
    ),
    'created' =>
    array (
      'x-default' => '1465363684',
    ),
    'changed' =>
    array (
      'x-default' => '1465363710',
    ),
    'promote' =>
    array (
      'x-default' => '0',
    ),
    'sticky' =>
    array (
      'x-default' => '0',
    ),
    'revision_translation_affected' =>
    array (
      'x-default' => '1',
    ),
    'default_langcode' =>
    array (
      'x-default' => '1',
    ),
    'body' =>
    array (
      'x-default' =>
      array (
        0 =>
        array (
          'value' => '
Test.

',
          'summary' => '',
          'format' => 'basic_html',
        ),
      ),
    ),
  ),
   'fields' =>
  array (
  ),
   'fieldDefinitions' => NULL,
   'languages' => NULL,
   'langcodeKey' => 'langcode',
   'defaultLangcodeKey' => 'default_langcode',
   'activeLangcode' => 'x-default',
   'defaultLangcode' => 'en',
   'translations' =>
  array (
    'x-default' =>
    array (
      'status' => 1,
    ),
  ),
   'translationInitialize' => false,
   'newRevision' => false,
   'isDefaultRevision' => '1',
   'entityKeys' =>
  array (
    'bundle' => 'page',
    'id' => '1',
    'revision' => '1',
    'uuid' => '88E2D589-473B-4FE9-9A5A-F1F768A5E4E8',
  ),
   'translatableEntityKeys' =>
  array (
    'label' =>
    array (
      'x-default' => 'Test',
    ),
    'langcode' =>
    array (
      'x-default' => 'en',
    ),
    'status' =>
    array (
      'x-default' => '1',
    ),
    'uid' =>
    array (
      'x-default' => '1',
    ),
    'default_langcode' =>
    array (
      'x-default' => '1',
    ),
  ),
   'validated' => false,
   'validationRequired' => false,
   'entityTypeId' => 'node',
   'enforceIsNew' => NULL,
   'typedData' => NULL,
   'cacheContexts' =>
  array (
  ),
   'cacheTags' =>
  array (
  ),
   'cacheMaxAge' => -1,
   '_serviceIds' =>
  array (
  ),
))

Even running drush php-eval 'var_export(\Drupal\node\Entity\Node::load(1)->toArray());' (i.e. using the toArray() method you tried) gave me an output different from NULL. In this case, using a node ID that doesn't exist, you get a Call to a member function toArray() on a non-object error.

array (
  'nid' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'uuid' =>
  array (
    0 =>
    array (
      'value' => '994535DB-7C4E-42F2-94CE-576DA3E9FC0B',
    ),
  ),
  'vid' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'langcode' =>
  array (
    0 =>
    array (
      'value' => 'en',
    ),
  ),
  'type' =>
  array (
    0 =>
    array (
      'target_id' => 'page',
    ),
  ),
  'title' =>
  array (
    0 =>
    array (
      'value' => 'Test',
    ),
  ),
  'uid' =>
  array (
    0 =>
    array (
      'target_id' => '1',
    ),
  ),
  'status' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'created' =>
  array (
    0 =>
    array (
      'value' => '1466285938',
    ),
  ),
  'changed' =>
  array (
    0 =>
    array (
      'value' => '1466285973',
    ),
  ),
  'promote' =>
  array (
    0 =>
    array (
      'value' => '0',
    ),
  ),
  'sticky' =>
  array (
    0 =>
    array (
      'value' => '0',
    ),
  ),
  'revision_timestamp' =>
  array (
    0 =>
    array (
      'value' => '1466285973',
    ),
  ),
  'revision_uid' =>
  array (
    0 =>
    array (
      'target_id' => '1',
    ),
  ),
  'revision_log' =>
  array (
  ),
  'revision_translation_affected' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'default_langcode' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'path' =>
  array (
  ),
  'body' =>
  array (
    0 =>
    array (
      'value' => '
Testing a Drupal function.

',
      'summary' => '',
      'format' => 'basic_html',
    ),
  ),
)

Also, remember to fully qualify the class with its namespace, or add a use \Drupal\node\Entity\Node; line before using the class.

Using drush php-eval 'print json_encode(\Drupal\node\Entity\Node::load(1));' I just get {"in_preview":null} because json_encode() doesn't prints out all the object properties.


New content pane (in view) not showing up for adding to panel Added new content pane as part of my view. Even after saving, and clearing the cache, this pane is not showing up on the available panes list when adding content to Geary type panel/column in Drupal 7. Could this be a configuration issue?

Turns out you have to save prior changes to the panel in question. In the list of panels you'll see a padlock icon and a hover-caption of "you have locked this panel, until you save these changes."

Once you save the panel in question, you'll see new content panes that you've created in a View.


Override View Output for Shopping Cart i am theming a template and currently working shopping cart section. The commerce module provides a view 'Shopping cart block' out of box. I am trying utilize this view, however, i am unable to rewrite the html code from the UI the way i need. So, i am looking to do the same in code using hooks.

function theme_views_pre_render(&$view){
    var_dump('got in pre view');
}

Is this the proper hook? Where is the output markup stored for views? Is there a render array of view output available that i could manipulate before its rendered? Thank you

What worked for me was:
verride the 'shopping cart block' view with custom template
    block--cart-blockNameInClonedView.tpl.php(referece themer-info for
    exact name).

Populate the 'vars' array with total number of items and total amount of a shopping cart in block preprocessor function as following:

function THEME_preprocess_block(&$vars, $hook){
    if ($vars['block']->region == 'cart_in_header') {
            if ($order = commerce_cart_order_load($vars['user']->uid)) {
                $wrapper = entity_metadata_wrapper('commerce_order', $order);
                $bazar_cart = array();
                $bazar_cart['total-qty'] = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());
                $price_raw= commerce_line_items_total($wrapper->commerce_line_items, commerce_product_line_item_types())['amount'];
                $bazar_cart['total-price'] = substr($price_raw,0,-2).'.'.substr($price_raw,-2);

                $vars['bazar_cart'] = $bazar_cart;
            }
      }
}

In custom block template file, the variable '$bazar_cart' is available to plug the values(total items and total amount of cart) as you wish in the html structure


Spam user accounts being created I've made a site where users can create accounts. Lots of spam accounts are being created and I am not sure why. The form at mysite.com/user is mollom CAPTCHA protected, what other paths should I check?

Mollom tests content for spam. But user creation form does not provide any opportunity to provide spam content in the first place. So you have 2 strategies available:

Protect user creation form with more traditional captcha, or one of it's mutations like reCaptcha or little game humanity test.
Protect comments / node forms with Mollom and automatically block users that will fail mollom test there.

Note, above ways are not mutually exclusive.


How to export custom user fields configuration? I'm developing a module and it needs some custom fields on the users table.

If I export the whole config yml zip, the field.field.xxx and field.storage.xxx files for my custom fields are there, but since "users" isn't a custom content type of my module, those fields are not added to the users table during module installation.

How do I add those fields to the users table during module installation?

Modules can add in the config/optional directory any configuration file for fields or  entities. For example, the Forum module uses the config/optional directory to define a new content type and its fields, but it could have as well defined fields for a content type defined from another module. Keep in mind that in this case, the module need to define an explicit dependency from the other in the configuration file for the field.

For an example of using the config/install directory for defining new bundles and its fields, see the config/install directory used from the Standard profile.


Problem with Javascript ad code I am trying to add a Javascript ad code on our Drupal based website through a block and when I do this, the page doesn't display but only ads display. Please see this sample page:
http://circuitdigest.com/forums/circuits-and-projects-help/arduino

I tried adding on different blocks and even added the ad code by directly inserting in the codes but no changes. Other Javascript based ad codes from other ad networks are working fine but only had problem with this one.

Could someone let me know what could be the problem? Here is the ad code.

    <script id="mNCC" language="javascript">
    medianet_width = "600";
    medianet_height = "120";
    medianet_crid = "455208315";
    medianet_versionId = "111299";
    (function() {
    var isSSL = 'https:' == document.location.protocol;
    var mnSrc = (isSSL ? 'https:' : 'http:') + '//contextual.media.net/nmedianet.js?cid=8CUWJ3143' + (isSSL ? '&https=1' : '');
    document.write('<scr' + 'ipt type="text/javascript" id="mNSC" src="' + mnSrc + '"></scr' + 'ipt>');})();
    </script>

If you are working on Drupal 8, create a twig like html.html.twig in your themes templates folder and the put your script in there.

<!DOCTYPE html>
<html{{ html_attributes }}>
<head>
    <head-placeholder token="{{ placeholder_token }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <script id="mNCC" language="javascript">
    medianet_width = "600";
    medianet_height = "120";
    medianet_crid = "455208315";
    medianet_versionId = "111299";
    (function() {
    var isSSL = 'https:' == document.location.protocol;
    var mnSrc = (isSSL ? 'https:' : 'http:') + '//contextual.media.net/nmedianet.js?cid=8CUWJ3143' + (isSSL ? '&https=1' : '');
    document.write('<scr' + 'ipt type="text/javascript" id="mNSC" src="' + mnSrc + '"></scr' + 'ipt>');})();
    </script>

</head>
<body></body>
</html>


{{ drupal_view('view1', 'block_2') }} renders only when cache is cleared I like to output 2 block-views in a template called "block--bar.html.twig", but only when i clear the cache they are printed.

(i installed Twig Tweak 8.x-2.x)

This is the template:

{{ drupal_view('view1', 'block_2') }}

{{ drupal_view('view2', 'block_1') }}

Any help is appreciated.

The answer to the issue is to prevent that block to be cached. So first find the "block--bar.html.twig" and substitute in "add-block-id-name".

 /**
     * Implements hook_preprocess_HOOK() for block.html.twig.
     */
    function YOUR_TEMPLATE_NAME_preprocess_block(&$vars) {
      if($vars['derivative_plugin_id'] == 'add-block-id-name') {
        //-- This stops the block being cache in drupal 8
        $vars['#cache']['max-age'] = 0;

      }


Commerce - Require login only for specific products I'm building a commerce site using drupal commerce. I know how to have anonymous users checkout, I know how to require login before checkout, but I can't figure out how to specify for each product if it requires a login or not...

You could use Rules to enforce login when the product is added to the cart.

e.g

Event: Before/After adding product to cart
Conditions: if user is not logged in (i.e. uid=0) and product match (e.g SKU matches)
Action: Redirect to user/login?destination=cart

Something like that could suffice.


500 error when deleting node with 300,000 comments I have a node which has been spammed and has 300,000 comments. Whenever I try to delete it I get a 500 internal server error.

Deleting all comments via database is not an option because I need to retain a large number of legitimate comments on OTHER nodes. However, this specific node has been spammed and I wish to delete the node and all associated comments, But I can't. I have disabled commenting on the node, but how can I remove these comments? Any ideas?

I think you could delete the comments via database, limiting the deletion to those attached to the involved node.

It might be a simple as this:

DELETE FROM comment
WHERE nid = <the involved node id>

To ensure avoiding any issue (or in case there is something subtle I missed) you can first execute the equivalent SELECT and control its results:

SELECT * FROM comment
WHERE nid = <the involved node id>

And obviously you shouldn't execute the DELETE query without previously getting a backup.

EDIT: as a non-expert, I only proposed what seemed obvious when examining the comment table.
But thanks to @MPD comment, I realize that there are some linked data to also consider.

Regarding fields, after looking at the tables definition I think that an additional DELETE query should be executed first (before deleting comments themselves), something like:

DELETE FROM field_data_comment_body
WHERE entity_type = "comment"
AND entity_id IN (
  SELECT cid
  FROM comment
  WHERE nid = <the involved node id>
)

If unfortunately supplemental comments had been added, a similar query should be executed also for each of them.

Regarding "The node won't be reindexed." and "Node statistics won't be updated.", I'm not expert enough to understand what is involved.
So I hope @MPD will be able to bring its own complementary information.


How to embed all comments and comment form to other website I have two sites.one is Drupal site (example1.com). It has a lot of comments. I want to embed all these comments and comment form to other site (example2.com)[non-Drupal site].

Is it possible?

I think the best solution is to expose the comments as a REST resource on example1.com. You can achieve this with the services module (you will probably have to create a custom resource).

Then on example2.com execute a GET request on the REST resource and display the comments.

Edit: If you want to fetch the comments per node you will have to add a query param to the resource containing the node ID for which you want to fetch the comments.


What does publishing a node accomplish? This is a general question that I couldn't find a satisfactory answer to. Apart from the obvious, making a node visible on the user side versus keeping it in a 'draft' mode, what does publishing a node accomplish? Especially if the node isn't front-end content.

Node status is baked into the node access system fairly deeply in implementations.  What I mean is, it is not directly used by used hook_node_access() and hook_node_grants(), but implementations of these hooks do.  The node access system defines who can see and do what to nodes.  So, if you are using nodes outside of page content (eg, using Rabbit Hole w/ Nodequeue), you can still hide your unpublished content from people who don't need to see it.


Editor being able to create tabs (quicktabs style) inside CKeditor I am trying to provide a way for our content editor to create tabbed content inside the ckeditor, but I am a bit stuck.

Do you guys, have any ideas how to do that ?

What I have already tried ?

Quicktabs module and blocks for specific page...but this method requires too much administrator rights for the editor ( quicktabs and blocks access ).

Oleg

A bit late to the party, but this module will do it for you. I've been using it for a while now.

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


Which Drupal functions can be called in hook_requirements('install')? Generally, implementations of hook_requirements() don't use any Drupal function, when they are invoked during installation. node_requirements() uses some Drupal functions for whatever phase it is invoked.

  $requirements = array();
  // Ensure translations don't break at install time
  $t = get_t();
  // Only show rebuild button if there are either 0, or 2 or more, rows
  // in the {node_access} table, or if there are modules that
  // implement hook_node_grants().
  $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField();
  if ($grant_count != 1 || count(module_implements('node_grants')) > 0) {
    $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count));
  }
  else {
    $value = $t('Disabled');
  }

Which Drupal functions can be called in hook_requirements('install')?

I've made severals tests and I found that depending on modules that you've installed or other things the list of available functions is quite different.

So, IMHO the best way to see which functions you can access at that moment its to list them with the PHP function get_defined_functions. Below it's the small code that I used to list all the functions you can use.

<?php
if ($phase == 'install') {
  $funcs = get_defined_functions();
  file_put_contents('./functions.txt', var_export($funcs['user'], 1));
}


Allow authenticated users to create taxonomy terms Currently I categorize content using nodes as categories, because authenticated users cannot create taxonomy terms.

What would be the way(s) to accomplish a term/add page for authenticated users?

Taxonomy Access Control provides finer control of taxonomy permissions, that sounds like what you need.


Schedule a rule to repeat every week at specific time not working I am sooo close to getting this to work, but cannot figure out why I cannot get my rule to repeat. It's driving me nuts.

I created a component that has an action item to generate send a newsletter using the simplenews module. It works just fine when I execute it manually, but I need this to repeat weekly.

I've read a ton about having it repeat by using the action "Schedule component evaluation" and this makes total sense, but it just isn't firing after the initial rule. Right now I am testing it with +2 minutes so that I can see if it works or not. Eventually I want to have it be +1 week. But if it's not working with 2 minutes it won't work with 1 week.

EDIT: Right now I am running cron manually to check to see if it's working and it's just not.

Make sure you're running cron on demand to force your process to run every those 2 minutes, the way rules scheduler works is to create a hook_cron process that checks the dates:

function rules_scheduler_cron() {
  // Limit adding tasks to 1000 per cron run.
  $result = db_select('rules_scheduler', 'r', array('fetch' => PDO::FETCH_ASSOC))
    ->fields('r')
    ->condition('date', time(), '<=')
    ->range(0, 1000)
    ->execute();

  $queue = DrupalQueue::get('rules_scheduler_tasks');
  foreach ($result as $task) {
    // Add the task to the queue and remove the entry afterwards.
    if ($queue->createItem($task)) {
      db_delete('rules_scheduler')
        ->condition('tid', $task['tid'])
        ->execute();
      $task_created = TRUE;
    }
  }

  if (!empty($task_created)) {
    // hook_exit() is not invoked for cron runs, so register it as shutdown
    // callback for logging the rules log to the watchdog.
    drupal_register_shutdown_function('rules_exit');
    // Clear the log before running tasks via the queue to avoid logging
    // unrelated logs from previous cron-operations.
    RulesLog::logger()->clear();
  }
}


Adding multiple nodes using a single form I want a user to be able to create n nodes of type "Photo Gallery Photo" using a single form.

The node would have the following fields:

name (For the entire upload; only shown once)
phone number (For the entire upload; only shown once)
town (For the entire upload; only shown once)
email (For the entire upload; only shown once)
title (per photo)
description (per photo)
photo (Image, per photo)
galleries (node reference checkboxes, per photo)

Is this possible?

Your question is so specific to your implementation; what you want to do is create a node with some single value fields and multiple images, each image with a title, description and nodereference.

It is the last part of the above that is actually the question: How do you add fields to an image?

The file entity module allows you to add fields to a file, but those fields are not available on the node edit form, you have to go to admin/content/file to add these values.
The Field Collection Module allows you to define a set of fields, so on your node you would define a field collection field which has an image, a caption, nodereferences or whatever. (not too clear...try it out)


Re-use value entered in component in previous webform page on following page in markup I'm creating a webform with multiple pages.  On the first page, I ask for "Name" (textfield), and on the second page, I would like to have a markup component that incorporates the value entered for "Name" on the first page.

I have tried using webform's token system in Webform 3.x and the new token functionality in Webform 4.x, as well as hook_form_alter(), all to no avail.

In regard to the later, in glue.module I defined:

function glue_form_alter(&$form, &$form_state, $form_id) {
  if (preg_match("/webform/i", $form_id)) {
   dsm($form);
  }
}

and the resulting array displays the "name" component value (from page one) as empty on page two.

Would someone please help me?

For one I would be wary of matching $form_id like that.
It means you will be altering any webform you might add in future.
Plus it is possible for other form id's to contain webform, for example webform_node_form, which is the node add/edit form for the webform content type.
There is also webform_components_form, webform_component_edit_form and probably lots of others.

If you really want to regex it I would use webform_client_form_\d+

However if I wanted to do all webforms I would use hook_form_BASE_FORM_ID_alter(), like this:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function hook_form_webform_client_form_alter(&$form, &$form_state, $form_id) {

}

and to do just one webform I would use hook_form_FORM_ID_alter(), like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_webform_client_form_922_alter(&$form, &$form_state) {

}

Now for your actual question, you can accomplish this in form alter:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_webform_client_form_922_alter(&$form, &$form_state) {
  // If we are on the second page.
  if ($form['details']['page_num']['#value'] == 2) {
    // You can get the value via the submitted_tree using the field key.
    $name = $form_state['values']['submitted_tree']['name_field_key'];
    // However I would recommend instead using submitted.
    // The reason is that with fieldsets the submitted_tree gets more complex,
    // and also, users can change the field key (who knows why that's allowed)
    // so that is unreliable. The submitted array uses the webform field cid
    // so it won't change.
    // (1 is the id of my name field)
    $name = $form_state['values']['submitted'][1];

    // There are 2 main ways you can add the markup.
    // 1. If you actually have a webform markup component on the second page
    // and you want to set its value. This means you can control the field via
    // the webform UI.
    // I use check plain because this is data entered by the user and needs to
    // be sanitised. You could also use filter_xss() if the field might
    // contain HTML.
    $form['submitted']['markup_field_key']['#markup'] = '
' . check_plain($name) . '
';
    // 2. If you don't have a webform markup component and just want to add
    // markup in, you can do this, just using regular form API.
    $form['submitted']['my_markup_field'] = array(
      // Defaults to type #markup.
      '#markup' => '
' . check_plain($name) . '
',
      '#weight' => 10,
    );
  }
}


Creating smaller menus from chunks of a bigger menu I have this really big nav menu in Drupal 7. The top-level links go to child pages. Each of these child pages has several pages hierarchically under them.

On these child pages, I want a block that shows links to sibling pages and children of the current page (But not children of sibling pages).

It seems like it should be relatively easy, but I've been beating my head against a wall all afternoon. Any help? Thanks!

What you are describing is the primary feature provided by the Menu block module.


feeds importer tamper double importing image Using feeds import with tamper to split up images at a | our database has thousands of products and only some of them have an image and then some have a second image (a room view of the product) and the images arent tracked in the data.

anyways the build of the url to retrieve the image is: http://domain.tld/imgs/flooring/Manufacturer/IemNumber.jpg|http://domain.tld/imgs/flooring/Manufacturer/IemNumber-room-view.jpg

when importing displays with a second image it works fine along with displays with no images however when importing displays with only one image it puts in two of the same image instead of ignoring the second image that it cant find as I would expect it to

I was having a similar problem using the standard feed tamper modules, so in the end I installed the Feed Tamper PHP module alongside it. Here's some example code I've used to split a string and import multiple values into a field using the Feed Tamper PHP module.

if (is_array($field)) {
  $value = implode($field);
}
else {
  $value = $field;
}

$field = explode('|', $value);

foreach ($field as $key => $value) {
  $field[$key] = trim($value);
}

return $field;


Unable to see URL path setting menu for a user edit page I want to see "URL path setting" tab which appears while editing any content, but can't see it while editing a user. need help or suggestion regarding this.

thanks

Download & install Pathauto module & then check.


Token insert with CKEditor doesn't work I'm using the CKEditor Module in combination with the Token insert (ckeditor) to show a user property in my body.

It looks like this:

But the results shows just the static text instead of the user property. What am I doing wrong?

UPDATE:

I've also tried to add the Token insert button to my editor like this:

But every time I save this and check again it is switched back.

These modules are enabled:

Entity Tokens
Token insert (ckeditor)
Token insert (text)
Token insert UI
Token

UPDATE:

The test gave me a result like this:

I tried to add a random number in my text field but the result just gave me the static text [random:number] instead of a random number...

You need to install the token filter module for the token insert to work.

Download the module.

Configure the tokens you want to use by role or globaly.

and add the filter in the Text Format:

Then you can use the ckeditor plugin to add the token in the Fields that have this Text format, and thats all.

I've just test and it works perfect.


custom HTML in search form ( site/search) I'm trying to customize the html of the search block form.
I know that I can use templates.php to modifiy the fields and customize it but I'm trying here to change the whole html block.
I've tried to use search-form-block.tpl.php, but it didn't work (yes I've cleared cache).

I guess I'm missing something here ...

Any help appreciated thanks !

Ps : I'm using solr in an acquia environment.

You can use hook_form_alter and use render API to alter the html attributes. You can add attributes such as class, id, wrapper tags(prefix and suffix), attaching css and js file to the rendered form this way too. It would be something like this.

function yourMod_form_alter(&$form, &$form_state, $form_id) {
 if(strstr($form['#form_id'], 'search_form')) {
   $form['#attributes'] = array(
    'class'=> array('search-form-custom-class'),
    'id' => array(),
    );
   $form['#attached'] => array(
     'css' => array( drupal_get_path('module', 'yourMod') . '/css/yourMod.css' ),
   );
   $form['#prefix'] = "
";
   $form['#suffix'] ="
";
 }
}

I advise to read more on the render API to see all attributes that you can alter.


how can i remove 'create new account tab ' from login page and show 'access denied' for 'user/register' in drupal  6? i have two roles in my sites and i have created a separate user registration pages for both roles with different urls.Now i want to remove the "create new account" tab in login page and
i want to show "access denied" message for user who try to visit "user/register" page.i am working in Drupal 6.

I removed the 'create new account tab' in theme layer and if user try to access "user/register" means, it shows the default registration page. i want to show access denied message instead showing default registration page. is there any another method or any module for this? how can i implement it?

Under admin/user/settings, change "Public registrations" to "Only site administrators can create new user accounts."


Webservices to create (Register) a new user I am planning to write client apps which connects to Drupal 7. I like to create new users through the app, have come across some literatures but I am not sure if the approach is secure and also whether it considers all possible use-cases.

The first link which I came across is this:
https://www.drupal.org/node/1514312

I was able to configure endpoint and successfully post + create user. However, the problem with above approach is, it is not secure because any client app with the POST URL to create user can successfully register a user in the website.

I then followed this link: https://www.drupal.org/node/1871498 through which I created a OAuth authentication context. Below are the configuration details:

OAuth Context:
Context Title: App Name
Signature Method: HMAC-SHA1

The Service configuration:

Endpoint: create_new_user
Authentication:
OAuth Context -> Context created above
Default required authentication -> Consumer key (2 legged OAuth Authentication)
Resources ->
user -> create (Only create in CRUD Operation)
Action ->
user -> request_new_password & register

And I created a new user and provided the following role:

By enabling 2 legged OAuth authentication I make sure that only my authorized app with the consumer key and secret is able to access my endpoint successfully.

Using the following POST request I am able to create user successfully from the REST client:

Post Request URL: http://ExampleWebsiteBase.com/create_new_user/user/register.json

Post Headers:

OAuth:
OAuth oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_nonce="kXZ3iOtGqD7f350", oauth_timestamp="1450257992", oauth_consumer_key="Lq7r.........", oauth_signature="htvy........"

Content-Type:application/json

Post Body:
{
   "name":"SomeName",
   "pass":"reset123",
   "mail":"SomeName@gmail.com",
   "status":"1",
   "roles":[
      "2"
   ]
}

I would need confirmation from experts that this configuration is secure and acceptable.

Questions:

The user created in this process does not has to verify the email ID. How do I configure the webservice so that the user is not created in backend without verifying the email?
How do I integrate Social login - Facebook, Twitter and Google for instance?

Try using the example reference below which displays the php code using OAUTH library with Services module.

Email verification needs to be done using the rules by adding condition to block user since using oauth it will be activated by default.

You can use the Facebook/Twitter end-point, consumer credentials(key & secret) replaced to Drupal services.

Reference:
http://www.covenantdesign.com/blog/drupal-services-rest-server-and-3-legged-oauth


8 - Views: list pages that are child menu items to the current node I have three nodes:

Node A
Node B
Node C

In the main menu, these nodes are organized with Node B and C as children of Node A's menu item, like so:

Node A

Node B
Node C

When Node A is viewed, I would like to display/list Node B and C in a block under Node A's content.

I would like to do this without using the Book module. I would also like to do this without adding an extra step to the user (i.e. using entity reference on Node A).

Is there a way to do this views? i.e. to create a relationship to the menu structure?

Here's a drawing of what I'm trying to achieve:

Any insight is greatly appreciated.

I hate answering my own question here, but just to save the effort anyone might be going through, here is a module that worked for me:

Views Menu Node Children Filter

Using this module I was able to pass the node ID of the current node and filter the node's children in reference to the menu structure. Works perfectly on 8.4.


How to achieve the use exposure filter of views, head Title Update？ I use the exposed filter on a Drupal 7 website. I want to achieve that when the user clicks on the filter, the head of the title will also output the filtering term.

Any suggestions?

1) Add Taxonomy term: Name as a field

Check Exclude from display
Uncheck Link this field to its taxonomy term page

2) Click on Title: and put [name]


Custom PDF template in Commerce Billy I have installed Commerce Billy module on my website.

Then upon ordering I get this PDF with this layout.

But I want to change the table displayed, because I've created some custom fields in it and I want to display it also in the table.

Any help will be greatly appreciated.

This table is actually the rendered view 'Line items (Commerce Line Item)' which is created in code by Drupal Commerce. So all you have to do is to modify this view to your needs.

To further customize the display of your invoice, you can make a copy of css/pdf.css and themes/commerce_order--commerce_order--pdf.tpl.php located in commerce_billy_pdf folder into your custom theme and experiment.


Creating a file upload field with a translatable title attribute field I have a File field with the title attribute enabled and I'm trying to figure out how to make the title attribute field translatable using entity translations without affecting the actual file field itself. I'd prefer to allow users to upload one file with a title attribute that can be translated.

What I ended up doing was I used hook_i18n_string_info to define a new "Captions" text group, hook_field_widget_form_alter to attach a new process function to the desired upload widgets, and my callback for hook_field_widget_form_alter cloned the title field (into title_fr for me), then also checked to see if #default_value was a string and used i18n_string_translate to update title_fr's default_value.

What I did and wouldn't recommend doing was I put the translation handling in the submit function for my form. In there I constructed my translation "name" using caption:$field_key::$nid::$field_delta and then calling i18n_string_translation_update($name, $french_caption, 'fr', $english_caption).


Duplicating drupal site without login info I'm a new Drupal user.

Someone gave me a backup of their Drupal and .mysql content.  I more or less followed these instructions: http://www.ostraining.com/blog/drupal/drupal-migrate/, except the site already had it's own settings.php, and so the site is now up and running.

The problem that I'm having now is that I can't log into the site to make any edits because I don't have a login.  I tried to create an active user in phpmyadmin with an md5 hash password, and changed the user to an administrator.  However I'm still not successfully logging in, the site says I'm still giving it the incorrect login info.  When I try to recover/reset my password by email I am not receiving any emails.  I am using Windows XP.

Is there any way I will be able to login to edit the site?

One way of solving your issue would be to update super admin (first user) password pragmatically, by creating a temporary php file under Drupal root folder and add the following code to it then access it from a browser.

<?php

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// load super admin user
$account = user_load(1);

// save user password
user_save($account, array('pass' => 'admin'));

echo "Super admin password has been changed";

Make sure to replace admin with desired password


Have an exposed filter on a view be a list of US states I would think this would be a pretty common thing, but I have a job board that I am exposing for users to search on. They can search by city and/or state so I exposed some filters on my view for city and state. Now, of course, plain text boxes work fine out of the box if I want the user to freely type in a state, but I really want it to be a dropdown of states. I see that I can do a "Grouped Filter" which allows me to specify some key|value pairs, but do I REALLY need to enter in all 50 states manually? Is there a way programatically to have the dropdown be a list of states? I also noticed that even if I DO specify a few values to test with like AZ|AZ, CA|CA, NV|NV, when I go to use the exposed filters instead of the URL being something like this:

http://sandbox/job-board?city=&state=AZ

it actually uses:

http://sandbox/job-board?city=&state=1

where there is a "1" instead of "AZ". I would really like to be able to pass "AZ" not a 1 in the URL because if I have other apps posting to the job search page, I don't want to have to map ID's to actual state values, I just want to pass in the state code. What's the best way to go about this?

THANKS

AL|AL
AK|AK
AS|AS
AZ|AZ
AR|AR
CA|CA
CO|CO
CT|CT
DE|DE
DC|DC
FM|FM
FL|FL
GA|GA
GU|GU
HI|HI
ID|ID
IL|IL
IN|IN
IA|IA
KS|KS
KY|KY
LA|LA
ME|ME
MH|MH
MD|MD
MA|MA
MI|MI
MN|MN
MS|MS
MO|MO
MT|MT
NE|NE
NV|NV
NH|NH
NJ|NJ
NM|NM
NY|NY
NC|NC
ND|ND
MP|MP
OH|OH
OK|OK
OR|OR
PW|PW
PA|PA
PR|PR
RI|RI
SC|SC
SD|SD
TN|TN
TX|TX
UT|UT
VT|VT
VI|VI
VA|VA
WA|WA
WV|WV
WI|WI
WY|WY
AE|AE
AA|AA
AP|AP


Need tags to update taxonomy list terms automatically? I'm not sure how this should work but I have a view that spits out taxonomy terms. I would like to create an article and add tags to the article that will update the taxonomy terms. I was also thinking it would make sense to update the path so the terms links to the article. Is this possible or how is this done? I have already created a tags field on my custom data type.

A path is the name for the term or article.  Giving a tag an alias that matches an article (or vice versa) is not creating an override to reroute the display. To link a term to an article, you will want to add a field to the content type (article) that is based upon the vocabulary. You access this through admin/structures/content type/manage fields/add.


How can I programmaticaly submit the user edit form in Drupal 8? I need to create a logout button in my app, and I do not know how to revoke simple_oauth tokens programmatically, but I have noticed if the user saves their profile form (form_id: "user_form") in Drupal, it revokes the user's access token.

So I'm wondering if there is a way to programmatically submit the form so I can do so in a logout endpoint for my app.

That is, unless someone can point me to the specific code that revokes a user's access token when the user edit form is saved, so I can fire that hook  more directly.

Because the oauth2_token table does not reference the associated user (auth_user_id is always zero), I don't know how to look up a token by UID for the purpose of revoking the token.  Thus, even though it seems like a hack, the only thing I can think to do is to try to submit the user edit form programmatically.

UPDATE: I was wrong about "auth_user_id is always zero".  See my answer below.

I was mistaken when I said "auth_user_id" is always zero.  It isn't.  It contains the user's ID, as you would expect.  That makes this task fairly simple.  Here is the function for my logout endpoint:

public function logout($name = NULL) {

    if ($name) {
      $user = user_load_by_name($name);
      if ($user) {
        $uid = $user->id();

        $msg = 'User ' . $name . ' (uid: ' . $uid . ') logged out of app.';
        \Drupal::logger('orb_common')->notice($msg);

        // Not sure if it would be a better practice to set the status to zero, or delete.  In this example I delete the row.
        $query = \Drupal::database()->delete('oauth2_token');
        $query->condition('auth_user_id', $uid);
        $query->execute();
      }
    }

    $response['data'] = [];
    $response['method'] = 'POST';

    return new JsonResponse($response);
  }

In my routing file I have...

orb_common.orb_common_logout:
  path: '/orb_common/logout/{name}'
  defaults:
    _controller: '\Drupal\orb_common\Controller\CommonController::logout'
    _title: 'Logout'
  requirements:
    _permission: 'edit activity entities'

The JsonResponse at the end of my logout function presumably isn't important in this case.  The main thing is to pass a UID or username to Drupal in the URL of the endpoint, and then delete/update the relevant row in the oauth2_token table.  At least, that is working in my app.


How do I insert the node ID into a link field? Building a site with content types Business, Product, and Review. Currently when users click a business name, they are taken to the Full Content view for that Business (e.g. sitename.com/business/[business name] since we are using PathAuto).

Created a custom View called Profile (sitename.com/profile) with a contextual filter that shows a selected Business as a rendered entity followed by two view attachments that show their Products and Customer Reviews.

We can manually type sitename.com/profile/6 into a browser and see a business with the attachments for products and reviews, but we are having trouble getting users there.

Tried adding a new field to Business with a default value and tokens to generate a URL to the business' profile view (e.g. Link with a default value of "/profile/[node:id]"). This field would be hidden on the input form for Business but displayed on the Full Content view.

We have not been able to get this working and do not know a better way to approach the challenge. If it is possible to get the Products and Reviews to display on the Business content page without using the Profile view (e.g. User clicks a Business name and sees their profile with products and reviews underneath), that would also meet the requirement.

Would prefer to do this without custom coding if possible, but acceptable if it is the only or best way. Happy to answer questions for clarification or provide links to the site (still in beta) if it would help.

Going from node/6 page to profile/6 page (which displays products and reviews) there is a simple module that can help with this https://www.drupal.org/project/field_token_value
It will allow you to add a field PROFILE PAGE hidden from the editor and can be configured to have the value of
profile page

after that go to the content type display admin/structure/types/manage/CONTENTTYPE/display to configure where should be displayed
The field will not be available on the edit form and after saving it will hold a link to profile/[nid]
Above module works in both drupal 7 and 8
More involved alternatives
you could use https://www.drupal.org/project/linked_field and https://www.drupal.org/project/field_permissions (drupal 7 & 8)
For drupal 7 projects https://www.drupal.org/project/token_field does the same thing


Deploy to production with git using Acquia like localserver I'm using Acquia to export my local proyect to production proyect but when I did git push just the code was saved, the changes that I did in UI was not saved for example I created a user in local UI but it did not reflect in production UI, do I have to use drush to do that?

You're missing the database. git only handles files.

So export your local database, and import it in production.
For that you could use drush sql-sync, but you need to set it up properly.

You could also export the database to an .sql file via phpMyAdmin or your preferred db-tool. and then in aquia devcloud, you import that .sql file.


Make 'Full HTML' the default text format How do I make Full HTML the default text format for the administrator? Currently it is Filtered HTML.

If I remember it correctly, the order that the text formats appear (depending on the permissions you as a user have on using the text formats) is set on the example.com/admin/config/content/formats page. Just use the cross icon on the left to drag an re-order the various formats. Put the Full HTML on the top to make it the first choice.


Taxonomy Hierarchy URL I have a taxonomy vocabulary with  name "Animals" along with following terms

  Mammals

              Animalia
              Chordata
              Mammalia

                       Bat
                       Bear
                       Fox

I have created a view with contextual filters in which I need to show the hierarchy of the taxonomy terms
For example : URL : base_URL/Mammals/Mammalia/Bat

Taxonomy Implementation that I have made :

Added relationship of taxonomy terms on node
Added relationship of parent term
Added contextual filters for parent term.
Added contextual filters for taxonomy term id with depth.
(Please find the settings of the same in attached screenshot).

But actual results I'm getting is "base_URL/tid" but expected URL result what I need is "base_URL/Mammals/Mammalia/Bat".

Can anyone please help me out with detailed implementation?

I can't see any screenshot.

It seems that your problem is with url and if it is then
go for Path Auto module.

The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias.


how to validate file size in drupal file upload in here file validate extensions are working,but the file size validate is not working,i just need file size only, resolution doesn't matter,i want to restrict max file size to 1MB

 $form['photo']['file'] = array(
'#title' => t('Photo (Max size 2 MB)'),
'#type' => 'managed_file',
'#description' => t('xvxcds'),
'#default_value' => variable_get('photo', ''),
'#upload_location' => 'public://photo_images/',
 '#upload_validators' => array(
'file_validate_size' => array(1024*1280*800),
'file_validate_extensions' => array('gif jpg jpeg'),
// Pass the maximum file size in bytes
), );

You're currently setting the limit to 1024*1280*800 bytes, which is the equivalent of about 1Gb.

Remember, 1kb = 1024b, 1mb = 1024kb, so for a 1mb limit:

'file_validate_size' => array(1024 * 1024),


Create a custom front page for anonymous users I'm trying to create a custom front page for anonymous users, something like page--front-anonymous.tpl.php.

I could use the page--front.tpl.php template file, and check the role there, but I believe it is possible to create a separate template file for the front page when it is visited from anonymous users.

Any advise?

in your THEME_preprocess_page(&$vars) hook you can put something along the lines of...

if ($vars['is_front'] && !$vars['logged_in']) {
   $vars['template_files'][]='page-front-anonymous'; // drupal 6
   $vars['theme_hook_suggestions'][]='page_front_anonymous'; // drupal 7
}

which should work using the is_front and logged_in variables set by the various modules before you get to it.  if you are using a module, and don't want to rely on weight/execution order, you could do it with:

global $user;
if (drupal_is_front_page() && !$user->uid ) {
.....


Views fields as Columns in table I have a content type called Pets, which only has title and description. In Pets there are only 3 data (set by Admin) Cats, Dogs and Mouse. User can select only from these data and cannot add more Pets.

After the Girls register in the site they can hit the checkbox to select the pets they have in their profile.

However, I want to have a Views table where I want to list the Girls' profile like: (that's the table I wanted to make)

Name ------ Age -------- Dogs ---------- Cats ----------- Mouse
Tina ----------- 21 ------------ Yes ---------------- No ----------------- No
Lita ----------- 27 ------------- No ---------------- Yes ----------------- Yes

When I add Pets title in the views it just shows as:

Title
Dogs
Cats
Mouse

but I want to change the fields(dogs, cats, mouse) as Columns and have Yes or No in the rows. I just tried Views Flipped Tables Module but wasn't able to do with it. any suggestions please ?

You could try to use Views aggregation.

Define the relationships of the fields.
Under Advanced > Other enable aggregation
Add fields of the animal nodes and define the grouping as "count" in the field's aggregation settings.
Define no results bahaviour as "No" and rewrite the result as "Yes". Define 0 as "no result". All in the field settings.

Hope that helps!

cheers,
j


Get contents of temporary uploaded file I've uploaded a file in a custom form and I can retrieve the file instance like this:

  $fid = $form_state->getValue('file')[0];
  $file = File::load($fid);

How can I get the contents of the file?

kint(file_get_contents($file->url()));

Returns false. If I visit the link manually, it gets downloaded.

You can't get the file from $form_state->getValue(). You have to upload the file first to the file table as temporary file with file_save_upload(). Then you can load the file content locally from $file->getFileUri().

  public function submitForm(array &$form, FormStateInterface $form_state) {

    $validators = ['file_validate_extensions' => ['txt']];
    if ($file = file_save_upload('file', $validators, FALSE, 0)) {
      $data = file_get_contents($file->getFileUri());
      drupal_set_message($data);
    }

  }


Adding a form to Views Bulk Operation for configurable operations I have a view with a list of nodes that I want to operate with, but I need additional user input for the function. Until now, I have been handing this by having many similar, but slightly different 'Execute arbitrary PHP script' actions. Is there any way to add a sort of form to accept user input other than the nodes to operate on?

Instead of running a PHP script. You would have to create a custom module and a custom Action. The action may be configurable (requiring a Form) and you can check the form for errors before proceeding.

An example template of what would go into your .module file can be seen at ( am not the author):
http://dropbucket.org/node/841

In case that website is taken offline, here is the code sample, which I believe to be self explanitory:

/**
 * Implements hook_action_info().
 */
function custom_action_info() {
  return array(
    'custom_action_callback_name' => array(
      'type' => 'entity', // Can be file, term, user, etc.
      'label' => t('Your label'),
      'configurable' => TRUE, //  Needs config form
      'behavior' => array('view_property'), // Uses view access rights
      'triggers' => array('any'), // Works always
    ),
  );
}

/**
 * Return a form definition so the action can be configured.
 */
function custom_action_callback_name_form($context) {
  // Set default values for form.
  if (!isset($context['recipient'])) {
    $context['recipient'] = '';
  }

  $form['recipient'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipient'),
    '#default_value' => $context['recipient'],
    '#maxlength' => '254',
    '#description' => t('The email address to which the message should be sent OR enter [node:author:mail], [comment:author:mail], etc. if you would like to send an e-mail to the author of the original post.'),
  );

  return $form;
}

/**
 * Validate custom_action_callback_name form submissions.
 */
function custom_vbo_action_send_node_validate($form, $form_state) {
  $form_values = $form_state['values'];
  // Validate the configuration form.
  if (!valid_email_address($form_values['recipient'])) {
    form_set_error('recipient', t('Enter a valid email address.'));
  }
}

/**
 * Process custom_action_callback_name form submissions.
 */
function custom_vbo_action_send_node_submit($form, $form_state) {
  $form_values = $form_state['values'];
  // Process the HTML form to store configuration. The keyed array that
  // we return will be serialized to the database.
  $params = array(
    'recipient' => $form_values['recipient'],
  );
  return $params;
}

/**
 * Add action callback where you perform the action.
 */
function custom_action_callback_name($entity, $context) {
  // Do the magic here.
}

EDIT

If you just want VBO validation rules and no form for your action, look at VBO Validation which supplies easy to use Hooks.


Copy path to variable in array using Kint In D7 using dmp() with Krumo in produced output like this:

Double clicking on a variable value, in this case "foobar" shows the path through the array to that value (the highlighted text in the image above).

Now with D8 it's using Kint not Krumo and produces output like this:

Is there anyway to copy the path to "foobar" using kint?

This is the text that I want: ['example']['#attributes']['class'][0]

It seemed there was no solution so I just copied the search_krumo module and changed it a bit so it works with Drupal 8 and kint and made search_kint.

I've only just done the first push so isn't showing as a download yet; and there is only a development snapshot release, at the moment, but it's something to get started with.

So far, it has worked well with my testing.

EDIT: search_kint now has a full release.


Make Hook in main-menu I created a module containing the following files:

menu_imoveis.info
menu_imoveis.module

The content of menu_imoveis.info is the following.

    name = Menu Imoveis
    description = Adiciona imoveis ao menu.
    package = Imoveis
    core = 7.x
    version = 7.x-dev

    files[] = menu_imoveis.module

**The content of menu_imoveis.module is the following.

function menu_imoveis_menu() {
  $items['node/27'] = array(
    'title' => 'Example Page',
    'menu_name' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

The code I wrote doesn't work.

Taken from this comment, written by zifiniti:

  I was having trouble getting a menu item to display with the following code:

function mymodule_menu() {
  $items['custom-page'] = array(
    'title' => 'Custom Page',
    'menu_name' => 'main-menu',
    'access arguments' => array('access custom pages')
  );

  return $items;
}

  It was continuously denying me access to the specified path in addition to not displaying the item in the menu. I discovered that the reason behind this is if you do not specify a page callback, then the access callback will acquire a value of 0 in the database and thus render that path/menu item inaccessible.

  Working code:

function mymodule_menu() {
  $items['custom-page'] = array(
    'title' => 'Custom Page',
    'menu_name' => 'main-menu',
    'page callback' => 'mymodule_custom_page',
    'access arguments' => array('access custom pages')
  );
}


Unserialize() Error after moving the installation directory I have just added a repository from git to my Eclipse IDE , setup the database with proper imports and dumps, however getting

Error at offset in cache.inc

Any suggestions what went wrong and solution.

After making a back-up of current db,

Try this in phpMyAdmin or mysql console.

TRUNCATE `cache`;
TRUNCATE `cache_block`;
TRUNCATE `cache_bootstrap`;
TRUNCATE `cache_field`;
TRUNCATE `cache_filter`;
TRUNCATE `cache_form`;
TRUNCATE `cache_image`;
TRUNCATE `cache_libraries`;
TRUNCATE `cache_menu`;
TRUNCATE `cache_page`;
TRUNCATE `cache_path`;
TRUNCATE `cache_rules`;
TRUNCATE `cache_token`;
TRUNCATE `cache_views`;
TRUNCATE `cache_views_data`;


Hide authoring information programmatically in a content type How do I programmatically hide the Authored by part in a content type using hooks?

I assume you need to hide the Authored by part basing on some conditions you check at run-time. If you need to hide that only for a content type, for example for the Article content type, then you can change settings in admin/structure/types/manage/article.

If you want to hide that information basing on the user ID of the user who created the node, then you could use the following code.

function mymodule_preprocess_node(&$vars) {
  $node = $vars['node'];

  // Remove that information if the node has been created from the user #1.
  if ($node->uid == 1) {
    $vars['display_submitted'] = FALSE;
    $vars['submitted'] = '';
    $vars['user_picture'] = '';
  }
}

Notice I am setting the same variables set by template_preprocess_node(), which uses the following code.

  // Display post information only on certain node types.
  if (variable_get('node_submitted_' . $node->type, TRUE)) {
    $variables['display_submitted'] = TRUE;
    $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
    $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
  }
  else {
    $variables['display_submitted'] = FALSE;
    $variables['submitted'] = '';
    $variables['user_picture'] = '';
  }

The template files used by Drupal core check $display_submitted before rendering $submitted and $user_picture. Probably Drupal core sets also $variables['submitted'] and $variables['user_picture'] for those template files that render them without checking first $display_submitted.


How I do configure the BigBlueButton module? I have installed the BigBlueButton module. Its demo is working fine. How do I create a meeting?

I have resolved the problem following these steps.

Install the module
On the module settings page (admin/settings/bigbluebutton), put values for Server base URL and Security salt key, and save the settings
Create a new content type, for example Conference
On the content type setting panel (for the Big Blue Button module),
select Treat this node type as meeting and Display meeting status on node, and save the settings
Create a new Conference node and go to meeting


Adding links on top of view rotating banner I am trying to add a link to a page (about us) on top of a view with a rotating banner. There are three banners and i only want the link to appear on top of one of them. Any suggestions?

Add a "Global: Text area" to the header of your view that includes the link. This way it will always appear.


"Image Upload Button" section remove after click on upload I am trying to edit users's  profile page in Drupal 7. I have an image upload button there, but it remove (hide) after click on upload button .

But If i login with admin its working fine, means image upload section is not hiding on upload click.

Any suggestions ?

Thanks

Put the following code in a custom module, this module will act on all users but admin (user 1), this will work after user saves/updates his account.  inside function there are two sentences begining with $form, first will hide user picture field, second will disable it. use only one. code:

// implementes hook_form_alter
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
global $user;
$uuid = $user->uid;
/*  check that user is NOT admin (No1) */
if ($uuid !='1') {
if ($form_id == 'user_profile_form') {
//dsm($form);
if (!empty($user->user_picture) {
    // Prevent editing a field
    // hiding the field entirely on the edit form.
    $form['field_user_picture']['#access'] = FALSE;

    // disable update field on the edit form.
    $form['field_user_picture']['#disabled'] = TRUE;
    }
 }
}
}


How to prevent users from adding content without putting the site into full maintenance mode? We are planning a scheduled update of our site. There is no reason for people to not be able to see the site as anonymous users, or even browse their account if they want to log in.

How can I simply prevent people from adding new content while I do the updates instead of having the site completely down from having to use maintenance mode?

I would uncheck the "add [type] content" permissions checkboxes on the roles that have it, and re-check them after. However, depending on the updates, having people attempting to log in or use other features of your site may be problematic during updates.


A non-Views, Panels-compatible slideshow? The common way to create some variety of slideshow within Drupal is to use Views Slideshow and then display content that way.

However, what if I just want a simple slideshow that appears in all of one Panel on the front page? Creating a new content type (and the requisite nodes) seems fairly overkill.

To that end — is there a slideshow that is both compatible with Panels and able to be invoked without using Views (or otherwise creating a bunch of nodes)?

umm sure. you can always make a Block using admin/structure/blocks with like full_html. You could then easily make whatever HTML markup you need to get your images on the page.

Then in your theme file include a scripts[] = /path/to/your/js-slideshow.js.

A slideshow is just a slideshow. For example the slideshow at www.ucsb.edu is simply some HTML for images, 1 custom JS file, and CSS to hide all but the first image initially -- this is easily reproducible with Core Drupal. You could then place the block wherever you want with Panels.

The only caveat with this approach is uploading images from Drupal to power the slideshow is obviously harder since your keeping it very lean and not 100% drupal integrated.

Edit

Another example of getting remote images into drupal could be seen here by Fago making Entities from Google Picasa images and slideshows. Unless your comfortable with all this custom code, I dont recommend this type of approach. Drupal may have many approaches to getting something done, but as I mention in my last comment dont fight drupal's conventions or default way of doing something simply learn to embrace it. I've seen this idea spread by MerlinofChaos telling themers (im paraphrasing) "learn to use Views css, even though its ugly -- its feature complete". The same applies to drupal 7 "table per field" default storage structure. When you try to work around what you perceive is a shortcoming you simply fight an uphill battle to make drupal do what you want.


recaptcha not allowing login on localhost hi Not sure if this is specifically a Drupal question but I'll try it here first.

I am using Google recaptcha on my site, I set it up while the site was already online. but now I'm trying to make some changes I've backedup and downloaded my site to a localhost dev machine. now when I use this site I get:
"Google reCAPTCHA does not accept this submission. Try again please, or contact to Site support services."

its a bit frustrating and the only method I can think of is to remove this tool on the website, then dump the DB for my local version.

Anyone know another way around this, specifically to get it working properly?

For Google, your production site is not the same, as your devel one. But you can disable modules using drush, that does not require you to log in.


Cannot access commerce order relationship in Add relationship form in Drupal 7 Views I have Drupal commerce installed on a Drupal 7 website. I needed to create a view of users and wanted to display the product type they had purchased along with the user name in the View. However I am unable to create a relationship between the view and commerce order even though the module (commerce) has exposed it via hook_views_data

'relationship' => array(
  'title' => t('Owner'),
  'help' => t("Relate this order to its owner's user account"),
  'handler' => 'views_handler_relationship',
  'base' => 'users',
  'base field' => 'uid',
  'field' => 'uid',
  'label' => t('Order owner'),
),

Can anyone point out what is causing this relationship to not appear in the View add relationship foorm? Is it required to modify any additional configuration settings to bring up this view?

This was a false alarm. I was on a different branch with a single module missing. Enabling the module solved the problem.


drupal 7 - drupal_add_js - inline doesn't execute I made a custom module and I added the following code inside the php tag and also in my hook_menu function

drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');

I can't figure out why it's not firing.

When I look at the 'view source' of the page
I do see this:

<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function () { alert("Hello!"); });
//--><!]]>
</script>

Go through this document http://drupal.org/node/171213 It shows how to use Jquery. The syntax for jquery ready function is:

jquery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});


Is there a way to search Drupal's and contrib modules configuration settings? With so many different modules in use with configuring Drupal it is hard to keep track of which settings are configured where, such as whether some CSS is set by the Code per Node or CSS Injector.

It would be nice to have search pinpoint what configuration settings contain some keyword. Does search have such a facility? I understand that the search module is mainly used by content such as nodes and entities.

But is there some way something like this can be accomplished, even by some module, or do module developers need to configure their modules settings to be indexable by search?

Useful fact: drush vget abc lists all variables with 'abc' in their name. So if you are looking for settings related to css, drush vget css might provide you with a clue. Likewise you can use the name of a module in your search to see all the settings from that module.

Some modules have complex settings that are stored in separate database tables. In that case I recommend using a tool such as SQLyog that has a search facility which will scan an entire database, or just specific tables, for a given input string.


A taxonomy-provider module: enable/disable vs install/uninstall If a module provides a taxonomy vocabulary, what should happen in hook_install, hook_enable, hook_uninstall and hook_disable?

My main concern is how hook_uninstall should differ from hook_disable. Should we just taxonomy_vocabulary_delete() in both hooks? Should the existing nodes referring to the terms just lose the references upon disabling as well as uninstalling of the module?

There is at least one core module that creates a vocabulary that we can use as a guide: Forum.

It creates the vocabulary "Forums" in hook_enable() (see form_enable() function).

It does not remove the vocabulary in hook_disable() or hook_uninstall(). (see forum_uninstall() function - Forum does not have a hook_disable() function.

So, to answer your question, create the vocabulary in hook_enable() and don't delete it.

One other note gleaned from the forum.install file that is probably relevant to your module is that you need to make sure your module is loaded after the Taxonomy module. You can do so by settings the module's weight to 1.


Youtube video does not play after clearing the cache I have added a Youtube video inside the CKEditor to load the video in Colorbox, in a content type from CKEditor plugin (plugin is extact data from view). It works fine after creating content.

After clearing cache the URL does not work. It show only http:// in Colorbox. Please give me some suggestions.

The sample URL is /?q=vef/load/fe380247ab1fef057fca83a1df37326c&width=640px&height=363, inside CKEditor.

You just need to enter url in the embed_video_field. Following is the sample url
http://www.youtube.com/watch?v=BRWKsjaEtKs

You can set other parameters like height, width using embed video field configuration.


Administration menu - How to remove the number of users + search bar Out of the blue, our administration menu now shows a number like 192/7 on the right side and a search bar.

Does anyone know what causes these items to appear on the administration menu? And how can I remove them?

Navigate to admin/config/administration/admin_menu Under the Plugins tab uncheck Search bar and Account links then click Save configuration


Set value of a webform field programatically I am using a custom block in which all nodes of a specific type are loaded and then a webform is loaded and attached to each of these nodes.
The webform has a hidden textfield field which I am trying to programatically set to the id of the parent node:

class CustomBlock extends BlockBase {

  public function build() {
    // Load all nodes
    $query = \Drupal::entityQuery('node');
    $query->condition('status', NODE_PUBLISHED);
    $entity_ids = $query->execute();
    $nodes = \Drupal\node\Entity\Node::loadMultiple($entity_ids);

    // Loop through all nodes, connecting the webform.
    foreach ($nodes as $node) {
      $form = \Drupal\webform\Entity\Webform::load('MYWEBFORM');

      // Set the value for the hidden field pointing to the 'parent' node.
      $form->setElementProperties('node_reference', [
        '#type'=> 'textfield',
        '#wrapper_attributes' => array(
          'style' => 'display:none',
         ),
        '#webform_id' => 'mywebform--node_reference',
        '#webform_key' => 'node_reference',
        '#value' => $node->get('nid')->value,
      ]);

      // Render form an assign it to each node.
      $rendered_form = \Drupal::entityManager()
        ->getViewBuilder('webform')
        ->view($form);

      $node->form = $rendered_form;
    }
  }

}

If I look at the generated markup for each nodes form it see different values in the node_reference field, but when I submit the form and then look at the submission all forms have the same node_reference value?
Can anyone help me figure out what I am doing wrong here or perhaps this could be solved in a much easier way?

It seems like the the value always are set to the nid of the first node in the array? Perhaps this is some kind of strange caching issue?

I don't know if your problem could be solved in an easier way. A lot of our solutions at my workplace seem equally convoluted. In fact, we use WebformSubmissions to hold a lot of submitted data.

Here is how you set a value in a WebformSubmission:

Load the submission.
Get the submission's data as an associative array.
Change the submission's data however you want.
Set the submission's data to this modified array.
Save the submission.

Here is the code:

use Drupal\webform\Entity\WebformSubmission;

// $sid contains the submission id
$submission = WebformSubmission::load($sid);

$data = $submission->getData();

// you can find the machine name in the devel tab
// or just do what I do and var_dump($data);
$data["field_machine_name"] = "new value";

$submission->setData();
$submission->save();


Using computed fields module to display certain fields? I just installed the computed fields module and I'm a little lost as to how to use it. I have 2 fields in my content type: field_shortdesc and field_audio_description.

If field_shortdesc is blank I need to display field_audio_description and vice-versa.

What code do I need to place into the computed code and display code areas?

Sorry for the late response, but this is an issue I struggled with as well.

In the first box, 'Computed Code' you determine the value of the computed field based on what is present in the $entity object. Calculations are possible, but drupal functions or methods are not available. In your case the entire determination can be performed here:

if ( isset($entity->field_shortdesc) && trim($entity->field_shortdesc[$entity->language][0]['value']) != "") {
  $entity_field[0]['value'] = $entity->field_shortdesc[$entity->language][0]['value'];
} elseif (isset($entity->field_audio_description)) {
  $entity_field[0]['value'] = :$entity->field_audio_description[$entity->language][0]['value'];
} else {
  $entity_field[0]['value'] = "";
}

The second box, 'Display Code', is for processing the value you determined in the first box. If you have to call drupal functions to load a user object or to format text this is where you would do it. In your case, no further processing is required, so you would leave the default:

$display_output = $entity_field_item['value'];

Then if your fields are using an input format (eg. 'Filtered HTML') you will want to set the display format (under 'Manage Display') to 'Filtered markup'.


Use multiple data blocks in the same chart created using forena reports I have created a chart using Forena reports. I need to set the chart title dynamically based on the logged in user's country. At present I have hard coded the title as "Your Country". The data for this chart is coming from a data block (let's say data_block_1). And the logged in user's country can be obtained from a second data block(data_block_2).

How can I show the logged in user's country as the chart tile?

Though I have the second data block I don't know where to put the name or how to call that data block.

I am posting the screenshot of the body tag inside the frx file and also the chart I created thus and also the sql file.

Using data contexts

This question is a (great) example of using "Data contexts" in Forena. To see an example of a "data context" at work (in a demo site), refer to the example about Master Summary with drill down. If in the report you click any of the linked columns (such as for state = VA), you'll get the Users in state Virginia report. In that report you should note these things:

... in state Virginia (in the report title).
... state with code = VA (near the top of the report).

If in the above example you pick another state, such as IL (Illinois), you'll get the report specific to that state.

Read more about "Data Contexts" in the Forena documentation, which you can also find in your own site within /reports/help.reportingfrx#datacontexts (after you installed Forena).

Below are some details about what's needed in this specific case (to use the user's country as your chart tile), based on these assumptions:

The user's country is contained in stored in a datablock named (say) "pec_reports/data_block2", within a column (say) "UserCountry".
The user's country is (say) "XYZ".
You want your chart title to be like (say) "Chart for country XYZ".

Based on these assumptions, this is what you should do:

Add a data context to the document in the  section of the document, which are preloaded before the report is rendered. The example below illustrates the syntax for preloading data in the head section:

<head>
  ..
  <frx:data id="countryinfo" block="pec_reports/data_block2"/>
</head>

Any data from any other section of a report may be used by referencing the datablock by its id and appropriate column name of that datablock. The example below contains an example of referencing the UserCountry column contained in pec_reports/data_block2:

<div> ... {countryinfo.UserCountry} ... </div>

The syntax for such reference is like so:

"Id" of the datablock, followed by a ".", and followed by the "ColumnName".
Preceeded by a "{" and followed by "}".

Same is true for any of the tags used to specify the details of the chart you want to create. So in this case you could use something like so:

frx:graph_title="{countryinfo.UserCountry}"

Ensure your SQL returns the correct value(s)

If you get a blank chart title after applying the changes as I suggested above, then most probably that is because the value of that chart title is blank. Looking at the SQL statement for your pec_reports/data_block2, here are a few tips to further verify (debug?) the actual SQL statement you're using:

Create a temporary (for debugging purposes only) tabular report using that same pec_reports/data_block2 data block, and run that report while logged in. Or as a variation, add that tabular report in your report with the chart, but in front of that chart. Do you get the expected "country" value for that user? I wouldn't be surprised if you get an empty output (which would confirm something is wrong in your SQL statement, and hence also explain your blank chart title). In that case continue with step "2." and/or "3." below.
In your from clause, change users to {users}, and rerun your temporary report in step 1.
In your where clause, change current_user to the value of the uid of your own user, and rerun your temporary report in step 1.

If none of the above seems to help, then I would use either (or both) of these other routes:

Have a look at the data blocks (SQL statements) related to the Drupal Administration reports that are delivered with Forena also, such as:

Active Users
Logs for User
Role Details

Use the query writing tool that comes with Forena, which is called the Forena Query Builder. This is a separated module that comes with Forena. It can be enabled as per standard Drupal instructions to enable an additional module. For a video tutorial about this query writing tool, checkout Define data blocks with optional filters.