How to add button to a form that calls custom JavaScript when clicked? I want to create a button on a form that when clicked:

Calls some custom JavaScript
Does not submit the form

Is this possible with Drupal 8 Forms?

In this example, I've added a custom button action to a Drupal 8 Form. When the button is clicked, it prevents the form from being submitted and allows custom JavaScript to do some work.

Here are the 3 pieces:

The form button element, with an #attached library
Your custom module's library declaration
The library's .js file

And here is the example code:

in ExampleForm.php

$form['actions']['clear'] = [
  '#type' => 'button',
  '#value' => $this->t('Clear'),
  '#attributes' => [
    'onclick' => 'return false;'
  ],
  '#attached' => array(
    'library' => array(
      'example/foo',
    ),
  ),
];

example.libraries.yml

foo:
  js:
    js/foo.js: {}

js/foo.js

Drupal.behaviors.example_hello = {
  attach: function (context, settings) {

    // Attach a click listener to the clear button.
    var clearBtn = document.getElementById('edit-clear');
    clearBtn.addEventListener('click', function() {

        // Do something!
        console.log('Clear button clicked!');

    }, false);

  }
};

Don't forget to clear all your caches to ensure your new foo.js library is picked up by Drupal 8.


How do I create a Twig override for server 500 error? How do I override the template used for a 500 error?
Is there any way to achieve this from a module?

This cannot be done in Drupal as a 500 error is a server error. Drupal will never be reached.

However, if you can configure the server, you can accomplish this yourself. This may also work from the .htaccess level in Drupal. I suggest trying it at the server level first if you can.

If you are running Apache, you can use custom ErrorDocument directives.

If you are running Nginx, see How To Configure Nginx to Use Custom Error Pages on Ubuntu 14.04.


What specific modules are included in Drupal Commerce Kickstart? Drupal Commerce Kickstart is a project built on Drupal Commerce that bundles Drupal 7, Commerce and a host of additional modules with some preset settings to speed up Commerce-based development.

I'm trying to find out what specific modules are actually included in this bundle, but all I can find is uninformative advert pages like this.

There's nothing about what exactly is included in the Kickstart documention. The closest I can find elsewhere online is this list of modules not included.

Is there any simple list of the modules that are bundled in the Commerce Kickstart package?

Here's the actual makefile that builds the latest version of Commerce Kickstart.

http://cgit.drupalcode.org/commerce_kickstart/tree/drupal-org.make

Within it, you can find every module that is built in. It includes the machine name of the project and the version number used.

For example, the entry "projects[ctools][version] = 1.9" shows you the machine name ctools, which is the Chaos Tools module, and the version is 1.9. You can look up the modules on drupal.org by substituting the machine name into the following URL: http://drupal.org/project/MACHINENAME.


Conditionally display field based on comparison to other field I have a content type Event that has a startdate (field_eventdate) and an optional enddate (field_eventend).
Although it's optional, the enddate is often filled in by the users with the same date as the startdate.
So I want to hide the enddate if it's equal to the startdate or display it on the same line as the startdate when it's different.

e.g.

2020-02-02 10:00
Here comes more text for a single day event

and

2020-02-02 10:00 - 2020-02-03 16:00
Here is more text for a multiday event

So far I managed to delete the enddate from the render array when it's equal:

function mytheme_preprocess_node__event(&$variables) {
  $startdate = $variables['content']['field_eventdate'][0]['#markup'];
  $enddate = $variables['content']['field_eventend'][0]['#markup'];

  if ($startdate === $enddate) {
    unset($variables['content']['field_eventend']);
  }
  else {
    // add an &em-dash; so the dates are nicely spaced
    $variables['content']['field_eventend'][0]['#markup'] = " — " . $enddate;
    // add float-left to the start date so they end up on the same line
    // TODO: what goes here?
  }
}

But I cannot find out how to notice in a twig template that I have a startdate and an enddate and therefore add 'float' css classes to put them in line.

I have tried to add a special attribute to the 'field_eventdate' field, and add a 'float-left' class in the twig template for the field, but the custom attribute gets lost somewhere.

How can I solve this problem?

I finally solved the problem by adding a template for the content type. This allowed me to simplify the preprocess function:

function mytheme_preprocess_node__event(&$variables) {
  $startdate = $variables['content']['field_eventdate'][0]['#markup'];
  $enddate = $variables['content']['field_eventend'][0]['#markup'];

  if ($startdate === $enddate) {
    unset($variables['content']['field_eventend']);
  }
}

I then copied the node.html.twig template to node--event.html.twig. I only changed the main {{ content }} part into:

    {{ content.field_tags }}
    {{ content.field_eventlocation }}
    <div class="event_dates clearfix">
      {{ content.field_eventdate }}
      {% if content.field_eventend %}
        &nbsp;&ndash; {{ content.field_eventend }}
      {% endif %}
    </div>
    {{ content|without('field_tags', 'field_eventlocation', 'field_eventdate', 'field_eventend') }}

This replaced my attempt to create and modify field--field-eventdate.html.twig template.

Maybe this is not the best option, but at least it works.


How can I remove old articles? I have a Drupal 7 database that stores articles since 2013. The database is too big and I want to drop all the old articles to keep only the ones created on 2019, just for development purpose. I read Delete a node after X weeks it was created, which describes what to do on Drupal 8. Is there a similar method for Drupal 7?

The code I would use is similar to the following one.

$entity_query = new EntityFieldQuery();
$entity_query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->entityCondition('created', strtotime('1 January 2019'), '<')
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $entity_query->execute();
if (isset($result['node'])) {
  node_delete_multiple(array_keys($result['node']));
}

The differences between the code I am using and the code shown in the answers for Delete a node after X weeks it was created are the following:

The object used to query the entity is instantiated differently and its class is different
The code doesn't select just the published nodes (I take you are interested in deleting all the nodes created before 2019)
The code is using addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT') to get all the nodes, even the ones to which the currently logged-in user doesn't have access (Remember that cron tasks are executed as anonymous user, which possibly doesn't have access to many of the nodes)
In Drupal 7, the functions to delete nodes are node_delete() and node_delete_multiple() which require, respectively, a node ID and an array of node IDs

If I were to do the task in a hook_cron() implementation, I would use the following code.

  function mymodule_cron() {
    $entity_query = new EntityFieldQuery();
    $entity_query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->entityCondition('created', strtotime('1 January 2019'), '<')
      ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
      ->range(0, 25);
    $result = $entity_query->execute();
    if (isset($result['node'])) {
      node_delete_multiple(array_keys($result['node']));
    }
  }

Older Drupal 7 versions would need to replace addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT') with addMetaData('account', user_load(1)). For those versions the code would be then similar to the following one.

  function mymodule_cron() {
    $entity_query = new EntityFieldQuery();
    $entity_query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->entityCondition('created', strtotime('1 January 2019'), '<')
      ->addMetaData('account', user_load(1))
      ->range(0, 25);
    $result = $entity_query->execute();
    if (isset($result['node'])) {
      node_delete_multiple(array_keys($result['node']));
    }
  }

Using hook_cron() avoids issues in the case there are many nodes to delete. Trying to load, for example, 3000 nodes (even if the EntityFieldQuery class returns partially loaded nodes) could cause memory or timeout errors.


Making a form by having a view I am trying to convert a view to a form as follows:

I need to have a table of articles (which can be produces easily by views) and inserting a checkbox next to each row (article), and a button next to this table as Submit button.
The created form out of the articles` view should be able to initialize the value of the checkboxes before showing them (which can be done somehow by form_alter).

So, the problem is that I really don't know how to create this form.

I used VBO, but VBO does the operation for the selected rows! I need a method which can help me to set the values of checkboxes by code, before views render, and when the submit button is clicked, whole rows should be checked!

can you please suggest a tested & working solution?

thanks

view_form_submit is not working in D7, you have to use the hook_form_alter and then you have to change the #submit:

$form['actions']['submit']['#submit'][] = 'custom_form_submit';


How to send data like NAME[]=value via POST request and simultaneously redirect user to 3rd party server? I'm writing a custom module which needs to send data string like this: "CODES[]=xxx&NAMES[]=xxx" via POST to 3rdparty payment gateway AND redirect user there.

I've written a form to gather data from customer, but I can't use [] in form fields names, Drupal reports an error (an array instead of string) and quits.

I can post all data manually via drupal_http_request, but it doesn't redirects browser to needed URL. If I use drupal_goto after drupal_http_request, the data is lost and payment service doesn't recognize the user. If I include $request(my drupal_http_request)->result in a page, I get redirected to 404 page of my site with a non-existent URL (/order/checkout.php which has to be appended to payment server root and instead glues to my server root URL).

If I use $form['#redirect'] or $form['#action'] it posts fields names without "[]".

Question is, how can I append these square brackets after request is formed, but before it is sent?

Or how can I send data along with redirecting?

Will be very grateful for help, this problem is driving me nuts for a week now.

UPD My code:

    //a form
function mymodule_ask(&$form_state) {

 $form = array();

$form['#action'] = 'https://3rdpartysite.url/script.php';
$form['#method'] = 'post';

 $form['ORDER_PRICE[]'] = array(
   '#type' => 'textfield',
   '#title' => t('Amount'),
   '#size' => 10,
   '#required' => TRUE
 );

 $form['ORDER_PNAME[]'] = array (
   '#type' => 'radios',
   '#title' => t('Name'),
   '#options' => array('Avia' => 'Avia tickets', 'Other' => 'Other'),
   '#required' => TRUE
 );

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

return $form;
}

function mymodule_ask_submit {
    //in form submit function retrieving data from form values
    $requestar['ORDER_PNAME[]'] = $form_state['values']['ORDER_PNAME'];
    $requestar['ORDER_PRICE[]'] = $form_state['values']['ORDER_PRICE'] * 1.02;
    //forming an array to post
    $onestr = '';
    foreach ($requestar as $key => $value) {
    $onestr .= $key."=".$value."&";
    }
    $resstr = chop($onestr, '&');
    // and then I tried different ways

    //either creating and auto-submitting a form with needed values
    create_form($requestar); //separate function creating this form
    drupal_execute('payu_addform', $form_state);
    // but it doesn't pass drupal evaluation because of "ORDER_PRICE[]" element name

     //or via http_request
    $result = drupal_http_request('https://PAYMENT_SERVER_URL/script.php',  array('Content-Type' => 'application/x-www-form-urlencoded'), 'POST', $resstr);
    drupal_set_message($result->request);

    // but it takes me to MY_SERVER_URL/order/checkout.php?CART_ID=442bc42170616cd36dfd2246434d4210, while I need it to make to PAYMENT_SERVER_URL/order/checkout.php?bla-bla-bla
    //may be I can use $result->request in some other way? Just printing within this submit function gives nothing... But how can I pass it to make drupal take me out?

}

Try setting the name directly:

$form['order_price'] = array(
  '#type' => 'textfield',
  '#title' => t('Amount'),
  '#size' => 10,
  '#required' => TRUE,
  '#name' => 'ORDER_PRICE[]',
);


How to fix the PDOException shown after upgrading to Drupal 7 I upgraded Drupal 6 to Drupal 7.

The following updates returned messages:

  node module

  Update #7006

  taxonomy module

  Update #7005

  search module

  Update #7000

I updated the schema_version column of the system table for module above to higher number.

After all the pending update has finished running.

My front page website show error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'base.format' in 'field list': SELECT base.tid AS tid, base.vid AS
  vid, base.name AS name, base.description AS description, base.format
  AS format, base.weight AS weight, v.machine_name AS
  vocabulary_machine_name FROM {taxonomy_term_data} base INNER JOIN
  {taxonomy_vocabulary} v ON base.vid = v.vid WHERE (base.tid IN
  (:db_condition_placeholder_0)) ; Array ( [:db_condition_placeholder_0]
  => 6 ) in DrupalDefaultEntityController->load() (line 198 of /home/domains/site.com/public_html/includes/entity.inc).

How do I fix it?

If you manually edited the schema_version column, you practically avoided Drupal would execute the necessary updates, and add the necessary fields in the database tables. That is why you get that error message.
How many updates you blocked depends on the number you set for schema_version; if you set it (for example) to 8000, then you avoided Drupal would execute all the updates.

To fix it, you can only restore the values schema_version had and run again update.php. This is not 100% error free: In some cases, executing the same update twice could cause an error that would stop the update process. It would be much better if you would restore the database from a backup you have from before manually editing the system table; in that way, you would be sure that executing update.php would not cause any runtime exception that would interrupt the update process.
The only alternative I see is executing the updates that were not executed, but you should have to track which updates were not executed or were executed but stopped because some error. It is also difficult because some updates need to be executed in a specific order; see system_update_dependencies() that defines the order for some of the updates for the System module, or node_update_dependencies() that does the same for the Node module. In short, you should write code similar to the one used by Drupal to update modules, adapting it to your case.


Node Teaser template in custom module I have used given below code for node--[content_type].tpl.php (default) template file

function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'node__NODETYPE' => array(
      'render element' => 'content',
      'base hook' => 'node',
      'template' => 'node--NODETYPE',
      'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
    ),
  );
}

but I don't know how to call my node--[content_type]--[view_mode].tpl.php

Please suggest.

You can use node--[content_type].tpl.php for changing the output for view mode.

if ($teaser) {
  // node is being displayed as a teaser

} else {
  //all other cases
}


Set value to specific custom theme setting I noticed that I can get a specific theme setting like so

theme_get_setting('myvar','mytheme');

but I don't see a way of actually setting a setting. Something along the lines of

theme_set_value('myvar','mytheme','value');
I looked at the functions available to me here https://api.drupal.org/api/drupal/core%21includes%21theme.inc/8.2.x
but I didn't see anything specific to my needs.

I do see there's already a question asking the same thing here
How to set theme setting
but that is for Drupal 7 and I'm using 8.

Is there a quick way to set the value of a specific theme setting?

Drupal 8 use configuration to store configuration settings. You can follow document. And snippet code to set new value for custom theme(replace theme_name with your theme name).

$config = \Drupal::service('config.factory')->getEditable('theme_name.settings');
$config->set('variable', 'value')->save();


Image styles do not work I am struggling to find a solution for image styles not getting generated. The original pictures get uploaded to the server but no styles or thumbnails are generated.

I have checked folder permission and set it to 775 and even 777 (temporarily) for the /styles/ and its subfolders.

I even set $conf['image_allow_insecure_derivatives'] to TRUE.

Yet I still get access denied for the anonymous users (not verified when I upload images and no styles or thumbnails).

Any suggestions are greatly appreciated.

Drupal version 8.5.3 Local dev with Aquia Dev Desktop.

I've tried all combinations with .htaccess (root, in /files and in styles) with no success.

Also tried with:

$config['image.settings']['suppress_itok_output'] = TRUE;
$config['image.settings']['allow_insecure_derivatives'] = TRUE;

No results.

Even though I had a settings.local.php solution was to uncommment this line in settings.php:

$settings['file_public_path'] = 'sites/default/files';


Debugging node/route access I want to set a breakpoint in xdebug to debug an interesting issue the site is having regarding user access to certain nodes. My question is where do I do that in D8? Where, specifically, is the D8 replacement for user_access to be found?
Not using any form of node access, but am using Group and Content Moderation. The problem could lie with either of them, but I thought the best approach would be to break where Drupal decides whether a user has access to node/###/edit, then step from there.
The problem is that the user's role's permissions give all node and content moderation permissions for the applicable content type. Yet, when going to the admin/content page or admin/content/moderation, given two nodes of the same content type authored by a user of the given role, with the same node and moderation status, only one has an edit button. In viewing the nodes, only one has an edit link.
I have rebuilt permissions, to no effect.

The /node/{node}/edit path is defined by the entity.node.edit_form route. This route uses the _entity_access requirement to lookup access. When that route's requested the entity API will execute EntityAccessCheck::access() and NodeAccessControlHandler::access() to lookup the account permssions for the relevant node.


How to set a rule that sets a term reference field value and text area value in a commerce order entity This relates to a post I made here How do I copy a "purchase limit" field from a product to a product line item

Situation:
We are building a commerce website using Drupal 7 and Drupal Commerce for a government agency that distributes free publications

They have a limit on the number of free items that can be ordered at once, (unless the person ordering has a good reason.)

We have a field called copy limit on our product entities.

If the user enters a quantity on the” add to cart “for that exceeds the copy limit, we want the order to go into a holding area after the order is completed for further review.

Our plan is to use a taxonomy term to do this. We have a vocabulary called "Is this a bulk order?" It has two terms, yes and no.

We want to have it so if the quantity in one of the line items in a customer's order exceeds the copy limit, the term reference field for the "Is this a bulk order" vocabulary is set to yes.

Also (I'm not sure if this belongs here but....)

In a related question, we are trying to get the user fill out a field if the copy limit is exceeded explaining why they need to exceed the limit. We have a field on the order called "Bulk Order Explanation"

Right now, I have rule that after saving a new line item, and the quantity exceeds the copy limit, the user is brought to a add content page for a content type I called "Bulk Order Explanation"

What we want to happen is that after they save the "Bulk Order Explanation" node, the body of the content type is used to populate the bulk order explanation field.

I am not even sure if I am headed in the right direction on either of these things.
Thanks for any insight you can provide!

Here's a strategy that I think will work:

Create a field on the product like field_bulk_order_limit
Create a field on the order called "field_held_bulk_order" or something. This can be a boolean or some similar thing.
Create a rule that looks at the product's field_bulk_order limit whenever a line item is created or updated and its product has that field. It could output to the screen (system: site message) at the user if the number is above the bulk order limit.
Create a checkout rule (a rule triggered by "when completing the checkout process") that loops through the line items and checks their products' field_bulk_order_limit. If it finds line items with a quantity higher than the field_bulk_order_limit, set the order's field_held_bulk_order to TRUE. Optionally also show them another message.
Fiddle with your administrative order views to have a view that explicitly shows held orders,etc.
Nice to have: create a custom pane that lets them enter the reason that they need so many. This requires a tiny module. It could imitate the commerce_order.module's pane (see commerce_order.checkout_pane.inc and commerce_order_commerce_checkout_pane_info()


Drupal admin themeing and customizations I am looking into how I might customize the backend, but re-themed is not the ultimate agenda. Say for instance, 'admin/content', where I have filter options for various content types. Below that I have a table of content sections.

I want to completely replace the table and render the list in the left region of my template and use the content area for a WYSIWYG editor -- this is a common UI for basic CMS and I figured would be a good advanced learning experience.

I started poking through the code and quickly discovered I have no idea what content/form/blocks are in which regions in the admin section.

I found the module that implements the menu for 'admin/content' but that wasn't very helpful.

My question is: In the admin portion of a drupal setup how would I position custom block module content in the right region of a template when using block admin seems only to affect the front-end of the site?

Use https://drupal.org/project/admin_views
Go edit a view and add a new display: block.
Register a new path in system:

a) using hook_menu in your custom module OR

b) using https://drupal.org/project/empty_page
Place that new created block in a region (edit also the paths where block should be displayed)
I'm not sure what you mean by WYSIWYG editor in content area - do you want to edit node or what?

a) If you used hook_menu, point its page callback into a function which returns WYSIWYG editor OR

b) If you used a empty_page you must create another block with editoror inside, and place it into content region


What is the best way to import new changes from dev to live site using feature module I have a live site and I have done many new changes on the dev site already.

I would drop the database on live and import the dev DB into it but there are users on live site.

I came across Features module . What will be best way if I:

create a huge feature with all the options selected (content types, permission, etc etc ) and import it to live site.
or create many little modules using feature and import them to live.

I don't know what changes I have made to dev. There is lot of work which I can't remember.

Do not use a huge feature with all your changes because Drupal may have problems managing it. I recommend to split your configuration in several Features.

If your project is absolutely custom and you are not going to reuse your custom configuration you can create a Feature for every Drupal domain obejct. For example, create a Features for each Content Type, a Feature for the base Fields, a Feature with all your Views, another Feature with the roles, anohter Feature witj all permissions, and so on. If any of those Features becomes too big (for example, you have hundreds of Views) you can just split it into smaller Features.

If your configuration may be reusable in other projects use Features that more or less pacakge a single site feature.

There's no way to know what you have changed from your dev site compared to live site easily. I suggest to just create your Features and deploy them in a clone of your pro site and check everything works ok. If not, trace the missing configuration.


How do you change the location of `form_set_error` output? Is there a way in Drupal 7 to change the location of the output of form_set_error?

At the moment, it calls drupal_set_message which queues all the form's errors to the top of the screen.

What I would like instead is for each message to appear below the appropriate field.

If this is not possible, can I manually flag the form as "invalid" within the MODULE_form_name_validate() function without using form_set_error?

Extending the (correct) answer from Clive, I worked through the IFE code. I didn't really need an entire module dedicated to this, so I adopted a few snippets here and there to get the result I needed. I've marked his answer as correct because it is ultimately the right answer.

The code is below, all credit goes to Clive and the IFE team - I just wanted to present the simplified version for anyone looking for a similar answer.

// Standard gear - do some custom validation and set the errors
// as you go..
//
// Once all the validation has been done, call MODULE_errors_reset
// which will return an array of all errors against their ID.
// Expose this array however you like to your template, or loop
// over your form adding a #suffix to each element with an error
//
function MODULE_form_name_validate($form, &$form_state) {
    drupal_set_message("validating...");

    form_set_error("description", "There is an error here!!!!");
    form_set_error("tags", "Yep, and here too!!!");

    $reset_errors = MODULE_errors_reset( $form );

    drupal_set_message( "<pre>" . print_r( $reset_errors, true ) . "</pre>" );
}

// This part is adopted from IFE. It's changed in two ways, it returns
// an array (which also merges with its recursive self).
// And it also skips all the 'display' stuff present in the original
// Essentially it extracts out the error messages from the session and unsets
// them. I am assuming that Drupal 7 marks the success of a validation based not
// whether the SESSION variable contains anything, the SESSION seems to be only
// for the message at the top of the screen.
//
function MODULE_errors_reset( $element ) {
    if( ! isset( $_SESSION[ 'messages' ] ) ) {
        return;
    }

    $reset_errors = array();

    // Recurse through all children.
    foreach( element_children( $element ) as $key ) {
        if( isset( $element[ $key ] ) && $element[ $key ] ) {
            $reset_errors += MODULE_errors_reset( $element[ $key ] );
        }
    }

    // Check for errors and settings
    $errors = form_get_errors();
    $element_id = implode( '][', $element[ '#parents' ] );

    if ( !empty( $errors[ $element_id ] )) {
        $error_message = $errors[ $element_id ];

        // Get error id
        $error_id = array_search( $error_message, $_SESSION[ 'messages' ][ 'error' ] );

        if( $error_id !== FALSE ) {
            unset( $_SESSION[ 'messages' ][ 'error' ][ $error_id ] );
            $_SESSION[ 'messages' ][ 'error' ] = array_values( $_SESSION[ 'messages' ][ 'error' ]  );

            if( count( $_SESSION[ 'messages' ][ 'error' ] ) <= 0 ) {
                unset( $_SESSION[ 'messages' ][ 'error' ] );
            }

            $reset_errors[ $element[ '#id' ] ] = $error_message;
        }
    }

    return $reset_errors;
}

// If there are no form errors, we still hit here, even after the 'reset', this is
// a good thing.
function MODULE_form_name_submit( $form, &$form_submit ) {
    drupal_set_message("submited!");
}


Hide Content Type Default Pages from Search Results I have multiple content types where users enter data that I consume in views and create pages from.

I want to exclude some of these default content type rendered pages from the search results, but do not want to exclude the content and the views page where the results are.

For example, I have Basic Page Content Type and want to see any basic page content. I also have Custom Page Content Type and want to see these fields, but not the default rendered page, just my View created page that consumes the Custom Page Content Type fields.

Where do I set this up or how do I set up search to handle this type of need?

You can use Custom Search module.

  This module alters the default search box in many ways. If you need to
  have options available like in advanced search, but directly in the
  search box, this module is for you. D8.x notes

  The module adds options to select:

which content type(s) to search,
which specific module search to use (node, help, user or any module that implements search),
which input type to use (with Elements),
advanced criteria

  For all these choices, there are options to switch between a select
  box, checkboxes or radio buttons, and also customize the selector
  label and the default - Any - text. Advanced options

  There are also options to:

change the default search box label,
add a default text in the search box,
add advanced search criteria,
change the default submit button text,
use an image instead of the submit button,
change the order of all the elements,
include some elements in a popup block,
add a filter to the results page,
show/hide basic and/or advanced search in the results page,
show/hide meta data in the results page,
multiple search paths


What should I pass as --core parameter? I'm having trouble using Drush version 8 to pull down an instance of Drupal 7. I've tried variations of drush qd --core=7 d7_no, but all seem to fail.

  No release history was found for the requested project (7).
  Could not download requested project(s).

Also drush qd --core=7.x d7_no fails.

  No release history was found for the requested project (7.x).
  Could not download requested project(s).

What should I pass as --core?

From the qd help output:

$ ./drush.phar help qd
Download, install, serve and login to Drupal with minimal configuration and dependencies.

Examples:
 drush qd                                  Download and install stable release of Drupal into a
                                           timestamped directory, start server, and open the
                                           site logged in as admin.
 drush qd --profile=minimal --cache        Fire up dev release of Drupal site with minimal
 --core=drupal-8.0.x --yes                 install profile.
 drush qd testsite devel                   Fire up stable release (using the cache) of Drupal
 --server=:8081/admin --browser=firefox    site called "testsite", download and enable devel
 --cache --yes                             module, start a server on port 8081 and open /admin
                                           in firefox.
 drush qd commercesite                     Download and install the "Commerce Kickstart"
 --core=commerce_kickstart                 distribution/install profile, display watchdog
 --profile=commerce_kickstart --cache      messages on the server console.
 --yes --watchdog
 drush qd --makefile=mysite.make           Create and install a site from a makefile.

It should be inferred that drupal-<Sematic Version Piece> would be the project name you're downloading from the --core=drupal-8.0.x example provided.

So the following should work I believe:

drupal-7
drupal-7.x
drupal-7.N.x

Actually Drupal 7 doesnt follow semantic versioning. So D7 would require either drupal-7 or drupal-7.NN. The above drupal examples would apply to drupal 8 and beyond as of 06-01-2017 due to semvar usage in drupal.


(hook_menu_alter) override the same path twice I have created a custom module which implements the hook_menu_alter in order to override those two paths and to add my own access control logic:

$items['taxonomy/term/%taxonomy_term/edit']['access callback']

$items['taxonomy/term/%taxonomy_term/edit']['access arguments']

Looking for an out of the box solution I found this module vppr which overrides the exact same paths adding its own logic.

The point is that if I have both modules enabled - vppr module and my custom module -  the ['access callback'] from my custom module is never fired. If I disable the vppr module my module is working fine.

Is that possible, two different modules can't override the same path or I'm missing something, and why the ['access callback'] from the contrid module is executed over mine?

thanks!

There can only be one set of metadata for a single path. Hooks are invoked sequentially, so yes, if you have another module altering the same path, either yours or theirs will 'win'; never both.

You can control the order hooks are called in using the 'weight' column in the system table, or through the use of hook_module_implements_alter().


how to change address bar by its content-type/title of node I have a content type where user allowed to add the content, which create a node of that particular content, when i click to that content for detail page it re-direct to the node page created by authenticated user, but the address bar is something like

  www.myexample.com/node/23 23

or some no.
Now i want the address should be

  www.myexample.com/(content-type)/(node-title)

please help me.

Thanks

Install Pathauto
Visit the URL Alias Patterns page at /admin/config/search/path/patterns
Choose an appropriate token-based pattern for your content type in the relevant text field, before saving. (e.g. [node:content-type]/[node:title])
Visit the "Bulk Update" tab and generate all Content aliases.

From now on any time you (or anyone else) creates a node of that type, the URL alias will be automatically set.


URL specific form for anonymous user I'd like to investigate if the following scenario is plausible somehow in Drupal 7:

The creation of a public form (node form/webform or whatever) with many instances so that each instance can be accessed only by a specific URL and can be filled by an anonymous user. The anonymous user should be able to fill in some of the fields, save his progress and come back later to fill some more using the same URL.

This scenario would allow the admin to create new instances, pre-fill some fields and send the form url by email to the final anonymous user.

The reason for all this is basically to avoid user registration and hold each user's submission to his unique URL form.

Any instance of a Webform is a node so each anonymous user get his own submissionreference. So e.g the name of the form is harrypotter the user is getting harrypotter/1
Where 1 is the submission nr.

In rules you are able to get the submission id, get the content and redirect to the form again.

However you have to protect it again other users. Therefore you can use another Web form in front of it which ask for a pincode. You can redirect the user with the help of the pincode and rules to the correct submissionid


Creating a custom locked role Within Drupal 7 I am trying to modify the page myserver.com/admin/people/permissions/roles so that a custom role which I have added cannot be edited. In other words, I'd like it to be locked like the anonymous and administrator roles.

I have found one possible solution at http://drupal.org/node/397480 but I think it is a Drupal 6 fix.

I've tried modifying the render array for the content directly, but also can't figure that out quite right.

Here is the closest I've been able to get it. Any suggestions or solutions will be much appreciated.

function access_group_preprocess_page(&$variables) {
  //check to see if the current page matches the path specified
  $match_path = explode('/', 'admin/people/permissions/roles');
  $match = TRUE;
  for ($i = 0; $i < count($match_path); $i++) {
    if ($match_path[$i] != arg($i)) {
      $match = FALSE;
      break;
    }
  }

  //if there is a match, modify the page
  if($match){
    //define the locked roles
    $locked_roles = array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID,);
    $access_group_role = user_role_load_by_name(ACCESS_GROUP_ROLE);
    if ($access_group_role) $locked_roles[] = $access_group_role->rid;
    kpr($locked_roles);

    kpr($variables);

    //recreate the render array for the table
    $header = array(
        t('Name'),
        array(
            'data' => t('Operations'),
            'colspan' => 2
        )
    );
    foreach (user_roles() as $rid => $name) {
      $edit_permissions = l(t('edit permissions'), 'admin/user/permissions/'. $rid);
      if (!in_array($rid, $locked_roles)) {
        $rows[] = array($name, l(t('edit role'), 'admin/user/roles/edit/'. $rid), $edit_permissions);
      }else{
        $rows[] = array($name . " <em>(locked)</em>", '', $edit_permissions);
      }
    }

    //$form = user_admin_role(array(), array(), );
    //$rows[] = array(drupal_render($form['name']), array('data' => drupal_render($form['submit']), 'colspan' => 2));
    $form = $variables['page']['content']['system_main'];
    $rows[] = array(
      array(
          'data' => drupal_render($form['name']) . drupal_render($form['add]']),
          'colspan' => 3,
      ),
    );

    $output = drupal_render_children($form);
    $output .= theme('table', array(
        'header' => $header,
        'rows' => $rows,
    ));

    $variables['page']['content'] = $output;
  }
}

Unfortunately this behaviour is hard coded into the theme_user_admin_roles() function, so you'll need to override that theme function to remove the link and add the locked label. You'll also need to override the access check for the role edit/deletion page so it can't be visited directly.

This is the theme override you'll need to use (it's exactly the same as theme_user_admin_roles() except it has an extra test for your custom role):

function MYTHEME_user_admin_roles($variables) {
  $my_role_id = function_to_get_custom_role_id();

  $form = $variables['form'];

  $header = array(t('Name'), t('Weight'), array(
      'data' => t('Operations'),
      'colspan' => 2,
    ));
  foreach (element_children($form['roles']) as $rid) {
    $name = $form['roles'][$rid]['#role']->name;
    $row = array();
    if (in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID, $my_role_id))) {
      $row[] = t('@name <em>(locked)</em>', array('@name' => $name));
      $row[] = drupal_render($form['roles'][$rid]['weight']);
      $row[] = '';
      $row[] = l(t('edit permissions'), 'admin/people/permissions/' . $rid);
    }
    else {
      $row[] = check_plain($name);
      $row[] = drupal_render($form['roles'][$rid]['weight']);
      $row[] = l(t('edit role'), 'admin/people/permissions/roles/edit/' . $rid);
      $row[] = l(t('edit permissions'), 'admin/people/permissions/' . $rid);
    }
    $rows[] = array(
      'data' => $row,
      'class' => array('draggable'),
    );
  }
  $rows[] = array(array(
      'data' => drupal_render($form['name']) . drupal_render($form['add']),
      'colspan' => 4,
      'class' => 'edit-name',
    ));

  drupal_add_tabledrag('user-roles', 'order', 'sibling', 'role-weight');

  $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'user-roles')));
  $output .= drupal_render_children($form);

  return $output;
}

And this is the code for the access override (needs to go in a custom module)

function MYMODULE_menu_alter(&$items) {
  $items['admin/people/permissions/roles/edit/%user_role']['access callback'] = 'MYMODULE_user_roles_edit';
  $items['admin/people/permissions/roles/delete/%user_role']['access callback'] = 'MYMODULE_user_roles_edit';
}

function MYMODULE_user_roles_edit($role) {
  $my_role_id = function_to_get_custom_role_id();

  if ($role->rid == DRUPAL_ANONYMOUS_RID ||
    $role->rid == DRUPAL_AUTHENTICATED_RID ||
    $role->rid == $my_role_id) {
    return FALSE;
  }

  return user_access('administer permissions');
}


How to apply or assign custom view mode to user display? I am using Display Suites. I have created a custom view mode and have made it available to the user display per Display Suite documentation, but I cannot figure out how to apply the custom view mode to the user display.  It always shows in the default view mode.

If I were editing a node, there would be a vertical tab called Display Settings that would have a field for selecting the view mode to use.  When editing an existing user profile, there is no Display Settings tab.

In various Drupal issues queues, specifically Display Suites, Panels and Profile 2, other users have asked essentially this same question: How do I assign a custom view mode to the user profile display?

Is the Drupal core responsible for user data and display?  Perhaps the problem lies there instead of with whatever module.

The question is too old, but for those who are still looking similar functionality. We can implement hook_entity_view_mode_alter in our custom module and change the rendered view mode dynamically. Check sample below:

/**
 * Implements hook_entity_view_mode_alter().
 */
function MODULE_NAME_entity_view_mode_alter(&$view_mode, $context) {
  // For nodes, change the view mode when in full display mode.
  // Add/Remove any condition based on requirement.
  if ($context['entity_type'] == 'node' && $view_mode == 'full') {
    $view_mode = 'teaser';
  }
}


Panels Everywhere and missing Page Title I am new to using Panels Everywhere and noticed that once I applied PE to my site the page titles went missing. I have site name and slogan and such set up. I can't figure out where the problem is. Has anyone run across this before?

I think page title is a pane you can add to your PE master.

In the region you want to put it:

Add content -> Page elements -> Page title


How do I display taxonomy child terms? I used the Taxonomy View Depth module to create a taxonomy vocabulary like this.

Animal

Cats

Brown
white

Dogs

Brown
White

What I did was enabling the default taxonomy view, and changing the depth in Content: Has taxonomy term ID (with depth) to 1 instead of 0 (also tried 2,3, etc.)

The children items will never show on the page. It does remove the There is currently no content classified with this term. from the page.

What I want? With Taxonomy menu I want to be able to click Cats and show the second level children.

I used View tree Module to achieve this same kind of functionality but i used it for Node Reference. As per their module page, this module is also compatible for taxonomy.

Here are the steps to set Views Tree to display hierarchical taxonomy.

Create a new term view using the fields row style

add relationship for taxonomy term: parent term
add field term id (do not use relationship) and exclude it from display
add field term id with relationship, exclude from display
add any fields you want to display, like term name, term description, etc...
Change style plugin to Tree (Adjacency model)
Set Main field to Term ID
Set Parent field to Term ID with parent relationship


How to enable Drupal site to be in an iframe? How can I enable a Drupal site to be in an iframe and place it in basic html page.

If I try this:

<iframe src="drupal-site.com"></iframe>

then it doesn't show any result.

Any suggestions?

Since Drupal 7.50, core is now protected against clickjacking by default (X-Frame-Options: SAMEORIGIN).

So by default, your Drupal site can only be embedded into a site on the same domain.

To change those settings, assuming of course you understand the associated risks, follow the advice in the change record:

  If you are using a module such as Security Kit that already writes the X-Frame-Options header on its own, that setting will be automatically respected (pending the patch at #2661644: Integrate with Drupal core clickjacking defense) and Drupal core will not overwrite it. The Security Kit module provides an administrative interface for setting this header, so it's a good choice if you need to override the default Drupal core behavior and aren't sure exactly how to do it.
  Alternatively, set the 'x_frame_options' variable via any standard method, for example in settings.php:

// Turn off the X-Frame-Options header entirely, to restore the previous
// behavior of allowing the site to be embedded in a frame on another site.
$conf['x_frame_options'] = '';

  or

// Set the "DENY" option to prevent the site from ever being embedded in a
// frame at all, even on this site itself.
$conf['x_frame_options'] = 'DENY';

  See https://developer.mozilla.org/docs/Web/HTTP/Headers/X-Frame-Options for more information on the various options this header can take.

  Removing the header (as shown in the first example code snippet above) should not be done lightly, or else your Drupal site could be embedded on other sites and then the user tricked into doing actions they don't want.
  If you want to remove the X-Frame-Options header in hook_page_alter() or theme preprocess functions that run later you can remove the header like this (requires PHP >= 5.3):

header_remove('X-Frame-Options');


Showing routes in maps I have a collection of points (latitude/longitude) that i would like to represent on a Map as route. Is there a module that permits this?

Funny you should say that. I just fixed a bug in leaflet module that was preventing me from showing linestrings (i.e. a route).

There are other ways of doing this but this is a good efficient way and leaflet maps are beautiful!

Install the patched version (i.e. the latest and greatest version) of leaflet module - http://drupal.org/node/1707882
Apply the tiny change I put here - http://drupal.org/node/1667780
Install http://drupal.org/project/geofield (7-1.x-dev version) and http://drupal.org/project/geophp
Install http://drupal.org/project/leaflet_more_maps to get a whole bunch of ready made tiles.
Add a field to your node using geofield with WKT format.
Add a node with your points using the WKT linestring format for your route = LINESTRING(lon lat, lon lat, lon lat)
Change the display format for the field to leaflet and choose which map style you want.

http://en.wikipedia.org/wiki/Well-known_text

http://leaflet.cloudmade.com/

Add a comment here if you get stuck at any point.


Why does JsonResponse keep returning a <?php tag at the beginning? I am returning my data like this:

return new JsonResponse([
  'data' => $this->data,
  'error' => $this->error,
  'errorMsg' => $this->errorMsg,
], 200);

Somehow, a PHP opening tag is always being added, making it impossible for Angular 2 to parse the result.

<?php{"data":[],"error":true,"errorMsg":"This email seems to be used by another user."}

I have already tried the most desperate solutions like str_replace() in Response.php in Drupal but it did not seem to help.

Why is it happening?

I was having trouble with this same bug.

At the top of my response there was a php short open tag

<?
<aside data-entity-id="392" data-entity-type="node" class="sidenote">

That was breaking my jQuery ajax call.

It was working locally but broken on the QA server.  Ultimately, after researching the problem, I knew that there was some corrupt PHP file outputting to the page before Drupal explicitly output the page.

After discovering from my php.ini file that short tags were disabled on QA and enabled locally, I was able to grep the codebase for documents in my theme and custom modules that started with a php short tag.  Sure enough, my theme's .theme file was empty with just a php short open tag in it:

<?

Changing this to a regular php open tag and a newline fixed the bug.

<aside data-entity-id="392" data-entity-type="node" class="sidenote">

The qa server was outputting this to the page, but only on this one page (that I know about).  I guess because I was calling

\Drupal::service('renderer')->renderRoot($data);

If I removed that, the controller could return clean json or output.  But when I got the theme layer involved, the bug crept up.


Populate article field based on user login I am trying to accomplish a task with Drupal and I'm kind of stuck in how to implement this, so I'm wondering if anyone has any ideas or can at least point me in the right direction.

My company has over 60 locations.  I am using Views to dynamically create a single "profile" page for each location.  What I want is a way for the manager of each location to be able to log in and create articles for a kind of "What's Happening" section for their respective pages.

When the "manager" user accounts are created, I assign them a location based on a "Location" field that I added to the "User" content type.

What I want to do is add a field to the "Article" content type that is automatically populated with the "Location" of the manager that is posting the article.  From there I can filter in Views to complete the page generation.

I could easily just add a "location" field to the Article content type that the user could manually select, but I know my users, and people will be creating articles for other sites and cause big mess for me to clean up.  I'd like to have the "Location" field in the article automatically populate depending on the users' login.

Possible?  If so, how?

I dont think you need to assign the location for the user.

When a person adds a content that content is automatically assigned the author. So if manager A creates a content then its author field is populated with Manager A.

Now you can use this information in views.

If you are creating a view with all the information related to the location you could create a view with all the contents added by the particular person.


How to upcast webform submission in custom routes resp. controller? Using this route:

confirm:
  path: '/node/{node}/submission/{webform_submission}/confirm'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MymoduleController::confirm'
    _title: 'Confirm your submission'
  requirements:
    _permission: 'confirm webform submission'

And visiting node/15/submission/15/confirm I get the error:

  RuntimeException: Controller
  "Drupal\mymodule\Controller\MymoduleController::confirm()" requires
  that you provide a value for the "$submission" 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()

What am I doing wrong? Why doesnt it load the submission 15? It does exist.

Edit: this is my Controller, the second argument is always null:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\Controller\EntityViewController;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Entity\EntityInterface;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\WebformSubmission;

/**
 * @todo
 */
// class MymoduleController extends ControllerBase { // doesnt make a difference
class MymoduleController extends EntityViewController {
  public function confirm(EntityInterface $node = null, EntityInterface $submission = null) {

    debug($submission);

    $response = new Response( 'test' );

    return $response;
  }
}

You probably just need to declare the parameter type:

confirm:
  path: '/node/{node}/submission/{webform_submission}/confirm'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MymoduleController::confirm'
    _title: 'Confirm your submission'
  requirements:
    _permission: 'confirm webform submission'
  options:
    parameters:
      webform_submission:
        type: entity:webform_submission

The parameter names also need to match, so update your controller accordingly:

public function confirm(EntityInterface $node = null, EntityInterface $webform_submission = null) {


"Non-existed service" errors after clearing the cache After clearing the cache in Drupal 8 (via the UI) I got "The website encountered an unexpected error. Please try again later." error. It happened for the first time. I haven't introduced any heavy changes to the site, basically only created a field and some features (via the Features module).

I've found this error in the logs:

  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "password_migrate". in /.../app/vendor/symfony/dependency-injection/ContainerBuilder.php on line 800

To fix this was trying different things: clearing cache tables directly in the DB, trying drush rebuild (rebuild wasn't successful since it yelds the same error). After some time the error is different (and I don't know why):

  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: The service "ctools.paramconverter.tempstore" has  a dependency on a non-existent service "user.shared_tempstore". in /.../app/vendor/symfony/dependency-injection/  Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php on line 58

I can temporarily get the site back to life by loading {cache_container} table from the old backup. But the site breaks again after clearing the cache and the first error reapers in logs.

The site is basically broken. How can I restore it? How is the {cache_container} populated, so I can reverse the process and restore what's missing based on the cache? Thanks!

It seems that a class is requesting the password_migrate service which does not exist.

This is usually caused when the module that supplies this service is not installed.

I suggest you search the project code for the string password_migrate to find both the requester and the provider.


Using views to display KML of each node in respective maps for each node I have been using OpenLayers and Geofield to try display the custom data layer (KML polygon) on the. First of all I havent been successful at it despite trying out many mays. Also I realized that the views approach discussed almost everywhere would show the custom maps on a 'new' Page or a 'new' block. But what I want is to show the map with the KML data layer right at each node.

Is this ever possible using Views (Data layer) + Openlayer + geofield in first case?

If so, how do I configure the geofield's map which is displayed in each node?

If I understand you correctly, your question is how to attach a view to a node.
You can check out the EVA module:

  "Eva" is short for "Entity Views Attachment;" it provides a Views
  display plugin that allows the output of a View to be attached to the
  content of any Drupal entity. The body of a node or comment, the
  profile of a user account, or the listing page for a Taxonomy term are
  all examples of entity content.

or this other question: Attach a view to a specific node


Add a field programmatically to a custom entity I am defining a new entity following the steps related here: http://www.istos.it/en/blog/drupal-entities/drupal-entities-part-3-programming-hello-drupal-entity

My question is how I can add a field programmatically to the Entity when I define it. I have read some links but I can't get it work.

My code:

function generador_examenes_entity_info() {
  $return['question_section'] = array(
    'label' => 'Apartado',
    'controller class' => 'SectionController',
    'base table' => 'question_section',
    'uri callback' => 'section_uri',
    'fieldable' => TRUE,
    'entity_keys' => array(
      'id' => 'sid',
    ),
    'static cache' => TRUE,
    'bundles' => array(
      'question_section'=> array(
        'label' => 'Question Section',
        'admin' => array(
          'path' => 'admin/structure/question-section/manage',
          'access arguments' => array('administer'),
        ),
      ),
    ),
    'view modes' => array(
      'full' => array(
        'label' => t('Full Content'),
        'custom settings' => FALSE,
      )
    ),
    'access callback' => 'section_access',
  );
  return $return;
}

Thanks

You'll need to define a field and an field instance in your module's .install file. The function can either be in hook_enable() or hook_install(). The field will provide the name of the field and some default settings. The field instance can be seen  as the link between the field and the entity you want to place the field on.

The format of the settings differs per field type (a text field has a maximum length, an entity reference field can define the selectable bundle(s), etc). Often the available settings are explained in the module's hook_field_info implementation. For core fields these can be found on the following page: 7 functions implement hook_field_info().
For non-core fields the settings are likely to be explained in the hook_field_info implementation as well, for example entityreference_field_info().

The process Drupal follows when registering a field is as follows:

The field is registered in the field api first, with it's default settings (the settings as defined in hook_field_info()). But your module can override them in the settings array of your field_create_field function. So that the field with your name will have by default your settings. Other values such as cardinality (how many values can the field hold) and translatability can be defined as well. See the detailed information on field_create_field() for all values.

From there the field is attached to the entity and it's bundle by means of a field instance. This instance defines which field should be attached to which entity and bundle. Here the settings can be overridden once more for this specific fields implementation on this specific entity. You can also select the widget here; the way the field is to be selected. Modules define their widgets in hook_field_widget_info(), available widgets for core fields can be found here: 7 functions implement hook_field_widget_info(). For a textfield you would use the widget text_textfield, for an image you can use image_image, for a non-core module you'll need to lookup the available widgets yourself in the hook_field_widget_info() implementation.
For a full lis tof all properties you can set on field instances, see field_create_instance().

Image field example

function mymodule_enable() {
  // Check if our field is not already created.
  if (!field_info_field('my_image')) {
    $field = array(
      'field_name' => 'my_image',
      'type' => 'image',
      'locked' => TRUE, // Settings can not be changed
      'settings' => array(
        'no_ui' => TRUE, // Field is not visible in field UI and can only be instantiated programmatically.
      ),
    );
    field_create_field($field);

    // Create the instance on the bundle.
    $instance = array(
      'field_name' => 'my_image',
      'entity_type' => 'my_entity',
      'bundle' => 'my_entity_bundle', // If your entity does not have bundles, this is the same as the entity type.
      'label' => 'Featured image',
      'required' => TRUE, // Field must have a value.
      'widget' => array(
        'type' => 'image_image',
      ),
    );
    field_create_instance($instance);
  }
}

Entity reference example

function mymodule_enable() {

  // Create an entityreference field.
  $field = array(
    'field_name' => 'my_entityreference',
    'type' => 'entityreference',
    'settings' => array(
      'target_type' => 'my_other_entitytype',
    ),
    'cardinality' => 1, // Field may only have one value.
    'translatable' => FALSE,
  );
  field_create_field($field);

  $instance = array(
    'field_name' => 'my_entityreference',
    'entity_type' => 'my_entitytype',
    'bundle' => 'my_entitytype_bundle',
    'label' => 'Reference to my_other_entitytype',
    'required' => TRUE,
    'widget' => array(
      'type' => 'options_select',
    ),
  );
  field_create_instance($instance);
}


Is there a way to disable the js of the Views Display Tabs module without hacking the module? I'm using Views Display Tabs module and it works really well. My problem is that I'm using Views exposed filters as a block. When I switch between tabs the filters don't get updated because they are in a  block and the module uses js to switch between tabs, so the page doesn't get refreshed. I would like to know a way to disable the js functionality of the module without hacking it. Ideally the module would have a setting for this.

The standard practice for adding javascript is to use Drupal.behaviors to execute your modules code when appropriate.

This gives an easy way to override modules javascript by redefining that modules behavior. For Views Display Tabs I took a look at their javascript source to see that the behavior was called Drupal.behaviors.viewsDisplayTabs.

So now you can add your own javascript to override this:

//Override Views Display Tabs javascript
Drupal.behaviors.viewsDisplayTabs = function() {}


Twitter-like follow button I'm trying to make a twitter-like "following" system for a content-type I have.

Users have an entity reference to the content-type.

What I want is a user to go onto the content and click the "follow" button. The user's entity ref field would then be populated with this content and the follow button would turn to followed.

Users can follow multiple content.

Can anybody point me in the right direction for accomplishing this please?

Update

I've now got Button and Rules and am trying to set this up, however, I've immediately hit a sticking point: I can't find my content-type in Rules. Shouldn't it be entity:MyContentType?

Update 2

See my answer.

It turns out I was going about this the wrong way.

To create a Twitter-like follow button the best thing to use is the module Flag.

Create a Flag called "Follow Me" (follow_me)

Create a Content-pane View which has:

Sort Criteria: Content: Type (=MyContent)
Context Filters: Content: Nid
Relationships: Flags: follow_chapter (by current user)

This content pane then can be used with Panels.

You can then create another view with the relationship with Flags: follow_me to get a list of content followed by the user.


duplicate terms added by taxonomy_term_save Doesn't taxonomy_term_save() check if terms are being added in duplicate ? I have the following code -

function custom_create_taxonomy_term($name, $vid) {
  $term = new stdClass();
  $term->name = $name;
  $term->vid = $vid;
  taxonomy_term_save($term);
  return $term->tid;
}

But whenever I pass it a $name- which already exists in that vocabulary, then also a new entry is made in the database and there are 2 tids for the same term.

It's perfectly ok to have terms with the same name in the same vocabulary, the name column is not unique in the taxonomy_term_data table, and taxonomy_term_save() doesn't contain any logic to check.

This is by design as it would be very restrictive otherwise. Imagine you had a hierarchical vocab with many different levels...what happens if two terms happen to have the same name but live under different parents?

If you need your term names to be unique for whatever reason you can check if the term exists before saving it by using taxonomy_get_term_by_name()


What is the difference between using drupal_goto('$path') and header('Location: $path')? I've been struggling a lot with a drupal_goto() not redirecting from a view to correct path in all displays.

This is the snippet code.

/**
 * Implements hook_views_pre_render().
 */
function HOOK_views_pre_render(&$view) {
  //if only on node matches, redirects to that node
  if ( $view->name == 'FOO' && $view->current_display == 'BAR' && count($view->result)==1 ){
    if(is_numeric($view->result[0]->nid)){
      drupal_goto('node/' . $view->result[0]->nid);
    }
  }
}

Instead, header('Location:node/' . $view->result[0]->nid); is working in any case.
Why doesn't drupal_goto() work, sometimes?

I had an exposed filter with identifier named destination. Since drupal_goto() takes care of the destination parameter sent in URL with the following code, it was overwriting my code.

  // A destination in $_GET always overrides the function arguments.
  // We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
  if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
    $destination = drupal_parse_url($_GET['destination']);
    $path = $destination['path'];
    $options['query'] = $destination['query'];
    $options['fragment'] = $destination['fragment'];
  }


Calendar display with custom table I am trying to show a calendar page with records stored in a custom table, using the Calendar module.

The table has been integrated with Views using hook_views_data. I also implemented hook_date_views_extra_tables and hook_date_views_fields to identity the relevant date fields to the Date module.

So far, I can create a new View with Calendar format (style plugin). When I add the Date: Date contextual filter (argument), I am able to see the field I specified in the hook_date_views_fields. So far so good.

Now when I save the view and show it, no calendar shows. When I get back to edit the view, the Date argument has been replaced with a "Broken/missing handler" notice.

Has anyone succeeded to show a calendar from a custom table?

N.B. This issue was created for the same purpose but it looks like the OP did not pursue it (or at least did not update it).

The reason for this problem was that the date argument handler was crashing. I had placed the implementations of the date hooks inside mymodule.views.inc, instead of mymodule.module. Duh!


Manually disable a module In Drupal 7, I could manually edit the {system} table in the database to disable a stubbon module.  In my Drupal 8 site, this table is gone.

How can I manually disable a module in Drupal 8?

The Drupal 7 system table data is now stored in the config table in Drupal 8 against the core.extension parameter.

Solution 1: Update configuration

You can run the following code using drush eval or may be using the Devel module's provision to Execute PHP Code.

// Read the configuration.
$module_data = \Drupal::config('core.extension')->get('module');

// Unset the modules you do not need.
unset($module_data['MODULE_NAME']);

// Write the configuration.
\Drupal::configFactory()->getEditable('core.extension')->set('module', $module_data)->save();

You can do this all in a quick one-liner with drush.

drush eval "\$module_data = \Drupal::config('core.extension')->get('module'); unset(\$module_data['MODULE_NAME']); \Drupal::configFactory()->getEditable('core.extension')->set('module', \$module_data)->save();"

Solution 2: Edit config table if you cannot execute PHP

If the site is broken because of the problematic module and you can't even run PHP code, then may be you can edit the config table directly.

In the row in the config table where name = "core.extension" and edit the BLOB column data. The data is a serialized PHP array where you have to remove the module you want to get rid of from the module key of the configuration.

Solution 3: Fast and dirty solution

Remove the module from the file system
Truncate the table cache_config

However, this solution might result in messages saying the module does not exist in file system which mean something is wrong. But at least the broken module gets disabled and you can access your site in most of the cases.

Clearing Cache

Sometimes you might have to clear cache after following the above steps. Read this handy documentation on how to clear cache.


Can I stay on Drupal 7 forever? I've been using Drupal 8 for a while now and while it's not bad, it does slow down development a bit, as the whole framework is more strict. Which is a good thing to some, but I know of many people like me, who prefer having the freedom of easily creating modules, versus having to set up the new folder structure etc.

So my question is, can one survive without upgrading for the foreseeable future? And what is the longest time one can realistically go without upgrading?

IF the current version of Drupal is working out for you and you don't need more features added than you can stick around on 7 for a long time.

The problem is that D7 will not receive any feature updates and most modules will not be updated for D7 aswell.

It is hard to say the exact date of when D7 will not be supported anymore but most likely in 3-4 years.

but the bug/security fixes will continue till the end of this year most likely.

source: https://www.ostraining.com/blog/drupal/drupal-7-end-of-life/


How to use Taxonomy to tag/categories content? I installed and enabled the Taxonomy module, created an Event content type, and a "International Competition" node of that type. I want to apply the tags senior, male, and annual to this event.

I can't figure out how to do this. I've tried reading the documentation for the Taxonomy module but can't figure out where in the CMS I am supposed to associate tags to a node.

The steps to follow to be able to use a vocabulary with nodes of a content type are two:

Create the vocabulary, if it doesn't exist, on admin/structure/taxonomy.

Associate the vocabulary with the content type on; for example, for the Article content type, the page is admin/structure/types/manage/article/fields.

Add a new field, using "Term reference" as field type.

Click the "Save" button, and select the vocabulary that is used for the taxonomy terms that will be added.

Change the settings in the page that appears after you click on the "Save field settings" button.

This is different from Drupal 6, where the form to create (or edit) a vocabulary also allowed to select which content type should use that vocabulary. In Drupal 7 is changed, as a vocabulary can be associated to other entities, such as users (see admin/config/people/accounts/fields) and vocabularies (see admin/structure/taxonomy/forums/fields for the "Forums" vocabulary).


Disable node summary using Page Manager There are a few modules and methods specifically for disabling / removing the node summary page (at /node), like Node Page Disable, but I'm wondering if there's a way to redirect or override the page using the Page Manager module.

There's a good summary of other methods on this stack exchange question and answer and this Drupal forum post. One problem I'm running into with Page Manager is that the /node/%node path is already in use, and I'm not sure how to set it up for just the /node page without any additional arguments.

Yes, you can do that with a variant. I've used that methodology on a personal project. Here are screenshots of the configuration.

The first variant (which returns a 404) checks, the node type (I have a content type called 'person'), the taxonomy terms applied to the node, and the role of the user.


D7 - List entries on config form I have what should be a simple question.  I am coding a module that allows the user to add meta and link tags to the  of your HTML page..think of something similar to CSS injector. (I'm sure something like this already exists, but I'm using this as a learning project).  I am able to create the config forms and everything that the admin would need to create a new entry, and I'm able to input new entries and save them to the database.

What I want is below the "new entry" part of the form, I want to list all current entries with "edit" and "delete" links next to each one (every module under the sun has this functionality).  Can someone point me in the right direction on how to do this?

To expand on mojzis's comment:

// Load your data.
$entries = db_query('SELECT * FROM {my_table}')->fetchAll();

// Prepare a header for your table. The array keys will match up to the key used to input rows in a minute. The values are the column headers.
$header = array(
  'title' => 'Entry title',
  'foo' => 'Bar',
  'op' => 'Operations',
);

// Loop through your data and prepare table rows.
$rows = array();
foreach ($entries as $entry) {
  // Prepare your operation links.
  $op_links = array(
    l('view', 'path/to/entry/' . $entry->id),
    l('edit', 'path/to/entry/' . $entry->id . '/edit', array('query' => drupal_get_destination())),
    l('delete', 'path/to/entry/' . $entry->id . '/delete', array('query' => drupal_get_destination())),
  );

  $rows[] = array(
    'title' => $entry->title,
    'foo' => $entry->bar,
    'op' => implode(' ', $op_links),
  );
}

// Prepare the build
$form['existing_entries'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('No entries have been created.'),
);


Updating Entity Properties with hook_update_N() I have a custom module which defines a custom entity. Now I would like to add a new field to this entity without reinstalling my module. I tried it with the hook_update_N() function:

/**
 * Description
 */
function MY_MODULE_update_7100() {
  $spec = array(
    'type' => 'int',
    'description' => 'Description',
    'not null' => FALSE,
  );
  db_add_field('my_table', 'my_new_field', $spec);
}

in my Module, I updated my existing hook_entity_property_info_alter to add the definition for this field:

function MY_MODULE_entity_property_info_alter(&$info) {
  $props = &$info['my_entity']['properties'];
  // snip
  $props['my_new_field'] = array(
    'label' => t('My Label'),
    'type' => 'integer',
    'description' => t('My Description'),
    'schema field' => 'my_new_field',
  );
  // snap
}

After updating, I can still create and update the entity, but sadly not my new Field which I created.

What did I wrong?

I looked for an example in the commerce module. But the module is using drupal_write_record instead of entity_save.

PS: I already saw this issue but it didn't worked.

I've had this problem myself in the past and almost pulled all my hair out! :)

It turned out that I had forgotten to update my hook_schema declaration within the .install file of my module, and include the definition of the new database field for my entity table.

Adding in the definition should make the new field available to you.


Drupal timezone and database I have a content type with datetime field. When I save node, in database I have 2014-04-28 11:00:00 for instance. But when I edit the node i have 2014-04-28 13:00:00. I guess that it has something to do with timezones.

Now the problem is that i have lot of nodes and i have to get the time from database. I don't want to node_load or anything like that.

The question is - is it possible to extract 2014-04-28 13:00:00 datetime from database with MySQL query? Or any work around where I don't have to use node_load?

Any input will be appreciated :)

What version of Drupal is this?

It's against best practices to go directly to the database but if you really need to I don't see why you can't query the field's table. What problems are you having?

When entering data for a field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.

You may wanted to use format_date to convert your time.
See: https://api.drupal.org/api/drupal/includes!common.inc/function/format_date/7

UPDATE:

I don't know what source you time is in, either a timestamp or formatted date/time. In your example you're using  2014-04-28 11:00:00 so lets convert that to a unix timestamp:

  $newdate = new DateTime('2014-04-28 11:00:00 UTC', new DateTimeZone(date_default_timezone_get()));
  $unixts = $newdate->getTimestamp();
  $siteDate = format_date($unixts, 'small', '', date_default_timezone_get());


How to programmatically print node from a specific author I am trying to print all nodes published by a specific author on my page. Anyway knows a way to do so ?

Thanks

With the  Views module I think you can add a filter on the user name.
I don't know if you are aware of this module, but for short you have to create a view with some settings like :

Row Style : Node (or fields but then you have to add some fields)
Filters : User-> Name (or ID)

To finish you have to add a display, for example "Page" and then edit the path. With this you can create a menu with the View Page.

See the documentation for more.

If it's not a good answer, can you explain more your problem ? (D6 or D7, how do you want to display the nodes...)

(Hope my english is not too bad)


Why does my selection gets only the last row? I rewrote for Drupal 8 a Drupal 6 query on 3 custom entities (see here):

$database = \Drupal::database();
$query = $database->select('amap_distributions_dates', 'amdd');
$query->leftJoin('amap_distributions_inscriptions', 'amdi', 'amdi.datedistributionid = amdd.id');
$query->leftJoin('association_personne', 'ap', 'ap.id = amdi.amapienid');
$query->fields('amdd', ['id', 'datedistribution', 'nombreproduits'])
    ->fields('amdi', ['id', 'datedistributionid', 'amapienid', 'role'])
    ->fields('ap', ['id', 'nom', 'prenom'])
    ->condition('nombreproduits', 0, '>')
    ->orderBy('datedistribution', 'ASC')
    ->orderBy('role', 'ASC')
    ->orderBy('nom', 'ASC')
    ->orderBy('prenom', 'ASC');
$results = $query->execute()->fetchAllAssoc('id');
foreach ($results as $row) { some code here }

Unfortunately, I can retrieve only the last of each {datedistribution-role-nom}.
For each 'datedistribution', if I have more than one 'role' or 'name', I can get only the last one considering the sort order I put in place.
Strange, no?
Any idea why?

Don't use fetchAllAssoc(). Just $result = $query->execute() and then loop over that


Restricted access on certain files in Open Atrium I have a situation where I have individuals that belong to a certain group and they want to have a sub-folder in the documents subspace that is restricted to only a few members of that space.

In my research I have come across a private file system that you can configure/set up, but that solution is not ideal as we still want to keep all the documents for that space in one central location.

Is it possible to break permissions down to level of special access on individual folders/files?

Information:

Using latest version of Open Atrium.
Have no other modules installed.
Current users are used to working with SharePoint as their CMS.

I apologize if I am missing something obvious or have holes in my basic understanding of Drupal, as I have been forced to dive in head first with out testing the waters.

Maybe you could create 2 files sections. The first one, accessible to everyone. Then another one, in a subspace, that would be private (check settings upon creation).

Maybe you could display then the whole structure using only one "files and folder" widget if this is what you need


Drupal site Instant Messaging I am trying to find a module or a standalone solution that I can turn into a module that will allow me to have an instant messaging system like Facebook does on a Drupal site that I am working on. I have never setup a chat system before.

My particular requirements are rather stringent. It needs to be a solution where we host the chatting server (if one is needed separate from the website itself). It must use the site's login state (can't use an external system at all, that means no GTalk, Yahoo IM, or AIM). It also must be able to handle up to 1,000 users at any given time.

I have looked through the Drupal community and I tried the DXMPP module, but it requires Jquery UI 1.8 and that doesn't work with all of the other things that my site uses (such as Homebox). We do have a Jabber server already setup and ready to go.

Does anyone have any thoughts or options here? Thanks!

Other modules that provides chat room are

DrupalChat does not require an additional server component/server. This ease installation but can become a performance issue as PHP/Apahce are not a good fit to efficiently server chat-like application. If scalability is an issue, it supports a more robust solution based on Ape's Ajax Push Engine. The module description implies that the module allow other backend to be written.
Drupal Strophe provides XMPP chat integration in Drupal. It only supports the ejabberd server.
Chat Room doesnt require an additional server component/server. The author is working on a Node.JS integration module aimed to be used by the D7 version of Chat Room to solve the scalability issue.


New server runs with https I have a Drupal site that I am currently developing on a local environment. Recently I uploaded my site to a "live" environment and everything seems to load fine except for all admin functionality. My local server runs with http, while the "live" server configuration runs securely with https. I have noticed that I cannot get into the Drupal admin pages and forms with the Drupal site when running https on the "live" server. Both the overlay and regular admin pages wont load. When clicking a toolbar menu item I get the following javascript console errors: Empty string passed to getElementById(). 5 times, and Error: permission denied to access property "document". Weird... I cant 100% say that this is an https problem, but it seems to be the case.

With more research involving http vs https with Drupal sites, I learned of the securepages module. I have since installed it but cannot enable it on the "live" instance of the site due to none of the admin pages working. I also tried enabling it via drush and it wasn't working for me. So then I figured why not try to enable it on the local version and then upload the database and modules to the live site. I couldn't do that either because my local connection is http and the secure pages module will only allow enabling when its detected SSl. See the conundrum? Has anyone ever seen this before?

Yes.  How you fix this depends on what you built and what you did.   You did not say if you built a Drupal 6 or 7 site.  It makes a big difference.  You also did not say what mods you made to the settings.php file if any when you uploaded this new site.

Your
$base_protocol
$base_url

AND a $conf statement as to HTTPS will need to be properly set - depending on which version of Drupal you are using

You may need to modify the DNS zone to accept a wildcard for the domain depending on what kind of site and content it already has and the

$cookie_domain may need to be properly addressed or Drupal (depending on which one you have ) may drop sessions and log people out by dropping the session if they switch between secures pages classes.  See the issues que of secure pages for examples - and make sure you are looking at the issue that has to do with whichever version you have installed - Drupal 7 and Drupal 6 respond completely differently to SSL and HTTPS issues  See https://www.drupal.org/project/issues/securepages?categories=All

See https://www.drupal.org/https-information for a head start and pointers

As to getting the admin pages to work - usually creating and setting $conf['https'] = FALSE;  should allow http access again by forcing the entire site to non-secure


Show exposed pager as links instead of select box How to show exposed pager as links instead of select box in drupal 7 views ?

Hope this will help, Use Better Exposed Filters
go to settings of better exposed filter


Webform Select Element Optgroup / hierarchy Hello fellow Drupal users, I have created an advanced HTML element in my webform. When the form is submitted the advanced html element reverts back to the default setting, which in this case is option A1. The users selection and data for this element is not in the submission.

This is the YAML an example form:

processed_text:
  '#type': processed_text
  '#display_on': both
  '#text': |
    <select  name="processed_textone" id="processed_textone" style="width: 570px;">
    <optgroup label="A">
        <option value="A1">A1</option>
        <option value="A2"> A2</option>
        <option value="A3"> A3</option>
    </optgroup>

    <optgroup label="B">
        <option value="B1">B1</option>
    </optgroup>

    <optgroup label="C">
        <option value="C1">C1</option>
        <option value="C2">C2</option>
    </optgroup>

  '#format': full_html

I would like to get the data of the selection upon submission. I tried using a computed twig and Ajax, but that doesn't seem to work either. I think I might be able to add a javascript file to get this data into the submission, but I'm not sure. I'm pretty new at subtheming and js in general.

@jrockowitz suggested I look here;
drupal.org/project/webform/issues/2783937

This solved my question. Thank you jrockowitz.


How can I override an entity form with the same date? I have an entity form that requires choosing from a date field.
I wanted to override a submitted entity form if there is an existing submitted form with the same date.
I was looking for a solution in the net, but I was not able to find anything useful.
Thank you in advance for those who can help!

When new entity created you need to implement check (if entity with certain date exists) in your FORM_ID_submit() function. If so, use entity_load() to edit existing entity, if not, create new one. Also I recommend using EntityFieldQuery and Entity Metadata Wrappers to deal with entities.


Custom search box to be included in a view I am using the search box provided from the Custom Search module. It works great. I want to know if there is any way by which i can include the search box in a view which i have created. Regards

PS: I tried this but no effect:

<?php
  $block = module_invoke('custom_search', 'block_view', 'custom_search');
  print render($block);
?>

It displays nothing

Based on below comments i tried doing this:

<?php
$block = module_invoke('custom_search', 'block', 'view', 0);
print $block['content'];
  ?>

If you are trying to filter views result, then adding Custom Search block will not work.
To get this work you need to add Global: Combine fields filter under Add filter criteria, then select fields on which you want to filter the result from Choose fields to combine for filtering. Expose this field to display a search text field. Please check screenshot below:


Is the MODULE.schema.yml required when you define the MODULE.settings.yml? Is the MODULE.schema.yml required when you define the MODULE.settings.yml? It seems that it also works when I remove the MODULE.schema.yml file from install/schema.

It is not absolutely required but strongly recommended to have one.

By default, Drupal doesn't validate the schema, but it does in tests and there is an issue that will enable it if you use the provided example.settings.local.php/development.services.yml. That's why you don't see an error right now when you install, but you'll see it when you write your first test.

It is currently used to ensure the saved configuration has the right data type (e.g. a float and not an integer); not doing that correctly can break stuff and the ability of translating the configuration. More things might follow later, for example a module that generates a settings form.


Are there any modules for Profile2 revisioning/moderation We're using Workbench moderation, and have a new requirement to add revisioning to the profile2 content. The primary reason for this is ensure that users' profile data has some degree of moderation before being made live.

If there is no current module solution for this, can anybody suggest the steps needed to create a module for this functionality.

Two options:

There is a patch for profile revisions here.
There is a Profile 2 Moderation module.

(I will update this answer as I'll be trying out both of these.)


field_type with existing data cannot have its keys changed our site is throwing up the following error:

A list field (field_type) with existing data cannot have its keys changed. in list_field_update_forbid() (line 363 of /modules/field/modules/list/list.module).

I've already researched and found on the drupal developer site a documentation about this error: https://drupal.org/node/1294264

But honestly I don't know what to do.

Has anybody an idea?

Thank you and best wishes

Chris

Try to delete the specified config file:

drush config-delete <name of the config to delete>

and than import the config again:

drush cim


My tab links turned into /user/%/edit, node/%/edit, etc Links on tabs turned into /user/%/edit, /user/%/contact, node/%/edit, admin/structure/types/%/fields, etc.
Also, the links on Administration Menu module have the same issue.

Here's what I did so far.

I've cleared all cache via Admin Menu -> Flush all cache, via Development -> Performance and via emptying MySQL cache_* tables. Didn't solve.
I noticed that tabs are themed by the menu_local_tasks() function. I traced the function to includes/menu.inc, where I found the following snippet, which makes me think it might be related to this function.

* For example, the ancestors of node/12345/edit are:
 * - node/12345/edit
 * - node/12345/%
 * - node/%/edit
 * - node/%/%
 * - node/12345
 * - node/%
 * - node

UPDATE:
Where is '%', of the above URLs, being populated? I want to be able to trace it.

Line 775 of /include/menu.inc was commented out.


Before I install this module I want to better understand this note I want to install the Autosave module.

In the module's page there is the following note. Can someone please clarify it for me in more simple words? I wonder if it could clash with other modules that also use jQuery.

  Autosave uses a modified version of the jquery.field plugin (modified since it doesn't support Drupal field naming conventions very well).
  This version of the plugin was based on jquery 1.2 and does not work with jquery 1.3. Rev 6.x-2.7 DOES support jquery 1.3 and should still support jq 1.2. Please raise an issue if you find that it doesn't.

Let's break the question down into parts.

  Autosave uses a modified version of the jquery.field plugin (modified since it doesn't support Drupal field naming conventions very well)

This means that when the project was written, they took a plugin (piece of code) from another module and used it as a base for their own code.

  This version of the plugin was based on jquery 1.2 and does not work with jquery 1.3.

This bit taken just by itself means that the module will not work if you are using JQuery 1.3 or higher with your Drupal site.  It does, however look like old information and should be disregarded because:

  Rev 6.x-2.7 DOES support jquery 1.3 and should still support jq 1.2. Please raise an issue if you find that it doesn't.

...which states that version 6.x-2.7 supports JQuery 1.3.

The module has been updated several times since then, as you can see the Drupal 6 module is now on version 6.x-2.11.  It is likely that the Drupal 7 version of the module supports much more recent versions of JQuery since it was last updated 6 months after the last Drupal 6 version.

What should you do?

Make a development copy of your site if you haven't already, where you can break things without worry.  Use a VirtualBox or similar if you know how or can learn.
Install the current version of the module and see if it works.  Click around your site and see if you can find any unexpected behaviour
If it doesn't work, consider installing JQuery Update which allows you to choose the version of JQuery being used by your site.


How can I add jQuery to DOM element through drupal.behaviours? On my site on the navigation panel I have a dropdown language switcher. (Dropdown Language Switcher module). I need to modify the js file and show the message to the user after he switched the language. What is the right way to modify js file?

(function ($, Drupal) {
'use strict';

Drupal.behaviors.dropdownLanguagesSelector = {
  attach: function(context, settings) {
   $('.dropdown-language-item .active-language', context).once('dropdown-language-selector')
    .click(function(e) {
      var $wrapper = $(this).closest('.dropbutton-wrapper');
      if ($wrapper.length > 0) {
        e.preventDefault();
        e.stopPropagation();
        $wrapper.toggleClass('open');
      }
    });
  }
};
})(jQuery, Drupal);

Language switcher HTML looks like following:

   FR

I am trying to attach following event:

$('.secondary-action').click(function(){
   alert(Message!);
})

Here's a skeleton of how you can add functionality to elements using Drupal.behaviors.

(function ($, Drupal) {
  'use strict';

  // Create a new function for each element the file attaches
  // handlers to. In this case, $(.secondary-action')
  function secondaryEventListener(context) {
    // Find the elements, ensure that any internal code is executed
    // a single time using $.once(), then loop through the found elements
    // using $.each()
    $(context).find('.secondary-action').once('secondary-event-listener').each(function () {
      // $(this) refers to the current instance of $('secondary-action')
      $(this).click(function () {
        alert("clicked");
      });
    });
  }

  Drupal.behaviors.someArbitraryButUniqueKey = {
    attach: function(context, settings) {
      // Call your function containing the handlers
      secondaryEventListener(context);
    }
  };
}(jQuery, Drupal));


Add classes to quick tabs and nested tabs within quick tabs How can I add custom css classes to quick tabs and nested tabs within quick tabs?

Have you read this issue. Try to apply the patch by using git apply command line :

$ git apply --directory=path/to/module-dir/ add-custom-class-656330-6.patch

If you don't use git, add this line in the theme_qt_quicktabs_tabset function near the line 589 on the quicktabs.module file and the function will become :

<?php
function theme_qt_quicktabs_tabset($vars) {
   if ($key == $vars['tabset']['#options']['active']) {
     $item['class'] = array('active');
   }
   $item['class'][] = drupal_html_class($tab['#title']);# new line added by the patch
   $item['data'] = drupal_render($tab);
   $variables['items'][] = $item;
 }
?>

of course WITHOUT the <?php ?> tags

After that you have the title in class attributes :

Example :

tab title => given tab title
automatic tab class => given_tab_title

Wish helps :)


Linking External Javascript with drupal_set_html_head I want to add the below external javascript file to the head of my Drupal 6 site.

<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
<script type="text/javascript">
stLight.options({
    publisher: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
});
</script>

I want to know if it's OK to do somethng like this, as it's not working at the moment.

function template_preprocess_page(&$vars){
  drupal_set_html_head('<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>');
  drupal_set_html_head('<script type="text/javascript">stLight.options({publisher: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}); </script>');
}

Someone should kindly assist me feature the links of the external file in the header of every page of my site.

Thank You.

I think all you need to add is $vars['head']=drupal_get_html_head(); after your code above so that the $head variable passed to your page.tpl.php is updated.  If you are doing anything "interesting" with your header, you may need to change that to a .= instead so that it is added to $head instead of just replacing it.


Content list empty to Administrator Using Drupal7, I am logged in as administrator, and I am getting an empty content list, even if  there are many nodes created by the administrator user before this.

Even if I add nodes as administrator, the list is still empty.

Here is the content view configuration's screen

Why does this happen? How can I fix it?

From the screenshot you show, it's clear that you installed and enabled the Administration Views module. In fact, for a fresh Drupal 7 installation, the admin/content page would appear as in the following screenshot.

I installed it on my test, and it works fine for me.

Once you install and enable the module, that administrative page is replaced from a view. If you changed the view, it could be it is filtering out the nodes to show in that page.
Go to admin/structure/views/view/admin_views_node/edit and check the filter criteria aren't too much restrictive. By default, that view has only exposed filter criteria; if you find any not-exposed criterium, that is something manually added to the view, and it could be causing the issue you are seeing. A filter for the content type can cause what you see, but so a filter for the creation date, and many other filters.

As reference, this is the setting page for the view as it comes after installing the Administration Views module.

Also, the view has a setting for caching it (as any view); if it has been changing from None to Time-based, then either the query results or the render output could be cached for too long. The default values are 1 hour for both.

The other reason could be that the view is being filtered by the author name. If I put three spaces in the Author field, and then I click Apply, I get the following.

Now the list says No content available. even if I still have those two nodes you saw in the previous screenshot. That is because the author name doesn't contain three spaces.
The same happens if I enter three spaces in the Title field.

To be sure the exposed filter criteria aren't causing any issue, click on the Reset button right to the right of the Apply button. That will reset the values for those filters.


Display a popup once in front page Does any one know a good module I can use to set a nice popup (supporting html) on the front_page when a user visit the website for the first time??

Zerolab is right! If disclamer module is not good for you, also try Splash (Splashify on D7)