Create folders in custom installation profile fails when usind drush site-install I am working on a custom installation profile, and am using $_SERVER['DOCUMENT_ROOT'] as part of creating custom folders inside <drupal-root>/sites/sitename.tld/.
It works as expected when using the UI installation process, but when I try to run it through drush site-install my_custom_install it fails. I expect this is because $_SERVER is never set in the CLI (at least that is what I could understand from search around for a solution).

In terms of the error I get when it fails, it is just a permission denied for creating the folder, since it tries to create it in /sites/sitename.tld in the root of the server, which it naturally does not have access to. It's this path that is correctly getting the document root in the UI, but not in CLI.

Code example that is creating the folder

copyTheme($from, $to, &$context) {
  $site_root = $_SERVER['DOCUMENT_ROOT'];

  $context['message'] = 'Copy theme';

  $source = $site_root . $from;
  $destination = $site_root . $to;

  try {
    // If the destination directory does not exist create it
    if (!is_dir($destination)) {
      if (!mkdir($destination, 0777, TRUE)) {
        // If the destination directory could not be created stop processing
        throw new Error('Could not create custom theme folder \'' . $destination . '\'');
      }
    }

    //if (chmod($destination, 0777)) {
    //  rcopy($source, $destination, $context);
    //}
  } catch (\Exception $e) {
    \Drupal::logger('custom_installer')->error($e->getMessage());
  }
}

Snippet of the actual error output during drush site-install
In the error, installtester.dev is the $project_domain and installtester is the $project_name.

Error: Could not create custom theme folder '/sites/installtester.dev/themes/custom/installtester' in /var/www/drupalvm/drupal/webroot/profiles/contrib/custom_installer/batch.inc on line 20 #0 /var/www/drupalvm/drupal/webroot/core/includes/batch.inc(252): copyTheme('/themes/contrib...','/sites/installt...', Array)
#1 /var/www/drupalvm/drupal/webroot/core/includes/form.inc(874): batch_process()
#2 /var/www/drupalvm/drupal/webroot/core/includes/install.core.inc(619): batch_process(Object(Drupal\Core\Url), Object(Drupal\Core\Url))
...

In case it is relevant, I am doing the development on drupal-vm via vagrant and virtualbox on a windows 10 machine.

Question
Is there a better way than using $_SERVER['DOCUMENT_ROOT'] to get the document root? one that will work both using UI install and drush site-install?.

Alternatively, is there a parameter I can check for if I use the --root option for drush site-install?

I found a solution that works.

Drupal sets it's own constants, such as DRUPAL_ROOT which can be used instead of $_SERVER['DOCUMENT_ROOT'].

So, all I had to do was to change $site_root = $_SERVER['DOCUMENT_ROOT']; to $site_root = DRUPAL_ROOT;, for it to work correctly when installed via Drush.


What can be put in 'Full HTML' node/fields? The obvious answer to this question is HTML code of course, but my deeper question is, is this an HTML body content-like HTML? I suppose I can't put HTML header content-like HTML? Correct? I mean I can't put META tags for example.

You technically can use <meta> tags, since they will not be stripped out of the content that you place into a textfield that uses the default "full HTML" input filter. However, this content will be output in the <body> of the HTML document, which means using <meta> tags here will cause invalid HTML and most likely be ineffectual.

If you are looking for a way to customize the <meta> tags used on your Drupal site, there are many modules available to help with this. The Meta Tags module is the most popular, but that project's page also lists some other meta tag-related modules.


Does deleting a field in a content type remove the data? A previously posted question appears to assume that the data is deleted in the database if the field is deleted in his/her forum content type.  I think that the field still exists and the data is still available if you add the field back.  I am reluctant to test this out on my current website in case I am wrong :}.

Deleting the field deletes the data too.
As far as I can see, the database tables used to contain the field data are renamed, but they are emptied.

Visiting the page at admin/structure/types/manage/forum/fields, I deleted the "Forums" field used for the "Forum" content type; this is what I see watching the content of the database used for my Drupal test site, after I removed the field.

To notice also that the "deleted" column in the "{field_config_instance}" table is set to 1 for deleted fields.


Clearing Boost cache with drush I am testing the boost module out, it is a great performance enhancement for the site I am working on.

However I would like to be able to get boost to clear it's cache using drush. Drush cc all doesn't seem to do this. And looking in the boost module code, there doesn't seem to be a cron command for it. Am I missing something or is this currently not implemented?

Answering my own question. I was missing something.

Boost is a bit more fussy about the URL than the rest of drush when clearing the cache

drush --uri=http://my.site.name cc all

will work.


insert new term as tag on node submit I want to add a term to the the node whenever it is submitted or edited. I have the term id of the term I want to add.
My first approach of putting this code inside the custom node submit function is not working.

function module_custom_submit_function($form, &$form_state) {
   $nid = $form_state['nid'];
   $node = node_load($nid);
   $term_id = '73';
   $node->taxonomy[] = $term_id;
   node_save($node);
}

This does not insert the taxonomy term with ID equal to 73.

My second approach was to put query inside the submit function. Though this made changes to the database, the taxonomy terms were not added as tags on the website for the corresponding node.

function module_custom_submit_function($form, &$form_state) {
  $query = db_select('node', 'n');
  $query->fields('n', array('created', 'sticky'))
   ->condition('nid', $nid, '=');

   $result = $query->execute();
   foreach ($result as $record) {
     $time = $record->created;
     $sticky = $record->sticky;
   }

   db_insert('taxonomy_index')
   ->fields(array('nid' => $nid, 'tid' => $term_id, 'sticky' => $sticky, 'created' => $time))
   ->execute();
}

Are there any corrections, or alternative ways?

This approach seems to be working for now. I just added this to the submission handler.

   $node = node_load($nid);
   $term_id = '73';
   $node->field_tags[$node->language][]['tid'] = $term_id;
   node_save($node);

It looks like you're using code from Drupal 6 in your first example, but from your second you must be using Drupal 7...$node->taxonomy isn't used in Drupal 7, taxonomy terms are related to entities via fields instead.

Your second example isn't working because the taxonomy_index table is just an index table relating nodes to terms...the hard-link between those two entities is actually contained in the field reference, which you haven't updated.

If I could offer a different approach, it would be to use hook_node_presave(). Using that method you can simply add another term id to the list of selected terms from the form, and rely on the node/field API to commit the changes and update the cache on your behalf.

function MYMODULE_node_presave($node) {
  $term_id = 73;

  // In reality you'd want to loop through the existing field values and check to
  // avoid duplicates; this is just an example to actually set the value.
  if ($node->type == 'mytype') {
    $node->field_term_reference_field_name[$node->language][] = array('tid' => $term_id);
  }
}

As an added benefit this will also work for any nodes that you add programatically, not just those added/edited through the node form.


Remove VAT based on company field and country How can I remove tax based on the company field and based on the country. For example:

In the Netherlands:

A customer from a company in The Netherlands - He must pay VAT

A customer private in The Netherlands - He must pay VAT

Outside the Netherlands

A customer from a company outside the Netherlands - He must pay no VAT.

A customer private outside the Netherlands - He must pay VAT.

What I have so far is this: If the company field has a value, they don't need to pay VAT. But the problem is now, if they are living in the Netherlands and they place a order from a company they don't have to pay VAT, but people in this country (The Netherlands) need to pay VAT.

I got the right settings now, but I have one problem. I want to show my product prices always with VAT. But with my current settings in rules the price is showing without VAT until I make a country selection on the checkoutpage.

In the view I selected: Display the calculated sell price for the current user.

Is there a way to fix this? Thanks!


Adding a custom js file to a core theme like Seven I've copied over the Seven theme to my /theme folder on Drupal 8 and I'm trying to customize it by adding in my own js file called custom.js. I added it to the seven.libraries.yml file as shown below, but I don't see it loading up on any of the pages. I even did clear the cache. Nothing shows up. I did add a custom.css file and that is showing. What could be wrong or that I'm missing?

global-styling:
  version: VERSION
  js:
    custom.js: {}
  css:
    base:
      css/base/elements.css: {}
      css/base/typography.css: {}
      css/base/print.css: {}
    component:
      css/components/admin-list.css: {}
      css/components/content-header.css: {}
      css/components/breadcrumb.css: {}
      css/components/buttons.css: {}

Asset injector has been made specifically to carry out the functionality that you stated. Simply install the module & flush cache.

Within configuration you'll see the link Asset injector and there you can select the theme to add your custom CSS/JS.

Hope that helps!


Composite block from multiple other blocks + layout I would like to create a block consisting of multiple other blocks, combined with a layout or some other kind of wrapper html.

A typical example would be a footer with 4 columns containing a menu, some custom text, etc.

The entire thing should be configurable in the UI and then exportable to the CMI system.

Known solutions

I know that this is possible in Drupal 7 using renderkit + cfrblock. However this has not been ported to Drupal 8 (yet). I will get there eventually, but atm I would like to find out if another solution might already exist.

EDIT:
On D8 there is blockgroup, but it does not really work for me.

Related issues

How to group multiple blocks into one big block I think this is for D7.

Thanks!

Use blockgroup. Add block_class if needed.

When creating the block groups, make sure that the machine name does not clash with existing theme region machine names! (from any theme, ideally)

After you created a block group, it will show up in two ways in the blocks UI:

As a new theme region (if you avoided the name clash)
As a block that can be placed.

Block class allows to add classes (e.g. bootstrap grid classes) to each block and block group.

This is not 100% what you would get with a layout, but it is getting close, and will be sufficient in many cases.


listing page in breadcrumb of single item how to make listing page created by views in the breadcrumb of single item of
specific content type like so:

Home >> Activities:   (created by views)
Home >> Activities >> item page: (desired breadcrumb)

(EDIT)
Drupal core will build breadcrumbs based on the menu structure. So if you manage to create a menu link for each of your activities, then Drupal core has you covered (see the answer by General Redneck).
If you don't want a new menu link per activity node, then you can use Path breadcrumbs or Crumbs, see below.
(/EDIT)

There are different modules that can help you with breadcrumbs, and I am sure more than one of them can help with this particular issue.

One of them is Crumbs. If you choose this, here are some steps for configuration (after enabling the module):

Go to admin/structure/crumbs/entity-parent, and specify the views page as the parent path for the node type of your choice.
On admin/structure/menu, edit the main menu (or another menu), create an item that links to the views page, and give it a title like "Activities". (*)
On admin/structure/crumbs, make sure that the menu.link_title.main-menu and menu.hierarchy.main-menu are enabled. Or just enable menu.*.
(enabling means to move those lines up into the "Enabled" section with drag+drop)
To see what going on behind the scenes, you can visit admin/structure/crumbs/debug.

(*) Creating the menu item is one option you have so that Crumbs can determine a title for the breadcrumb item that points to the activities view. There are other ways, but this is the most straightforward, and you probably want to create this menu link anyway.


How do I create content links to a group node without using panels? I am new to Organic Groups and I am following the videos at https://modulesunraveled.com/organic-groups-7x-2x . Video 4 demonstrates how to insert a create content link on a group page using Panels and I am able to replicate this, when following the video.

However, I would prefer not to use Panels and can not display a create content link in a basic layout (without Panels or Display Suite).

Various posts say that having entityreference_prepopulate module is key, but as far as I can tell, I have this configured properly (otherwise my panel wouldn't work).

I am expecting to see a display formatter on the content type or perhaps a module generated block, but nothing seems apparent.

What am I missing?

Answering my own question.

Seems I needs to use install OG Extras -  https://www.drupal.org/project/og_extras


drupal_render() returns "Array" instead to render the content I'm using Drupal 7 and I have made a custom module in which there is this function.

    function product_search_by_pin_form($form, &$form_state) {
           // Provide a text field.
           $form['pin'] = array(
           '#method'=> 'POST',
           '#action' => '$come_back',
           '#title' => t('Input your PIN'),
           '#type' => 'textfield',
           '#attributes' => array('size' => '20', 'maxlength' => '20'),
           '#placeholder' => 'Type your PIN',
           '#required' => TRUE,);

           // Provide a submit button.
           $form['submit'] = array(
           '#type' => 'image_button',
           '#required' => TRUE,
           '#src' => "/images/upload/search.png",
           '#attributes' => array('id' => 'submit'),
           '#value' => 'Search',);

           return $form;
    } // END of Function

The form is being used from the following code.

    $arr = drupal_get_form('product_search_by_pin_form');
    print drupal_render($arr);

The problem is that Drupal displays the Array instead of showing the form.

How can I solve it?

EDIT
As asked, and after have followed suggestions but without result, please here the code of the module

<?php
/**
 * @file
 * a test file
 */

/**
 * Implements hook_menu().
 */

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

  $items['/examples/myform-examples'] = array(
    'title' => 'Example myform',
    'description' => 'Configuration for TEST module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('product_search_by_pin_form'),
    'access callback' => TRUE
  );

  return $items;
}

/**
 * Implements hook_help().
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */

function myform_help($path, $arg) {
  switch ($path) {
    case "admin/help#myform":
      return '' . t("<b>Myform</b> to test a drupal form") . '';
      break;
  }
}

function product_search_by_pin_form($form, &$form_state) {
       // Provide a text field.
       $form['pin'] = array(
       '#method'=> 'POST',
       '#action' => '$come_back',
       '#title' => t('Input your PIN'),
       '#type' => 'textfield',
       '#attributes' => array('size' => '20', 'maxlength' => '20'),
       '#placeholder' => 'Type your PIN',
       '#required' => TRUE,);

       // Provide a submit button.
       $form['submit'] = array(
       '#type' => 'image_button',
       '#required' => TRUE,
       '#src' => "/images/upload/search.png",
       '#attributes' => array('id' => 'submit'),
       '#value' => 'Search',);

       return drupal_get_form($form);
} // END of Function

First try Render instead of drupal_render

$arr = drupal_get_form('product_search_by_pin_form');
print render($arr);

From Clive answer on what is the difference between render() and drupal_render()?

  The docs for render() explain it pretty well:

  This function renders an element using drupal_render(). The top level
  element is shown with show() before rendering, so it will always be
  rendered even if hide() had been previously used on it. render() is
  basically just a wrapper for drupal_render(), except that it makes
  sure the element passed in is set to be shown when passed through to
  drupal_render().

  It also makes sure the element passed in is an array (which is all
  drupal_render() can accept). If it isn't, the element is return back
  as-is. So it provides a bit of a safety net if you like.

  If for any reason you have a variable you need to render, and you
  don't know if it's a string or a render array, you can pass it
  straight through render() without having to test the variable type
  yourself.

and another solution is, use drupal_get_form as you call back function and pass your form to it as an argument. ( take a look at https://www.drupal.org/docs/7/howtos/how-to-make-a-simple-module-with-a-form-and-menu-link )

function YOURMODULE-NAME_menu() {
  $items = array();

  $items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('product_search_by_pin_form'), //put the name of the form here
    'access callback' => TRUE
  );

  return $items;
}

function product_search_by_pin_form($form, &$form_state) {
         // Provide a text field.
       $form['pin'] = array(
       '#method'=> 'POST',
       '#action' => '$come_back',
       '#title' => t('Input your PIN'),
       '#type' => 'textfield',
       '#attributes' => array('size' => '20', 'maxlength' => '20'),
       '#placeholder' => 'Type your PIN',
       '#required' => TRUE,);

       // Provide a submit button.
       $form['submit'] = array(
       '#type' => 'image_button',
       '#required' => TRUE,
       '#src' => "/images/upload/search.png",
       '#attributes' => array('id' => 'submit'),
       '#value' => 'Search',);

  return $form;
}

and third is another way of implementation second solution

function product_search_by_pin_form($form, &$form_state) {
       // Provide a text field.
       $form['pin'] = array(
       '#method'=> 'POST',
       '#action' => '$come_back',
       '#title' => t('Input your PIN'),
       '#type' => 'textfield',
       '#attributes' => array('size' => '20', 'maxlength' => '20'),
       '#placeholder' => 'Type your PIN',
       '#required' => TRUE,);

       // Provide a submit button.
       $form['submit'] = array(
       '#type' => 'image_button',
       '#required' => TRUE,
       '#src' => "/images/upload/search.png",
       '#attributes' => array('id' => 'submit'),
       '#value' => 'Search',);

       return drupal_get_form($form);
} // END of Function


Node titles are erased when I update a field with entity_metadata_wrapper I've written a script which fetches data from a REST API and uses it to update a field in a node. The website is multilingual (Canada English, Canada French, Australia English and US English) with US English as the default language. When I run the script with drush, it updates field_gj_metro_id with the correct value from the REST API, but for all nodes with languages other than US English, it deletes the node title.

What am I missing in my script that would take care of the language settings so that the titles will be unaffected?

function fetch_metros() {
  return gj_api_request('GetMetroList', $arguments = array());
 }

$metros = array();
$metros = fetch_metros();
foreach ($metros as $metro) {
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'gj_locations')
    ->propertyCondition('status', 1)
    ->propertyCondition('title', $metro['metroName'])
    ->propertyOrderBy('created', 'DESC')
    ->fieldCondition('field_display_in_listing', 'value', TRUE);
  $result = $query->execute();

  if (!empty($result)) {
    $nids = array_keys($result['node']);
    $node = node_load($nids[0]);
    $node_wrapper = entity_metadata_wrapper('node', $node);
    $node_wrapper->field_gj_metro_id->set($metro['metroID']);
    $node_wrapper->save();
  }
}

I tried calling resetCache but the problem persisted. In the end I created a page for each language and used the PHP filter to add the script to the page. By switching to each language, setting the value of propertyCondition('language','') to the loaded language and loading the corresponding page, I was able to import the metroIDs and update the pages, one language at a time, without deleting the titles.


Can't Remove Image from CCK File Field when editing node (Throbber just spins) I was able to upload an image, but the thumbnail didn't appear until I hit save on the form.  When I try to remove the image, it just sits there spinning the throbber; if I click on "Save" in the form, the image is not removed.

I think this has to do with AJAX getting caught up somewhere, but I don't know how to go about troubleshooting this.

Do you have any idea? I've tried switching the field from "Bar with progress meter" to "Throbber" and that didn't help.

Edit:

I forgot that I updated jQuery to the latest version and used some special code to prevent it from affecting the backend.  Here is the jquery_update_jquery_path() function from jquery_update.module (I modified it to fix this issue by checking for 'edit' in the uri):

function jquery_update_jquery_path() {
  $curr_uri = request_uri();
  if (strpos($curr_uri, 'admin') > 0 || strpos($curr_uri, 'edit') > 0) {
  $jquery_file = array('none' => 'jquery.js', 'min' => 'jquery.min.js');
  return JQUERY_UPDATE_REPLACE_PATH .'/'. $jquery_file[variable_get('jquery_update_compression_type', 'min')];
  }
  else {
  $jquery_file = array('none' => 'jquery-1.5.2.js', 'min' => 'jquery-1.5.2.min.js');
  return JQUERY_UPDATE_REPLACE_PATH .'/'. $jquery_file[variable_get('jquery_update_compression_type', 'min')];
  }
}

I was going to say it was probably permission-related (no delete permission) but if you managed by turning off javascript than its definitely not that.

Turn on firebug, enable the console & turn javascript back on.

If its an ajax error it will show up in the firebug console.


Views slideshow overlapping right hand sidebar block I'm using the default bartik theme and have created a views slideshow.  I have a url for this and have marked this as the front page under the admin section.  All great so far, in that when the (unauthenticated) user first visits the site they see the slideshow.  Once they log in, I have a block that appears in the right hand side sidebar.  However, the width of my slideshow is too wide in that it appears overlapped with this block on the right.  What is the best way to address this?  I could fix the width of the slideshow, but then that means I loose the flexibility to easily change the theme.

Also, can anyone point me to documentation that would help me understand why this happens?

Thanks in advance,

I found two ways of resolving this.

Permissioning the splash screen so that only non authenticated users can see it.  That way, whenever anyone logs in they do not see the slideshow.
Use the corporate clean them - much better than anything I can develop!


How can you hide "Your search yielded no results." when no keywords have been entered on the search page? On the core default search page located at /search/node, if you visit this URI the page displays "Your search yielded no results." It displays this message whether keywords have been entered that truly have no search results, as well as when no keywords have been entered. It is odd to be presenting "Your search yielded no results." to users when they have yet to actually search for anything.

What's the most appropriate way to remove this message when no keywords have been entered?

First find out how this string got there in the first place. Simply search your codebase for the exact string Your search yielded no results.. In a Vanilla Drupal you'll find only 6 occurrences of this string. 5 of them in tests, and only one in a controller, the SearchController.

Looking into the SearchController you'll see that this string is part of a render array. Keyed as '#empty' and themed with '#theme' => ['item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'],. This means you can target that pretty easily with a preprocess function. Let's go for item_list__search_results since you don't know of any plugin yet.

In your theme or module implement hook_preprocess_HOOK. Replace hook with your theme or module machine name and HOOK with the '#theme' key from earlier.

Now find out if any search query has been entered at all via if \Drupal::request()->query->has('keys'), and for safety let's also check if there's an 'empty' key in the $variables and then unset it. If you want you can tighten the condition now also on the plugin you'll find in $variables['context']['plugin'].

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE/MYTHEME_preprocess_item_list__search_results(&$variables) {
  // ksm($variables);
  if (!\Drupal::request()->query->has('keys') && isset($variables['empty'])) {
    unset($variables['empty']);
  }
}

Hint: Use the Devel sub-module Kint and its debugging function ksm() to have you any variable pretty-printed in the messages block of your site for easy debugging.


OG group content notification for group administrators I'm using Drupal 7.12 with OG 7.x-1.3 and Rules 7.x-2.0.

There is a pre-installed rule that I'm using for group notifications which is "OG group content notification". This sends out an email to all group members when new group content is created. I want to modify this so it only sends out emails to group members who have an "administrator" role for that group.

Does anyone know how I can achieve this?

I did see that it's possible for me to get a list of group managers instead of group members but I don't want just the manager I want all the group administrators.

Many thanks.

Your task cannot be done in an obvious way. A piece of content can be content of several groups. If a user is admin in the first group, but not in the second group, should he receive the email or not? If a user is an admin in both groups, should he receive the email twice?
You'll have to think about that first before one can give a precise answer.

Either way, my guess is that one should create either a rule component "Send email if group admin" that receives a user and a group as variables, or one should create a view of group admins that the rule loops over. Do ask me for details if you still need the advice.


How to use hook_form_search_block_form_alter? I was referring this page in the process of learning hooks How to Customize the Block Search Form and found following code.

/**
* hook_form_FORM_ID_alter
*/
function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#size'] = 40;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-button.png');

    // Add extra attributes to the text box
    $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search';}";
    $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search') {this.value = '';}";
    // Prevent user from searching the default text
    $form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='Search'){ alert('Please enter a search'); return false; }";

    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
}

This code is very helpful and precise to point. For example, if we want to change the placeholder, we need to put following code inside the template.php file and it works.

function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
}

Now,

From the literature on api.drupal.org, I can get the information that Hook, YOURTHEME_form_FORM_ID_alter(&$form, &$form_state, $form_id), can be used to alter the various parts of forms.
But on that page, there is nowhere a description about any part which all are described in above first code, For example, $form['search_block_form']['#attributes']['placeholder'] = t('Search'); This code is used to change the placeholder. And same way all other like title, #title_display etc...

Why I am asking this, because for hooks all things are already defines and to use them we have to use them as they are provided, So What is the method to connect this all dots, from Hook name to what can we change with that hook.

Precise Question,

To make this question to the point, I what to know from where on api.drupal.org shall I find out, this part $form['search_block_form']['#attributes']['placeholder']? Or how shall I come to know that, if I have to change placeholder I have to use $form['search_block_form']['#attributes']['placeholder'] this code only?

So What is the method to connect this all dots, from Hook name to what can we change with that hook.

There isn't one - each hook is different, has different input, different output, different contents, affects different parts of the system, and so on. You have to look for documentation contextual to what you're working with, each time you have something different.
In this case, you're working with a form, which means you should be referring to the Form API. From there it's an easy search to find information about #attributes:

Description: Additional HTML attributes, such as 'class' can be set using this mechanism.
Values: Any HTML attribute not covered by other properties, e.g. class (for control types), enctype (for forms).

It's basically an arbitrary pass-through of the key/value, so
$form['search_block_form']['#attributes']['foo'] = 'bar';

Will get you (e.g.)
<input type="text" foo="bar" />


Which releases are supported with semantic versioning of modules? I have a site running Drupal 8.9.13.  I have enabled email notification for "only security updates" and it generally works well - I get a mail for "urgent things" otherwise I wait and apply ordinary updates once a month.
Today I received a warning about an unsupported release.  When I check, all I find is an available update.  For this module, I am running 2.0.0 and 2.1.0 is available.  According to the documentation about semantic versioning for Drupal modules, this is a change to the minor version.  I don't see any reason why 2.0.0 is in fact unsupported.
From my perspective, this isn't an "urgent thing" and I don't want to be mailed about it every day.  Under the "old" version numbering scheme, a minor version change such as 8.x-3.5 to 8.x-3.6 does not cause the same behaviour.
Is this a bug in the Drupal core update module?  Or have I misunderstood how the new semantic version mechanism works?
Screenshot:

You got an email because the 2.0.0 version has been marked as unsupported by the project maintainer when, on the Releases edit form, the Supported checkbox for that version has been deselected.

On Drupal.org, 2.x, 2.0.x, and 2.1.x are considered like three different branches, and have each the setting to make them supported or recommended.
It's not just a matter of version number, but also what the project maintainers mark as supported. Probably, if you had version 2.1.0 installed, that were marked as unsupported, and version 2.0.0 were marked supported, you would get an email telling you the version you installed got unsupported.


Using code field to display field from referenced entity I have a content type of 'facility' which has an entity reference field ('manager') to a user. The user has a field 'telephone'.

Is it possible with a code field to display the manager's telephone number on the facility node?

I have played around with this but don't seem to be having any joy. I have looked for examples but can find none, so am beginning to think this isn't possible.

Any suggestions or advice most welcome.

(posted here at the suggestion of DS maintainer aspilicious)

Thanks,
Martin

Use views and a contextual filter with the entity reference relationship you have created. Use EVA to get the block as field in Display Suite.

Display Facility nodes, choose the right format (I'd go for Unformatted List). Create the relationship in the right panel choosing two references, one that points from Facility to User, then one the points from User to Telephone using the first relationship.

Use contextual filters, provide default value Content ID from URL, validation criteria Facility content type.

Add a field "Title" using the second relationship. Now you have a block that you can publish on your page. If you need it as field in DS, use EVA to create it.


Trying to add a class to a menu in a preprocess function I want to add a class to a menu - doing it in hook_menu won't work because I'm adding an icon with the icon API, and this seems to override any classes put on the menu items.

I have this preprocess function:

/**
 * hook_preprocess_page().
 */
function MYMODULE_preprocess_page(&$vars) {
  $vars['main_menu']['menu-1914']['attributes']['class'] = array('message');
}

But it doesn't seem to add the css class "message" onto my element.

How do I reliably add a css class to a menu item before display, but before icon API would display it. Theming has to be my weakest Drupal skill.

To add class in navigation's
 element, include below code in template.php

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


How do I link to a local/internal file in Drupal 7? Is there a way to get and display a local file's path in Drupal 7?

We have very large files on intranet, so I would like to instead display the file locations.

The ideal scenario would be to browse & select a file. Then instead of uploading the file drupal would save the file path i.e. x://projects/shared/example.mov

This is a solution for Intranet deployments only.

Install the Any Menu Path and the Filter Allowed Protocols modules.

Enable both modules and add "file" to the configuration  > text format > allowed protocols.

Edit the link in your menu to read file:///directory/file.html. Check the box labeled "No Path Validation" and save.

If it still doesn't work, check to make sure your browser doesn't need extensions or privacy settings adjusted to accept the file:/// protocol.


Show fields empty via render() I have a content type with some fields. My client want that the empty fields must to be visible, obviously only the label. Like

Status: New
Owner:
Read: 714

I write these "fields" in my node--XYZ.tpl.php file  via

<? echo render($content['field_all_status']); ?>

But there are not "emtpy fields"

How I can set Drupal to display all fields, empty too?

Try the Empty fields module. I didn't use it, but look like that's the module you need.

  This module provides a way to show empty fields that would otherwise be hidden.


What's wrong with my plupload implementation? For reasons that are out of scope here I should not send packets over 32 MB, so my php.ini looks like this:

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 500M

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20

; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 32M

I know plupload can do this, so I "only" needed to integrate it with Drupal. For this I installed Plupload integration module. Thanks to Clive I found this bug report:

  Right now you need to spesify a max file size larger than the max post size as plupload is stil honoring the setting.

I'm not particularly happy with upload_max_filesize = 500M but I guess for now I can live and work with it.

I tried custom code first:

  'DownloadFile' => array(
    //'#type' => 'managed_file',
    '#type' => 'plupload',
    '#title' => t("Download"),
    '#title_display' => 'invisible',

    '#upload_validators' => array(
      'file_validate_extensions' => array(),
      'file_validate_size' => array(variable_get('my_max_file_size', 300 * 1024 * 1024)),
    ),
    '#upload_location' => 'public://mymodule/download',
    '#default_value' => $item->fid,
    '#required' => TRUE,
    '#plupload_settings' => array(
      'runtimes' => 'html5',
      'chunk_size' => '10mb',
    ),
  ),

It was showing 300MB under the Form API field all right. Sadly, everything over 20MB gave me:

  Error: File too large: Some_182MB_file.zip

So I thought I'm doing something wrong and decided to try ready-made solution. I went for FileField Sources Plupload - I see 32 MB on the node add form, but 182 MB file uploaded all right.

So what's wrong with my implementation? I practically copied example from official documentation so I would expect it to work.

When using Plupload integration module in custom code, you need to set up size twice. Preferably to the same value. First place you do it is the usual:

'#upload_validators' => array(
  'file_validate_size' => array(variable_get('my_max_file_size', 300 * 1024 * 1024)),
),

This handles display and post-upload verification.

Second place is #plupload_settings:

'#plupload_settings' => array(
  'runtimes' => 'html5',
  'chunk_size' => '10mb',
  'max_file_size' => variable_get('my_max_file_size', 300 * 1024 * 1024) . 'b',
),

This is what actually goes to the plupload JavaScript.


How to get "configure" icons next to each block back? My configure icons have disapeared. How do I get them back?

If you are referring to the gear icon that appears when you hover the mouse over a block, that is output from the Contextual links module that comes with Drupal core.

The same module adds contextual links to other parts of a page, such as a node.

It also handle the gear icon that you see in the page to edit a view.


Flag a node programatically I am trying to get flag "purchase" and flag it for an user while completing an order in Rules (Commerce). This is how it goes in a PHP code:

$flag = flag_get_flag('purchase');
$nid = $_SERVER ['REQUEST_URI'];
$nid = explode("node/", $nid);
$node = node_load($nid[1]);
global $user;
$flag->flag('purchase', $node->nid, user_load($user->uid), TRUE);

Does anybody see any inaccuracy in what I've done? I just don't know why it is not working.

This is the error I am getting (actually it says nothing to me):

  Notice: Undefined offset: 1 in eval() (line 4 of C:\xampp\htdocs\mysite\sites\all\modules\rules\modules\php.eval.inc(146) : eval()'d code).
  Notice: Trying to get property of non-object in eval() (line 6 of C:\xampp\htdocs\mysite\sites\all\modules\rules\modules\php.eval.inc(146) : eval()'d code).
  Notice: Trying to get property of non-object in flag_entity->applies_to_entity() (line 130 of C:\xampp\htdocs\mysite\sites\all\modules\flag\includes\flag\flag_entity.inc).

Try below code... You can read node arguments using arg function in Drupal...

global $user;
$flag = flag_get_flag('purchase');
$node = node_load(arg(1));
$flag->flag('purchase', $node->nid, user_load($user->uid), TRUE);


Is there anyway to upload a picture to a user image field via services without an FID? So I want to update a user image field (let's say field_picture for the sake of convenience).

Preferably I only want to make one AJAX call rather than two, so I'd prefer to not have to create the file, get the fid back and pass that to the user.

Is there anyway to just pass in a local URI or anything like that, or do I need to essentially do two calls?

Ok I am going to post what I did to make this work with services. I'll also include a bit of information about my specific use-case because I don't see any list of steps anywhere else on the internet to make this happen, so maybe it'll make it easier for someone along the line.

Here's the optional part of the answer:

I was doing this in PhoneGap. To pass the image data from a mobile device via PhoneGap to a user, I did the following:

navigator.camera.getPicture(saveProfile,
                            function(message) { alert('get picture failed'); },
                            { quality: 50,
                            destinationType: navigator.camera.DestinationType.DATA_URL,
                            sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
                            );

function saveProfile(image) {
json.image = image;
}

                $.ajax({
                    url: "http://drupal/services_endpoint" + uid,
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(json)
                }
                );

And now the actual answer:

After finding this link here: Create file through services

I released I could do something similar:

function MY_MODULE_services_request_preprocess_alter($controller, &$args, $options) {
  switch ($controller['callback']) {
    case '_user_resource_update':
      if (isset($args[1]['image'])) {
        $data = base64_decode(trim($args[1]['image']));
        $finfo = finfo_open();
        $mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
        finfo_close($finfo);
        $ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
        $file_name = uniqid();
        $file = file_save_data($data, 'public://users/' . $file_name . '.' . $ext, FILE_EXISTS_REPLACE);
        file_usage_add($file, "user", "user", $args[0]);
        $args[1]['field_picture'] = array(
          'und' => array(
            0 => array(
              'fid' => $file->fid,
            ),
          ),
        );
      }
  }
}

This will generate a random file name. I'm not sure if that'll work perfectly for everyone, but it worked for my use-case.

Anyway, that is a basic way to get image data from a mobile device (iPhone in this case) into a Drupal user in one RESTful call.


How do I change option name? I have sort link 'Best' in exposed form. I want after user click this link, link title changes to 'New'
I'm try this, but it don't work:
function helper_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    if($form['#id']== 'views-exposed-form-pozdravleniya-taxonomy-term-page-1') {
      $form['sort_by']['#title'] = '';
      $form['sort_by']['#options']['created'] = '';
      if ($form['sort_by']['#value'] == 'count') {
        $form['sort_by']['#options']['count'] = 'New';
      }
    }
}

Also I'm try this, it don't work too:
function helper_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    if($form['#id']== 'views-exposed-form-pozdravleniya-taxonomy-term-page-1') {
      $form['sort_by']['#title'] = '';
      $form['sort_by']['#options']['created'] = '';
      if ($form_state->getValue('sort_by') == 'count') {
        $form['sort_by']['#options']['count'] = 'New';
      }
    }
}

I get answer here https://stackoverflow.com/a/65888182/13738862
function helper_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    if($form['#id']== 'views-exposed-form-pozdravleniya-taxonomy-term-page-1') {
      $form['sort_by']['#title'] = '';
      $form['sort_by']['#options']['created'] = '';
      if ($form_state->getUserInput()['sort_by'] == 'count') {
        $form['sort_by']['#options']['count'] = 'New';
      }
    }
}


Print current drupal menu level Hitting my head against the wall here. I've volunteered to print a list of the current menu items (at the same level as the currently viewed menu)

print theme('links', $secondary_links, array('class' => 'links', 'id' => 'subnav'));

Does anyone know how I would print out a list of the menu items at the currently selected level rather than just the top level primary links?

Update:
Also just prints the children of the primary link parent.

      print theme('links', $primary_links, array('class' => 'links'))

print theme("links", array('links'=>$secondary_links), array('class' => 'links', 'id' => 'subnav'));


When passing a variable from a render array to JavaScript how do you reach that variable in your Javascript I add a variable in the backend to a render array like so (removed superfluous code):
$some_var = 'Hello World';
return [
  '#attached' => [
    'drupalSettings' => ['someVar' => $some_var],
  ],
  '#theme' => 'core_portal_customer_subscription_edit',
  '#data' => [
    'namespace_something' => $some_var,
  ]
];

I would then like to use that variable in my JavaScript but I can't seem to access the drupalSettings.
I tried doing the following but that console.logs undefined.
(function($, Druapl, drupalSettings) {
  Drupal.behaviors.escrowPortalCore = {
    ...
    console.log(druaplSettings.someVar);
  }
}());

When you need to use a variable in the JavaScript you have set from the backend and added to the drupalSettings, you can access that variable using the drupalSettings object like tried in the example code from the question but then without adding drupalSettings to the js function, like so:
(function($, Drupal, drupalSettings) {
  Drupal.behaviors.portalCore = {
    ...
    console.log(druaplSettings.someVar); // "Hello World"
  }
}(jQuery, Drupal, drupalSettings));


How to use node data in content type as hierarchical select I have a content type having the following fields

Project Type (Node Reference - Select List)
Project Name (textfield)
Manager (user reference - manager role) - Select List
Employee (user reference - employee role) - Checkboxes

Created two nodes as following

node-1(see Image)

Project Name - Project-1

Manager Name - Manager-1

Employee   -  Emp-2, Emp-3

node-2

Project Name - Project-2

Manager Name - Manager-3

Employee    - Emp-1

I need to use these fields data in another content type like follows

All Project names to be listed in select list(like node reference). If I choose Project-1 , the relative Manager Name (Manager-1) and Employees(Emp-2, Emp-3) should be loaded automatically(like hierarchical/chain select).

Is there contributed module available for this or I need to create a custom module for this?

It looks like you need Reference field option limit, or module with similar functionality:

This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.
This is best illustrated by examples:
(...)
Example 2: sports and teams
Suppose you want news stories to be marked as being about a sport and a particular team for that sport, perhaps using taxonomy terms for both. To make editing easier, you would probably like want the 'team' dropdown to be limited to just teams for the current news story's sport.
To achieve this with this module, add the 'sport' field to both news story nodes and team taxonomy terms. Hence the team 'Chudley Cannons' would have as its sport taxonomy term 'Quidditch'. (This probably entails taxonomy term reference fields on terms themselves... which was bound to happen with FieldAPI sooner or later.)
Thus, when editing a news story node, selecting 'Quidditch' as the sport will cause the team reference field widget to update to show only teams which also have 'Quidditch' as their sport.

If this module is not exactly what you want, it can be a good start for coding own functionality. At least it solves all AJAX interactions for you, so only part you might need to alter is the actual selection.


Weform textbox placeholder I know I can set "default value" for textbox in D7 webform. Unfortunately, user needs to remove the default value and key in their own information. Actually I want something like placeholder feature. How to do this setting?

You can do this by using Webform Hints module.

  This module allows users to enable automatic placeholders to
  textfields, textareas, select lists, and email fields within a webform
  created by the Webform module.


dev site reverts to production site url when clearing cache I have moved a copy of my production site to a development box. When I clear cache at admin/settings/performance or save settings on a theme, all of a sudden the URL jumps from localhost/example/admin/build/themes/settings/theme to www.example.com/admin/build/themes/settings/theme for instance. I have cleared all of my cache tables manually via phpmyadmin and for the browser (chrome, cleared everything "from the beginning of time"). I can't successfully run cron .

EDIT: If I had enough reputation, I would downvote myself. I had the "base url" setting enabled in settings.php.

@Clive's suggestion jarred my memory and I figured it out. I have a multisite setup that I was migrating and had the base url setting in settings.php set to www.example.com and I had forgotten to change it to the localhost url. When I commented out the base url setting, everything was fine.


Import password hash I'm trying to migrate users from a non Drupal System into Drupal. I implemented my own CSV import script which basically generates Drupal user entities.

I already managed to teach Drupal how to handle the password hashes from the old system so that on first login of an "old" user, the old hash is getting replaced with a new one.

When creating a user account, Drupal automatically hashes the input for the Password field. I guess this is happening in the post save hook of the user entity.

How can I create user entities which will have my old hash inside of the pass field?

I figured it out by myself now. In case someone runs into the same problem:
Updating the database directly avoids the problem of rehashing:

$query = \Drupal::database()->update('users_field_data')->fields([
    'pass' =>$prefixed_password_hash,
])->condition('uid',$user->id());

$query->execute();


How to create a product without a variation? I'm migrating to drupal commerce (kickstart 2) from woocommerce and contao isotope.

My biggest problem was/is understanding the terminology behind it - product types, variations, etc.

In woocommerce and isotope the product categories would be for example:
- Books
- Computers
- T-Shirts.

Each category would then have individual products in it, and each product would have optional variation.

I'm having hard time understanding this in kickstart2. More than that, is it even possible to create a product without variations? How can I create a store of simple unique products that would belong to different categories (woocommerce terminology), without variables.

For example:

Books: product1, product2, product 3, ... (no variables)
PCs: -- || --
...

Thanks.

It is - as You said - difference of terminology.
The easiest way for You would be trying this: https://simplytest.me/
Here You can quickly test Drupal modules and whole distributions. Please try Commerce Kickstart with this tool and during install click to install demo content.

There You'll see that Variations are more like Categories in Your meaning:
Each product display must have one or more product variations, which is why each product display type has a matching product variation type.
Different product variation types have different fields, used for storing images, attributes such as color and size, as well as any other information.

And Categories are more like taxonomy - You can list colors, sizes etc there and reuse it in multiple products.

Hope i helped You a little :)


base_url in settings.php with mobile version I've both www.example.com and m.example.com pointing to the same directory in Ubuntu and there was in the settings.php  with this line:

$base_url="www.example.com";

I want to ask what will happen in this case in Drupal where sites are accessed as www. or the m. versions?

In the hook_custom_theme I'm returing a mobile theme whenever the URL is starting with "m.".

I was getting some wierd mix up of mobile and the desktop versions.

I was not able to find any cid with "http://m." URLs in the cache_page mysql table. After I removed this $base_url now  both mobile and the desktop versions seem to be showing fine now and also cache_page table is having rows with cid with "http://m...".

I'm not fully sure this but could $base_url cause this?

How is your /sites folder structure? You can create subdomain m.example.com, and implement the mobile version in there.

There are different approaches in implementing the subdomains in drupal. it may be multisite and shared database or multisite with different databases and single code and different databases .

what you are looking for is a shared database but different themes (multiple codes), Here is good discussion about this.


Previous/ next navigation in taxonomy terms Due to some complex project, I would like to organize navigation between taxonomy terms programmatically, with generation of custom links.

Example of navigation I need in vocabulary "fruits" with following terms, situated in same order in taxonomy management admin module :

apple -> has next link to apricot
apricot -> has previous link to apple, has next link to banana
banana ->  has previous link to apricot, has next link to cherry
cherry ->  has previous link to banana

The question, is : what is the most convenient method to get the id of previous and next term, in the same order as they organized in vocabulary ?

It's seems what in current taxonomy API of Drupal 7 there is no specific functions to do it in simple way.

We will make a view, load the term from contextual argument, get its weight into $static variable, and check on each row if row's term's weight is higher than our arg's one.

Create a view of terms, order them by weight.
Display only 1 item.
Add and hide taxonomy term: weight field.
Add a contextual filter : Taxonomy term: Term ID
Add a PhP filter and :

Setup code :

$static = taxonomy_term_load($view->args[0]);
$static = intval($static->weight);

Filter code :

if(intval($data->taxonomy_term_data_weight) < $static) {return TRUE;}

If you're sure that your terms have following weight, you can use that filter code :

if(intval($data->taxonomy_term_data_weight) == intval($static - 1) || intval($data->taxonomy_term_data_weight) == intval($static + 1) ) {return TRUE;}

to get the next and following terms. But careful with 0 and last values... :)

And of course, in that case, you have to display all items in the view.


How to delete Unused Images? I am using Drupal 7. When I test my page speed in Google PageSpeed Tools, it says to compress the images. After that I compress the image and uploaded it. The uploaded image placed in files folder like (test_0.png) and the old name is test.png. I have lot of images like that. How to remove images which are not in use.

Try audit Files module

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

  This module can be helpful in identifying orphan files that have not
  been deleted when their corresponding node was removed.

  The module has configurable options to ignore specified files and/or
  directories.

  The reports allow you to permanently remove files or database entries
  that represent orphans.


Re-enable forum commenting on a topic 24 hours after an admin has disabled them I would like an to have my Drupal forum set up so that an administrator can disable comments (by selecting disable comments in forum topic) for a particular topic, but then 24 hours later have comments opened up again automatically.

Can anyone help?

Your friend here is hook_cron().

Furthermore, you would need to check how to find the nodes that have had comments switched off in the last 24 hours. There's something useful you can check (perhaps it is the node's change time), or you have to keep a record yourself by implementing hook_nodeapi().


How to theme PDF generated by Print module? I would like to theme the PDF generated by the Print module. I would like to add header, footer, margins, border to the generated PDF.

The certificate module in Drupal provides theming to the certificate, but my site is almost like a read and get certified site, so I wish not to change print module.

I tried the form alter and other stuffs, but not sure from where the PDF can be changed.

You should on your creation of node call a function which will generate a pdf.
Use tcpdf class for it generate pdf and download  tcpdf functions./
Check also the link

 class my_pdf extends TCPDF { //Page header public function Header() { } // Page footer public function Footer() { } }

$pdf = new my_pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, UTF-8', false);

$pdf->setPrintHeader(true);
 $pdf->setPrintFooter(true);
$pdf->SetMargins(25.0, 40, 25.0);
$pdf->SetFooterMargin(1.5);
$pdf->SetAutoPageBreak(TRUE, 50);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->lastPage();
$pdf->Output('my_document.pdf', 'D');


Drupal 7 context module fails to load on front page I have the context module installed on Drupal 7. It worked perfectly fine for a long time. But, recently when I try to add or remove a reaction(block) for a context the related page fails to load. I get an error: "The website encountered an unexpected error".

Has anyone had a problem like this?

Figured it out. I had another reaction added that was causing the issue. I removed the reaction and it seems to work now.


How to make the Admin interface language switch based on node content? How can I make the Administration interface language be the same as the Editing content?

By example. If I edit a French content, I would like my interface in French.
If I edit an English content, I would like my interface in English.

On D7 you'll find a language detection and selection page at admin/config/regional/language/configure:

If you enable and put "URL Determine the language from the URL (Path prefix or domain)" on top the system will show the interface in French for nodes (and other content) in French and it will be English for English content.


CTools modal with webform unable to close I'm using the CTools modal with a webform, the form comes in via ajax. When a user is logged in, all works normally. If an anonymous user clicks on the link for the modal, I'm seeing the following behavior:

CTools modal close button does not work. No js errors.
The 2nd time the link to display the modal is clicked, the page links directly to the form page (no ajax, no modal).

For logged in users, the close button works and the button to trigger the overlay behaves properly on repeat clicks.

Any tips greatly appreciated.

We figured it out - this was being caused by the ThemeKey module. The base page was one theme, and the ajax call was requesting default theme, trigging a reload of all the javascript.

The solution is to enable  'Bypass a request forgery protection in theme selection for Ajax responses.' and select the safe themes.


Installed a feature, getting warnings on cache clear and view content not loading The Feature included a menu link, main menu, 2 views, and a custom content type. Now I am getting a warning on cache clearing on my local and dev site. Never saw it before when clearing cache, and one of the views is not loading the content items.

They do load for admin. I have tried setting the view permission to none, to role anonymous, removed sorting by published content, and returning NODE_ACCESS_ALLOW in the module's hook_node_access().

The full drush warning is

class_exists() expects parameter 1 to be string, array given handlers.inc:34

and the watchdog output that corresponds seems to be

Warning: strnatcmp() expects parameter 2 to be string, array given in token_asort_tokens() (line 575 of /home/example/public_html/sites/all/modules/token/token.module).

I'm at a loss for how all these components interact, or if they are even related.

Edit: module.info file

name = Example
description = Example description
core = 7.x
package = Features
version = 7.x-1.0
dependencies[] = course
dependencies[] = menu
dependencies[] = references
dependencies[] = text
dependencies[] = views
features[ctools][] = views:views_default:3.0
features[features_api][] = api:2
features[field_base][] = field_example_key
features[field_base][] = field_example_passcode
features[field_instance][] = node-example-body
features[field_instance][] = node-example-field_example_key
features[field_instance][] = node-example-field_example_passcode
features[menu_custom][] = main-menu
features[node][] = example
features[views_view][] = example_sessions
features[views_view][] = examples
features_exclude[dependencies][ctools] = ctools
features_exclude[dependencies][features] = features
features_exclude[menu_links][main-menu_examples:examples] = main-menu_examples:examples

I was able to get the view to display data by Disabling SQL rewriting in the view.

In the view under Advanced > Other > Query Settings: Settings > check Disable SQL rewriting.


Field permission for Administrator How to disable this fields for Administator?

Install Disable Field module and install. After installation go-to admin/structure/types/manage/YOUR_CONTENT_TYPE/fields and edit the desired field. In the bottom, you can see DISABLE FIELD SETTINGS open that and you can choose to disable option in DISABLE THIS FIELD ON ADD CONTENT FORM? and DISABLE THIS FIELD ON EDIT CONTENT FORM?. In that Select Disable for certain roles and choose administrator. After that save and that field will be disabled in ADD/EDIT based on your selection


Programmatically add node translation I am using i18n module. How can I programmatically create node translation?

// Define which node is the source, this node has his own id as translation nid (tnid)
$source_node = node_load($source_nid);
$source_node->tnid = $source_nid;
node_save($source_node);

$new_node_in_a_other_language = new stdClass();
$new_node_in_a_other_language->type = 'your_type';
node_object_prepare($new_node_in_a_other_language);
$new_node_in_a_other_language->title    = 'title fr';
$new_node_in_a_other_language->language = 'fr';
// define source tnid
$new_node_in_a_other_language->tnid = $source_nid;
node_save($new_node_in_a_other_language);


Error in query : Call to a member function execute() My query return me an error.
I have the gid of a organic group.
I want to retrieve the last news for this group.

 $query = db_select('node','n');
 $result = $query
 ->fields('n')
 ->condition('type','news','=')
 ->join('field_data_group_audience','fdga','n.nid = fdga.entity_id AND fdga.group_audience_gid = :gid', array(':gid' => $gid))
 ->execute();

This query give me a : Fatal error: Call to a member function execute() on a non-object

Thanks

The join() method doesn't return the query object, so can't be used in a chain like you're currently doing. You'll need to do something like this instead:

$query = db_select('node','n');
  ->fields('n')
  ->condition('type','news','=');

$query->join('field_data_group_audience','fdga','n.nid = fdga.entity_id AND fdga.group_audience_gid = :gid', array(':gid' => $gid));

$result = $query->execute();


How can I add a custom content pane to a feature? I have a custom content pane that I'm using in a panel that I would like to include in a feature.  In the features UI, I don't see any options to add it to the feature; however, on the custom content panes page there is an export option, so it seems like there must be some way to do this.

How can I add a custom content pane to a feature?

Unfortunately, as per this issue, a bug in features prevents custom content panes from being exported.


Has 'Administer content' permission always been required to expose publishing, authoring etc options? I've been using Drupal full-time for over six years and I always thought you could use the [content type] create, edit and delete permissions to allow users to create, edit and delete nodes AND use the 'Publishing options', 'Authoring information' etc settings on the node/#/edit page.

Looking at my most recent build today, this is not the case. Additionally, the 'Update options' dropdown and corresponding checkboxes are missing on the admin/content page.

I know there are third party modules like Override Node Options but I'm sure the above was possible.

Additionally, using the 'Administer content' permission is too aggressive because the user can then administer all content types, not just the ones you specify.

Has 'Administer content' permission always been required to expose publishing, authoring etc options? And is there a way around this other than using third-party modules?

This is from node_form() in Drupal 7.0:

$form['author'] = array(
  '#type' => 'fieldset',
  '#access' => user_access('administer nodes'),
  '#title' => t('Authoring information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#group' => 'additional_settings',
  '#attributes' => array(
    'class' => array('node-form-author'),
  ),
  '#attached' => array(
    'js' => array(
      drupal_get_path('module', 'node') . '/node.js',
      array(
        'type' => 'setting',
        'data' => array('anonymous' => variable_get('anonymous', t('Anonymous'))),
      ),
    ),
  ),
  '#weight' => 90,
);

Note that #access is set to user_access('administer nodes'). The revision and options fields have the same access set. So yes, it's always been required, at least as of Drupal 7.

You don't necessarily need a 3rd party module, but you'll need at least a custom module to make changes. You can implement hook_form_alter() (or hook_form_FORM_ID_alter()) to change the #access key of the desired elements in a few lines of code.


How do I make the content of one user not accessible to other I have created separate dashboard for each student using login destination module. I am able to redirect the student to their profile page. There are some other pages (score card, attendence etc) which are different for each student. how do I make the details of one student not accessible for other?

For nodes check Content Access module. It has video tutorials.


Assign Multiple roles to Ubercart Product I am using ubercart and Roles module to sell some roles on my drupal 7 site.
I wonder whether I can sell multiple roles with a single product, I tried to add multiple roles to a single product under features, but after purchasing a product I found only one role is assigned to the purchaser, Is there any way I can assign multiple roles.

Yes, the UC Roles module can assign multiple roles on purchase. All you need to do is add each role assignment you want at /node/XXX/edit/features.

If the roles aren't being assigned after purchase, you might want to check the SKU options you have for each feature. It could be that your product purchase is a SKU that isn't configured for role assignment. If that isn't it, you should check to make sure that your checkout rules are configured to set the right order status to trigger role assignment.


How do I add og:image script in meta? My facebook is grabbing the wrong image.

I try to adding this open graph image in my head.

<meta property="og:image" content="<?= $_GET['image'] ?>" />

and

<meta property="og:image" content="<?php echo $image; ?>"/>

but the content image path is not shown.
It became this

<meta property="og:image" content="" />

I want it to be like this.
If the article A have image a_name.jpg, the meta will be <meta property="og:image" content="/images/a_name.jpg"/>

If the article B have image b_name.jpg, the meta will be <meta property="og:image" content="/images/b_name.jpg"/>

You need to supply the tag the full URL to the image. If you install the Metatag module not only can you have full control over keyword, description, etc. but also all the og tags too per node.


Gmap Module open info window(bubble) from external link Not even sure where to start.

Would like to have a menu in the sidebar that when clicking on a link will open an info window (bubble) in the Google map.

Any ideas on a jumping off point?

You can create a function that opens an existing infoWindow:

function triggerPopup(marker) {
  // Get the map using getMap() which needs the maps ID
  var mapID = $('.gmap').attr('id');
  var map = Drupal.gmap.getMap(mapID);
  map = map.map;
  // Get the map's current markers
  var markers = map.markers;
  // Trigger the popup for the marker passed to triggerPopup()
  google.maps.event.trigger(markers[marker], 'click');
};

Then you can use this function with any external link:

$('.your-external-link').click( function(e) {
  e.preventDefault();
  triggerPopup(0);
});

This gives you the basic idea of how you can trigger the popups, you'd need to figure out a way to associate the sidebar links with the markers - this is completely dependent on how you have everything set up.


views module for node reference fields I'm looking for a module, where I can exchange the normal node reference output in a node's edit form as a view (preferably with the table design).

Kind of like the Reference Views, but for edit forms. Does anybody know a module like that?

You don't need an additional module. When you configure the node reference field you can use a view to select the nodes. Its under the advanced section.


How can i limit hours in date field? I have a reservation form with entityForm and i want to limit hours in date field.
like it begins 3:00 till 9:00 .
i've searched a lot and use Date Restrictions module but i couldn't do this .
Any idea would be appreciate it ?

Keeping your date field, I don't know an easy way. But if you take a look at https://www.drupal.org/project/office_hours, it would create a new field allowing custom hours. Maybe combining both fields you could do the trick.


Tracking how long it takes a user to submit a node edit form? For a quiz node, I want to track how long it takes a user to submit a node form (the time from Drupal generating the form until the time that the user presses submit), and I want to store this duration in a field on my node.
Use case
Each node of content type Quiz is a 10 question quiz.  I want to track the time that users spend filling out the node in order to track their improvement in speed over time.
I do NOT want to track the time spent on the website in general; for that, I already use Google Analytics with scroll tracking, and there is also the Time Spent module.
What I tried
On my node, I added an Integer field, Duration.  My thought was that I could calculate the interval from the timestamp when the form was generated until the time the node was saved by adding code in hook_node_presave():
  $original_time = ??? // How do I get the time when the node form was generated?
  $current_time = \Drupal::time()->getCurrentTime();
  $duration = $current_time - $original_time;

Where I'm stuck is I don't know how to get the time when the node form was created.
I tried to add a Datetime field to my node with a Default date of Current date, but the current date is not set until the node is saved, so that doesn't work.
So, how can I track the time from generating a node edit form until the time the user presses submit?

Here is how I would do it:
/*
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_quiz_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_duration']['widget'][0]['value']['#type'] = 'hidden'; // hide field
  $form['field_duration']['widget'][0]['value']['#default_value'] = time(); // set default value to start time
  array_unshift($form['actions']['submit']['#submit'], 'mymodule_calc_duration'); // adds a custom submit that runs before the default node submit
}

function mymodule_calc_duration(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $start_time = $form_state->getValue('field_duration')[0]['value']; // get default value
  $duration = time() - $start_time; // calculate duration
  $duration_value = [
    ['value' => $duration],
  ];
  $form_state->setValue('field_duration', $duration_value); // set duration value
}


How to get Block Plugin Id? when block created using block type entity? I have created the Block type entity using Drupal 8 UI. Now I have to Place that block entity programatically in theme region. The related question discussed.
Here

As solution given by @Shawn Conn is fine when we define our own block plugin class. As in my case I don't. I created Block type using UI

You use the custom block uuid:

'plugin' => 'block_content:' . $custom_block->uuid(),


Drupal module powered by Wikitext I am developing a website which basically has the main data source from wikipedia. The website currently needs users to copy paste text from various data sources (like wikipedia). But the problem which I realized out of it is that soon the data in the primary datasource will be outdated when people enter

Instead, I am looking in developing a module for wikipedia interface with a following workflow:

User will create a new page (a species page in this instance) and link it with its corresponding wikipedia page.
The local database will have 2 more tables (lets say) apart from the content type information of the current page of the Drupal powered website's node, in this case a species node.

a. A table for storing the RAW wikitext of the linked wiki page with the most recent timestamp.
b. A table for storing the processed wikitext which will be mapped into the Drupal node's appropriate fields.

Provide a button in the species page which will check if the 2(a) wikitext is the current in the wikipedia's corresponding article. If not, 2(a) will be updated and user will have to perform the task of 2(b) which is mapping the new wikitext into Drupal node's fields - This can be accomplished by injecting tags in appropriate way.
Provide a module where the wikitext of 2(b) is pulled into the various fields of drupal's content node.

Now my questions:

Is it feasible?
How should I get going?
Any scope for enhancement in the requirement analysis?
Loopholes?

Please see, I know my question is very broad but I would need suggestions, pointers and guidance for going ahead. I believe a proper plan is much necessary before starting to implement it.

Thank you.

EDIT:

We have released IndianSnakes application in both Android and iOS. This is possible coz we had information of species formatted across different fields which can be visualized in the above links which I have pasted. Now, the whole point of my question stands, I need some ideas in developing a middleware with which the wealth of wiki information can be formatted across different fields for each species.

First recommendation: Just use MediaWiki for the whole thing. It's not as nicely modular as Drupal but it has a lot of facilities. And as a bonus it's likely that upgrading will be easier (Dn->Dn+1 has always been a pain to me, MW upgrades have always been very smooth for me).

If you still want to use Drupal, I would use MediaWiki's parsing. E.g. fetch articles through index.php?action=render&title=Page_Name. It's probably best to simply fetch data when needed but with a long cache time (e.g. 1 week) to avoid Wikipedia blocking your server's IP.


Using the fetch() method in database query to get an array I have a very simple query that does the job, to get a collection of a specific content type's node id and title, that's it.

$connection = \Drupal::database();
$query = $connection->select('node_field_data', 'n');
$query->condition('n.type', 'employee');
$query->condition('n.status', 1);
$query->fields('n', ['nid', 'title']);
$results = $query->execute()->fetchAll();

And what i get is an array filled with objects (for each individual results) with two properties the nid and title values. But i want to have an single layer/dimension array filled with key => valued pairs (nid => title). Example bellow.

$results = [
  0 = {stdClass} (
     nid => 123,
     value => Susan Green
  )
];

And what i want:

$results = [
  123 => Susan Green,
  567 => Bob Young
];

I've tried fetchAllAssoc, fetchAssoc, etc but either the result is empty or i get something completely opposite of what i want.

Any ideas? without using a parses to convert objects into what i want, that's what i'll do if none one can find an appropriate answer.

You can use fetchAllKeyed try with:

  $connection = \Drupal::database();
    $query = $connection->select('node_field_data', 'n');
    $query->condition('n.type', 'employee');
    $query->condition('n.status', 1);
    $query->fields('n', ['nid', 'title']);
    // use fetchAllKeyed
    $results = $query->execute()->fetchAllKeyed(0,1);


Can I have a views field handler with an exposed form, or a filter handler with pre_query? It's basically in the title, but here's the question:

I'm trying to create a way to allow the user looking at a view to control which columns are visible. This isn't very hard, provided I can get called in the right place. Specifically, I need to be called in three places:

in some kind of configuration pane
in the exposed form
in the pre_render function

Both field handlers and filter handlers get a configuration pane. But only filter handlers get to affect the exposed form, and only field handlers get access to the pre_render function.

Although I might be able to get something working by combining a handler with various hooks, I would prefer everything to be together.

Does anyone know how to convince Views to either call a field handler when rendering the exposed form, or to call a filter handler for the pre_render function?

If I understand your question correctly, here's how I would go about this:

What you need to do is create a base node view. This should have all fields which are present regardless of other options selected. You'll want at least one exposed filter, so that views will render a form which you can hook into for form alter. Your process for modifying the view on the fly will be two fold.

The first will be a hook_form_alter() in which you make any modifications needed to the exposed views form. Add in any custom form elements which you'll use to control the fields displayed in the view. In your submit handler, you'll need to stuff the form values into session, so you can access them later.
The second is to use hook_menu_alter to override the default page handling in views and provide your own callback. In that callback you'll need to programmatically load and display the view. You can also add/remove additional fields to be displayed on the fly by calling $view->override_option('fields', array($some_fields));. I recommend looking at exported views to get the proper format for this, as anything you see in there is valid to do before executing the view. After you've added the fields you need, just return $view->execute_display(); to render the view. You can see an example of where I do this at http://890234892342.privatepaste.com/6b72c3e011 -- In this case, I'm only swapping out views displays / filters / arguments on the fly, but the exact same method will work for adding/removing fields. Again -- looking at exported views code is a great method to understand how you can swap this stuff out on the fly. When trying to figure out the format for modifications I need to make, I actually modify the view, export it, look at the exported code, and then revert it back to what it was originally. This allows me to see how views is formatting various fields and what array I need to pass into $views->override_options() to get the desired behavior.

It's not a particularly easy process to either explain nor do, but this is an effective method for programmatically altering views on the fly. Feel free to ask followup questions if there is something you don't understand.


unable to force JS library to HEAD I've read the main docs about this but find it lacking context. This did better job of explaining and it seems it should work. How to force a JavaScript library to load in the <head> of a Drupal 8 page
EVERY attempt I try returns

A colon cannot be used in an unquoted mapping value

Searching for this, I've attempted to enclose the include line in single quotes, without, but all within context of attempting
js-header

Since this YML, I'm making sure we're using two spaces for indentation and nothing else. What am I overlooking here? This is a snippet of mytheme.libraries.yml

  flexslider:
  version: 1.x
  css:
    theme:
      includes/flexslider/css/flexslider.css: {}
  js:
    includes/flexslider/js/jquery.flexslider-min.js: {}
  dependencies:
    - core/jquery

fontawesome:
  version: 1.x
  css:
    theme:
      includes/fontawesome/css/font-awesome.css: {}

global-styling:
  version: 1.3.2
  css:
    theme:
      includes/mapquest/css/mapquest.css: {}
  js-header:
    header: true
      js:
        includes/mapquest/js/mapquest.js: {}

This is portion of mytheme.info.yml that applies:

  #Libraries
  libraries:
  - mytheme/bootstrap
  - mytheme/flexslider
  - mytheme/fontawesome
  - mytheme/global-components
  - mytheme/global-styling

I think you've indented too far. The line following header: true is directly beneath it in the example you linked to.

global-styling:
  version: 1.3.2
  css:
    theme:
      includes/mapquest/css/mapquest.css: {}
js-header:
  header: true
  js:
    includes/mapquest/js/mapquest.js: {}


drush Invalid argument supplied for foreach() backend.inc:709 I have aegir setup, I'm trying to cache clear on all the sites in remote platform machine but failed with below error.

drush @sites cc all
You are about to execute 'cc all' non-interactively (--yes forced) on all of the following targets:
Continue?  (y/n): y
Invalid argument supplied for foreach() backend.inc:709

Would be great if some one had any idea to overcome.

The cause of above error is that @sites is returning no sites.

Try drush sa @sites too, and see what it says.

Note, however, that @sites refers to all of the sites in a multisite install; it does not refer to all of the sites in your aliases.drushrc.php. If you rename your aliases file to foo.aliases.drushrc.php, then @foo will reference all of the aliases in that file.

Else check this as well: https://www.drupal.org/node/1031170

Reference:
https://www.drupal.org/node/161698


Is it possible to Insert a view in a content type in drupal 7? Is it possible to Insert a view in a content type in drupal 7?
Is so can you help me do that?

The Entity Views Attachment module is the successor of the Views attach let you attach the output a view to the content of any entity.


How do I programmatically get a styled version of an image via imagecache in D7? I want to save locally to the server, a styled version of an image attached to a node. "Styled" as in  filtered through a custom image style that I have already configured. What is the correct function, I can't find it anywhere.

I have file_unmanaged_copy() of the original image working fine, I can't see how to retrieve a styled version.

theme_image_style. Imagecache is replaced by image style in Drupal 7.
Example:

print theme('image_style',array('style_name' => 'thumbnail', 'path' => 'path/to/image'));


Composer: require dev branch then go back to stable once current dev is stable Let's say you need a patch in a Drupal module (or core) only included in the dev version yet.

It's already commited and should normaly be included in the next stable release.

So I'd like composer to grab the dev version for now but switch back to stable as soon as the next release is out.

If I do this for ex.:

composer require drupal/bootstrap:3.x-dev

It'll continue to update to the dev version even after the patch I need is included to stable, wich I'd like to avoid...

Is there a way to achive this ?

For ex. a way to tell composer "I want a version of this module that has to include that commit be it dev or stable, but I'd prefere stable if available".

So I can patch my module and forget about it.

You should better use a patch.

You will ask composer to download and install the required patch on top of the current stable release.

Once the patch will be inside the stable release, the patch won't be applied anymore (a patch is basically a diff file, so when there's no diff, there's not patch)

Install https://github.com/cweagans/composer-patches this is a dependencies that will allow to use a section in the composer.json to declare the patch. It will install it automatically.

composer require cweagans/composer-patches

Then add an extra section in your composer.json

"extra": {
    "enable-patching": true,
    "patches": {
        "drupal/module_to_be_patched": {
            "<patch1 information>": "<patch1 file path>",
            "<patch2 information>": "<patch2 file path>"
        }
     }
}

You will find the patch file path on the module tracker, on the repository of the module, for an issue

For exemple, successive patches for a drupal/webform issue : https://www.drupal.org/project/webform/issues/3137981

Then simply

composer install

You will see the patch is being installed right in your terminal.

Reference : https://groups.drupal.org/node/518975

Patching : https://www.drupal.org/patch/apply


Node delete performance issue I am using below code to delete all unregistered users node.
But it takes very long time to execute node_delete function.I have around 5000 records of users in node table.
How can I improve the performance of node_delete() function?

$query_node = db_query("SELECT n.nid FROM node n,status s WHERE s.entity_id = n.nid  AND type = 'employees' AND s.field_employee_status_value = '2' AND n.status = '1'");
$result_node = $query_node->fetchAll();

foreach($result_node as $node)
{
    $nid = $node->nid;
    // $node id , which you want to delete;
    node_delete($nid);
}

Two appropriate options:

Use node_delete_multiple function instead of the node_delete(). I guess you need to do this only once, so this might be a faster solution if your server can execute the whole process at once (ie enough memory, not too many fields/modules, etc.).

$query_node = db_query("SELECT n.nid FROM node n,status s WHERE s.entity_id = n.nid  AND type = 'employees' AND s.field_employee_status_value = '2' AND n.status = '1'");
$result_node = $query_node->fetchAll();

$nids = array();
foreach($result_node as $node) {
  $nids[] = $node->nid;
}
// Delete everything at once.
node_delete_multiple($nids);

You can also use Administration Views with Views Bulk Operations. You can filter the nodes based on what you need and then perform operations on all rows. This will process the deletion as a batch process. Downside is that you might need to install 2 additional modules if you don't have them already.


Corresponding Type and Size of Data Types in Drupal in order to create a table field in PostgreSQL I was trying to create dynamically a table in Postgres using db_create_table function.

$schema = array(
    'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
    'fields' => array(
                     'bigint_column' => array('type' => 'int', 'size' => 'big' )
                ),
);

db_create_table('myid_template_1', $schema);

The code above works fine. It creates a table myid_template_1 in my database with a column field bigint_column with a type of bigint.

I also wanted to create fields with the following type:

bit
boolean
character varying
date
double precision
time with timezone
time without timezone
timestamp with timezone
timestamp without timezone

What is its corresponding type and size in Drupal? It is somewhat missing in the documentation I read.

UPDATE 1:

Basing from Sir Mario Steinitz answer, I updated my code above.

$schema = array(
    'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
    'fields' => array(
                    'bigint_column' => array(
                                           'type' => 'datetime',
                                           'size' => 'normal',
                                           'pgsql_type' => 'time with timezone'
                     )
                ),
    );

It was not working still. Am I missing something?

The linked documentation is not missing any field types supported by Drupal. For maximum compatibility to all supported database types, the field types of Drupal's database API is limited to the field types you find within the documentation.

This assures that most modules using the default database API will run the same with PostgreSQL as they do with MySQL and almost SQlite.

However, if you need these field types in order to work on database stored information that will be used by other applications, or have another module specific requirement for using them, you can use the 'pgsql_type' attribute within your schema definition.

This attribute overrides the generic 'type' and 'size' attributes.

Within your module, you may need to query / handle the information of these fields on your own, as the Drupal database driver might not always be able to map / fetch them properly to / from your PHP objects / arrays.


Controlling the height of a jQuery accordion in content page I have managed to add a jQuery accordion content page to my Drupal7 site by following the instructions/code given here: http://www.chrisherberte.com/blog/drupal-7-and-jquery-ui-accordion.

However, the height on the drop down fields is not being calculated correctly. Some are too long with lots of white space, others are too short meaning a scroll bar is added to view all the text. It appears to be taking all the heights of each field and using that to calculate an average height which it then applies.

I have tried the default Bartik theme, as well as my custom theme, functionality is the same on both so not a css issue, but a problem with the jquery itself.

On top of this, using HTML list elements stops it working all together, and messes up the formatting completely.

I do not have any idea where or how to edit the Jquery to fix this problem and certainly don't really want to be hacking core.

First you should try to set autoHeight to false , this will fix the height problem.
You should aslo consider to use behaviors in Drupal.

<?php
drupal_add_library('system', 'ui.accordion');
drupal_add_js("
  (function ($) {
    Drupal.behaviors.accordionRoles = {
      attach: function (context, settings) {
        $('#accordion').accordion({
          autoHeight: false
         });
      }
    };
  }(jQuery));
", 'inline');
?>

Then I could find the problem regarding HTML lists, I grabbed your HTML, put it locally and used the demo source for jQuery UI accordion (the section 3 have some HTML list inside) and it seems to work fine.


How do I solve the "table '.cache' doesn't exist" error? My friend's site shows the following error message:

  user warning: Table '.cache' doesn't exist

I am working with zero documentation pertaining to the previous person's work on the site; I'm not sure what has been mucked around with.

How can I fix this?

To recreate this table for Drupal 6, execute the follwing in a SQL tool:

delimiter $$

CREATE TABLE `cache` (
  `cid` varchar(255) NOT NULL DEFAULT '',
  `data` longblob,
  `expire` int(11) NOT NULL DEFAULT '0',
  `created` int(11) NOT NULL DEFAULT '0',
  `headers` text,
  `serialized` smallint(6) NOT NULL DEFAULT '0',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

You may need to adjust this if the rest of the database is MyISAM (someone should confirm the CREATE statememt; I converted all of my Drupal 6 sites to InnoDB).

For Drupal 7, use

delimiter $$

CREATE TABLE `cache` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching things not separated out...'$$

It is possible that the old webmaster DROPed this table thinking it would save space.  Drupal will mostly work with without this table.  Then try to clear caches from admin/config/development/performance  When you do this, you should get some exceptions from any other missing cache tables.


How to get the nearest place from database i am using drupal 6 gmap and location module to save the users latitude and longitude in database. I need to create a service in which i am returned the places list in the order of nearest first. I have all the rest of the code ready and would be all set to go if you guys could share the SQL

You have to play around location views. Add a filter and argument to sort by proximity.


Why does hook_menu_link not work? theme_menu_link allegedly "Returns HTML for a menu link and submenu."

In attempting to use this 'hook' I added code to my template.php as such:

function themename_menu_link(array $vars) {
  dpm($vars);
}

It didn't work.  Nothing appears.

I confirmed that the template.php code is executing and cleared caches several times.

Every other hook_ or theme_ function I've tested runs without issue, however this one does not.

I've also tested the alternative method, themename_menu_link__your_menu_name with no success.  The code seems to be ignored.

Try print_r instead of dpm --

function theme_menu_link(array $variables) {
  return print_r($variables['element']);
}

or use hook_menu_link_alter --

hook_menu_link_alter($variables){
  var_dump($variables);
}


Unknown column errors because of table alias Because of truncated identifiers with more than 63 chars, causing Views to break

It causes errors like

  SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'taxonomy_term_data_node__draggableviews_structure_weight_coalesce' in
  'order clause'

Goal: I want to change the table alias from _draggableviews_structure_ to _dv_

If I change

    $data['draggableviews_structure']['weight'] = array(
      'title' => t('Weight'),
      'group' => t('Draggableviews'),
      'field' => array(
        'help' => t('Display the weight value.'),
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'sort' => array(
        'help' => t('Sort entities by the draggableviews weight table field.'),
        'handler' => 'draggableviews_handler_sort',
      ),
    );

    $data['draggableviews_structure']['parent'] = array(
      'title' => t('Parent'),
      'help' => t('The parent entity id.'),
      'group' => t('Draggableviews'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
      ),
    );

  // Explain to every entity how to join with draggableviews structure table.
    $data['draggableviews_structure']['table']['join'][$info['base table']] = array(
      'handler' => 'draggableviews_join_handler',
      'left_table' => $info['base table'], // Because this is a direct link it could be left out.
      'left_field' => $info['entity keys']['id'],
      'field' => 'entity_id',
    );

to

   $data['dv']['weight'] = array(
     'title' => t('Weight'),
     'group' => t('Draggableviews'),
     'field' => array(
       'help' => t('Display the weight value.'),
       'handler' => 'views_handler_field_numeric',
       'click sortable' => TRUE,
     ),
     'sort' => array(
       'help' => t('Sort entities by the draggableviews weight table field.'),
       'handler' => 'draggableviews_handler_sort',
     ),
   );

   $data['dv']['parent'] = array(
     'title' => t('Parent'),
     'help' => t('The parent entity id.'),
     'group' => t('Draggableviews'),
     'field' => array(
       'handler' => 'views_handler_field_numeric',
     ),
   );

   // Explain to every entity how to join with draggableviews structure table.
   $data['dv']['table']['join'][$info['base table']] = array(
     'handler' => 'draggableviews_join_handler',
     'table' => 'draggableviews_structure',
     'left_table' => $info['base table'], // Because this is a direct link it could be left out.
     'left_field' => $info['entity keys']['id'],
     'field' => 'entity_id',
   );

This works. However, all of the views with draggableviews fields/sort components have disappeared. In the admin view, views complains able missing relationship, and it trying to fix them for you. If you read the fields, the view works again.

Is there a way to fix this, without manually changing everything? Is there a better way to solve it?

I've used the MD5 alias patch from that issue queue here: http://drupal.org/files/issues/views-571548_40.patch (#40) to fix that issue.

You may need to apply the patch manually to views/includes/query.inc

The good news is, if you can do that, it should fix all those alias truncation issues for you.