Drupal go to with destination I have a page with two links visible to people, but on clicking  of either of two, user needs to log in to view, so in case user is not logged in, i am sending users to login page with drupal_goto('user'), i want that if the user clicked 1st link and is redirected to login page, after successful login, he should be redirected again to that 1st link
i tried with this code but did not work,

$query = array('destination' => 'node/id');
drupal_goto('user',$query);

You need to use drupal_goto the same way you use url.

So what you need to do is this:

$query = array('destination' => 'node/id');
drupal_goto('user', array('query' => $query));


Completely hide/remove views exposed form? I created a view with exposed filters.
The only purpose of the filters is to have url query parameters, which are controlled through custom UI elements.

There is no purpose in displaying the exposed form.

I can think of a number of ways to get rid of the form. But they all involve custom code that directly targets the view id. So it will be throwaway code, not reusable.

Another option could be to put the exposed form into a block, and then simply not display this block. But this will produce noise in features.

I wonder if there is a more elegant way to do this.
E.g. a contrib module or a piece of custom code which gives me a checkbox in Views UI where I can say "don't show an exposed form".
Maybe an exposed form plugin which does not display the form at all..

If you're using hidden exposed filters instead of contextual filters, then you're already on a bit of a hacky path so you might as well just hide the filters with css.
If you think the contextual filters won't work which is sometimes the case, then the elegant solution is using the Global:Null contextual filter + Views Argument Substitutions to use parts of the url in the normal filters.
But really, just hide it with css.


How to populate field X with value of field Y in Organic Groups? I want to use rules in order to populate Organic Groups field X value with the value of field Y. Keeping in mind these fields are Organic Group fields.

Field X is a 'long text & summary' field, while field Y is a normal 'text field'.

I'm trying to use Rules Actions to achieve this but no luck so far.

Any suggestions?

Here is a rule (in Rules export format) that should be close to what your question is about:

{ "rules_og_populate_fields" : {
    "LABEL" : "OG populate fields",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "og" ],
    "ON" : { "og_user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_x" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_y" } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-y" ],
          "value" : "[node:title-x]"
        }
      }
    ]
  }
}

You didn't specify which Rules Event you want to use. In my sample, I used "User has become a group member" (adapt the event to fit your own needs).

Notice the "entity has field" conditions, for both fields. Those conditions will make the fields available in the Rules Action ... (so that you can reference field X and set the value of field Y).

If you have the Rules UI enabled, and if the machine names of your fields are indeed "field_x" (for field X) and "field_y" (for field Y), you should be able to just import this rule in your own site. If you're using other machine names, just adapt the machine names prior to importing this rule (and apply similar changes in the fields mentioned in the Rules Action).


How to resolve conflict between zen theme breadcrumb function and Path Breadcrumbs? Apparently there Path Breadcrumbs module and the Zen theme's breadcrumb append title option have a conflict where the Path Breadcrumbs module overrides the theme's implementation of the breadcrumbs. Such that when the PB module is enabled, the theme's breadcrumb trail doesn't append the title to the breadcrumb trail. This leaves me with three options: 1) hack the theme breadcrumb implementation to re-add the titles, 2) implement views page breadcrumbs in code; 3) implement path bread crumbs for all of my pages. None of these options seems particularly pleasant, but I think approaching the theme breadcrumbs will be the least work. Any ideas? or simple workarounds?

So, more obvious than I'd like to admit: there is a Path Breadcrumbs settings tab where you can configure the theme settings as well as per theme breadcrumb settings. Enabling the theme breadcrumbs for my custom theme solved the problem!.


Views slideshow z-index I have view slideshow setup (with views slideshow module)  to display some fields (image, title, node teaser) on very top of content area on front page. Also i have drop-down menu setup (with nice menu module).
Now, when menu is expanded it goes over slideshow fields, but when slideshow auto-rotates it then position it self in front of menu and never go back again (until i reload page). I tried to solve this with z-index with no luck.

here is a screen shot when image go in front of menu.

Any one had same problem? Can any one point me in right direction?

Try adding a "display: relative" to the outer div that wraps the slideshow.


The path admin/content/files is missing in Drupal 8.5 I have installed Drupal 8.5 and today I realised that the tab admin/content/files is missing. Thanks to my backups I realized that this tab link is already missing since the 14th of March. Prior to the disappearance on the link I did not install any module. How can I solve this issue?

I had the same problem and was because the route that creates the page (view.files.page_1) was not recognized by Drupal. Why? I don't know, but I reinstalled the Views UI and the Views module and the problem was solved.

You can read about this problem in Add Item for Files under Content Menu and this is why we added in the Admin Toolbar module a validation for the route. The file module can be installed and the route can be missed from the site.


How can I add custom markup with a theme function? I have a simple form as follows

function MY_MODULE_form($form, &$form_state) {
  $form['MY_MODULE']['message'] = array(
    '#type' => 'markup',
    '#markup' => 'My Heading',
    '#tree' => true,
  return $form;
}

But I want the markup to change depending on some factor which will be defined inside a function.

So how would I call a function to do this for the #markup ?

To do this the drupal way, you should use a theme function:

function MY_MODULE_form($form, &$form_state) {
  $form['MY_MODULE']['message'] = array(
    '#theme'    => 'mymodule_markup',
    '#var1'     => $var1,
    '#var2'     => $var2,
  );
  return $form;
}

Then implement hook_theme:

function MY_MODULE_theme() {
return array(
  'mymodule_markup' => array(
    'variables' => array('var1' => NULL, 'var2'=>NULL),
  ),
);

}

Then implement your theme function

function theme_mymodule_markup($var1, $var2) {
    return 'some string';
}

You also could use a template to render your markup. That way themers can overwrite your markup without having to dig into your module files.


Custom block disable caching? I've created a custom module to show On This Days in a block but they are not changing each day until I flush the caches.
I call the entity:
public function build() {
    $query = \Drupal::entityQuery('node');
    $query->condition('status', 1);
    $query->condition('type', 'on_this_day');
    $query->condition('field_filter_date', '-' . date("m-d"), 'CONTAINS');
    $entity_ids = $query->execute();

...
and then return from the build function like this:
return array(
        '#markup' => $content,
        '#cache' => array(
            'max-age' => 0,
        ),

Any ideas?
I'm thinking entity cache or something but I'm quite new to this and not too sure

The way to invalid the Cache in a Block is with
  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 0;
  }

This comes from BlockBase


Redirect user to previous page after registration I'd like users registering on my website are redirected to the page where they clicked the "create account" button which is in a modal.

First, I tried to redirect to an absolute url
I tried

$form_state->setRedirect($myUrl);

I tried

$_REQUEST['destination'] = '<front>';

I tried this too :

$response = new \Drupal\Core\Routing\TrustedRedirectResponse('http://www.google.be');
$form_state->setResponse($response);

I'm always redirected to /user/[uid]/edit

You could use Rules module to achieve that..


Use GMaps with just one country I would like to have a map on my website displaying all my stores. That worked out pretty well except for the fact the map is displaying more then just my country.
Is there a way to just show one country?

I made the map undraggable and users are not able to zoom, so the map is pretty much fixed but still, I would like to just show my country.

Is this possible with macro's? And if so, how do I create them?

EDIT:

So my country is Belgium and I would like to hide France and Germany (and if possible highlight Belgium...)

You can not do it through macro's but alternatively you can set the zoom option for the map.

Go to Gmap Setting and set the Default zoom option to your requirement.

Hope it works for you!


How can i change the html generated of filter field of views? Mi problem is that my field (Filter Date-Popup of views) have the following html:

    <input type="text" maxlength="30" name="date_filter[value][date]" id="edit-date-filter-value-datepicker-popup-0" size="20" value="" class="form-text">
 Format: 2012-09-17

But, in only need the following portion of this html:

    <input type="text" maxlength="30" name="date_filter[value][date]" id="edit-date-filter-value-datepicker-popup-0" size="20" value="" class="form-text">
 Format: 2012-09-17

I try to do with create a template of the filter. With the Theme Information and rewrite the output of this HTML but doesn't work.

I work with Drupal 6 and Views 2

How can i do this? Thanks :D

On Drupal 6, if you don't want to work with tpl, you can use Semantic Views.


Receiving XML Posted data I have a question about what would be the best way for a module to accept a posted XML file via a web service.  What I am trying to do is receive the file, read through the contents of the file, and update a setting on my site via the contents of the file. Could some one point me in the right direction?

This isn't something I've tried myself, but if you create a form with a file element, you should be able to control the $_POST['id'] that Drupal looks for by manipulating the id of the file-element.

That way the file should get passed on to the forms submit function, and then you can do whatever you want with it's content and react accordingly afterwards.


How to use URL-based AJAX in Drupal 7 to serve all pages? I know this can be done through jQuery alone, but I'm interested in knowing if there any Drupal 7 ways of achieving this:

I want to use AJAX to serve all non-admin pages on my site. Also I don't want it to just replace parts of a page, but load entire pages over AJAX. The AJAX Framework allows loading partial contents over AJAX based on various triggers. But I want to make a URL based navigation system.

Here are the things I want to accomplish:

Redirect http://example.com/node/1 to http://example.com/#!/node/1. So search engines can index the node normally.
Drupal reads the string from URL (node/1) and fetches the relevant string in json format.
Insert the resulting data into page and replace existing content.
Refreshes blocks that should appear on the corresponding page.
Refreshes title in browser (optional).
Needs to work with Panels.

If I create a new module, what functions and/or frameworks in Drupal can I use to make this work?

Thanks.

-Kaustav

I'm searching also a solution to do that. I would like to allow users to choose witch content type is displaying in a region.

I started by create one block by region and inside I put different functions like the following one to get different content.

node_view_multiple(array($node->nid => $node), $display_type); // To get a node.
module_invoke($module, 'block_view',$delta); // To get a block.
panels_mini_block_view($minipanel_name); // To get a mini panel.

Now, with the CSS ID of the block, I will try to refresh them using AJAX link.
I think I will have to override all the links of Drupal to somethings like main/nojs/#div_region_id/[drupal-url] (e.g. main/nojs/block-content/node/1) and add them a class="use-ajax".

The management what is refresh will be in ajax_callback_response().

$commands[] = ajax_command_html('#block-content', $output );
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

Another way may be also with the Content page module.


how to get the absolute path for files based on fid How can i get the absolute path for a file based on the fid? Sorry if this is a repeat, I did a search but was unable to find the answer.

Drupal 7

This is a two part process, using file_load() and file_create_url()

First, you need to turn the $fid into a Drupal URI:

$file = file_load($fid);
$uri = $file->uri;

Now, you can turn this into a URL

$url = file_create_url($uri);

file_create_url() always creates an absolute URL, either using the global $base_path that you have defined, or using the one that Drupal guessed during bootstrap.


FAPI #required and hook_form_validate ? I made a custom form using FAPI (Drupal 7), with '#required' attribute in some form elements.
Besides this, I use hook_form_validate() to check some business rules.

The point is at first submission, required fields appears red-bordered, but still no error message.

On second submit, the error messages appear with both required and business rules .

Is there a way, to have the second behaviour on first attempt ?

Thank you.

This behaviour is usually caused by the form being rendered too late in the page build process (for example by calling echo render(drupal_get_form('form_id')); directly in a template file).

By the time the form submits, the session messages have already been prepared for rendering, and so when more messages are added by your form's validation, they don't display until the next page load.

Without knowing exactly where you're rendering/preparing the form is hard to offer advice on how to fix it. I think it would suffice to say that if you're rendering the form directly in a template file, you should move it to a preprocess function at least.

The better way would be to prepare and render the form at the module level, rather than the theme level, as that will be processed early enough in the page load for this problem to disappear.

To address your comment:

I think the problem is definitely where you're calling the form building function from. You should be able to just take that code and put in a preprocess function, preferably in a module file as that pretty much guarantees the call won't come too late:

function MYMODULE_preprocess_page(&$vars) {
  if ($_GET['q'] == 'some/path') {
    $vars['the_form'] = module_invoke('my_module', 'block_view', 0);
  }
}

Then just print it if it's available in page.tpl.php:

<?php if ($the_form): echo $the_form; endif; ?>


How to theme single node differently to nodes in taxonomy list? I'm editing node.tpl.php, to apply custom theming when the site displays single nodes.

However, if I browse for a certain taxonomy term, the list of nodes presented is also affected by my changes.

Is there a way to theme just the single node pages?

You have access to the $page variable in your template file; if the node is being displayed in a full page this variable will be TRUE, and FALSE otherwise.

If you look at the core node.tpl.php file you can see it too takes advantage of this:

<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>

That's used to only display a title on the node if it's not the main page display.

You also have access to a $view_mode variable if you want to be more specific about the particular view mode, e.g.:

<?php if ($view_mode == 'teaser'):
<?php // print something ?>
<?php endif; ?>


Group results of same taxonomy term with search api and views I have couple of products which are classified with taxonomy terms.

I am using Search API with views to display search results.

I want to show the search results in this way.

Term 1 Name

product 1
product 2
product 3

Term 2 Name

product 5
product 8
product 3

Term 3 Name

product 10
product 25
product 1

What should I look into? Any idea how canIi group the results based on the term?
Thank you.

Open your views, in editing mode , in formatting section, near table, select settings,
and then in Grouping field Nr.1 select your taxonomy field ,save ,it makes the views result goruped by selected field in Grouping field Nr.1.


Request header field X-CSRF-Token is not allowed by Access-Control-Allow-Headers in preflight response for Drupal 7 REST API I have few APIs created in Drupal 7 which uses session authentication. Now when I get the CSRF token and try to use it in my API call, I get following error:
Request header field X-CSRF-Token is not allowed by Access-Control-Allow-Headers in preflight response.

Here is my javascript code:

var url = "http://dev/api/v1/macc/*";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(xhttp.responseText);
    }
};
xhttp.open("GET", url, true);
// xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.setRequestHeader('X-CSRF-Token', 'xxxxxxxxxxxxxxxxx');
// xhttp.setRequestHeader('cookie', cookie);

xhttp.send();

If I run the same API from Advanced Rest Client, I get the correct response.

Any help will be appreciated.

Have a look at cors module
You'll be able to add necessary Access-Control-Allow-Headers

Otherwise, you can do this by changing your apache (or nginx or whatever) conf.

In drupal 8, you define this in services.yml, as explain here.


A select list of user created nodes I am creating a commerce store for custom clothing. I am trying to implement a product line item where users are posed with a dropdown of their uploaded artwork via a select list. I have created a content type called artwork that users will create. Now I just need to create a field that is a dropdown list of user-created nodes of artwork type. Does anyone know how to implement this?

Depending on the purpose of that dropdown, you should have a look at the entity reference module. Here is an excerpt about it from the module's project page:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

  Two implemented on top of the Options module (Select and Radios/Checkboxes),
  Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

  Two formatters:

  A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.)
  A "Rendered entity" formatter, that renders the references entity using a configurable view mode

  Integration with Views (for both forward and backward references)
  Integration with Entity Metadata (and as a consequence with Search API and the like)
  Integration with Devel generate
  Integration with Feeds and Migrate (>= 2.3) for painless data import


Ubercart Authorize.Net checkout loops back to cart page I am trying to process an Ubercart order using Authorize.Net. I go through the Checkout and Review pages. When I submit the cart for credit card processing, I get returned to the Checkout page.

The only error I can find is:
    page not found  09/23/2014 - 17:39  cart/sites/all/themes/metroblocks/images/int.png

I think maybe the cart solution has an incorrect relative path somewhere to go to cart/../sites/all....

At one time I tried getting Commerce to work, but couldn't install Kickstart. I deactivated Commerce, but didn't uninstall it. Don't know if there is a conflict between Commerce and Ubercart.

Could someone please explain how I might troubleshoot/resolve this issue?

Using Drupal 7.32, Ubercart 3.7 on a shared hosting server, Apache2.

I reinstalled Drupal, and it was able to identify the missing image files. It was an issue with Drupal after all. Good thing I don't get dismissed so easily.


Child navigation sidebar or drop-down navigation displaying child items I have a 'basic page' which is a parent and is provided a menu link. This page has several children (subpages).

How would I display the subpages for each nav item either in the following cases?

Drop-down menu from the main navigation menu, or some close alternative
Display all the children for that page in a sidebar

Drop-down menu from the main navigation menu, or some close
  alternative

Use Superfish. It integrates the jQuery Superfish dropdown plugin with your Drupal menus.

  Display all the children for that page in a sidebar

Use Menu Block. It provides configurable blocks of menu trees starting with any level of any menu. And more!


Drupal site communication with other site Hello I have a Drupal 7 site.
I want users to login without using the drupal form.
I will silently send username and password credentials from another site and when users click the link to my drupal site they will be already logged in.
So how to communicate with drupal login and send the details of the user from another site or maybe a browser plugin or a PC application etc.

This is a fairly complicated thing to do, but the "go to" module for handling integration with third-party sites is the services module.


How to print taxonomy term name with published node count and with a custom link? How can I print taxonomy name with published node count with a custom link?

eg: Taxonomy term-a (23) Taxonomy term-b (10) Taxonomy term-c (55)

I need to link each of them to a separate page.

I found this below code to print taxonomy term with count. but now how to make to print specific taxonomy term with it's node count? so that I can link it to a page later, so if I repeat the same code with different term ids to have multiple terms with its count.

    <?php
$vid = 23;  // Set the vid to the vocabulary id of the vocabulary you wish to list the terms from
$parent = 130;

$terms = taxonomy_get_tree($vid, $parent, -1, 1);
foreach ( $terms as $term ) {
  $count = db_result(db_query("SELECT COUNT(n.nid) FROM {node} n INNER JOIN {term_node} t ON n.nid = t.nid WHERE t.tid = %d AND n.status = %d", $term->tid, 1));
  {
    print '
' . l($term->name, "taxonomy/term/$term->tid") . " ($count)"  . '
';
  }
}
?>

Can someone please help me?

__HAD TO ANSWER HERE AS I CAN'T AT THE BOTTOM__

This is it!!!

Took a while to write this code... :(

<?php
$tid = 100;
$term = taxonomy_get_term($tid);
$name = $term->name;
$result = db_result(db_query("SELECT COUNT(n.nid) FROM {node} n INNER JOIN {term_node} t ON n.nid = t.nid WHERE t.tid = %d AND n.status = %d", $term->tid, 1));
print '
' . $name. " ($result)" . '
';
?>

Change: 100 at the second line of above code to your specific taxonomy id, that's it and repeat the same for different tid.

And make sure to change the link at the bottom from (http://example.com/) to your (custom link).

Thanks a lot to all, let me know if this code can be fine tuned further...

Although it looks like you have come up with a solution, you might want to compare against the Taxonomy List module.


How to disable AVS check in commerce cybersource SASOP Using Commerce CyberSource SASOP it is possible to ignore the results of AVS verification?
There is an option for this as specified in the CyberSource Development Guide on the page 74.

It is possible to add parameters to the data using hook_commerce_cybersource_sasop_transaction_data_alter($data)

<?php
my_module_commerce_cybersource_sasop_transaction_data_alter($data) {
  // Ignore AVS check
  $data['ignore_avs'] = 'true';
}

Issue in Drupal.org


Changing form field title within hook_preprocess_form() does not work I have customize drupal user registration form which I want to change some field titles.

I implemented hook_preprocess_form() within theme and changed titles of some form fields, but it didn't work.

While debugging I found that it has '#children' item already there with rendered HTML inside it. Then I tried to change that value by using drupal_render_children(), but that also doesn't work.

What is the right way?

Use hook_form_alter() to change the form before it gets rendered.


aligning nodes in views grid style i need help aligning nodes in the views grid style. Each of my rows has 2 nodes but the problem am facing is that they are not aligned. in each row one node is slightly higher than the other. How can i create fixed grid dimensions so that each row is inline?

I use the ccs_injector module to add css snippets to fix alignment issues like the one you described.

For example, the css I used to assign even widths on a 4 column grid and to vertically align the content:

td.col-1, td.col-2, td.col-3, td.col-4 {
width: 25%;
vertical-align: top;
text-align: center;
}


Views calender missing menu tabs I cannot get my Views calendar to have the tabs (e.g. Month,Week,Day,Year) in the upper left corner like the below image:

How do I get those tabs to appear?

In case anyone is experiencing the same problem:

1) Go to each display's Page Settings.
2) Set the Path $path/week, $path/month, etc., where $path the respective path you have in the month display.
3) Set the Menu Type in Menu to Menu Tab.

Save view and clear caches.


in teaser view, truncated body is displayed instead of summary My content type has the following settings for body field in "Manage display" tab, for "Teaser" display mode:
Label: Hidden; Format: Summary or Trimmed, Trim length: 2000

However, the summary is never actually displayed in Teaser mode, only trimmed body.

For example, in node edit form, after clicking Preview, the Teaser preview clearly displays an automatically truncated beginning of the body. The summary was entered, but is not displayed in preview.

The same in a View, the format is set to show Content, Teaser. Again, the summary is not taken into account, only the body field.

What to check, how to fix this??

In the Manage Display settings for the content type, choose 'Summary or Trimmed' this way if a summary is provided it will display that. Otherwise it will display a trimmed version of the body.

You can download other formatters, i.e one that will strip tags and trim on a word boundary. By default the trimmed function will always split on a paragraph.


Render paragraph reference field in page.html.twig In page.html.twig I want to show a paragraph reference field which contains a left and right text_field.

The name of the reference field in the node is: field_intro. That field is linked to a paragraph type named: text_left_right

Using below code I can render the paragraphs, but if I add an extra field to the paragraph type, it is not updated. I would like to render all fields, even if I add a new field in the future.

That is not going to happen with this piece of code:

{% for item in node.field_intro %}
  {{ item.entity.field_left.value }}
{% endfor %}

I found a lot of answers for rendering in node.html.twig but not in page.html.twig.

UPDATE after below comments and answer:
It is not recommended to print fields in a page.html.twig page. Better use views or blocks to establish what you need. And if you want to use templates, use node.html.twig.

but if I add an extra field to the paragraph type, it is not updated.
  I would like to render all fields, even if I add a new field in the
  future.

To answer the question, you just need to loop though the paragraph fields.

{% for item in node.field_intro %}
  {% for paragraph_field in item.entity %}
     {% if 'field_' in paragraph_field %}
       {{ paragraph_field.value }}
     {% endif %}
  {% endfor %}
{% endfor %}


How do I disable modules via admin interface or via Drush? In Drupal 7 it was possible to disable modules via admin interface or via Drush drush pm-disable. In Drupal 8 the checkboxes are greyed out in the admin interface and Drush is not able to disable them via pm-disable? How do I disable modules in Drupal 8 with Drush or via admin UI? Or do I need Drupal console for such tasks?

(Sorry for the confusion caused by using the word "programmatically" mistakenly, it was referring to the meaning of "via command line")

Like the admin interface in Drupal 8 states in the message area, the paradigm and concept of how modules get installed and disabled has changed in Drupal 8, since there were many problems involved in the way how it was before, because of Database left-overs and data inconsistencies while disabling and enabling modules, etc.

Therefore users are encouraged to rather uninstall modules than disabling them now in D8. This doesn't mean the modules are gone or removed from the Drupal root, but they are completely removed from the database including their configuration.

Try drush pm-uninstall module-name instead and you will see the desired effect you are after.

The checkboxes are greyed out to be still able to enable and install inactive modules the way known from D7. But you can't disable them this way no more. And uninstalling should not be provided by checkboxes, since this would be to dangerous.

Look twice in the admin interface: You will find a new tab for uninstalling modules too.


Altering a Drupal Commerce Form I can't figure out how to alter the drupal commerce form. I created a module with a .module and .info file and have enabled 'devel'. I've also enabled this module. However, when I use the following code, or derivations thereof, no message appears in the message area no matter how many times I refresh the page. I've flushed caches and made sure $messages is set to display on the template.

<?php
  function module_name_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == "commerce_checkout_form_checkout") {
      dpm($form_id);
    }
  }

Anyone know what the problem is here?

Try hook_form_alter() like this;

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_form':
      ...
    break;
}


"Save Configuration" in Drupal 7 Module not visible I inherited a customized Drupal 7 site and am trying to add some things without a lot of knowledge of how drupal works (I have general html/css/JS, and some classic ASP, .Net experience).  I was able to install a couple of modules (Widgets, Widgets Service Links, Widgets Services  - for Social Media buttons) but can't seem to enable them.  They have dependencies with each other, but they are all there.  I can click the check boxes but I see no where to save the enabling of the modules.  According to what I see out there, there should be a Save Configuration button, but it is not visible to me.  We have a couple of security updates that we haven't done, but when we did these previously they mucked up our configuration so we decided to hold off on them until we know what we're doing a bit more (we were able to restore from a backup).  Could the security update alerts be preventing the saving of modules?  That's the only thing I can think of other than our whole configuration being messed up somehow?

Sounds very much like a custom module is hiding the module save button to stop people adding/changing things. I've had the misfortune of inheriting sites with these sort of "security features" before too.

If you do have any custom modules installed. the simplest thing you can do to test is get Drush installed, run drush dis CUSTOM_MODULE and check to see if the button comes back. Then you'll know if it's the custom module's fault at least. You can also disable them manually in the system table but you should only do that if you really know what you're doing.

The upshot of that is you can also use Drush to install the other modules outside of the UI, so even if that's not the problem you'll still be able to install new modules.

Also, to find out if a change to core files is responsible for the problem, grab the Hacked module and run a report. If you install the Diff module along with it you'll get a side-by-side diff of exactly what has changed in core/contrib modules.


Email marketing in Drupal 7 I have a site with articles which has an RSS feeds.
I 'd like visitors to be able to subscribe to those articles using their email.
They ll give their email and then new articles will be sent to their email.

I m using feedburner to email right now, but I dont like it at all.

How this can be done in using Drupal modules and an SMTP server?

What technology is stackexchange.com using for the email notifications?

See Messaging and Notifications framework.


How to edit Menu primary nav tab in Drupal 8 Page contains two nav bars with primary having View, Edit, Notes, Resend, Devel tabs and a secondary nav bar with Definition, Render, Load, Tokens. I am using css to not display particular tabs in primary and totally hiding the secondary nav bar. But, one of the requirement is to edit the name of a tab. I tried using theme_preprocess_menu_local_task hook but I am not able to edit the protected object values. What is the approach I need to take to edit the name of the tab. In this case 'resend' to 'forward'.

    function theme_preprocess_menu_local_task(&$variables) {
     if($variables['item']->text =='Resend'){
        $variables['item']->text = 'Forward';
     }
    }

the above code bombs with error saying protected values cannot be accessed.

You may wish to use hook_local_tasks_alter() and/or hook_menu_local_tasks_alter() to hide/rename local tasks.


is there a way to know witch module is responsible to programmatically alter a view's query? I have a view that diplays some orders with a filter by current user if he is owner of the order or not ..

If the current user is admin, i can see my orders with no problems.
If im logged in with another role the view is always empty althought im ordering products with that user.

I doubt about the view access, or some modules permission (for example if this role has the permission to view his own orders or if he has permission to view his own product ...) I checked these permissions carefully, but the view result still empty.

when I debug the query I get inside where clause an additional condition that's applyed only for non admin users :

  (AND 1 = 0)

as you know this condition returns always false, so that's why the result of the query is empty.

Is there a way to know from where is coming this condition when im logged in with a non admin role ?

Thanks in advance.

Interesting question / challenge, not obvious to debug ...
Here is what I would do, in the order specified:

Scan the entire modules directory for a string containing '1 = 0'.

Scan the Drupal database (all tables) for a string containing '1 = 0'.

If none of both scans lead to any results, I'd consider using the X-ray module, to check if that would help me any further. Some details about this module (from its project page):

X-ray module gives a look at the skeletal structure of a site to help developers and site builders see how things work.
X-ray Features:

A technical summary is added to the help above the main administrative sections. For example, blocks, content types, and menus are summarized on Structure; themes on Appearance; etc.
A table of permission titles matched to their permission machine names.
A table of most* hooks which Drupal invokes (and when they are invoked) and that are available to be implemented.
The function and arguments producing each page you visit, displayed on that page.
The form ID of every form you see, displayed on the form.


How to move the content of 'Node content' display (Views) to the end of a view? I installed the Answers module and I am trying to edit the question_answer view. Basically I would like the answers (which are generated by the 'node content' display) to appear below the question. This is done by default by the module: See Picture.

The problem is that I would like to move 'Post an Answer' link before the list of answers. Now it works as follows
- Question Header
---List of Answers
---- Question Footer

and I would like to change it to
- Question Header
---- Question Footer (or just the entire Question node)
----List of Answers.

I know that's because the display is "Node Content", but I don't know how to do it properly. I've tried with Attachement, Blocks and no success. You can find the screenshot of the view settings here (Default view has the same values as Node Content Display)  Any advice greatly appreciated.

Have you tried playing with the "Row style" setting ? You could change it to "Fields" and select the node:title, node:body, node:nid and node:answers (?? does that exist ?? I'm guessing that answers are just comments, right ? In that case, node:comments).

Output them in the order that you want, but rewrite the node:nid as a link to the "post answer" url. I don't know this module, but say the answer url is node/xxx/answer, you can rewrite the node:nid field as

Post your answer


(Good or bad?) Calling a Function in Template File which returns a theme() Function value I have a function which get some values from a Term, calculates something and at the end of my function, there is a statement like this:

return theme('foo', array('bar' => 1);

This function is in a self-written module. In the same module, I've got a template file.

Now my question: is it good or bad Practice to call the function which one I describe above in the template file? I know that I could calculate all this before calling the template file, but with my solution, the could would be more readable.

Thank you in avantage for inputs.

If you are asking about calling theme() from inside a template file, that is possible, but it is rarely done: Out of 214 calls to theme() done from Drupal (and the Views module) only two calls are done from inside s template file.

This is the code used in the default implementation of page.tpl.php; similar code is present in the implementation of page.tpl.php for the Bartik theme.

<?php if ($main_menu || $secondary_menu): ?>

    <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Main menu'))); ?>
    <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Secondary menu'))); ?>

<?php endif; ?>

What you should do is initializing a variable in the preprocess function for the template file, and use that variable in the template file.

Truly, you should not put logic code in your template file; this means that, for example, code similar to the following one should not be used in a template file.

<?php if ($condition1): ?>
  <?php print theme('theme_1', $values1); ?>
<?php elseif ($condition2): ?>
  <?php print theme('theme_2', $values2); ?>
<?php elseif ($condition3): ?>
  <?php print theme('theme_3', $values3); ?>
<?php endif; ?>

If the code is similar to the following one, then it would be more acceptable, but I would still think of possible future versions of the code, and prefer using a variable in the preprocess function.

  <?php print theme('theme_1', $values1); ?>
  <?php print theme('theme_2', $values2); ?>
  <?php print theme('theme_3', $values3); ?>


Setting exposed filter default value from query string I have a view which show products and an exposed filter block (category, manufacturer, price).

I want to set category default value from URL, like this:

/browse-products/category-id

though, I wrote this module which take the parameter from URL and put it into exposed filter default value.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $request;

  if ($form_id == 'views_exposed_form') {
    $category_id = (int)($request->attributes->get('_raw_variables')->get('arg_0'));
    $form['category_id']['#default_value'][$category_id] = $category_id;
    dpm($form['category_id']);
  }
}

dpm output for /browse-products/5

Array
    (
        [#type] => checkboxes
        [#multiple] => 1
        [#options] => Array
            (
                [5] => Tablets
                [10] => -Ainovo
                [7] => -Galaxy Tab
                [6] => -IPad
                [1] => Smart Phones
                [4] => -Galaxy
                [3] => -IPhone
                [9] => --IPhone C
                [8] => --IPhone X
            )

        [#size] => 9
        [#default_value] => Array
            (
                [5] => 5
            )

        [#bef_nested] => 1
        [#theme] => bef_checkboxes
    )

but it doesn't work?

another thing, why dpm($form) prints the views exposed form data twice!

update 1: I tried something like this (but didn't work):

function mymodule_views_pre_build(Drupal\views\ViewExecutable $view) {
    $view_filters = $view->display_handler->getOption('filters');
    $view_filters['field_category_target_id']['value'][8] = 8;
    $view->display_handler->setOption('filters', $view_filters);
}

or this:

function mymodule_views_pre_build(Drupal\views\ViewExecutable $view) {
  $filters = $view->getExposedInput();
  $filters['field_category_target_id'] = 8;
  $view->setExposedInput($filters);
}

The #default_value parameter should be set to the key of the select list array.

Example:

$form['category_id']['#default_value'] = $category_id;


Where does location cck module save the data? I've gone through the code in modules/all/location/contrib/location_cck but am unable to figure out where this CCK field is storing the address data.

I guest that it's install file should have table fields to store geographic data like city, lat long etc. But it isn't there.

Edit: Ultimately I want to access all those location fields separately(beyond Views) when writing modules etc. For example I want to read postal code attached to a particular node for some analysis. That's why I'd like to extract location info about nodes.

As mentioned, the data's stored in the location table, which is handled by the location API and indexed by location ID (lid). The CCK field stores an lid. If you have access to the node object with the field, then you can access the address fields directly from the node object. If you don't have the node object and want to avoid the cost of loading lots of nodes, you can get the CCK DB details using content_fields($field_name, $content_type_name) and content_database_info($field). Then you can use location_load_location($lid) to get the location. I've just taken a quick look at the source for location_load_location() and note that it might do JIT geocoding (so it might actually write as well as read!). I imagine you won't have any issues with doing a join directly on the location table, but I always prefer to use the API where possible.

There's also the command location_load_locations($id, $key) which looks like it can give you all locations associated with a particular nid or vid, but I don't think that's what you're after.


How to add custom login logout links in Bootstrap theme? I am new to drupal, but I had a requirement, my current site using bootstrap theme. Previously there was no login and logout buttons on header. Today I got html login and logout strip from desinger. For this I have created a new block and selected bootstrap region as Navigation. Now this custom header perfectly sits at the top of the page. with static Myaccout, Logout , contactus  which are sent by desinger.

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>

Navigator

Contact Us

 My Account

 Log Out

But my question how to make that header dynamic like when user with out login need to show Login , and after login need to show myaccount and logout. Above code is the static html bootstrap header sent by desinger. Please suggest me how to do this?

It can be done this way

<?php
global $user;
 if($user->uid):?>

 My Account

 Log Out

<?php else: ?>

 Log in

<?php endif; ?>

Hope it will help


How to get custom role ID from Drupal UI? Really simple, where I can I look up the custom roles and their role id's?

Not what I was looking for, but if you inspect the Roles Drop Drop on the People Page then the array has the ID in it.


How to use Drush's concurrent execution capability? I am using Drupal multi-sites (single codebase, multiple sites/*). Along with this, I have started using Drush aliases to manage them:

$ cat sites/all/drush/aliases.drushrc.php
<?php
$aliases['localdev'] = array(
  'site-list' => array(
    'site1',
    'site2',
    'site3',
  ),
);
?>

This allows me to easily perform actions on all sites:

$ drush @localdev cc all

>> I've also just discovered that I can just use @sites, and forgo the drushrc file.

Doing this, will execute "cc all" on each of my sites in series (one at a time).

I'd like to take this to the next level and try to run these commands on all sites simulantiously. I've been doing some reading, and am under the impression that Drush does indeed support this. The drush_invoke_process() function takes $backend_options, which can contain (from function documentation):

 *      'invoke-multiple'
 *        If $site_alias_record represents a single site, then 'invoke-multiple'
 *        will cause the _same_ command with the _same_ arguments and options
 *        to be invoked concurrently (e.g. for running concurrent batch processes).
 *      'concurrency'
 *        Limits the number of concurrent processes that will run at the same time.
 *        Defaults to '4'.

What I can't figure out, however, is how do I actually use this from the Drush command line. Is there an option I need to pass to Drush, or do I need to set something in a settings file?

Any info will be much appreciated - my curiosity is piqued!

UPDATE

Based on the answers below, I was able to create a simple test that demonstrates Drush's behaviour, and draw some conclusions:

Drush's default behaviour when executing operations on multiple sites is to use concurrent processes:

$ drush @localdev ev "drupal_set_message(time()); sleep(5);"

Continue?  (y/n): y
site1             >> 1360512943      [status]
site2             >> 1360512943      [status]
site3             >> 1360512943      [status]

This is true even when not using aliases, and is also true when using Drush's built-in @sites alias. These two commands yield identical behaviour as above:

$ drush site1,site2,site3 ev "drupal_set_message(time()); sleep(5);"
$ drush @sites ev "drupal_set_message(time()); sleep(5);"

To change the number of concurrent processes (default is 4), the '--concurrency=N' option can be passed in the drush command. For example, if I want serial execution, I can set the number of concurrent processes to 1:

$ drush @localdev ev "drupal_set_message(time()); sleep(5);" --concurrency=1

Continue?  (y/n): y
site1             >> 1360513387      [status]
site2             >> 1360513393      [status]
site3             >> 1360513399      [status]

This worked for me:

drush @site1,@site2,@site3,@site4 cc all --concurrency=4

I'm not sure how concurrent it actually was; the last message about site1 came immediately after the first message for site2, and all other messages were printed sequentially.  I did not measure to what extent each cc operation happened concurrently, or to what extent the system might have just been cpu or i/o bound, but it did seem to be nominally working.


Different front page template for different domains I have Drupal 7 installation with the Domain Access module.

I need to have different page--front.tpl.php templates for some of the subdomains, for example:

www.example.com should have one type of the front page template (not a node, but some custom blocks and module outputs) and d1.example.com, d2.example.com and d3.example.com should have different kind of blocks, module outputs, forms, and template.

The style for the rest of the site should be pretty much the same for all domains.

How can I accomplish this?

You can use a combination of the Context and the Delta modules to achieve this.

You can create a new instance of a theme using delta module and use context to use that instance for a specific module.

Alternatively, you can use Domain theme module (sub module of Domain module).

Let me know if you get stuck.


Image styles deleted on node save I just created a custom module following this tut:
generate-programmatically-image-styles-drupal-8

It works great but the following occurs. When I create a new node and upload the image you see that for every style I have it creates a image (like the custom module should). But when I save the node all the created images are deleted?

Is this a standard function in Drupal that can be disabled? Hope someone can help me with this.

Thanks in advance

It turns out that image_path_flush() is being fired in Drupal\file_entity\Entity\FileEntity->postSave() even when the image is not actually updated. You can see the issue and proposed resolution outlined here: https://www.drupal.org/project/file_entity/issues/2816761


Page cache not rebuilding after page cache maximum age is reached I have a pretty minimal Drupal 8 install with some views blocks that show upcoming event node links. I've noticed that once an event is passed they still show up and it is because the pages of my site are cached. However, I set the "Page cache maximum age" on the performance page to 6 hours and Drupal continually caches pages for days or weeks. I have to manually click clear all caches before the site will update. Cron is also setup and running regularly without a problem. I thought maybe that triggered the cache rebuild but I've set it to 6 hours, 12 hours, 3 hours, etc. with no result.

I'm not sure why this is happening. I'm not doing anything else to cache, no other modules or server programs like Varnish or anything.

The Internal Page Cache for anonymous users doesn't use any configuration option. If you want a quick solution in UI your only chance is to de-install this module.

Better for performance is to set an expiration time for the cached pages, but for this you need custom code, see this answer Anonymous user cache control.

In both cases the setting on the performance page is still necessary to set the correct headers for external caches.


How to display nodes based on the taxonomy terms of the current logged in user, with multiple vocabularies? Say I have 3 taxonomy vocabularies:

Products, Professions and Support

Each vocabulary has 2 terms:

Products -> product1, product2

Professions -> profession1, profession2

Support -> support1, support2

Users can be tagged with terms. User A is tagged with:

product1 and support1

Nodes can be tagged with terms. Node 1 is tagged with:

product1

Node 2 is tagged with:

support1

Node 3 is tagged with:

profession1

So when User A logs in and goes to the view, they should see Node 1 and Node 2 only. I can't seem to achieve this in views. It's possible when there is just one vocabulary, but i can't seem to get it done when there are multiple vocabularies involved. Can anyone help without coding? Or perhaps I need to use code?

Did you try this using fields instead of taxonomy? I personally prefer using fields over taxonomy since fields are more flexible with views. In your case, if your site is still under development I suggest you to use fields and try out the same.


How to replace authentication links with custom routes? I am working on a custom Drupal 8 module that has its own authentication form.

For this, I created a Drupal page with the custom authentication form, i.e. I have a route at drupalsite.com/custom-signup

What I am not able to figure out is how can I replace Drupal's default Register and Login links which are scattered everywhere on the website to point to above route. I don't want to redirect from /user/login page to /custom-signup as I still want to allow admin to login. For all other users except admins should be redirected to \custom-signup.

I could use jquery to brute-force my way to replace the links, but is there an efficient way to achieve this?

TL;DR: I need to replace following default Drupal links using my module.

Update:

Following the first solution, I added the routing files as follows, the links are redirecting me to my custom form.

However, when I try to enter user/login manually in the URL, I get page not found message on the website.

You need to alter the route, in your custom module add:

mymodule/src/Routing/RouteSubscriber.php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change path '/user/login' to '/customn-login'.
    if ($route = $collection->get('user.login')) {
      $route->setPath('/custom-login');
    }
    // Change path '/user/register' to '/custom-signup'.
    if ($route = $collection->get('user.register')) {
      $route->setPath('/custom-signup');
    }
  }

}

mymodule/mymodule.services.yml

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

For more in depth information, see Altering existing routes and adding new routes based on dynamic ones.

If you still want /user/login to work, then you can create a new route for it.

mymodule/mymodule.routing.yml

mymodule.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

Remember to clear all caches to see changes.


How to hide all tabs (local tasks) except the user account tabs? I want to hide all tabs (local tasks) for non-admin users except the tabs on the user account page (for example, I want to hide tabs on nodes of all content types).

To hide the tabs, I added a check for admin permission in my theme template: templates/menu/menu-local-tasks.html.twig

{% if user.hasPermission('administer nodes') %}
  {% if primary %}

{{ 'Primary tabs'|t }}

{{ primary }}

  {% endif %}
  {% if secondary %}

{{ 'Secondary tabs'|t }}

{{ secondary }}

  {% endif %}
{% endif %}

This works, but it hides the tabs on the user account page as well.

I tried to find a more specific template of menu-local-tasks for the user account. I turned on twig debugging, but these were the suggestions:

All of these affect the entire site; there is no way to target just the user account local tasks.

Is there a way to do this with theme templates?  I chose this approach rather than trying to unset the local tasks in a hook because in a template you can do it in just a line or two of code.

I wouldn't recommend not doing this by code, this can be achieved using built-in configuration settings, by using a second block with proper rules. Try this:

Go to Structure > Block layout
Select your theme
Place a second tabs block where-ever you want it
Limit the visibility on the block fitting your requirements

Most likely limit Pages to something like user/*
and by Roles, e.g. Authenticated user
(remember that administrators are authenticated users too, so you might need more specific roles to to prevent admins seeing tabs block twice; or add the "hide"-option on user-pages for the first, original tabs block )


How do I get the UUID of a bundle? The getBundleInfo method returns only the machine name and label for bundles.  How do I get the UUID of each bundle, or of all bundles?

Replace BUNDLE_MACHINE_NAME with your bundle machine name.

Drupal::entityTypeManager()->getStorage("node_type")->load("BUNDLE_MACHINE_NAME")->uuid();

Or you can also load it like this:

Drupal\node\Entity\NodeType::load("BUNDLE_MACHINE_NAME")->uuid();

Entities based on EntityInterface will have the uuid() method.

See EntityInterface::uuid


How to make a page where two content types are combined It should be a portfolio website. I'm going to place there information about projects I was engaged in and products I designed. The relationships between project and product nodes are those:

--Project 1
----Product 1
----Product 2
----Product 3
--Project 2
----Product 4
----Product 5
----Product 6
etc.

My question. How to create a page where placed all project articles and under each project article there should be related product article teasers. Like on image.

In views you can "Group By" the parent nodes. So if you were using entity references to do the relationship, you would have it as a field in views and group by it.

Are they different content types? How are you relating the children to the parent?

If the default Group By isn't enough, there's a module called Views Field View which can put a view inside a view but that could be a bit unnecessary.


Views Rest Export and sending page numbers in it's response I have a paginated views using "rest export" and I'm using it to show that data on mobile app, everything works fine, but I want to know how many pages exist on that endpoint to show page numbers in my app.

I know I can alter the view programmatically, but I'm asking if there is a simple solution to achieve this.

This is the view settings page.

As of now there is no way to display total page count in views rest export. But you can get total pages, current page, items per page and total number of items using new custom style in your custom module which extends existing Serializer class as shown below:

<?php

namespace Drupal\custom_module\Plugin\views\style;

use Drupal\rest\Plugin\views\style\Serializer;

/**
 * The style plugin for serialized output formats.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "custom_serializer",
 *   title = @Translation("Custom serializer"),
 *   help = @Translation("Serializes views row data and pager using the Serializer component."),
 *   display_types = {"data"}
 * )
 */
class CustomSerializer extends Serializer {

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];
    // If the Data Entity row plugin is used, this will be an array of entities
    // which will pass through Serializer to one of the registered Normalizers,
    // which will transform it to arrays/scalars. If the Data field row plugin
    // is used, $rows will not contain objects and will pass directly to the
    // Encoder.
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[] = $this->view->rowPlugin->render($row);
    }
    unset($this->view->row_index);

    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }

    $pager = $this->view->pager;
    $class = get_class($pager);
    $current_page = $pager->getCurrentPage();
    $items_per_page = $pager->getItemsPerPage();
    $total_items = $pager->getTotalItems();
    $total_pages = 0;
    if(!in_array($class, ['Drupal\views\Plugin\views\pager\None', 'Drupal\views\Plugin\views\pager\Some'])){
      $total_pages = $pager->getPagerTotal();
    }

    $result = [
      'rows' => $rows,
      'pager' => [
        'current_page' => $current_page,
        'total_items' => $total_items,
        'total_pages' => $total_pages,
        'items_per_page' => $items_per_page,
      ],
    ];
    return $this->serializer->serialize($result, $content_type, ['views_style_plugin' => $this]);
  }

}

After adding above file clear drupal cache and edit the view. There you need to change the format from Serializer to Custom serializer.

In this style there is a little difference in the output. All rows are children of rows and pager information is part of pager. Sample output is as shown below:

{
   "rows":[
      {
         "title":"Test"
      },
      {
         "title":"Test"
      },
      {
         "title":"Title 5"
      },
      {
         "title":"Title 4"
      },
      {
         "title":"Title 3"
      }
   ],
   "pager":{
      "current_page":0,
      "total_items":6,
      "total_pages":2,
      "items_per_page":5
   }
}


drush sql-sync fails drush sql-sync @devyau @stageyau returns:

Call to a member function dump() on a non-object in
/root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc, line
275

echo $PATH returns:

/root/.composer/vendor/bin:/usr/lib64/qt-3.3
/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:
/root/bin

drush @devyau uli returns:

Call to undefined function drush_sql_get_class()
in /root/.composer/vendor/drush/drush/includes
/environment.inc on line 366

drush @stage uli returns:

call to a member function db_spec() on a non-object in
/root/.composer/vendor/drush/drush/includes/environment.inc, line 370

Here's environment.inc lines 361 to 378:

/**
* Tests the currently loaded database credentials to ensure a
database connection can be made.
     */
function drush_valid_db_credentials() {
try {
    $sql = drush_sql_get_class();
    if (!$sqlVersion = drush_sql_get_version()) {
      return FALSE;
    }
    if (!$sqlVersion->valid_credentials($sql->db_spec())) {
      return FALSE;
    }
    return $sql->query('SELECT 1;');
  }
  catch (Exception $e) {
    return FALSE;
  }
}

drush ard returns:

The external command could not be executed due to
an application error. Unable to determine sites directory for
devyau. Archive saved to /root/drush-backups/archive-dump/20150703220104
/none.20150703_220105.tar.gz

drush status returns:

 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /root/.composer/vendor/drush/drush/drush.php
 Drush version          :  7.0.0
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /etc/drush/prodyau.alias.drushrc.php
                           /etc/drush/devyau.alias.drushrc.php
                           /etc/drush/stageyau.alias.drushrc.php

devyau.alias.drush.php:

 <?php
 $aliases['devyau'] = array(
 'uri'=> 'dev.[sitename]',
 'root'=> '/var/www/vhosts/dev.[sitename]/',
 'db-url' => 'mysql://[username]:[password]/devDBname',
  );
?>

stageyau.alias.drush.php:

?php
$aliases['stageyau'] = array(
'uri'=> 'stage.[sitename]',
'root'=> '/var/www/vhosts/stage.[sitename]',
'db-url' => 'mysql://[username]:[password]/[stageDBname]',
  );
 ?>

Been working on this one for a week. Stumped. Any ideas?

Your site doesn't look like it is bootstrapping completely. So I would suggest that you see if drush status will complete in the sites/default or sites/sitename folder. It should look something like the full output below.

A full drush status output

Drupal version                  :  7.38
Site URI                        :  sitename.com // could be http://default if you have not set your site url
Database driver                 :  mysql
Database username               :  db_user
Database name                   :  db_name
Drupal bootstrap                :  Successful
Drupal user                     :
Default theme                   :  default_theme
Administration theme            :  admin_theme
PHP executable                  :  /usr/bin/php
PHP configuration               :  /etc/php5/cli/php.ini
PHP OS                          :  Linux
Drush script                    :  /usr/local/bin/drush-master/drush.php
Drush version                   :  8.0-dev
Drush temp directory            :  /tmp
Drush configuration             :  /usr/local/bin/drush-master/drushrc.php
Drush alias files               :  /usr/local/bin/drush-master/includes/../aliases.drushrc.php
Install profile                 :  install_profile
Drupal root                     :  /var/www/html/docroot
Site path                       :  sites/default // Could be sites/sitename.com
File directory path             :  sites/default/files // Same thing here could be sites/sitename.com/files
Private file directory path     :  /vagrant/private
Temporary file directory path   :  /tmp

To help this is my alias setup I usually use

This is what I usually use to setup my complete drush alias, it has options that most do not need but it may help someone in the future setup their drush alias that they may have not known existed. If you don't use the "path-aliases" below then you need to use "default" or whatever the "sites/sitename" folder name is named. You can see this in the example alias file from drush.

$remote_sites = '/path/to/site'; // usually /var/www/drupal-root-name
$aliases['site.dev'] = array(
  'uri' => 'sitename.com',
  'remote-host' => '{ip to remote}',
  'remote-user' => '{remote ssh user}',
  'root' => $remote_sites,
  'ssh-options' => '-p {if you ssh in on another port like 2222}',
  'path-aliases' => array(
    '%drush-script' => '/root/.composer/vendor/bin/drush', // This is so you can have multiple drush installs and use different ones on different sites.
    'php'=> '/usr/local/bin/php', // Again if you have different php's for different sites.
    '%site' => 'sites/default/', // This is the important part here, it will ensure the proper bootstrap
    '%dump-dir' => '/path/to/drush.dbdumps', // This is where you want to dump your databases, normally /tmp folder I think.
    '%files' => $remote_sites . '/files' // Your sites file folder, incase it is somewhere else.
  ),
  // You may actually need this, especially if you are running D7 since I haven't ever tested the db-url thing on D7 or above.
  'databases' => array (
    'default' => array (
      'default' => array (
        'driver' => 'mysql',
        'database' => '{db_name}',
        'username' => '{db_user}',
        'password' => '{db_pass}',
      ),
    ),
  ),
);

After writing the answer I was thinking that this may be a D6 question but I answered assuming the opposite. If that is the case please let me know and I will try to answer for D6 also if there are in fact any differences. Hope this helps, thanks!


How do I disable Drupal 7 Theme Debug? "drush vset theme_debug 0" NOT WORKING I enabled theme debug on my drupal 7 installation using drush vset theme_debug 1, But Now I can't disable theme debug using drush vset theme_debug 0, What the wrong, Is there any wrong or mistakes in the drush command above?

I also tried to comment out $conf['theme_debug'] = TRUE; in the settings.php and then replaced with $conf['theme_debug'] = FALSE; but none works.

Any help and suggestions on this issue?

Thanks

If using drush vset theme_debug 0 doesn't work. Try disabling the theme debugging on your settings.php file, adding the below line of code:

$conf['theme_debug'] = FALSE;

Don't forget clear the cache.


Add Clear Button to Comment Field? Use Case: User wants to clear his comments to rewrite it.

When the User is populating the Comment field, I would like to offer a Clear or Cancel button that will remove the content.

OPTION 1

Use hook_form_alter to add a Clear or Cancel button/anchor tag(blank)
Add simple JS code to clear the fields

OPTION 2

Use hook_form_alter to add a Clear or Cancel button/anchor tag(blank)
Use Drupal AJAX Framework

UPDATE

You can use the hook_form_alter() inside your template.php file which is better based on your comment being more on the front-end side.

Next is you just need to get the ID of the form you want to alter/update by its form id value and just converting the dashes to underscores. An example would be:

<form id="leo-form">
  // form elements here
</form>

then you need to target it in your hook_form_alter() like so:

// Implements hook_form_alter.
function themename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'leo_form') {
    // place your code to add the clear button here
  }
}


How to create responsive list items using bootstrap theme I am using bootstrap theme. I am trying to create responsive list items. When viewing the page in tablet, laptop, desktop, I would like to see items in two columns.  When viewing the page in mobile, list should display in a single column. I entered the below code in body field but it is not working for me. I googled for some bootstrap classes but I could not find anything specific. Can you please advise how I can write the code to create responsive list items?

Probate Problems

Title Issues

Foreclosure

Liens

Judgements

Code Violations

Job Transfer

Mold

Divorce

Tenants Issues

Behind on Taxes

Fire Damage

Foundation Problems

Run-down Properties

You might need to use the Bootstrap column classes with divs instead of table elements, inside of a "row" element, which must be inside a "container" element:

There is more information about using the Bootstrap grid system in the main Bootstrap page.


Inject a service inside a block I need to inject a service inside a block. Since I need some logic before displaying the block, it feels dirty to do it inside the block itself, not to mention it's not actually related to the block itself.

Normally I'd inject a service by using the create() method available in the controller, but blocks don't seem to have this method.

How do I use a service from a block?

You do it the same way, the only difference is that you need to make your block class aware of the container first.

Example:

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
...
class FooBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $aliasManager;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, AliasManagerInterface $alias_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->aliasManager = $alias_manager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('path.alias_manager')
    );
  }
}


Need to override page/meta title on views page I have installed meta tag modules,then enable the meta:views mudule for meta tags.
After that i have added meta tags from views interface.
Now I need to override these value on the basis of exposed filter dropdown.I mean when i change filter,then meta values should be changed.

You can use hook_metatag_metatags_view_alter

/**
 * Implements hook_metatag_metatags_view_alter().
 */
 function mymodule_metatag_metatags_view_alter(&$output, $instance, $options) {
   if (isset($_GET['some_filter']) && $_GET['some_filter'] == 'some value') {
     $output['title']['#attached']['metatag_set_preprocess_variable'][0][2] = t('New meta title');
    $output['description']['#attached']['drupal_add_html_head'][0][0]['#value'] = t('New meta description');
   }
 }


How to remove url alias when node is deleted I am using Pathauto. When I deleted a piece of content, I was surprised to find that its url alias was still mapped to the now-nonexistent content (node/xxx).

How can I have this alias and System name mapping removed automatically when the node is deleted?

Edit:
I want to keep the Update action set to "Do nothing. Leave the old alias intact.", because I don't want paths to change when nodes are adjusted. However, it doesn't make sense to keep a path around if the node was deleted completely. Can I have both options somehow?

You can use hook_node_delete:

function hook_node_delete($node){
    // Delete alias.
    $path = path_load(
      array('source' => 'node/'.$node->nid)
    );

    path_delete($path['pid']);
}


what are the consequences of altering the users schema? I was tasked with altering the signature/signature format and make the length larger than 255. Within the given time, I had to alter the table using hook_schema_alter, db_change_field and hook_update. While I am aware this is semi hacking, I want to know what if this could have a huge consequence on my website.

For your case, as you are just altering a field's length, without adding new fields, or new indexes, the only problem could be code that handles the same field, and which uses an hardcoded value for its length. That could be code executed from a third-party module, or a future version of Drupal.
For example, user_validate_name(), the function that is used to validate the username entered during the account registration, or when the user account is edited, uses the following code.

if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
  return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
}

If a module alters the database field containing the username to make it bigger, Drupal would still throw an error when the username length is higher than USERNAME_MAX_LENGTH (actually 60, also in Drupal 8).

The reason why altering a database table defined from a module is not something suggested to do is that it would cause problems when more than one module do that for the same field.   Imagine what would happen if a module increases the length of the signature field to 350, and another module changes it to 300.
The other problem is when the modules are uninstalled. Which size would the field get when one of the modules is uninstalled? If modules remember the size the field had before they were installed, there would be a problem when modules are uninstalled in an order that is different from the installation one. If modules restore the field size to the original one, that would cause a problem when only one module changing the field is uninstalled.

In the case a module adds a new field, there could be some performance issues if the module doesn't introduce an index. If the module introduces an index for the added field, there could be errors with the SQL queries used from the module that introduced the database table; if then those queries are not dynamic, it would not be possible for the module that added the field to alter them.


Feeds Setup to Automatically Update and Delete Nodes I have an RSS feed from which I use Feeds module to fetch data from this to create nodes of a particular content type, I then use Views to display this information.

What settings do I use to setup Feeds module to automatically keep the nodes created in sync with an RSS feed?

This seams like it should be quite easy but I am coming across some trouble with this. The RSS feed has new items added, items updated and items deleted, so the feeds module need to look for all of these and be in sync with these changes.

These are my Settings:

Attached to: None
Use Standalone form
Periodic import: Often as possible
HTTP Fetcher
XPath XML Parser
Replace existing nodes
Skip has check
Expire nodes: after 1 day (this I set to delete nodes to keep in sync with items being removed)
Elysia Cron is set to run update at 2am.

What version of Feeds are you using? Deletion of existing items is not currently in the latest stable release, but it is in the latest dev release of the Feeds module, 7.x-2.x-dev (2014-Sep-17).


Programmatically pass parameters to Apache Solr integrated with Search API I'm currently trying to enable spellcheck results with the search api. If I visit my apache solr server directly with http://myserver:8983/solr/d8/select?q=goood+worksd&spellcheck=true and provide the keywords and set spellcheck to true in the url parameters

I receive expected results

  {   "response":{"numFound":0,"start":0,"docs":[]   },   "spellcheck":{
      "suggestions":[
        "goood",{
          "numFound":1,
          "startOffset":0,
          "endOffset":5,
          "suggestion":["good"]},
        "worksd",{
          "numFound":1,
          "startOffset":6,
          "endOffset":12,
          "suggestion":["worked"]}]}}

In the response I can see the spellcheck information I need in the spellcheck section.

However when I set the options programmatically before doing the query with the search api I don't receive any of this information.

    $index_id = 'default_solr_index';
    $index = \Drupal\search_api\Entity\Index::load($index_id);
    $query = $index->query();
    $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
        ->createInstance('terms');
    $parse_mode->setConjunction('AND');
    $query->setParseMode($parse_mode);
    $query->keys($search_terms);
    $query->setFulltextFields(['title', 'body_field_parse', 'type','field_description','name','body','field_title','field_summary']);
    $query->addCondition('status', 1);
    $query->sort('search_api_relevance', 'DESC');
    $query->setOption('spellcheck','true');
    $executed_query = $query->execute();
    var_dump($executed_query->getAllExtraData());

When I var_dump($executed_query->getAllExtraData()) all I get is

  { ["search_api_solr_response"]=> array(1) { ["response"]=> array(4) {
  ["numFound"]=> int(0) ["start"]=> int(0) ["maxScore"]=> float(0)
  ["docs"]=> array(0) { } } } }

I've done all kinds of variations giving true instead of 'true' and adding other options like

$query->setOption('spellcheck','true');
$query->setOption('spellcheck.build','true');
$query->setOption('search_api_spellcheck','true');
$query->setOption('spellcheck.extendedResults','true');

But nothing seems to work. I saw a spellcheck search api module someone posted but I couldn't get it to work and it seemed to do things very similar to how I'm doing it now. Is there a way to pass these parameters to my query to my apache solr? Or is my method correct and getAllExtraData not the proper way to get this information back?

After digging deep into the search_api_solr module I found a spot where it's applying options to the solr parameters inside the search method of the SearchApiSolrBackend class here

  foreach ($options as $option => $value) {
    if (strpos($option, 'solr_param_') === 0) {
      $solarium_query->addParam(substr($option, 11), $value);
    }
  }

I noticed that it only applies the parameter if it's preceded by 'solr_param_' and if it is it strips out the 'solr_param_' before applying it to the actual parameter.
All I had to do was add 'solr_param_' to the beginning of my option like so.

$query->setOption('solr_param_spellcheck','true');

Once I did that, getAllExtraData() returned what I needed.

  array(1) { ["search_api_solr_response"]=> array(2) { ["response"]=>
  array(4) { ["numFound"]=> int(0) ["start"]=> int(0) ["maxScore"]=>
  float(0) ["docs"]=> array(0) { } } ["spellcheck"]=> array(1) {
  ["suggestions"]=> array(16) { [0]=> string(5) "goood" [1]=> array(4) {
  ["numFound"]=> int(1) ["startOffset"]=> int(11) ["endOffset"]=>
  int(16) ["suggestion"]=> array(1) { [0]=> string(4) "good" } } [2]=>
  string(5) "goood" [3]=> array(4) { ["numFound"]=> int(1)
  ["startOffset"]=> int(42) ["endOffset"]=> int(47) ["suggestion"]=>
  array(1) { [0]=> string(4) "good" } } [4]=> string(5) "goood" [5]=>
  array(4) { ["numFound"]=> int(1) ["startOffset"]=> int(60)
  ["endOffset"]=> int(65) ["suggestion"]=> array(1) { [0]=> string(4)
  "good" } } [6]=> string(5) "goood" [7]=> array(4) { ["numFound"]=>
  int(1) ["startOffset"]=> int(93) ["endOffset"]=> int(98)
  ["suggestion"]=> array(1) { [0]=> string(4) "good" } } [8]=> string(5)
  "goood" [9]=> array(4) { ["numFound"]=> int(1) ["startOffset"]=>
  int(111) ["endOffset"]=> int(116) ["suggestion"]=> array(1) { [0]=>
  string(4) "good" } } [10]=> string(5) "goood" [11]=> array(4) {
  ["numFound"]=> int(1) ["startOffset"]=> int(129) ["endOffset"]=>
  int(134) ["suggestion"]=> array(1) { [0]=> string(4) "good" } } [12]=>
  string(5) "goood" [13]=> array(4) { ["numFound"]=> int(1)
  ["startOffset"]=> int(154) ["endOffset"]=> int(159) ["suggestion"]=>
  array(1) { [0]=> string(4) "good" } } [14]=> string(5) "goood" [15]=>
  array(4) { ["numFound"]=> int(1) ["startOffset"]=> int(182)
  ["endOffset"]=> int(187) ["suggestion"]=> array(1) { [0]=> string(4)
  "good" } } } } } }

Not entirely sure why I have so many duplicate results here so if anyone has input on that that would be helpful. Otherwise I do have the data I need.


How to make author name hyperlinked to its profile in node template There is a variable {{ author_name }} in node.html.twig, it will print something like below:

Your author name

But I would like to print something like that:

Your author name

How can I get this done in node.html.twig?

Normally {{ author_name }} already comes as renderable markup containing the linked author name. But there's also {{ node.getOwnerId }} (the author's user ID) and {{ node.getOwner.label }} (the author's user name) you could simply use to build the link yourself.

    {{ node.getOwner.label }}

Note you can easily inspect what variables are available for a template by installing the Devel sub-module Kint and then in your template print {{ kint() }}, flush cache and reload. You now will get all available variables pretty-printed to easily find out which ones you could use to solve your problem.

To make that snippet a little bit more sustainable use the path() function to build the link target. By that also path aliases (built with Pathauto for example) will be taken into account.

    {{ node.getOwner.label }}


use admin theme to render modules pages I want my custom module pages to be rendered using the admin theme, at the moment they only render using the admin theme for User 1 (see below).

I have a module called mymodule that defines many administrative views. It's setup in the following structure:

function mymodule_menu() {
    return [
        'admin/content/foo'     => ['page callback' => 'handle_foo', /*other opts*/],
        'admin/content/foo/bar' => ['page callback' => 'handle_foobar', /*other opts*/],
        /* list goes on*/
    ];
 }

 function handle_foo() {
    return ['#theme' => 'handle_foo'];
 }

 function theme_handle_foo() {
    /*database logic here, then return compiled html to be rendered. */
    return '<div> I am a foo!</div>';
 }

Say I have 2 users:

User 1: All permissions available(including administration)
User 2: 1 custom permission defined in the module

When logged in as User 1, all pages that follow admin/* are rendered with the drupal admin_theme including mymodule paths.

When logged in as User 2 all of mymodule pages are rendered using the frontend theme.

I've tried using hook_admin_paths but this doesn't work:

function mymodule_admin_paths() {
  return [
    'admin/content/foo'   => TRUE,
    'admin/content/foo/*' => TRUE,
    '/admin/content/foo'  => TRUE,
  ];
}

I have also read on here that any path that follows the admin/* convention should use the admin_theme by default which appears to be true for user 1 but not user 2.

My take on this is that I need to give user 2 some kind of permission, however I don't want them to be able to do anything other than login and access the paths set out in mymodule

(I don't want to use 3rd party modules)

I found 2 solutions to this:

Solution one

Use hook_custom_theme(): see hook_custom_theme()

function mymodule_custom_theme() {
 $use_admin = workout_when_you_want_to_use_admin(); //true or false
 if ($use_admin)
   return variable_get('admin_theme');
}

Solution 2 (preferred)

Ensure that the user account has the permission View the administration theme attached to their role.


Replicating a Node with Replicate UI Leads to an Incorrect Hreflang Tag we are using the Replicate UI module to replicate nodes and then changing the new replicates language to build up our site in different languages.

However, we are seeing an issue with our Hreflang tags where the hreflang tag gets the correct url of the new node, but keeps the old language code.

So let's say the old node was in English and the new one is in German - the hreflang tag still says that the new version hreflang that still contains "en" rather than "de" like that:

<link href="https://de.website.com" rel="alternate" hreflang="en" />

The question is, how can we change the hreflang code once the page is replicated? We have multiple pages that we do not want to create from scratch.

As the module's page on https://www.drupal.org/project/hreflang says if it's for Drupal 8, then you should implement hook_language_switch_links_alter() or hook_page_attachments_alter() to modify the hreflang tags. If it's for Drupal 7 then use either hook_language_switch_links_alter() or hook_html_head_alter()


Add a filter in views page I'm new in Drupal and i have crated a view for content type doctors who have many fields and i choose just some fields to be displayed in the view. Now i want to add a new filter like a select list in my page to select the country of doctor.

Create a filter using the field (eg field_country), and select 'Dropdown' under settings. If this is a taxonomy term, select 'Expose this filter', then select 'Is one of' as the operator, and save. This will give you the drop down list.

If it is not a taxonomy term, the sequence might vary slightly, but it will be substantially the same.


Custom module - find out the name of the field I have written a custom field module and I would like to know how I can programmatically find out what the name of the field in the database.

E.g. someone installs my module, that installs a new fieldtype and widget. The user adds a new field to a content type and calls the field "test_field". How can the module provide the database name of the field ("test_field") to some function within the module?

Currently I am hard-coding the name of the field which works fine until a user decides to use another name. Then I am not able to do some database operations anymore.

OK. I ended up doing it a little differently:

In my field_widget_form function I added a hidden field. In this function it is possible to access the $field and therefore the name of the field using

$field['field_name'];

So I saved that value to the hidden form. Then when I trigger a function within that form it is able to access that value. So in my different function that relies on the machine_name of the field I actually access the value of the form that is set when the widget form is built.


Allow a role to assign user roles but not to manage user permissions on Drupal 7 how I can give to the "special" role the possibility to manage roles of other users (add a role to a user, remove, add more than a role, etc.), but not the possibility to manage all user permissions?

Use the role delegation module

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

  For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role.


How to exclude an item from a view if it appears in another view on the same page? I am very new to Drupal and now I am trying to build some small website to try different things out.

I made my website's homepage a Panel, and in it there is a "Promoted News" View, and under this view there is a "Latest News" View.

I want to be able to exclude from "Latest News" any news item that appears in "Promoted News".

Is that possible to do without having to write code? And if not, how can it be achieved?

So you have 2 views: "Promoted News", and "Latest News" View.

To exclude any view results ('items' as you call them) from "Latest News", add a 'filter' in that view with as criteria the opposite (negation) of the 'filter' criteria that are used in your "Promoted News" views.

E.g. if "Promoted News" is implemented with a filter like "published to frontpage", then in "Latest News" the filter o be added should be "NOT promoted to frontpage".

Note: If you're new to Drupal, you might also want to review the set of 30 video tutorials about the Views module to become more familiar with the Views module.


menu inside views page I was wondering if this is possible. I have a views which is displayed as a page and I want to have menu inside that page. Is there a module available to achieve this?

Here's a picture of what I want to copy:

Thanks for the suggestions. I'm a newbie

If you simply want to place a menu in side bar use Menu Block Module.When  user clicks on a menu item, it will load the page linked to that menu item.

But If you want to provide filter criteria in side bar, like if user clicks on "Koryo", It will filter the results and display results of "Koryo" only, than you should consider Facet API.


PDOException "column not found" but does exist This is on Drupal 7.39 with Domain Access and Ubercart

When pressing "checkout" button the site returns and error which shows in the dblog as:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'uc_payment_method_credit_checkout' in 'where clause': SELECT value FROM {variable} WHERE name =uc_payment_method_credit_checkout LIMIT 0, 1; Array ( ) in uc_domain_variable_get() (line 291 of /. . . /uc_domain.module).

Line 291 of the uc_domain_module is:

$result = db_query_range("SELECT value FROM {variable} WHERE name =" . $variable, 0, 1)->fetchField();

The column exists in the variable table and I triple checked it for an exact format match  (they all exist for the variable_set commands  I placed to be used in the install file)

This module is a Drupal 7 version module but is not an official project owned or maintained by anyone though it was originally written by the Drupal 6 project author and maintainer and released by him at https://www.drupal.org/node/946574.  I am working with that released file as modified by "henk" - but this section is unchanged by "henk" either

The equivalent command in the Drupal 6 version is near identical

D6 version starts . . .
  $result = db_result(db_query("SELECT value FROM {variable} WHERE name = '%s'", $variable));

D6 version ends . . .

I put a space in the => " . . . WHERE name = " . $variable . . ." to match the D6 version

But the error now simply reads  " . . .  WHERE name = uc_payment_method_credit_checkout . . . " with the space at "name = "

It seems to work -partly as it created an order entry in uc_domain_orders when i tries to test it - somehow - even though the jump to checkout failed.

This is not not like any other "column not found" issue I have searched here.

Anyone have any words of wisdom or ideas ???

Concatenating variables into an SQL query is usually a bad idea (search for SQL injection and you'll see why). The D6 version you're starting with:

$result = db_result(db_query("SELECT value FROM {variable} WHERE name = '%s'", $variable));

uses parameters, you just need to convert that to use the newer query substitution in D7. The docs for db_query() have some good examples, essentially what you need for this particular query is:

$query = 'SELECT value FROM {variable} WHERE name = :name';
$params = array(':name' => $variable);
$result = db_query($query, $params)->fetchField();


hook_menu title callback on wildcard I have two pages, the first page 'test' has links to test/%.
On test/% I want to have different titles but some how this wildcard
and the title callback aren't working properly.

/**
 * Implements hook_menu().
 */
function cjgimport_menu() {
  $items['test'] = array(
    'title' => t('Test title'),
    'title callback' => 'function_title_callback',
    'title arguments' => array(0),
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('access content'),
    'page callback' => 'function_content_callback',
  );

  $items['test/%'] = array(
    'title' => t('Test title'),
    'title callback' => 'function_title_callback',
    'title arguments' => array(1),
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('access content'),
    'page callback' => 'function_content_callback',
  );

  return $items;
);

/**
 * Custom callback function for title
 */
function function_title_callback($arg) {
  if($arg == 0) {
    $title = ucfirst(arg(0));
  } else {
    $title = ucfirst(arg(1));
  }
  return $title;
}

Can anyone tell me why the title doesn't work on the test/% pages?

You need to provide the wildcard as title arguments:

$items['test/%'] = array(
  'title' => t('Test title'),
  'title callback' => 'function_title_callback',
  'title arguments' => array(1),
  'type' => MENU_NORMAL_ITEM,
  'access arguments' => array('access content'),
  'page callback' => 'function_content_callback',
);

And obviously make sure that your function is actually called function_title_callback() (which you've listed in hook_menu()), and not cjgimport_title_callback(), which you have listed in the question.

You should also be using the $arg variable, not the arg() function in your callback...but I guess that might be the result of debugging.


Drush error cygintl-2.dll is missing So I get the following error "the program can't start because cygintl-2.dll is missing from your computer. try re installing the program to fix this problem" I am getting this error when I try to run a ls command. I have re installed like the pop up suggests. I used the windows installer to install this.

Apparently you have somehow broken your Cygwin installation. In the Cygwin setup.exe, go through the setup sequence until you get to the "Select Packages" screen, then type "intl" in the Search box. Open the Libs section, and click the third column on the "libintl2" line until it says Reinstall. Proceed.

That should fix this one particular problem, but chances are good that if you've lost that one library, you've broken other things, too. A complete Cygwin reinstallation might be in order.

You too can follow this steps for install drush properly:

Installing Drush on Windows

or

Installing Drush on Windows using Cygwin


How to manage / consume multiple Queue API queues in a module? For a site I'm running, I'm going to have a few different queues for message sending. For example: high priority email, low priority email, high priority twitter, low priority twitter... etc.

I have set up queues (like "UrgentEmail", "UrgentTwitter") etc. using Drupal's Queue API, but now I need to work on the queue processing (consuming).

I can simply use hook_cron in a module to consume one queue at a time, or all of them, as much as possible, but I'd like to be able to maybe have one queue get hit every couple minutes, while the lower-priority queues would only get it once every half an hour or so...

Is this possible without writing up some of my own cron handlers? I know elysia cron for D6 was good at setting options for module-specific cron, but is there a way I could branch out cron in a single module and run different tasks at different intervals? Or is there another Drupal Way™ to do this?

It's possible to achieve this using Ultimate Cron! module.

This module creates a separate entry for each Queue item.
Maybe it will help somebody.


How can i customize the output of "repeat rule" for human readability (german)? I'm using the Calendar Module, which comes with a date-repeat feature. Showing the "repeat rule" in a view results in e.g.

  Wiederholungen jede Woche jeden Mittwoch !repeats_every_interval, 10
  mal .

which is rather unacceptable. Is there a way to rewrite the output of this? Which replacement patterns do i have to use to reproduce the repeat rule?

I resolved this by just deleting the phrase by hand from the localized translation set.

I hope this won't trigger any other unwanted stuff.


Where does redirect from default search to apachesolr_search occur? We're using the apachesolr_search module on our site. (This is a site I inherited fully coded, so there's tons going on that I'm not intimately familiar with yet.) We have a search block that has been customized (see this post for details; we did eventually get the radio buttons to display, although in a really dirty, non-drupal way.)

I'm trying to get the form values on submit. Forgetting for a moment the radio buttons, I can't even figure out a way to get the value of the search box. Obviously it's getting passed to the solr search, but when I look at the Net panel in Firebug, there are no POST requests, only GET. In my submit function (which does run), I've tried print_r('$_POST'), echo $form_state['values']['search_box'] (where search_box is the element name of the actual form element), tried looping through $form_state and printing all key/value pairs... nothing. Not a single one of these returns anything.

Obviously there's a redirect occurring somewhere that sends the value of the search_box to the solr search module to build the GET request, but I can't for the life of me figure out where it's happening. I think in order to see the values of the posted form, I'd need to intercept the values before the redirect - how do I do that?

Unless I'm mistaken, there is no redirect taking place. Instead the hook_search is used, which will pass the search params from the url.


Determining the $POST variables of a submitted form I have a form on my site. Users fill out the form and submit it. When I want to target one of the fields in the form with a custom module I'd target it with something like the following:

$form['customer_profile_billing']['field_organization'];

But, if I want to target the value a user entered - after they clicked submit, in a custom module, what would be the proper syntax to use, or how would I figure out what my $POST variables are?

The submitted values are available in your custom validate/submit handler in the $form_state['values'] or $form_state['input'] (with the later one storing raw and unvalidated user input). I think this is considered better practice than accessing the values through the $POST variable.


How do I include jQuery scripts at the bottom of the  tag? I want to include a JavaScript file at the bottom of the <body> tag, and I only want to  include it for a specific node type, but my node.tpl.php file's content is only wrapped by <article> tag; there is no ` tag in this file. If I do this in the root template.tpl.php file, it will effect all pages, which is not what I want.

Can I do this via theme preprocess functions?

The example on the documentation for drupal_add_js() can explain this.

drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

If you want to add jQuery files, just change 'type' to 'file'.