Update warning: "Some of the pending updates cannot be applied because their dependencies were not met." Followed by "No pending updates." I inherited a site from a previous webmaster (who doesn't seem to have known what he what doing) last month and I have been trying to fix it up since then, but one pesky update issue won't go away. Whenever I run update.php, it goes through halfway and then stops with the following messages:

✓ Verify requirements(done)
✓ Overview(done)
▶ Review updates(active)

Warning message

Some of the pending updates cannot be applied because their dependencies were not met.

Status message

No pending updates.

• Front page
• Administration pages

I've been getting this error message for some time now whenever I run update. Some searching revealed that uninstalling and reinstalling the affected module might fix the error, but I can't figure out where it is coming from, or which module could be causing it. Is there any way to find out which module is causing this error without uninstalling and re-installing every single module on the site?

Just in case someone else finds this ... I added a watchdog line to the function update_script_selection_form($form, &$form_state) in update.php.

foreach ($updates as $module => $update) {
  if (!isset($update['start'])) {
    $form['start'][$module] = array(
      '#type' => 'item',
      '#title' => $module . ' module',
      '#markup'  => $update['warning'],
      '#prefix' => '
',
      '#suffix' => '
',
    );
    watchdog('update','NO START: '.$module);
    $incompatible_updates_exist = TRUE;

    ...

It was XML sitemap causing the problems on a D6->D7 upgrade, and I ended up having to delete its tables manually before it would uninstall.


Nested Dropdown Menu of Bootstrap I would like to add Nested bootstrap menu in my project. (I'm using the Bootstrap Business Theme.)
I already tried with the Superfish module.. But I don't like that much because the appearance of menu is not good looking and have to overwrite many CSS files.
I also tested with TB Mega Menu. It doesn't work. I put TBMenu Block in Navigation block. But the whole menu was totally disappear. I don't know why it happen like that.

Anyone knows other flexible dropdown menu for bootstrap theme?

Responsive Menus module is suitable for bootstrap theme.
https://www.drupal.org/project/responsive_menus


Wildcards in dynamically generated menu I'm working on a custom module, and I'm building menu items using entries in a database. These are being cached, and the database is only really updated about once a month.

I'm having an issue getting wildcards to work with this menu.

Here's my menu structure that WORKS:

$dbconn = dbConnect();
$query = "SELECT TOP 3 id, title FROM table";
$q = mssql_query($query, $dbconn);
while($r = mssql_fetch_assoc($q)) {
    $title = $r['title'];
    $items[$title] = array(
        'title' => $r['title'],
        'description' => 'Page for ' . $r['title'],
        'page callback' => 'programs_page',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );
}
mssql_close($dbconn);

But the moment I add the % into the array key, the menu items just disappear, like so:

$items[$title . "/%"];

Any suggestions on why drupal is tripping up on this? Even if I tack the ."/%" onto the $title variable, it doesn't work.

There is no need to add wilcard placeholders after your last path element. Anything tacked onto the end of the URL will be passed to the callback as arguments automatically.

If the example you give above, if someone goes to $title/arbitrary/arguments, then 'arbitrary' and 'arguments' will be passed as arguments to your page callback:

programs_page('arbitrary', 'arguments');

If you want arguments in the middle of your path, you can specify them with a % sign, or if you would like to automatically load and pass an object to your page callback, you can use wildcard loaders.


Is hook_file_download the right hook for taking action when a private file is downloaded? I'm trying to create a module that will fire send an event via google analytics' Measurement Protocol API when a file is downloaded.  These files are all in the private file system outside of the document root.

hook_file_download looks like a somewhat likely candidate for triggering an http request to google analytics, but since the hook is responsible for access, it seems possible that another module might deny access after this version of the hook is run, and google analytics would get an event even in cases where the download didn't go through.  If there a better hook that would be run after all the access check have finished?  I should probably mention that I am using the media module.

Supplementarily, the existence of both hook_file_download and hook_file_download_access is confusing since they both claim to control access to files.  Is it a correct understanding that hook_file_download_access basically controls whether a user has access in relation to the entity the file is attached to (so likely would control whether the download link is displayed at all or not), and hook_file_download only applies to private files, and checks on access after a request for the file has been made?

Follow Up

I ended up implementing two hooks: hook_file_download and hood_file_transfer which as far as I could tell is undocumented in the drupal api site as a hook.  Both of those hooks calls a function passing the $uri parameter which in turn builds the google analytics request and then sends an http request.  That seems to cover the two different cases when a file download passes through drupal for my setup.

If I recall correctly, there's an access pass before hook_file_download is ever called. hook_file_download is called so you can modify headers, or do a last minute abort on the download.

So on the assumption that no one else is calling that hook (which you should check for the modules you have installed), a hook_file_download implementation is a perfectly fine place to do something like call a Google API. The only caveat is that if you're calling a web service, you want to make sure it doesn't take so long as to screw up the download.

I'm fairly certain that the hook will be called for any file scheme (i.e., "private:", or a custom scheme).  You may want to look at the Drupal 7 Example module "File" example, which I believe shows a hook_file_download implementation.

The behavior in Drupal 8 is similar, BTW.


Creating view filter that lists most recent, except the x most recent I'm trying to create a view that will go on a front page where the three most recent articles will be featured content displayed in a slideshow. I've got that working, but my issue is displaying the rest of the most recent articles in another view, as a list formatted normally as they appear in the teaser display. My problem isn't achieving that display, it's filtering the articles properly so I get most recent - 3 most recent. I'm trying to not be redundant on this articles page.

If my approach of creating two different views to achieve this effect is totally misguided, or if there's some other glaring way to do this more easily, please correct me. I'll be very grateful.

For clarity, I'm including a rough sketch, where the numbers indicate the recentness of the article and the top unit is the featured content slideshow display:

I would create a view and have two different displays. One display holds your slideshow thing and the other display holds the rest of the items.

The second display would be set to have the style item list and the pager settings should be set to have an offset of three. The offset will skip the first X items that are present in your first display.


Output Paragraph values instead of the Paragraph IDs in a View REST export? I have a View with a REST export display (image attached) that has some indexed field values from Search API.

The highlighted portion, authors, is a Paragraph field. Instead of the entity ID pointing to the Paragraph, how can I output a JSON object per delta with the field value?

Note, I am not using JSON:API (and cannot). Also, this is a Search API DB (and eventually Solr) based index, so 'Entity' mode cannot be used (and thus, no custom Normalizer).

What can I hook into, or what class can I create, to change how the Paragraph is being included in the result output? I thought about using a custom field formatter, but that seems like a lot of work just to output JSON data (classes, theme hooks, twig etc).

I thought about using a custom field formatter, but that seems like a
  lot of work just to output JSON data

No Code Solution:

Install Views Field View

Create a new View, "User view" in this case (does not to be a REST view).

Add user fields you want to show.
Add Contextual filter of ID

When adding, scroll down to the "More" section. Checkmark allow multiple values.

Go to your Rest View

Add field of "View", select the view you added above.

For contextual filter, use the replacement pattern for your author's field.


Change page title output How can I change the page title output?

<title>{{ head_title|safe_join(' | ') }}</title>

in html.html.twig changes the mark/letter which creates: <pagetitle> | <sitename>, but I want to change this order to <sitename> | <pagetitle>

Another option without the extra module overhead (still a valid option):

<title>{{ head_title|reverse|safe_join(' | ') }}</title>

Simply add the reverse filter to that part of your html.html.twig file

Twig rulez! Cheers!


What is the programmatic equivalent of block save? From hook_save(), I've updated the "pages" attribute of a block, adding a path to the list.

db_update('block')
    ->fields(array('pages' => $pages))
    ->condition('delta', $delta)
    ->execute();

I've used the database API, (maybe that's the problem?) instead of the block API, because I'm under the impression there is no support in Drupal 7 for this. (hook_block_configure() I think is just for changes to default block configuration.)

The problem I'm having is that the update to the block pages attribute is not reflected, even after clearing caches, until I go to block edit form and click on Save.

There's actually one thing in core's block module function block_admin_configure_submit, and that is to pass the event along:
   module_invoke($form_state['values']['module'], 'block_save', $form_state['values']['delta'], $form_state['values']);

I'm not sure how go about structure $form_state['values'].
Is there a way to do this with the block API?

With regard to Context, we're already using it; we could accomplish the same thing by writing to path to exclude to the context['condition']['path'] attribute, (prefixing the path ~ to indicated "exclude").   This might be a better approach for us, but still would like to see the block code working.

The solution is to call drupal_form_submit.  For example:

module_load_include('inc', 'block', 'block.admin');
$form_state = array();
$form_state['values']['module'] = 'block';
$form_state['values']['op'] = 'Save block';
drupal_form_submit('block_admin_configure', $form_state, 'block', $delta);

You can apply this solution to other forms: from the browser, inspect the submit button, and get the 'op' value and the form's machine name.  In source, find the admin.inc that implements the form, and include that, and get the submit functions parameter signature; in this case, the 4th parameter is the form's delta value.


Best way to get best breadcrumbs for Commerce When a user is checking the product page, the breadcrumb trail should give Home > Shop > Category > Product aka Home > Shop > Hats > A Hat

I used Crumbs, but it only gives me Home > Hats > A Hat and I cannot figure out how to include > Shop >.

Well obviously at the same time the breadcrumbs should also work fine in the rest of the pages like for contacts page it would be Home > Contacts

What would you recommend? What module? Or is it still possible with Crumbs and I am missing something?

You can add breadcrumbs in your page using drupal_get_breadcrumb and drupal_set_breadcrumb function

In template.php

 function THEMENAME_preprocess_page(&$variables, $hook) {

        if(arg(0)=='shoppage'){  //Put appropriate condition
            $breadcrumb = drupal_get_breadcrumb();
            $breadcrumb[1] = l('Shop', 'shop_link');
            $breadcrumb[2] = l('Category', 'category_link');
            drupal_set_breadcrumb($breadcrumb);
        }
    }


How to use current user object in Drupal 8? The answer to "Is there a function to get the current user object that avoids accessing the global variable?" includes this:

  In Drupal 8, you simply use the static method \Drupal::currentUser()
  to get the equivalent of Drupal 7 $GLOBALS['user']

I tried to use the following code:

$user = \Drupal::currentUser();
$name = $user->get('name')->value;

But that results in an error like so:

  Fatal error: Call to undefined method Drupal\Core\Session\AccountProxy::get() in /home/remindme/uhoc.org/modules/testmodule/src/Form/FruitForm.php on line 173
  (Line 173 is $name = $user->get('name')->value;

Do I need to used some namespace or there is some other way to access the user object?

Yes you need to use a name space, you can include the name space directly like this

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$name = $user->get('name')->value;


Login Security block my IP address I installed the Login Security module to block IP address for more than 4 number of login attempts, but unfortunately my IP blocked.

I tried uninstall the module, but still my IP address blocked. How to remove ban for my IP address. It shows the message Sorry, 00.000.00.00 has been banned.

I'm using Drupal 6.

Even though I uninstalled the module, I kept being banned. To remove the ban for a particular IP, I followed the following steps:

Connected to the database
Changed the access table; either  changing the status to 1 or deleting the row with  mask equal to '127.0.0.1' and type equal to 'host' works

I found the solution on Sorry, 127.0.0.1 has been banned.


Can not override template for specific view I'm new to Drupal so this might be a noobish question.
I have a view called 'Category' where all posts are listed that belongs to the chosen category.

I would like to override the views-view-unformatted.html.twig as well as the views-view-field.html.twig which is working fine for other views.

When I enable the twig debug mode I see this at the top of the page:

<!-- FILE NAME SUGGESTIONS:
   * html--taxonomy--term--31.html.twig
   * html--taxonomy--term--%.html.twig
   * html--taxonomy--term.html.twig
   * html--taxonomy.html.twig
   x html.html.twig
-->

So I thought templates with the name

views-view-unformatted--categories.html.twig
views-view-fields--categories.html.twig

would do the job. Or being even more specific:

views-view-unformatted--categories--block-1.html.twig
views-view-fields--categories--block-1.html.twig

But these templates aren't used.
I have also tried to use 'taxonomy--term' for the template names with no success.
There is also no file name suggestion for these templates.

Can anyone please tell me how I can get it working or hint me to the right direction?

You either haven't rebuilt cache, or the page you're viewing isn't being generated by your Categories Views. It seems to be generated by the default Taxonomy term Views. Or you're viewing the wrong page :)

Views templates debug info is shown further down the source HTML, you won't find it at the top of the source page. Try looking below the main page heading in the source HTML, that's there the page views will start with their own templates.

This issue is also relevant:
Views file name suggestions often missing from Twig debugging

Especially the fifth comment there:
#5

Also:
[PP-3] Twig debug output does not display all suggestions when an array of theme hooks is passed to #theme

I haven't tried this module but it may be relevant:
Views Templates


Comments only showing subject, no comment Using Drupal 7 with a custom made theme, the comments are only showing Subjects, and ignoring the comment body.

In my comment.tpl.php file I have:

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php print $picture ?>

<?php if ($new): ?>
<?php print $new ?>
<?php endif; ?>

<?php print render($title_prefix); ?>
<h3<?php print $title_attributes; ?>><?php print $title ?>

<?php print render($title_suffix); ?>

<?php //print $permalink; ?>
<?php print $submitted; ?>

<div class="content"<?php print $content_attributes; ?>>
<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['links']);
  print render($content);

?>
<?php if ($signature): ?>

  <?php print $signature ?>

<?php endif; ?>

Any ideas on how to get the comment to show?

I found the solution and it was pretty obviously now that I found it. In content type --> Edit --> Comment Display --> The Comment field was hidden! DUH!! :)


admin theme changes to default at editing page, Themekey module Using the ThemeKey module, I have changed the theme of user role (EDITOR) to Administration theme. So, when the user of this role logs in, he gets admin theme.

It works find but when he edit something the theme changes back to default. I want to have admin theme, even at editing pages for this user role. Please suggest.

I found the solution for this. I had to deselect the administration theme when editing or creating content, in admin/appearance.


Product questions in Ubercart I need some guidance in how to go about this.

I have some products (ubercart using Drupal 7) for which the users need to answer some questions with yes and no, before buying the product.

How can I achieve this?

You can use the Ubercart Webform Checkout Pane module.

  This module allows you to define Webform nodes as checkout/order panes
  in Ubercart.

  This is useful if you want to collect additional information during
  the checkout process. For example, you may want a quick survey or
  require additional fields that apply to the entire order.


Drupal 7 stopped working 500 internal Server error For some reasons, my site stopped responding today, Error

  The www.mysite.com page isn’t working

  www.mysite.com is currently unable to handle this request. HTTP ERROR
  500

I understand there are many reasons for 500 error and it hard to know what exactly happend, I had a look into server log and notice this error

  [Wed May 11 10:31:27 2016] [warn] [client x.y.z] mod_fcgid: stderr:
  PHP Parse error: syntax error, unexpected 'return' (T_RETURN) in
  /var/www/vhosts/mysite.com/httpdocs/pro/includes/common.inc on line
  5106.

Looking into common.inc

function drupal_json_encode($var) {
  // The PHP version cannot change within a request.
  static $php530;

  if (!isset($php530)) {
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
  }

  if ($php530) {
    // Encode <, >, ', &, and " using the json_encode() options parameter.
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  }

  // json_encode() escapes <, >, ', &, and " using its options parameter, but
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
  return drupal_json_encode_helper($var);
}

Line 5106 =   return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);

For some reason under PHP selector in Plesk dom and gd was disabled. after enabling those two the site return back to normal.


Configuration variable inside a hook take always the default value in a PHPUnit test I'm trying to create a Functional test for the dev version of the No Autocomplete module to test that if the configuration is set then an autocomplete attribute=off will be added to the password edit in the user login form.

<?php

namespace Drupal\Tests\no_autocomplete\Functional;

use Drupal\Tests\BrowserTestBase;

class FormTest extends BrowserTestBase {

  protected static $modules = ['no_autocomplete'];

  public function testUserLoginForm() {

    $account = $this->drupalCreateUser(['administer no_autocomplete']);
    $this->drupalLogin($account);

    $this->drupalGet('/admin/config/people/no_autocomplete');

    $edit = [
      'no_autocomplete_login_form' => 1,
    ];
    $this->drupalPostForm(NULL, $edit, 'op');

    $this->drupalLogout();
    $this->drupalGet('/user/login');

    $this->assertSession()->elementAttributeContains('css', '#edit-pass', 'autocomplete', 'off');
  }

}

So basically I'm trying to test this hook after that the configuration is set:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Turn off autocomplete on key forms.
 */
function no_autocomplete_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Add to the user_login.
  if (\Drupal::service('config.factory')->get('no_autocomplete.settings')->get('no_autocomplete_login_form')) {
    $form['pass']['#attributes']['autocomplete'] = 'off';
  }
}

The problem is that the module works as expected, but when I run the test this line inside the hook:

\Drupal::service('config.factory')->get('no_autocomplete.settings')->get('no_autocomplete_login_form')

Always return FALSE, because this is the default configuration value that comes in the no_autocomplete.settings file, if I change the value from FALSE to 5, the 5 is returned. But when I check the value of the config in the test it assert correct with TRUE, inside the test the value is TRUE but inside the hook the value is FALSE (or whatever the default value of the variable is) I check the value in the test with the following lines:

$config_factory = $this->container->get('config.factory');

$no_autocomplete_login_form = $config_factory->get('no_autocomplete.settings')->get('no_autocomplete_login_form');

$this->assertSession()->assert($no_autocomplete_login_form == TRUE, t('The default configuration value for no_autocomplete_login_form should be TRUE.'));

$this->assertSession()->elementAttributeContains('css', '#edit-pass', 'autocomplete', 'off');
  }

}

So, the configuration variable have TRUE as value, but inside the hook the value is always FALSE, so the autocomplete=off attribute is never added to the form element en the test fail.

I'm trying to read in the wrong way the variable inside the hook or I'm missing something here?

EDIT: It seems a cache problem, if I clean the cache inside the hooks the test is OK, but the only problem is that I really don't need to clean the cache for made the module works.

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Turn off autocomplete on key forms.
 */
function no_autocomplete_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Add to the user_login.
  drupal_flush_all_caches();
  if (\Drupal::service('config.factory')->get('no_autocomplete.settings')->get('no_autocomplete_login_form')) {
    $form['pass']['#attributes']['autocomplete'] = 'off';
  }
}

So I don't know now if this is a Drupal or PHPUnit issue. Any ideas?

I found an answer that solve this problem, but I think that maybe there are other answer to this.

After some ideas from @tim.plunkett on slack:

  as i see it: with render caching, changing the config value will not
  alter the form

and

  the tl;dr is that any conditionals in render-related code need cache
  contexts

I made the test work with this code:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Turn off autocomplete on key forms.
 */
function no_autocomplete_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Adding cache tags.
  $form['#cache']['tags'] = ['config:no_autocomplete.settings'];

  // Add to the user_login.
  if (\Drupal::service('config.factory')->get('no_autocomplete.settings')->get('no_autocomplete_login_form')) {
    $form['pass']['#attributes']['autocomplete'] = 'off';
  }
}

This is the simplest way that I was found because in this case the config object only have one variable and each time that the config is changed is because this variable has changed, so in this case I think that the use of the cache tags is fine.

But I'm still trying to made works the code with a custom cache contexts. But I don't have luck for the moment.


Form doesn't submitted <?php

        //https://www.drupal.org/node/1806758
        function mhzipcode_block_info() {

          $block = array();
          $block['mhzipcode'] = array(
            'info' => t('mhzipcode'),
          );
          return $block;
        }
        /*
        Implement hook_block_view
        */

        function mhzipcode_block_view($delta= ''){
          $block = array();
          switch($delta) {
           case 'mhzipcode' :
             $block['content'] = drupal_get_form('mhzipcode_storage_form');
           break;
          }
          return $block;
        }
        /*
        Implement zipcode_view function
        */

        function mhzipcode_storage_form($form, &$form_state) {
          if ($form_state['rebuild']) {
            $form_state['input'] = array();
          }
          // Initialize
          if (empty($form_state['storage'])) {
            if (empty($form_state['input'])) {
              $_SESSION['constructions'] = 0;
            }
            // Put the initial thing into the storage
            $form_state['storage'] = array(
              'thing' => array(
            'zipcode' => '',
            'phonenumber' => '',
              ),
            );
          }
          // Count how often the form is constructed.
          $_SESSION['constructions']++;
          //drupal_set_message("Your form has been saved.");

          $form['zipcode'] = array(
            '#type' => 'textfield',
            '#title' => 'Zip Code',
            '#size' => 15,
            '#default_value' => $form_state['storage']['thing']['zipcode'],
            '#required' => TRUE,
          );
          $form['phonenumber'] = array(
            '#type' => 'textfield',
            '#size' => 15,
            '#title' => 'Phone Number',
            '#default_value' => $form_state['storage']['thing']['phonenumber'],

          );
           $form['continue_submit'] = array(
            '#type' => 'submit',
            '#value' => 'Continue submit',
            '#submit' => array('mhzipcode_storage_form_submit'),
          );

          if (isset($_REQUEST['cache'])) {
            // Manually activate caching, so we can test that the storage keeps working
            // when it's enabled.
            $form_state['cache'] = TRUE;
          }

          return $form;
        }
        function mhzipcode_storage_form_submit($form, &$form_state) {
          $zipcodeAlias = $form_state['values']['zipcode'];
          $zip_code = db_query("select PhoneNumber from {Phone_number} where Zipcode='".$zipcodeAlias."'")->fetchField();
          die;
          $form_state['storage']['thing']['phonenumber'] = $zip_code;
          $form_state['rebuild'] = TRUE;
        }

Form doesn't submitted and mhzipcode_storage_form_submit isn't working .doesn't load this function code , and die is not load .

I have tested it in my module, i didn't get any issue. It worked fine for me.
The output i received after using print_r(); and die(); in my submit function is

Array
(
    [zipcode] => 23423423
    [phonenumber] => 423423423
    [continue_submit] => Continue submit
    [form_build_id] => form-zVFjX4fMorTyOI6m3JE0SL3w0_rSCTsVzEho63Qb1u4
    [form_token] => Pg3erepuKQvtsCSQT-3G7FWLivsSWDH69P0Z3YfRD6M
    [form_id] => mhzipcode_storage_form
    [op] => Continue submit
)

Just try it in a separate module where no extra code exists and then debug the issue.
It can be conflict with some module or any other issue. Hope it will help.


How to do some calculations using fields within a Field Collection field? I have a Field Collection field and I'm trying to do the following:

Multiply the value in one field with the value in another field and have the result shown within a third field.

I have tried Mathfield, but it doesn't support Collection Fields.

Is it possible to do this with Computed Field? How? Or would be difficult to write a custom module to do this?

You can do it by using Computed Field.
The sentence
$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
foreach($wrapper->field_FIELDCOLLECTION as $collection) {
$sum += $collection->field_SUBFIELD->value();
}
$entity_field[0]['value'] = $sum;


Role Hierarchy and Management of Assigned Users I need to set up a role hierarchy like this:

Super Admin - Full permissions, can manage all users and content

Regional Manager - can manage only his/her own Store Managers;
cannot manage another regional manager's Store Managers. Can manage
those users' content as well.

Store Manager - can manage only his/her own employees; cannot manage another store manager's employees. Can manage those users'
content as well.

Employee - the low-end of the totem pole. All they can do is create content of a certain type.

How can I go about setting that up?

Thanks!

You could try to use Organic Groups, it's a module used in many distributions, Open Atrium probably would be the most popular.

With OG you could create groups and assign permissions to create/update content only in those groups.


How to reset values of elements in multi-step form I'm building quite a complicated and large custom form. Below I've made a simple example form to demonstrate my case:

function mymodule_form($form, &$form_state) {
  $form['step1']['element1'] = array(
    '#type' => 'select',
    '#title' => 'Element 1',
    '#options' => array('All' => '- Any -', 'option1' => 'Option 1', 'option2' => 'Option 2'),
  );

  $form['step1']['element2'] = array(
    '#type' => 'select',
    '#title' => 'Element 2',
    '#options' => array('All' => '- Any -', 'option1' => 'Option 1', 'option2' => 'Option 2'),
  );

  $form['step1']['addfilter'] = array(
    '#type' => 'submit',
    '#value' => 'Add filter',
    '#name' => 'addfilter',
    '#ajax' => array(
      'callback' => 'mymodule_form_callback',
      'wrapper' => 'results-div',
    ),
  );

  $form['step2'] = array(
    '#type' => 'fieldset',
    '#title' => t('Results'),
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // Ajax values process
  if(isset($form_state['values'])) {
    foreach($form_state['values'] as $key => $value) {
      if($value != 'All') {
        $form['step2']['step2-'.$key] = array(
          '#type' => 'button',
          '#value' => 'remove ' . $key,
          '#name' => 'step2-'.$key,
          '#ajax' => array(
            'callback' => 'mymodule_form_remove_callback',
            'wrapper' => 'results-div',
          ),
        );
      }
    }
  }
}

function mymodule_form_callback($form, &$form_state) {
  return $form['step2'];
}

function mymodule_form_remove_callback($form, &$form_state) {
  // What to do here???
}

Basically what should happen is:

Select a value from the step1 elements
Click Add Filter button
The form function runs again, and this time it creates ajax'd "remove" buttons under step2.
When you press the remove button, the corresponding form element in step1 should get its value reset to 'All' and the corresponding step2 button needs to get removed.

I'm getting stuck at step 4, I'm not sure how to reset a submitted multi-step form's values.

As I understand it, you don't need the ajax callback for the remove button. You should be able to do that with just using jQuery, and a rel attribute to hold the ID. Consider the following:

Add a class for the jQuery script and a rel attribute that holds the Step 1 element count id to the remove button.

$form['step2']['step2-'.$key] = array(
  '#type' => 'button',
  '#value' => 'remove ' . $key,
  '#name' => 'step2-'.$key,
  '#attributes' => array('rel' => 1, 'class' => 'remove-button'),
);

jQuery script to remove the "remove" button and reset the the Step 1 form element.

$('.remove-button').click(function(e) {
  var id = $(this).attr('rel');
  $('#element'+ id +').val('All');
  $(this).closest('.button-wrapper-class').remove();
  e.preventDefault();
});

This is (most likely) non-working example code, but I think you'll understand my point.


Render content from page.tpl.php in ajax callback, without the html.tpl.php I am attempting to render an entire page through an ajax callback using either custom javascript or drupals ajax_deliver.  The issue is that it is trying to render the entire page and I simply want it to render what is in a custom page.tpl.php file created.  I have found a solution around this using a $_GET in the html.tpl.php but it seems hacky to me.

Basically I am rendering only the $page variable if a $_GET is set, if not render it as normal.  Is there any functions or way to simply render all the regions in a page, minus what is in the html.tpl.php

There is AJAXify Pages (dev version only)

  Module to ajaxify site browsing and navigation. For instance, it
  allows for continuous audio playback via Background Audio module while
  changing the content of the pages.

or AJAXify module (D5 only)

  You can always create links that load other pages via AJAX but you
  will still load a full page HTML while you may only need a single HTML
  element from the loaded page and this is what AJAXify focuses on.

If youre not planning to use any of these module take a look at THIS function
to get some idea.


block['content'] contail both string and form I created a form and used a block to show it. I would like to add a message before the form. Before I added "You can use the form below," the form was working fine. Right now, it doesn't work.

The code is the following one.

$block['content'] = 'You can use the form below';
$block['content'] .= 'Enter your email';
$block['content'] .= drupal_get_form('custom_request_price_form');

It just shows "Array" where it should show a form. Why does this happen?

drupal_get_form returns an array, so you can't concatenate it with a string.

Something like this will work, using a render array:

$block['content'] = [
  'preamble' => [
    '#markup' => '<strong>...</strong>',
  ],
  'form' => drupal_get_form('custom_request_price_form'),
];


Using migrate module to import to a list_boolean field I'm trying to use the migrate module to import data from a mysql table to Drupal 7. I've created a content type with a field type of boolean and used "single on/off checkbox" as the widget. So in the migration destinations the field is (list_boolean).

The data in the database is integer (0/1).

I set the field mapping:
$this->addFieldMapping('field_my_event', 'my_event');

However, none of the 1's get stored as 1 in the field_my_event table when migrated.

I tried also forcing the value to a boolean value of TRUE/FALSE in the prepareRow hook, but that didn't make a difference.

versions I'm working with: Drupal 7.33 and Migrate 7.x-2.6-rc1

Can someone steer me in the right direction?

See this comment on this issue:
https://www.drupal.org/node/1729996#comment-9511751

"I found a way to import, you must set the "on" and "off" values.

I went to my field in my content type and set the "on" value to 1 and
the "off" value to 0.

In the migration mapping I made a callback function for this field and
convert my true value to 1 and the false value to 0, you could do this
instead creating a new feature.

This way worked perfectly here.

I don't know if it is a really necessary feature."


How to validate node field for minimum length for a custom content type? I notice body has some preselectable minimum lengths.

How do I do this for text fields?

Also, how do I set a custom minimum length for node body of a content type?

hook_form_alter() would alter your node edit form to define a custom validate handler.

function custom_module_form_alter(&$form, &$form_state, $form_id){
   ...
   case 'form_id': //applying this check will help to restrict only on certain content type form
      $form['#validate'] = 'custom_validation_handler';
   break;
   ...
}

And when this validation handler is invoke upon submitting the node form it will validate the field value in following logic.

function custom_validation_handler($form, $form_state){
   if(strlen($form_state['values']['field_id']) < 200){
       form_set_error('field_id', t('message about validation error'));
   }
}

If form_set_error() is invoked the form will not be submitted and will be back with validation error message.


what is #target_type in EntityAutocomplete? what is #target_type in EntityAutocomplete?

in EntityAutocomplete it said: #target_type: The ID of the target entity type.

how can i see the list of the ID?

and

can I extend the ID on my own?

Thank you,
AnD

The ID accepted from EntityAutocomplete is the ID of any entity defined from Drupal core, or third-party modules.

You don't normally need to have a list of all possible entity IDs, since you normally know which entity your code is going to autocomplete, but the list can be easily obtained using the following code.

print_r(array_keys(\Drupal::entityTypeManager()->getDefinitions()));

I ran drush ev "print_r(array_keys(\\Drupal::entityTypeManager()->getDefinitions()));" on my test site, and I got the following.

[0] => block
[1] => block_content
[2] => block_content_type
[3] => comment
[4] => comment_type
[5] => editor
[6] => field_config
[7] => field_storage_config
[8] => file
[9] => filter_format
[10] => image_style
[11] => configurable_language
[12] => language_content_settings
[13] => mollom_form
[14] => node
[15] => node_type
[16] => rdf_mapping
[17] => responsive_image_style
[18] => search_page
[19] => shortcut
[20] => shortcut_set
[21] => action
[22] => menu
[23] => taxonomy_term
[24] => taxonomy_vocabulary
[25] => tour
[26] => user_role
[27] => user
[28] => view
[29] => menu_link_content
[30] => date_format
[31] => entity_form_display
[32] => entity_form_mode
[33] => entity_view_display
[34] => entity_view_mode
[35] => base_field_override


How to prevent Drupal from automatically truncating blog entries? When you enable the Drupal 7 Blog module, the blog page (http://mydrupal.tld/blog) displays truncated blog entries.  It looks like Drupal truncates after the end of the first paragraph (<p>).  In order to see the entire blog entry, you have to click on its title or on the Read more link.

I'd like to save that click to my visitors by displaying full length blog entries directly on the blog page.

It seems that print render($content); performs the truncation, but I couldn't find anything in the method's API about that.

Any idea ?

The length of the body text for a node teaser is set in the "Manage Display" section for  the content type's fields.

Just go to http://mysite.com/admin/structure/types/manage/blog/display/teaser, and change the format/format settings (i.e. "Trim length") until the teasers look exactly like you want.


Change a block programatically, accesing to the Views results I have a Views block, which prints a list of products, in unformatted text. I would like to wrap each of these items with a custom href string, which is somehow convoluted and so it is difficult to set in the Views options. I have managed to do so, by retrieving the Views results with hook_views_pre_render and

foreach($view->result ...

and then print the results directly to screen. If I use, instead,

block_view_VIEWS_MY_VIEW_BLOCK_alter and

$data["content"]["#markup"]

I have the problem that the data is in raw form and cannot achieve my initial goal.
What method should I do for this apparently simple goal? I want the block to be finally printed by Drupal, even if modified with the href added programatically, but the rest of properties (pager, etc.) remaining untouched. Thanks!

Reading from some sources and experimenting a little, I have been able to reply to my question. In your template, you must put the views-view-unformatted.tpl.php file (from themes folder), and there you can modify each of the rows based in some logic (though logic should be constrained to template.php y from there populate a variable in this tpl).
The output of the view must be unformatted text, and the "auxiliary" data must be added, but hidden from view.

<?php

/**
* @file
* Default simple view template to display a list of rows.
*
* @ingroup views_templates
*/
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; $i = 0;?>
<?php foreach ($rows as $id => $row): ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php

if($view->result[$id]->taxonomy_term_data_description != ""){
 // Here I use a logic to show only the item name surrounded by dots.
  print ".." . $row . "..";
}else{
 // Here I use opposite logic to show the link
     print "result[$id]->taxonomy_term_data_description . "'>" . $row . "";
} // if
$i++;
 ?>


How to add a button to a custom table that opens a form in a new tab and automatically fills out with data from that table I have a custom module where I create a table from some data. In one of the columns I need to have a button that when clicked will open a new tab and show the user a form and a submit button and some of the form fields are pre-filled with data from the table (data from the same row).

I know how to add a button but I don't know how to pass the data to the form.

Also, for the button I'm using the following code and maybe this is already wrong:

$new_button = 'New form';

Note: the data is not in the drupal database. The table is made on the fly using REST.

Any help will be greatly appreciated. Thanks!

Prepopulate module can pass value to form with query parameter.

Simple example:

New form';

More examples can be found on its documentation.

If you find problems, please check this issue, some known bug has been introduced from 7.x-2.1 version. You may need to patch it.


No search results display when using core search I have added Drupal the search module block and it displays the search form.

When I type and click on search button, it displays nothing, just a refresh in page only.

What do I need to do to get search results to show up? I could use alternative search modules if that is recommended/necessary.

Note: I've already indexed the content. In configuration page, it's showing "your 100% content has been indexed".

Actually, It was just a refresh happens to the page, while clicking the search button.  Anyway, I just added custom search module in drupal and its now working fine :).  Thanks for all :)


Would disabling core modules, which I don't need, speed up my site? Would disabling core modules which I don't need, like Color, speed up my site? If so, why?

In theory, the answer is yes, but in practice, I doubt it. It depends entirely on on the module though.

If you have badly written module that implements hook_boot, so it executes on even cached page requests, and it performs lots of logic in there, and you have no use for it, then sure, you would gain speed from disabling it.

Most likely though, the average module is going to be implementing logic that is only actually executed when it is used, so if you don't use it it's not going to cost much.

If it's a big module, you could see a small dent in memory usage, as all enabled modules are loaded into memory, and as pointed out by Mołot, a modules variables and menu router entries will consume some resources, but again, I think in practice, it's not going to make a big difference.

That said, if you don't use the module, why keep it enabled? It by definition doesn't provide you with any benefit if it's not used, and at least it's going to clean up the administrative pages.


HTML table to Drupal table How can I translate this to drupal table?

http://www.bootply.com/sXmuAJQjO4

I know how to do simple tables and the header and first row I can do also with this code:

$title = '

Table Title

';

    $header = array(
        array('data' => '&nbsp;'),
        array('data' => 'Job Name'),
        array('data' => 'Description'),
        array('data' => 'Provider Name'),
        array('data' => 'Region',),
        array('data' => 'Status'),
    );

    #'data-toggle' => 'collapse'
    $row = array(
        'data' => array(
            array('data' => '<button class="btn btn-default btn-xs"></button>'),
            array('data' => 'OBS Name',),
            array('data' => 'OBS Description'),
            array('data' => 'hpcloud'),
            array('data' => 'nova'),
            array('data' => 'created'),
        ),
        'class' => array('accordion-toggle'),
        'data-toggle' => 'collapse',
        'data-target' => '#demo1',
    );
    $rows[] = $row;

But I can't add the hidden row. Can anyone help me?

Thanks!

For the hidden row, you need a second table which would look like:

// This is the hidden table
$table_hidden = '
';
$table_hidden .= theme('table', array('header' => $header_hidden, 'rows' => $rows_hidden));
$table_hidden .= '
';

$row2 = array(
  'data' => array(
    array(
      'data' => $table_hidden,
      'colspan' => '12',
      'class' => array('hiddenRow'),
    ),
    array('data' => 'OBS Name',),
  // more array data here
);

Option 2, a more module-clean way would be to use hook_theme function and create a simple template file where additional markup is placed like so.

function YOURMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'any_name_you_like' => array(
      'template' => 'hiddentable', // This called hiddentable.tpl.php
      'arguments' => array('table' => null),
    ),
  );
}

Then in your page callback or wherever, you would just need to use your declared theme function like so.

$table_hidden = theme('table', array('header' => $header_hidden, 'rows' => $rows_hidden));

$row2 = array(
  'data' => array(
    array(
      'data' => theme('any_name_you_like', array('table' => $table_hidden)),
      'colspan' => '12',
      'class' => array('hiddenRow'),
    ),
    array('data' => 'OBS Name',),
  // more array data here
);

Now in your hiddentable.tpl.php

  <?php print $variables['table']; ?>


Is there ever justification for adding HTML before passing content to a twig template? There seem to be many people trying to pass HTML markup into a twig template and having trouble doing it. It sounds like the best solution is to use something like:

$variables['test'] = ['#markup' => 'some markup'];

But, when would this be preferable (or necessary) over adding the markup in the twig template instead?

It's not possible to put all html markup in templates. Often for example in case of an error you need to generate some extra markup.

If it is a string constant like in your example this is no problem.

If you have variables, don't concatenate in markup.

Use Drupal\Component\Render\FormattableMarkup instead:

$variables['error']['#markup'] = new FormattableMarkup('Error @message at line @line', [
  '@message' => $message,
  '@line' => $line,
]);

Most times you need to make this translatable and this is why t() is still one of the most used functions in drupal:

$variables['error']['#markup'] = t('Error @message at line @line', [
  '@message' => $message,
  '@line' => $line,
]);

If you are in a class use $this->t().

To summarize, the answer to the question is yes, there is justification for adding html in php. This is, if you need to react dynamically on things happening in your code. Then instantiate a new FormattableMarkup object. If you need translation, you can simply use t().


How to make a complex grid layout with the Omega theme? How do I make a complex grid layout with the Omega theme where regions can be embedded in regions? I included an image of how I want the page layout to be set. Right now I'm thinking that I will use the CSS property in the Views UI to manually set the grid-[columns] and alpha or omega properties of the Views block. Is there a better way of doing this so the code is in a logical place and not a hack?

For something like this, I will simply use the Block Class module and for the blocks I'm placing inside a region, add a grid-X and alpha/omega appropriate classes as needed.

I've never found the reason (even in really advanced layouts/designs/grids) to do anything more than that...


How do I override an entity view controller? I am trying to override the entity view controller for a commerce product view, so that I can  redirect the user based on certain conditions.
I am trying to do this through the RouteSubscriber::alterRoutes implementation.
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.commerce_product.canonical')) {
      $route->addDefaults(['_controller' => '\Drupal\mymodule\Controller\ProductViewController::view']);
    }
  }

}

My custom controller is acknowledged, but I'm getting the following error:

RuntimeException: Controller "Drupal\mymodule\Controller\ProductViewController::view()" requires that you provide a value for the "$_entity" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one. in Symfony\Component\HttpKernel\Controller\ArgumentResolver->getArguments() (line 78 of /var/www/html/vendor/symfony/http-kernel/Controller/ArgumentResolver.php).

My ProductViewController extends the Drupal\Core\Entity\Controller\EntityViewController.
class ProductViewController extends EntityViewController {

  public function view(EntityInterface $_entity, $view_mode = 'full')
  {
    return parent::view($_entity, $view_mode);
  }

}

Can anyone tell what additional route context parameters I need to add to get this working?

I think you may be unsetting some things in your alterRoutes method doing it the way you are. (However, I can't tell if or why that's happening after looking at Route::addDefaults().)
I'm doing the same thing for a media entity's route. My alterRoutes method is a little different - I'm using Route::setDefault().
public function alterRoutes(RouteCollection $collection) {
  if ($route = $collection->get('entity.media.canonical')) {
    $route->setDefault('_controller', '\Drupal\my_module\Controller\MyController::view');
  }
}

Additionally, the variable names in your controller methods are important - they must match the variable name from the route definition. See the documentation for Using parameters in routes

In most PHP code the name of the variable does not matter but here it does: the name of the method argument must match the slug. Conversely, if the method argument name matches the name of the slug, the parameter will be passed in, irrespective of the order of arguments.


All my blocks are gone. Even the block menu entry is gone Anyone know what I might have done? I found a few things about hook_block being implemented in template.php causing this, but I don't implement hook_block at all.

If you have a module and theme with the same name, this will happen (regardless if you do/don't have hook_block in either of theme).


Am I able to call functions in my custom module from other modules? I would like to integrate the Barcode (http://drupal.org/project/barcode) module functionality into a custom shipping module that I am creating.

I would like to make calls the genBarCode method or something similar so I may generate barcodes within my module.

Is this ok within the context or custom/contrib modules and if so how can it be done?

There are two issues:

Is the function you're going to call intended to be an API function? In general, functions that are not intended to be called by other modules are prefixed by an underscore as in _mymodule_private_function().
Is the function in a file that is guaranteed to be loaded when you need it to be.  If it's in a .module file and the module is enabled, then it will be available. If it's in a class that's declared in a file listed in a files[] declaration of an enabled module's .info file, it will also be available. If it's a regular function in a .inc file, you may have to force it to be loaded with module_load_include() or require_once() or similar techniques.

How do you do it? Just call the function the same way as that module calls the function, the same way as you call any Drupal core function.

Don't forget to make the module a dependency of your module.


Provide unique values from a user profile field in a content type field (How to use DISTINCT in ER View)? My users profiles contain a field with department name.

How can I make the unique values from department available in a select list within a content type field?
i.e. Sales, Marketing, IT, etc. (to avoid duplicates).

UPDATE:

I created Entity Reference > Select List > User (target type) + a view with ER that contains the user profile field department, but Query settings DISTINCT still doesn't get rid of the duplicates.

I even tried views_distinct module with Filter Repeats.

Try using aggregation. Set this value in your View under Advanced > Use aggregation. The Group Results Together aggregation type should be the default and should provide the behavior you're looking for.

If this isn't quite what you're looking for, please export a copy of your view configuration, from Configuration > Development > Configuration synchonization > Export, then select Single and find your view under the Views dropdown and update your question with this export.


Printer - PDF format: How can I change the header info and add page count on the footer? I like this Printer module on my Drupal 7 site. But, when it generates PDF, it contained breadcrumb and no page-count on the footer. Is there a way to add name of "Content type" and node "Title", instead of breadcrumb? I also would like to have the page-count number on the footer on every page. Is there a file that I can modify?

PS: I'm using mPDF third-party tool

The Print module uses a separate template for the print, email, and PDF versions of a page.  You would need to implement a hook_preprocess_print() to set up some addtional variables, and then duplicate print.tpl.php into your theme and use your new variables (and/or change the markup in the template).  The default template file is rather well documented, and explains what is possible.


Is this the proper way to alter a path defined in code by another module? I have installed the FAQ module on my site, and it defines the path to the FAQ page in code as 'faq-page'. I would like to make the path be 'mypath/faq' instead. I think I need to create a little module that implements hook_menu_alter(), so that if I upgrade the FAQ module, my custom path won't be overwritten. I think it should go something like the following:

/**
* Implements hook_menu_alter.
* Override FAQ page path defined by the FAQ module.
*/
function MYMODULE_menu_alter(&$items) {
  $items['mypath/faq'] = $items['faq-page'];
  unset($items['faq-page']);
}

Is this the proper way for me to override the path defined by another module?

No, that's not the right way. You are actually looking for aliases. They are provided by the Path module that is integrated in core.

It's possible to do it the way you propose, but it comes with possible side effects and is a little to much for what you want.


Why do functional tests require a running website? I'm trying to set up functional tests in Drupal 9 using the BrowserTestBase class. The Type of Tests page on drupal.com and Browser test tutorial are quite clear that browser tests will build their own website and browser.

Browser tests create a complete Drupal installation and a virtual web
browser and then use the virtual web browser to walk the Drupal
install through a series of tests, just like you would do if you were
doing it by hand.

However, as soon as I try to run a browser test using run-tests.sh I get an error stating that the --url parameter needs to be provided (this led me down a rabbit hole: Curl error in basic functional test). There is a tutorial on running browser tests, which clarifies that the --url parameter is in fact needed.

In phpunit.xml make the following changes:

Set the SIMPLETEST_BASE_URL variable to the URL of your site.
Set the SIMPLETEST_DB variable to point to the URL of your Drupal database.
If you are placing phpunit.xml somewhere other than core, change the value of the phpunit tag's 'bootstrap' attribute to reflect the
new location.
For kernel and functional tests, set the BROWSERTEST_OUTPUT_DIRECTORY.

The section titled Run All PHPUnit Tests The Way The Testbot Does It sheds a bit of light on this by clarifying that when testbot runs a Browser test, it sets up a drupal site with the testing module enabled.

The first step is to make sure you have a fully working Drupal
installation, with the Testing module enabled. The drupal.org testbot
assumes that contributed modules will be installed inside the
modules/contrib directory and Drupal's application root for unit tests
is set to a value assuming this directory structure.

This seems to suggest that the browser test does not "create a complete Drupal installation" but rather requires one, but that leaves more questions about these tests.

Can the URL be any drupal site with the testing module enabled?
What changes does the test make to the website?
Do I need a fresh site everytime I run the tests?
Do I need to provide login details? Is that handled by the testing module?
What about the database, what changes are made to it? How do I revert them?

Any kind of clarity on how this works would be appreciated, as I think it will probably answer my other question as well.

You can theoretically run a functional test on a production website. (I am not saying you should though.)
In my experience the testing framework will install a new Drupal site for every individual test and in the end remove these sites. This is done by creating testing tables in your existing database, for which you need to provide the credentials in SIMPLETEST_DB.
As long as the tests do not error, all of this data will be cleaned up at the end of the test and you do not need to worry about anything.
If the test unexpectedly stops you might need to clean op some items manually (previously could be done with simepletest module, but I believe there are plans to remove that).
I have no idea if you can use a different site. You need to have database access to that site to install the testing tables. Modules should be available, etc. I do not think it would be reliable.


Get the CCK field value using dbquery I have a content type called user registration under this one cck field called regid. i would like to fetch the entered values of this particular field through programmatically probably by using dbquery() functions and print it. Anyone guide me how to achieve it.

Here is a little example, how to make requests in Drupal 6. You may change table name and field name and it should work for you.

$query = db_query('SELECT n.nid, regid.regid_FIELD_VALUE
   FROM {node} AS n
   JOIN {regid_FEILD_TABLE_NAME} AS regid ON regid.vid = n.vid
   WHERE n.type = %s AND n.status = %d, $your_node_type, 1);

$result = array();
while($node_data = db_fetch_object($query)) {
  $result[] = array(
    'nid' => $node_data->nid,
    'regid' => $node_data->regid_FIELD_VALUE,
  );
}


Why can I not login on my live site? I am not able to login on my site.  All the times I try, I get this error:

  Sorry, unrecognized username or password. Have you forgotten your password?

I checked 10 times, but the password I use is correct.

I am not sure what happens; even if I try to create a new account, and login, I still get the same error.

I was able to login with that username and password previously, even on live, where I am still able. It is just on local where I cannot login anymore.

mod_rewrite is enabled on the server, so the problem cannot be that. I noticed that the session is automatically destroyed, for the administrator user.

Why does this happen?

Please check:

your cookie_domain value in your settings file

Normally it should work when it's empty, however if you're using across multiple domains or protocols (e.g. form is HTTP, but you're submitting to HTTPS), you should set it to its full domain name, so Drupal automatically generates a unique session cookie name for each site. E.g.

$cookie_domain = '.www.example.com';

or assign it dynamically like (not recommended):

$cookie_domain = @$_SERVER["SERVER_NAME"];

watchdog logs, e.g. drush ws --tail,
if you're using LoginToboggan or similar, check whether you should use username or e-mail to login,
whether cookies are created fine in DevTools console,
if you're using Varnish, check whether cookies are deleted,
try login to the site using one time login link, e.g. via drush uli command and verify that your account works (it's not blocked or something),
try in another browser or in incognito mode,
disable any 3rd party authentication modules (ldap, openam, etc) which may override the default logic,
debug your code using XDebug.


How to place custom menu in user profile I have created a user menu as shown below

I am using Edit Profile and Me alias module and the menu system is as below

Edit Account : user/uid/edit
Edit Profile : user/uid/edit-profile
Logout : user/logout

This works fine but I am not able to display it on http://localhost/user or http://localhost/users/uname (alias to the former url). I wanted to show this menu only on that page.

In the 'Visibility settings' of the block, using 'Only on listed pages' option I tried various like user, users/me, http://localhost/user, http://localhost/users/me, but the menu is not appearing on the user page. When I check it with other pages, it works fine. Any idea what might be the cause?

I have been searching for this for 2 days now, and decided to go for bounty. But, didn't know the solution was so simple. I tried doing the same on fresh install of Drupal and it worked fine. And kept on adding the modules one by one, again testing the functionality for any change.
It appeared to me that after disabling Menu token module, the requirement worked absolutely fine.
Then I checked to see if I gave a wrong token replacement. And the menu structure which i was using was as below

--My Account with path [node:url:absolute] which i thought would direct to same page.
----Edit Account with path user/me/edit
----Edit Account with path user/me/edit-profile
----Logout with path user/logout

And I used gave the path as *user/** in the Visibility settings of the block(highligted of corporate theme) as discussed in question and comments above,

The Problem identified(as per me) was that I was considering user profile page as a node which I think now is wrong, so the token [node:url:absolute] was actually a wrong token and hence the menu was not displaying on user page. What I did is changed it simply to [current-page:url] (as I wanted the user to be on same page, and I suppose we cannot give # in the path of the menu to achieve it)as shown in fig below and used the same visibility settings and it worked :)
So, basically the parent menu path was wrong which created the problem. Nevertheless, it was good learning experience!!


How to highlight active teaser in Views? Using Views and Panels, I have an unordered list of node teasers that appears on every page. When viewing a node, I would like to highlight that node's teaser in the list.

Class .active gets applied to the teaser link, but I'd like to apply it to the whole list item. Is this possible?

The following does the work for me:

function YOUR_THEME_preprocess_views_view_unformatted(&$vars) {

  if (arg(0) != 'node') return; // no active node

  $index = 0;
  foreach($vars['view']->result as $node) {
    if (arg(1) == $node->nid) {
      $vars['classes_array'][$index] .= ' active';
    }
    $index++;
  }

}


How can I display 2 or more fields horizontally? In my content type I have several fields. I want to display two or more of them horizontally.

Here is an example:

 Auto
+------------+
|  INPUT     |
+------------+

 Ascensore
+------------+
|  INPUT     |
+------------+

Nome                Cognome
+------------+          +------------+
|  INPUT     |          |  INPUT     |
+------------+          +------------+

Città
+------------+
|  INPUT     |
+------------+

How can I do this?

By using the Display Suite module you should be able to do this.

By default Drupal core wraps fields in multiple HTML elements. Display Suite allows you to override this markup via the user interface by using field templates. You can add CSS classes to the fields and start styling them in your CSS.

For more details, refer to the Community Documentation about Control markup with field templates.


Notices: Undefined index and trying to get property of non-object include() I have a "page--front.tpl.php" and get these notices:

  Notice: Undefined index: nodes include() (line 47 in file /home/dunmicro/public_html/sites/all/themes/dunartis/page--front.tpl.php).

  Notice: Trying to get property of non-object include()(line 47 in file /home/dunmicro/public_html/sites/all/themes/dunartis/page--front.tpl.php).

Here is my code:

<?php if ($site_name): ?>
    <?php if ($title): ?>
      <div id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>

          <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">
                      <?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?>

    <?php else: /* Use h1 when the content title is empty */ ?>
      <h1 id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>
        <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">
                    <?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?>

    <?php endif; ?>
  <?php endif; ?>

How do I fix these notices?

You need to check if $page['content']['system_main']['nodes'] is set or not:

Please check updated code:

<?php if ($site_name): ?>
    <?php if ($title): ?>
      <div id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>

          <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">

<?php if(isset($page['content']['system_main']['nodes'])):?>
<?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?>
<?php endif;?>

    <?php else: /* Use h1 when the content title is empty */ ?>
      <h1 id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>
        <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">

<?php if(isset($page['content']['system_main']['nodes'])):?>
<?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?>
<?php endif;?>

    <?php endif; ?>
  <?php endif; ?>


Hide the "view exposed filter" form or reload the page after submit the form? I am using view exposed filter on a view display as "block". The block is added to dashboard.

I added a second function to "Apply" button using hook_form_alter. I want to hide the expose form of view after submit it. I added the jquery to hide the element using drupal_add_js. But it didn't work.

Is there any way to hide the form or reload the page after submit of expose form so i can hide the form on page load?

Try this:

function custom_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-YOURVIEWNAME') {
    if($_GET['xxx'] == 0){
      hide($form);
    }
  }
}


New Drush install instructions use Composer for install, even on Drupal 7? The current Github install instructions for drush (http://docs.drush.org/en/master/install/#git-clone-ie-manual-install) say as the last step:

  From Drush root, run Composer to fetch dependencies.

  $ composer install

Since Drupal 7 does not usually have Composer installed, I assume these are Drupal 8 specific instructions.

Where can I find a link to instructions for installing Drush for a Drupal 7 install, where composer is not present?

Drush uses composer to install its dependencies, so please follow the composer instructions regardless of whether you plan to use drush with Drupal 7 or Drupal 8.


How to add custom fields and display settings to built-in content types via custom module install? I'm pretty new to Drupal, I come from Wordpress development and I'm trying to "translate" some of my plugins to modules in Drupal 8.

I'm following the documentation trying to add a new field, say "price" to a node.
All the documentation I found is related to add a field to a custom node, but in my case I want to add those fields to normal predefined nodes.

First question that comes to my mind is, I can create the custom field with YML configuration files or code right?

I created the field with YML and it is recognised by drupal; the problem is that they don't appear on the nodes (I have to manually activate it).

I created on my module /config/install/:

core.entity_form_display.node.article.default
core.entity_view_display.node.article.default

I add my field, but of course when I try to activate the module it does not like it since they are already defined by Drupal.

Is there a way to "extend" those core files? is that possible with YML or code?

I followed https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type. I created the YML files on /config/install, and indeed the field is created, the problem is I don't know how to "extend" view and form display entities as they are not related to a custom node type, otherwise they should be linked to pre-built node types and I cannot redefine those files (core.entity_form_display.node.article.default core.entity_view_display.node.article.default) since they already exist on the core.

Following this comment I've created the following files:

/config/install/field.field.node.article.field_price.yml

langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_price
    - node.type.article
id: node.article.field_price
field_name: field_price
entity_type: node
bundle: article
label: Price
description: 'Premium Price'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  min: 1
  max: 9999
  prefix: ''
  suffix: ''
field_type: integer

/config/install/field.storage.node.field_price.yml

langcode: en
status: true
dependencies:
  module:
    - node
id: node.field_price
field_name: field_price
entity_type: node
type: integer
settings:
  unsigned: false
  size: normal
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

Also I created FieldFormatter and FieldWidget. (I am not sure if properly.)

What I found out is the module is creating the field Price.
If I go to /admin/structure/types/manage/article/display, I see my price there, but it is under Disabled.

I feel I'm so close, but at the same time so lost.

What am I missing in order to make that field go active?

For a beginner I'ld recommend to use Drupal's convenient user interface in the back-end. Create an admin user, log in, start adding fields, change display, reorder – all done by clicking through the interface.

For example you can add custom fields to the existing Article content type at https://example.com/admin/structure/types/manage/article/fields. There's is a button Add fields. Click it and explore. There is no difference in adding fields to a built-in content type.

As others said before YML are for configuration export and import, when deploying a site. As you would do as an advanced developer: You'ld have that page locally on your computer, add some fields by clicking through the back-end, export their config, push that to a Git repo, and then on your live page, pull from your repository, import the config files and get the same fields there without the need to click anything again.

Adding fields from a custom module can be achieved by providing certain YML in your modules /config/install folder. There as well is no difference between built-in content types or custom content types. It is described pretty good on DO at https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type. Except that you would have to change the naming and especially change the value of the bundle: car_brand (content type) you want your fields to get added to.

Apart from that, you may need to install and uninstall this module pretty often during development. Get used to drush commands, for example drush dre module_name to do that in Terminal/Console (you need to have installed the Devel module to use drush dre). For your own good, I hope you already work with a UNIX based OS (Linux or OSX). Maybe you always have a fresh database backup available you can re-import with drush sql-cli < database.sql when you want to start over during development.

Just for reference I paste the deleted answer code here OP originally had put in his question. To finally make the fields available in the content type OP came up with this. I strongly guess he had put this into the module's *.install file calling hook_install() or hook_update_N(). Possibly deprecated functions, but I think you'll get the idea.

$entity_type         = 'node';
$bundle              = 'article';
$field['field_name'] = 'field_price'; // your field id

entity_get_form_display($entity_type, $bundle, 'default')
  ->setComponent($field['field_name'], array())
  ->save();

entity_get_display($entity_type, $bundle, 'default')
  ->setComponent($field['field_name'], array())
  ->save();


Drupal 8 page template for view page I know it should be very simple, I know it was working in Drupal 7 but I can't make it work in 8.

I tried this but it is not working. "page--path.html.twig" is not used, Drupal is using the "page.html.twig" template. The page I'm trying to theme is "example.com/path" . This page is just a view page. I'm not interested in theming the view, just the page markup around it.

Since its an alias,

For Drupal 8

In your THEME_NAME.theme file:

function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Checks for node pages.
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $current_path = \Drupal::service('path.current')->getPath();
    $alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $alias = ltrim('/', $alias);
    $clean_alias = str_replace('/', '__', $alias);
    $suggestions[] = 'page__'.$clean_alias;
  }
}

You would like to check out clive answer from here for drupal 7

Template file naming with alias


Add header and footer for every pages printed I've used print module version 7.x-2.0. I've used pdf-version and print-friendly-version.

Now i want to do two different things. That is,

Is it possible to add separate CSS for pdf, html or email templates like: print-pdf.css, print-html.css, print-email.css, print.css.?
I have added header and footer. It only works for first page and last page, But I want to display them for every printed pages. How can I do that?

you can do it to inset html tag in header ot footer file in tpl.php

enter your header

print $content of your page

enter your footer


how to show teaser view of my content types in search result page in drupal 7 I have customize my teaser view of my content types. Now i want to show that teaser view in search result page also. How can i do this? If anyone can give me a example with code will great help.

You can use template_preprocess_search_result for that

function MYTHEME_preprocess_search_result(&$vars) {
  $node = $vars['result']['node'];
  if ($node->nid) { // here you load the teaser if the result is a node
    $vars['teaser'] = node_view($node, 'teaser');
  }
}

You can make a template file to customize the result: https://api.drupal.org/api/drupal/modules!search!search-result.tpl.php/7.x


Admin custom module not displaying in theoverlay How to show the data fetched from the database in the overlay of the admin custom module.
The data are retrieved but not showing in the overlay. Kindly help me out

There is Overlay Paths

  This is a simple module that enables site builders to use the built-in
  Overlay for non-admin pages.

Refer

Working with the overlay

https://drupal.stackexchange.com/a/8265/4471


Start form as modal, from the controller I see a lot of examples of modal forms. But in all these example the modal is started from a current form. There is always a link-button involved. I would like to start a form as a modal from the controller by using:

$form = \Drupal::formBuilder()->getForm($formId);
return $form;

Can someone give me an example of which extra code is needed to show the form ($formId) as a modal??

I did an example of this a while ago. Basically I defined a route, and that controller returned an AjaxResponse:

mymodule.growl:
  path: '/mymodule/growl'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::growl'
  requirements:
    _permission: 'access content'

Basic controller:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\igrowl\Ajax\GrowlCommand;

class MyModuleController extends ControllerBase {
  public function growl() {
    $options = GrowlCommand::defaultOptions();
    $options['message'] = 'This is a message.';
    $options['title'] = 'Hello';
    $options['icon'] = 'feather-check';
    $options['type'] = 'success';

    $response = new AjaxResponse();
    $response->addCommand(new GrowlCommand($options));
    return $response;
  }
}

Any link hitting that route fired that Command. So, anytime someone clicks a link going to your defined route, it should create a modal.

You basically want to return a form (use the form builder service provided by ControllerBase instead of the static container) and at a basic level, use OpenModalDialogCommand (or supply your own modal js with custom Command). AjaxResponse will take care of the rest.


Using group and rules modules to automatically create group for new user I am using the Group (not OG ...) and rules modules for this task. I created group type, Applications Support. Then I created a rule, After saving a new user.
Under the rule, I used the following configuration, but it did not create a group.

My previous question was related to the OG module, this one is for the Group module. So I think it is a different question.

You didn't mention any errors, but for starters your group name should be:

test group {{ user.uid }}


Programmatically update node via array I'm trying to import some nodes into a new D8 installation. Therefore I wrote a module. Importing nodes is already working perfectly.
As you can see in my code snippet, I'm using the $field_array variable to create the nodes.
Now my questione: is it possible to use this variable also for the node update functionality?

Regards

M.

 public function ausgabe($import_node,$action,$new_old_uid,$new_old_nid) {
    global $content_type;

    $lang = $this->get_current_language();

    $field_array = [
        'uid' => $new_old_uid["new_uid"],
        'type' => $content_type,
        'langcode' => $lang,
        'status' => $import_node->status,
        'created' => $import_node->created ,
        'changed' => $import_node->changed ,
        'title' => $import_node->title,
        'body' => [
            'summary' => "",
            'value' => (isset($import_node->body) && !empty($import_node->body)) ? $import_node->body : "",
            'format' => 'full_html',
        ],
        'field_teaser' => [
            'value' => (isset($import_node->teaser) && !empty($import_node->teaser)) ? $import_node->teaser : "",
            'format' => 'full_html',
        ],
        'field_onid' => array('value'=>$import_node->nid),
        'field_image' =>  $this->get_set_images($import_node->field_ausgabe_bild),
        'field_files' => $this->get_set_files($import_node->files),
    ];

    if($action == "create") {
        $node = Node::create($field_array);
    } else {
        $node = Node::load($new_old_nid["new_nid"]);

    }
    $node->save();

    \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), '/'.$import_node->path, $lang);
    echo $action.": Node " . $import_node->title . ' ('.$node->id().') <br>';

    $this->pre("",true);

}

There seems to be no method to update a complete node.

But you can do this on a field basis:

foreach ($field_array as $field => $values) {
  $node->set($field, $values);
}


How to add a view dependency to a Drupal 8 functional test I'm working on a contrib module port to Drupal 8 and am currently adding additional test coverage (#2586125). The module provides both a field formatter and a views style plugin. I have good working test coverage for the field formatter and am now focusing on several views test cases (simpletest based on Drupal\simpletest\WebTestBase).

I have built a simple view, that uses my module's views style plugin along with a few other simple dependencies (some field storage conf, etc.), and exported this as a couple yml conf files. What's not clear to me however is the best practice way to load this bundled view during each functional test case.

A couple ideas come to mind:

Method 1: Bundle View as Config in Test Module Dependency

I Drupal 7 the standard method appeared to be to export a view and then bundle it inside a test-only module (with hook_views_default_views()) which is installed as part of the test case setup. In D8 the exported view yml can just be placed inside a test module's config/install directory and then the module made a dependency inside the $modules property of the test class.

Method 2: Add View Explicitly during Setup with ViewTestData::createTestViews()

Some of the D8 views module's own tests use Drupal\views\Tests\ViewTestData::createTestViews(), along with a $testViews property array to directly enable a specific view inside the test setup. Something like:

  public static $modules = array('node', 'field', 'image', 'my_module', 'views');

  // Views used by this test.
  public static $testViews = array('my_test_view'); // Exported yml inside config/test_views of my_test_views_module

  /**
   * Define setup tasks.
   */
  public function setUp() {
    parent::setUp();
    ViewTestData::createTestViews(get_class($this), array('my_test_views_module'));
    // Additional setup...
  }

Other Factors

The way configuration is loaded and cached, and related dependencies are resolved during tests is slightly mysterious. I've noticed that test cases which also programmatically add configuration that a view depends on (using something like $this->drupalCreateContentType() for a content type config or entity_create() for field storage config) can be tricky. In these cases Method 1 could be problematic as the view may get loaded from conf before it's dependencies are programmatically prepared. This is leading me to think that Method 2 is potentially preferred, but all the factors are not yet clear.

Sometimes the code in core is not as pretty and consistent as we would like, which can make it a but tricky to find out what is best practice.

For views, it seems that this is pretty consistent. You should create a test module and have the view config yml files be placed inside a test_views folder of the module.

There are examples of this in node and rest modules.


Unsupported serialization format on REST/Delete request I'm getting the following error on my custom resource when sending the following DELETE request even though POST and GET are working fine

"A fatal error occurred: Serialization for the format  is not supported"

The request looks as follows:

If I'd change the method from DELETE to GET it would return status 200 with the intended - and for testing purposes identical - behaviour. The configuration in the Rest UI module looks as the following and the permissions for the requests (GET, POST and DELETE) are allowed for Guests:

Here is the code of my custom class:

/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "test_resource",
 *   label = @Translation("Demo Resource"),
 *   uri_paths = {
 *      "canonical" = "/test_rest_api/test/{email}",
         "https://www.drupal.org/link-relations/create" = "/test_rest_api/test",
 *   }
 * )
 */
class TestResource extends ResourceBase {
  //Here are construct and create functions

  /**
   * Responds to entity GET requests.
   *
   * Does something
   *
   * @return \Drupal\rest\ResourceResponse
   */
   public function get($email) {
    $message = ["message" => $email];
    return new ResourceResponse($message);
   }

  /**
   * Responds to entity POST requests.
   *
   * Does something
   *
   * @param $data
   * @return \Drupal\rest\ResourceResponse
   */
  public function post(array $data = []) {
    $message = ["message" => $data["email"]];
    return new ResourceResponse($message);
  }

  /**
   * Responds to entity DELETE requests.
   *
   * Does something
   *
   * @return \Drupal\rest\ResourceResponse
   */
  public function delete($email) {
    $message = ["message" => $email];
    return new ResourceResponse($message);
  }
}

Has somebody an idea what I'm overlooking? I disabled/enabled the resource multiple and cleared the cache multiple times

In delete method you can not return ResourceResponse. Try return ModifiedResourceResponse.

return new ModifiedResourceResponse(NULL, 204);

Notice: First argument of ModifiedResourceResponse need are NULL, if your specific data for this parameter  throw same error.


Question about drupal_add_js I used drupal_add_js() to add a jquery plugin, but there is an error TypeError: $ is undefined at console of firebug. So how should I add the js?

I think you'd find this article in the Drupal documentation relevant and helpful.

The solution is to wrap your custom Javascript code within a closure as shown below:

(function($) {
  // Your Javascript code goes here
})(jQuery);

Javascript files from all Drupal core modules follow this convention. So, you can look them up for reference.

I'm not really sure but either before/after some version of jQuery, the $ was a global alias for the jQuery object itself and could be used directly without the closure but was later removed as it conflicted with other libraries.


Use swatches and not the color picker widget The Color core modules allows for a user to perform css color overrides via the theme settings page. This is handy for exposing the means for users to update color specifications without touching a line of CSS code. I've successfully integrated the Color module with an Omega 3.x subtheme. However, we have a range of branded color swatches that I'd like to make available to our users, rather than the too-broad color picker that the color module uses.

So; I'd like to swap (it can be additive, i.e., use one or the other) the Drupal color picker with a pane of swatches that I can configure.

How to do so?

Interesting question - You should try the color field module -

  Color Field is simple field that use a hexadecimal notation (HEX) for
  the combination of Red, Green, and Blue color values (RGB).

This uses the jquery simple color widget

and you can add your colors directly in as hexadecimal codes when you setup the field:


How can I list the current user's posts? How can I list all posts of the current user? I know I should use Views, but how do I do it?

You can use 'filter by current user' in the Views module.


Add class on row by modifying view.tpl.php file I am trying to add some classes on the specific row in one of my view table. I have tried to use MYTHEME_preprocess_views_view_table, but failed. Nothing changed on my page.(Here is my previous question link:How to add css class to specific rows base on fields in order commerce view page, if you have any idea about this, I am interested in hearing from you). So I decided to create a new view.tpl.php file to display them. However, nothing showed on my page again.

Here is a screenshot includes: 1.my view theme detector 2.my code 3.result on Chrome

I can find my file being used by my view, however, I don't see any changes on my page. Does anyone know what mistake I have made? Or any idea about how to add class on specific row.

Update:

I have already cleared the cache several times.

Finally:
Normally, Chris Happy's answer should work. But there might be some problem with my website, so we figured it out my problem by using JQuery. Thank you for @Chris Happy's help.

I tested it out, and it didn't work for me....until I cleared the cache!

Just go to yoursite.com/admin/config/development/performance/ and click "clear all caches".

Update: since clearing the cache didn't work, check if you are editing the right file: delete all the code in the tpl.php file.

If the view disappears, you are editing the right file.
If it still shows, close your editor window and select the file again.


Drush sql-sync failing with Ubuntu 14.04 I'm having no luck with sql-sync, there's two seemingly unrelated errors it's throwing at me which I'll detail below.

I've been successfully sql-sync'ing the same site to another server, so I'm pretty sure it's the remote server, not the local server, that is causing the problems. The remote server MySQL version is: 5.6.19-0ubuntu0.14.04.1 (Ubuntu)

1) Adding the --create-db switch gives me:

ERROR 1044 (42000) at line 1: Access denied for user 'user'@'localhost' to database 'database'

2) Regardless of whether or not I use the --create-db switch, I always get this:

ERROR: ASCII '\0' appeared in the statement, but this is not allowed unless option --binary-mode is enabled and mysql is run in non-interactive mode. Set --binary-mode to 1 if ASCII '\0' is expected. Query: '��T'.

Any ideas?

So it turns out I'd installed Drush 6 on the remote server, while my local version was Drush 7. Upgrading solved the problem.


Difference between .inc and .module? I am trying to figure out what the main difference is between mymodule.module and mymodule.admin.inc.

Can anybody explain it?

Without going into the ins and outs, Drupal understands the .module file as being a module within the system. The .inc notation has always been used in PHP for 'include' files. When developing modules you might want to split functionality into different .inc files.

Modules being used in specific cases use conventions similar to .admin.inc. That file typically includes all the code necessary to run the administrative interface, and a file node.pages.inc for example contains the code executed for other menu callbacks.


How do I get the user ID from the $user_profile variable? How can I get the user ID and load the user with user_load() using the $user_profile variable in the user-profile.tpl.php template file?

You cannot get the uid from $user_profile as it does not contain any information we can use to get the current user.

To get the current user's object, use the following:

global $user;
echo $user->uid;


Display fields from a paragraph as a single field I have a paragraph which is essentially a date range, however, the individual dates can have prefixes, suffixes, can be in differing formats, I have a dropdown to select the format and dates need to be displayed differently depending on whether they span within a decade, over decades or over century boundaries. The date values have been split out into a daterange field so we can search / filter by date, however, within the parent paragraph, I'm wanting to return just the processed date instead of the list of fields.

I can do the IF this RETURN xyz to get the date fields into the required formatted string, however, I'm struggling to find how I can build this into a plugin and attach to my desired paragraph(s) / nodes.

It's fairly simple to do this within the theme templates, however, I'm needing to do this at a field / node level, not a twig template as the data will be pulled both as a traditional web page, but will also need to be pulled out via XML export, probably within various views and so on, so don't want to be doing the presentation transformation in multiple places. I need it to be independent of the site theme files.

This is in Drupal 8.8

Hope this makes sense.

If you wish to have absolute control on the display of your date range, I'd recommend you to create a module with a new FieldFormatter to expand one of the DateRange fieldformatters (the original files are in code/modules/datetime_range/src/Plugin/Field/FieldFormatter).

By overriding the viewElements() function, you'll be able to set the desired display(s) for your date range from one place and independent from the site theme files.

Once your new fieldformatter file is created, go to your paragraph "manage display" page and modify the display of your date range field to your new fieldformatter.

Hope this helps.


How to create a content type based on users with entities? I want to create a content type that I can add to a map view based on nodes. I am using the GMap and Location modules. There doesn't seem to be an obvious way to add users to view based on nodes. So, I want to make a content type, which is a subset of the users and the fields in my user profiles. I know that I can separately have a map view based on my users, but I need to show them all together users, and 3 spatial content types.

My initial thought was just to copy the raw user data from the database and create a content type and populate it from feeds, but this would lead to a lot of duplicate data in the database.

I've created a content type with an entity reference to users. This lets me manually add content with the user name but I don't know how to share fields between the content types and I don't know how to autopopulate the content from the existing user fields.

How do I proceed?

So the thing is that u want to populate user fields with content from node, what you can do is enable module, hook_post_action, and after that use its hook "hook_node_update", and you will get user id (uid) from the user reference fields, u can load a user from that uid, using user_load, after that set required value of field, and use user_save function to save that user, If u are using profile2 for the user, then u can use profile2_load_by_user, profile2_save.


Is there a drupal.org API for retrieving the list of available modules? Is there a drupal.org API for retrieving the list of available modules, a description of them and available versions?

Very recently there's an API published: https://www.drupal.org/api


Services 3.5 q=system/connect.json 404 (Not Found) I have code that use JQuery to call services module and login.
After Login, I call token through ?q=services/session/token and gets the token of the user.
I think that i have got the right token...
After that the code calle to ?q=my_services_endpoint/system/connect.json and pass through the header the token.

the problem is that i get those lines in the console and no success of course...

  7dR8Eo0pmiTeMCHLUeneAAQFCONn80NgXnJuNqhrtYw login.js:38

  OPTIONS http://{localhost}:8888/drupal2/?q=system/connect.json 404 (Not Found)
  jquery-1.6.4.min.js:4 POST

  POST http://{localhost}:8888/drupal2/?q=system/connect.json 404 (Not Found)

this is the code:

   $.ajax({
        url: "http://{localhost}:8888/drupal2/?q=test_test/user/login.json",
        type: 'post',
        data: 'username=' + encodeURIComponent(name) + '&password=' + encodeURIComponent(pass),
        dataType: 'json',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert('page_login_submit - failed to login');
            console.log(JSON.stringify(XMLHttpRequest));
            console.log(JSON.stringify(textStatus));
            console.log(JSON.stringify(errorThrown));
        },
        success: function(data) {
            $.cookie("sessid", data.sessid);
            $.cookie("session_name", data.sessid);
            // Obtain session token.
            $.ajax({
                url: "http://{localhost}:8888/drupal2/?q=services/session/token",
                type: "get",
                dataType: "text",
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("Didn't got the token");
                },
                success: function(token) {
                    console.log($.cookie("sessid"));
                    console.log(token);
                    // Call system connect with session token.
                    $.ajax({
                        url: 'http://{localhost}:8888/drupal2/?q=test_test/system/connect.json',
                        type: "post",
                        dataType: "json",
                        beforeSend: function(request) {
                            request.setRequestHeader("X-CSRF-Token", token);
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            alert(errorThrown);
                        },
                        success: function(data) {
                            alert('Hello user #' + data.user.uid);
                        }
                    });
                }
            });

what version of drupal did you use?Can you try to remove the q?= and try it again?Also i notice on OPTIONS http://{localhost}:8888/drupal2/?q=system/connect.json 404,it doesn't contain your endpoint.


Getting more organized data? I get the impression the module works best for blog-type websites. My website's nodes have many many different (short) text fields with about 30-50 characters worth of text each. It would be incredibly helpful if I could get the search results data formatted differently. It looks like snippet is just a markup string ready to be printed. Whereas I would benefit a lot more from structured data. Let's say I search for the word "communication" then I would want data that looks more like:

 array(
  'matched_node_id' => 'xyz',
  'node_title' => 'abc',
  'matched_fields' => array(
               'matched_field_1' => 'full text for this field',
               'matched_field_38' => 'full text for this field'),
   );

This way I would be able to structure my page a lot more cleanly for my users. The data sort of resembles tabular data, and showing snippets without organization would be very unhelpful. Any ideas on how this could be implemented? Monkeying with theme_preprocess_HOOK? Perhaps a new module?

It turns out that all of this information was already available, and I just had to work within mytheme_preprocess_item_list__search_results. I had the Node objects for all the nodes that matched, and so I was able to reconstruct the render array exactly the way I wanted.