Taxonomy else if not working my code not working. I'm trying to get custom breadcrumbs if user is different taxonomy vocabulary category page. if elseif's not working, but I don't know why..

Example: If I go to taxonomy term page that vocabulary id is 2, breadcrumbs is:

Page 1 > Page 1 > Term name

and vocabulary id 2, breadcrumb looks like this:

Page 2 > Page 2 > Term name

and if ID is not defined it shows default breadcrumbs ( else )..

It shows page 1 and else breadcrumbs but else if statement not working..

Is that code correct or what?

 /*
 * Taxonomy term callback page
 */

function taxonomy_taxonomy_term_page($term_id) {
$term = taxonomy_term_load($term_id);
$html = '';
$breadcrumb = array();
$parents = taxonomy_get_parents($term->tid);
$desired_vocab_1 = 1; // Vocabulary ID
$desired_vocab_2 = 2; // Vocabulary ID
$desired_vocab_3 = 3; // Vocabulary ID

if(count($parents) > 0) {

    $show_sub_cat = false;
    $list = get_legal_articles($term->tid);
    foreach($parents as $item)
        $_parent = $item;

    $breadcrumb[] = l(t('Default page'), 'Default page');
    $breadcrumb[] = l($_parent->name, 'taxonomy/term/'.$_parent->tid);

    $html =  theme('category_details', array('term' => $term, 'list' => $list, 'is_sub_cat' => $show_sub_cat));

 } else {

 if (((arg(0) == 'taxonomy')
 && (arg(1) == 'term')
 && is_numeric(arg(2))
 && ($term = taxonomy_term_load(arg(2)))
 && ($term->vid == $desired_vocab_1))) {

$breadcrumb[] = l(t('Page 1'), 'Page 1');

$childs = taxonomy_get_children($term->tid);

$html = theme('parent_category_details', array('term' => $term, 'list' => $childs));

 } elseif (((arg(0) == 'taxonomy')
  && (arg(1) == 'term')
  && is_numeric(arg(2))
  && ($term = taxonomy_term_load(arg(2)))
  && ($term->vid == $desired_vocab_2))) {

$breadcrumb[] = l(t('Page 2'), 'Page 2');
$breadcrumb[] = l(t('Page 2.1'), 'Page 2.1');

$childs = taxonomy_get_children($term->tid);

$html = theme('private_category_details', array('term' => $term, 'list' => $childs));

} else {

$breadcrumb[] = l(t('Page 3'), 'Page 3');
$breadcrumb[] = l(t('Page 3.1'), 'Page 3.1');

$childs = taxonomy_get_children($term->tid);

$html = theme('private_category_details', array('term' => $term, 'list' => $childs));

}

// Set Breadcrumbs
drupal_set_breadcrumb($breadcrumb);
drupal_set_title($term->name);

return $html;
}

In your code the html of 'Default page' is never returned. I have refactored it a little bit to make it cleaner and easier to maintain.

/*
 * Taxonomy term callback page
 */
function taxonomy_taxonomy_term_page($term_id) {
  $term = taxonomy_term_load($term_id);
  $breadcrumb = array();
  $parents = taxonomy_get_parents($term->tid);
  // Vocabulary IDs
  $desired_vocab_1 = 1;
  $desired_vocab_2 = 2;
  $desired_vocab_3 = 3;

  if (count($parents) > 0) {
    $show_sub_cat = false;
    $list = get_legal_articles($term->tid);

    foreach ($parents as $item) {
      $_parent = $item;
    }

    $breadcrumb[] = l(t('Default page'), 'Default page');
    $breadcrumb[] = l($_parent->name, 'taxonomy/term/' . $_parent->tid);
    $html = theme('category_details', array('term' => $term, 'list' => $list, 'is_sub_cat' => $show_sub_cat));
  }
  else if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));

    switch ($term->vid) {
      case $desired_vocab_1:
        $breadcrumb[] = l(t('Page 1'), 'Page 1');
        break;
      case $desired_vocab_2:
        $breadcrumb[] = l(t('Page 2'), 'Page 2');
        $breadcrumb[] = l(t('Page 2.1'), 'Page 2.1');
        break;
      case $desired_vocab_3:
        $breadcrumb[] = l(t('Page 3'), 'Page 3');
        $breadcrumb[] = l(t('Page 3.1'), 'Page 3.1');
        break;
      default:
        $breadcrumb[] = l(t('Default page'), 'Default page');
    }

    $childs = taxonomy_get_children($term->tid);
    $html = theme('private_category_details', array('term' => $term, 'list' => $childs));

    drupal_set_title($term->name);
  }

  // Set Breadcrumbs
  drupal_set_breadcrumb($breadcrumb);

  return $html;
}


Drupal 8 separate pages for separate taxonomy terms I have two taxonomies. I want different page templates for each taxonomy term page. Lets call the taxonomies as taxonomy_one and taxonomy_two.

When I go to taxonomy term twig debug suggests following names:

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

Is there any way to override the taxonomy term page template by adding twig file such as:

page--taxonomy-one--term.html.twig?

Finally I found answer and posting it here in case someone needs it.

To do this you need to create the following function in your your_template.theme file:

use Drupal\taxonomy\Entity\Term;

function stravel_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()
      ->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()
      ->getRawParameter('taxonomy_term')
  ) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

This allows you to create page templates such as page--taxonomy--mytaxonomy.html.twig to display single term data. Now you can easily add regions, blocks and views as usual.

However,
to display data related to the relevant term, you need to add contextual filters.


How can I reuse translations from other contexts? I know that in Drupal 7, contexts are used to provide multiple translations for the different meanings of the same string.

This works great for sentences that do have different meanings depending on the context. But for most of the cases, this means that I'll need to translate the same string twice or more times.

Is there a way to automatically reuse the translations from other contexts, when it's not already translated for the real context of the string?

If not, what is the best way to automatically import all the translations from one context to another?

The problem is that the set of i18n modules set the context for strings automatically.  For instance, suppose I reuse a taxonomy reference field in many content types.  The vocabulary name and each of the field labels are exactly the same and have the same set of translations, but each one must be translated entirely independently.  That field may also show up as an exposed filter in views and I have to translate it independently in each view as well.

Now suppose I mistranslated the vocabulary name for one of the languages and need to fix it.  I have to change it everywhere, which is a ridiculously tedious process.

It would be REALLY nice to be able to translate a particular string such as this once and have it automatically update everywhere that string appears.  I have been able to hack it by manipulating the locales_target table in the database directly, but that is definitely not a good solution.


Commerce checkout, check if checkbox is checked I added a field to my commerce checkout form:

mymodule_form_alter(..) {
 ...
 if($form_id ="commerce_checkout_form") {
 $form['thisfield'] = array(
  '#type' => 'fieldset',
  '#title' => t('Contact settings'),
  '#weight' => 5,
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
 );

 $form['thisfield']['checkbox']= array (
   '#type' => 'checkboxes',
   '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
   '#title' => t('What standardized tests did you take?'),
   '#required' => TRUE,
 ),
 ....
 }
}

Now the form may not go to the next step if the checkbox is not checked. If i press the sumbit button now, i go to the next step with the error displayed that the field is requierd. So  the error message appears, but the form still continues to the next step.

Now i don't really know how to keep the commerce form on the same step if the checkbox is not checked.

You shouldn't add the field directly to the checkout form, but rather create a new checkout pane and add the field to that.

e.g:

/**
 * Implements hook_commerce_checkout_pane_info
 */
function MODULE_commerce_checkout_pane_info() {
  $checkout_panes = array();

  $checkout_panes['contact_settings'] = array(
    'title' => t('Contact settings'),
    'file' => 'includes/commerce_checkout.checkout_pane.inc',
    'base' => 'MODULE_checkout_contact_settings_pane',
    'page' => 'checkout',
    'callbacks' => array('checkout_form_validate' => 'MODULE_checkout_contact_settings_pane_validate')
    'fieldset' => TRUE,
  );

  return $checkout_panes;
}

Put your form builder in includes/commerce_checkout.checkout_pane.inc > MODULE_checkout_contact_settings_pane

You can then use the Commerce API to validate your checkout form in

/**
 * Checkout pane validation for contact_settings
 */
function MODULE_checkout_contact_settings_pane_validate(&$form, &$form_state, $checkout_pane, $order) {

  // Do some validation tests here... omitted for brevity.
  if (empty($form_state['values']['thisfield'])) {
    drupal_set_message(t('Some validation error message'), 'warning');
    return FALSE;
  }

  return TRUE;

}

More info: hook_commerce_checkout_pane_info


Detect when a user clicks file download link I Have a view that outputs nodes, and also a link to download files that are attached to these nodes. I'd like to know when a user clicks one of these links, so that I can log the event.

All attached files are files in drupal's public file directory, inside a directory at sites/default/files

Is there good approach for detecting a click or file download in this case?

Module Track da files (despite its goofy name) tracks both public and private files. Here is a quote about it (from the module's project page):

... enables the possibility to track how much visitors are viewing files on site.
Every link to a file can be configured to be tracked. Then, a record is registered each time a visitor access the file from this specific link.


Determine if node is new I am inserting nodes from an external application into Drupal (7.x). I've taken care of the node_revision table and other tables needed by Drupal to see the node. However I have pathauto installed and it does not recognize the node as new as per this link. So my question is, how does Drupal/Pathauto determine if a node is new or not?

Obviously I can't use the $node->is_new property, cause I am doing the inserts from a Zend application. I just want Pathauto to check the Automatic alias checkbox by default.

Pathauto reacts on node save, which doesn't happen when you insert directly via SQL. Pass data from your external application to a custom hook_menu entry, assemble the node from $_GET-data, and run node_save($node), instead of inserting it directly.

Second option, if to enable Services, which allows you to pass data in as json, and have the nodes created that way.

I belive both ways will properly trigger Core hooks, so that pathauto will be called.


List of users who visited node Is there any module available, with a functionality to show list of users who have visited certain nodes?

I've searched for module like this but haven't found anything like this.

I think this Node view count contrib module helps you.

Node view count

  Node View Count module allows to count node views. Unlike statistics
  module, this module records each view of node with user uid and
  timestamp. So now you can know how many times a user viewed node by
  day, week, month and etc.


How to render links to youtube as video I'd like to know, how could I render links to video sites like youtube and vimeo as a video, the way Facebook does when a user simply pastes a link.

The other modules or solutions I've found involved embedding videos as a field requiring users to go through a process like the one from Embeded Media Field module does. The closest one is the Video Filter module, but it still more complicated that Facebook.

I'd like this feature over because I'm implementing this for a forum and I'd like to make it as simple and familiar (since everyone uses Facebook) as possible.

I guess the simplest solution would be a normal textfield with a youtube-specific formatter. A formatter is some code that takes the value of a certain field and uses it to generate a chunk of html, displaying the field on your page the way you want. The downside of this solution is that it will add a separate field to your form.

A quick search found two sandboxes with youtube field formatters:

https://drupal.org/sandbox/Hydra/1404188
https://drupal.org/sandbox/double/1795842

Unfortunately I could't find an oficially released, stable module.

If you want complete control over your formatter, here's a tutorial how to create your own: Creating Custom Formatters with the Field API . In the comments, some commenters even say it helped them create a youtube field formatter.

[Update]

I just noticed the Googtube module, it seems to be exactly what you're looking for: like Video Filter module, but parsing regular YouTube URL's as embedded video's.


How to create a view that automatically shows all fields as a table, even if new ones are added to the entity? I need to create a table view that shows all of the user accounts on the site and their fields. The client has the ability to add new fields to the user entity but I do not want to make them go into the view to add the field as well. Is there a way to have views just output all fields? I know I can change the display as an entity and select a view mode but I need this to be in table format.

I've run into exactly the same use-case. So far my intuition has been to create a fieldset to which the client can add fields, and develop a new Views plugin to add a whole fieldset to a view using every field's defaults. (The challenge here is that each field has different parameters to configure when you add them to a view.)


Execute custom php to manage click2call I need to POST to a url with php code in order to make a phone call. This is an example of javascript:

<script>
        function callme() {
            var XHR = new XMLHttpRequest();
            XHR.addEventListener('readystatechange', function() {
                if (XHR.readyState == 4 && XHR.status == 200) {
                    document.getElementById("result").innerHTML = XHR.responseText;
                } else {
                    document.getElementById("result").innerHTML = "ha ocurrido un error: " + XHR.responseText
                }
            });

            var FD  = new FormData();
            FD.append('number', document.getElementById("number").value);
            XHR.open('POST', 'doC2c.php');
            document.getElementById("result").innerHTML = "calling ..."
            XHR.send(FD);
        }
    </script>

And the doC2c.php file must be:

<?php

$apikey = ""; //API KEY MUST BE PUT HERE GOT FROM DB
$origin = ""; //ORIGIN EXT MUST BE PUT HERE OR GET FROM SOMEWHERE
if ($apikey == "") {
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
    echo "APIKEY MISSING";
    die();
} else if ($origin == "") {
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
    echo "ORIGIN MISSING";
    die();
} else {
    $opts = array(
       'http' => array(
           'method' => "GET",
           'header' => "Content-type: application/json\n"
                       ."X-Api-Key: ".$apikey,
       )
    );

    $context = stream_context_create($opts);
    $response = file_get_contents("https://....../api/originatecall/".$origin."/".$_POST['number'], false, $context);

    //echo $response;
    echo "CALLING...";
}
?>

I would like to make a D8 module that create a URL I could POST to execute the php code, but I want to have Drupal API to query de DB and so on. I know how to make a module with a form and a route to show it, but I don't know how assign a route to a php code file.

A route is a path which is defined for Drupal to return some sort of
  content on

source: Routing system overview

You can think of it like this, a route creates a url that displays a page. This route has a controller which executes the function/method that is in the controller class.

my_module/my_module.routing.yml

my_module.content:
  path: '/fetch'
  defaults:
    _controller: '\Drupal\my_module\Controller\DoC2cController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

In the example above when you go to /fetch it will execute the content() method that is inside the DoC2cController class php file. This method must return a render array.

For more in depth info read Structure of routes.

my_module/src/Controller/DoC2cController.php

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\drupal_set_message;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Defines HelloController class.
 */
class DoC2cController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   *   Return markup array.
   */
  public function content() {

    $apikey = ""; //API KEY MUST BE PUT HERE GOT FROM DB
    $origin = ""; //ORIGIN EXT MUST BE PUT HERE OR GET FROM SOMEWHERE
    if ($apikey == "") {
        drupal_set_message(t('APIKEY MISSING'), 'error');
        throw new NotFoundHttpException();
    } else if ($origin == "") {
        drupal_set_message(t('ORIGIN MISSING'), 'error');
        throw new NotFoundHttpException();
    } else {
        $opts = array(
           'http' => array(
               'method' => "GET",
               'header' => "Content-type: application/json\n"
                           ."X-Api-Key: ".$apikey,
           )
        );

        $context = stream_context_create($opts);
        $response = file_get_contents("https://....../api/originatecall/".$origin."/".$_POST['number'], false, $context);

        //echo $response;
        $response = "CALLING...";
    }

    // Make response string translatable
    $translatable_response = new TranslatableMarkup("@reponse", [
      '@response' => $response,
    ]);

    return [
      '#type' => 'markup',
      '#markup' => $translatable_response,
    ];
  }

}


How do I use entity_metadata_wrapper to create a node and at the same time multiple node references? I have an XML response from a REST api call that returns an object with an array of sub-objects contained in it.

I need to create a node with all the properties of the top level object and node references to nodes created from the sub-objects. I probably will make them nodes but I would prefer to use the Entity API instead of the Node API even if they are nodes.

<toplevel>
  <prop1></prop1>
  <prop2></prop2>
  <array_of_sub_objects>
    <sub1>
      <sub_prop1></sub_prop1>
      <sub_prop2></sub_prop2>
      <sub_prop3></sub_prop3>
    </sub1>
    <sub2>
      <sub_prop1></sub_prop1>
      <sub_prop2></sub_prop2>
      <sub_prop3></sub_prop3>
    </sub2>
  <array_of_sub_objects>
</toplevel>

Here is an example of 3 objects with 2 contained inside the 1. I need to create 3 nodes or entities with an entity reference of the 2 sub-objects to the toplevel object. How do I use the Entity API to programmatically do this?

You should probably look at Migrate module. IT has support to import xml data into nodes.


Overriding a view with views_pre_render. How to be more specific? I have a view which has a page display and a block display. I'm trying to write some custom code that takes one of the fields from the block and uses it to amend the title of the page. So far, here's my code:

function custommodule_views_pre_render(&$view) {
  if ($view->name == 'topic_page') {
    $title = $view->result[0]->node_title;
    drupal_set_title($title);
  }

I managed to pinpoint the field I need by looking through the returned views result array. The problem is that there are multiple results arrays returned - one for each display, so there's two $view->result[0] in this view. The code above only happens to work for me because the one for the block is returned after the one for the page.

So in the interests of making sure the code doesn't break should another display be added to the view, and therefore having that display's result[0]->node_title become the one that overrides the page title, how do I increase the accuracy here? How do I pinpoint my block display?

(I realise there are plenty of contrib modules that can do this for me, but I'd really like to do this with custom code as something of a learning exercise.)

You should be able to put in logic like

if ($view->name == 'topic_page' && $view->current_display == 'MACHINENAMEOFBLOCKDISPLAY') {
  // do whatever you want whenever Views is crafting up this view and display
}

which will further filter to a specific View as well as display.


Cannot modify header information following page not found error I see a lot of these in my dblog;

  Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/includes/bootstrap.inc:1368) in drupal_send_headers() (line 1220 of /var/www/html/includes/bootstrap.inc).

or

  Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/includes/common.inc:2700) in drupal_send_headers() (line 1220 of /var/www/html/includes/bootstrap.inc).

and

  Warning: ini_set(): Cannot change zlib.output_compression - headers already sent in drupal_serve_page_from_cache() (line 1357 of /var/www/html/includes/bootstrap.inc).

This happens after a page not found error of a comment that had been deleted.
Even though this does not generate any problem, having them filling up my dblog annoys me. Any help will be appreciated.

Thank you

Edit: Fixed it temporarily by adding a redirect.

Please note that there are a lot of things that can cause this, and it's very hard to say what goes wrong depending on your system. But the following seems the most plausible:

The page is deleted, so drupal immediately serves a cached 404 page (with 404 header). Some other module which perhaps invokes a wrong hook, then tries to alter the output or output header. Which it can't because the page is already compiled.

You could try to read the headers of a regular page and one of a 404 page to find out what header is missing (and thus what module might be causing it) I use Fiddler to post such requests and read the server's response, but there are plenty of other tools.
You could also try to read the issue queues of the modules you use, try to find if someone else ran into this problem earlier.

As a last resort you could start disabling your modules and try to find when it stops. Or use 'find in files' to see if there are modules calling 'drupal_send_headers'.

But then again, it might not even be a module...

Please note that a theme is also capable of editing output, and thus might be causing this.


Why is this code using the global $user variable? This is the code used by someone:

/**
 * @Implement of hook_comment()
 */
function mycaptcha_comment(&$comment, $op) {
  global $user;
  switch ($op) {
    case 'insert':
      if (isset($_SESSION['mycaptcha_ask_key'])) {
        // unset the information
        unset($_SESSION['mycaptcha_ask_key']);
      }
    break;
    case 'validate':
      if ($comment['mycaptcha_ask']) {
        // validate the information
        mycaptcha_ask_form_validate($comment['mycaptcha_ask']);
      }
    break;
  }
}

On the above code, why is he using global $user;? I see he doesn't use $user in his code.

The code is not really using the global $user variable. Probably, the code was first using it, and that line has been left; it could also be the code using it was moved in mycaptcha_ask_form_validate().

As that line is just a variable declaration, there is no problem in leaving it, even if I generally remove it.


Interface translation conflict / same EN word, different translations I've created a custom module, that uses templates with hard coded strings. I've created the .pot and .po files and included them my module's YML file. The Twig tempatles translate those strings using the |t operator. This works fine.

Now I've run into a problem: My module offers button to book an accommodation, which clashes with Drupal's book (to read) module. In the german translation those two words are completely different.

I've got two questions:

How to I provide a translation for the book verb in my module, in a way that it doesn't clash with the book module.
How to I use the tell Twig to use the correct book string from my module?

E.g. this template code
First I want to {{ 'book'|t('context_accomodation') }} a hotel room and when I arrive I want to read a {{ 'book'|t('context_reading') }}

should render in english
First I want to book a hotel room and when I arrive I want to read a book

and should render in german
First I want to buchen a hotel room and when I arrive I want to read a Buch

Drupal does have an answer to this problem, at least if it's your own code where you need to make that distinction. It's called context.

In the PO file, add a msgctxt line

# an explanatory comment line for your translator
msgctxt "Accomodation"
msgid "book"
msgstr "buchen"

In PHP, it works like this:

<?php
t('book', [], ['context' => 'Accomodation']);
?>

In twig, it should go like this:

{{ 'book'|t({}, {'context': 'Accomodation'}) }}

The problem with this approach is that the developer needs to be aware that a certain word might have a multiple context specific translations in another language that he most likely doesn't know. But for your specific scenario, it should work fine.


Gmap Location in views - exposed filter by distance/proximity and post code I am currently working with Drupal 7 and Location 7.x-3.4 module
I have created a view, choose the Gmap format, and added the post code and distance field in filter section, so that the visitors are able to search for the locations they want.
Gmap Settings:

Data Source = Location.module
Marker handling = Use single marker type

Here is my configuration for the Location: Distance / Proximity :

Expose this filter to visitors, to allow them to change it = 1
Filter type to expose = Distance / Proximity
Operator = Proximity (Circular)
Postal code = Blank
Distance = Blank
Origin = Postal Code (assume default country)
Filter identifier = distance

After saving the changes, the result is not changing. Is anyone knows what's wrong with my configuration above? Please help..

It's a bit hard to say for sure but my guess is that you have missed a step when installing the location module.

For post code proximity searching the location module uses a database of postcodes and their coordinates to convert the postcode to the lat/lon coordinates that are then used to calculate whether other locations fall in the request distance.

See installation step 6 in the INSTALL.txt file of the location module.

  (Optional) Import a postal codes database for the countries served by your    website, to support proximity searches and other useful
  features. Postal    code databases may be found in the "databases/"
  sub-directory of the    Location module directory. The files are in
  the format of zipcodes.CC.mysql,    where CC is a two-letter country
  code such as 'us' or 'de'.

  Note: If your site is using table prefixes, you will need to adjust
  for this    manually, by opening the file in a text editor and
  replacing 'zipcodes' with    'prefix_zipcodes' throughout.

  To import the files from the command line, enter the following:

  cd sites/SITENAME/modules/location
   mysql -u username -p database-name < database/zipcodes.us.mysql

Note that this proximity functionality may not work for some countries if the data is not available.


How to use uploaded images from an image gallery in an article? Maybe I am not searching for the correct terms, but I am trying to use an image gallery and be able to reference the images in that gallery from an article.  I want to be able to upload the images one time, but then have specific images to be shown in the article, either as a "sub-gallery" or just inline with the text, depending on the context of the article.

Is it just as simple as creating an image tag and setting the source to the relative address inside the drupal site?  Or is there a better way to accomplish what I am trying to do?

The module Entity reference can do the job.

  Entity reference provides a field type that can reference arbitrary
  entities

...ie your gallery files!

With this module you can add an "Entity Reference Field" related to your gallery files to the Article Content Type.

Then, for each Article, you can add 1 or more images among those already loaded.


Create two dynamic select lists Hi,
I want to create a drupal view that display as the uploaded image. There are two select list. First select list is static. According to the selected category sub category should by populated. All categories and subcategories are stored as taxonomy term. Any idea would be appeciated.

You can take a look at the Taxonomy menu module. Some details about it (from its project page):

  Transforms your taxonomy vocabularies into menus with ease!

  Custom Menu per vocabulary
  Uses the default taxonomy term path or custom paths
  Integrate with Views
  Integrate with Pathauto: use URL/path aliases
  Does not interfere with other menu modules

Also look at this post:

How do I direct link a view to a taxonomy menu?


Return value on a submit handler Below is a hook from the LinkedIn Integration module.

Then I have a hook form alter in my module and it's all setup and ready to go to call a submit handler.

When the user goes to authorize LinkedIn, and come back, I want to fire some my code.

The question is I don't know what states or values are after it comes back. I tried this

function my_module_form_link($form,$form_state, $uid)
{
  dpm($form_state['values']);
}

but it did not return anything

function linkedin_user_enable_form($form, $form_state, $uid) {
  $form = array();
  $form['#user'] = $uid;
  $form['#action'] = url('linkedin/token/' . $uid);
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Go to LinkedIn'),
    '#suffix' => '
' . t('You will be taken to the LinkedIn website in order to complete the process.') . '
',
  );
  return $form;
}

Looking at the linkedin module source code,  there's some ways that can run code on the way back (but only when are logging-in, it seems).

When they are logging-in:

hook_linkedin_external_login: if they don't already have an account and will be asked to register.
hook_linkedin_tie_external_login: if they already have an account and will be logged-in using that account.

When they are associating a linkedin account:

I do not see any hooks or any stable way of running code in this case.

Here's an example on how to hook into hook_linkedin_external_login:

In your mymodule.module file:

function mymodule_linkedin_external_login($uid) {
  // do something
}

But you'll have to be careful since linkedin_auth_linkedin_external_login does a drupal_goto() so you'll have to have your module hook called first, so that your function doesn't get skipped. See how drupal decide execution order of same hook in different modules?


D8 How to create custom configurational form translatable? I am new to Drupal 8 Custom Translation.
I am working on a custom module with a backend form from where user can add some textual inputs.

The Site is multilingual, so I need to have this backend form translatable.

May I know the steps or any links from where I can get an idea where to start for translatable configuration form/page where user can add textual inputs for each languages.

Thanks in advance.

You need a schema yaml file in the module folder /config/schema to make configuration forms translatable:

  What are schema files used for?

    The primary use case schema files were introduced for is
  multilingual support. We need to have a tool to identify all
  translatable strings in your shipped configuration so when you ship
  with your own settings as well as default Views, additional user
  roles, menu items, etc. we can offer those up for translation as part
  of your module/theme release on http://localize.drupal.org. The
  nesting levels and types would be enough for this use case.
    We also use schemas to provide actual translation forms for
  configuration based on your data. This use case is where types gain
  more importance and labels become crucial. The core Configuration
  translation module uses schemas to generate translation forms and
  save translations. The two most important built-in translatable types
  are 'label' for one-line text input and 'text' for multiline text
  input.

Source: https://www.drupal.org/node/1905070


How do I programmatically get the link for a webform submission? I have managed to create a table of webform submissions of a particular type, thanks to the answer from a question posted here.  What I would like to do now is add a link for each webform submission, and I can't figure out how.

I tried looking through the API, and found a toUrl function, but I don't understand how to use it to get the link for each webform submission.  Once I have the link, I would like to combine it with the rest of its info in submission_data[] for display in the table.

Thanks in advance!

$query = \Drupal::entityQuery('webform_submission')
  ->condition('webform_id', 'sign_up');
$result = $query->execute(); // Gives me IDs associated with the "sign_up" webform.

$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);
$submission_data = array();
foreach ($submissions as $submission) {
  $submission_data[] = $submission->getData();
}
// $submission_data now contains all the submissions from "sign_up" webform.

How do I add a link to the webform submission? When I look through submission_data[] it doesn't contain the ID of the webform submission

Webform submissions are content entities, you can use any method defined in \Drupal\Core\Entity\EntityInterface including…

$submission->toUrl();
$submission->toLink();


Loading more content in mobile (Slider) - Views core module I am using the view core module to view the featured articles, latest articles and more stuff in my project, it is rendering 3 articles and the load more button to load more content using ajax, This is working great in Desktop, However in Mobile, the load more button doesn't exist (As per website design) and the articles are displayed in a slider. I am hiding load more button using CSS, the user has no way of loading more content!!

1st Approach: Load more content using ajax.

How can I automatically load more content after the user slides 2 or more slides ? I can easily detect when the user slides to the 2nd slide using jquery but how can I load more slides dynamically using ajax? Do I have to load more content by myself or does Drupal 8 have a way of doing this?

2nd Approach: Make 2 blocks, one for desktop, one for mobile.

I thought of doing 2 separate views blocks:

Desktop view block: 3 items and load more button

Mobile view block: all items

But this doesn't feel right, and I will have to toggle between them using CSS which means the content will be fetched by network anyway, So this approach is not correct.

I could not find how to hide or show a block depending on view width without CSS.

If there is another approach please tell me.

Maybe can you detect with jQuery that the user's screen is near the bottom of the page (or with your 1st approach), then you use an .click() on your invisible "load more" button ? In that way, user will scroll and more content will appear each time ?


how to set custom permission to custom menu access? I  am trying to create student management system in which i have been created custom 'registration form', for registering to website then i have created 'list of registered students' menu to show registered students.I want to set permissions such that admin can edit registration form and authenticated user can only see 'registration form',admin can see list of registered students but authenticated user can not see that list.So please guide me to do so.

If you do this using a custom module, you can use hook_permission to defile your permissions, and use in the views. You can also restrict access by role and set the visibility if you use blocks fir the 'list of registered students'.


Is it possible to redirect after "pushing" a file to the user? I've got a setup where a site generates internal analytics about site usage. Users are able to request a download of their personal analytics, and because this information is sensitive I do not create any files, I generate a CSV file in a variable and then "push" it to the user with this:

function _cex_download( $output, $filename )
{
  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: private");
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=$filename");
  header("Accept-Ranges: bytes");
  echo $output;
  exit;
}

This causes the user's browser to pop a "save file" dialog, and the user gets the file created on their end. This works fine, except the site's administrators are able to trigger 'destructive exports' - and in that situation I have a secondary confirmation form the admin needs to accept before the destructive export executes.

The problem is that this "push download" routine ends the Drupal page processing. There does not appear any way to redirect the admin to some page after that push download routine is called. Admins get a 'save file' dialog popped by their browser, but they remain on the confirmation form.

I tried going the multi-step form route, but after a day of dinking around with strange redirects, I backed out of that confusion. Started looking at ChaosTool's multi-step form logic too. But something tells me that the issue really is that this "push downloading" is a guided-process-killer.

Perhaps a jquery confirmation dialog that intercepts the initial 'Export' button click, do the confirmation entirely in javascript, forget out having a php/FAPI confirmation form, and when the user confirms in jquery I programmatically submit the Export I intercepted?

As far as I know, that is not possible. You can either send content (in your case a file), or redirect. Not both. This is a limitation of the HTTP protocol


Get shipping and billing information from rule I am using the Drupal commerce module. I want to write a PHP script to execute on order completion, and I want that script to update an external database with the shipping information. How would I go about doing this?

I have already setup a rule to execute PHP code on order completion, and I am given the variable $commerce_order, but I don't know what to call to get out the customer shipping information. I have tried to email var_dump($commerce_order) but it does not give me anything.

How can I get a list of the fields? Am I on the right track?

The shipping information isn't directly stored on the order. The only way you have of figuring the shipping details is to look at the line items at $order->commerce_line_items one or more of them will be shipping line items, which can tell you about the shipping details.


Change menu link before rendered in mmenu module I've used Mobile sliding menu module version 7.x-1.0-dev.

We can change menu link using theme_menu_link().

Similarly is any other hook for change menu link in this module?

You want to implement hook_translated_menu_link_alter() and hook_menu_link_alter(&$item). This hook is not called for all menu items.

According to the API documentation:

It is only invoked if $item['options']['alter'] has been set to a non-empty value (e.g., TRUE). This flag should be set using hook_menu_link_alter().
Here's an example:

function MODULE_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['options']['alter'] = TRUE;
  }
}

function MODULE_translated_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['href'] = 'node/5';
  }
}

Some notes

You may want to filter additionally by $link['menu_name']; MODULE_menu_link_alter() is invoked on cache clear for all menus items declared via hook_menu().
For menu items created via web it is only invoked on save, that is, for this code to take effect you need to edit-and-save menu links you want to alter.


Two relationships in Views I'm wondering if the following construction is posible with Views in Drupal in combination with relationships. I build this in Drupal:

Manager <--(Entity Reference)--> Group <--(Entity Reference)--> User

A manager can control groups with different users, so I have the following setup:

  Manager A <--> Group A <--> User 1 Manager A <--> Group A <-->
  User 3 Manager A <--> Group A <--> User 5 Manager B <-->
  Group B <--> User 2 Manager B <--> Group C <--> User 4
  Manager B <--> Group C <--> User 6 Manager B <--> Group C <-->
  User 7

I'm looking for a way to generate a view with the logged in manager to get all the users of the group the manager is part of.

So we get this result when I'm logged in with manager B:

  User 2 User 4 User 6 User 7

I tried to create an Contextual filters with an default value of the logged in user. Then 2 relations: one for the

Manager <--(Entity Reference)--> Group

ans an second one for the

Group <--(Entity Reference)--> User

And then I tried to make fields with an relationship. But only I get is no results. Is there a way to get this working?

You will want you view set up so that:

The view is displaying Users.
There is a relationship from User to Group
There is a relationship from Group to Manager
You add the contextual filter that defaults to the currently logged in user. Make this filter use the Group-Manager relationship.


How to get nodes by custom field value using EntityFieldQuery? I am trying many options, e.g:

$entities = $nodeQuery->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->fieldCondition('field_archived','field_archived_value', '1', '=')
    ->pager(10)
    ->execute();

field_archived is the machine name of my custom field added to article. field_archived_value is a column inside field_data_field_archived table.

In this case I am getting error:

PDOException: SQLSTATE[42S22]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'field_archived_field_archived_value

What I am doing wrong here?

The correct code is the following one.

$entities = $nodeQuery->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->fieldCondition('field_archived','value', '1', '=')
  ->pager(10)
  ->execute();

Instead of 'field_archived_value' you need to use 'value'.


How to access weight of a paragraph in twig? I use paragraphs with my content type. I need to show weight (order) value of each paragraph in my twig template. I can change weight with select box when I edit the node, but I can't figure out how to get it in twig.

I thought it would be something like this:

function ws_preprocess_paragraph(&$variables)
{
    $par = $variables['paragraph'];
    $myweight = $par->weight;
}

Please help)

The weight of a paragraph is not stored in the paragraph itself, but in the host field.
So if you need to get the weight of a paragraph from within the paragraph (e.g. from  within hook_preprocess_paragraph()), you have to go upwards to the parent entity and find your the weight there:
function MYMODULE_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  $parent = $paragraph->getParentEntity();
  // get all paragraph IDs sorted by weight
  $weights = array_map( function($a) {return $a['target_id'];}, $parent->get($paragraph->get('parent_field_name')->value)->getValue());
  // find the weight of my paragraph ID
  $weight = array_search($paragraph->id(), $weights);
  // ...do stuff with $weight... e.g. assign it to a Twig variable
  // $variables['weight'] = $weight;
}

Please note that the weight is easier to get if you use the paragraph host field template instead (see @4k4's comment below the original question):

Use {{ loop.index0 }} in a field template like
field--field-paragraph.html.twig


How to disable/enable a context programmatically I want to disable contexts programmatically (for automated updates, where a new release of a website needs a context to be disabled).

I manage contexts using Features, but Features doesn't hold the enabled/disabled status of the context.

I can't find a function to change context status programmatically. There's a support request but the snippet is not working (nothing happens, context remains the same status).

After some investigation I came across the context_status variable. It seems to hold an array with context names as key and TRUE as value: each of these contexts is disabled. If you edit that variable by unsetting one context, the context becomes enabled.

So it seems the only way to disable/enable a context programmatically is to edit this conext_status.

Is there a better way to do it?

Use the context_status to enable/disable contexts.

This variable is an array with context names as key and TRUE as value: each of this context is disabled.

To disable a context: add a new pair to the array like this:

$contexts = variable_get('context_status', array());
$contexts['context_name'] = TRUE;
variable_set('context_status', $contexts);

To enable a context: unset the context name from context_status.

$contexts = variable_get('context_status', array());
unset($contexts['context_name']);
variable_set('context_status', $contexts);

Also you can use Features, exporting the context_status to a feature.


views_query_alter never called I want to alter a query for sorting a field. I read the documentation, it says

  This hook should be placed in MODULENAME.views.inc and it will be
  auto-loaded. MODULENAME.views.inc must be in the directory specified
  by the 'path' key returned by MODULENAME_views_api(), or the same
  directory as the .module file, if 'path' is unspecified.

I used to implement all hooks inside my sites/default/realia/template.php so I first went stright and implemented the hook in sites/default/realaia/template.php which obviously didnt work.

function realia_views_query_alter(&$view, &$query) {
    print "
I am in alter query
";
    var_dump($query);
}

After reading doc carefully which says the hook needs to be placed inside the specific file and in a specific place I totally feel lost. Because I don't see any .module file in my sites/default/themes/realia. This is where my all files provided by realia (3rd party) are placed there is only .info file but no .module file.

There are also other related modules inside sites/all/modules/realia but looks like this folder is not a module itself becuse there are no .info or .module files inside the root but subfolders/modules has it. I went and created a file reala_submodule.views.inc with the implementation and placed one in each of the modules but I still dont see it really got executed ever.

Of course I did drush cc all every time whenever I doubted there could be caching issue. I will have followup questions related sorting once I get this implementation working. Please help.

Maybe  reason can be if you use Search API module, in this case hook_search_api_views_query_alter will work instead

link 1
link 2

I have the same problem now and after some search find that when search API module enabled  hook_views_query_alter not worked.


How do I pass parameters to the form builder? I have the following routes in module_name.routing.yml.

module_name.usergroup_delete:
  path: 'module_name/usergroup/delete/{arg1}'
  defaults:
    _form: '\Drupal\module_name\Form\DeleteUserGroup'
    _title: 'Delete User group'
  requirements:
    _permission: 'access admin menus'

This is the code in module_name/src/Form/DeleteUserGroup.php.

namespace Drupal\module_name\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class DeleteUserGroup extends ConfigFormBase {

  public function getFormId() {
    return 'delete_user_group';
  }
/**
 * General form for switching all nodes from one user to another.
 */
  public function buildForm(array $form, FormStateInterface $form_state,$product_code) {
  $form['_product'] = array(
        '#type' => 'value',
        '#value' => $product_code,);
//get the user group and username to display the confirmation message
$result = db_query('select field_p_group_name_value from {content_type_usergroup} ctu'
        . ' where vid=%d',$product_code);
    while ($row = $result->fetchObject()) {
      $user_group = $row->field_p_group_name_value;
    }

return confirm_form($form,t('Are you sure you want to delete "' .$user_group. '" User Group?'),
        isset($_GET['destination']) ? $_GET['destination'] : "function_name",t('This action cannot be undone.'),t('Delete'),t('Cancel'));

  }
/**
 * #submit callback for node_adoption_transfer_form().
 */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
  //if ($form_state['values']['confirm']) {
    $param = $form_state->getValue('_product');
    drupal_set_message(t('Group ' .$param.' will get deleted.'));
    db_query('DELETE FROM {content_type_usergroup} WHERE vid = %d', $param);
    //delete the users of the usergroup too
    db_query('DELETE FROM {usergroup_user_map} WHERE group_id=%d', $param);
    drupal_set_message(t('usergroup has been deleted.'));
    drupal_goto('function_name');
  }

  protected function getEditableConfigNames() {
    return "delete_user_group";
  }

}

I am getting the following error:

  DeleteUserGroup::buildForm() must be compatible with
  Drupal\Core\Form\FormInterface::buildForm(array $form,
  Drupal\Core\Form\FormStateInterface $form_state)

Why?

The parameter has to have the same name in routing.yml and build method. And when using parameters in forms you have to set a null value in the parameter list:

public function buildForm(array $form, FormStateInterface $form_state, $arg1 = NULL) {


Is there a way to skip bootstrapping drupal to save load time via drush? I currently use drush alot to manage my sites, but I was wondering if there was a way to skip bootstrapping drupal everytime drush is run for certain commands that might not need it. This would save significant load time. I tend to do pm-list alot, but sometimes it just takes a long time to load depending on the size of the site. Same goes for enabling/disabling modules.

That is hard-coded for each command: The module defining a Drush command sets the bootstrap level required to run the command. For example, cache_drush_command() defines cache-clear as the following:

  $items['cache-clear'] = array(
    'bootstrap' => DRUSH_BOOTSTRAP_MAX,
    'description' => 'Clear a specific cache, or all drupal caches.',
    'arguments' => array(
      'type' => 'The particular cache to clear. Omit this argument to choose from available caches.',
    ),
    'callback' => 'drush_cache_command_clear',
    'aliases' => array('cc'),
  );

To require not bootstrap at all, the "bootstrap" property should be defined as follows.

  $items['xkcd-fetch'] = array(
    'description' => "Retrieve and display xkcd cartoons.",
    'arguments' => array(
      'search' => 'Optional argument to retrive the cartoons matching an index number, keyword search or "random". If omitted the latest cartoon will be retrieved.',
    ),
    'options' => array(
      'image-viewer' => 'Command to use to view images (e.g. xv, firefox). Defaults to "display" (from ImageMagick).',
      'google-custom-search-api-key' => 'Google Custom Search API Key, available from https://code.google.com/apis/console/. Default key limited to 100 queries/day globally.',
    ),
    'examples' => array(
      'drush xkcd' => 'Retrieve and display the latest cartoon.',
      'drush xkcd sandwich' => 'Retrieve and display cartoons about sandwiches.',
      'drush xkcd 123 --image-viewer=eog' => 'Retrieve and display cartoon #123 in eog.',
      'drush xkcd random --image-viewer=firefox' => 'Retrieve and display a random cartoon in Firefox.',
    ),
    'aliases' => array('xkcd'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH, // No bootstrap at all.
  );

Using DRUSH_BOOTSTRAP_DRUSH says to Drush that Drupal doesn't need to be bootstrapped at all.

Clearly, that is not something that can be arbitrarily changed; it depends from the code executed from the command.


Is it possible to have language specific content? I am working on a Drupal 7 site that is currently in English only. We are now looking at adding additional language support and so far I've got the hang of content translation using i18n.

We currently have a news section composed of articles for each story. Is it possible to write language-specific articles? E.g. if there is a French-only news story, it won't appear on the English language site.

We managed to find a solution and it involved using view filters.

In case it is useful for anyone else, you can do this by selecting Edit View in the top right hand corner of the view. Click on the Add button next to Filter Criteria and then choose "Content translation: Language".

Alan


Alter default message presented to user on failed login attempt I need to alter the default D7 message that gets presented to the user on a failed login attempt. I need to give them one message if their username isn't found, and another if their password is wrong. Default Drupal behavior is to give a single, generic error message that doesn't distinguish between the two.

For the password check, The best solution I've found is user_check_password(). This doesn't sit well with me. The password.inc file isn't included in all page requests, and as there are several different context dependent login pages on the site, it isn't always there. I've been forced to require_once it in my custom validation handler which seems very un-drupal-ish.

You can set your own custom message according to the validation by adding your custom validation function with login form.

function custom_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login_block' || $form_id == 'user_login')
    $form['#validate'] = array('custom_module_login_validate', 'user_login_authenticate_validate');
}
function custom_module_login_validate($form, &$form_state) {
  $uid = _custom_module_is_user_exists($form_state['values']['name']);
  if(!$uid) {
    form_set_error('name','Username not found.');
  }
  else {
    if(!user_authenticate($form_state['values']['name'], $form_state['values']['pass'])) {
       form_set_error('pass','Incorrect password.');
    }
  }

}
/**
 * Query user table to check if such username is already exists.
 */
function _custom_module_is_user_exists($username) {
  return db_query("SELECT u.uid FROM {users} u WHERE LOWER(u.name) = LOWER(:username)", array(':username'=>$username))->fetchField();
}


Updating existing products via Drupal Migrate I have 2 migrate classes - ProductsNewMigrate and ProductsUpdateMigrate.

1) ProductsNewMigrate runs initially, adding products from a CSV file into Drupal.  I can confirm this works correctly, the new products are created and a migrate map is set up in the database.

2) ProductsUpdateMigrate is required to import another CSV (exactly the same structure as in 1.) but with the updated product data originally migrated via ProductsNewMigrate.

I just can't get the Update migrate to work.
I receive the error:
array_flip(): Can only flip STRING and INTEGER values

When looking at the migrate map table for this Migration - migrate_map_productsupdate..
I notice sourceid1 is set to the SKU - which is correct.  However, destid1 and destid2 (product_id and product_revision respectively) are both null values - which could be causing this?

Edit: Also receive the warning message: "product_id" was used as destination field in "sku" mapping but is not in list of destination fields when viewing the migrate page!

See the code below:

Code:

class ProductsUpdateMigration extends CustomMigration {
  public function __construct() {
    parent::__construct();
    $this->description = t('Import new products from CSV');

    $csvfile = "/drupal/products_updated.csv";
    $columns = array(
      0 => array('sku', 'Product SKU'),
      1 => array('title', 'Product title'),
      2 => array('colour_specific', 'Product colour specific'),
      3 => array('price_group', 'Price Group'),
      4 => array('composition', 'Product Composition'),
      5 => array('width', 'Width'),
      8 => array('price', 'Product Price'),
    );

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'sku' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'description' => 'SKU/newref',
          'alias' => 'p',
        )
      ),
      MigrateDestinationEntityAPI::getKeySchema('commerce_product')
    );
    $this->source = new MigrateSourceCSV($csvfile, $columns, array('header_rows' => 1));
    $this->destination = new MigrateDestinationEntityAPI('commerce_product', 'blinds');
    $this->systemOfRecord = Migration::DESTINATION;

    // print_r($this);

    // Mapped fields
    $this->addFieldMapping('product_id', 'sku')
      ->sourceMigration('ProductsNew');
    $this->addFieldMapping('title', 'title');
    $this->addFieldMapping('commerce_stock')
      ->defaultValue(5);
    $this->addFieldMapping('field_blinds_colour_specific', 'colour_specific');
    $this->addFieldMapping('field_blinds_composition', 'composition');
    $this->addFieldMapping('field_blinds_width', 'width');
    $this->addFieldMapping('commerce_price', 'price');
    $this->addFieldMapping('field_blinds_price_group', 'price_group');
    $this->addFieldMapping('type')
      ->defaultValue('blinds');
  }

  public function prepareRow($current_row) {
    $colours = explode(';', $current_row->colour_specific);
    // // print '<pre>';
    // // print_r($colours);
    // // print '</pre>';
    $current_row->colour_specific = $colours;
    // $current_row->migrate_map_destid1 = 62;
    // $current_row->migrate_map_destid2 = 67;
    print_r($current_row);
    return TRUE;
  }

  public function prepare($entity, stdClass $row) {
  }
}

Took a slightly different approach to solve this.

Upgraded Migrate module from version 2.5 to 2.6
Ran upgrades drush updatedb, made sure the migration groups were registered (did this via migrate ui)
After reading the following articles regarding the new 'trackchanges' hash value option:
http://timonweb.com/using-hash-value-trackchanges-to-detect-source-data-changes-in-migrate-for-drupal-7
& http://www.acquia.com/blog/migrate-26-framework-changes I now
applied the following to the migrate in step 1):

$this->source = new MigrateSourceCSV($csvfile, $columns, array(
  'header_rows' => 1,
  'track_changes' => 1
));

The use of track changes now allows the same CSV to be uploaded, any new rows will create a product. Any changes will be detected via the hash that this option provides in the migrate_map table - thus causing the particular product to be updated.


Highlight current user in multiple user reference field on /user page I am displaying a block on all /user pages, that will show all upcoming events, and the staff that have been assigned to certain roles at that event.

For example...

Manager: Jake

Bar Staff: Mike, Fred, Jim

Sound Tech: James, Bill

What I want to achieve, is for every instance of a users name to be highlighted in that view, if they are logged in. So, go to Bills user page, and all "Bill" entries have an "active" class applied to them. Then, go to Mikes user page, and all "Mike" entries are given the "active" class etc.

Usually, I would name a template field for the view field views-view-field--field-manager.tpl.php and do a comparison with the current user page title, which is the current users name...

<?php

$title = drupal_get_title();

if ($title == $output) {
  $class = "active";
}

?>

<span class="<?php if(isset($class)) { print $class; } ?>"><?php print $output; ?>

But this is affecting the whole field, which is no good when you have multiple users referenced in the field.

Is there a way to target individual multiple results in a field with a tpl file?

This was actually much easier than I anticipated.

Of course, by default, every user name is a link, and for the user name to be highlighted on each users page, it meant that the link could automatically be given an active class as the current page.

Problem solved.


D7 - Webform Email Field Read Only We would like to target a webform field "email" so that it only has readonly option when the field uses the logged in users email address.

The webform email field has an option to "Set the default value of this field to the user email, if he/she is logged in." and to toggle a "readonly" option.

How would we go about achieving this?

There's two possible approaches you could take here:

Add a custom hook_form_alter to test in php if the user is logged in, and then set the disabled/locked attribute to the field.
Add javascript that on page load checks to see if the body has the "logged-in" class and if the field is already populated/has a value; then disable/lock it.


Get the route name of the current page The route name of the current page is available in page.html.twig?
The page is generated by the default feedback form.

To get the current route name, use:

$route_name = \Drupal::routeMatch()->getRouteName();

You can add the current page's route name as a variable in your theme's ".theme" file.  Add a _preprocess_page function like this, and clear the drupal cache.

/**
 * Implements hook_preprocess_page().
 *
 */
function mytheme_preprocess_page(&$variables) {
  $variables['route_name'] = \Drupal::routeMatch()->getRouteName();
}

Then you can access in page.html.twig like this:

{{ route_name }}

Note: \Drupal::routeMatch()->getRouteName() will sometimes return null.

If you are inside a class, to do things properly, you'll want to inject the route match service in the constructor and then call it this way:

$this->currentRouteMatch->getRouteName()

The constructor (and variable) will be like this:

  /**
   * The current route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $currentRouteMatch;

  /**
   * Constructs a new ThemeTestSubscriber.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $current_route_match
   */
  public function __construct(RouteMatchInterface $current_route_match) {
    $this->currentRouteMatch = $current_route_match;
  }

If it's a service class, you'd then pass it into the service in the yaml file in your custom module:

services:
  mymodule.service:
    class: Drupal\mymodule\MyCustomService
    arguments: ['@current_route_match']


Fill form on ajax callback Seems to be an extremely simple question. But I can't figure it out. In my module's form I need to load form values depend on the value of certain one and rebuild the form using those.

here is the part of the code (form builder):

$namevalue = isset($form_state['values']['name']) ? $form_state['values']['name'] : "";
$form['name'] = array(
    '#type' => 'textfield',
    '#default_value' => $namevalue
);
$form['load_settings'] = array(
    '#type' => 'button',
    '#value' => t('Load my settings'),
    '#ajax' => array(
        'callback' => 'simplenews_mod_load_subscriptions',
    )
);

Here is the callback:

function simplenews_mod_load_subscriptions( $form, &$form_state){
  $form_state['values']['name'] = "loaded value"; // here will be a function which will get the value form DB
  return $form_state;
}

Nothing changes in the $form_state array.
I think I just don't get the basis of ajax in D7 itself... I'd be very appreciated if someone show my the simplest example of how to change a form field value using ajax.

Or alternatively: how do I rebuild form with new values using custom submit callback. Not on validation.

Thank you.

the problem was in the way I pass submit callback. It should be like

'#submit' => array('foo_submit_callback')

ARRAY!

the less visible thing is the most visible one...


Which hook do I use to alter product entity data in a product display? In Drupal Commerce, which hook do I use to alter product entity data in a product display?**  And it needs to be a hook that fires each time I change an attribute that causes a different product entity to be loaded in the display.

I added a line item to my product type called "Comments". It is a textarea, and it has a field description too. Then, on my product type, I added the following fields:

Customizable? (On/Off checkbox)
Custom Field Label
Custom Field Description

As each product entity is about to be displayed (whether it's the first one shown when the page loads, or I make a drop down selection to change which one shows), I want to check if that product entity is "Customizable".  If it is, I want to rename the title of the "Comments" line item with the value stored in "Custom Field Label".  And I want to change the Comments field description with the value stored in "Custom Field Description".  If the product entity is NOT "Customizable", then I want to hide the field completely (such as by converting the field type from a textarea to a hidden field).  This way, the "Comments" line item really only shows for the product entities we want it to, and it can have a custom label and instruction when it does show.

Any help someone can give is greatly appreciated.  I am having a lot of trouble even figuring out which hook fires each time a product entity is loaded, either the first time, or when switched via ajax.

hook_entity_load may be the answer that some folks are looking for in situations that differ from mine.

For my specific need, I discovered that everything I needed to accomplish could be done with hook_form_alter.  The form_state holds the value of the currently selected SKU in $form_state['default_product']->sku.  Here is a hook_form_alter function I wrote to accomplish my goals:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if(strstr($form_id, 'commerce_cart_add_to_cart_form_')) {

        // Load the current product entity
        $prod = commerce_product_load_by_sku($form_state['default_product']->sku);

        // Check and see if the produt is customizeable or not, and then react
        $customizeable = $prod->field_prod_customizable['und'][0]['value'];
        if(isset($customizeable) && $customizeable == 1) {
            // Grab the custom label and instruction
            $customize_label = $prod->field_prod_customize_label['und'][0]['value'];
            $customize_instruction = $prod->field_prod_customize_instruction['und'][0]['value'];

            // Alter the field to display the custom label and instruction
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#title'] = $customize_label;
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#description'] = $customize_instruction;
        }
        else {
            // If not a customizeable product, then make the field hidden and not required
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#type'] = 'hidden';
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#required'] = 0;
        }
    }
}

Note that the textarea field I added to my Product line item type is called field_prod_comments.  The fields I added to my product entity are field_prod_customizable, field_prod_customize_label, and field_prod_customize_instruction.


Views Exposed Filters - position each filter independently I am working on a drupal 7 project and have a view (v3) over 6,000 product items with 4 exposed filters.  This all works fine - I can put the "filter form" in a block - that is fine.

But I can't figure out how to separate out the individual filter drop downs for nicer positioning.  Say I want two dropdowns on the top of the result area and 2 with the apply button stacked on the left...

Is my only option to play with absolute positioning in the css?

you can add more functionalities to Exposed Filters forms, or control his style/layout, touching template views-exposed-form.tpl.php. try this resource http://drupal.org/node/320992 or this http://ykyuen.wordpress.com/2011/07/25/drupal-theme-the-exposed-filter-in-views/ to see guides about how to implement it.


How to insert drupal username and email fields into create booking form? Am using the Booking Time slot module. The module introduces a "Booking entity".

I want to insert the default drupal 'username' and 'email' fields into the form used in creating a new booking, so that user is able to register while completing form.

Assuming "Booking" was a "Content Type", I would use the inline registration module. However, that option does not exist in this case.

Is there a way to insert the fields or merge the 2 forms?

To create a new booking, the form for that already contains a (required) entity reference field to an existing user (with field_bt_user). Head over of admin/structure/booking/fields in your own site to get more details on that.

If you however want to add another username and email field, just use "Add new field" on admin/structure/booking/fields for both of those fields.

However, as per your "... so that the user is able to register while completing form ..." (as contained in your question), it appears to me that you want an anonymous user to be able to do so. If that's the case, you'll have to decide about how an anonymous user should complete that form, for the required field field_bt_user. You might think "just make that field no longer required", but I doubt that's a good idea to do, since there must be good reason for this module why that field is required.

Because of what is above, I think you should slightly adapt your workflow regarding that  "... so that the user is able to register while completing form ...":

Step 1: use the Rules module to intercept a path equal to /admin/structure/booking/add, if it is entered by an anonymous user, and redirect them to the login page, with an option to register and a Drupal message shown to them like "this path can only be used by authenticated users, try again after login" (piece of cake with Rules).
Step 2: wait for the login to be completed, and have the authenticated user enter the same path (/admin/structure/booking/add) again. When that happens, the Rules Actions in custom rule as in Step 1 will not be executed anymore (since user is authenticated), while the form is not used by an already registered user.

If you can't solve a problem,

then prevent the problem from ever happening again is a typical plan-b ...


Implement Field API Pane Editor into Views I have a View which shows nodes from a content type. I need user to be able to edit only one field from these nodes. I installed FAPE module and read its instructions but cat figure out how to implement it into views. I can't ever find out how links should look. Any help would be appreciated. 10x

For editing single-field values in views, there's the editable fields module rather than FAPE. However, this edits a single row at a time, rather than bulk updating all nodes or entities in the view at the same time.


Max length of text field How can I increase the max lenght of Tab-Title ?

With module: Title you can convert title to field and then you can change the field length

For title-tab goto: admin/structure/types/manage choose your content type and then manage fields edit your field


How to put "Advanced form block" in a twitter bootstrap modal? I want to add an Advanced Form Block into a modal. So far I've been partially successful, the block is added to the modal but the form is outside the modal markup.

The area marked in red is the form which should be in the div with the class modal-body. How do I make this work?

The problem was that the Advanced Form Block, has a CSS class of .node-form and this is not encapsulated in the standard block content div .block-content. So when the Twitter Bootstrap Modal Block module tries to add the .modal-body CSS class to the .block-contents div, it will not find the div and the form will be left outside the modal body.

For me the easiest way to solve this was to edit Twitter Bootstrap Modal Block JavaScript file, i.e. sites/all/modules/twitter_bootstrap_modal/twitter_bootstrap_modal_block/twitter_bootstrap/modal_block.js, as follows:

Change the line that reads

$(this).children('.block-content').addClass('modal-body'); //line 29

to

$(this).children('.block-content, .node-form').wrapAll('<div class="modal-body" />');

This will put the advanced from block into the modal body.


Page manager (or panels) override path I want to override Drupal 8 paths (routes) like node/{node} or taxonomy/term/{taxonomy_term} with custom panels variants. Is it possible?

Page Manager module.  Add a new page that has the Path of /taxonomy/term/% and as @Todd Young wrote, disable the default Taxonomy view.

However, there is a bug that this is not working at https://www.drupal.org/node/2785195


How does Drupal 7 Load its Modules I'm debugging a Drupal 7 system I didn't setup, and I'm trying to understand how Drupal loads its modules.

This system appears to have modules nested within one other -- here's one example.

modules/custom/modulename/modulename.info
modules/custom/modulename/modulename.install
modules/custom/modulename/modulename.module
modules/custom/modulename/modulename_statistics/modulename_statistics.drush.inc
modules/custom/modulename/modulename_statistics/modulename_statistics.inc
modules/custom/modulename/modulename_statistics/modulename_statistics.info
modules/custom/modulename/modulename_statistics/modulename_statistics.module

It appears there's one module named modulename, and inside this module there's another named modulename_staticstics.

Is this a "legal/normal" setup?  Does nesting one module within another confer any special features between the two modules?  Where in the drupal source code are modules searched for/loaded?  Is there any canonical piece of documentation that covers how module loading works? (my googling didn't turn up a lot)

(experienced software engineer here, but only passingly familiar with Drupal)

Is this a "legal/normal" setup?

It's perfectly legal, and yes it's normal for modules that need or want to break their functionality down that way.

  Does nesting one module within another confer any special features between the two modules?

No, they’re just standard modules.

  Where in the drupal source code are modules searched for/loaded?

I think this is pretty much exhaustive for Drupal 7:

/modules/**
/profiles/*/modules/**
/sites/*/modules/**

  Is there any canonical piece of documentation that covers how module loading works?

I wouldn't have thought so - following the code is probably the best way to understand how it works. Core is pretty well commented.


how to remove empty rows from view how to remove empty rows from view(block) ?
I have a created a View block using field collection even empty condition are enabled in the fields settings still im getting empty rows PFA for image 2 in that only view-row-95 has values rest all the view-row are empty .

In this given image(second image), it is clear that there is a value " "(space) coming for the field Footer Col3.

Check in Footer Col3 field settings or in any custom module if you are set any default value for that field.


HTTPS and SecurePages Infinite Redirect - How do I reset which pages are always HTTPS? Using Secure Pages, I checked the option to have the site always be using HTTPS when logged in as an administrator, but now I have an infinite redirection issue, and I cannot log-in and navigate the site, leaving me to edit the settings manually.

How do I "uncheck", or revert the option that I selected manually in SecurePages?

I pulled this directly from the README.txt of the module.

  Configuration

  Generally on test/development servers you do not have access to SSL,
  so  generally you would like to disable secure pages on these systems.

  To do this add the following to your settings.php

  $conf['securepages_enable'] = 0;

  Removal of SecurePages

  In the case where your SSL mode has been disabled and you can no
  longer access the administration section of your site to disable
  securepages you can do one of the 2 following things.

  Use the above method to disable securepages.
  delete the secure pages module from your site.

  If you can use the first option but if you can't edit your
  settings.php then deleting it will not break your site, but will leave
  some variables that are set by secure pages.


Non-Clickable Menu Items In a Drupal 8 site, I want to add menu items with "no link", I was thinking that nolink is allowed but when I entered this, I got error

  Manually entered paths should start with /, ? or #.

Is there a way for adding menu items not clickable without adding "#" because "#" add attribute [data-drupal-link-system-path=""] and [class="is-active"]

You need to use route:<nolink> to achieve this. Then it will validate and render without a link.


Adding text before and after cart contents block in Drupal 7 commerce I need to add some text above and below the Cart Contents block at the top of the checkout form. I tried just editing the view and adding a header and footer to that view but no dice, it doesn't work (it shows in the View preview but not in the view results when saved).

So I'm looking for the page--checkout.tpl.php form and I can't find it anywhere. Does anyone know where I can find this template?

The easiest way to do this, for me, is by code, as checkout pages are normal Drupal forms and as such, we can use hook_form_alter() to do whatever we need. In this case, you can use

(yourmoduleorthemename)_form_commerce_checkout_form_checkout_alter (&$form, &$form_state)

And inside it, you can use Form API(https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#markup-attribute) to change the way you want.

You can also create a block and put on the "checkout/%/*", but it generates a lot of extra markup for almost nothing.

I believe you can solve your problem with one of these, but let me know if you need more details.


Drush site-upgrade : "Unknown option: --uninstall" I'm trying to upgrade a Drupal site from 6.34 to 7.x using Drush.
When I run drush site-upgrade @alias, everything goes well until step 12-a where it ends up throwing this error :

Unknown option: --uninstall.  See `drush help pm-disable` for available options. To suppress this error, add the option --strict=0.

I made some search about this and tried a few things :

I created a file ~/.drush/my.drushrc.php using the example code given here : http://api.drush.org/api/drush/examples%21example.drushrc.php/6.x
I then uncommented line 198 :

$options['strict'] = FALSE;

In that same drushrc file, I added this line :

$command_specific['pm-disable'] = array('strict' => 0);

This solution was proposed here : https://www.drupal.org/node/2074781

I then tried defining a drush alias in my .bash_aliases (https://drupal.stackexchange.com/a/128974/39434)

alias  drush='drush --strict=0'

Neither of these solutions helped, I always get the same error.

OS: Ubuntu 14.10
Drush : 6.2.0
PHP: 5.5.12-2ubuntu4.1 (cli)

My Drush configuration file was simply misplaced, I had to put it in Drupal's directory (sites/all/drush/drushrc.php) rather than ~/.drush/

When running drush status from your Drupal source site directory, make sure there is a Drush configuration loaded.

Drush version                   :  6.2.0
Drush configuration             :  /var/www/html/drupal/sites/all/drush/drushrc.php
Drush alias files               :  /root/.drush/my.alias.drushrc.php

And here is the content of file sites/all/drush/drushrc.php

<?php
$options['strict'] = FALSE;


How do I rewrite attached file field output in Views to override the filename? I am trying to build a simple Views Accordion view to display support documents. I created a simple content type with three fields: Group (my category), Document Title, and File. The only way I can get the attached file to appear is by inserting the field Content: File. That links to the file and displays the little PDF icon, but shows the actual filename as the hyperlink text. I would like to use the Document Title field contents as the hyperlink text, but can't figure out the proper way to do this. I have tried hiding the file from display and rewriting the output of the Document Title field to be something like:
    [title]
However, it appears Drupal is rendering the link to the file instead of inserting the path to the file, as it shows the PDF icon and the filename.

Is there a way to override the hyperlink text when showing an attached file?

Certainly, you just have to use the correct formatter to start with.  I am guessing that you are using the "Generic Files" one.  If you instead select "Path to File" you can then use rewrite output the way you mention in your question.  Little gotcha:  make sure the title field you are using isn't "linked to its node" or things will get odd :)

(Note, I am suggesting you rewrite the file field instead of the title field)


Any alternative for webform_mysql_views I am using postgresql as database. I want to create views of webform submissions. is there anything similar to webform_mysql_views for postgresql.

Maybe you could use the Data module.

  Data module helps you model, manage and query related sets of tables. It offers an administration interface and a low level API for manipulating tables and accessing their contents. Data module provides Views integration for displaying table data and Drupal search integration for searching table content.


Which permission do I need to give to see all open tasks in the Maestro taskconsole It is unclear to me which permission I do need to give to a specific role, to see all open tasks in the Maestro taskconsole, just like an admin sees all tasks.

Thanks for your help

Seems that you need to give the following permissions:

Access Maestro Task Console
View Outstanding Tasks


How to iterate extra fields in a webform component When I select the extra field of a webform component:

$webform_components = db_select('webform_component', 'c')
                          ->fields('c', array('type', 'form_key', 'extra'))
                          ->condition('nid', $nid)
                          ->execute()
                          ->fetchAll();

The extra field is something like this (the following example is a grid component):

"a:8:{s:13:\"title_display\";s:4:\"none\";s:7:\"private\";i:0;s:15:\"wrapper_classes\";s:0:\"\";s:6:\"sticky\";i:1;s:7:\"options\";s:20:\"5|poor\n10|excellent\n\";s:18:\"custom_option_keys\";i:1;s:9:\"questions\";s:159:\"mensaje|Each message is associated with a language, which may or may not be the\nactual|current user's selected language, depending on the type of e-mail being\n\";s:20:\"custom_question_keys\";i:1;}"

I want to get the options and the questions. In the previous example:

\"options\";s:20:\"5|poor\n10|excellent\

Option 1: 5 (key) | poor (value)

Option 2: 10 (key) | excellent (value)

\"questions\";s:159:\"mensaje|Each message is associated with a language, which may or may not be the\nactual|current user's selected language, depending on the type of e-mail being

Question 1: mensaje (key) | Each message [...] (value)

Question 2: actual (key)| current user's [...] (value)

I don't know how to process this extra string. I tried to transform it to an array and a json, but it didn't work.

Thank you for your help! :)

It's a serialised PHP string, so:

$unserialised = unserialize($input);

// Split $unserialised['options'] by the '|' char, then extract keys/values


Conditional patterns with automatic nodetitles I`m using automatic nodetitles module to hide and autogenerate the title of one of my content types. My question is:

Is it possible to use conditional rules to define which pattern to be used when certain conditions is met? I need the pattern to be X if a certain field in the node is present, another if not.

Thanks,

That module also provides the ability to use PHP to construct the pattern.  Look for the check box at the bottom.

Please refer to the module's help file for more info on combining PHP and tokens for the pattern.


sort by subject in privatemsg Is there any possibility to sort all the messages by subjects? For example, there is a button on the main page "send a message to author". Subject from the sender is defined as "main page". If several users send message with this subject, can i see in my mailbox one subject "main page" and then see the list, who wrote it?

Messages in the inbox can be filtered by subject.  To do so, if you are on the default path (messages), just click the blue link for "Subject" at the top of the table.

Alternately, if you want to always filter by subject, you can change the messages link to this:
messages?sort=asc&order=Subject.


How do I create and delete a forum via POST to taxonomy_term? I'd like to be able to programmatically create and delete Forums on a Drupal 7 install, via the Services module. I want to send in HTTP requests and have those things happen.

I know how to create a node (page, article, or forum topic).
I know how to delete a node.

How can I create a forum? I think Forums is a taxonomy_vocabulary. I think creating and removing forums is equivalent to adding  and removing terms to the vocabulary.  But I would like to see an example.

Any help?

Part one: How to delete a forum.

curl -i -X DELETE \
  -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
  -H X-CSRF-Token:v6j7r9Rbase62tokenHere-m9YYZA \
  -H Accept:application/json \
  http://myserver/rest/taxonomy_term/7

Some notes:

to construct the URL, you need to use the Term ID of the particular forum you would like to delete
You need to use the Cookie obtained from the prior call to /user/login
You need to use the CSRF token obtained from that same call

Where does the term ID come from?

The term id in my case, is something I retrieved from a combination of two other calls: one to retrieve the taxonomy id for the forums, then another to retrieve the terms under  that taxonomy. Like this:

curl -i -X GET \
  -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
 'http://myserver/rest/taxonomy_vocabulary?parameters\[machine_name\]=forums'

The response is like this:

[{
  "vid": "1",
  "name": "Forums",
  "machine_name": "forums",
  "description": "Forum navigation vocabulary",
  "hierarchy": "0",
  "module": "forum",
  "weight": "-10",
  "uri": "http://myserver/rest/taxonomy_vocabulary/1"
}]

And then, with the taxonomy ID returned there, I can retrieve the terms, which correspond to actual forums, like this:

curl -i -X GET \
 -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
 -H Accept:application/json \
 'http://myserver/rest/taxonomy_term?parameters\[vid\]=1'

The response is an array of JSON items, each of which has a term id.  You can then choose one of those term id's to delete, as above.

Part two: How to create a forum.

To create a forum, do the converse; add a new term in the same "forums" vocabulary. like this.

curl -i -X POST \
  -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
  -H X-CSRF-Token:v6j7r9Rbase62tokenHere-m9YYZA \
  -H Accept:application/json \
  -H content-type:application/json \
  http://myserver/rest/taxonomy_term \
  -d '{
    "vid": "1",
    "name": "Another Forum on the site",
    "description": "",
    "format": null,
    "weight": "10"
  }'

The vid property needs to be the "vocabulary id" of the forums
vocabulary. The uuid and the tid of the newly-created term will
be generated for you. Unfortunately, the tid will not be returned
for you to reference. You need to query again to find it.

curl -i -X GET \
  -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
  -H Accept:application/json \
  'http://myserver/rest/taxonomy_term?parameters\[name\]=Another+Forum+on+the+site'

Response:

[{
  "tid": "36",
  "vid": "1",
  "name": "Another Forum on the site",
  "description": "",
  "format": null,
  "weight": "10",
  "uuid": "dcbe0118-c160-4556-b0b6-1813241bb851",
  "uri": "http://myserver/rest/taxonomy_term/36"
}]

Therefore, make sure you use unique names for these "terms".


how to develop multiple pages registration form I want to develop a registration form employees based on different steps like company,salary,interview,pors and crons etc. they are pages for the registration process.
Can anyone tell me how to develop this kind of functionality?

Try the Multi-Step Registration module

  With Multi-Step Registration you can create multi-step (wizard) user account registration forms. Each step of the wizard can be configured to, optionally, expose one ore more Profile2 types.

You can also achieve that by creating a custom module. Checkout this post and

Altering User Registration Form to Multi-Step Drupal 7


How to display content for a Taxonomy Vocabulary? I am using Drupal 8.

I have a Vocabulary called Fruit which contains terms:

Apple
Banana
Orange

I can go to page for term Apple and I can find all the content which was tagged with apple there. I want to create a page with all content tagged under Fruit as well. Is there a way to achieve this?

You need to look at creating views you can start by watching
as many as the following to get the idea:

https://www.google.com/search?q=drupal+8+how+to+create+a+view&source=lnms&tbm=vid


How do I stop the site content from being internally indexed? I have a Drupal 6 website, which is indexing the content for internal use. I don't use the Search module to search in the nodes, but The Search module is installed and enabled, since it seems to be required by the Google CSE module.

Is there anyway to stop Drupal indexing the content of the site?

Go to admin/settings/search and set "Number of items to index per cron run" to 0.


Is it possible to use different tokens in metatag based on content type Lets say I have the summary field enabled on article type but not on page type and then I setup meta tag descriptions to use the token [node:summary] would is be possible to do something like if [node:summary] doesn't exist or is empty than use [node:body] ?

Otherwise i was would most likely need to add the summary field to page types and fill the summary field for all the pages that didnt have it.

In Drupal 7
When you configure Metatag, you can click on + Add default meta tags and this will allow you to set them up by Content Type.

You will see this gets added to the config tree. Simply now edit the content type you just added.
Bonus/Extra Info
If you need to alter only specific nodes, edit your node and scroll down to the end and select the Meta tags tab.


How to display form submitted values without storing in database I am new to Drupal. I couldn't figure out how to display the values submitted in a form on a new page without storing in a database.
I found a video on how to retrieve data submitted through a form and stored in a database, but, for my site I wouldn't need to store data. The data will get some simple mathematical processing and then the result will be displayed on another page. Here is the code I have.

<?php
/**
 * Implements hook_permission().
*/
function form_price_permission() {
return array(
'submit form_price' => array(
  'title' => t('Submit form_price'),
  'description' => t('Submit the form_price form'),
  ),
);
}
/**
* Implements hook_menu().
*/
function form_price_menu() {
$items = array();
$items['form-price'] = array(
  'title' => 'Form to calculate price',
      'page callback' => 'drupal_get_form',
  'page arguments' => array('form_price_form'),
  'access arguments' => array('submit form_price'),
);
return $items;
}
/**
 * form implementation
*/
function form_price_form($form,&$form_state){
$form = array();
$form['numberb'] = array(
    '#required' => '1',
    '#field_prefix' => 'Number B',
    '#weight' => '1',
    '#title' => t('B'),
    '#type' => 'textfield',
);
$form['numbera'] = array(
    '#required' => '1',
    '#field_prefix' => 'Number A',
    '#weight' => '2',
    '#title' => t('A'),
    '#type' => 'textfield',
    );
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add item'),
    '#weight' => '3',
);
 return $form;
 }
/**
  * how to display A + B
 */
function form_price_form_submit($form, &$form_state) {
$a = $form_state['values']['numbera'];
$b = $form_state['values']['numberb'];
$c = $a + $b;
}

I suggest:

deleting all the default submit handlers in the submit array in the $form variable - to stop the data being stored in the database
add your own submit handler to do the calculation and store the result in the standard PHP _SESSION variable
add a #redirect property in the (correct place) $form array variable to redirect the to URL of the result page
write code for the result page output the result in the _SESSION variable. To do this determine what type of page will display the result so that you can implement appropriate code to display the result  - there are several ways to do it: e.g. code in a template file, or a custom programmatically created block


editing how a field is output (changing commas to ) I am getting data from an outside source to populate some of my fields. It comes in as a string separated with commas. In order to display this data in a list format. I did this:

$commaString = ($items[0]["#markup"]);
$NoCommaString = str_replace("," , "<br />", $commaString);
$items[0]["#markup"] = $NoCommaString;

In field--field-MYFIELD.tpl.php. So now field displays like this:

item 1
item 2
item 3

instead of

item 1, item 2, item 3

Which is exactly what I want, yay! However, I'm new to Drupal and am worried I'm bypassing something or not using an API when I should be. So is there a better way to do this?

Just for security purposes I would wrap $commaString in check_plain() to get rid of any naughty characters or code that could come through.

And as for doing extremely simple things with PHP, you shouldn't have to worry about doing it the "Drupal way" too often. There are such things as PHP wrapper functions which are useful for keeping your code safe from PHP version quirks.

Also just to add, if the question were: "I want to format this CSV as a bulleted list." Then I would've suggested using a theme() function like the following:

print theme('item_list', array('items' => explode(",", check_plain($commaString))));

Because Drupal's theme layer is your friend and will help you to almost never write markup in your code. And I'm not aware of a theme function that converts a CSV string into a newline separated one. Item list is a good example of a theme function, so is a table theme.


Drupal 7 and Views 3: Page Display and Random Appended Arguments in URL This is going to seem like an odd question. I am not sure if this is the way Views is meant to work but I want to see if I can turn it off.

Say I have a View with a Page Display with a defined URL like so: /testimonials

The Display takes not arguments what so ever. Here is the problem: I can now access this view using URLs like this:

/testimonials/5898
/testimonials/hello/what
/testimonials/stupid/appended/data

I can't for the life of me figure out how to turn this off in Views. Any ideas?

5898 is just an extra URL argument in View's point of view. Views doesn't have the ability to throw 404 pages because there are "extra" arguments in the URL. Views does throw 404s when there is no argument in the URL (if configured that way). In any case, you can implement something like hook_views_pre_view() and redirect the user to a separate 404 page if you see that extra arguments are found in the URL. This should take like 15 minutes for a Drupal developer to do.


Integrating Search API and Views? I just today decided to try out using Search API instead of just the regular exposed filters within views. However, even with the Search API Views module enabled, my indexes don't appear to be exposed to Views as filters. Documentation on integrating Search API and Views is relatively non-existent, so I can't really go to that for help. In fact, the documentation for the integration module states that "Most features should be clear to users of Views." Well apparently not. Any help would be appreciated.

The important points, which I can't seem to find stated clearly anywhere:

Each Search API search index you create becomes an option in the "Show [content]" dropdown at the top when you first create a new view. Unlike regular search views (where you could just take any old view and add a "Search" contextual filter), to use search API in views, you have to create a special type of view, choosing and fixing the search index to use at the point of creating the view, by choosing it in this dropdown.
You'll need to pipe the actual search terms in somehow. A common way is to use the "Search fulltext" contextual filter, which interprets an argument in the URL as the search terms to use. There's also (depending on search server, I believe) the popular "Search More like this" option, which uses the content of the entity loaded via the contextual filter as the search terms (so if it's a block on a node page set to use the node's nid, it gives you results as if you searched using that node's content). Another way is using an exposed filter then getting the search terms from the input or exposed filter part of the URL query string.
For reasons I don't quite understand (probably something to to do with how entity API module does views integration for entity views, which has some limitations, more info at http://drupal.org/node/1378656), some elements of a Search API view are different to how they would be normally. For example, where in a node view, the path would be [path], in a Search API index view on a search index set to search nodes, it's [url]. It's no big deal, mostly the differences are fairly easy to figure out, but it's something to watch out for. Some things e.g. some relationships don't work for similar reasons - test complex views thoroughly and look at both Search API and Entity API issue queues if you find problems.

There is, technically, a documentation page that touches on some of this, which might be of some use to someone.


How do I show the username field in the user edit form? I need to show username textfield in user edit form. Normally, it shows only for administrator user. How do I show this for all users' edit form?

Go to admin/people/permissions and select the Change own username for the roles you need to be able to change their username.