How to use drupal_add_html_head() to add the same metatag multiple times? I have a node which has multiple images attached to it. And each image should also be printed in a <meta property="og:image" content="image_url" /> metatag. I have tried to use drupal_add_html_head() for each image in a template_preprocess_page(), but only the last image is printed as metatag.

function mytheme_preprocess_page(&$variables) {
...
    // add multiple og:image tags
    foreach ($images as $image) {
        $element = array(
            '#tag' => 'meta',
            '#attributes' => array(
                "property" => "og:image",
                "content" => $image,
            ),
        );
        drupal_add_html_head($element,'facebook_share_image');
    }
}

The tags are stored by key, so using a different key for each should do the trick:

$delta = 0;
foreach ($images as $image) {
    $element = array(
        '#tag' => 'meta',
        '#attributes' => array(
            "property" => "og:image",
            "content" => $image,
        ),
    );
    drupal_add_html_head($element,'facebook_share_image:' . $delta++);
}


Which hook is invoked when a user's roles are changed? I am trying to set a custom role expiration date in a subscription website using Ubercart and Paypal. Role expiration date is set by the role expiry module when a user completes payment.

I am trying to achieve this by using hook_user(). Is there any other way to achieve this?

There isn't any other hook to use, as it is evident from the code used from user_multiple_role_edit().

  // The role name is not necessary as user_save() will reload the user
  // object, but some modules' hook_user() may look at this first.
  $role_name = db_result(db_query('SELECT name FROM {role} WHERE rid = %d', $rid));

  switch ($operation) {
    case 'add_role':
      foreach ($accounts as $uid) {
        $account = user_load(array('uid' => (int) $uid));
        // Skip adding the role to the user if they already have it.
        if ($account !== FALSE && !isset($account->roles[$rid])) {
          $roles = $account->roles + array($rid => $role_name);
          user_save($account, array('roles' => $roles));
        }
      }
      break;
    case 'remove_role':
      foreach ($accounts as $uid) {
        $account = user_load(array('uid' => (int) $uid));
        // Skip removing the role from the user if they already don't have it.
        if ($account !== FALSE && isset($account->roles[$rid])) {
          $roles = array_diff($account->roles, array($rid => $role_name));
          user_save($account, array('roles' => $roles));
        }
      }
      break;
  }

The only invoked hooks are the ones used by user_save().


Nodejs integration for Chatroom I am following the Nodejs integration documentation to set up Chatroom, but am a little confused.

In step 2, do we cd to the folder of nodejs installation, or the drupal nodejs module?

Also, what is the server.js file?

Updated the documentation page.

In step 2, we need to move in to nodejs module folder inside your drupal's sites directory. Install the dependencies using package manager(npm). Most probably the nodejs module is installed at sites/all/modules/nodejs.

Also don't get confused by these notation (path/to/your/nodejs/module/directory). It used to say that it exist in some directory.

server.js holds the code related to your express application from configuring your app to starting your app. Express will be installed in your node_modules folder when you install the dependencies. node_modules will be created in you nodejs module(drupal site).

node server.js starts the express application from the location where server.js file is present.

Also you can follow the tutorial links provided by No Sssweat.


Why Content Path cannot be used to sort a view? Using Views with Drupal 7, how can I use the content path to sort a result table?

I have node title, created date and path as fields for a view.
The first two fields have the checkbox to make them sorting options in the display settings, but the node path field doesn't.

Node path is not a field from DB table. It is calculated dynamically.

In views you can only sort if a sorting can be applied to the underlying SQL query.


Can't find location of files after running drush make I am creating a drush .make file for a site.  I have generated the drush.make file using drush make-generate and then updated the file as necessary.  I am now trying to use the .make file to create a new site.

To do this I first change to the directory where I wish to install the new site.  I then run the command drush make qmlc.make.  Drush asks me if I want to "Make new site in the current directory? (y/n)".  I reply "y" and then drush begins building the site.

The problem is that after the build has finished, the current directory is empty, except for the qmlc.make file.

Why are the files not appearing in the directory? If they are not here, then where are they?

Look for errors and warnings in the output of the make command. An empty directory is often the result of an error. This leaves your install directory in the drush temp location (usually /tmp/drush-xxxx).

You can add the --force-complete argument ignore errors and to copy the directory in to place anyway. But it's probably worth figuring out what the errors are.

drush make --force-complete qmlc.make

https://github.com/drush-ops/drush/blob/master/commands/make/make.drush.inc#L58


Get child page content based on menu So I have a website structure as follows:
Homepage > Level 1 > Level 2 > Level 3 (Article)

On display of a Level 1 page I want it to print out all of the level 2 articles that are a child of that content (relationships taken from the main menu). Information that needs to be printed is title, body summary, plus a custom image field that I have added.

This image shows the desired effect: the user is in About Us (Level 1), and so the main body of the site displays teasers of the level 2 pages (Who we are, what we do etc.) that have been set as children to About Us in the main menu.

Is it possible to take the parent/child relationships from the main menu, then on a page print the content of the child pages in this way?

Or, if not using the menu, is there a more appropriate/logical way to do this in Drupal?

I have lots of experience in using MySQL/PHP and writing custom modules in other content management systems however new to Drupal. Thank you for your help!

I managed to do this in the following way:

function theme_get_page_children($nid) {
         $parentPath = 'node/'.$nid;
          $parentId = db_query("SELECT mlid FROM {menu_links} WHERE link_path ='".$parentPath."'");

      foreach($parentId as $pid){
         $finalID = $pid->mlid;
      }

        $getChildren = db_query("SELECT link_path FROM {menu_links} WHERE plid='".$finalID."' ORDER BY weight");

      foreach($getChildren as $child){
          $nodeID = str_replace('node/', '', $child->link_path);
          $children[]= $nodeID;
      }

        if(isset($children)){
             foreach($children as $nid){
                 $node = node_load($nid);
                 if($node->status ==1){ //check node is published
                      print render(node_view($node, $view_mode = 'teaser'));
                 }
            }
        }
    }

And on the template files where to call it:

innovista_get_page_children($node->nid)

I think using foreach to get $finalID was bad practice. I also think I should have used drupals menu API to call the child links instead of querying the database. So if anyone knows how to improve this in these ways, or tidy up the code in general then comment below :)


how to change h2 tag for div in block_view I've created a block like this

function mymodule_block_view($delta = '') {
    if($delta == 'myblock') {
        $block['subject'] = 'mytitle';
        $block['content'] = myfunction();
    }
    return $block;
}

but the output is like this:

mytitle

I need change h2 to div

mytitle

I've tried with _preprocess_block hook but i cant change that tag

could you please help me?

try with the following:

Implement hook_theme_registry_alter to take the templates from your module.

/**
 *  Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  // Defined path to the current module.
  $module_path = drupal_get_path('module', 'mymodule') . "/templates";
  // Find all .tpl.php files in this module's folder recursively.
  $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
  // Iterate through all found template file objects.
  //test if this page isn't in BO page
  if (!path_is_admin(current_path())) {
    foreach ($template_file_objects as $key => $template_file_object) {
      // If the template has not already been overridden by a theme.
      if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
        // Alter the theme path and template elements.
        $theme_registry[$key]['theme path'] = $module_path;
        $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
        $theme_registry[$key]['type'] = 'module';
      }
    }
  }
}

Copy modules/block/block.tpl.php and past it in templates folder of your module.
Rename it from block.tpl.php to block--mymodule--myblock.tpl.php to change only for your block.
Change the line from <h2<?php print $title_attributes; ?>><?php print $block->subject ?>
 to <div<?php print $title_attributes; ?>><?php print $block->subject ?>

Clear cache.


Does "hook_ENTITY_TYPE_load" have performance advantages over "hook_entity_load"? I googled Drupal 8 hook_ENTITY_TYPE_load faster than hook_entity_load, but got no information on the question.

I was told that putting an entity type in the hook name is faster than putting an if statement for the entity type inside hook_entity_load(). This makes sense to me, but I want to make sure.

I also have a subscription to drupalize.me and couldn't find anything that supports the possibility of hook_ENTITY_TYPE_load() being faster than hook_entity_load(). In fact, it tells me to use hook_entity_storage_load() for that purpose.

The only difference is that hook_entity_load() is invoked for every entity loaded, while hook_ENTITY_TPE_load() is invoked for every entity for which the entity type is ENTITY_TYPE.
If a module implemented hook_entity_load() only to handle a specific entity type, or a group of entity types, but not every entity type, its hook_entity_load() implementation would need to check which entity is being loaded, but since the second argument passed to the hook ($entity_type_id) is the entity type, checking that isn't time consuming nor a performance issue.

As for using hook_entity_load() or hook_entity_storage_load(), the second hook is invoked for content entities (not configuration entities) with a storage handler that saves the data in the database. In the other cases, including entities loaded from the entity cache, only hook_entity_load() is invoked.


Gallery with jQuery 1.6.4 How do I implement a gallery like the following one with jQuery 1.6.4 and Drupal 7?

There is more than one way to do it - for instance, it depends on where the images are coming from. You could do it with Views for instance, creating a list of images, adding the correct classes, and applying the js from your custom theme.


Views PHP : couldn't print dates I'm using views php to printing, and calculate some dates in my view.but when I try to print a date (06/01/2015) in the global php field it printed like: 16831 which is the node id
Value code:

  $load=$row->field_date_loading;
  return $load;

Out put code:

  echo $value;

use

$load = $data->field_field_date_loading[0]['raw']['value'];
echo $load;

if you are using an end date as well you can get it with:

$data->field_field_date_loading[1]['raw']['value'];


A newly created Page does not Display Below is my .module file, when i go to mysite/timeline/nodes there is no display. While what i am planning is to display a timeline . I am new to Drupal (and web development). I have other JS,JSON and PHP file in my module folder too to make the simile timeline script available to the code, if somebody needs to see that please tell. Also i have read that tpl.php provides sometype of solution (i havent read it much so i dont know how it does exactly) but i want to display the regular page theme and put content in the content area when using hook_menu to create a new page.

function similetimeline_menu() {
$modulepath = drupal_get_path('module', 'similetimeline');
drupal_add_js($modulepath . '/similetimeline.js');

$items = array();
$items['timeline/nodes'] = array(
'page callback' => 'similetimeline_callback_nodes',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
$items['timeline/ratings'] = array(
'page callback' => 'similetimeline_callback_ratings',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}

function similetimeline_callback_nodes() {
$query = new EntityFieldQuery;

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1);

$results = $query->execute();
$output = array();
if (isset($results['node'])) {
$nodes = node_load_multiple(array_keys($results['node']));
foreach ($nodes as $nid => $node) {
  $output[$nid] = array(
    'title' => $node->title,
    'timestamp' => $node->created,
    'body' => $node->body[LANGUAGE_NONE][0]['safe_value'],
  );
 }
}
dpm($output);

global $base_path;
$timeline_lib_path = $base_path . libraries_get_path('simile_timeline');

// Set some global js variables that the library is going to need for proper inclusion and funcionality
$timeline_inline_js = "
var Timeline_ajax_url = '$timeline_lib_path/timeline_ajax/simile-ajax-api.js',
     Timeline_urlPrefix = '$timeline_lib_path/timeline_js/',
     Timeline_parameters = 'bundle=true';
";
drupal_add_js($timeline_inline_js, array('type' => 'inline', 'weight' => 10));

// Adding general timeline library
drupal_add_js("$timeline_lib_path/timeline_js/timeline-api.js", array('weight' => 11));

$html = '';
$html .= '

 This page uses Javascript to show you a Timeline. Please enable Javascript in your browser to see the full page. Thank you.';

 print theme('similetimeline', $html);
 return null;
 }

So continuing from the comments above.

You are calling theme('similetimeline', $html);, which in turn will call theme_similetimeline($html). So the main reason you don't get any output, is simply that you lack the theming function.

To get started, you can do away with theme() all together and just print $html;. Especially since you've already generated the markup, but on the other hand, it's great that you've already gotten far enough to know you should use theme(), considering you say you are a beginner. The reason for theme calls, is that you can separate the module and it's functionality, from it's markup, meaning this timeline can look different in different themes.

You will find a more extensive example, and a great answer by Clive, in a similar question I asked recently.


Weird behaviour when customising views-view-unformatted.html.twig with grouping I'm trying to override the views-view-unformatted.html.twig template by an unformatted view that includes a hidden Grouping field.

The default template includes this code:

{% if title %}

{{ title }}

{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    {{- row.content -}}

{% endfor %}

When I copy the default template into my theme, this generates the results I would expect:

When I try to modify the code by wrapping a div around the loop that fetches the rows, like this:

{% if title %}

{{ title }}

{% endif %}

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    {{- row.content -}}

{% endfor %}

I get this output instead:

Note that the first two rows are wrapped in the group-content div, whilst the third row is now wrapped in a separate group-content div. There should obviously be only one group-content div, with all rows inside it.

My goal in overriding the default template is to put them all in a separate div, which I can't do from within the views settings, so the fact that overriding the template isn't working defeats the object of the exercise.

Any ideas why this is happening, and how to get around it?


How to delete content of sheetnode spreadsheet field? I am using the Sheetnode spreadsheet module to upload data. I am looking for ideas on how to clear the contents of the spreadsheet each time the form is loaded.

I have tried setting form state using all the following ways:

hottopicsresearchsheet_form_hottopics_node_form_alter() {
  $node = $form_state['node'];
  $node_wrapper = entity_metadata_wrapper('node', $node);
  unset($node->field_spreadsheet[$node->language][0]);
  $form['#node']->field_spreadsheet[$node->language][0]['value'] = "";
  $node_wrapper->field_spreadsheet->set(NULL);
}

function hottopicsresearchsheet_field_widget_sheetfield_spreadsheet_form_alter(&$element, &$form_state, $context) {
  $element['#entity']->field_spreadsheet['und']['0']['value'] = "";
  $form_state['field']['field_spreadsheet'] = array('name' => '', 'value' => '');
}

Solution I found was to not save the data in the first place. Will make debugging harder, but here it is:

function hottopicsresearchsheet_node_presave($node) {
  // Check that the nodes of the type I need and process data...

  // Clear data.
  if (!empty($node->field_spreadsheet[$node->language][0]['value'])) {
    unset($node->field_spreadsheet[$node->language]);
  }
}


Rename the taxonomy menu in drupal 7 I have taxonomy menu as the menu in my page.Here when i edit the taxonomy menu it is not getting updated in my menu.Can anyone help menu to fix this issue.

For example let say I have taxonomy menu item hello.Now i go to structure-->taxonomy-->Home page menu--->list links and I edited the hello to test.When I come to my home page it still showing the hello and it is not getting updated.

When you edit your vocabulary, on "Structure > Taxonomy > Home page menu > Edit" there should be a "Select to rebuild the menu on submit" checkbox.  This helped in my case.

Because the following warning, you should consider making a backup before doing this.

  This will delete then re-create all of the menu items. Only use this option if you are experiencing issues like missing menu items or other inconsistencies.


How do I change the global site url when serving Drupal from behind a reverse proxy? I want the site name to be the FQDN instead of the machine's internal name (ie: localhost), especially in tokens.
I'd like to be able to change the value once (like say in an env var) so it shows up any time the site's url needs to be used, say in automated emails.

aggravating factor: we're using IIS7

inside settings.php:

global $base_url;
$base_url = 'http://my.domain.name';


hook_ENTITY_TYPE_insert never gets called Can anyone help me on the below functions. I am trying to alter user registration form and add my user form fields to default registration form. I am successfully retrieving data till validation, but I am not sure where I am going wrong in hook_user_insert. I am not able to retrieve the field value of my custom fields in hook_user_insert function.

Early support will be helpful in completion of the module.

function security_questions_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Hide the questions form when the user is being registered by an admin.
  if (!\Drupal::currentUser()->hasPermission('administer users')) {
    // Merge in our user form.
    $form += SecurityQuestionsUserForm::buildForm($form, $form_state);
    array_unshift($form['#validate'], 'security_questions_form_user_register_form_validate');
    // We can't add our submit handler here, because the user account doesn't
    // exist yet. Instead, we will get the info during hook_user_insert().
  }
}

/**
 * Validation handler for security_questions_form_user_register_form_alter().
 */
function security_questions_form_user_register_form_validate(array &$form, FormStateInterface $form_state) {
  //module_load_include('inc', 'security_questions', 'security_questions.pages');
  SecurityQuestionsUserForm::validateForm($form, $form_state);
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function security_questions_user_insert(\Drupal\user\UserInterface $account) {
  // During registration, save the user's answers.
  print_r($account->questions);
  die;
  if (!empty($account->questions)) {
    security_questions_user_answers_save($account, $account->questions);
  }
}

You probably need to add a field to the user entity, which matches your form field key. Or, save the data in the session ..


Exposed view in field widget submits node form when filtering I have defined my own field widget for node_reference fields. This contains a simple view that lets you select a node to reference. However, if i try to use exposed filters as a part of this widget it will try to submit the whole node form every time i press "Apply". Thus i can't use the exposed filters in views. How can i get around this?

I have ajax activated for the view and have tried different types of displays.

EDIT:
Just want to add that i am using Drupal 7 and the latest version of views!

I don't understand exactly whether you're using a form here, but if so, you could give this little module a try, that resolved a similar issue of mine.

http://github.com/Itangalo/Node-creation-block--Drupal-7-

creates blocks for node-forms. If you seperate view from the block (e.g. with Panles) this approach could possibly help you too...


php generated URL link I have a menu link that is a link to another client site. This uses a single-sign-on. The users info(in Drupal) is sent via SOAP to create a URL with a authenticated ticket for them to use to login. The ticket is a one use ticket. I can't figure out where to implement this,  I feel like this is something that needs to be done between jquery and hook_menu maybe? The problem is that this SOAP code needs to be called every time a user clicks this link.

Anyone have any suggestions? I'm using drupal 7.

thanks
-fw

I'm not sure jQuery is really necessary here.

If I've understood you right you could have your link pointing to a path with a menu callback which requests your token via SOAP, and then simply forwards the user on to a URL containing that token as a parameter

function MYMODULE_menu() {
  $items['goto-other-site'] = array(
    'title' => 'Forwarder',
    'type' => MENU_CALLBACK,
    'page callback' => 'MYMODULE_forwarder',
    'access arguments' => array('some permission')
  );

  return $items;
}

function MYMODULE_forwarder() {
  $token = MYMODULE_function_to_generate_token();

  if (!$token) {
    return 'An error occurred.';
  }

  // Add a query string containing the token.
  $options = array(
    'query' => array(
      'auth_token' => $token
    )
  );

  $url = 'http://other-site.com/';
  drupal_goto($url, $options);
}

Apologies if I've got the wrong end of the stick here.

UPDATE

Just a bit more to address your comments:

You can use hook_menu() to place each link in a specific menu in the system by using the menu_name key like so:

function MYMODULE_menu() {
  $items['goto-other-site'] = array(
    'title' => 'Forwarder',
    'type' => MENU_CALLBACK,
    'page callback' => 'MYMODULE_forwarder',
    'access arguments' => array('some permission'),
    'menu_name' => 'main-menu',
    'weight' => -10
  );

  return $items;
}

The weight key describes where in relation to other menu items this link should sit in the menu (a lower number means earlier in the list). When you add a menu link in this manner it will be automatically added to the correct menu so you don't need to add a custom link through the UI (you can delete the one you've already made).

Have a quick read of the Module developers guide to get familiar with that side of things, in this case you're only going to need a .info and .module file.

Hope that helps


Restrict Profile2 Profile Type on Role I would like to do a few things:

Limit the profile type a user has based on their role. When/if they change roles, their profile type would change and any fields that were the same are brought forward.
When accessing a user's profile page, the relevant profile type displays (one URL).
Allow users to display some of the fields in their core profile in the profile2 page that people see. (eg. birthday in core displayed as age in profile2 page).

Or am I thinking about this all wrong? Should I just think of profile types as different pages of the same profile that happen to have different fields?

You can use permissions to assign profile(s) to roles.

about:

  When/if they change roles, their profile type would change and any
  fields that were the same are brought forward.

Remember each profile form is independent, so what you want could be done with code.  Or you can use only one profile form and use the field permissions module to assign role(s) per field (even if this is the case, maybe you don't need profile2).

Using only profile 2 (and turning off profile2 page),  you would see your core profile fields and the profile2 fields together.


How do I include taxo description in a View's no argument summary? I've got a view with an argument based on taxo terms that shows a summary list when no argument is present. Now I need the list of terms to include a description for each one. Clearly the logical way to get this is to include the taxo description under each term, but I don't see how to do this. Drupal 6, views 2.

I'd be willing to take a stab at writing a Views plugin to get this functionality, but I don't really know where to start. I do have some idea how to get the taxo description through code, but now how to integrate that into a Views no argument option. Any suggestions?

Hmm. Interesting that no one replied to this. I would have thought this was a common need.

Turns out the answer was not a plugin but another display. Using the Views Group By module (https://drupal.org/project/views_groupby - thanks Phase2!) I created a page with the summary links but also including the taxo description. Made the links bring up the other display, and all is well.


Table too wide for view I created a view (from Views module) where I display my content in a table.
The table contains about 22 columns:

The table continue to the right of the screen (see screenshot above).
How to fix that? (fit it to view boundaries or make the view area wider)

I would recommend using the FooTable Views plugin. I've used it before and it's quite helpful when dealing with responsiveness and smaller content areas.


Ajaxify certian content on the front page My site uses dashboard as front page and loads boxes to show content. As there are many boxes, the page takes some time to load. So what i want to do now is to load the theme and interface first and then load the boxes using ajax.
Is there any kind of solution already available or something that needs to  be tailored.

My site is here

You might be interested in Ajax Blocks, which allows you to load a block on a given page via AJAX, after the page has loaded.

See also: Calling a block by AJAX


Text comparison rules on node:body:value with input filters My text comparison rule works like a charm if the user selects 'Plain text'.  If they use 'Filtered HTML' it doesn't find a match even though the pattern does exist in the raw and filtered versions of the text.

The short question is how can a text comparison rule be run against filtered input?

The long version is what's the process by which rules and input filters interact and why is this an issue?

In my case a custom input format was replacing youtube links with an iframe embedded video. Everything inside the iframe wasn't matching. My solution was to add the original youtube link outside of the iframe tag replacement pattern.

But why? Hypothesis is that one of the filters ends up running the body through htmlspecialchars.


Migration of field_collection with migration_d2d In D7 to D7 migrations, when it comes to field_collections I know “ Your field collection migration should be run after the host entity migration. ”.

I have done my host entity migration via the migrate_d2d module.

For my field_collection I have written a custom module and added migrate_d2d class name (7f4f1882cNodecook_committee_vote) as a dependency.

Has this logic flowed?

I ask because my field_collection migration does not update the previously migrated cook_committee_vote nodes, rather it makes empty stubs for them!!!

The answer is: the logic is not flowed, it is correct.
when you write your own custom migration module you can establish dependencies to other migrations that you have done via code or done via UI using migrate_ui or d2d_migrate_ui modules.
here is custom migration code that depends on a class generated by d2d_migrade_ui. this code worked for me:

$this->description = t('casey will migrate this field cllection even if it kills him!!!!!!');
// class of prviously imported node, this class name was generated by d2d_migrate module
// that is why the name is diffrent
$this->dependencies = array('7f4f1882cNodeorg_vote');

$query = $this->getConnection()
// start with the field that embeds the field_collection
->select('field_data_field_org_member_votes', 'nodeField')
->fields('nodeField', array('entity_id', 'field_org_member_votes_value', 'delta'))
->groupBy('nodeField.field_org_member_votes_value')
->orderBy('nodeField.entity_id')
->orderBy('nodeField.delta');

// join it to the fields that make up the field_collection, in my case there were 3 fields
$query->leftJoin('field_data_field_org_votes_member', 'member',
'nodeField.field_org_member_votes_value = member.entity_id');
$query->addField('member', 'field_org_votes_member_nid');

$query->leftJoin('field_data_field_org_votes_vote', 'vote',
'nodeField.field_org_member_votes_value = vote.entity_id');
$query->addField('vote', 'field_org_votes_vote_value');

$query->leftJoin('field_data_field_org_votes_majority', 'majority',
'nodeField.field_org_member_votes_value = majority.entity_id');
$query->addField('majority', 'field_org_votes_majority_value');

$this->source = new MigrateSourceSQL($query);

$this->destination = new MigrateDestinationFieldCollection(
    'field_org_member_votes',
    array('host_entity_type' => 'node')
);

$this->map = new MigrateSQLMap($this->machineName,
    array(
        'field_org_member_votes_value' => array(
            'type' => 'int',
            'not null' => TRUE,
            'description' => 'Unique ID for each commitee vote',
            'alias' => 'nodeField',
    )
  ),
  MigrateDestinationFieldCollection::getKeySchema()
); //map END

$this->addFieldMapping('host_entity_id', 'entity_id') ->sourceMigration('7f4f1882cNodeorg_committee_vote');

$this->addFieldMapping('field_org_votes_member', 'field_org_votes_member') ->sourceMigration('7f4f1882cNodemember');
$this->addFieldMapping('field_org_votes_member:source_type') ->defaultValue('nid');

$this->addFieldMapping('field_org_votes_vote', 'field_org_votes_vote');

$this->addFieldMapping('field_org_votes_majority', 'field_org_votes_majority');

}//construct END

 function prepareRow($row) {
   // this is a good wat to test and make sure
   // A) you have connected to the db
   // B) you are getting proper values from your query
   // drush_print_r($row);
 }//prepareRow END
 function complete($row) {
   // drush_print_r($row);
 }
 public function prependTextNotes($row) {
     return 'Imported notes: ' . $row;
 }//prependTextNotes   END

 }


Adding readonly wysiwyg field to entity form I'm using entity forms and I want to add a wysiwyg text block in between two form fields, that is just an explanation text. This text does not need to be submitted and should not be editable for the user. It is just an explanation text block that needs to be in the form and that has to be entered via an wysiwyg editor in the backend as it contains some formatted stuff like an headline etc.

Any ideas? Thanks!

You can try the Markup module.  Should do exactly what you're after.

  This module adds the ability for site admins to add "Markup" widgets
  to the form. These essentially let designers of cck content-types
  insert additional markup into the node/edit form to display to
  content-authors. This is the equivalent of adding additional elements
  to $form of the type '#markup'.


Unable to install the “H5P.Scorm.h5p” library: “The uploaded file was not a valid h5p package” Thanks to jackrabbithanna’s help on this other question I seem to be 1/2 way to getting H5P related libraries installed in my Drupal 7.59 install. I am attempting this on macOS High Sierra under MAMP 4.5 (PHP 7.1.12) and MAMP 3.5.2 (PHP 5.6.10).

But like I said, I am 1/2 way there; not fully there. I am able to get the H5PEditor.ScormFile (1.0.8) library installed, but not H5P.Scorm (1.1.16).

The libraries in question are as follows:

H5PEditor SCORM
H5P SCORM/xAPI

To help this process, I have now devised a bit of a Bash scripting process to get the h5p packages built from the source GitHub repos. Here is what I do…

The H5PEditor.ScormFile (1.0.8) Bash dance:

cd ~/Desktop/

git clone https://github.com/pavloshevchuk/h5p-editor-scorm

cd ~/Desktop/h5p-editor-scorm

find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

mkdir H5PEditor.ScormFile && mv {scripts,styles,*.json} H5PEditor.ScormFile

echo '{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5PEditor.ScormFile",
      "majorVersion": 1,
      "minorVersion": 0,
      "patchVersion": 8
    }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}' > h5p.json

zip -r ../H5PEditor.ScormFile.h5p *

The H5P.Scorm (1.1.16) Bash dance:

cd ~/Desktop/

git clone https://github.com/pavloshevchuk/h5p-scorm

cd ~/Desktop/h5p-scorm

find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

mkdir H5P.Scorm && mv {css,js,*.json} H5P.Scorm
mkdir content && mv icon.svg content

echo '{
  "title": "SCORM/xAPI",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5P.Scorm",
      "majorVersion": 1,
      "minorVersion": 1,
      "patchVersion": 16
    }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": [
    "div"
  ]
}' > h5p.json

zip -r ../H5P.Scorm.h5p *

And with those two things done I now have two H5P files ready to go: H5PEditor.ScormFile.h5p and H5PEditor.ScormFile.h5p.

But while installing H5PEditor.ScormFile.h5p proceeds as expected, the same can’t be said for H5PEditor.ScormFile.h5p. I get the following Drupal system information message:

  For security reasons, your upload has been renamed to H5P.Scorm_.h5p.

Followed by this “great news”:

  The uploaded file was not a valid h5p package

Screenshot attached below. Any insight is appreciated.

Short Answer

Font Awesome (4.5.4) libraries needed to be explicitly installed for H5P so that Scorm (1.1.16) can be installed. Details on how that was done near end of answer.

Long Answer

Happily, I was able to self-solve this. Starting with a fresh, clean, 100% new install of Drupal 7.59 I went ahead with this process again. Getting H5PEditor.ScormFile (1.0.8) installed was fine—as before on a more established Drupal 7.59 install—but ran into the same exact issue with H5P.Scorm (1.1.16)… But on this clean install I did get a major clue via more details in error reporting; screenshot below but the text reads:

  “Missing required library FontAwesome 4.5”

I took this error to mean that the Drupal module and related libraries for Font Awesome were not installed and that is why the “The uploaded file was not a valid h5p package.” error came up.

So I went ahead and did that—and installed Font Awesome 4.7 libraries—screenshot below:

Tried installing H5P.Scorm (1.1.16) again… And again, the same message:

  “Missing required library FontAwesome 4.5” message.

So I took this all to mean that H5P needed it’s own library install of Font Awesome, Googled and found this H5P related Font Awesome repo.

Great! So now learning what I learned previously in this other answer, I figured out how to create my own H5P.FontAwesome.h5p library, which WORKS GREAT! Screenshot below to show the process did work and I was able to get H5P.Scorm (1.1.16) installed once the H5P specific Font Awesome library was installed as well:

And to make everyone’s life easier—especially mine—I created a fairly simple Bash script that allows me to automatically create the H5PEditor.ScormFile.h5p, H5P.FontAwesome.h5p and H5P.Scorm.h5p libraries on my macOS machine; see below for source code. Just save it as a Bash file named something like build_h5p_scorm_libs.sh and give yourself execute permissions via chmod u+x build_h5p_scorm_libs.sh and you are good to go.

Library installation order should be as follows:

H5PEditor.ScormFile.h5p
H5P.FontAwesome.h5p
H5P.Scorm.h5p

Genuinely hope this helps someone in the future!

#/bin/bash

################################################################################
# Build the H5PEditor.ScormFile H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/pavloshevchuk/h5p-editor-scorm

# Go into that cloned repo.
cd ~/Desktop/h5p-editor-scorm

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir H5PEditor.ScormFile && mv {scripts,styles,*.json} H5PEditor.ScormFile

# Create the 'h5p.json' file.
echo '{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5PEditor.ScormFile",
      "majorVersion": 1,
      "minorVersion": 0,
      "patchVersion": 8
    }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5PEditor.ScormFile.h5p *

################################################################################
# Build the H5P.FontAwesome H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/h5p/font-awesome

# Go into that cloned repo.
cd ~/Desktop/font-awesome

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir FontAwesome && mv {*.css,*.otf,*.eot,*.svg,*.ttf,*.woff*,*.json} FontAwesome

# Create the 'h5p.json' file.
echo '{
  "title": "FontAwesome",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "FontAwesome",
      "majorVersion": 4,
      "minorVersion": 5,
      "patchVersion": 4
    }
  ],
  "mainLibrary": "FontAwesome"
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5P.FontAwesome.h5p *

################################################################################
# Build the H5P.Scorm H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/pavloshevchuk/h5p-scorm

# Go into that cloned repo.
cd ~/Desktop/h5p-scorm

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir H5P.Scorm && mv {css,js,*.json} H5P.Scorm

# Create the content directory and copy files into it.
mkdir content && mv icon.svg content

echo '{
  "title": "SCORM/xAPI",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5P.Scorm",
      "majorVersion": 1,
      "minorVersion": 1,
      "patchVersion": 16
    }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": [
    "div"
  ]
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5P.Scorm.h5p *


#attached property doest't work!(render array/form api) the css file style.css never get loaded when using the form api #attached properties. here is my code:

mymodule_menu() {

  $items['test'] = array (
            'title' => t('test css'),
            'page callback' => 'drupal_get_form',
            'page arguements' => array('test_attach_css'),
            'access callback' => TRUE,
            );

return $items;

}

function test_attach_css($form,$form_state) {
   $markup = '
style the font as red
';
   $form['content']['#markup']  = $markup;
   $form['content']['#attached']['css'][] = drupal_get_path("module",       "mymodule")."/style.css";

return $form;
  }

the content of css file:

.test {

 color:red;

}

after many hours of searching and debugging for an anwser, i finally realize  it's a naming issue. you cannot name the css file as style.css. i changed the name  to custom.css,then it works as expected!


How can I capture Watchdog output during a functional test? I have a functional test that is failing, and I think that there could be some useful information in the database log, but unfortunately the test suite only runs in containers on GitLab CI so I don't have any way to get to the database log while the environment is running.
Is there any easy way to get a dump of the contents of the watchdog log in a test artifact?

The Watchdog to File module is handy for this use case. You can initialize it in a test setup, like so:
<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * My browser tests.
 */
class MyBrowserTest extends BrowserTestBase {

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->enableFileLogging();
  }

  /**
   * Enables logging of ALL watchdog events to a file.
   */
  protected function enableFileLogging() {
    $installer = \Drupal::service('module_installer');

    $installer->install([
      'watchdog_file',
    ]);

    $config_factory = \Drupal::configFactory();
    $config         = $config_factory->getEditable('watchdog_file.settings');

    $log_path =
      sprintf(
        '%s/artifacts/watchdog-%s.log',
        dirname(DRUPAL_ROOT),
        $this->databasePrefix
      );

    $config->set('log_filename', $log_path);
    $config->save(TRUE);
  }

}

Then, just configure GitLab CI to capture the test artifacts folder:
  artifacts:
    when: always
    reports:
      junit: artifacts/junit/*.xml
    paths:
      - artifacts/*
      - web/sites/simpletest/*

As a bonus, the above snippet also captures browser output produced by browser tests, in case you need to review them as well.
Each watchdog log will be named according to the Simple Test database ID that is used for the corresponding test run. For example, if you have five cases in your test, you should end up with five watchdog file logs.


How to change link to a node's path in Views conditionally I have what I'm calling a "student blog" section. Students can create a blog either locally (with a Body field), or remotely using a Link. A single conditional_fields value of "blog is hosted" controls what is shown on the add_node_form.

These blog entries are moderated via Workbench Moderation.

Anyways in Views 3.x I want to make a listing of the blog titles, linked to their content. If the content was "local" I want a link to node/NID or the url alias. If the content was "remote url" I want the url to point to the offsite url for the blog post (eg, Blogger.com).

I have created the content type, and a simple views block that lists the node titles .... but I can't get the link(s) to point to the correct locations per entry.

If possible, please submit answers using Views 3.x Core only (not views_php, etc) ... this site has a ton of modules already :P

Images of configuration:

Content Type Fields

Initial Blog Creation Screen

Blog was Local screen

Blog was Remote Url screen

Views Block Output of Node Titles (that should link either local or remote

You could add a blog_url field which you hide in a form alter and  programmatically set when the form is submitted. If the blog is remote, you set it to the value of the link field. If it's local, you set it to the value of the node. You can then use this field in Views (just include the Title field and use 'Link this field' to link it to the value of blog_url). Something along the lines of:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'school_blog_node_form') {
    $form['field_blog_url']['#access'] = FALSE;
    $form['#validate'][] = 'mymodule_validate_school_blog_form';
  }
}

/**
 * Validate handler for school_blog edit form.
 */
function mymodule_validate_school_blog_form($form, &$form_state) {
  if ($form_state['values']['field_blog_is_hosted'] == 'local') {
    $form_state['values']['field_blog_url'] = 'node/' . $form['nid'];
  }
  else {
    $form_state['values']['field_blog_url'] = $form_state['values']['field_blog_remote_url'];
  }
}


How to use entity form in pop-up window? I have created a view, and there is one column named "forward to delete". I want to open an entity form in a pop-up after clicking on this link and get the node id of the clicked node so that I can use this node id for other purpose.

I am using the entity form module.

Make sure you have 7.x-1.4 of the entityform module installed or this won't work.
Install the Modal operations module.
Install the Modal forms (with ctools)
Enable the Modal entityforms module that came as part of the modal module.
Create a link to your modal popup like this:

Open Entity Form in Popup!

I found this blog post very useful for figuring this out and getting it working.

If you cannot use version 7.x-1.4 for some reason then there is a patch here that some have had success with however I could not get it to work this method.


What is the best way, programmatically, to iterate through a view's results? Given a view, named 'Children' (with two fields: child_node_id and a birth_order_value) what is the best way, programmatically, to iterate through the views results set given a display_id of 'default' and an argument that contains the parent node id?

Previously, I have used the View in a block using code similar to the following:

if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2)) {
   $node = node_load(arg(1));
   $args = array($node->nid);
   $view = views_get_view('Children');
   print $view->preview('default', $args);
}

However, in another block I want to perform some logic based on the values found in the view.  You might be able guess that business logic based on my final requirement: I want the block of code supporting the view ('Children') be called multiple times. As I iterate through the view dataset results, I want to recursively iterate through the children nodes querying for their children.

Playing around with Views a bit I seem to have worked out an approach. However, I'd like to leave my question open to other answers and better solutions.

<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
   $node = node_load(arg(1));
   $args = array($node->nid );
   unset($view);
   $view = views_get_view('Children');
   $view->set_display('default');
   $view->set_arguments($args);
   $view->set_items_per_page(20);
   $view->execute();
   $newarg = array();
   for ($i=0; $i<sizeof($view->result); $i++) {
      $newarg[$i] = $view->render_field('nid_1', $i);
   }
   for ($i=0; $i<sizeof($newarg); $i++) {
      unset($view);
      $view = views_get_view('Children');
      $view->set_display('default');
      $view->set_arguments($newarg[$i]);
      $view->set_items_per_page(20);
      $view->execute();
      ....
   }
}
?>

The key to executing the view multiple times was for me to unset($view) when I was done with the result set.


custom module date formatter for publication date I have a Drupal 8 contrib module AP Style Date that provides a formatter for dates to conform to the AP Style Guide date rules. When using the module Publication Date, this formatter does not come up as an option. The AP Style Date does come up in views and in managing field display for other date types. Is there a modification that needs to be made to the AP Style Date module or something in the publication date that needs to be modified?

The publication date module provides a function to define which formatters can be used. I added a patch, which we maintain locally, to add the defined "timestamp_ap_style" format to the options. Optionally, I could have added it inside a custom module, but the patch seemed to make more sense.

 function publication_date_field_formatter_info_alter(array &$info) {
   $info['timestamp']['field_types'][] = 'published_at';
   $info['timestamp_ago']['field_types'][] = 'published_at';
   $info['timestamp_ap_style']['field_types'][] = 'published_at';
 }


Modifying the HTML generated for Menus I've read the questions already asked but they didn't answer my question. But they were sucessful in confusing me more. There are hooks, render functions of two types, theme functions, pre-processing functions, processing functions. In every question I read over internet the answer is different every time. My head's gonna explode.

Coming to question, I need just the text & href from menu-item or link. I'll handle the rest.

How I want it?

//I need control over the HTML wrapper elements for menu
foreach $menu_items as $menu_item:
    if(has_submenu($menu_item)):
        print "custom html here";
        foreach $menu_item as $sub_menu_item:
            print "custom html here".$sub_menu_item['name'].$sub_menu_item['href']."custome html here";
    endif
    print "custom html here".$menu_item['name'].$menu_item['href']."custome html here";

Try to use: menu_tree_all_data(). It will get a menu tree of your given menu machine name.


How to add different field values in views? I have two contents A and B. I have created a view for A, I need a one of field value from B in my A view.

I have referred some tutorials, they are suggesting relationship by using entity reference field.

Actually in my content B there is no any entity reference fields. In content B I have only two fields one is title and other one is plain text. How can I overcome this? Thanks in advance.

create a block view of content B By overiding fields and render a content of block in A's view page.


ImageCache not working I recently moved my website (Drupal 6) and database to a new server. I am now getting an error whenever I try to upload images using the image field. When I upload images the thumbnail doesn't appear and the error I get is:

"ImageMagick reported an error: libgomp: Thread creation failed: Resource temporarily unavailable"

I tried switching to using GD2 but this didn't make any difference. I've also checked that I have the correct temp folder set in the file system. I had migrated from a 1&1 hosting account to a newer 1&1 hosting account...

It seems like the ImageCache files are not being generated.

I'm not sure what to try next.

Any advice would be appreciated.

EDIT:

I also found that even inserting images that are already on the server into content are not showing up. The path is correct (I've checked the files) but they just don't appear.

Actually, hardly any images are showing at all throughout the website even though the paths are correct and when ImageCache is not even used.

I found a solution to my problem. There were two changes I needed to make.

The first was in the .htaccess file in the "files" folder there was the line:

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

When I commented out this line I could see the images again.

However, I was still having problems generating new ImageCache images. I managed to fix this by adding the line below to the settings.php file:

putenv("MAGICK_THREAD_LIMIT=1");

I find out this last solution from my hosts (1&1) technical support.


Warning: Cannot use a scalar value as an array function theme_test($form) {

  $output = '';

  foreach($form['field'] as $key => $val){

    $output .= '
';
    $output .= drupal_render($val['uid'. $key]);
    $output .= '
';
    unset($key,$val);
  }

  return $output;

}

When I run this code, I get the following warning message:

  Warning: Cannot use a scalar value as an array in theme_test()

How do I resolve this, and what is the reason behind this warning?

There's somehting funky happening on this line:

$output .= drupal_render($val['uid'. $key]);

$val is not an array, you'll need to rethink your PHP code. Do a Google search for "Warning: Cannot use a scalar value as an array" and you'll see a bunch of cases where other users are dealing with the same issue. As an example:

PHP : Cannot use a scalar value as an array

EDIT:

Looking at your code again, this line looks suspect:

unset($key,$val);

You're in a loop that is using these values. Applying an unset could result in the issue in addition to the point I made above.


How to upload .tif image file? I want to upload image(.tif extension) to drupal website, but as per current we can upload only jpg/jpeg/png/gif only.

According to Display TIFF image in all web browser unless you're on Safari, you will not be able to render the .tif image on your site.

Therefore, this more like a file rather than an image. If you want to upload it, for your field type use file instead of image.

If you plan to display/render the .tif image, you will have to convert it to a known image file: .png, .jpeg, .gif, etc..

Edit:

  Do we have any drupal module that can convert .tif to other image
  extension? – Govind

According to Henk's comment in Upload tif using image API there is a way:

  I was looking for a similar solution and found a working solution in
  Drupal 7 to upload, scale and display tiff images.

  Install ImageMagick module and its dependencies with ImageMagick tif
  support on the server

  Install Media module

  Use the media module as the widget type for your image type field
  because the regular image widget type does not support TIFF's, with
  that you should be able to upload tiff images in Drupal

  And i forgot...add the "change file format to : png" for your image
  style because only Safari is capable of displaying tiff's directly


One page website with Drupal 7 I saw many personal or company websites with one-page website style. the one-page design is very good for giving as quick as possible all information that you have without letting users click around to find out who are you and I really want to apply them in Drupal.
I also tried to implement one-page website by using the single page website module (http://drupal.org/project/single_page_website) and it's quite nice for the simple pages.
So my questions are:

Which is the best way for making one-page design: create one-page templates or using contributed modules?
The advantages and disadvantages for Drupal to make one-page design?

I haven't done any one-page design before so can someone give me the right direction for that.

Well if you want ideas for one page websites you can look here for some awesome one page websites.
    onepagelove.com

you can pick any one of these as design however you will have to heavily custom theme your drupal site.


How can I get the number of comments per page? I need the value "default comments per page" for special theming in comments-type.tpl.php for Drupal 6. Should I use variable_get()?

Those variables are stored per content type, named comment_default_per_page_TYPE. So to get the default comments per page for the article content type you would use:

$default = 50;
$per_page = variable_get('comment_default_per_page_article', $default);


How Can I have Exposed filter for Taxonomy vocabulary in Heirarchical Select? I use drupal 7 and simple hierarchical select module for filter views module result by taxonomy terms and taxonomy vocabularies.

my views have results only if select both vocabulary and taxonomy term from select list (exposed filter) .if I select only vocabulary from select list I have no any result for views.

So i want to have a exposed filter that can filter views by vocabulary (all its taxonomy terms) and taxonomy term (sub level of vocabulary)  .
please see this picture.

Is any other way for filter views result by both vocabulary and terms in heirarchically?

thank you beforehand.

Solution of My problem:
I use SHS module and in views filter fields select "has taxonomy term (with dept) - simple_hierarchical-select" and in dept field of its settings set 1 .
Now with select any parent term or subterm , views has the result.


How to display node add answer form on a question page using the Answers module? I want to set up my own Q&A site. I've installed the Answers module. It has satisfied me mostly, but not entirely. I need to place an answer node add form on the question page. I have no idea how to do this. I tried hooks from dru.io/quieston but my hook does not work.

I tried Advanced form block and it is ok: it displays node add form in question page but answers need to have a relationship to their question. When I add an answer on a page /node/add/answer it does not allow me to add an answer without question id.

So to place an answer, the relative path should be like this: /node/add/answer/117 - where 117 is the node id of the related question. And when I create answer using an Advanced form block form, it really adds  a new node, but such answer is not displaying in the question page and has an empty body. Because of question id should be defined.

How to display node add form in other node page with entity reference? And to define question id for this form?

The most recent version of the Answers module (= 7.x-4.0-rc2) already comes, out-of-the-box, with a "answer node add form on the question page" (as in your question). So you don't need any other modules, such as Advanced form block (it all happens automagically).

To experience it yourself, try out a demo of it. Here are the steps to do so:

Head over to the demo site.
Just accept the defaults to create a sandbox demo site (hit the create sandbox button, and wait for the process to complete).
Login to the site (using the suggested defaults).
Create at least 1 question using either the "Add content" menu link and then selecting "Question", or just enter relative path /node/add/question. And complete the title and body of the question.
After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
Use the Questions tab (or enter relative path /questions, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

Note: you may also want to enable the Answers Theme (sub-module of Answers, new as of 7.x-4.x). After you do, return to the question you created before, and see how the look-and-feel of both the question and related answer(s) below it changed ... Here is a sample screenprint of it:


Three level menu: How to show only the children of the current page? A three level menu:

  Item 1
    Item A
        Item X
        Item Y
        Item Z
    Item B
        Item Xx
        Item Yx
        Item Zx
    Item C
        Item Xy

When viewing the "Item 1" node,  I'd like to display the sub-menu items in the template: Item A, Item B, Item C

When viewing the "Item B" node,  I'd like to display the sub-menu items in the template: Item Xx, Item Yx, Item Zx

While I would like to rely totally on the menu structure, the output will not be displayed as a traditional menu.

This code does what I need:

function subpages($nid=null) {

$nid = 'node/'.$nid;

$menuItems = menu_tree_page_data('main-menu');

foreach($menuItems as $key => $m) {
    if ($m['link']['in_active_trail'] && $menuItems[$key]['below'] && $m['link']['link_path']  == $nid) {
        $menu = menu_tree_output($menuItems [$key]['below']);
        } else if ($m['link']['in_active_trail'] && count($menuItems[$key]['below']) > 0) {
            foreach ($menuItems[$key]['below'] as $k => $third) {
                if ($third['below'] && $third['link']['in_active_trail']) {
                    $menu = menu_tree_output($third['below']);
                //foreach ($third['below'] as $item) {
                //  echo $item['link']['link_title'].'<br>';
                //}
            }
        }
    }
}
return $menu;

}

You can do that with Menu Block module.

  It provides configurable blocks of menu trees starting with any level of any menu. And more!

You can then first create a menu block in the block configuration page.  Then configure the menu block to start with the 2nd or 3rd level according to which level of the menu you want to have and set the depth to 1 so that it only lists that level and not its children.

If you want to have sub-menu items follow the current menu item, i.e. it always shows the children of the current page, you should set under the menu block configuration, Advanced Options, and check Make the starting level follow the active menu item.


How can I know which button was clicked? I have a form with a "Submit" and a "Cancel" buttons. In hook_submit(), how do I know which button was clicked?

You must use $form_state->getTriggeringElement().

Best practice is to define a #name attribute for your button, so you can have this value in the triggering_element.

For example:

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

In this example:
$form_state->getTriggeringElement()['#name'] will return "delete" when called within public function submitForm(&$form, $form_state)

If you don't define this attribute triggering_element will hold the button's #value (the text that user can read), but this is discouraged as other modules may change this value or be changed by the localization).

You may use $form_state['clicked_button'] too, but this is deprecated.

You can read more info at the drupal_build_form function documentation page.


How can I pull slideshow filenames from the database using jQuery? I've have a jQuery plugin I'm using in my Drupal 7 site to make a fullpage background slider. I load it from a javascript file. How can I get the image names from Drupal's database instead of having to manually edit the list of images in the javascript file?

Here's the .js I load in my theme:

(function($) {
  Drupal.behaviors.BackgroundSlider = {
    attach: function(context, settings){
      $.backstretch([
            "/sites/default/files/styles/background_transition/public/ba5933c356c60f895785da952f8ad3e4_0.jpeg?itok=PjRiZj-V"
          , "/sites/default/files/styles/background_transition/public/8bad4c95b3776bed84222abe4c5288ba.jpeg?itok=cKq-2Dgj"
          , "/sites/default/files/styles/background_transition/public/78cefce14e9d9a613b0bc1950da662c6.jpeg?itok=4pAyvgsM"
          , "/sites/default/files/styles/background_transition/public/00336b1506db0487ea33af734abd3b16.jpeg?itok=QcS5dV2K"
      ], {duration: 3000, fade: 750});
    }
  };
})(jQuery);

Here's another option - how about create a view to generate JSON for the image paths and then pull that into your JS?

The module "Views Datasource" can output your view as JSON.  You would need to create a view that pulls the images from the content type you are using and make sure that the image is rendered as a URL (rather than the actual image tag).

From there you could update your JS to pull the JSON from the view output.  Create a loop that sets a variable with the JSON data (as a comma separated list) and use that variable within your backstretch function.

I can't provide any code examples at this time, but hopefully that can get you started down a path.  Here is a stackoverflow article that provides examples on how to convert JSON to CSV and store that in a variable:

https://stackoverflow.com/questions/8847766/how-to-convert-json-to-csv-format-and-store-in-a-variable


how do I change the number of nodes that the admin layout shows? The drupal 7 admin overlay for nodes seems to show 50 by default. How do I  a raise or change that number? I've googled for this information, but apparently I'm not guessing the right keywords, because I didn't get any relevant results.

You could create a nodes view of all your nodes. Set the pager to whatever number of nodes you want to view, and put various exposed filters on the View to help you find the content you need.

You could also access your database directly. Depending on your hosting provider, you probably have access to some sort of database interface. PhpMyAdmin is very common. If you go to the nodes table, you can view as many nodes as you'd like and figure out the NID you need to pull up the node. Clunky, but it'll work.

There's an old doc page for Drupal 6 regarding this same issue, but based on some of the comments, I don't think it'll work for D7. Worth a shot, though.


How to add a function to web form submit button? On a Drupal site, when a form submission is done. I need to trigger a SMS. I am unable to edit the form submit code. Please let me know how to add a function to webform submit button. So that on SUBMIT button click the SMS function get executed as well the form data goes to the database.

Your mileage will vary, but it's the same as adding submit handlers to any form:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['actions']['submit']['#submit'][] = 'MYMODULE_some_function';
  }
}

function MYMODULE_some_function($form, &$form_state) {
  // Do something...
}

See hook_form_alter() for full details.


How to build custom breadcrumbs I have to build a breadcrumbs, In fack I only need to add a breacrumbs between the "home" and the "books breadcrumbs" to get something like this:

  home>>view-path>>book-breadcrumbs-with-deep

I have try with paths breadcrumbs, with hansel, and with custom breadcrumbs, I don't get nothing.

There is another module, or I should make my own module?

Thanks

Oskar

You can accomplish this with hook_menu_breadcrumb_alter():

function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  $home = $active_trail[0];

  $new = array(
    'title' => t('Some title'),
    'href' => 'internal/drupal/path',
    'link_path' => '',
    'localized_options' => array(),
    'type' => 0,
  );

  $active_trail = array_merge(array($home, $new), array_slice($active_trail, 1));
}

This is a fairly simplified example that creates a new breadcrumb item, and sticks it after the first entry.  The $item parameter will be the router entry for the current page.  If you want to use that, you need to dpm() it to see what is there.  A more concrete example, which assumes that you are on a node page would be:

function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  $home = $active_trail[0];

  if (arg(0) == 'search') {
    $active_trail = array($home);
  }
  else if (isset($item['load_functions'][1]) && !empty($item['map'][1]) && $item['load_functions'][1] == 'node_load') {
    $node = $item['map'][1];

    $new = array(
      'title' => $node->title,
      'href' => 'node/' . $node->nid,
      'link_path' => '',
      'localized_options' => array(),
      'type' => 0,
    );

    $active_trail = array_merge(array($home, $new), array_slice($active_trail, 1));
  }
}


A page that list all the nodes by views but to have a one CMS controlled banner image on that page I have created a views page which list maximum of 50 nodes of type 'event'. It works fine but I want have a single image banner on the top that can be uploaded by the logged in user from the admin area for that page. I can't add a banner field on the event content type as it will get pulled 50 times.

The other solution I managed was to create another content type called 'Banner image' and create another view which lists 1 node of event type 'Banner image' and add it to the initial page view but that seems like a really dirty solution. Is there a simpler solution to this problem?

Create a admin form that allows the admin user to upload the image file, as you say in your question.
Create custom block that renders the image as you want. You can do in a custom module (better, more solid) or crete the block using the GUI and add the HTML code. In both cases, the img should point the file uploaded by the admin form.
Place the block over your view in the view's page.

This is good if:

You only have one view that needs the header image.
That image is the same for evey user.


Is there any sensitive data in the Configuration Management Export? I noticed in default.settings.php this comment:

  Location of the site configuration files.

  The $config_directories array specifies the location of file system
  directories used for configuration data. On install, "active" and "staging"
  directories are created for configuration. The staging directory is used for
  configuration imports; the active directory is not used by default, since the
  default storage for active configuration is the database rather than the file
  system (this can be changed; see "Active configuration settings" below).

  The default location for the active and staging directories is inside a
  randomly-named directory in the public files path; this setting allows you to
  override these locations. If you use files for the active configuration, you
  can enhance security by putting the active configuration outside your
  document root.

And then the example:

$config_directories = array(
  CONFIG_ACTIVE_DIRECTORY => '/some/directory/outside/webroot',
  CONFIG_STAGING_DIRECTORY => '/another/directory/outside/webroot',
);

I also noticed that when you export to the directory you specify, an .htaccess file is added that denies access to the directory.

I understand that most people will not want their configuration available for anyone to read, but what if your site is in a public repository?

https://github.com/davidbarratt/davidwbarratt/tree/develop/config

Is there anything I should be concerned about? Could this data be used to exploit the site?

Well, it contains the complete configuration, like list of modules, views, roles and their permissions.

While those things are not directly sensitive, it would make it easy to check for misconfigurations for example, views that aren't access protected, roles that have administrative permissions and so on.

I'm not sure if core adds anything that is explictly sensitive in there, I don't know any examples.

It does depend on the modules you have installed though. Many sites store API Keys or passwords, when integrating with third party services. Those would also be stored in configuration. For example configuration to send mails through an SMTP server or username/password for a Solr server.  And you don't want to have that public.

But you probably also don't want those in git in the first place. You can solve that by setting them through configuration overrides in settings.php.


How to group rules together in the UI? My website has a lot of rules and it's becoming hard to find a specific one fast via the UI. I know I can filter them, but I almost never use that feature. Is there a way to group rules with the same tag together in an expandable block or something? That would make life a lot easier. (Maybe I should post this as a feature request on the Rules' issue queue.)

As you've mentioned, Rules provides a tagging feature to tag / label rules. You then apply a filter to view that set of Rules only.

Any other grouping of Rules would require custom coding to retheme / template the layout of that page.


How to do Question and answers with email notification in drupal 7 To make question and answers for users, I found Answers or Question/Answer modules can be used. But these are only for flow of making questions and answers. If any user (Role: customer) asks question in that site, then that question should sent to the other users (Role: Support). Any suggestions?

Well, this can be achieved using Rules module.

Also refer to this question - https://stackoverflow.com/questions/4463011/drupal-rules-sending-an-email-address-to-a-user-reference


Errors with "LOAD DATA LOCAL INFILE" I am using \Drupal::database()->query() with the following SQL statement.

LOAD DATA LOCAL INFILE '{my file name}'
INTO TABLE {my table name}
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
({my column names})

I have also tried with db_query() with same result.  I can confirm the SQL statement works as expected in phpMyAdmin, so I don't think it's a problem with the SQL statement.

First error

  Warning: PDOStatement::execute(): LOAD DATA LOCAL INFILE forbidden in Drupal\Core\Database\Statement->execute() (line 59 of {my directoreis}\core\lib\Drupal\Core\Database\Statement.php)

Line 59 is $return = parent::execute($args); which I believe is referring to PDOStatement.

Second error

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

Not sure if this can be set in a call to \Drupal::database()->query();

My research on this has shown me it should be possible to do in Drupal.

https://www.drupal.org/node/1034584

https://www.drupal.org/node/2110935

https://evolvingweb.ca/blog/import-hundreds-of-thousands-of-records-15-seconds-custom-entities

Database Abstraction Layer and 'LOAD DATA INFILE' Statements

https://stackoverflow.com/questions/3994133/how-to-load-data-to-db-from-csv-using-load-data-infile-in-drupal

So, where am I going wrong and how can I fix it?

UPDATE

Based on some of the pages I linked to above, I was able to come up with a working solution.

// set up an extra db connection
$connection = \Drupal::database()->getConnectionOptions();
$connection['pdo'][\PDO::MYSQL_ATTR_LOCAL_INFILE] = 1;
\Drupal\Core\Database\Database::addConnectionInfo('extra', 'default', $connection);
\Drupal\Core\Database\Database::setActiveConnection('extra');

// instantiate the extra db connection and query against it
$db = \Drupal\Core\Database\Database::getConnection();
$db->query($sql_statement)->execute();

// set connection back to default;
\Drupal\Core\Database\Database::setActiveConnection();

But for some reason I don't think this would be the "Drupal" way.  And now, I am not sure what my question is.  Maybe, is this the appropriate Drupal way or is there a more elegant built in solution I am unaware of?

Maybe, is this the appropriate Drupal way or is there a more elegant built in solution I am unaware of?

Yes, that's an appropriate "Drupal" way.

The other way is to make it global, and add it to the database settings array in settings.php.

But you're essentially setting the same thing whichever way you do it. If you were to use your method, and then remove that option from the connection afterwards, it could arguably be considered more secure, since you're limiting the time and scope that LOCAL INFILE can be used in.


Notification email on Content creation - admin approval? I made a custom content type to replace comments, as the current comment options are not satisfactory for me. Anonymous users can create this content type (comment).

I need to send an email to the administrator users each time a new comment is written, to allow them to publish the new comments.

I searched for notification email, but it is not what I expected; it only allows to send emails on regular basis. Maybe I could not make it work.

How can I send automatic emails to administrators to notify them a new comment has been created, and it is waiting for approval?

You should try the Rules modules, it can does exactly what you want.

  The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.


How to check the success of AJAX request for following chunk of code using Drupal.ajax() The following code makes and AJAX request using Drupal.ajax() function. What I want is to have some kind of callback that will be executed once the request completed, basically the 'success' parameter of usual jQuery AJAX request. Adding success = function(request, status) parameter doesn't help either, or maybe I did something wrong ther. So how could I get a success callback to this request?

var ajaxSettings = {
    url: eventEditFormUrl + '/nojs',
    selector: popContClass + '>div.content',
    wrapper: popContClass + '>div.content',
    event: 'add_event',
    method: 'html',
    progress: {
        type: 'none',
    },
    speed: 'fast',
    effect: 'fade',
};
var req = new Drupal.ajax(null, popContClass, ajaxSettings);
$(popContClass).trigger('add_event');

Could you provide more information on why the success function didn't work for you or what code you were using for it? This should work exactly like ajax settings in jquery Ajax since its just a passthrough, so your code would be something like this in your js:

$.ajax({
    url: eventEditFormUrl + '/nojs',
    selector: popContClass + '>div.content',
    wrapper: popContClass + '>div.content',
    event: 'add_event',
    method: 'html',
    progress: {
        type: 'none',
    },
    speed: 'fast',
    effect: 'fade',
    success: function(){
       $(this).html("woot.");
    }
});


How do I display inline content with the Colorbox Module? I understand that I need to add the class "colorbox-inline" to the link and build the url like 119 this "?width=500&height=500&inline=true#id-of-content"... but how do I do that? Do I need to edit a .tpl file?

No PHP, this is done with HTML and JavaScript

CSS style the inline-content you want to display with "display: none;"
for colorbox: in "configuration", "Media", "Colorbox" --> advanced settings,
activate "Enable Colorbox inline"
add this as the html code for opening the colorbox webform link: <a class="colorbox-inline" href="?width=310&amp;height=460&amp;inline=true#name-of-your-inline-content">
If this is not working try some additionally jQuery-Magic: $('#name-of-your-inline-content').colorbox();


How to apply theme_menu_tree to only the top  menu I am using the following function in the template.php (drupal 7) to override the original menu output. However, the  tags in all levels are also affected. I wonder how to only apply it to the top/first  tag? Please advise. Thanks!

function THEMENAME_menu_tree__MAIN_MENU($variables) {
  return '
' . $variables['tree'] . '
';
}

In order to theme the top level ul tag only:

function THEMENAME_menu_tree__menu_top_menu(&$variables) {
 return '
' . $variables['tree'] . '
';
}

You have to put this piece of code in your custom theme's template.php file and replace THEMENAME with your theme's name.


organic group content not displaying I enabled organic group example module. When I looked at my groups, none of the content belong to the group was displaying. It seem to be a filter error of some sort, but this is all straight out of example and it's not working.

Has anyone experienced this problem?

I have experienced similar kind of problem, I want to show all the group content shared within a group in a view. Just download og_extras module, enable it and you will get amazing blocks and views including the one you wanted.


Thumbnail generation with nginx reverse proxy I'm using nginx as a reverse proxy for a Drupal 7 site running on Apache2.

When I try to view a thumbnail I get the Drupal 404 page saying that the location is not found.

I have implemented the location rules to rewrite requests to the thumbnail to index.php and the error message includes this rewritten request.

These are my nginx location blocks:

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1 last;
}

location ~ ^/sites/.*/files/styles/ {
    try_files $uri @rewrite;
}

# Try to serve files with Nginx if possible
location / {
     try_files $uri @proxy;
}

# Pass on php to Apache
location ~* \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    proxy_pass http://127.0.0.1:8000;
    include /etc/nginx/proxy_params;
}

location @proxy {
    proxy_pass              http://127.0.0.1:8000;
    include /etc/nginx/proxy_params;
}

The url of a thumbnail looks like this:

http://example.com/sites/default/files/styles/thumbnail/public/pictures/picture-1-1437996028.jpg?itok=19uLP_Ax

The error message displayed is:

The requested page "/index.php?q=sites/default/files/styles/thumbnail/public/pictures/picture-1-1437996028.jpg&itok=19uLP_Ax" could not be found.

I have tried setting the flag to allow insecure content generation (without a token) to test with.  Obviously I've removed that flag.

that is similar to me, i added this line in my nginx vhost config,

location ~* /sites/default/files/styles/ {
    if (!-e $request_filename) {
    rewrite  ^/(.*)$  /index.php?q=$1  last;
    break;
    }
}

you need to reload to make the image display, hope someone can improve my answer


Image styles are not beeing generated I have a problem where Drupal tries to access the files in the "styles/stylename" directory, but they are not there since they aren't beeing generated. I allready tried changing the theme for a while (image style (imagecache) images are not being created) and also tried creating the style folder, changing permission and editing the .htacces file (https://www.drupal.org/forum/support/post-installation/2015-06-16/image-styles-not-generating#comment-11859066). I also tried a few other things, nothing seems to work.
Maybe usefull information: the images are created in a directory based on the month and year.
 for example "sites/default/files/2019-07/filename.png"

edit:
When accessing the url of the image style it returns:

  Error: Class 'lsolesen\pel\PelJpeg' not found in Drupal\file_mdm_exif\Plugin\FileMetadata\Exif->getFile() (line 108 of modules/file_mdm/file_mdm_exif/src/Plugin/FileMetadata/Exif.php).
      Drupal\file_mdm_exif\Plugin\FileMetadata\Exif->getFile() (Line: 127)
      Drupal\file_mdm_exif\Plugin\FileMetadata\Exif->doGetMetadataFromFile() (Line: 280)
      Drupal\file_mdm\Plugin\FileMetadata\FileMetadataPluginBase->loadMetadataFromFile() (Line: 377)
      Drupal\file_mdm\Plugin\FileMetadata\FileMetadataPluginBase->getMetadata('Orientation') (Line: 183)
      Drupal\file_mdm\FileMetadata->getMetadata('exif', 'Orientation') (Line: 39)
      Drupal\image_effects\Plugin\ImageToolkit\Operation\gd\AutoOrient->execute(Array) (Line: 172)
      Drupal\Core\ImageToolkit\ImageToolkitOperationBase->apply(Array) (Line: 124)
      Drupal\Core\ImageToolkit\ImageToolkitBase->apply('auto_orient', Array) (Line: 143)
      Drupal\Core\Image\Image->apply('auto_orient') (Line: 138)
      Drupal\image_effects\Plugin\ImageEffect\AutoOrientImageEffect->applyEffect(Object) (Line: 302)
      Drupal\image\Entity\ImageStyle->createDerivative('public://2018-05/02_1.jpg', 'public://styles/project_gallery_image/public/2018-05/02_1.jpg') (Line: 161)
      Drupal\image\Controller\ImageStyleDownloadController->deliver(Object, 'public', Object)
      call_user_func_array(Array, Array) (Line: 123)
      Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 582)
      Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
      Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
      Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 151)
      Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
      Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
      Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
      Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
      Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
      Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
      Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
      Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
      Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
      Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Try to installed missed library by the following comment on the root of your drupal website :

composer require drupal/image_effects:^2


Give users a stripped down version of add node page and then require admin approval I want to give my users stripped down versions of the 'add node' pages to create nodes of various content types. Once they fill out the stripped down version (less fields and options) an admin/editor can then approve each node manually and fill in fields not in the stripped form. What method or modules can I use to achieve this?

For example, a user would fill in the title, body, tags and the admin would fill in custom fields such as the imagefield, filefield etc.

You can assign permissions to fields, the content permissions module should give you what you want. Look in the permissions pages and you can see what rolls have access to which fields.

A simple way to set up the workflow you suggested is to set the default node status to unpublished (look under workflow settings on the edit content type page). Then make sure only your admin role has the administer nodes permission.


How to subscribe to any or all taxonomy terms on one page? I'm wondering about the best way to set up "subscribe to get email alerts"

I have a content type which is "tagged" with various terms from various taxonomies
and I want to set up a simple "subscribe to get email alerts" page, where users can subscribe to whichever 'terms' they like, so that emails are sent to them when a new item of the content type is created with the associated tags.

I have installed the notifications and messaging modules
which have enabled me to create a "subscriptions block", which is presented on the content pages with links like "Subscribe to: Content tagged with: XXXXX", which allows users to subscribe to a specific tag.

But what I really want is a page, which lists ALL available tags (terms) a user could subscribe to, with check boxes, so the user can skim the list and subscribe to any / all the tags they are interested in, in one go

I am struggling to work out how I might do that using the notifications and messaging modules…
perhaps I would be better off allowing users to 'tag' themselves with the same terms used on Content Type… and then set up a rule which fires an email to the user if new content (of the specific content type) is created with the same terms as they have tagged themselves with?

But I'm not entirely sure how I would go about that… or if there is a better / simpler plan?

I don't think this is a very complicated task - and am surprised I can't find links to similar requests / solutions online…

Any advice appreciated!

Subscriptions
The Subscriptions module (with over 5K reported installs) is a typical solution used to setup such Subscriptions. Some details about it (from its project page):

This module enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made. Admins can turn this on by default.

Total Subscription
The Total Subscription module (only a bit over 100 reported installs)  seems like a possible alternative for such subscriptions. Some details about it (from its project page):

Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.
... provides users the ability to:

Subscribe to a specific content type through the node page.
Subscribe to the related taxonomy terms associated with the node on the node page.
Subscribe to a specific taxonomy term from the term page.
Unsubscribe from any previous subscription.
Add a separate ctools content type - "subscription", which could be integrated with any panel page.
Add a "subscription" block to the any region.

Refer to its Community documentation for more details about it, or this video tutorial (without sound ...) that takes you through various admin screens.
Apart from that, to understand what this module is about, the readme.txt might be helpful also.
Module comparison
Some more details about how both modules compare (from the Total Subscription project page):

Subscriptions provides the following features which are not there in Total Subscription, namely it allows subscription to new comments in specific forums, or additions to some category of blog. More control on subscription management for user. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made which can be turned off by admin. But the biggest disadvantage of Subscriptions is it does not allow anonymous users to subscribe, which Total Subscription provide. Total Subscription also has Views and Token integration.


Adding a "three line" character (☰) or image to TB Mega Menu dropdown button I'm currently developing a website with TB Mega Menu using a Zen subtheme. The problem is that the default TB Mega Menu button (the one that replaces the 'normal' horizontal menu on smaller screens) is just an empty white button without any signs. I want to make it more understandable for users by adding an industry-standart "three line" character (☰) or an image. Does anyone know how this can be done?

element:before {content: "☰";} should do the trick. I'm seeing some other problem in there actually. The presence of <i></i> element means there should be a font icon on load, with the i:before reacting as your three bars. Sirate theme, for example, doesn't have it, so it has to be a bug.

Could you provide a live site so we could give you a solution based on it? TB Megamenu could be different as markup depending on the theme. Or your CSS could be changed, based on some Zen stuff.


Add 2 form elements to Form via AJAX I am newbie into Drupal.

I want to add 2 form elements dynamically to existing form via AJAX based on particular condition. But in the examples I saw till now the AJAX callback defined returns only one element to form. I tried to achieve this by adding these two fields in fieldset and returning fieldset as a single item. But this replaces my container div completely. This works only at first time and then the contents returned by callback replaces the container.

function new_registration($form, &$form_state) {
    $form['select-reason'] = array(
        '#type' => 'select',
        '#title' => t('Reason'),
        '#options' => array('' => 'Select') + _global_reasons(),
        '#description' => t('Reason.'),
        '#ajax' => array(
          'event' => 'change',
          'callback' => 'is_true',
          'wrapper' => 'options',
          'method' => 'replace'
        ),
      );

    $form['options'] = array(
        '#type' => 'container',
        '#prefix' => '
',
        '#suffix' => '
'
      );
    }

function is_true(&$form, &$form_state) {
      $product_quality = $form_state['values']['select-reason'];
      if(_belongs_check($product_quality)) {
          $form['a-add'] = array(
              '#type' => 'fieldset',
              '#collapsible' => FALSE,
              '#collapsed' => FALSE,
          );
          $form['a-add']['detail'] = array(
              '#type' => 'textfield',
              '#title' => t ( 'Details' ),
              '#description' => t ( 'Enter product name.' ),
              '#maxlength' => 400,
              '#size' => 100,
              '#required' => TRUE,
          );
          $form['a-add']['num'] = array(
              '#type' => 'textfield',
              '#title' => t ( 'Number' ),
              '#description' => t ( 'Enter number.' ),
              '#maxlength' => 400,
              '#size' => 100,
              '#required' => TRUE,
          );
      } else {
            //remove 2 fields added in IF block
      }
      return $form['a-add'];
    }

I also tried to return HTML structure of these two and place it in #markup type of form element. But I am not convinced with this way as theming might be complicated.
Can anybody help? Thanks in advance.

Add the additional form elements in the build function. The build function is rerun on every ajax request. If you don't have other things to do as modifying the form structure, then the ajax callback can be empty and you only need to return the new ajax container.

So you need to change this:

Put the new form elements inside the ajax container (in the first function):

$form['options']['a-add'][...]

And then return the whole container in the ajax callback (second function):

return $form['options'];

You always have to return the outside ajax div, otherwise the ajax callback will not work a second time.


How to natural sort by text fields in Views? I'm trying to sort a view by a text field. The text field include numbers, in general.

While sorting it sorts as below:

1
10
11
2
20
...

But I want to make the sorting natural.

The Views Natural Sort module doesn't work, it only works with the Title field, unfortunately (there was some options to sort text fields before but now there isn't any option for this).

How can I natural sort the view by text field? And use the table sort asc/sort desc feature?

(The field should be text field and couldn't be an integer field.)

As per Views Natural Sort module homepage, you should enable Enable Views Natural Sort Text Field support to make the text fields sortable.
Here are the steps:

Enable Views Natural Sort.
Also Enable Views Natural Sort Text Field support (this will most likely go away in the future)
Navigate to the fields edit page for the field that you wish to enable 1. Natural Sorting on and check "Enable natural sorting."
http://screencast.com/t/eDkW0c6AC This is needed so that we aren't
indexing other text fields needlessly bloating the sorting table. In
the future there may be a separate table for each field, I'll have to
do some performance testing.
When you do that, your fields "Should" be reindexed... at that time. You should be taken to a batch operations screen.
Next you can go to the view you are editing and the option to sort the view naturally should be there. http://screencast.com/t/6XD7oeBtl

Note: When working with fields there is the need to enable fields for indexing. At the point the setting is enabled, the field is indexed and will be ready for use in a view. Follow the following steps to allow natural sorting on text fields:


How do I add 2 blocks side-by-side in Bootstrap theme's "Content" region? I have block views on the first page in the "Content" region of the Bootstrap theme that I would like to display as follows:

 _________________
|                 |
| another block   |
|_________________|
|        |        |
| block1 | block2 |
|________|________|

Is there a way to do this easily, without using float left/right for block1/block2 (as Bootstrap using a grid layout using rows and columns)?

Normal Bootstrap syntax would make block1 go in the first
 element and block2 go in the second
 so that the two blocks appear as equal-sized columns.

I see that regions are laid out in themes/contrib/bootstrap/templates/system/page.html.twig.

If there is not an easy way to achieve the desired layout, do I need to somehow create a twig template, similar to page.html.twig, in my Bootstrap subtheme that defines say 2 side-by-side regions under the existing "Content" region (i.e. "Sub-Content Left" and "Sub-Content Right" regions)?  If so, how is this done and how to make the template apply to a specific page?

I looked into Bootstrap Layouts and Display Suite, but it wasn't clear how to integrate the two to accomplish the above.

Thank you very much in advance for your help.

You can extend the page twig like this.

Make a copy of page.html.twig in your theme template folder and put a twig block around the content:

page.html.twig

...
{% block content %}

  {{ page.content }}

{% endblock %}
...

Then create a new file, and name it so that it will target the specific page, for example the view "myview":

page--view--myview.html.twig

{% extends "page.html.twig" %}

{% block content %}

  {{ page.content }}

    {{ page.subleft }}

    {{ page.subright }}

{% endblock %}

This new file extends the page twig and contains only a new version of the the twig block "content". You can define multiple twig blocks in one file and replace them.


Get the field value in markup? I have 2 fields in a content type.

field_link and  field_hoster

if in the hoster field youtube is selected the markup should embed the linked video.

can you guys give me a example of what i have to write in the markup field?

use hook_form_alter()

$form['field_name'] = array(
  '#type' => 'markup',
  '#markup' => $form['field_name'][#value]
);

or you can use prefix or suffix

$form['field_name']['#prefix'] = '
'.$form['field_name']['#value'] .'';