Loading menu on basis of user profile We are working in Drupal 8 website and same user will have two different user profiles buyer and seller.

We want to show a user drop menu and when user click on "buy" link in drop down then main menu of the site would be changed as per "buyer" profile.

And if user click on "sell" link in drop down menu then main menu of the site would be changed as per "seller" profile.

The primary way to control visibility is through block visibility conditions.

There is no default condition available for what you are trying to achieve, so you have to implement your own.

See \Drupal\user\Plugin\Condition\UserRole, that does visibility based on the user role, what you want would be fairly similar, visibility based on a field, so like any other plugin, you can copy that into your module into the plugin namespace (\Drual\yourmodule\Plugin\Condition) and then adjust it to check the field instead and also offer the same select.

Then you place two blocks in the same region, each with a visibility configuration using your plugin. You need to think about what should happen when a user is not logged in, so maybe you have a default or hide both for anon users/users without a selection.


How do I add module theme elements to drupalSettings I have a module "flot_d8" which is a wrapper for a javascript library. I would like to streamline the way this library is called from other modules (flot_examples in this case). I currently call it like this from src/Controller/FlotExample.php

$data[] = [
  'data' => [
    [0, 12],
    [7, 12],
    NULL,
    [7, 2.5],
    [12, 2.5],
  ],
];
$div_id = 'placeholder';
$drupalsettings['flot_d8'][$div_id] = ['data' => $data];
$output[] = [
  '#attached' => [
    'drupalSettings' => $drupalsettings,
  ],
  '#theme' => 'flot_d8_my_template',
  '#data' => $series,
  '#options' => NULL,
  '#div_id' => $div_id,
];

Is there a way to force the flot_d8 module to add the $data to drupalSettings instead of passing this task to the flot_examples module in every single class function?

I tried this

function flot_d8_page_attachments_alter(&$page) {
//$div_id = $output["#div_id'];
//$data = $output['#data'];
//$options = $output['#options'];
  $page['#attached']['drupalSettings']['flot_d8'][$div_id] = ['data' => $data, 'options' => $options];
}

But I know this isn't the right way to access $div_id, $data, and $options. Can I use the value in $output['#div_id'] in hook_page_attachments_alter()?

I created an Element within the parent module. This element includes code to add the data and options to drupalSettings. It also determines which libraries are needed and includes them.


VBO Custom Operation to create pdf of selected nodes detail page I need to create an vbo action to produce a seperate document (pdf) of every selected node's detail page (node--content.tpl.php).

What i have to do for that..??

Right now i am creating simple pdf with dummy variables to check pdf is generate or not,

For that i done the following code

function MYMODULE_action_info() {
    return array(
        'export_pdf_bulk' => array(
        'type' => 'entity',
        'label' => t('Export PDF'),
        'configurable' => FALSE,
        'behavior' => array('view_property'),
        'triggers' => array('any'),
        ),
    );

function export_pdf_bulk(&$entity, $context) {

$html = '';
$html.="
";
$html.="
Testing
";
$html.="
Dear Sir/Madam,
";
$html.="

";
$html.="
Testing string Here
";
$html.="

";
$html.="
Details are as follows:
";
$html.="

";
$html.="
";
$html .= '';

pdf_using_mpdf_api($html, "Track grievances");
}

Using this code to generate dummy pdf (Use MPDF for generate pdf https://www.drupal.org/project/pdf_using_mpdf) for selected content, i got the ajax error and in error pdf content is displayed in junk characters, but ajax code is 200 and status is ok, then why pdf is now downloading and display in ajax error in junk characters??

You can achieve this using rules. Import following component & add Rule component in Views bulk operation list as shown in figure below:

{ "rules_create_pdf" : {
    "LABEL" : "Create PDF",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "ACTION SET" : [
      { "php_eval" : { "code" : "$view = node_view($node, \u0027PDF\u0027);\r\n$html = drupal_render($view);\r\npdf_using_mpdf_library_exist();\r\n_pdf_using_mpdf_generator($html, \u0027node-\u0027.$node-\u003Enid);" } }
    ]
  }
}

In order to save PDF files at server use above Rule component & comment two line given below in pdf_using_mpdf.module of function _pdf_using_mpdf_generator. You can find that on line no. 324 & 325 of pdf_using_mpdf 7.x-2.6.

//drupal_goto($_SERVER['HTTP_REFERER']);
//exit;

Figure:


Need help on adding options to $form via select field I altered the username field in login block into a select field and now I'm trying to filter the usernames by their user roles via another Select Field.

function design_form_alter(&$form, $form_state, $form_id){

    $users = entity_load('user');
    $user_names = array();
    $acc = array("PH","SL");
    $rolePH = array();
    $roleSL = array();
    foreach ($users as $user_id => $user) {
    $user_names[] = $user->name;
      if (in_array('PH', array_values($user->roles))) {
        $rolePH[] = $user->name;
      }
      elseif (in_array('SL', array_values($user->roles))) {
        $roleSL = $user->name;
      }
    }
    $user_arr = array_combine($user_names, $user_names);
    if($form_id=="user_login"){
    $form['roles']['#type'] = "select";
    $form['roles']['#weight'] = -0;
    $form['roles']['#size'] = 'auto';
    $form['roles']['#options'] = $acc;
    $form['roles']['#title'] = t('Role');
    $form['name']['#type'] = "select";
    $form['name']['#options'] = $user_arr;
    $form['name']['#required'] = true;
    $form['name']['#size']= 'auto';
    $form['name']['#title']= t('Organization');

    }
}

I'm a bit stuck, as you can see, I already separated users depending on their roles. My problem is how do I set the $form['name'] options when a role is selected. Right now I'm just showing all users in the DB.

Borrowed From HERE:

If you want to do this hardcoded, you might try to use the #ajax property of the Form API

You can reload your second dropdown on change of the value of the first dropdown and change the value while reloading the form.

I made a little example to give you an idea :

$form['number'] = array(
  '#type' => 'select',
  '#title' => t('Select Number'),
  '#options' => array(
      0 => 1,
      1 => 2,
      2 => 3,
  ),
  '#default_value' => 0,
  '#ajax' => array(
    'callback' => 'ajax_replace_dropdown_default_value_callback',
    'wrapper' => 'wrapper-dropdown',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

$default_value = !empty($form_state['values']['number']) ? $form_state['values']['number'] : 0;

$form['open_closed'] = array(
  '#type' => 'select',
  '#title' => t('Open / Closed ?'),
  '#options' => array(
      0 => t('Open'),
      1 => t('Closed'),
      2 => t('Progress'),
  ),
  '#value' => $default_value,
  '#prefix' => '
',
  '#suffix' => '
',
);

function ajax_replace_dropdown_default_value_callback($form, $form_state) {
  return $form['open_closed'];
}

In your case you will have to do it in a hook_form_alter and add the #ajax property to your first dropdown and add prefix and suffix to give the second dropdown the proper value.

You can also check this link about AJAX with the FORM API :


How to import a view in .install file? I have an exported view code.How can I import it in .install file?

You don't. You implement hook_views_default_views() in yourmodule.views_default.inc and place the export there.

See Using default views in your module for a detailed guide.


Drupal 7 module issues using node_ functions I'm building a basic D7 module that fetches data from an API and then add it as a certain content type. Problem is, every node_ function is coming back as undefined. node_object_prepare, node_submit, and node_save with this error message:

Call to undefined function node_object_prepare()

The module is bare bones...
info file:

name = Social Fetch
description = Fetches feeds from various social media platforms.
package = public-action
version = 1.0
core = 7.x
files[] = social_fetch.module

and the social_fetch.module...

<?php
if(isset($_GET['fetch']))
{
    social_fetch();
}

function social_fetch(){
        $node = new stdClass();
        $node->title = 'test';
        $node->type = "social_boxes";
        node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
        $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
        $node->uid = 1;
        $node->status = 0; //(1 or 0): published or not
        $node->promote = 0; //(1 or 0): promoted to front page
        $node->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write
        $node = node_submit($node); // Prepare node for saving
        node_save($node);
}

So much as I knew, node_ was part of the core and wouldn't need any dependencies but I may be wrong. I tried adding this:

module_load_include('inc', 'node', 'node.module');

but that did nothing.
also tried loading the bootstrap to see if maybe this was being run before the core loaded, but that did nothing as well.

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

Am I missing something? should this be run in a hook of some kind and if so, which?

Side Note

I am able to achieve what I need by using the db_ methods below. It just seems like an inferior way to do so since I don't actually know the anatomy of a node to know if these are the only things required to make sure the system remains stable. The kind of things the node API would have handled 100%.

      $nid = db_insert('node')
        ->fields(array(
          'title' => 'test',
          'uid' => 1,
          'type' => 'social_boxes',
          'language' => 'und',
          'status' => 0,
          'comment' => 0,
          'promote' => 0,
          'created' => REQUEST_TIME,
          'changed' => REQUEST_TIME,
        ))
        ->execute();

        if($nid)
        {
            db_update('node') //add vid back into the new node
              ->fields(array(
                'vid' => $nid
              ))
              ->condition('nid', $nid, '=')
              ->execute();

            db_insert('node_revision')
            ->fields(array(
              'nid' => $nid,
              'vid' => $nid,
              'uid' => 1,
              'title' => $class->getText(),
              'timestamp' => REQUEST_TIME,
              'log' => '',
              'status' => 0,
              'comment' => 0,
              'promote' => 0,
              'sticky' => 0
            ))
            ->execute();
        }

Never ever call functions from the global scope. You are probably running into a situation where other modules (the node module) are not yet loaded.

<?php
if(isset($_GET['fetch']))
{
    social_fetch();
}

You could try to add your function to hook_boot(), but even then the node module might not be loaded, so you will have to ensure it is loaded manually.   drupal_load('module', 'node');

You'll end up with

function social_fetch_boot() {
  if(isset($_GET['fetch'])) {
    drupal_load('module', 'node');
    social_fetch();
  }
}


Allow a user to flag the same node/user multiple times The flag module allows flags to be defined per user.  For example, User 1 can flag Node A and B, and User 2 can flag Node A but not Node B.

In this situation, a flag is either on or off per user.  However, is there a way to allow a single user to flag the same piece of content multiple times?

Use case: I have created two content types, Message and Reply.  I want to limit the number of times that users can reply to a message (say, to 3).  To do this, I was going to use Rules to automatically flag the original message each time a user writes a reply.  However, since content is either flagged or unflagged, I don't see any way to allow a user to flag the content multiple times.

Any ideas on how to approach this use case are welcome, including using modules other than the flag module.

How about using the Five Star module and incrementing the rating each time?  Eg, first reply, rate the message 1.  Next reply, re-rate the message 2.  When you get to 3 (or 4 or 5) don't allow more. You could implement this directly with the Voting API if you wanted to, too, I'd imagine, if you needed higher than 5.


Does variable_get() first go to 'variable' table in the database or the $conf array in settings.php? I can't tell from the source for variable_get() for Drupal 6 whether it first looks for something in the variable table in the database, or the $conf array in settings.php.

Also, if I were to add something in some code to the $conf array, would I need to do anything in order for variable_get to see it?

global $conf;
$conf['myvalue'] = 'newvalue';

If 'myvalue' were set to 'oldvalue' in settings.php, then what would I need to do in order for $conf['myvalue'] to now return newvalue instead of oldvalue?

The function that is responsible for loading the values of the Drupal variables in memory is variable_init(), which executes the following code:

  if ($cached = cache_get('variables', 'cache')) {
    $variables = $cached->data;
  }
  else {
    $result = db_query('SELECT * FROM {variable}');
    while ($variable = db_fetch_object($result)) {
      $variables[$variable->name] = unserialize($variable->value);
    }
    cache_set('variables', $variables);
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

$conf, the value passed to the function from _drupal_bootstrap() is the array read from the settings.php file. The function that reads the configuration file is conf_init(), which is called from _drupal_bootstrap() before calling variable_init().
As you see in the code, the values read from the database are then overwritten with the values find in the $conf array.

Similar code is present in Drupal 7 (see drupal_bootstrap(), _drupal_bootstrap_configuration(), and _drupal_bootstrap_variables()).

The only way to use the value read from the database is to remove the value set in settings.php.


How to change the product type of selected Drupal Commerce products (without direct DB updates)? In order to apply a price calculation rule for certain products only, I have created a new product type. But I am having problems changing the product type for the selected products. Right now it seems to me that the only way to apply the new product type to these products is to delete them and then re-import them (using Feeds) with the new product type selected. This works as expected.

But there are hundreds of products and it seems to me that there should be an easier way. I have read this post How Can I change the machine name of product type but I am a bit wary that I might break something by changing things in the database.

Does anybody have a cleaner solution for this?

For sure I'd not use the approach of changing things in the Database directly. Instead I would try to use the Rules module to create a clone (using the new product type) of the selected products. A solution that could possibly work is to (also) get the Views Rules module involved. Some details about this module (from its project page):

  Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (yet), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

Create a view (using Views) so that you have 1 Views result (row) for each product of old product type and for which you want to create a similar one with the new product type. This view should have fields (columns) for each of the fields from your old products that you want to use to create your new product (with your new product type). Important: use a Views display type of "Rules".
Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop". If you're not familiar with Rules Loops, then have a look at the tutorial titled "Lists and loops".
For each iteration step in your Rules Loop, perform a Rules Action to create an entity which corresponds to your product but with the new product type. At that point you'll have all data from each column of your Views results available as so called Rules Parameters (remember: they are the values used in your products with the old product type). So at that point it's a piece of cake to populate the various fields of your product with the new product type.
The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

Possibly, you also want to delete the product (of the old product type), e.g using a variation of this rule (to delete those products instead of creating new entities). I would definitely do that in a separate rule (not as an extra Rules Action in the same rule), to be able to verify that the new products are created (correctly) before deleting the products with the old product types (better safe then sorry ...).

Note: Refer to my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?" (the option 2-part of it) for an example (with screenprints) about how to use the Views Rules module.


views_row_selector module - capturing a form submission I am using the views_row_selector module to add checkboxes to a table created in Views

The hook_menu $item looks like this

$items['admin/structure/account'] = array(
    'title' => 'Accounts',
    'description' => 'Names and addresses',
    'page callback' => 'views_embed_view',
    'page arguments' => array('accounts_view'),
    'access arguments' => array('administer booking'),
);

Everything works perfectly, but how do I capture the form submission?

When using this module you need to write custom code to include a submit handler and use the results. See my inline Issue Queue links where the module maintainer describes this. This is code from a toy example i have sitting around:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // As per this issue responded to by the module author, we need to add our
  // own submit button and handler to make use of the data
  // selected in views row selector.
  //
  // https://www.drupal.org/node/1898842#comment-6984976
  if ($form_id === 'views_form_identity_search_page') {

    $search_had_results =
            count($form_state['build_info']['args'][0]->result) > 0;
    if ($search_had_results) {
      // some custom tasks I make up that could use the results as
      // arguments. Ideally these paths are Rules, Views or hook_menu stuff.
      $my_tasks = array(
        '/foo/bar' => 'report 1',
        '/foo/baz' => 'report 2',
        '/foo/bak' => 'report 3',
      );

      #$form['views_row_selector']['#required'] = TRUE;

      // Some magic to make horizontal form elements.
      // http://drupal.stackexchange.com/questions/7954/horizontal-form-elements
      $form['actions']['#attributes']['class'][] = 'container-inline';
      $form['actions']['my-task'] = array(
        '#type' => 'select',
        '#title' => t('Task to Perform'),
        '#options' => $my_tasks,
        '#weight' => -5,
        '#required' => TRUE,
      );

      $form['actions']['submit']['#value'] = t('Perform Action');
      $form['actions']['submit']['#submit'][] = 'ucsb_identity_selection_form_submit';
    } else {
      $form['actions']['#access'] = FALSE;
    }
  }
}

function MY_FORM_ID_form_submit($form, &$form_state) {
#  dpm($form_state, __FUNCTION__);
  $ids = array_filter($form_state['values']['views_row_selector']);
  // take the results, compact them as "1,2,3" for example and perhaps
  // redirect to a new Views page setup to use Contextual Filters
  // with arguments.
  $ids = @implode(',', $ids);
  $options = array('query' => array('identity_results' => $ids));
  drupal_goto('custom-user-diagnostics', $options);
}

good luck!


Ajax request: 500 (Internal Server Error) I am using this jQuery plugin to render a toggle button in a block. When the button is toggled off/on I want to write to a databse table (with entity_save). Here's the relevant code I'm using to try to acheive this:

// hook_menu item
$items['product-status-update'] = array(
  'title'=>'Status update',
  'page callback' => 'my_module_status_update',
  'access callback' => 'product_entity_access',
  'type'=> MENU_CALLBACK,
);

// jQuery
drupal_add_js('
  (function($) {
    $(function() {
      $(".toggle-button").toggles({' . $status . $state . '});
      $(".toggle-button").on("toggle", function (e, status) {
        status = status == true ? 1 : 0
        $.ajax({
          type: "POST",
          url: "?q=product-status-update",
          data: "pid="+' . $pid . '&"status="+status,
        });
      });
    });
  })(jQuery);
', 'inline');

// Callback
function my_module_status_update() {
  $pid = $_POST['pid'];
  $status = $_POST['status'];
  $product = entity_load_single('product', $pid);
  $product->status = $status;
  entity_save('product', $product);
}

// Console log output when toggling
POST http://example.com/?q=product-status-update 500 (Internal Server Error) jquery-1.10.2.js:8706
1 ?q=home:98
0 ?q=home:99
POST http://example.com/?q=product-status-update 500 (Internal Server Error) jquery-1.10.2.js:8706
1 ?q=home:98
1 ?q=home:99
POST http://example.com/?q=product-status-update 500 (Internal Server Error) jquery-1.10.2.js:8706
1 ?q=home:98
0 ?q=home:99

As you can see from the console log output I am receiving: 500 (Internal Server Error).

Any ideas why or what might be the culprit? Thanks.

At a glance, there's some issues with the code, however, the main error may be:

$product = entity_load_single('product', $pid);

where you don't have a $pid value, you're setting $fid instead.

$fid = $_POST['pid'];


Unable to show the block title in D8 I want to show the D8-based blocks in the block.html.twig file with the  html tag only. However, when I entered this special split file, I created a special branch file for each block area (eg region - sagblok.html.twig), block title and content css, html codes. Unfortunately, the block titles did not appear. My code is below:

{{ title_prefix }}

{%if label %}

{{ label }}

{% endif %}
{{ title_suffix }}

{% block content }}

  {{ content }}

{% endblock %}

Editor screenshot

Sorry for my English.

I have debugged the theme, I am cleaning the cache with the "drush cr" command continually. I have copied the style files of the blocks to the folder of the theme I am developing "core / templates / stable / templates / block / block.html.twig".

The content of the "block.html.twig" file looks like this:

  {{ title_prefix }}
  {% if label %}

{{ label }}

  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content }}
  {% endblock %}

I changed the codes in this file like this:

  {% block content %}

    {{ content }}

  {% endblock %}

then I created a twig file called "region--sagblok.html.twig" belonging to the block region, codes:

{{ title_prefix }}
  {% if label %}

{{ label }}

  {% endif %}
  {{ title_suffix }}

  {% block content %}

    {{ content }}

  {% endblock %}

unfortunately block names do not appear in this way. but when I looked at the source code, I realized that the html codes came, but the block names did not.

You are supposed to put your templates into a /templates subfolder of your theme.

I'd recommend you find out how to enable debugging for Twig templates during development. Here is a how-to on DO: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

By that you'll get template suggestions printed as HTML comments directly inside the markup of your page. It will suggest you certain file namings which then must be placed inside the /templates subdirectory of your theme.

And last but not least: Flush caches as often as possible. And find out how to disable caches completely during development. Here is another how-to on DO: https://www.drupal.org/node/2598914


Drush 9 can't find installed module, yields CommandNotFoundException On my newly installed Drupal 8.4.4 sandbox installation, I've installed Drush 9 and the Devel module:

composer require drush/drush:^9
composer require drupal/devel

After running these commands, I installed the Devel module using the Extend tab in Drupal.

Drush seems be be installed correctly:

www-data@39e134dc7690:~/html$ /var/www/html/vendor/bin/drush version
Drush version : 9.1.0

The Devel modules seems to be installed correctly:

www-data@39e134dc7690:~/html$ grep -r devel-container-service /var/www/html/modules/contrib/devel/
/var/www/html/modules/contrib/devel/src/Commands/DevelCommands.php:   * @aliases devel-container-services,dcs,devel-services
/var/www/html/modules/contrib/devel/drush/devel.drush8.inc:  $items['devel-container-services'] = array(

But Drush doesn't seem to find the devel module:

www-data@39e134dc7690:~/html$ /var/www/html/vendor/bin/drush devel-container-services
[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "devel-container-services" is not defined.

Are there any path settings I need to tweak to get Drush to find the Devel module?

I looks like I simply had forgotten to enable (i.e install) the module in /admin/modules. I had just ran "composer require", but not actually enabled it.


How to add 'add to cart' button in custom content type using Commerce 2? I have created a new content type with product title, description, price(field_price), SKU(field_sku) fields. I just want to add a Add to cart button into this content type.

What I tried?
I have read many places, it says to add 'Product references'. I have tried to do that using 'Entity reference' field and selected 'Product'. But no luck.

Can someone guide me step by step about how can we add such 'Add to cart' button in custom content type?

Follow below steps to show Add to cart button into any content type.

Add field with reference as Product and select list of product bundles you want to show in content type.
And in field settings select reference as shown in below.

Go to content type manage display and select as "Rendered Entity" as shown below.

Go to the product type which you selected in content type and click on manage display.
See for variations and select as "Add to cart form" as shown in below.

And that's it after adding node with product you will be able to see the Add to cart button into node view like below.


Where are these modules - "Views Slideshow: SingleFrame" & "Views Slideshow:ThumbnailHover"? Were these integrated into some other modules? Cannot find a trace of them anywhere on drupal.org but they are used at many places, like in this tutorial: http://mustardseedmedia.com/podcast/episode42

Screenshot from the tutorial showing the Modules: http://www.tiikoni.com/tis/view/?id=0000d1a

They are packed with the Views Slideshow module.

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.


Why isn't the value for a new Boolean field rendered? I added a new Boolean field to a content type. For some nodes, I did set this field.

Still, the field value is not shown on the node page.

Why?

I realize that, as long no value is set for the new field, it isn't present in the database, but (as seen in the screenshots) on that node, the field is set to true and it should be shown on the node page, shouldn't it?

This is a Durpal 7 Problem.
It lies about that it will fall back to 0/1 if you don't provide your custom true/false values, when it actually does not fall back.
See
https://www.drupal.org/project/drupal/issues/1750950

In short, in the field-settings, you have to set on-/off- values.
If you don't the default renderer will output an empty string and in the edit forms the field's checkbox or radio-buttons will have no label.


want to ask if there is a way that I can display a field from another content type to a field of another content type Im quite new to drupal (7) and want to ask if there is a way that I can display a field from another content type to a field of another content type and applying condition at the same time?

Here is the scenario:

I have created content types: Courses and Course schedules

I will be creating more than 50 contents for courses (containing their description, objectives etc as fields).

I will create different course schedule contents (data in here changes regularly including fields like time, date, venue, etc).

What i want to accomplish is to display the course article with a field that is linked to the courses schedule content, thus showing the available class sched data for each course.

I dont want to do it with views because im thinking it would be tedious to create a view for each course.

Is there a best way you can recommended to accomplish this? or is there a module that does this?

Thanks so much for your time.

You can use the entity reference module for accomplishing your requirements.

On the "Courses" content type you will add a field type entity reference which refer to the "Course Schedules" content type.

Then in the "Courses" content type Manage Display, You can choose that the referred node link to appear, I think you can also choose that the rendered node to appear.


ctools with panels colon issue IIS When using Panels module I have noticed that one of the ajax calls is creating an url with colon inside :

For Example :

dev-www.redbusbingo.com/panels/ajax/editor/select-content/panel_c

%3A = :

The problem is that iis Dont know how to Handle ":/" , or to say this colon in the end of string

This case break the site with error 500 .

500 Error Case : "dev-www.redbusbingo.com/panels/ajax/editor/select-content/panel_c" ( Colon at the end Before "/")

Good Case :

 "dev-www.redbusbingo.com/panels/ajax/editor/select-content/panel_c" ( NO colon at the end Before the "/")

Is there any way to replace this colons ?

Just to say i have reported this bug to Microsoft and they said that this a security issue and because of that they will not allow colons in the url .

Currently i can't work on my site because of this error and my iis ,
Please assist me with this .

Thanks
Haniel

I've finally succeded in correcting this bug, by modifying directly the Panels module. I'll publish a patch on panel's forum on drupal's site. Here's the solution :

In the file /sites/all/modules/panels/plugins/display_renderers/panels_renderer_editor.class.php, you have to change get_url() function (line 505), replace this:

 $url = 'panels/ajax/' . $this->plugin['name'] . '/' . $command . '/' . $this->display->cache_key;

by this

 if (variable_get('clean_url', FALSE))
  $url = '?q=';

$url .= 'panels/ajax/' . $this->plugin['name'] . '/' . $command . '/' . $this->display->cache_key;

As you maybe know the problem is caused by cleans Url, so it works without the fix if u disable it. But if you want to keep cleans url, apply the fix, it forces all ajax requests to be without cleans urls

PS: Thank you to MPD♦ who deleted my previous answer where i put a link to azure forum which was a possible way to solve the problem.


How do I create custom content types in drupal? I need to create a content type that is similar to a textarea, but I need to do some server side formatting before it can go out to the page.

I want a user to be able to input a chunk of text, then if it's a link of a certain type, leave it be, if it's not a link, create a link of sorts out of it with some server side (PHP) magic.

Can this be done in Drupal? Can someone point me in the right direction?

Yes this can be done.

For the processing you'll need a custom module. Here's a tutorial to get you started with modules.

As for the specific functions you'll need all revolve around hook_nodeapi (d6) or node api hooks (d7).


How to call ctools modal window from mycustom.tpl.php? I need to show a modal window on click from my mycustom.tpl.php

Here is my code in mycustom.tpl.php

False Positiv1e

In my module file :

$items['modal/%ctools_js'] = array(
    'page callback' => 'modal_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

 return $items;
}

function modal_callback($ajax) {
    ctools_include('ajax');
    ctools_include('modal');
    ctools_modal_add_js();

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('MyModule Modal Form'),
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $output = ctools_modal_form_wrapper('modal_form', $form_state);
    // If the form has been submitted, there may be additional instructions
    // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();

}
function modal_form($form, $form_state) {
  $form = array();

  $form['new_link_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Link text'),
  );

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

  return $form;
}

But when I am clicking on the button, Modal window Breaks and print $output array as below

You have to include below code in your mycustom.tpl.php also.

ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();


add "items_per_page" number in title tag and meta tag I created a view which has set up "Exposed items per page options." I used "24,48,72" as my options. Here is my view "Exposed setting":
When I choose "items per page" as 72, the url of that page will change to "https://www.domain.com?items_per_page=72". Here is a test page screenshot:

My question is how can I add the number to "title" tag in order to distinguish "title" for SEO. There are some websites suggest to used [current-page:page-number] token, but this is not working in my case.  Does anyone have any idea?

I got a solution. Just add the following code in template.php file.

function yourtheme_preprocess_html(&$vars){
    // add pager number to title.
    parse_str($_SERVER['QUERY_STRING']);
    if(isset($items_per_page)){
        $vars['head_title'] .= $items_per_page;
    }
}


ajaxifying simplenews subscribe is there a way to ajaxify simplenews subscribe to newsletter block?
I was thinking of hook_form_alter ing it and adding my ajax callback, But its not working.

my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'simplenews_block_form_7182') {
    $ajax = array(
          'callback' => 'simplenews_block_form_validate',
          'wrapper' => 'simplenews_wrapper_block',
          'method' => 'replace',
          'effect' => 'fade',
          'progress' => array('message' => '')
        );
    $form['submit']['#executes_submit_callback'] = TRUE;
    $form['submit']['#ajax'] = $ajax;

but now when I trigger the submit button i get
Fatal error:  Call to undefined function simplenews_block_form_validate() in /includes/form.inc on line 1460

Hope this will help you,

In Drupal 7, you can achieve this using form_load_include OR require_once

Try form_load_include() OR require_once() in your form alter.

function test_form_alter(&$form, &$form_state, $form_id) {
 switch ($form_id) {
    case 'simplenews_block_form_ID'://add your form_id
        require_once(DRUPAL_ROOT . "/modules/contrib/simplenews/includes/simplenews.subscription");
        //OR
        form_load_include($form_state, 'inc', 'simplenews', 'includes/simplenews.subscription');
    break;
   }
}

Reference


Uploaded image in Block Plugin keeps on getting deleted overnight I have a block plugin that allows users to upload an image to be used as a background. Below is what is inside my blockForm function.

    $form = [
        'image' => [
            '#type' => 'managed_file',
            '#title' => 'Image',
            '#upload_location' => 'public://my_style/images',
            '#default_value' => $this->configuration['image'],
        ],
    ];

And my block submit function is as follows.

public function blockSubmit($form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    foreach ($values as $index => $value) {
        $this->configuration[$index] = $value;
    }
}

Initially this works just fine. The image is uploaded and appears in the background of my block plugin. However overnight it's always deleted. I did see this post Set image as permanent in custom block plugin, temporary URI however I don't see anything different that would cause issues with my code against the one provided in that post. Is there something missing? Or is there anything wrong with how I'm performing the submit function.

I suppose I could try to check if the formstate value is a file and then load the file and then set it to permanent and then save it. But even if that works why would it be necessary in this case but not in others?

As you guessed its must to set permanent while saving the file. You need to include,
    $file = File::load( $fid );
    if ($file) {
      $file->setPermanent();
      $file->save();
    }

  The files will be added to the {file_managed} table as temporary
  files. Temporary files are periodically cleaned. Use the 'file.usage'
  service to register the usage of the file which will automatically
  mark it as permanent.


Displaying a list of image thumbnails, with click-through So, a few days ago I asked this question, Drupal 7 Site for Displaying PPT or JPG.  Since that time I have been studying up on Drupal 7 and learning more about what I REALLY want.

Here's what I am trying to do:

Upload a bunch of images (around 150)
Have a number of pages which list images including a thumbnail and comments.  (These pages are roughly 'image galleries', I think)
Let users browse each of the 'galleries'/lists, and click through on the ones they want to view in detail.  Also, users can add comments at this point.
If the user saves a comment or clicks a back button, they return to the gallery/list

So, I think I need to create a new content type for the images, including comments.  Then a View, which displays as a list.  Does this sound right?

Also, what's the best way to create each of the image nodes?  Do I need to use the Insert module?  And upload the images one by one?

Any pointers much appreciated!

Creating a new Image content type is a good way to approach this.  Views can certainly display the content as a list or a gallery-- or some combination of both-- but you may want to think about how you want to display the content in the gallery.

Comments are handled by Drupal out-of-the-box so I don't think you have much to worry about with regard to them.

You do not need to use the Insert module if you're just going to be uploading an image file.  If you're only going to be adding 150 images once, I would just create the image nodes one-by-one.  If you anticipate having to add lots of images regularly, you should post a separate question asking for a solution to that.

Here are some resources to get you started.

First, there's a screencast about building a gallery in Views.  Although this is for Drupal 6, and a fair number of things have changed in Drupal 7, the basic principles are the same.

Second, there are some helper modules which can give you pop-up and gallery-type effects without much work.  Two of the more popular, well-supported ones are:

Lightbox2
Colorbox

Either can be used on its own or with Views.


node_save() not working with LANGUAGE_NONE My question is exactly similar to the one posted here
https://www.drupal.org/node/2324047.

The answer posted here is not complete and I'm looking for a solution. I'm using the below code to save a node.

function api_add_getabstract($node_values, $api_endpoint) {
  //initialise node object
  $ex_node = new stdClass();
  $ex_node->type = 'getabstract';
  $ex_node->language = 'en';
  node_object_prepare($ex_node);
  dpm($node_values,'node values');

  //add field values
  $ex_node->title = $node_values['bookinfo']['title'];
  $ex_node->body['en'][0]['value'] = $node_values['recommendation'];
  $ex_node->body['en'][0]['format'] = 'full_html';
  $ex_node->field_authors['en'][0]['value'] = $node_values['bookinfo']['authors'];
  $ex_node->field_sub_title['en'][0]['value'] = $node_values['bookinfo']['subtitle'];
  $ex_node->field_publisher['en'][0]['value'] = $node_values['bookinfo']['publisher'];
  $ex_node->field_ex_cover_image['en'][0]['value'] = $node_values['bookinfo']['bookcoverOriginal'];
  $ex_node->field_ex_deep_link['en'][0]['value'] = $node_values['publicURL'];
  $ex_node->field_api_info['en'][0]['value'] = $api_endpoint;
  node_save($ex_node);
}

I tried by changing the value 'en' to 'und' and LANGUAGE_NONE, but none seem to save the node completely. Using 'en' at least creates the node with only Title field, but for the other 2 values, node is not even getting created.

I presume by your code example you use D7. And I presume by the error you get you don't use Entity Translation.

In D7 the built-in approach to offer multilingual content is called 'content translation'. Meaning you translate node by node. You hit the language switch and get redirected to another node.

Whereas in D8 the Entity Translation module now became part of core and so it replaced the 'content translation' approach by the 'entity translation' approach. Meaning you translate field by field. By providing a language key for every field. You hit the language switch and the same node reloads, but this time rendering the field values in a different language.

To come back to your question, as you don't use Entity Translation, you only have to set a language for the node (and possibly map it to their matching nodes in other languages). You MUST NOT specify a language for each field.

Alternatively, start using Entity Translation and configure the fields you want to be multilingual. Then, if I remember it right, your code will work.

Comparing both approaches, each has its pros and cons. And I already built D8 sites where we had to somehow rebuild a custom 'content translation' workflow (node by node translation), to get back the flexibility this has (especially in connection with Paragraphs – but that's a different story to be told).


How can I add form elements in custom form on click of link? I want to add form elements inside my custom form when some body clicks on the link outside the form. Links are like :

Add textfield
Add selectlist

When user click on any link it via ajax add an element to the form. I just want and idea whether it is possible or not in drupal. If it is possible then just give me some idea about this.

Thanks

You should take a look at Examples module or in particular the AJAX example
 https://api.drupal.org/api/examples/ajax_example!ajax_example.module/7 It's really helpful.


How do you force Drupal login to encrypt the credentials To make the Drupal login as secure as possible, we don't want to send the login credentials as clear text, but want to somehow encrypt the credentials or the entire request.

Ideally the solution should both for the actual login page, but also if the user logs in via the login block on any page.

You can't really do that.

Drupal 8 hashes and salts the password on the server side.Both the form and the authentication API require the plain password which is then validated. You should use HTTPS to protect the password during submission.

To be able to do something like this, you'd either need to use encryption, so you can decrypt again on the server or bypass the API somehow, but that isn't really possible since Drupal's hashing implementation has a dynamic salt and each hash has its own salt that you do not know in JS. Also keep in mind that anyone can read/debug the JS and figure out your salt or encryption key if you have it in JS.


Form processing issue while generating a dynamic form and preparing via API calls directly How can I fix the processing and submission of forms that I am preparing and rendering dynamically via API calls.

function drupal_set_confirmation($message, array $options, array $escape=array(), $type='warning', $details=NULL){
    $form = array();

    $form['title'] = array(
    '#markup' => '<h3>' . t($message) . '</h3>'
    );

    if (!empty($details)) {
        switch(gettype($details))   {
            case 'string':
                $form['details'] = array(
                    '#markup' => $details,
                );
            break;
            case 'array':
                $form['details'] = $details;
            break;
        }
    }

    if (!empty($options)) {
        $form['options'] = array(
            '#type' => 'container',
            '#attributes' => array('class' => array('user-confirmation-options')),
        );

        foreach($options as $key => $option) {
            $form['options'][$key] = array(
                '#submit' => array($option['callback']),
                '#type' => 'submit',
                '#value' => $option['title'],
                '#attributes' => $option['attributes'],
            );
        }

        if (!empty($escape)) {
            $form['options']['escape'] = array(
                '#markup' => l($escape['title'], $escape['path']),
            );
        } else {
            $form['options']['escape'] = array(
                '#markup' => l(t('Cancel'), current_path()),
            );
        }
    }

    $form_state = form_state_defaults();
    $form_id = 'form_user_confirmation';

    drupal_prepare_form($form_id, $form, $form_state);
    // I do not see any reason to call drupal_process_form while serving the form.
    //drupal_process_form($form_id, $form, $form_state);
    $rendered_form = drupal_render($form);
    return drupal_set_message($rendered_form, $type);
}

And it works greatly to show a dialog form of my own choice by calling.

drupal_set_confirmation(t('Do you really want to suicide?'), array(
        'okay' => array(
        'callback' => '_yes_kill_me',
        'title' => t('Yes'),
        'attributes' => array('class' => array('button', 'tiny')),
    ),
    ), array(
        'title' => t('No'),
        'path' => current_path(),
    ));

And callback function as #submit handler for a particular element is not invoked.

How can I fix the form processing and submission issue using this approach to work?

I fixed it this way, it started to invoke form submit handlers.

function MODULE_init() {
    if (!empty($_POST) && $_POST['form_id'] == 'form_user_confirmation') {
        $form_state = form_state_defaults();
        $form_id = 'form_user_confirmation';
        drupal_build_form($form_id, $form_state);
    }
}


How to integrate webform into multi form wizard into drupal 7 I am trying to integrate webform into multiform wizard in drupal 7. but its not working, i dont have any idea how to integer it. if it is not possible to integrate awebform into multiform wizard then is there any alternate solution to do the same like wizard format.

You could set the redirection path of the webform to your new form upon completion. By default it stays on the node page.


How to override Entity Autocomplete required validation error message? I have entity reference autocomplete field (which is term reference field )

users are not allowed to create new terms while node creation.

The validation error shows like below on form submit :

  There are no entities matching "newterm".

I need to override this message with something like "No new terms are allowed please select from existing terms"

When I tried to find code from where it is working it looks from this :

core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php and function where message is there : https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Element%21EntityAutocomplete.php/function/EntityAutocomplete%3A%3AmatchEntityByTitle/8.0.x

Please suggest how I can override this. I tried searching lot but was not able to find right direction and have tried overriding status message as well but sure how to proceed with this.

Thanks!

In HOOK_form_FORM_ID_alter() add #element_validate attribute to the form element

$form['field_your_field_name']['#element_validate']

Reference: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x#element_validate


How do I redirect a user role on login (Drupal 6)? So I want to create a new user role (already done) and redirect them to a certain page (and use a certain menu) when they log in.

I'm not seeing any specific place to do this under roles or permissions - does it need a third party module? I can give a list of the modules my client is using if that helps.

Note, this is in Drupal 6.

I'm not 100% sure since I don't have a D6 to test, but you should be able to do this with rules.

If there's a missing link in rules it's straight forward to code your own condition or action:

add your own action
add your own condition


How to create specific role permissions for authenticated users in Drupal 7 I'm developing a Drupal 7 based site. As an administrator of a site I want to add some specific access permissions for authenticated users.
By default in Drupal authenticated users can read the content. And they can view the author of content. I want to disable the feature of viewing the author, but only for concrete contents.
When an authenticated user creates content, I want to make him able to choose "creating a content as anonymous author", i.e. other users can read and comment that content, but unable to see it's author.
And additionally this feature shouldn't affect quantity of content posted by that user. When the user creates content it will be incremented in "Number of content created by this user", whether content was created as "anonymous author" or not.
I've looked up in "People > permissions" , but couldn't find a permission like that. I know a little PHP, so if the answer requires a knowledge of PHP, go ahead.

You could have a look at User points module, you also need userpoints_nodelimit, part of User Points Contributed modules to limit the number of nodes a specific user is allowed to create. For the deletion of nodes you'll need the rules modules so you can give the user a point back.

You could write your own implementation, but depending on your skills this might be harder, in short you need to implement:

an access callback where you check the user and the number of available points
use hook_menu_alter to replace the access callback of 'node/add'
implement hook_node_delete and hook_node_isnert to change the counter


How to control CSS cascade? I've got a module building/theming question I was hoping to get some help with today?

I'm building two custom modules that create their own pages to be displayed on. Adding CSS and JS though "drupal_add_css" and "drupal_add_js" has worked just fine.
the problem I'm having is that the CSS/JS is not the last CSS/JS that gets added when the page is called.
The theme css is still being called last and overriding some of my styles.

So my questions are: can I unset the theme css from the module for the page where my mod appears? is that the right way to do things? or would it be better practice to rename my IDs/classes where conflicts occur?

Thanks!

Stephanie

The theme layer loads after your module has, so you won't be able to modify that part yet. I think you can just set the weight on your functions: http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7

Or just rename your ID's and classes to be specific to your module to reduce conflicts. I usually would name my ID's or classes nothing to generic, usually a shorthand for the name of the module then the name of the id or classes i want to reduce conflict.


How to troubleshoot general module issues? My site has a somewhat complex setup, so I therefore have a good number of modules installed. As a result, sometimes different things will randomly stop working, and I am not sure what exactly the cause was. Posting in issue queues can only go so far, and I'd like to start learning how to troubleshoot these problems myself.

For instance, I'm currently using Entity Reference Prepopulate to help prepopulate fields in a "Review" entity type. I'm also using LoginToboggan to redirect users to a login page when they don't have permission to view the current field. Upon login, they are supposed to be redirected to the last page that they were on. So, with Prepopulate, the URL is something like http://www.gigindie.com/node/add/review?field_review_venue_reference=235, but after logging in with the LoginToboggan login form, the user is redirected back to http://www.gigindie.com/node/add/review instead of http://www.gigindie.com/node/add/review?field_review_venue_reference=235, which does not include the Prepopulate portion of the URL.

Obviously the above example is a specific use case, and help with that would be appreciated, but this question is a more general one. How do I go about figuring out why a module might not be working, and which other modules are conflicting with it, if any? Are there any tactics that would help specifically with troubleshooting module malfunctions?

My first port of call is usually the reports in /admin/reports, in particular 'recent log entries' (use the filters) and 'status report'. Also the PHP error logs on the server can be useful.

Also, keep an eye on Javascript errors by using your web browser's javascript console/log, as you attempt to do the broken activity.


Why does my D7 User view only display 6 results in Block View, but all results in Page view? I have a simple  D7 view that lists all usernames and a couple of associated fields (business name, contact name) in table format.  It has exposed filters on those fields, and about 200 users to list, sorted by creation date.

In Page View, this works perfectly as expected : I can page through a list of active users, and filter them.

However, when I try to embed the same view as a block, it displays only 6 results and no pager or exposed fields.

I've changed the pager ID - didn't help.  I changed the pager ID on the other block shown with this one, too.  I have no contextual filters or relationships set up. I tried changing to 'show all results' without a pager - still just those six results.

Any thoughts on where to start looking to fix this?

ETA
I checked the queries being run, and as suggested, they turn out to be different in page view to block view.

This is my page view query:

SELECT users.name AS users_name, users.uid AS uid, users.status AS users_status,
 users.created AS users_created, 'user'
AS field_data_field_business_name_user_entity_type
FROM
{users} users
WHERE (( (users.status <> '0') ))
ORDER BY users_created DESC
LIMIT 30 OFFSET 0

But my block view query is different, all the exposed filters are applied, and I can't change them:

SELECT users.name AS users_name, users.uid AS uid, users.status AS users_status,
users.created AS users_created, 'user'
AS field_data_field_business_name_user_entity_type
FROM
{users} users
LEFT JOIN {field_data_field_business_name} field_data_field_business_name
ON users.uid = field_data_field_business_name.entity_id AND
(field_data_field_business_name.entity_type = 'user' AND
 field_data_field_business_name.deleted = '0')
LEFT JOIN {field_data_field_contact_name} field_data_field_contact_name
ON users.uid = field_data_field_contact_name.entity_id
AND (field_data_field_contact_name.entity_type = 'user'
AND field_data_field_contact_name.deleted = '0')
WHERE (( (users.status <> '0') AND
(field_data_field_business_name.field_business_name_value LIKE '%%' ESCAPE '\\')
AND (field_data_field_contact_name.field_contact_name_value LIKE '%%' ESCAPE '\\') ))
ORDER BY users_created DESC
LIMIT 30 OFFSET 0

A good way to start understanding what happens is to turn on the Show the SQL query option  in the basic view settings under admin/structure/views/settings. You can then copy-paste the generated query into your database application and check if the query catches all expected results. If yes, then the problem most probably happens during the rendering of the results, maybe a custom views block template (check the theme overrides for the views display)? If no, then there is probably something wrong with the query itself, which could be either some kind of filtering, or maybe a contrib module that alters the query from code.


How do I populate a webform component with a %_GET variable token? I have webform 4 enabled. I just created a textfield component and set its default value to %get[my-key]. But the token is not working at all. I also tried with %_get[my-key] and [%get[my-key]] but is not working neither.

As far as I understand Webform 4 in not working anymore with POST variables in favor of GET variables.

How can I get the GET variables?

I use tokens to get keys from the URL. The token for the %get variable would be [current-page:query:?], where the ? = the query name in the url. For example, if your url is mysite.com/page?foo=bar, you would use [current-page:query:foo] to return "bar".


Choose header content from entity-reference dropdown? Been struggling with this for a while... I know there is probably a fairly easy way to accomplish it but I haven't been able to figure it out.

The goal:
When a user creates a new page for the site, I would like them to be able to choose from several different headers using a drop-down list. I know I can set up blocks for the different headers and use the built-in functionality to have them appear on different content types or pages, but for various reasons I would like to have the header as a custom field within the page content type.

I have created a "Header Content" content type and used the Entity Reference module to populate a select list field in the page content type. I can display the selected option or the rendered entity it refers to in the body of my page without any trouble.

What I can't figure out is how to display the rendered entity in the header section instead of the main content.

Put another way: When creating a new page or editing an existing one, the user should be able to select existing nodes from a drop-down list (this part is done). The selected node should show up in the header region (this part is giving me trouble).

I think it could be accomplished in one of two ways:

1) Using Views:
I tried creating a views block to read either the reference or rendered content from the parent page and display it in the header (or wherever I place the block) but I can't seem to get the relationship right.

2) Using a custom module
This seems pretty straightforward but I'm not sure how to reference the value of "field_header" (the name of my custom field using hooks. I'm also not sure if the data will be available if I configure field_header not to display in the configuration.

This seems like a problem that's likely to be solved already. Maybe I'm not phrasing it correctly when I search because I haven't been able to find any examples to help me solve it.

What I'm 99% sure you want is the Header Image module. It works by being able to select a piece of (node) content to place in some region thats been pre-defined.

Eg, put an image in some header region of your site. Or text or whatever ....


Show table header in views (Bootstrap table) I need to show header table in a view (bootstrap table) like: title, image, descripton, etc. But i can't find the option. I compare this view to an old one and everything seems normal. Any idea? Thanks!

You can check if your label of the row is enabled or checkbox is checked which shows Show Label. Go to fields in view, and click on any field, you can see that option.


Have conditional fields in entityform So it's my first time using entityform module which is awesome to create an order form.

Within my form, I have an "Entity Reference" field which prepoppulating as checkboxes from my "Node: Products".

in my order form now I have my node:title to choose from, what I want is that another field appear IF the user select one.

mainly I want the user to be able to select/check the product name then provide the amount he is ordering with another textfield or something.

I tried conditional fields module which is in dev version to make it works!

  Conditional fields module, define dependencies between fields based on their states and values.


Possible to have 2 contextual filters with "or" rather than "and"? I would like to create a view that shows all nodes created by the currently logged in user OR where the currently logged in user has commented on.

D6 had a views_or module but it's not ported to 7.

Are there any simple solutions?

OR is built in Views 3 (see this issue) with a rather pleasant interface.

But for what you need, you can do this with a single filter: "Content: User posted or commented - Display nodes only if a user posted the node or commented on the node."

Views 3 AND/OR filter interface:


How to add a class to the webform error message When people fill in incorrectly in my webform, the error message will output as follow, e.g:

  ×

Error message

Name* field is required.

Email field is required.

Contact No. field is required.

Comment field is required.

Now, I wonder is there way I can add a CSS class to this message so that I can target this particular message that fired by this particular webform. e.g

 ........

or even more specific, add the ID to the message .e.g

  ....

I think the short answer is no, since the errors set in the error message box could come from any source, meaning the errors in that <div> aren't necessarily just your webform errors. Since it looks like you're using your webform as a block I'm guessing you can't target a body class to check if you're on a particular page type either.

If you were setting your own error messages you could add a <span> around the message with your custom class, but that would mean bypassing the validation handling webforms provide.

One possible solution would be to use JavaScript to find <li> elements that have text matching the error messages you want to style and moving them to a custom container. Another could be creating a YOURTHEMENAME_status_messages() function in your theme's template.php and doing a regular expression or string comparison to output specific error messages in a separate container. This route would affect all error message using the same text though, so it could affect an error message that was not from your webform.


use-ajax class for ajax link not working in dynamic content load use-ajax class link not working when i load new content using custom ajax code, which has the use-ajax class links.

I use normal jquery ajax to load the content because, i have drag and drop functionality which use ajax to load new content

i tried a lot but didn't get the idea why it is not working

Thanks in advance

jQuery(".clips-list .section-add-clip").droppable({
        accept: '.mysrapbook-clip-drag',
        hoverClass: "ui-state-active",
        drop: function(event, ui) {
            var source_url = ui.draggable.find('a').attr('rel');
            var destination_url = jQuery('.scrapbook-mongo-id').data('scrapbooid');
            var section_idx = Number(jQuery(this).attr('rel'));
            var ul_container = jQuery(this).parent().parent().find('li.clips-inner');

            var post_data = {
                source_url: source_url,
                destination_url: destination_url,
                idx: section_idx,
                load_node: 1,
                index_countr: ul_container.length
            };
            var ajax_data = jQuery(this);

            //call ajax to save clip to haggadah
            jQuery.ajax({
                url: "/clip-to-page",
                data: post_data,
                type: 'POST',
                success: function(data) {
                    //console.log(data);
                    console.log(data);
                    if (data[1].data != "") {
                        ul_container.last().after('
' + data[1].data + '
');
                    }
                }
            });
        }
    });

here is the code where i fire ajax to load new content and that content has 'use-ajax' class link which is not working it works fine page page is loaded

Did you use Drupal.behaviors?
Javascript event listeners that are attached to DOM objects at the jQuery(document).ready event won't be attached to ajax-loaded stuff. Drupal.behaviors sort that out for you.


Create top 5 of selected options I would like to create a top 5 of selected options from a webform.

As users fil in the webform i would like to create a view with the top 5 selections of the list.
How can i do this with views?

Example: i have a webform with 5 options.

a,b,c,d,e

User get a dropdown to choose 1 or multiple options.

When 10 users have filled out the form these are the results

option a is chosen 4 times
option b is chosen 7 times
option c is chosen 2 times
option d is chosen 1 time
option e is chosen 9 times

How can i create a view that show this

Top 5 of selected options:
Option e
Option b
Option a
Option c
Option d

Kind regard Kevin

You can create a view with webform type. Then add a Global PHP field in header.

<?php
$nid=62;
$option1_count=0;
$option2_count=0;
foreach($results as $results1) {
    $each_submission=webform_get_submission($nid, $results1->sid);
    //print_r($each_submission->data);
    if($each_submission->data[1][0]==1) {
        $option1_count++;
    }
    if($each_submission->data[1][0]==2) {
        $option2_count++;
    }
}
$top=[$option1_count,$option2_count];
arsort($top);
?>

I haven't tested this code but something like this should work.

EDIT:

You can make that code generic but if you don't want that then use grouping and aggregation in views and try Views Distinct

First add field Webform submission data:Value(your webform field) and set aggregation to yes. This will help.


Transfer Value of Field to Another Field under Content Type Manage Fields I have created several content types and unfortunately, I made a mistake on some of the fields. The fields are field_image and field_screenshot.

Under manage fields, I use field_image and sometimes field_screenshot. Now I want to use one field only for featured image on my node content. So, how can I transfer the value of field_image to field_screenshot? Is this possible?

No, this is not easily possible through the Drupal interface. You will need to execute a custom SQL query to move your data from one field to another.

The following two queries will copy all field data from field_image to field_screenshot for each entity where field_screenshot is empty.

INSERT INTO field_data_field_screenshot
SELECT a.*
FROM field_data_field_image a
LEFT JOIN field_data_field_screenshot b ON a.entity_id = b.entity_id
AND a.entity_type = b.entity_type
WHERE b.entity_id IS NULL

and

INSERT INTO field_revision_field_screenshot
SELECT a.*
FROM field_revision_field_image a
LEFT JOIN field_revision_field_screenshot b ON a.entity_id = b.entity_id
AND a.entity_type = b.entity_type
WHERE b.entity_id IS NULL

After running this you can then delete the first field.

If field_screenshot alreadly has data that you want to overwrite you will need to  delete it first using these queries. Make sure this is what you want to do first because this WILL delete your data

TRUNCATE TABLE field_data_field_screenshot
TRUNCATE TABLE field_revision_field_screenshot


Prevent Multiple user registrations from single IP I'm using Drupal 6.19.I need two things to be done.First thing, I want to disable multiple user registrations from the same IP.The Second thing is ,I want to allow only 3 user to register at a time.
Anyone know this how to do in Drupal6.19?

Please help me to do this.

You may find the problem there is that Drupal doesn't store the IP address of the user during normal core registration process.

Assuming you can hook in and store that IP address for later lookup, you could then validate that ip address count for the user with something like:

/**
 * Implements hook_form_FORM_ID_alter
 */
function mymodule_form_user_register_alter(&$form, &$form_state) {
  $form['#validate'][] = 'mymodule_user_register_validate';
}

/**
 * hook_form_user_register_alter validation callback
 */
function mymodule_user_register_validate($form, &$form_state) {
  $account = (object) $form_state['values'];
  $ip_address = ip_address(); // api call
  // do something to look up ip_address on registered user..
  // for example:
  $count = db_query("SELECT count(uid) FROM {user_ip} WHERE ip = :ip", array(':ip' => $ip_address))->fetchField();
  if($count > 3){
    $error = t('Sorry, too many registrations.');
    form_set_error('name', $error);
  }
}


How to print the prices node.tpl.php? I installed the Commerce Price Savings Formatter module. Can you explain me how to display the price in a file node--scs.tpl.php? it is for a newsletter.

When I put

 <? php print render($content[ 'product: commerce_price']); ?>

It displays the full price with the original price, percent discount and the reduced price.

I want to display each item in the "td" separate.
I tried

<? php print render($content['product: commerce_price: Trade-price-savings-formatter-savings']); ?>

But it does not work.

thank you in advance

Calling render($content[...]); renders the field—but you need to change how the field is being rendered. To do this, you'll need to modify it's display widget.

Go to Admin→Store→Configuration→Product types→Product type→Manage Display. Then, on the price field, change the the formatter (the first arrow):

This can be further configured by clicking on the gear icon (right arrow) to get access to more configuration.

If this still does not suffice, try these:

Add a HOOK_commerce_price_savings_formatter_formatter to your theme to override the theme provided by the module.
Create a new formatter (the price saving formatter modules can be used as an example) and then use that formatter to display your prices.


Edit button on the top right menu disappeared, how can I get it back? Put my website in development mode in the past but I'm having a hard time finding the setting to re-enable the in field editing of nodes.

Which configuration setting is responsible for toggling the edit button in the top right corner and the pencil icon on blocks and content?

Edit:

I found out there are many javascript errors, check the screenshot here.

The issue was caused because of an unclosed div tag in multiple blocks on my site. If you have this issue check all related twig templates, blocks and content for unclosed HTML tags.


How to set the default format in text_format and hide the select? /**
 * Implements hook_form_alter().
 */
function MODULE_NAME_form_alter(
  &$form,
  \Drupal\Core\Form\FormStateInterface $form_state,
  $form_id
) {

  if ($form_id == 'node_article_form') {
    $form["body"]["widget"][0]['#allowed_formats'] = ['full_html']; // Your default format
    $form["body"]["widget"][0]['#after_build'][] = 'MODULE_NAME_hide_format';
  }
}

function MODULE_NAME_hide_format(
  &$element,
  FormStateInterface $form_state
) {
  if (isset($element["format"]["format"])) {
    $element["format"]["format"]["#access"] = FALSE;
  }

  return $element;
}

The module suggested (in comments above) seems interesting, but if you want to do it with code only for body field and you don't want to use the module,
you can use hook_field_widget_form_alter instead of hook_form_alter.

Try this:

use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldConfig;

/**
 * Implements hook_field_widget_form_alter().
 */
function MODULE_NAME_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
  $field_definition = $context['items']->getFieldDefinition();

  // Base fields are not configurable.
  if (!$field_definition instanceof FieldConfig) {
    return;
  }

  if ($field_definition->getName() === 'body'){
    // Set only full_html as allowed format.
    $element['#allowed_formats'] = ['full_html'];
    // Add after build to remove the help wrapper and text.
    $element['#after_build'][] = 'MODULE_NAME_after_build';
  }
}

/**
 * @param array $element
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *
 * @return array
 */
function MODULE_NAME_after_build(array $element, FormStateInterface $form_state) {
  // Remove Guidelines and Help text.
  unset($element['format']['help']);
  unset($element['format']['guidelines']);
  unset($element['format']['#type']);
  unset($element['format']['#theme_wrappers']);
  return $element;
}


hook_module_preuninstall doesn't run early enough Uninstalling my module threw this error:

[error]  my_module: The My Field field type is used in the following field: my_module.my_field

But, since my module defines both an entity and a field, both of which will be uninstalled when I uninstall this module, it doesn't make sense.  I'm trying to handle this by removing all of the fields programmatically in hook_module_preuninstall, which I have in the .module file because it wasn't working in the .install file.

The problem is, this hook runs after the checks for field dependencies.  It would make more sense if it ran before, in my opinion, but, what can I use to get ahead of these checks?  Anything?  If not, what should I do so that my module realizes it needs to uninstall these things when the module is uninstalled?

Also, shouldn't this hook run earlier?  If not, what is the point of it?

Yes, there is currently no hook to do this.

The only thing you can do is have your own custom uninstall form that allows you to prepare the uninstall by deleting all data and then delete the field through the API, then point the user to the uninstall form.


how to set cron correctly on a shared server I set the following command for cron on a shared server.

/usr/bin/php5.3 home/public_html/cron.php

(All the Drupal files are under /public_html)

This commend seems to be working but I get the following error

PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/public_html/sites/default/settings.php:1) in /home/public_html/includes/bootstrap.inc on line 1163
Sorry,  has been banned.

Am I missing something?

Looks like perhaps you settings.php file has some extra characters outside of the


Adding taxonomy term list to another taxonomy term's overview Let me start by saying I'm fairly new to Drupal. I'm using Drupal 7.

I have a content type "product" which is assigned to one or more taxonomy terms in "collections" (taxonomy). Then I have another taxonomy called "brands".

The "brands" taxonomy has a field reference to a "collections" taxonomy term. For instance: brand "Google" can be assigned to collections "Shoes" or "Bags".

On the collection page for "Shoes", all the products tagged "Shoes" are being displayed. On top of the page, I want to add a list of all the brands in the "brands" taxonomy, that are assigned to this particular collection ("Shoes"). They are independent from the products themselves. How would I display this list on top of the page? Do I need to create a custom overview?

In this case you need to a create view that displays block on top of the collection page.
The view should display taxonomy terms in the "collections" vocabulary filtered by a contextual filter (taxonomy term id) so that only the desired taxonomy term is display.
Next you should add a relationship using the field reference you're using on that term.
Finally you can use the relationship to display fields or taxonomy terms to the display.

I tried to explain it briefly, let me know if you need further explanation.


Create a view to display the list of content created by user and any published content I am creating view for displaying content list and some exposed filters. I wanted to display all published content of any user and all content created by user(current user).
Currently i am able to display only own content list by using contextual filter:

Click "Advanced" > "Contextual Filters"
"Add" > "Content: Author uid"
"Provide default value" > "User ID from logged in user"
Save

How can i display in list a combination of All published contents from all authors + published and unpublished contents of logged in user?

You anyway want to display all content from all the authors and current user so no need to add contextual filter, then it's going display all the content from your site with logged in user's content too.

Also you can try this link


Granting access based on an entity reference field using rules I have two content type one called audit and one called non-conformance, a non conformance is raised after an audit has been complete.

An audit contains an entity reference field called auditee which references a user, I would like to give edit access to the non conformance based on the the content of the auditee field in on the content type audit.

Thanks

This should do the trick for you. You only have to write the code for extract_uid_from_audit(); if you don't know how we can help as well.

function mymodule_node_access($node, $op, $account) {
    if(!empty($node->type) && ($node->type == "non_conformance")
             && $op=='update') ){
        $uid = extract_uid_from_audit($node);
        if($uid = $account->uid)
             return NODE_ACCESS_ALLOW;
    }
}


How to automatically add new users to a OG Group (MyCommunity) using Rules? This is a configuration task.

it continues the request here:
Automatic add user to organic groups

Task

Using Rules UI: all new users are automatically members to group MyCommunity

Steps

Events: After saving a new user account
Conditions : none
Actions: OG: Add entity to a group

But how to configure data selector to get a specific group: MyCommunity?

UPDATE

Apparently there is no clean way to do that other by a patch: https://drupal.org/node/1706884

One of the elements you can use under actions is "Fetch entity by id". Say the node id of your MyCommunity group is 10, then the Entity type value will be Node, and the Identifier value is 10. In the Provided variables section, you give your fetched entity a label and variable name. Let's give it a label of MyCommunity, and name it my_community. Save the action element. The next action element to add is "Add entity to group". The Entity data selector is the new user so give it the value of "account". Then under group, the data selector is the variable name we created in the previous step, which is "my_community". I tested this out locally and it worked. Here's an export of the rule.

{ "rules_115407" : {
    "LABEL" : "115407",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "stackexchange" ],
    "REQUIRES" : [ "rules", "og" ],
    "ON" : { "user_insert" : [] },
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "node", "id" : "10" },
          "PROVIDE" : { "entity_fetched" : { "my_community" : "MyCommunity" } }
        }
      },
      { "og_group_content_add" : { "entity" : [ "account" ], "group" : [ "my_community" ] } }
    ]
  }
}


Managing module library dependencies with composer I've found Dependencies in a custom module with drupal-composer, How can I include a third party library in my custom module without using Composer Manager and How to manage contrib modules composer dependencies on drupal 8 which are releated to my question, but no longer seem to apply since Drupal 8.1 and the deprecation of Composer manager.

Also popular guides such as The definitive introduction to D8 and Composer appear to no longer apply as they also mention composer manager.

The other solution opposed to composer manager, alter the core composer.json file feels like too much core hacking and would probably break with every Drush update of Drupal core(?).

More specifically, I am attempting to update Views vCards from Drupal 7 to 8. I have created my composer.json file as follows:

{
  "name": "drupal/views_vcards",
  "description": "Allows creation of vCards using the fields provided by the Views module.",
  "type": "drupal-module",
  "license": "GPL-2.0+",
  "homepage": "https://drupal.org/project/views_vcards",
  "require": {
    "maennchen/zipstream-php": "0.3.*"
  }
}

But if I put a composer.json file in my module folder, how do I make Drupal aware that that file is there, and how do I make sure the required zipstream-php library is downloaded?

Simply running composer update from the Drupal root does update a lot of Drupal dependencies, but it does not include the composer.json files that are in the modules folders. I also don't assume I should be calling composer install from inside all modules with dependencies.

How do I make Drupal aware of a module's dependency without using composer manager and/or hacking core?

UPDATE:

The composer merge plugin used by core appears to have support a wildcard path:

{
    "require": {
        "wikimedia/composer-merge-plugin": "dev-master"
    },
    "extra": {
        "merge-plugin": {
            "include": [
                "composer.local.json",
                "extensions/*/composer.json" // < ---- THIS LINE
            ],
            "require": [
                "submodule/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-dev": true,
            "merge-extra": false
        }
    }
}

Why doesn't core merge modules/*/composer.json, that would solve everything right?

Update 2:

THe reasoning for not supporting this is covered in this issue (which also has been quiet for some time now).

New method using drupal-scaffold for greatest flexibility

For Drupal 8.4.0 and greater using drush >9.0.0, drush make is deprecated and you should use a full-composer work flow as detailed in the drupal.org documentation links below. Those links do recommend using a composer project, but this may not work for everyone's web server setup. The following is step-by-step how to setup composer.json manually for detail explanation. The instructions regarding adding modules manually can still be done.

# Initialize composer. Stability alpha is important for custom modules that may be source managed outside of packagist or drupal.org
composer init --name myvendor/mysite --stability=alpha --license=GPLv2
composer config repositories.drupal composer https://packages.drupal.org/8
composer config discard-changes true

Then you need to add to composer.json manually the following based on your preferences because there is no way to do so automatically with composer as-is. These will configure drupal-scaffold to install your modules where you want them (as opposed to in vendor/ or a directory chosen by some other developer). Change 'webroot' to 'www' or 'public' or what your host is.

    "extra": {
        "installer-paths": {
            "webroot/core": ["type:drupal-core"],
            "webroot/modules/contrib/{$name}": ["type:drupal-module"],
            "webroot/modules/custom/{$name}": ["type:drupal-custom-module"],
            "webroot/themes/contrib/{$name}": ["type:drupal-theme"],
            "webroot/themes/custom/{$name}": ["type:drupal-custom-theme"],
            "webroot/profiles/{$name}": ["type:drupal-profile"],
            "webroot/libraries/{$name}": ["type:drupal-library"]
        },
        "patches": {}
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold"
    }

Now you can install some dependencies. Note that composer must be able to use scripts and plugins for this to work.

composer require composer/installers:^1.4.0 drupal-composer/drupal-scaffold:^2.3.0 cweagans/composer-patches:^1.6.2

Run the drupal-scaffold script once (or on your build server as needed):

composer drupal-scaffold

Drupal core, modules, themes, etc... can be installed as per the instructions below without the drupal-merge-plugin.

composer require drupal/core:~8.5.1 drupal/views_vcards

Older method using drupal-merge-plugin or working with core directly

For Drupal 8.1.0 and greater, you can use composer to require Drupal modules directly. The documentation around Using Composer in a Drupal project and Using Composer to install Drupal packages through Drupal.org has been updated to take advantage of drupal.org's packagist. I find it works well already in a deployment scenario.

composer config repositories.drupal composer https://packages.drupal.org/8
composer require drupal/views_vcards

For development, I think that manually adding in the dependency with composer require works fine. The merge approach works too with the drupal-merge-plugin and I use this for my drush make work flow.

composer config repositories.drupal composer https://packages.drupal.org/8
composer require mile23/drupal-merge-plugin
composer update

Update 2016.06.22

I ran into an issue using drush make, which added the traditional Drupal version tags and drupal.org packagist URLs using semver. To that end, I needed to switch to using the stabler packagist at https://packagist.drupal-composer.org, which still supports the traditional Drupal version tags.

Also note that the build server or machine requires an exorbitant amount of memory to do a composer update (or require), which is necessary in all scenarios where running composer update on a similar development machine is not possible in your build process.

Update 2016.09.23

Added link to Using Composer to install Drupal packages through Drupal.org.
Added onto the development section about how I use it with drush make.

Update 2018.03.30

Noticed an up vote. This is fairly old so decided to clarify about more recent development and setting up your site directly with composer since drush make has been (sadly) deprecated for a while.


Using Drush on a Drupal 8 site installed via Composer I had a Drupal 8 project installed from Drupal 8 sources what had been downloaded from Drupal 8 site. Recently I heard a good thought that it would be more comfortable to have the project originally installed via Composer. I did the migration and now the project has a structure likewise installed via Composer. That is, it has the "web" subdirectory with Drupal 8 files, the "vendor" directory isn't included in Drupal files and so on.

The site worked successfully after migration.

However, I ran into a problem. Namely, after migration, I couldn't use Drush on the project. The following error appeared upon trying to execute a command "drush cr".

Command cache-rebuild needs a higher bootstrap level to run - you will need to invoke drush from a     [error]

more functional Drupal environment to run this command.
Command cache-rebuild requires Drupal core version 8+ to run.

My colleagues advised me to install Drush-launcher from GitHub as a shell for original Drush. I did it, this problem seemingly disappeared. But I ran into a next one. Namely, Now I can't use Drush for projects made on Drupal 7.

Could you clarify me, is it possible to set up original Drush for sites installed via Composer and without using the Drupal launcher?

Acquia Dev Desktop comes with Drush included, and I assume that you could just continue to use that for Drupal 7. However, since you installed Drush Launcher and are using it as drush (drush.bat), you are shadowing it. Break the shadowing by renaming one of the two.


Best way to create a property of an association in Drupal 7? I have a node Theater, and a node Movie, and a Theater can have X movies and for each movie at that specific theater there are Y showtimes. How can I set up the property "showtimes" of the association of Theater to Movie within Drupal?

Look into Field Collection:

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

You can then create:

a content type Movie. You could have fields like a Poster image field, Title, Cast, synopsis, and then a Showtimes field collection.
Then have a content type Theater. Which is a theater. It can have fields like geolocation, a picture of the building, a description, hours of operation, etc.
Then your Showtimes field collection is itself a multi-value field which contains 2 fields: an entityreference to a Theater, and then a multi-value collection of times (maybe look at event module).

Using Views you should be able to list movies, Theaters and their movies, Movies at a certain time -- etc.

How to integrate this all into the Commerce module or something ... I leave this as an exercise for you.

I don't guarentee this is the best way to build the relationships between data you want. Another alternative to field collection and even the entities could be the Relation module.

EDIT:

If you want to easily create like a Theater that doesn't exist yet for a Movie (when making a movie entry) look at the Inline Entity Form module.


Statistics per node only visible to node author I want a simple block (or it could be attached to the content, I don't really care) displaying how many hits a node has had, visible on the node itself, and only visible to the user who created the node (and admins obviously).

Any easy way to do this?

The Google Analytics Reports modules offers blocks that will report on individual pages. Wouldn't this off-load the stat works to Google?


RSS Feeds: Using Aggregator (Drupal Core) vs Feeds module - which has more features and is more reliable? RSS Feeds: Using Aggregator (Drupal Core) vs Feeds module - which has more features and is more reliable?

It looks like Feeds has more features. Is this true? and is it more reliable?

Answering my own question, I would be inclined to say Feeds module, on the basis of:

more integration with other Drupal entities allowing more possibilities for manipulation of the content
extensibility - ability to extend with extension modules that parse the XML content of the feed to re-purpose it. e.g. rather than a text list of youtube videos, the actual videos themselves embedded into the page
standard api for extensions
well supported and active in drupal 7


How to Modify Drupal 7 Bootstrap Theme Title? I cannot find where to modify the title from:

SiteName | SiteSlogan

to

SiteName - SiteSlogan

I am using the https://drupal.org/project/bootstrap theme.

Anyone have any ideas?

This thing is come under $head_title variable on html.tpl.php.
So for changing this you need to override template_preprocess_html
where replace statement
$variables['head_title'] = implode(' | ', $head_title);
with
$variables['head_title'] = implode(' - ', $head_title);
I am assuming you have enough idea about overriding of templates.


How we theme created view in Drupal 8 I created a view in drupal 8.
Name home page client view block &
machine name home_page_client_view_block.
Now I want to theme this view.

Try using:
Views Templates

Creates the views templates functionality which was removed in D8
views.

(have not used this myself, as I haven't made the jump to D8 yet).


How to hide the text formats help text? I want to hide the description of the text format under the "Comment" box which says:

No HTML tags allowed.
Lines and paragraphs break automatically.

There are a variety of ways to do this on Drupal 7, but what about Drupal 8?

AFAIK there is currently no core UI to control showing/hiding of those tips.

Th simplify module, one of the D7 choices you link to, has a D8 port that may still help with this.

The Allowed formats module is an incubator for future core improvements in the area of giving sitebuilder's UI control over text format and their help tips.

== UPDATE ==

A patch just committed to that module gives sitebuilders considerable control over help tips, using UI settings on the widgets.

== OLD ==

There are a couple of relevant issue in the issue queue for that module:

Allow to control if "About text formats" link should be shown or not

Allow to hide text format help text for Text(formatted)

The first of those issues contains this code from floretan, which points in the direction you would need to go to hide the help by custom code:

<?php
/**
 * Implements hook_field_widget_form_alter().
 */
function allowed_formats_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  if ($context['widget'] instanceof \Drupal\text\Plugin\Field\FieldWidget\TextareaWidget) {
    $element['#after_build'][] = '_allowed_formats_remove_textarea_help';
  }
}

/**
 * #after_build callback.
 */
function _allowed_formats_remove_textarea_help($form_element, FormStateInterface $form_state) {
  if (isset($form_element['format'])) {
    // All this stuff is needed to hide the help text.
    unset($form_element['format']['guidelines']);
    unset($form_element['format']['help']);
    unset($form_element['format']['#type']);
    unset($form_element['format']['#theme_wrappers']);
  }

  return $form_element;
}
?>


What is the purpose of a configuration schema file? I created a /config/schema/drupolo.yml file with the following content.
drupolo.social_network.setting:
  type: config_object
  label: 'Sacd Menu module settings.'
  mapping:
    facebook_page:
      type: string #Type: can be string | integer |  boolean
      label: 'Facebook page'
    twiiter_page:
      type: string
      label: 'Twitter page'

I created the /config/install/drupolo.social_network.setting.yml file with a key that doesn't exist in the schema file.
The problem is that the module is installed and the configuration is stored in the configuration table, and it doesn't respect the schema file.
facebook_page: 'https://facebook.com/default'
twitter_page: 'https://twiiter.com/default'
linkedn_page: 'http://linkedin.com' # key that don't respect the "drupolo.social_network.setting" structure that has been declared in the drupolo.yml

What is the purpose of the /config/schema/{module}.yml file if the config/install won't respect that structure?

Drupal does not check the configuration schema at runtime when the configuration is loaded - the configuration is assumed to be correct.
The schema is used in the tests - when running tests, configurations are automatically validated against the schema to ensure they are correct. Presumably you have developed your module with tests, and by the time you make your module publicly available you will have your tests running and verifying that the configurations you are shipping are valid.
The contributed config_inspector module is very useful for validating and debugging configuration and configuration schema.


In views, how can you link "read more" to the webform submission? I have created a view from webform submissions but some of the answer in the submission are too long. I tried to add a "read more" link in the view to be able to view the rest of the answer but I'm not sure which path to give it. When I do node/[nid], as you would with a content type, it goes back to the blank webform.

I believe the link should be node/%nid/submission/%sid/view.

Where %sid is the webform submission id.


How to log to console when in a Drupal attach behavior? I'm using Drupal 7. I have the following code that tries to log to the console:

function mymodule_get_jquery() {
  $jquery = <<<JAVASCRIPT

  console.log("here");

  (function($) {
    console.log("there");

    Drupal.behaviors.addHighStockChart = {

      attach: function(context, settings) {

        console.log("everywhere");

        /* ... */

      } // end attach
    } // end Drupal.behaviors.addHighStockChart
  }) (jQuery);

JAVASCRIPT;

  return $jquery;
}

If I open the Console in Firefox or Chrome, the log outputs the following:

JQMIGRATE: Migrate is installed, version 1.4.1
here
there

Why isn't the "everywhere" line getting logged? Is there any way to log JavaScript info in the Drupal behavior attach function?

UPDATE:

Here is how I am calling the mymodule_get_jquery() function:

/*
 * Implements hook_page().
 */
function mymodule_page() {

  /* ... */

  $jquery = mymodule_get_jquery();
  drupal_add_js($jquery, "inline");

  /* ... */
}

Drupal object should be passed as function parameter like below:

(function($, Drupal) {
    console.log("there");

    Drupal.behaviors.addHighStockChart = {

      attach: function(context, settings) {

        console.log("everywhere");

        /* ... */

      } // end attach
    } // end Drupal.behaviors.addHighStockChart
  }) (jQuery, Drupal);


Cron job run, but module updates not checked - how to automate? I configured a script to run as part of my cron.daily tasks, and tested the script.

My status report says that the cron was correctly run by the script, so I'm happy that that will happen.

However, I went to the available updates page, and it still says that I last checked 17 hours ago - isn't this part of the cron?

Is there a way I can include this in the automated checks and reporting?

Looking at the code of update_cron(), I notice that the function checks for updates if there aren't cached data or if the update interval is past.

function update_cron() {
  $frequency = variable_get('update_check_frequency', 1);
  $interval = 60 * 60 * 24 * $frequency;
  // Cron should check for updates if there is no update data cached or if the
  // configured update interval has elapsed.
  if (!_update_cache_get('update_available_releases') || ((time() - variable_get('update_last_check', 0)) > $interval)) {
    update_refresh();
    _update_cron_notify();
  }
}

By default, updates are checked once per day; if you want Drupal checks for updates twice per day, you can change the value of the "update_check_frequency" variable to 0.5.
As the setting page doesn't allow you to set a value that is lower than 1, you can change the value of that variable with variable_get('update_check_frequency', 0.5). Cron tasks needs to be executed at least twice per day, or the trick doesn't work.
You can also invalidate the cache, and force update.module to check for updates the next time the cron tasks run, by visiting the page that lists all the modules and clicking on the "Save" button; alternatively, you can call update_invalidate_cache().