How to download a module hosted on GitHub via composer.json? I've got the following composer.json file:

{
    "name": "my-project",
    "type": "project",
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "package",
            "package": {
                "name": "contrib/term-csv-tree-import",
                "version": "dev-master",
                "type":"drupal-module",
                "source": {
                    "url": "https://github.com/grahl/term_csv_tree_import.git",
                    "type": "git",
                    "reference": "master"
                }
            }
        }
    ],
}

However after composer update, the module is downloaded to the vendor folder as:

./vendor/contrib/term-csv-tree-import/term_csv_tree_import.info.yml
./vendor/contrib/term-csv-tree-import/term_csv_tree_import.module
./vendor/contrib/term-csv-tree-import/term_csv_tree_import.routing.yml

How can I correct above configuration to download the project as a Drupal module under docroot/modules/contrib folder? My Drupal root is under docroot folder.

You need Composer Installers for that:

{
    "name": "my-project",
    "type": "project",
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "package",
            "package": {
                "name": "contrib/term-csv-tree-import",
                "version": "dev-master",
                "type":"drupal-module",
                "source": {
                    "url": "https://github.com/grahl/term_csv_tree_import.git",
                    "type": "git",
                    "reference": "master"
                }
            }
        }
    ],
    "require": {
        "composer/installers": "^1.2"
    },
    "extra": {
        "installer-paths": {
            "docroot/libraries/{$name}": ["type:drupal-library"],
            "docroot/modules/contrib/{$name}": ["type:drupal-module"],
            "docroot/profiles/contrib/{$name}": ["type:drupal-profile"],
            "docroot/themes/contrib/{$name}": ["type:drupal-theme"]
        }
    }
}


How to switch between user roles I have three user roles

Merchant
Seller
End User

Merchant has more permissions privileges than Seller. Merchant can become a seller or an end user. When i created a user, i assigned all three roles to that user. But when the user is logged in, by default he should only have Merchant privileges. But he can switch to seller or End user from a drop down. The user will not have all permission privileges (Merchant  + Seller + End User) at a time. He will only have a single role at a time. Is there any way to achieve this.

There are couple of module available to do this job. Hope this will be helpful

1. Masquerade

  The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.

2. Role Switcher

  Role Switcher module provides with an option to change role for
  testing purposes. It creates 'roleswitcher' role and grants it
  permission to administer permissions which makes possible to switch
  back to the original role the user had. The module provides a
  roleswitcher block and a page, /roleswitcher.


Change the Default Empty Node Content I want to change the default empty node content of my Drupal site installation.

I want to customize its text display as well as the "Add new content" link. How can I achieve this?

You can try this:

<?php
function THEMENAME_preprocess_page(&$vars, $hook) {
    unset($vars['page']['content']['system_main']['default_message']);
}
?>


Adding target _blank to ajax form based on response I have been pulling my hair out on this for a few days now, and I cannot seem to actually execute something as simple as this successfully on submission of my form.

What I am trying to do is this... If I fill out my form and it passes validation and the ajax response is sold on click, I would like the form to go to /success and open a new tab/window that goes to google.com else just go to the failed page

It's simple I know. The problem is this, that when I do click it and have a new window/tab come up, the pop up window blocks it. This tells me that this method isnt really a valid method of clicking the button.

This is what I have as my form
.module

    function storageform($form, &$form_state){

        $form['first_name'] = array(
            '#type'  => 'textfield',
            '#title' => t('First Name'),
            '#required' => TRUE,
        );

        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            '#ajax' => array(
                'callback' => 'storage_form_ajax_callback',
            ),
            '#attached' => array(
                'js' => array(
                drupal_get_path('module', 'storage_form') . '/storage_redirect.js' => array(
                'scope' => 'footer',
            ),
         ),
      ),
    );

        if(isset($form_state['values'])){
            $form['page_output'] = array(
            '#markup' => storagedb_submit($form, $form_state)
            );
        }
        return $form;
    }

    /**
     ** Form Ajax
     **/
function storage_form_ajax_callback($form, $form_state) {

      $receipt_info = 'sold';

$commands = array();
      $commands[] = ajax_command_remove('div.messages');
      $commands[] = ajax_command_before('#main', theme('status_messages'));

    if(!form_get_errors()){
      $commands[] = array(
        // The command will be used in JavaScript file
        'command' => 'storage_redirect',
        // JavaScript function:
        'itemstatus' => $receipt_info,
    );

    }
    return array('#type' => 'ajax', '#commands' => $commands);
}

    function storage_form_ajax_callback_validate($form, $form_state){

        if($form_state['values']['first_name'] == ''){
            form_set_error('first_name', t('First name required.'));
        }
    }

storage_redirect.js

    (function($){
    Drupal.ajax.prototype.commands.payday_redirect = function(ajax, response, status){
                if(response.leadstatus == 'sold'){
document.location.replace("http://localhost/storageform/thanks");
window.open('http://www.google.com','_blank');
                    }else{
document.location.replace("http://localhost/storageform/failed");
                }
        }
    }(jQuery, Drupal));

Please someone help me with this small nightmare of a problem I am having.
Thank you.

I believe the answer is, you can't.  Pop-up blocking is intended to prevent the browser from opening a new window or tab when the action was not initiated by the user (they click on a link).  There are several ways to open a new window or tab; however, unless you can truly trick the browser into thinking the user actually clicked it (no, $(a).click() will not fool it) or the user has pop-up blocking turned off, you will always have the pop-up blocker doing it's intended duty.

I'm sure you're advising the user that you intend to open another window for them, why not just provide the link upon successful form submission? Alternatively, you can do a delayed redirect such as is often seen on, I believe, phpBB login screens (the ones that say, "Thank you for logging in.  You will be redirected to XXX in 5 seconds").


Alter views results in a hook When I use contextual filters in a view, I can select an option to display a summary when the argument is not present. If I do it, it shows a list of node IDs instead of titles. For example, I get the following output, where the first number is the node ID, and the second number is the count of nodes.

1256 (12)
4323 (723)
5643 (34)

I want is to rewrite the output and replace the node ID with its title. ViewExecutable has a $args property I can check to know when the argument is not present.

How could I achieve this in a hook? In Drupal 7 I could use hook_views_post_execute(). I modified $view->result and changed it on my own.

I tried to do the same with Drupal 8 and the same hook, but hook_views_pre_render() gets a ViewExecutable object, and I don't know how to change it. I used the following code.

function MYMODULE_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'myidoftheview') {
    $results = $view->result;
    foreach ($results as $result) {
      \Drupal::logger('myview')->notice('<pre>'.print_r($result,TRUE).'</pre>');
      // What code should I write here?
    }
  }
}

It depends on what your result stores. It can be like entity with relation or just field:

1) $result->_entity->set('field_Name', 'xxxxxxxxxxx');

2) $value->node__field_Name = 'xxxxxxxxxxx';


How to add a catch-all wildcard to hook_menu? I want a url structure like so:

https://example.com/bob

which loads a custom page for the user bob. This is what I'm trying:

function mymodule_storefront_menu() {

    $items = array();

    // Wildcard catch for user's storefront
    $items['%'] = array(
      'title'           => 'User custom page',
      'type'            => MENU_CALLBACK,
      'page callback'   => 'mymodule_load_user_page',
      'page arguments'  => array(0),
      'access callback' => TRUE,
    );

    return $items;
}

function mymodule_load_user_page($user) {
    echo $user;
}

However, I'm getting a server 404 and drupal is logging a 'page not found' message the the dblog. Any ideas?

Edit:

I am able to get this to work:

$items['u/%'] = array(...);

but would prefer the plain wildcard to work, if possible.

The documentation for hook_menu() says it in the first wildcard example it provides. (Emphasis is mine.)

  Wildcards in Paths

  Simple Wildcards

  Wildcards within paths also work with integer substitution. For example, your module could register path 'my-module/%/edit':

  $items['my-module/%/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

  When path 'my-module/foo/edit' is requested, integer 1 will be replaced with 'foo' and passed to the callback function. Note that wildcards may not be used as the first component.

The reason of this is pretty easy to understand: A wildcard as first component would be a catch-up for every Drupal route.
It would also conflict with the routes every Drupal module defines. This is also the reason why Drupal core uses node/%node for nodes, and user/%user for user accounts: Despite the wildcards being qualified, Drupal would not understand if a URI like 1 is referring to a node or a user account.


Convert node URL to absolute We are using Drupal Core v8.6.2 and we have a url variable in our node--page.html.twig template. While using ksm() and {{ kint() }} we are finding that if we use hook_preproces_node($variables) that the url is inserted into the $variables array. Unfortunately this url is relative, but we need an absolute URL in our twig template.

How can we convert this url variable from our node--page.html.twig template to be absolute?

node--page.html.twig

I have reduced the comments section to only include comments that were relevant to the question.

{#
/**
 * @file
 * Theme override to display a node.
 *
 * Available variables:
 * - node: The node entity with limited access to object properties and methods.
 * - label: The title of the node.
 * - content: All node items. Use {{ content }} to print them all,
 * - url: Direct URL of the current node.
 * - attributes: HTML attributes for the containing element.
 * @see template_preprocess_node()
 *
 */
#}

<a href="{{ url }}> {# url is the variable we want to be absolute #}
  <h2> {{ label }} </h2>
  {{ content.body }}
</a>

You can use hook_preprocess_node to passe base_url to your twig like the following:

function mymodule_preprocess_node(&$variables) {
  global $base_url;
  $variables['base_url'] = $base_url;
}

in node--page.html.twig you will get the absolute url by:

{{ base_url ~ url }}


Specific permissions for rules components I created two rules components but i can't find any module to set specific permissions for roles.

I want to let some role's users to allow run the first component but not the second one.
thanks.

Rules provides a UI to configure access to components based on a permission.

Edit the component
Click to expand "Settings"
Check "Configure access for using this component with a permission"


Update cache after writing data I'm writing a custom module to extend the Casetracker module to allow users to update the cases' due date via the comments form. So far I have successfully used hook_form_comment_form() to add the date field to the comment form and hook_comment() to write the new value to the DB using drupal_write_record().

I'm running into a caching problem though. The updated values don't show up in the node until I drush cc all. Is there a way I can tell Drupal to update it's cache to show the new value?

I'm using Drupal 6.26, Casetracker 6.x-1.0-beta9 (part of OpenAtrium).

you can use cache_clear_all() to clear the caches after you write the new value to the database. it will be best if you can find out the comment's cache id and clear only that one. Unfortunately I don't have any D6 databases on my server to look into the database


Creating a menu based on cck field I would like to build a custom menu structure based on cck fields.

lets say I have 2 fields in which I will type the menu item.

parent item = field_category
child item= field_subcategory

So in a node create form i use for 'field_category' apples or pears and for 'field_subcategory' green or red.

These items will also be made terms(i have a 3rd field containing tags that are equal to all menu items)

my menu structure is like:

apples

green
red

pears

green
red

my terms are: apples, pears,red, gree.

Then part 2:
These items must be linking to a term or multiple terms.

apples --> links to term apples

green --> links to term apples AND green
red --> links to term apples AND red

pears

green
red

I suspect i wuould need a custom module to do so, but i am not a programmer...so I really hope someone has a solution with contrib.

If you're only concerned about taxonomy term fields, then I reckon that you should investigate the taxonomy_menu or similar family of modules. In fact, looking at your other post, I suggest that you go through the entire list of taxonomy modules on Drupal in general :)


Display custom user profile field as name in articles I would like to display the custom user profile field name as the author's name in articles, instead of the user's username. How can I do this without modifying code of my template or Drupal itself?

I saw solutions for Drupal 7 but I'm using Drupal 8. I found custom modules for Drupal 7 or earlier and code modification ways. Both seems wrong to me because the mentioned modules aren't updated nor it feels correctly to me to change code to achieve this quite basic task.

You can use the Realname module to override the display name with the values of one or more fields:

  The RealName module allows the administrator to choose fields from the
  user profile that will be used to add a "real name" element (method)
  to a user object. Hook_user is used to automatically add this to any
  user object that is loaded. It will also optionally set all nodes and
  comments to show this name.


Remove " edit Article " and [current-page:pager] I'm working on a Drupal 7 site in which I'm using Meta tag module for SEO purpose. I have configured the meta-tags global and content settings.

When I try to edit a node for a content type, for example, edit an Article, inside the meta tag section in the page title field, it always displays <em> Edit title </em>, even I have removed all the tokens for this field but it still displays these tokens.

These are the global and content configurations.

This is how it displays the page title field inside the meta tags section in the content node edit page.

I want to remove <em> edit Article </em> and [current-page:pager].

If you indeed removed tags in global and content settings, then they should not appear when creating new nodes. What you are looking at is probably a node that existed before you changed the meta tag settings.


The Search API module shows a two-words taxonomy term as two separated words, in its widget I am using taxonomy terms to classify my content, and the Search API and Facets modules for searching.

I have some nodes that are tagged with "Asian Cuisine" term; after indexing the content, "Asian Cuisine" is handled as two separated words.

Is there a way to avoid it happens?

Based on your screenshots, consider using the "Taxonomy Term" type for the field indexes. This should remedy your issue.

By using Full Text, you're breaking up the taxonomy term names into searchable words. Use either the default taxonomy term value, or try using the "All Parent Terms" field.


PAReview.sh error, Expected "switch (...) {\n"; found "switch(...) {\n" In my theme's template.php file, I have a custom function as:

function _MYTHEME_content_grid($columns = 1) {

  $class = FALSE;
  switch($columns) {

    // No sidebars, just content.
    case 1:{
      $class = 'grid-100';
      break;
      }

// etc...

When I run the code through http://ventral.org/, I get this message in regard to the switch statement line: switch($columns) {

ERROR | Expected "switch (...) {\n"; found "switch(...) {\n"

I googled around but I can't really find anything on this error. My function works perfectly fine though. I'm guessing it's a syntax error but it would seem weird to insert a ; after the curly brace...

Put simple switch, why put curly braces.

    function _MYTHEME_content_grid($columns = 1) {

      $class = FALSE;
      switch($columns) {

        // No sidebars, just content.
        case 1:
          $class = 'grid-100';
          break;
        case 2:
          //something
          break;

       // etc...
     }
   }


Avatar upload during register. D6 It is possible upload a avatar during the registration process? Then save it into the profile.

I haven't used it before but the Register with Picture module sounds like it would do the trick:

  This module exposes the 'upload picture' element to the registration form. It also gives you the ability to set a picture as required in the module settings.

There are stable versions for both Drupal 6 and Drupal 7. It also has 1600+ installs, is actively maintained and has very few issues in the queue, so I'm assuming it should work great.


How to forward an email to external URL I would like to create a page that will automatically forward to an external site? Similar to what bitly, tinyurl do. So when people type example.com/page in address bar, site will automatically take them to mysite.com? How can I achieve that?

Sounds like you can just create a URL redirect with Redirect, and send to an external URL. No need to create a node.


Print ALT tag from an Image FIeld in a Custom Field Template I'm attempting to create a custom field template for an image field with mutliple values. My field name is field_photo_slidshow

My field template name is: field--field-photo-slideshow.php and I've got it coded like this to produce a Flexslider slideshow:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
<?php if (!$label_hidden): ?>
<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

<?php endif; ?>
<div class="flexslider"<?php print $content_attributes; ?>>

<?php foreach ($items as $delta => $item): ?>
<li class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

<?php endforeach; ?>

And this does what I want so far -- creates and unordered list of the rendered images. But now, I want to add an optional caption, derived from the Image fields alt tag -- but I have no idea how to render the ALT tag from a given image in the above code in the field tempalte. That part of the code, in theory, would something like this:

<?php foreach ($items as $delta => $item): ?>
<li class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

ALT TEXT FROM IMAGE FIELD

<?php endforeach; ?>

Doe anyone have any idea out to print out that alt text in the field template code?

thank you,
Nathaniel

If you install Devel module and use dpm($item); in your code, you will see the structure of $item. Alt is in $item['#item']['alt'].

See for example Modify tpl file to print the path to the image instead of the image itself?.


Removing Drupal GET Form apparently unnecessary parameters I have a FORM built with Drupal 7 Form API, with URL (action) pointing to:

www.example.com/search-products

and the default method POST. My SEO mate has asked me to change the method to GET, so for SEO indexing purposes the URL will be explicit, for example:

www.example.com/search-products?brand=BRAND%201&model=Model%20Fantastic

I have changed the behaviour of the form by adding the following line at the end of the hook_form function:

$form["#method"] = "get";

Now the problem is that the generated URL has some "extra" info that I wouldn't want to be displayed. And it is apparently unnecessary, because if the View (landing page of the FORM) is paged, if I only pass the above parameters + the page, it works perfectly, also if I remove this extra info by hand.

The "ugly" URL is:

www.example.com/search-products?brand=BRAND%201&model=Model%20Fantastic&op=Submit&form_build_id=form-Ab-i8LlsUjtftyuTlL8b7OvZj_tM1MfyuKCnAg5-VncY&form_id=hook_form

(extra info: ... &op=Submit&form_build_id=form-Ab-i8LlsUjtftyuTlL8b7OvZj_tM1MfyuKCnAg5-VncY&form_id=hook_form )

How can I make Drupal ignore that extra info?

Here's a workaround you can use:

    $form['#after_build'][] = 'mymodule_form_modify';

Then:

    function mymodule_form_modify($form){
      unset($form['form_token']);
      unset($form['form_build_id']);
      unset($form['form_id']);
      return $form;
    }

And finally to get rid of the &op parameter:

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

Source.


Integrate Radioactivity with Apache Solr (sort by popularity) Has anyone integrated integrated Radioactivity with Apache Solr?

I'm using the apachesolr module for search and would like to add the ability to sort by popularity. The Radioactivity module assigns points to a module based on 'hotness' (fivestar ratings, comments, views, etc). I want to submit the points Radioactivity gives a node to Solr to use as a popularity index.

I believe that means I'll need to modify the schema.xml file on the Solr end and add some sort of hook on the drupal end. Can anyone point me in the right direction?

You should be able to do this without modifying schema.xml. At a minimum, you'll need to implement hook_apachesolr_update_index(), and you may also need to implement hook_apachesolr_modify_query() to add the Radioactivity data to each query.

Good examples for this can be found in the apachesolr_search.module file itself (and the apachesolr_date module that comes bundled with apachesolr), and also in the additional contrib modules apachesolr OG and apachesolr attachments.

The apachesolr_date module in particular has some code related to adding an available sort option.


How do I create custom layouts for Panelizer? I was wondering how do you create custom layouts for Panelizer in D8? In D7, I can easily create my layouts, and just add a couple of lines on my .info file to let Drupal know where my layouts are.
I created a custom module following a "How to create custom layouts using Layout Builder tutorial". Can I just change the dependencies in the info.yml file that's inside my custom layout module like this:
name: 'Custom Layout'
type: module
description: 'Provides a way for layout'
core: 8.x
package: 'Custom'
dependencies:
  - panelizer:panelizer

Thanks!

Panelizer is based on Panels module, which uses Layout API module in Drupal Core for providing  layout plugins. Please refer to the relevant documentation:

https://www.drupal.org/docs/drupal-apis/layout-api/how-to-register-layouts is written with newer Layout Builder in mind, but basics should be the same
https://www.drupal.org/node/2578731 is an older version of the same docs - might be slightly out of date, but also contain something not present in the previous document


Adding Constraint to Paragraph field I have a Content Type with a field that references 6 different paragraph types.  The field is set up to accept unlimited values.   For one of the types I would like to have exactly four values added.  I've been trying to add a Constraint but it seems that Constraints are built to check if a fields values are valid and not if there are only four items

Is using hook_entity_bundle_field_info_alter the correct hook or should I be focused on using hook_entity_type_alter or maybe even some other method?

Yes, use hook_entity_bundle_field_info_alter and when you add a constraint to the field (and not to a item or property), your constraint gets the entire field item list, so you can check how many items you have of which type, see FieldConfigInterface::addConstraint:

function mymodule_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node' && $bundle == 'page') {
    $fields['field_paragraph']->addConstraint('MymoduleParagraphTypes');
  }
}

Example for a constraint restricting the field to four paragraph items of a specific type:

  public function validate($items, Constraint $constraint) {
    $paragraphs = array_filter($items->referencedEntities(), function ($paragraph) {
      return $paragraph->bundle() === 'image';
    });
    if (!empty($paragraphs) && count($paragraphs) != 4) {
      $this->context->addViolation($constraint->errorMessage);
    }
  }

You can generate the constraint with the Drush command:

drush generate plugin-constraint


How to use external JSON API to create/update node's fields? I have a content type: siteinfo.

This content type has multiple fields: text, entity reference etc.

I want to use an external API to automatically fill some fields of the created node.

The API I want to use says that:

  API returns consistent and well-structured data in XML & JSON
  format. Returned data contains parsed fields that can easily be
  used by your application. This is a RESTful based API.

And this is the API's output:

{
    "status": 1,
    "api_query": "siteinfo",
    "whois_record": {
        "domain_name": "example.com",
        "query_time": "2016-05-05 14:01:12",
        "create_date": "1995-08-14",
        "update_date": "2015-08-14",
        "expiry_date": "2016-08-13",
        "domain_registrar": {
            "iana_id": 376,
            "registrar_name": "RESERVED-INTERNET ASSIGNED NUMBERS AUTHORITY",
            "whois_server": "whois.iana.org",
            "referral_url": "http://res-dom.iana.org"
        },
        "name_servers": [
            "a.iana-servers.net",
            "b.iana-servers.net"
        ],
    },
}

How can I use this external API?

If there's no complicated authentication/request method for the service (e.g. a simple HTTP GET for http://service.example.com/api/siteinfo/1), then a combination of Feeds, Feeds extensible parsers, & Libraries with the JMESPath library installed works great here.

The Feeds module has an HTTP fetcher that can be used in conjunction with the JSON JMESPath parser that allows you to enter JMESPath queries for each field you want parse and insert/update into a node (e.g. in the parser settings you'd could put "@" (root) as the Context & "whois_record. domain_name" if you wanted to map that object's property to a node field).

In this solution, Feeds is handling the import/update bookkeeping while you're tasked with figuring out the correct queries to parse the data. If you go this path, it's very helpful to study JMESPath syntax while using the Feeds Import Preview module to test your imports before execution.

If you need your URL to vary for each import, you can wrap a programmatic invocation of a Feeds import into a function and call it for each imported URL in a drush eval or some other arbitrary location in your environment. For example:

//$url = Is your imported feed.
//$my_feed = Your imported feed machine name
//(i.e. the MY_FEED_MACHINE_NAME in http://example.com/import/MY_FEED_MACHINE_NAME)
function MYMODULE_import_feed($url, $my_feed) {
  $feeds_source = feeds_source($my_feed);
  $feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);
  $feeds_config['source'] = $url;
  $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
  $feeds_source->save();
  $feeds_source->startImport();
}

//Example execution
function MYMODULE_cron() {
  $import_titles = array('title_1', 'title_2');
  foreach ($import_titles as $title) {
    MYMODULE_import_feed("http://service.example.com/api/siteinfo/$title",'MY_FEED_MACHINE_NAME');
  }
}


There are no products in your shopping cart I'm using Ubercart in a Drupal 6 setup.I have created products and able to order the products as an authenticated user mode ,but when i go with anonymous buying it doesn't showing any products in cart page and it results "There are no products in your shopping cart." when click add to cart button.

For me its working good in live site , when i took live dump to my testing site , am facing above bug (There are no products in your shopping cart.) please help if anyone knows the solution for this .Thanks in advance.

That issue might be a MySQL problem. I'm assuming here that you dump the live DB and load it in your test machine.

Please check the uid value for the anonymous user in "users" table. The anonymous user is the one with empty fields. The uid value should be 0.

With certain MySQL configurations when loading sql dumps, autoincremental fields cannot accept the 0 value, and gives an incremented value.


How to get SMS as send method in the Messaging&Notification module (D7)? I cannot find anything for D7, only D6.
Anyone knows howto?
Alternatively; any way to send SMS via views-send-module?

I've used SMS Framework for D7 ,, built a sub-module for my SMS Getway provider (it might be already there for your case),, and with my custom module controlled the rest in notifying|messaging ,,, etc

  The SMS Framework is set of modules that enables interaction between
  mobile users and Drupal using SMS. Several popular SMS gateways are
  supported and the included API allows developers to add support for
  additional gateways. The API also allows other modules to implement
  SMS features.


Truncating text instead of wrapping in a view I have a view that displays an image, title, star rating and user name of a custom content-type I have created in a grid. When  I have a very long title it messes up the layout of the view and makes it look bad as you can see in the below image:

Is there a way I can have long titles like the one below display with only one line and then truncate the rest with an ellipsis.  I.E. I would like the first content to have a title of "Very Long title for..." instead of "Very Long title for this project that will wrap to the next line".  This doesn't seem possible to do from the site builder, is there a module that might allow you to do this?

If you are using Views to do this:

In the Node : Title field, there is a setting to limit the number of characters labeled Trim this field to a maximum length.


How to render an array to twig I've a block with values in the following array structure.

        $block['tag'][] = $term;
        $block['image'][] = $url;
        $block['title'][] = $title;
        $block['description'][] = $description;

From the function build in block, I'm passing it to theme as

$build = [
      '#theme' => 'allofus_four_grids_block',
      '#test_var' => $this->t('Test Value'),
      '#doubles' => array('key' => $block),
    ];

Then inside the module, I'm passing it to twig as

'allofus_four_grids_block' => [
      'variables' => [
        'block' => array('key' => array()),
      ],
      'path' => drupal_get_path('theme', 'basis') . '/templates/custom-blocks',
    ],

And in the twig I'm iterating it as

{% for key,value in block %}
    Key : {{ key }}
    Value : {{ value }}
    {% for key,text in value %}
        Key : {{ key }}
        Value : {{ text }}

    {% endfor %}

{% endfor %}

But this is not giving me the values?

Here you declare

'allofus_four_grids_block' => [
      'variables' => [
        'block' => array('key' => array()),
      ],
      'path' => drupal_get_path('theme', 'basis') . '/templates/custom-blocks',
    ],

So you need to use the variable block :

$build = [
      '#theme' => 'allofus_four_grids_block',
      '#test_var' => $this->t('Test Value'),
      '#block' => array('key' => $block),
    ];

Not #doubles


How to allow user to use one exposed filter and select between two views I am using the search_api module with views as the back-end. Users will have the ability to search through two different kinds of content, and there will be two separate views (one for each content type) to power the search results. I want to expose one search box, but then allow the user to direct those search terms to one view or the other.

Here is a picture that should make my desire more clear:

If the user selects "songbook", then their search gets directed to the song view. If they select "blog", then their search is directed to the blog view. How do I accomplish this using views?

Usually views with exposed filters use get params fx

example.com/view1?filter_a=search
example.com/view2?filter_b=search

If you create your own form then build the URL bases on input and search type it should work just fine. I don't think it will be possible to do a view selection with exposed filters.


How to I add translations for Month and Day in a date field? I am working on a Drupal 7 site that will be in English and Inuktitut.
I have the i18n internationalization module installed. It does provide Inuktitut as a language option, but there are no available translations for Inuktitut.

I can see the options to localize the date format, but I need to be able to translate the months and days. How do I do this?

I'm looking for

Monday = naggajjau

Tuesday = aippiq

...

January = jaannuari

February = viivvuari

and so on.

Thank you

You can translate everything in Administration » Configuration » Regional and language » Translate interface (admin/config/regional/translate/translate)

Concerning dates, you usually need to translate the following strings :

!month-name |January|February|March|April|May|June|July|August|September|October|November|December : you must keep !month-name and | in the translated string
every string starting by !long-month-name
!day-name Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday

And you should be good.

Even better, if you know several people interested in maintaining a language translation, you should go to https://www.drupal.org/node/807756 and reopen the issue. The goal is to have one place to improve and maintain the translation in https://localize.drupal.org/


add jquery to drupal website I want to add 2 jquery scripts to my website that have to be executed on every page.

Smoothstate

<script src="jquery.smoothState.js"></script>
<script src="functions.js"></script>

If i read some websites I don't understand how to add them. I can call the js file's in my .info file or is there an other way? I also read about template_process_html() to add js to my theme but in what file i have to put this?

Can someone help me out with this.

I would recommend you to just add it to your theme info file.
That is the easiest way really, since you need them on every  page.

PS: dont forget to clear caches after you added it to your themes info file.


Aggregate uploaded files for simplified download I have a content type that users are uploading a lot of files into, and the client would like to be able to download all of the attached files with a single click. It seems that a server-side compression of all the files would be a good solution, something like Stephen.Colson is trying to do here stephen.colson's sandbox.

I haven't found anything appropriate, though. Is anyone aware of a good solution for aggregating file downloads?

Take a look at the pclzip suite of modules ZipCart.


Show help text above input and below title of a cck field Hi I am working with a drupal 7 I have created multiple content types for the site. I want to display the content of the help text of a particular cck field above the input field instead of displaying it below the input field

you could use template_preprocess_field ( preprocess for theme_field ) to adjust the position of field description/help text.

Cheers


How to group uploaded documents into folders? I want to group my documents in sub folders... when i upload the document using core upload module, i want that those modules get categorised under different section and a user can see those and when he selects an optio then all the files under that folder gets displayed.

i am using drupal on shared web hosting.

In Drupal, this is probably easier to create a custom content type Document, to which you add a file field.  You can then add a taxonomy term reference field targeting the included Tags vocabulary (in Drupal 7) and then tag the files however you like.  Then, you can create views using the Views module to display the files however you like.  This approach offers a lot of flexibility but will be very complicated to set up your first time.

Alternately, if you have a simple structure, you could create a custom content type Group of documents and attach a file field that allows for unlimited uploads.  Then, you could create a node of the Group of documents content type for each page and upload the files that way.

I didn't describe a way to organize the documents into folders because Drupal doesn't really care about folder structure.  If you really wanted to have a folder structure, it would be better to just upload them via SFTP and let users browse the directories without interfacing with Drupal at all.


How can I theme individual fields in a row? I'm having trouble doing something that I think should be relatively simple Drupal 8 views.

I have a content type called Countries. I would like to display the 3 latest country nodes on my homepage in a views block. Each country is displayed with the class "views-row" on the container div. I am using views--view--unformatted--countries--block_1.html.twig to theme the output.

I would like to output something like the following markup:

Title of node

Title of node

Title of node

The problem I'm having is accessing individual fields in the template.
If I use a view mode, I can access individual fields. If I select "show fields" in the view, I can add a field for "view result counter" and "path", which would allow me to add the "view-row-N" class and link the a tag to the node, but I can't get access to the fields individually. I have the {{ row.content }} variable, but any attempt to dig further into the variable (eg row.content.field_name) gives me nothing and calling a {{ dump(row.content) }} crashes the website.

I can't output this as a view mode for 2 reasons. I don't have access to the "view result counter" or "path" fields in a view mode and, even if I had these variables, some fields would be nested inside others (The image and title are nested inside the )

I feel this should really be as simple as

etc but I've tried everything I can think of. Am I completely on the wrong path?

You are on the wrong track. If you want to rewrite in twig how the fields are built to a row, you have to use the template views-view-fields.html.twig.

But the simplest method would be to rewrite the result of the fields in views ui. This is the option "Override the output of this field with custom text". If you apply this on the last field and hide all previous fields with the option "Exclude from display", you can see the twig variables for all fields in "Replacement patterns" and you are able to rewrite the complete row like the example you have shown in the question.


Display block after some action (saved node) I want to display block after an action. My user will create new content (node). After he save it, the content is shown with a specific block (only once, no further).

I was looking on trigger module, but I do not see this option.

I am using Drupal 6

Thank you for help!

You can use Rules + Rules Bonus Pack for this. The Rules Bonus Pack module has actions for enabling and disabling blocks upon a certain event (e.g. save a node). See this screencast for an explanation.

Note; Rules Bonus Pack is a testing ground for new functionality for the Rules module, so test thoroughly. However, the linked screencast above was published in 2011, so perhaps the code had some test mileage already.


popup after contact form submit we want the "message sent" message that comes out after you submit the sitewide contact form to come out in a popup instead of in a div on the front page.  How can I achieve that?

I have googled everywhere and asked questions on drupal.org but no one has answered me.

You can use Better Messages module

  Better Messages is a very simple module that provides "Popup-like"
  Drupal messages.

  Better Messages intends to let you control where and how you want to
  see your Drupal messages! Combine different animations and override
  better_messages.tpl.php to create your custom look.


storage_api The file could not be uploaded I'm attempting to upload a a file using a custom context type that uses the storage class i defined thru the storage_api module.  For some reason the upload of an image to it is failing with "The file could not be uploaded."  I have the local file system as the initial container and should propagate to an s3 bucket after the upload.

I've tried the built in Content>Media> add file and that works fine.  i think the file lands in public://  However I want to use the storage class from the storage_api.

I see the following in the dblog when i attempt the file upload that fails:

  Message: The upload directory storage-field-corp-image: for the file
  field field_corp_image could not be created or is not accessible. A
  newly uploaded file could not be saved in this directory as a
  consequence, and the upload was canceled.

Not sure where to go from here.

Found the issue.  Turns out the Directory Path in the local container, which is the initial container, for the storage class the content type is using NEEDS to have a trailing slash. As in:

sites/default/files/storage/

instead of:

sites/default/files/storage

it's that picky.  and the log does not say its the issue.  it just says it had trouble accessing the field.  I found it by trial and error.

I hope this helps someone.


how do I get my module to install a view? I have developed a module in a dev environment. I built a view for it using the UI. I've exported the view, but I don't know where to put it so that an installation of the module in a fresh environment will also create the view.

How do I do this properly?

Bonus: how do I have the module uninstall the view on hook_uninstall?

Create the MODULENAME.views_default.inc file (replace MODULENAME with the name of your module), and copy the exported code in the implementation of hook_views_default_views() you write in that file.

For example, the Views module implements node_views_default_views() for the Node module. The relevant parts for the front page view are the following ones.

  $views = array();

  // Omissis

  $view = new view;
  $view->name = 'frontpage';
  $view->description = 'Emulates the default Drupal front page; you may set the default home page path to this view to make it your front page.';
  $view->tag = 'default';
  $view->base_table = 'node';
  $view->human_name = 'Front page';
  $view->core = 0;
  $view->api_version = '3.0';
  $view->disabled = TRUE; /* Edit this to true to make a default view disabled initially */

  // Omissis

  $views['frontpage'] = $view;

The hook then returns the content of $views.

If the view has not been overwritten by a user, it should not be shown in the view list, once the module implementing the hook is uninstalled.


7 - Display translated content using Flexslider Views Slideshow I have a Views block which uses FlexSlider Views Slideshow as the format. The fields which supply the captions have translations but only the default (English) versions are displayed with the FlexSlider Views Slideshow format. Example of the Views block using FlexSlider Views Slideshow can be seen here.

I have a Views page as part of the same view which uses unformatted list as the format. This handles the translated as expected. Example of the Views page is here.

The captions are from the title field of the content type which use the Titles module so they can be translated.

Other modules in the mix are i18n, i18n_block, i18n_field, i18n_views which enable the content to be translated in the first place.

So, my question is: How to get the FlexSlider Views Slideshow to display translated content?

I've checked the Field Language setting is Current User's Language in the View.

I've checked the Make this block translatable option is checked in the block's configuration.

I've checked the Language Detection Settings are ordered; URL, User, Default

I've cleared all the caches.

I appreciate your suggestions.

Your problem might be because of the "language detection" configuration.

So check this configuration via Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.


Calculate bonuses for users I'm trying to implement bonus calculation system to my website. It should calculate bonuses for users.

This is how it should work:

User1 can get 2% bonus
User2 has for example 100 points
The bonus for User1 is calculated as User2 points * User1 bonus % * level x%

There are different levels of bonuses.

Level1 x% bonus: User1 gets amount x% of bonus from three users who have registered after User1. So User1 gets bonus from User2, User3 and User4.
Level2 y% bonus: User1 gets amount y% of bonus from nine who have registered after User1, User2, User3 and User4. Like this: User1 gets bonus from User5, User6, User7, User8, User9, User10, User11 and User 12.

There are 9 levels and it continues like explained above. Users are multiplicated by 3 so users where User1 gets bonuses are: 3, 9, 27, 81.. etc.

Any ideas how to implement bonus calculation? I was thinking about using the Rules module, but I am not sure how it can handle this. Does performance suffer, if there are ten of thousands or even more users?

The Userpoints module will be used.

Treat bonuses as fields, and use Computed Field to manage calculations:

  Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!

In user's profile, keep an Entity Reference to all users that registered from his links or gave his name at registration. Use simple recursion or deep scan to make actual computation, and you're there.


How do I use print to generate a PDF of all entities referencing a specific node? I'm trying to use the Print module to generate pdf's and epubs of the stories on my site. However, I need to get Print to generate these files from the story page and then generate the pdf with ALL nodes that reference the story, the chapters. I'm not sure how to do this as I've never really done tpl.php's before. I need some help here.

Can print be made to work with a panels layout that shows what I want in it? I have a panels layout working mostly for an example of what I'm trying to achieve.

http://fanbards.net/print/stories/13008

How do I make the tpl.php file I need to make that end up as my print selections for Stories?

Seeing the url for print layout works fine, my first suggestion would be, that you can actually do it simply by activating the pdf module and changing the path to trigger the 'pdf-generator':

print-path:
http://fanbards.net/print/stories/13008

printpdf-path: http://fanbards.net/printpdf/stories/13008

…you may find further useful info about this on the documentation page for Print.


Architectural - How to setup content types for very unique editable pages We are working on a site for a client. This page has in total about 30 different pages. Each page has a unique and complicated design. In order to give the client the possibility to edit texts on the pages without changing the design we created text fields for each content type. Each content type has around 30 fields (text or long text) which we manually render in the template files. Each field has a unique machine name. We always created a new field whenever we needed a new field in one of the content types. And each content type has only a few contents (variation of the page).

Current structure:

Content type 01
    Field 01
    Field 02
    ...
Content type 02
    Field 05
    Field 06
    ...

The question now is if there is a better way of building such a architecture, since we are having a quite large php memory usage. The idea of drupal is to create a content type and have then a lot of contents of that type. But that approach doesn't fit to our customized page design.

One possible solution which we gathered is to reuse the fields in all the content types. Originally we named the fields in the example above field_content_type_01_field_01 and field_content_type_02_field_05. This solution would mean we have to change the fields to have field_field_01 and reuse that field in all content types.

But is there a better way for our setup?

Option 1: Panels
Maybe you should check to what extend your unique and complicated design of each page" could be implemented using the Panels module. Some details from its project page:

The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Learn Page manager! is an interesting (and amazing) set of videos. They contain various topics related to the Panels module. Here is a summary of the entire set of videos about this topic (quote from the link above):

Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
The screencast series is targeted at experienced Drupal developers.
Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Refer to Explaining Panels: An Overview for Drupal Developers for another great explanation about the Panels module.
Option 2: Display Suite
Another approach is to use the Display Suite module. Some details from its project page:

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.

Screencasts & articles about Display Suite has numerous screencasts with more details about it.


Rules- how can I redirect a user to view their profile only when they update their profile? I want to redirect users to their profile (/user) after they save changes to their profile settings (/user/[uid]/edit).

If their accounts are updated in another manner (by rules, etc.), I do not want them to be redirected.

I made a rule like this:

Event-> After updating an existing account
Actions-> Page redirect to user/[account:uid]

This redirects properly; however, on my site sometimes user accounts get updated when a user adds content.  Adding content then also causes this rule to get called, which I don't want.  I only want the user to be redirected if they updated their account details at user/[account:uid]/edit.

I tried adding:

Condition: Path has URL alias: user/[account:uid]/edit

However, then the redirect ceases to function.

{ "rules_cw_profile_redirect_user_to_profile_page_after_edit" : {
      "LABEL" : "Redirect user to profile page after editing account",
      "PLUGIN" : "reaction rule",
      "REQUIRES" : [ "rules" ],
      "ON" : [ "user_update" ],
      "IF" : [
        { "data_is" : { "data" : [ "site:current-page:url" ], "value" : [ "account:edit-url" ] } }
      ],
      "DO" : [ { "redirect" : { "url" : "user" } } ]
}


How to use $variables from theme setting in main menu I make some field in theme setting and can use them normali in block, page, but when I want to use them in main menu its dont work.

function saka_theme_preprocess_menu__main (&$variables, $hook) {

    $variables['social_url_fb'] = theme_get_setting('social_url_fb','saka_theme');

}

and in menu--main.html.twig I write this..

{% for item in items %}

                     {{ item.title }}

        {% endfor %}

You can't use name suggestions with double underscore in preprocess function names.

You have to replace this with an if statement in code:

function saka_theme_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    $variables['social_url_fb'] = theme_get_setting('social_url_fb','saka_theme');
  }
}


Display blog posts from Wordpress to my Drupal site and filter it by taxonomy terms I am new to Drupal and need some help. I have a Wordpress blog and a Drupal (version 7) website. I want to display a few blog posts from Wordpress onto my Drupal site. The problem is that I want to select/filter the blog posts based on taxonomy terms I've created in Drupal (blog posts will have corresponding tags for filtering). How can I do this?

This is a bit complicated. You'll need to fetch the data somehow from WordPress and make it Drupal data. Fortunately, there's the Feeds module that can help you getting data from your WordPress and transforming it into Drupal nodes. You'll need to configure the Feeds to also parse WordPress categories and create taxonomy terms from it.

I recommend you to read the Feeds documentation before start using it.


Link value not updating after 'Save' I've got a content type that has a link field in it. I added this link: '
https://wwwdev.ebi.ac.uk/interpro/' and saved. Then I realised this was an old address. It should have been 'https://www.ebi.ac.uk/interpro/' so I went back in, added the new address, and saved again. But the value didn't change! It was still showing 'https://wwwdev.ebi.ac.uk/interpro/'. Here's what I've done:

Flushed the Drupal caches
Flushed the browser cache
Tried in a new private/incognito window in another browser
Checked the database - it has the correct value, not the one showing on the page
Tried another url in the link field (like 'www.google.com') and that works fine
I put the correct address back in the field and it shows as the wrong address, even though the wrong address doesn't exist in the database.
Tried adding the correct address to the body field and it was transformed to the wrong address!
In 'Manage display' I tried the different settings for the link field. 'Domain as link' resulted in the right domain showing in the link text  ('www.ebi.ac.uk') but with the link 'https://wwwdev.ebi.ac.uk/interpro/' in the href attribute.

Does anyone know what might be happening? I'm not using Conditional Fields, incidentally.

Okay, I fixed this. It was a legacy script in html.tpl.php. What I should have tried in my debugging was to switch theme. That would have at least narrowed it down to the theme layer.


Notify user by email when matching content is uploaded I'm setting up a real estate website that sends an email to a user notifying them when a property meeting their specifications is uploaded.

Any ideas how I can do this in drupal 6/7 ?

Take a look at subscriptions module also and especially at this tutorial. I think this is a much simpler approach.


How do I disable the "Flood attempts IP blocking" functionality? Drupal blocks the IP used to access the site, when a user tries to log in many times.

How can I disable this functionality?

What you can do is adding the following code in the settings.php file.

$conf['user_failed_login_ip_limit'] = PHP_INT_MAX;

In this way, the IP will not blocked.

user_login_authenticate_validate() contains the following code.

  if (!empty($form_state['values']['name']) && !empty($password)) {
    // Do not allow any login from the current user's IP if the limit has been
    // reached. Default is 50 failed attempts allowed in one hour. This is
    // independent of the per-user limit to catch attempts from one IP to log
    // in to many different user accounts.  We have a reasonably high limit
    // since there may be only one apparent IP for all users at an institution.
    if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) {
      $form_state['flood_control_triggered'] = 'ip';
      return;
    }
    $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();
    if ($account) {
      if (variable_get('user_failed_login_identifier_uid_only', FALSE)) {
        // Register flood events based on the uid only, so they apply for any
        // IP address. This is the most secure option.
        $identifier = $account->uid;
      }
      else {
        // The default identifier is a combination of uid and IP address. This
        // is less secure but more resistant to denial-of-service attacks that
        // could lock out all users with public user names.
        $identifier = $account->uid . '-' . ip_address();
      }
      $form_state['flood_control_user_identifier'] = $identifier;

      // Don't allow login if the limit for this user has been reached.
      // Default is to allow 5 failed attempts every 6 hours.
      if (!flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) {
        $form_state['flood_control_triggered'] = 'user';
        return;
      }
    }
    // We are not limited by flood control, so try to authenticate.
    // Set $form_state['uid'] as a flag for user_login_final_validate().
    $form_state['uid'] = user_authenticate($form_state['values']['name'], $password);
  }

The limits are actually two: one for the case Drupal always has an IP, and one for when Drupal has also a user ID. The latter is for the case the user enters a username for an existing account; in that case, Drupal register the user ID, and the IP.
If you want to avoid also that case, then you need to add also this line to the setting.php file.

$conf['user_failed_login_user_limit'] = PHP_INT_MAX;
$conf['user_failed_login_user_window'] = 5;


How do I count the number of nodes in a View I would like to display the number of nodes in a particular view OUTSIDE OF THAT VIEW. For example, on the home page (page--front.tpl.php) I want to insert a simple php echo statement that pulls the number of nodes in "View X", and another php echo statement that pulls the number of nodes from "View Y", etc.

function theme_get_node_count($content_type) {
     $query = "SELECT COUNT(*) amount FROM {node} n ".
              "WHERE n.type = :type";
     $result = db_query($query, array(':type' => $content_type))->fetch();
     return $result->amount;
}

The previous code does not work because I am not counting a content type. Is there a $view variable I can plugin into this function to achieve the same results?

Thanks

In an executed view object, you can access how many rows or results are returned by looking at:

$count=count($view->results);

So, if your view returns 2 rows, $count would be 2, if 1, $count would be 1, etc. This can be accessed from a module that executed a view itself or from inside almost any of the views templates as well.


Unable to debug drush command using xdebug with batch api I have been debugging drush commands with xdebug and my IDE (currently PHPStorm 7) for a while, but I have been noticing that there are certain commands that die whenever I have the dubegger enabled in the IDE. From what I can tell, it's commands that do batch processing and therefore call drush_backend_batch_process(). In tracking it down as far as it will let me with the debugger, it looks like it dies in _drush_backend_proc_open().

An off the shelf example is the solr-index command in the apachesolr module. I can debug up to the point where drush_backend_batch_process() is called, but it never returns from that call.

Is this a known issue with xdebug on the command line with drush with no way around it? Or is there something I can do in my configuration?

Thanks.

You're debugging your script using IDE which require valid xdebug.idekey to be present in the session which probably isn't passed correctly to the forked process.

It's probably the bug of XDebug (see: #938) which doesn't debug well the forked processes.

I assume you've xdebug.remote_port working correctly and there is no any communication issue. Remote debugging generates log file (defined by xdebug.remote_log), so you should check further debugger communications details there.

As for workaround, you should debug your script manually by calling the functions: xdebug_start_trace() and xdebug_stop_trace().

In case debugging on demand won't work with forked processes, enable xdebug.auto_trace, restart Apache, so all forked processes can be debugged properly which will generate huge trace file which you can analyze (defined by xdebug.trace_output_dir/xdebug.trace_output_name).

Check my xdebug.ini for suggestions, especially these settings are useful to see all the details:

; Data
xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=0       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=200        ; int: Controls the protection mechanism for infinite recursion protection.

If XDebug still won't work, then consider using phpdbg instead.

For suggestions how to debug Batch API process, see: How to debug Batch API more efficiently?


Allow users to view others contents with autocomplete Entity Reference field I'm trying to build a content type where any user can select an entity reference value through an autocompleted Entity Reference field.

Using this field works as an admin. I'm able to see the referenced contents. But when I try as a logged in lambda user, I can't view the content created by other users.

The field is in the content type "Invoice" and has to allow users to select a contact name (content type "Contact").

I think it's a matter of access rights on this specific content type. So far, I've tryed creating a module with a hook_node_access function :

function contact_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if (in_array($type, node_permissions_get_configured_types())) {
    if ($op == 'view' && user_access('view ' . $type . ' content', $account)) {
      return NODE_ACCESS_ALLOW;
    }
  }

}

It still doesn't allow users to see and select other's people contacts.

Generally if a user cannot see another user's content then it is either because there is a content access module installed that is restricting access or the content is unpublished.

By default in Drupal you cannot see unpublished content unless you created it or you are an administrator with access to all content.


how to get the web form results I need to get the results of the web form as a block to display with the webform.

It seems views has no way.

I have been able to get Webform information into Views in the past, but I ended up delving into the database to do so since the integration of Webform and Views is limited to submission ids and edit links, not the specific data that was entered by the user.

I found this tutorial online that might be useful for you. http://archive.org/details/DisplayWebformSubmissionDataInViews


Create a printable document from template I am fairly new to Drupal. I have a Microsoft Word Document template and would like to allow users to fill in fields and insert an image and then print the document. I am not stuck on using the Word template if that is not feasible.

We have been using a document that is a fillable form. We fill out the fields and then have to add an image to the form in a particular position. I would like, if possible, to have Drupal do this. I would like it so a use goes to the site, fills out the information and uploads the image. Once that is done they would need to print the document and have it retain a specific layout.

Possible? Please point me in the right direction. I am using Drupal 7.x

thanks

This use-case is perfectly normal for Drupal, but you're better off not using Word at all.

Create a content type (let's call it fillable) that contains all of the fields you require including an Image field which requires the ImageField module.
Give your users the 'fillable: Create new content' and any of the other relevant permissions for that content type that you wish them to be able to do.
Edit the content type and go to the manage display tab, determine how you want the fields to show (with labels? as links?).  If you need to group fields you can use the Field collection module.
Use your theme to make the node page layout how you want it to be
Put a print.css file in your theme and use that to fine-tune how the document prints

If you want to make other changes to the output of the node (like extra text in certain places, or complicated formatting), you can create a node template for that specific content type by giving it a name such as node--fillable.tpl.php


Find slowest loading / longest time to generate pages Is it possible to find pages that take the longest time to generate? I am aware Devel can collect query log per page, but is there a module that collects these per page and displays a list of slowest pages?

The Performance Logging and Monitoring module was split out from the Devel module last summer, but is mostly the same.

The summary logging page is sortable by all of the table columns.  For example, if you want to show the slowest pages first, you just need to click on the "MS (MAX)" column heading until it sorts descending.  The direct URL would be at /admin/reports/performance-logging/summary?sort=desc&order=ms+%28Max%29

You can also do a manual query on the database if that is where you are storing results:

SELECT *
FROM {performance_summary} performance_summary
ORDER BY ms_max DESC


Request a new password using username only We don't want to use email id for request a new password.
How can we accomplish this without customizing/touching to core module.

User module accepts either username or email to reset password.. Code goes below in user module...

/**
 * Form builder; Request a password reset.
 *
 * @ingroup forms
 * @see user_pass_validate()
 * @see user_pass_submit()
 */
function user_pass() {
  global $user;

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username or e-mail address'),
    '#size' => 60,
    '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH),
    '#required' => TRUE,
    '#default_value' => isset($_GET['name']) ? $_GET['name'] : '',
  );
  // Allow logged in users to request this also.
  if ($user->uid > 0) {
    $form['name']['#type'] = 'value';
    $form['name']['#value'] = $user->mail;
    $form['mail'] = array(
      '#prefix' => '<p>',
      '#markup' =>  t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the e-mail.', array('%email' => $user->mail)),
      '#suffix' => '</p>',
    );
  }
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password'));

  return $form;
}

function user_pass_validate($form, &$form_state) {
  $name = trim($form_state['values']['name']);
  // Try to load by email.
  $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1'));
  $account = reset($users);
  if (!$account) {
    // No success, try to load by name.
    $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
    $account = reset($users);
  }
  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }
  else {
    form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
  }
}

You need to implement hook_form_alter in your own custom module and alter above form validation to add your own which accepts only username... You can achieve using custom module with out touching Drupal core... In hook form alter check for form id user_pass and override validate handlers like below..

$form['#validate'] = array('custom_module_user_pass_validation');

function custom_module_user_pass_validation(($form, &$form_state) {

}


Exporting comments only from one drupal site to another How can i export only comments from a Drupal Site (Live) to a Drupal site (Dev).

The content of both sites is same. The live site only has new users and comments. I already exported the users and imported into Dev Site.

I looked into many modules but non on them only allow comments to be exported. Can i simply copy some MySql tables ?

thanks

Assuming you are using Drupal 7.

Use the Views module and create a table view of node comments.

Add fields: Node ID (nid), Comment ID (cid), Comment Title, Comment Body, Commment Author, Created Date.

For export, use Views Data Export and export the CSV file.

For import, use the Feeds module + Feeds Comment Processor and import your CSV.

Checkout this Feeds Video Tutorial (this is for nodes, not comments, but it will give you an idea on how feeds with the CSV import works).

--

Exporting MySQL tables approach:

Never done it like this, but if I were you, I would look for all the tables that have the name comment, export those and import.

Note sure if it will work as simply as that, but worth a try.


Change the code in the module from the front end of drupal I have created my custom module. Can i edit my module from the from end of drupal rather then going to backend and editing the module. Is there any module for this purpose?

I'm not sure there is a module for this, but this thread begins to touch on how to create your own module admin page.
How to add module to admin/config page?


How to create a Content Type field that will be only set by query parameters? I'm using Drupal 7. I want to create an Entity Reference field in my Order content type that will be set based on whatever the query parameter node ID is for my parent node. In other words, the user is viewing a table list of parent nodes. The right-most column is a link to "File Order" (as in, create a child node relating to that particular parent node). So the URL that it links to is /node/add/order?nid=[nid of parent].

On the Order node add screen, the "Related Node ID" Entity Reference field should auto-populate based on whatever the nid query parameter is. So the user should not have to worry at all about setting that value ever. How do I do this?

The Prepopulate module appears to be what you're looking for.


In Drupal 7 how do you output array objects to be view able in watchdog error reports? For some reason I couldn't use devel to debug output object arrays. Is there a way to output the array data to watchdog error reporting? This would also solve the issue of having to install or enable another module.

You can use watchdog but the message part should be translatable, so any variables should use placeholders defined in the variables array. Check out format_string to see how these should work.

watchdog(
  'my_module_name',
  'Here is the printed variable: <pre>@placeholder_name</pre>',
  array('@placeholder_name' => print_r( $my_variable, TRUE)),
  WATCHDOG_INFO
);

Also, convention dictates that the first parameter, $type, should be the module name calling watchdog.


How do you do a redirect after a batch job? I'm working on setting up a batch process in Drupal 8 that will gather a bunch of remote information for a collection of entities, cache it, and create a list of the results on its own page. The batch process is kicked off from a form using batch_set().

The batch job runs fine, but I'm not sure how to do the redirect at the end. Since Drupal 8 uses RedirectResponse objects or $this->redirect('user.page'); in a controller and the callback for a batch job doesn't have a return type, I'm not sure what to use to trigger the redirect.

I've tried using the url_options value of the batch job definition but that's not working.

$batch = [
  'title'    => $this->t('job running'),
  'init_message' => $this->t('starting job'),
  'operations'  => $ops,
  'finished' => '\Drupal\my_module\MyClass::finished',
  'url_options' => [
    'query' => [
      'destination' => '/job/results',
    ],
  ],
];

Apparently I needed to ask to see the answer: return a RedirectResponse from the finish callback:

public static function finished($success, $results, $operations) {
  if ($success) {
    // Here we do something meaningful with the results.
    $message = t("@count tasks were done.", array(
      '@count' => count($results),
    ));
    drupal_set_message($message);
  }

  return new RedirectResponse('/job/results');
}

As far as I can tell this is an undocumented behavior.

From the helpful comment below, you can also add batch_redirect on the batch array that's either a string or Url object:

$batch = [
  'title'    => $this->t('job running'),
  'init_message' => $this->t('starting job'),
  'operations'  => $ops,
  'finished' => '\Drupal\my_module\MyClass::finished',
  'batch_redirect' => '/job/results',
];


Easiest method for conditional fields in a form What is the easiest way to get some javascript magic for enabling/disabling form fields based on another field's value? This sounds like something there should be an helper for somewhere, but I can't find it. I am looking for a solution that is not restricted to nodes.

The magic is using the #ahah/#ajax property with form elements, that way you can define what should trigger the modification and what should be modified as a result, plus it integrates seamlessly with jQuery.

This is the important part from the example below:

'#ajax' => array(
    'event' => 'change',
    'callback' => 'myajax_ajax_callback',
    'wrapper' => 'dropdown_second_replace',
),

Here is an example that shows a form-based page with two dropdowns: the list of options in the second dropdown depend on the selection in the first dropdown.

<?php

/**
 * Implementation of hook_menu().
 * Registers a form-based page that you can access at "http://localhost/myajax"
 */
function myajax_menu(){
    return array(
        'myajax' => array(
            'title' => 'A page to test ajax',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('myajax_page'),
            'access arguments' => array('access content'),
        )
    );
}

/**
 * A form with a dropdown whose options are dependent on a
 * choice made in a previous dropdown.
 *
 * On changing the first dropdown, the options in the second are updated.
 */
function myajax_page($form, &$form_state) {
    // Get the list of options to populate the first dropdown.
    $options_first = myajax_first_dropdown_options();

    // If we have a value for the first dropdown from $form_state['values'] we use
    // this both as the default value for the first dropdown and also as a
    // parameter to pass to the function that retrieves the options for the
    // second dropdown.
    $value_dropdown_first = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);

    $form['dropdown_first'] = array(
        '#type' => 'select',
        '#title' => 'First Dropdown',
        '#options' => $options_first,
        '#default_value' => $value_dropdown_first,

        // Bind an ajax callback to the change event (which is the default for the
        // select form type) of the first dropdown. It will replace the second
        // dropdown when rebuilt
        '#ajax' => array(
            // When 'event' occurs, Drupal will perform an ajax request in the
            // background. Usually the default value is sufficient (eg. change for
            // select elements), but valid values include any jQuery event,
            // most notably 'mousedown', 'blur', and 'submit'.
            'event' => 'change',
            'callback' => 'myajax_ajax_callback',
            'wrapper' => 'dropdown_second_replace',
        ),
    );
    $form['dropdown_second'] = array(
        '#type' => 'select',
        '#title' => 'Second Dropdown',
        // The entire enclosing div created here gets replaced when dropdown_first
        // is changed.
        '#prefix' => '
',
        '#suffix' => '
',
        // when the form is rebuilt during ajax processing, the $value_dropdown_first variable
        // will now have the new value and so the options will change
        '#options' => myajax_second_dropdown_options($value_dropdown_first),
        '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
    );
    return $form;
}

/**
 * Selects just the second dropdown to be returned for re-rendering
 *
 * Since the controlling logic for populating the form is in the form builder
 * function, all we do here is select the element and return it to be updated.
 *
 * @return renderable array (the second dropdown)
 */
function myajax_ajax_callback($form, $form_state) {
    return $form['dropdown_second'];
}

/**
 * Helper function to populate the first dropdown. This would normally be
 * pulling data from the database.
 *
 * @return array of options
 */
function myajax_first_dropdown_options() {
    return array(
        'colors' => 'Names of colors',
        'cities' => 'Names of cities',
        'animals' => 'Names of animals',
    );
}

/**
 * Helper function to populate the second dropdown. This would normally be
 * pulling data from the database.
 *
 * @param key. This will determine which set of options is returned.
 *
 * @return array of options
 */
function myajax_second_dropdown_options($key = '') {
    $options = array(
        'colors' => array(
            'red' => 'Red',
            'green' => 'Green',
            'blue' => 'Blue'
        ),
        'cities' => array(
            'paris' => 'Paris, France',
            'tokyo' => 'Tokyo, Japan',
            'newyork' => 'New York, US'
        ),
        'animals' => array(
            'dog' => 'Dog',
            'cat' => 'Cat',
            'bird' => 'Bird'
        ),
    );
    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}


Site upgrade to D7 using drush stuck on the "Run update.php" step I am attempting upgrading my site from D6 to D7 using Drush Site upgrade.

The process gets stuck on the 13th step. This is the last output I get :

    UPGRADE.txt Major Upgrade Step 13

13. Run update.php by visiting http://www.example.com/update.php (replace
    www.example.com with your domain name). This will update the core database
    tables.

    If you are unable to access update.php do the following:

    - Open settings.php with a text editor.

    - Find the line that says: $update_free_access = FALSE;

    - Change it into: $update_free_access = TRUE;

    - Once the upgrade is done, $update_free_access must be reverted to FALSE.

Note that Drush will copy your database and run updatedb on the copy. The
source database remains unchanged.

Drush will automatically do this step now.

Why is this happening and how can I fix it?

You may get the information you need by running drush with the verbose flag: -v or --verbose.


How do I automate shipping calculation? Is it possible to auto calculate shipping for Drupal 7? Is there a way to automate with coupons integrated as well? e.g. Free Shipping coupon.

Currently, if someone were to input a free shipping coupon, these are the necessary steps.

Enter FREESHIPPING code
Apply to order
Update order
Calculate shipping
Select "Free Shipping" instead of "Paid Shipping"

I would like to exclude the last three steps as it's a pretty long process, and some customers might not know to click on Calculate Shipping after clicking Update order. They may think the coupon is broken. Anyway, applying a free shipping code is self explanatory. What I'm looking for is a way to automate the calculate shipping when users enter or change the delivery country  when Apply to Order is clicked on the coupon pane.

Do you have any thought?

I'm still using D6 but I did something similar with jQuery:

Make a mymodule.module file that goes like this:

<?php

function mymodule_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'uc_cart_checkout_form'){

    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');

  }
}

The format of your hook_form_alter may be different in 7, but there are tutorials all over the place for this. The point is that you use drupal_add_js (again, format may differ) to cram some javascript onto only the form with the ID you want - your checkout form.

Make a mymodule.info that goes like this:

name = Re-calculate Shipping
description = Use JavaScript to automatically click the Calculate Shipping button at checkout.
core = 6.x
dependencies[] = uc_quote
package = "Example.com custom modules"

(But you're core is 7.x - copy another module's info file.)
And make a mymodule.js file that goes something like this:

$(document).ready(function(){
      $("#edit-panes-quotes-quote-button").click();
      $("#edit-panes-delivery-copy-address").click();
});

$(document).ready(function(){
   $("#edit-panes-billing-billing-zone").change(function() {
      $("#edit-panes-quotes-quote-button").click();
   });
});

$(document).ready(function(){
   $("#edit-panes-delivery-delivery-zone").change(function() {
      $("#edit-panes-quotes-quote-button").click();
   });
});

Note that this just clicks the "calculate" button for the user, but I'm sure that you can work out how to use jQuery to click more things.

Imagine you have a drop-down select with the attribute id="cram".
In your js file you would use $("#cram") to select anything with the ID "cram":

$("#cram").change(function() {

Sticking .change() on the end triggers anything between the brackets after .change when the #cram element changes, such as when a different fruit / rodent is selected. we're triggering a function here, and it is defined in-situ.

Sticking .click() on the end of a selector clicks the selected element.

Enjoy :)


load Ajax form in another page I have a link in a block and when i click it it brings with ajax a form from another page let's call it contact. In contact page the form uses ajax to submit the data, it works ok. But when i get the form by clicking that link in another page using ajax the form loses the ajax submit. and instead it redirects me to the contact page.

How can i keep the ajax submit even if the form loads with ajax in another page???

It seems, I found some solution, may be not fully drupal-way.

Firstly, we need to load JS libraries, needed for working of ajax submit. This code helps us:

drupal_add_library('system', 'drupal.ajax');
drupal_add_library('system', 'drupal.form');
drupal_add_library('system', 'jquery.form');
drupal_add_library('system', 'druapl.progress');
drupal_add_library('system', 'drupal.textarea');

Nextly, we need to fill JS class Drupal.settings.ajax with data about page elements, which provides ajax behavior. I have not an universal solution, I only stops JS code on breakpoint in misc/ajax.js when running it on page with correct working ajax form. You can see correct values in this part of code:

Drupal.behaviors.AJAX = {
  attach: function (context, settings) {
    // Load all Ajax behaviors specified in the settings.
    for (var base in settings.ajax) {
      if (!$('#' + base + '.ajax-processed').length) {
        var element_settings = settings.ajax[base];

        if (typeof element_settings.selector == 'undefined') {
          element_settings.selector = '#' + base;
        }
        $(element_settings.selector).each(function () {
          element_settings.element = this;
          Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
        });

        $('#' + base).addClass('ajax-processed');
      }
    }

So, in my case resulting JS code, needed to be added into startup javascript, looks like this:

if(Drupal.settings.ajax == undefined){
    Drupal.settings.ajax = {
        'edit-submit': {
            callback: "faqform_ajaxsubmit",
            event: "mousedown",
            keypress: true,
            prevent: 'key',
            submit: {
                _triggering_element_name: "op",
                _triggering_element_value: "Send"
            },
            url: 'system/ajax',
            wrapper:'submit-message'
        }
    };
}

If all done correctly, you form, loaded by ajax, will have correct ajax behavior, in my case - ajax submit.

May be there are more graceful solutions, may be diving deeper into code will help you to find them.

So, here is much more graceful solution!

After some analyses of steps, maked above, I decided, that only thing we need to make ajax form, loaded by ajax, to work is fill javascript  Drupal.settings array with correct data, describing forb behavior.
In the above example we made it by hands, with hardcode, whitch is not true. Obviously, somewhere in drupal code it work does automatically.
I found this place. It is function ajax_pre_render_element in the ajax.inc. It gives array of any form element with ajax property and appends to it additional parameters, which will be converted to JS code and added to Drupal.settings array later. Exactly thing, that we need.

Here is my code now:

function anyform_block_info()
{
    //standart form for displaying to user
    $blocks['any_form'] = array(
        'info' => t('Any form'),
        'status' => true,
        'region' => 'content',
        'weight' => 99,
        'visibility' => 1
    );
    //hidden 'form' needed to generate and load ajax behavior settings before form loading
    $blocks['faq_form_hidden'] = array(
        'info' => t('Any fake form'),
        'status' => true,
        'region' => 'footer', //I thing, it will be better place it in footer^ in my case content is ajaxed
        'weight' => 99,
        'visibility' => 1
    );
    return $blocks;
}

function anyform_block_view($delta)
{
    switch ($delta) {
        case 'faq_form':
            $block['content'] = drupal_get_form('anyform'); //standart form
            return $block;
        case 'faq_form_hidden':
            $block['content'] = anyform_get_hidden_form(); //fake form
            return $block;
        break;
    }
}

function anyform_get_hidden_form()
{
    $form = drupal_get_form('faqform'); //give our original form
    $form = ajax_pre_render_element($form['submit']); //create settings for element with #ajax property (don't pass whole form as argument - not works)

    //makes fake form with hidden element in footer, but with correct array with settings for ajax behavior
    $fakeform['fakeform'] = array(
        '#type'=>'markup',
        '#markup'=>'

',
        '#attached'=>$form['#attached'], //our magical array
    );

    return $fakeform;
}

So, I hope, it will solve most of your problems with drupal ajax-loaded forms. For me this solution works without any problems, and I going sleep being happy =^_^=
Good luck!


how to get webform title and category with no submissions in view or hook? I have a survey form created with webform module.i have to display all survey form title with submissions and without submissions with webform category on home page.but it displaying only submitted survey forms title.how can i display webform title with zero submission in drupal8?

use below code as a function in your module file and call it on your custom block.

  function module_name_webformtitle(){
    $query = Drupal::service('entity.query')->get('webform');
    $query->condition('category', 'survey_name');//your survey name
    $entity_ids = $query->execute();
    $webform_id=array();
     foreach($entity_ids as $webid){
       $webform_id[]=$webid;
     }
    $webform = Webform::loadMultiple($webform_id);
     foreach($webform as $webforms){
        $webformtitle=$webforms->get('title');
    }
  }


How to create a taxonomy terms "skills" with level "low", "medium", "high" I'm trying to create a field that allows you to add your skill from a select list, and the level of your skill.

i.e.
skill football, level medium.

I may create the taxonomy in this way
Football
-Low
-Medium
-High
and the use hierarchical taxonomy but it means that I need to add the level per each term.

Is there a way to attach a vocabulary to another vocabulary? in this way I may create a vocabulary skills with all the skills and one vocabulary level with 3 terms.
Is there a module or a better technique?

Thanks in advance

Without knowing how you're planning to use this in a larger context, here's what I would do:

Create a vocabulary (or possibly just a plain text field with a select list) for "skill"
Create a second field with a dropdown list for skill level (I probably wouldn't use a taxonomy for this).
Make the second field dependent on the first, per this Stackoverflow question about fieldsets and conditions


Drush make Distribution throwing errors: exec() unable to fork bootstrap.inc:636 I'm using DrupalPro VM and trying to do a drush make on the distribution One Page CV.

I build the distribution:

sudo drush make onepagecv.make -y

But I'm getting the following errors during the make and crashes my terminal. I logged the install process and it seems to stop at the following.

Here is the log:

This is probably related to some resources limit or temporary glitch. So first try to restart your Apache.

If this won't help, make sure that you've necessary requirements to run drush (which is either curl or wget).

Otherwise it could be some resource limitation on your environment. E.g. check for ulimit -a or kern.maxprocs.

If there is still problem, please add -v for verbose mode or -d for debug messages for drush, you could more easily track the issue.


Page title from the exposed filter term I have a view that shows all the contents of my site, with an exposed filter, that allows to filter these contents according to different taxonomy terms.

I would like the taxonomy term chosen via the exposed filter to appear as a page title.

Example:

I type in my search form: drupal,
I arrive on a page with the title "drupal" and presenting all the contents having for term "drupal".

I tried different options, especially with the contextual filter, but without success.

For example, i tried this solution (1) or this solution (2), but either I do not get any title (1), or I get many errors that make the site crash (2), of type

  Warning : Illegal string offset 'value' dans Drupal\views\Plugin\views\area\Text->preQuery() ((...)/core/modules/views/src/Plugin/views/area/Text.php ligne 50)

Help would be much appreciated

Edit:

My views configuration (maybe views can't find the id in the url? The url of my page: : mysite/myviews?tid=term+taxonomy+(ID) )

To use term names in a Contextual filter in Content views you need to add the Relationship to the taxonomy reference field you have in your content. Then you'll be able to add Taxonomy term: Name Contextual filter that will take names as arguments, and not term ID numbers.

You will be able to override the title for the Name contextual the same way, only use the corresponding token for the taxonomy name. You can look it up under Replacement patterns.

You can find more details about how to set up the Name contextual here in a section of this answer: Create view with path relative to taxonomy term


project version/revision module I'm in search of a module (or technique) to keep track of the software/release version that a Drupal installation is running. I am not talking about the Drupal version running the site (e.g 7.12) but of the implemented site itself, exactly like any Stack Exchange site does on the footer (currently: rev 2012.4.5.2127).

I need a structured way to keep track of this data (so a plain text block on the footer will not do) because I'll need to access this information from other systems as well.

Currently I've solved it by using a persistent variable that I handle with Drush.

# Set it.
drush vset --always-set release "1.0.4"

# Get it.
drush vget release

Is there another (probably better) way of handling this?

As part of your build script and/or revision control checkin script, write out a version number to constant in an include file.  Write a custom module that does something with this include file, such as make a block that prints it out, stuffs it into $conf expose the value via webservice, etc.  You could also do this directly to settings.php, too, if you just need a variable.


Drupal 7 - Multi Step Registration with save on end I have been looking through some tutorials, but couldn't find what i wanted to accomplish.

The thing i can't find in any tutorial/resource is the ability to save users registration data on the last step.

What i want to accomplish is to display a registration page for users, and the user goes through 3 steps.

Step 1 - Registration info
Step 2 - Payment Info
Step 3 - Save and show custom message

Can some one post some good resource, where it shows how to do this.. Preferably with explanation so i can learn from it.

The tutorials i followed so far were saving after the first submit.

Thanks in advance

As a clue, build a module and insert your form inside it, then set your form ['rebuilt'] attribute to TRUE in this way your form is saved in ['storage'] attribute in every step and you can get them via $Form_state variable.


Why isn't this module library loaded? I am using the following code.

wk_elastic.info.yml

name: Blablabla
description: Blablabla
package: BlaBlaBla

type: module
core: 8.x

libraries:
  - wk_elastic/list-js

dependencies:
  - block

wk_elastic.libraries.yml

list-js:
  js:
    js/list.js: {}
  dependencies:
    - core/jquery

wk_elastic.module

function wk_elastic_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'wk_elastic/list-js';
}

The library is not being loaded.

What can I do to fix this?

Switch the active theme to a core theme. If the library loads now then make sure that your custom theme has <js-bottom-placeholder token="{{ placeholder_token }}"> and  <js-placeholder token="{{ placeholder_token }}"> in the html.html.twig template.

Another pitfall is an incorrect reference to the library. Although it does not apply to the original question I'll state it anyway because it solved the problem for me. If your my_module.libraries.yml looks like this

my_libraries.my-library:
  js: ...

then you have to use

['#attached']['library'][] = ['my_module/my_libraries.my-library']

instead of

['#attached']['library'][] = ['my_libraries.my-library']


how to access drupal site using domain containing host ip address as prefix My drupal site works in local domain dev.example.com (which is configured as a virtual host).

For some reason, now I need to access the site using exactly the following address:

http://192.168.3.149/dev.example.com

where 192.168.3.149 is the IP address of the local host where the site resides.

When this address is entered, I am redirected to http://192.168.3.149/install.php. Looks like Drupal treats this as a new domain.

How to tell Drupal to treat these two domains identically, i.e. treat http://192.168.3.149/dev.example.com as an alias of http://dev.example.com ?

It sounds like your site's settings might be in a multisite folder like /sites/dev.example.com/. When you aren't visiting via the hostname it will fall back to the settings in /sites/default/—check that those values are correct.