Give a basic page a different appereance by rendering it with views I'd like to render a basic page to look somewhat different for my mobile site.
Now I have come up with a combination of views-view--mobile-aboriginalartsfestival.tpl.php, page--mobile-aboriginalartsfestival.tpl.php & html--mobile-aboriginalartsfestival.tpl.php to change the appareance of my mobile-aboriginalartsfestival view. Now, the page contains certain elements that I would like to alter, in particular I would like to get rid of the <h2> title on top of the content (but not all h2 elements on the page!) and I would like to replace the image, too. How do I best go about it?

edit 1

So far, I have a  couple of arrays on top of my page. One contains strings to search for $searchstr and the other one $contentstrcontains strings to replace the search strings with. Then, where to content gets rendered in my page--mobile-aboriginalartsfestival.tpl.php, I implemented a few lines like:

        <?php $i = 0;
              $contentstr = render($page['content']);

              foreach ($searchstr as &$value) {
                $contentstr = str_replace($value,$replacestr[$i],$contentstr);
                $i++;
                }
              print $contentstr;
        ?>

and even thought, that approach seems to work fine, I doubt that it's the best way to go about it, does any one have a better idea for this?

The Theme Key module enabled me, to do what I was looking for: enable a different theme per page based on certain criteria (like mobile browser e.g.).


How to disable EDIT tab for webform? It would be great if anyone tell me how to disable EDIT Tab. I'm using Drupal 7.

I try with role permission, I successfully disable it for other submitter but failed to do the same for some submitter.

At the same time, I want that the submitter be able to change the workflow state, this is why i check all that permissions.

Thanks for the help.

For the roles in question, remove their ability to edit webform content types and make sure they don't have something like administer nodes checked off. It sounds like they may have too many permissions assigned to the role(s) that would cause the edit tab to appear. Also uncheck permissions pertaining to 'submissions' other than administrative roles.


Cannot add CSS class to views field I have a view in Drupal 8, and have configured a field in the view to have a custom CSS class.

The field I am adding the class to is an image. Under Style Settings I have chosen "Customize field HTML" and "Create CSS class".

When I inspect the image element on the front end, the class is nowhere to be found, and the styles are not applied.

I also have a view fields template for this view named:
views-view-fields--home-page-top-three-stories.html.twig

{{ fields.field_story_preview_image.content }}

{{ fields.title.content}}

{{ fields.field_subtitle.content }}

"fields.field_story_preview_image.content" is the image field that I would like to apply the CSS class to. Am I missing a configuration step?

Why isn't the CSS class being applied to this image field?

I hope you cleared cached
I hope u added css under [themename].library.yml
If still not working plz use rewrite result add your custom html.


Views taxonomy page by content type I've got two content types: "job" and "job description".

Both of these types are categorized by using ONE taxonomy vocabulary "category".

I've enabled the default "taxonomy term view" for views.

No when I navigate to the site /category/entertainment (for example) all jobs and job descriptions which are tagged with the category "Entertainment" will be displayed.
But I want to extend this view like:

/category/entertainment/job => show all nodes of type "job" with the category Entertainment
/category/entertainment/job_description => show all nodes of type "job_description" with the category Entertainment

Basically you have to add a second parameter to your views page path so it looks somthing like this: taxonomy/term/%/%. The first % will be the category, the second will be the node type.

Now you have to add a contextual filter. Choose the filter "Content: Type". The default filter setting should work fine. You can try rewriting the title under "When value IN URL" to something like node type %2 to see if the value is correct.

You can test it in the preview at the bottom by setting the parameters to "entertainment/job" or "entertainment/job_description".


Which test cases/tests should I run? I'm a bit confused about best practices for testing in Drupal 7.

When I'm going to deploy, should I run the entire test suite—including all Drupal core tests—every time? This seems like a bit of overkill, especially given how long each test takes to run.

At the same time, it seems logical that I should run all tests every time, since code changes I make in my custom modules could break something in core (via hooks, etc.). The problem is, each test runs in a sandbox with only its dependencies enabled, so core tests won't even be aware of my custom modules and thus won't fail even if they should.

I'm accustomed to testing in Rails, in which tests are run against the entire application as a cohesive unit, with all "modules" (gems) being enabled at test runtime. It seems that in Drupal, only certain pieces are tested at a time, which prevents an accurate assessment of whether the site will work in production.

So I guess my question is twofold: A) Should I run the entire Drupal test suite (including core tests) every time I deploy? B) How do I check whether my custom code causes core tests to fail, given that core tests don't take custom modules into account?

No, running Drupal core test suite is wrong. You can assume that your code won't messed up drupal core and if you so - you'll get exception for that and then the fun will start :).

If you came from the ruby world then you probably familiar with the Behat solution and if not you should check this - very easy to use QA platform and a lot of posts were written in order to test your site with behat. But there is also selenium that can help you.

And i'll give a you a tip on how to start the testing suite for your site: For now you probably have a running site. You need to take a pen and paper or a google doc and start what features you create for your site: what happens when the use login, what happens when he create node. After you wrote your tests you can start to write them in test - behat, selenium simple test... what ever! As long as those tests testing your features.

Another tip is: when ever you have a bug and you fixed this, you write a test that verity that the bug can't be reproduced. This the way all of the big projects i know works: OG, Message stack, Open scholar,


Form submit button with ajax, replace form with another one (error 500) I am trying to turn my Form into multi-step ajax form.

I have:

class ProjektForm extends FormBase {

    public function getFormId() { return 'projekt_form'; }

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

        $form['title'] = array(
            '#type' => 'textfield',
            '#title' => t('Title*:'),
            '#required' => TRUE
        );
        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Add'),
            '#button_type' => 'primary',
        '#ajax' => [
            'wrapper' => 'projekt-form-ajax-id',
            'callback' => 'form_ajax_submit',
            'method' => 'replace',
            'effect' => 'fade'
        ]
        );
        $form['#prefix'] = '
';
        $form['#suffix'] = '
';
        return $form;

    }

    public function form_ajax_submit($form, $form_state) {
        return 'OK';
    }
...

But when I click on "Add" (submit) button and see the "please wait" Drupal icon for a while I eventually get 500 error for my ajax request:

Should I register somehow form_ajax_submit? Note that it's member function of ProjektForm. And I use ProjektForm inside my custom module which displays it from block.

What I want to do is to send the data from form via AJAX (and here I get error 500), validate it and display next form (via ajax, replacing the previous one without page reload).

You need to add your namespaced class to the callback property.
For example:

'callback' => 'Drupal\mymodule\Form\ProjektForm::form_ajax_submit'

or

'callback' => [$this, 'form_ajax_submit']

You also need to make sure the wrapper and the prefix html id are the same.

Finally, after you do all that, do check your logs for more details on the error that caused the 500 response.

Good luck!


How do I add block configuration information for themes using features? Is it possible to use features to manage block configuration information (for example, the positioning of a block [header, footer, etc.]) using features?

Yes, but not directly you need to use the Context module to do it.


Views Grouping field position I have a view and i use a date field for grouping. The position of the grouping field is at the top of the view row.
Is it possible to position the grouping field at the bottom of the view row?

With a view template file it was possible to place the grouping field at the bottom of the View.


Programmatically delete pathauto alias pattern? I know how to remove a pattern via the UI. Is it possible to do this programmatically to be used in hook_update()?

EDIT: I think asking this answered my question. Will post a followup answer. Probably just entity_load/entity::delete

Ended up throwing the following into my_module.install

/**
 * Deletes the product_nodes path alias. Check watchdog for error in case of failure.
 */
function my_module_update_8001(){
  $alias_id = 'product_nodes';
  if($alias_entity = Drupal\pathauto\Entity\PathautoPattern::load($alias_id)){
    try{
      $alias_pattern = $alias_entity->getPattern();
      $alias_entity->delete();
      return t('Successfully deleted @id PathAuto pattern. If this was done in error, you can recreate it by using the pattern: @pattern.',
        array(
          '@id'=>$alias_id,
          '@pattern'=> $alias_pattern,
        )
      );
    } catch(Exception $e){
      \Drupal::logger('my_module')->error('Encountered the following error while trying to delete the @id path alias pattern: @error',
        array(
          '@id'=>$alias_id,
          '@error'=>$e->getMessage(),
        )
      );
      return 'Failed to delete @id PathAuto pattern. Check the error log for details.';
    }
  } else {
    return t('No PathAuto pattern found with the ID @id.',
      array(
        '@id'=>$alias_id,
      )
    );
  }
}


Bootstrap horizontal form layout In Bootstrap there is a nice horizontal form option. But in Drupal + Bootstrap base theme I couldn't find any ways to use this horizontal forms and layout form elements as it described, eg. col-2 for labels and col-10 for inputs.

The only way I found is Strapped theme (https://www.drupal.org/project/strapped)  but it is in dev stage and I don't need one more base theme.

Bootstrap is so popular along with horizontal forms and I don't want to believe there is no way to solve this problem.

Or everybody uses hook_form_alter() and render horizontal form somehow in code?

Thanks in advance.

Can you paste an example here with the code that didn't work for you?

Did you respect the structure below?

  Enter long URL:

    <input type="text" maxlength="100" size="60" value="http://" name="example_input" id="edit-example-input" class="form-control col-md-10 form-text" tabindex="1">


Using Migrate in Drupal 6, setup and parsing XML Is there a better walkthrough to setting up Migrate than this documentation on Drupal.org? I have followed those directions, and I can't get my classes to show up in the UI. Is there anything clearer?

And how would I go about using Migrate, once it's set up, to parse a series of XML documents (one list XML that includes an additional document per node) into nodes which I can then manipulate in Views?

EDIT
Now I've gotten my XML read and fields set up (I think), but now I can't get the nodes to save. The import has the correct number of nodes, but they don't ever get imported. The wine examples in the documentation didn't say anything about using prepareRow() or anything when you are using XML. Where are my nodes? Can I pull out that data with Views even if nodes don't import? My end use for this is to arrange everything with Views.

Yes, look at the Beer examples that come in the migrate module itself. If you want some example code and usage with some explanation I find the BTMash blog posts useful. While the BTMash blog is D7 based -- the hooks and usage of Migrate is widely similiar between D6 and D7.


How to add Permalink for custom content type(nodes) I need to add Permalink for my section/div where the ID will keep on changing whenever i update the page(custom content type).

I have achieved it through client side(Jquery) by find & get ID seems like tedious?

I have checked for module support like permalink & permalink block, Deeplink nothing seems to be helpful?

Is there is any better way to achieve it?

You can create permalinks, better known in the Drupal world as "aliases", using the Pathauto module.

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

See Video Tutorial.


How to selectively import and export content between 2 Drupal websites? How to merge simple core content into from site a to site b. Content is created using core functionality and modules.

Let's say I have 2 Drupal 7 sites, both have same configuration and modules.

Site A has:

3 content types
3 taxonomies
3 articles

Site B has:

1 content types
1 taxonomies
1 articles

How do I append content of site B to site A?

I want the content from site A to be appended to site B. If I do backup migrate, the content of site A will be overwritten.

I've noticed that backup migrate can have manual selection of what to export, but it will overwrite destination right?

What is the best procedure for this?

You could always write a couple of migration classes with the Migrate module, and hook up Site B as the datasource (the module would live in Site A).

You can do this by adding Site B's database credentials to the settings.php as another configuration, then calling on that in your script.

Here is an example of what a Migration class might look like:

class YourMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $query = Database::getConnection('connection_name', 'connection_key');
    // other query arguments to execute
  }
}

Where the Database::getConnection arguments are the names of the items in your $databases array in settings.php. With a working script, you can then write other scripts (or a cron job) to periodically run the migrate job.

Others will say to use Feeds, but I've always been a big Migrate fan (not Drupal2Drupal migrate module, the main Migrate module itself).

  I've noticed that backup migrate can have manual selection of what to
  export, but it will overwrite destination right?

Pretty much. Site A would get wiped out. It also isn't as simple as moving MySQL data around, unless every data model in Site B is identical or exists in Site A even then its a fairly large technical challenge not to screw anything up. I would not do anything with SQL at this level - it needs to go through the API.


Views pager uses wrong URL when using views_embed_view() I have a custom AJAX app which allows the user to filter some nodes, which uses a View. By custom AJAX app, I mean that this is not just a view with AJAX enabled.

The user accesses /reports which includes the output of views_embed_view(). An AJAX-enabled browser interacts with the page, resulting in an AJAX call to /reports/ajax to fetch just the results and save a full page re-load.

It all works, except that the results returned by the View in this case use /reports/ajax as the base URL for the pager (because that's the path used to invoke the custom AJAX controller), which means that when the user clicks one, they get a page of AJAX response.

I would like to train Views to use a different URL (i.e. /reports) for pager requests. Beyond a str_replace in the output of views_embed_view(), is there another way?

Manually set $_GET['q'] to the appropriate value before calling views_get_view().

Views' pager uses the standard Drupal pager from includes/pager.inc which uses this request variable:

function theme_pager_link($variables) {
  // (... code omitted here ...)

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}


Domain Access + Domain i18n = Site names not translating in other languages? I have 4 languages and 2 domains: site.com site.eu
I set up languages in these domains like:

site.com - english (default)

br.site.com - brazilian

site.eu - german

fr.site.eu - french

When I try to type Site Name for french and brazilian it does not save the line. but it save Slogan.
So Drupal use default site name of default language for both Brazilian And French sites: br.site.com and fr.site.eu

this instruction did not help me http://reyero.net/drupal/internationalization_domain_access_multilingual_variables_for_each_domain

There are Realms information that I've found. But how to configure correct I do not know.

I'm assuming you're using the "Domain Access" module. And even though you didn't explicitely mention it, you also use the i18n module. If my assumptions are correct, then be aware of what's mentioned on the project page of the "Domain Access" module:

  If you use the contributed i18n module suite, you should use the Domain Variable module instead of the provided Domain Configuration and Domain Settings modules.

Therefor I think you should try the Domain Variable module, to check if it fixes you issue.


How to change order_number on hook_commerce_payment_order_paid_in_full or hook_commerce_checkout_complete I'm trying to change the order_number after the order has been created.  Specifically, I need to do this in the hook_commerce_checkout_complete or hook_commerce_payment_order_paid_in_full functions.

I'm sending orders out for 3rd party fulfillment and want to store the 3rd party's unique order_number (which is different than Drupal Commerce's order_number) into DC's order_number column.

I do not need to change the order_number in hook_commerce_order_presave because this happens before I make the call to 3rd party fulfillment when the new order_number gets generated in their system.

You can see in the code below that this is being executed as the order is paid in full, during checkout completion.  In this example the order_number 00001890 is trying to be changed to 9999999 and saved, but the new order_number is not actually saving.

function custom_module_commerce_payment_order_paid_in_full($transaction) {
  print "<pre>";
  print "paid in full\n";
  print_r($transaction);

  $orderid = $transaction->order_id;
  $order = commerce_order_load($orderid);

  print "BEFORE CHANGING ORDER NUMBER \n";
  //order number is 00001890
  print_r($order);

  $order->order_number = 9999999;

  print "AFTER CHANGING ORDER NUMBER \n";
  //order number is 9999999
  print_r($order);

  $result = commerce_order_save($order);

  print "Order save result\n";
  //SAVED_UPDATED = 2
  print_r($result);

  print "DID ORDER NUMBER CHANGE??? \n";
  //no, it did not change, it's still 00001890
  print_r($order);

  $order = commerce_order_load($orderid);
  //confirm order number did not change, it's still 00001890
  print_r($order);

  print "</pre>";
  die();
}

Any help or advice would be much appreciated!

I don't think it's a good idea to change the order id.

I would rather goto admin/commerce/config/order/fields and a new number field which will be used to store the 3rd party's order id in the field.

That way you are not changing the default workflow of Drupal commerce and it will also be easier for you to compare your order id against the third party order id if something goes wrong.


CSS not updating with aggregation turned off I'm running into an issue that I'm not sure how to diagnose. I'm working on minor CSS updates on a custom zen theme for a Drupal 7 site. I have the dev site set up on a laptop running ubuntu dev server. I have gone to performance and turned off css and js aggregation and flushed all the caches via Drush. The problem I'm having is that my css changes are being saved to the styles.css file, but they're not reflected when I refresh the site. Poking around in inspector, the css files have a ?oegwy2 suffix, which suggests that something is still aggregating or modifying the files. I'm not sure what that would be, I didn't set up sass for the this project, so the sass recompiling isn't likely what's going on here.

Your CSS file may still be being cached, even if not aggregated.
You can refresh the ?oegwy2 querystring with drush

drush cc css-js

Which refreshes the config variable: css_js_query_string

You could also add the following to your dev env settings.php to disable that querystring var:

$conf['css_js_query_string'] = '';

Then you should be able to just use hard reload (e.g Shift+Refresh) to refresh the CSS.


Commons: can each non-admin user create groups? I wan to configure a Drupal Common site so that every user can create groups. Can I do so? how? Thanks.

And is there any documentation anywhere for commons? OR a support forum?

The answer is yes. Straight out of the box, each Commons user can create groups.


Hiding a drupal block on particular page I am trying to hide a Drupal block on a View page.

The View url is http://localhost/alphabetical

And name of the block is family tree. So I went to Structure ->Block ->Configure(for Family tree)
and added /alphabetical to Show block on specific pages(with Radio button All pages except those listed)
But it didn't work.
Then I cleared all the caches.Still it didn't work.

In the block configuration page, in the Pages tab select All pages except those listed; in the text area below, write alphabetical. As the example shown in the description for the text area, you don't need the slash at the beginning of the path.


How to create charts in Views using Google Analytics data? I'm trying to generate charts in Views using Google Analytics data.

I have the Google Analytics Reports module installed, but this module doesn't allow aggregation of data which make charts very difficult to develop.

Does anybody have a working solution to get charts in Drupal 7 using Google Analytics data?

You could pull in the data to your Drupal DB via the Google Analytics API (https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtDataImport)

Then create views to display the reports/charts you want. Then install and build data visualizations packages like Views Dataviz with Google Charts API.


Change site logo for an specific content type I'm building a really simple site and I came into this question now. The site has a few content types and one of them acts as a moderated wiki (only users with a certain role may create/edit that content). When viewing lists of these nodes or when viewing any node of that content type in full-mode I would like the site logo to be different. Say, instead of «My site», something like «My site [[wiki]]».

My first thought was tweaking context to change theme settings based on context. Too bad, I didnt find how to get that :/

I've been diving in the available answers here, but I dont seem to have an answer, though a couple of similar question tackle this subject through different systems:

One attempts to show different logo for different languages and relies and i18n and variable modules. see thread on i18n and variable
Second one adds a variable (though it is not clear if they put it directly in the node--type.tpl file (and i wouldnt like that :-/), by hand-writing the path to the desired image... see thread on tpl "abusing" :D

Any ideas on what is the best approach to get this custom logo for an specific content type?

Thanks :)

The code provided in the answer wasn't working properly, but I adapted the code and got it to work:

function YOURTHEMENAME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
  // If the node type is "blog" the template suggestion will be "page--node--blog.tpl.php".
   $vars['theme_hook_suggestions'][] = 'page__node__' . str_replace('_', '--', $vars['node']->type);
   }
}

With this function I got a tweakable and customized page.tpl.php. Now I only need to change the $logo value for this content type or add extra settings to the theme, as hard-coding the url path for the alternative logo seems inelegant :)

The simplest way would be to create a tpl for the content type to do that you can follow the below steps

First create a preprocess_page function as given below. This would go into the template.php file.

function YOURTHEMENAME_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

now you can create a new page.tpl per content type something like

page__CONTERNTTYPENAME.tpl.php

You can copy the entire content of the existing page.tpl.php into this and replace the logo with the desired logo.

in zen theme the logo is in the page.tpl is printed as follows

<?php if ($logo): ?>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
    <?php endif; ?>

here you can replace the image src with the direct path to your logo.


How to execute javascript iframe in custom module? I have created a custom module for Drupal 7. In this module, I would like it execute a javascript file that embeds an iframe when the module is viewed. I have tried the following code with no success:

function chat_with_librarian_block_view($delta = '') {

  $block = array();
  switch ($delta) {
    case 'chat_with_librarian':
      $block['subject'] = t('Ask a Librarian');
      $block['content'] = chat_with_librarian_get_html();
      break;
  }
  return $block;
}

function chat_with_librarian_get_html() {

  $html = '
' .
    '
' .
    '';
  $form = array(
    'chat_frame' => array(
      '#type' => 'markup',
      '#markup' => $html,
      '#prefix' => '
',
      '#suffix' => '
',
    )
  );
  return $form;
}

What do I need to do to get the embedded javascript to work properly. As a side note I can make this work by creating a block through the administration screen, so I know this can be done. I just need to know what I am missing in my code to accomplish the same thing. When I do execute this code, the title is rendered but the body isn't. Examining the body of the block, I can see it contains the javascipt as returned by the function and an additional message:

Reload the page to get source for: url

It seems like the executing code cannot get correct div dimensions to return a proper iframe (but that is just a guess on my part - have put inline css to define a size). Has anyone come across something like this or how to get this working?

Thanks.

The $form var in chat_with_librarian_get_html()is rather useless, just return the $html var instead and it should work.

function chat_with_librarian_get_html() {
  $html = '

' .
    '
';
  return $html;
}


How to make radio buttons required and have a possible default value I have a set of radio buttons. I first check the database to see if one of the options has already been set for the user and if so add it to $attending. If none have been set I don't want a default value. I thought I could achieve this by setting default_value to false. The problem I have is that when setting default_value to false and I submit the form without selecting an attending option, Drupal does not give me an error saying I didn't select an option for that radio group. How do I set a default value to nothing so that Drupal gives an error when I try to submit without selecting an option?

$form['attending'] = array(
  '#type' => 'radios',
  '#title' => t('Will you be attending?'),
  '#options' => array(
    '1'   => t('Yes'),
    '0' => t('No'),
  ),
  '#required' => TRUE,
  '#default_value' => isset($attending) ? $attending : false,
);

I'm not sure exactly why this happens; maybe FALSE is being cast to an integer in the validation, being evaluated as 0, and becoming an acceptable selection (your value for "No" being 0).

Fortunately you can use NULL instead:

'#default_value' => isset($attending) ? $attending : NULL


Why does Drupal not register Menus Nor Links? One of the website that I manage the menu system is not working. I have installed many modules (including the commerce modules) and are not being displayed on the menu. However, all modules links (and commerce) works, if I type it on the URL.

After troubleshooting a little bit more I figure out that this is not only for commerce. I created a new content type and is not been display on the node/add page  or in the admin_menu. And once again I'm able to go to the page if I type the URL.

I click on rebuild menu, I flush all caches and still not been register. I do not see any Drupal logs errors.

How can I address this problem ? I cannot expect the sysadmin to know all the URL.

Update 3/27/2015

I'm now using the latest Drupal (v7.35) and I noticed this at first on 7.34.

Like I mentioned before it is not only on the menu. So I do not think the admin_menu is the problem. I remove the module admin_menu and use the toolbar module. But there are missing links on the pages that are been created for the latest module that I have installed. So any module that I enable from now on it would not register the pages.

Update 4/3/2015

I'm now using the latest Drupal (v7.36) and I noticed this at first on 7.34.

I disable/uninstall and enable drupal core menu module and still not fix this issue. Someone from the Google + community suggested that this issue may be cause by the jquery updated I try to used different jQuery version and still have issues. In addition, I try to follow this How to completely wipe and rebuild drupal menus? and to rebuild all my menu and did not work.

I strongly believe is need to be something with the hook_menu not working on my Drupal website.

Update 4/4/2015

I notice that if I add a new content type it would not appear the links on the node/add nor under the content menu. However, it appear in the page admin/structure/types and in the menu under structure -- > Content Type.

Some more updates to address one of the suggested answers to try to get my issue reolved:

This is single site installation.
I do not think is because of the memory_limit. Because I have managed bigger sites that does not have this issue. I did try it out and it did not help. I.e in my setting.php I set it up to 300M and on my php.ini as well. After that I cleared caches, run cron, restart the webserver. And still nothing.

It would be interesting to see if your problems could be related to the "memory limit", which might not be high enough (anymore), especially since in the OP it says "I have many modules enabled".

I'm assuming that this is NOT a multi site. So therefor consider editing your /sites/default/settings.php, and change the line to set the memory limit. If it is a multi site, then edit the settings.php file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

ini_set('memory_limit', '100M');

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

Curious to hear if that helps somehow ...

Here are a few other thoughts that might ring a bell in the right direction (if you haven't tried them yet):

temporary turn of all caching, to see what the impact is of doing so. Of course that cannot be the real solution in most cases, but at least it might give some indication like "it seems to be caching related".
what about compression of JavaScripts and/or CSS? If you have turned them on, what happens if you (temporary) disable them?


How to prevent users uploading images from their system? I have some image fields on my site.

My requirement is that the user should not be able to upload an image. Instead there will be a directory where I will place some images. And the user can only select an image from those images through image field.

Is it possible?

There are three major projects for handling media libraries in Drupal 7:

IMCE
Media
Scald

The most basic solution is IMCE. It is simply a file browser for files on your server. I.e. image files are just files on your server and Drupal isn't really aware of them and their meta-data.

The Media module uses in its ver. 2.0 File Entity module to manage media files, making it well aligned with the Drupal framework. It is a tried and tested solution for those who want something more sophisticated than IMCE.

Scald is a relatively new entry for media management. It comes with a very powerful media library sub-module and integrates seamlessly with the CKeditor WYSYWYG editor through drag and drop.  It has a bit steeper learning curve than the two others, but is IMHO well worth the effort.

Whether users are allowed to upload files (as opposed to pulling them from a library) are for all three projects handled by permissions settings.


Fullcalendar is putting my events into the "all-day" category I'm doing some stuff with fullcalendar and views that, more or less, is working.  In particular, a month view properly shows a set of events on the day in which they're scheduled. However, when I switch to week or day view, the events show up in the "all day" part of the calendar.

The nodes' fields containing the dates definitely correspond to specific times. How can I get them properly showing up in the right time areas in those calendar views?

Fixed; my bad.  I hadn't (properly) set the granularity of the node's time field.  Duh.


Organic groups content propagation direction where can I set content propagation direction in Organic groups (7.x-2.x). Post https://drupal.stackexchange.com/questions/40835/need-groups-within-a-group/175000 shows screen which I can not find even though I have installed modules Organic groups and Subgroups for organic groups.

Do you have any advice where can I find this screen or any other way I could set proparation of content from parent to children groups?

That screenshot is from Drupal 6.

In Drupal 7 the organic groups module works much differently in that it now uses fields to store its settings.

With Drupal 7 organic groups you need to go the the "OG field settings" administration page (admin/config/group/fields) and configure which fields appear on which content types.

The way that admin page works can be a little confusing but it's fairly straight forward once you get used to it.

The fields provided by the Subgroups for Organic groups module are:

Group user inheritance
Group user permission inheritance

On that admin page add those fields to your sub-group content types, then you can go to the content type field settings for those content types (in the admin/structure/types section) and you can configure default for those fields that will be used whenever sub-groups are created.

If you want to stop content administrators from being able to change the value of that field you can then use the field permissions module to restrict access to those 2 fields.

This is the same way you have to manage the fields from the base OG module (Group and Groups audience) and the fields in the OG access sub-module (Group visibility and Group content visibility).


Not able to access the key value of a list in a twig file I'm trying to access the key of a list (Text) in a paragraph twig file

This is what I have in my list
small|Small Item
big|Big Item

{{content.field_option.0['#context'].value}}
{% set value = content.field_option.0['#markup'] %}
{{ value }}

I always got the text. Small Item or Big Item. I would like to obtain small or big of course depending of the user selection.

I'm going to use this value as an HTML Class.

Thanks for your help

I changed the entity_view_display of my paragraph so that my field output the key, instead of the value. I was then able to access the key. I hope that helps?

I'm able to use this: content.field_button_chrome[0]['#markup']


How to convert a Drupal website to standalone exe file? I'm trying to convert my Drupal website to a standalone .exe file. I tried some popular applications like ZZEE PHPExe or ExeOutputPHP, ZZEE PHPExe returns the error that /includes/boostrap.inc is not found in the output directory, while I copied that folder in there. The ExeOutputPHP errors File not Found and nothing else! it doesn't even tell me what file is not found!

Any suggestion to convert Drupal website to standalone exe file?

You should generate a static copy of your site first.

For that you can either use a module like the static module, or just "copy" your entire site with wget or curl.

So for example you can do something like this :

wget -p --convert-links http://localhost/ -P ~/site_static_copy

(This assumes that you're accessing your localhost with http://localhost/ and that you want to copy under your ~/site_static_copy directory )

Once you've done that you'll be able to package the copy with the tools you mention.


Body title gets displayed with content I have a content type of something, with title and body only as fields, body field reporting field_body as machine name.

problem is, i create a node with content and then when it's displayed on the page, the text Body: head up the main content area, for all posts.

Tried removing the name Body from the field type name but it's a mandatory field property.

any way to rid the page of that title?

Assuming that you are using D7. Go to /admin/structure/types and select your content type.

Under the 'Manage display' tab, find the body field, and set the label to 'Hidden'. The field label will not display. You may have to repeat this for each display type (default, teaser etc.).


Add to Custom Entity Content on Node add/update I am new to Drupal. Now, learning drupal 8.

I have added a module from command drupal generate:module named 'my_module`

I have added an entity for my_module:

drupal generate:entity:content
//bundle "NO"

What I want

I would like to add/insert in to this entity on every Node add/update.

I have got this code into my my_module.module

function my_module_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'my_module_node_form_submit';
      }
    }
}

function my_module_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
   $node = $form_state->getFormObject()->getEntity();

   $url = $node->field_website->uri; //my node field
   $name = $node->field_com->value; //my node field

   //HOW TO ADD $url, $name IN TO above custom ENTITY
}

My entity table:

1: my_module

id
uuid
langcode

2: my_module_field_data

id PrimaryIndex
langcode PrimaryIndex
name
url
status
created
changed
default_langcode Index

Please help.

You can do like this

Suppose your entity name is my_entity.

<?php
use Drupal\my_module\Entity\my_entity;

function my_module_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
            $form['actions'][$action]['#submit'][] = 'my_module_node_form_submit';
        }
    }
}

function my_module_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $node = $form_state->getFormObject()->getEntity();

    $url = $node->field_website->uri;
    $name = $node->field_com->value;

    // Now to check
    //Generate my_entity entity.
    $entity = my_entity::create(
               [
                 'label' => 'token',
                 'id' => $node->id(),
                 'status' => true,
                 'name'=> $url,
                  "url" => $name,
                  "created" => time()
               ]
         );
    $entity->save();
}

To update enity:

$entity = my_entity::load('content entity id');
$entity->set("name", 'name value');
$entity->set("url", 'url value');
$entity->save();


Entity reference autocomplete field node I am using Services module to create nodes via an api and am having problems using entity reference autocomplete to populate the field.

The ER field is linked to a taxonomy and uses a multi field setting so that more than one value can be set. I have tried multiple different options including a var_dump of the node entity upon insert and can see its not being set.

The following are the 6 ways I tried to set the field. Do you have any idea? I am using the latest Services module and the ER module.

{"und": ["112326"]}

{"und": [{"target_id":"112326"}]}

{"und": [{"target_id":"A S (112326)"}]}

{"und": ["A S (112326)"]}

{"und": [{"tid":"A S (112326)"}]}

{"und": [{"tid":112326}]}

First, to handle multi value fields you'll need this patch: https://www.drupal.org/node/2224803#comment-11477609

Second, depending on what Widget you have selected for your Entity Reference field, this does/can change what Services expects to be POST/PUT up to the server.

I personally always set the Widget as an Autocomplete, and then this JSON format is the correct one to use:

var node = {
  type: 'article',
  title: 'Hello world',
  language: 'und',
  field_foo: {
    und: [
      { target_id: '... (123)' }
    ]
  }
};

You can literally put anything you want in the position of the ..., the only thing that matters is the Entity ID is wrapped in the parenthesis.


Limit Taxonomy Term references to special vocabulary I have a custom entity type with custom fields, one of them is  an entity_reference type ,
I saw this question How to create entity reference field from custom entity to specific content type , and according to it some references I googled , try the below code but it not works .

 $fields['book_cat'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Book Category'))
    ->setDescription(t('Book Category Name'))
    ->setSetting('target_type','taxonomy' )
    ->setSetting('handler','default' )
    ->setTranslatable(TRUE)
    ->setDisplayOptions('form', array(
        'type' => 'options_select',
        'weight' => -1,
        'handler_settings' => array(
            'target_bundles'=>['book_cat_agency'=>'book_cat_agency'],
            'size' => '60',
            'placeholder' => '',
        ),
    ))
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

But not working.

my vocab name is : book_cat_agency

I see two mistake in your code, first ->setSetting('target_type','taxonomy' ) is mistake and try ->setSetting('target_type','taxonomy_term' )  and try to set handler_settings with  setSetting I mean  ->setSetting('handler_settings',['target_bundles'=>['book_cat_agency'=>'book_cat_agency']] ) (although there is a way to set handler_settings in setDisplayOptions  )

and finally try  following

$fields['book_cat'] = BaseFieldDefinition::create('entity_reference')
   ->setLabel(t('Book Category'))
   ->setDescription(t('Book Category Name'))
   ->setSetting('target_type','taxonomy_term' )
   ->setSetting('handler','default' )
   ->setSetting('handler_settings',['target_bundles'=>['book_cat_agency'=>'book_cat_agency']] )
   ->setTranslatable(TRUE)
   ->setDisplayOptions('form', array(
       'type' => 'options_select',
       'weight' => -1,
       'settings' => array(
           'size' => '60',
           'placeholder' => '',
       ),
   ))
   ->setDisplayConfigurable('form', TRUE)
   ->setDisplayConfigurable('view', TRUE);


Views exposed filter to search multiple fields To my knowledge there hasn't been an option in drupal 7 to create a single exposed filter in a view which searches multiple fields, while in previous versions there existed modules to do just that.

Using the or operators is fine but then you get multiple fields in the form.

Add Global: Populate filters and you can have a single field but then the view never shows anything.

Is there any way or module that will make this work?

Edit: What I didn't notice was the field operators. For some reason the default operator for text fields in views is =, while a proper search function needs contains or has word. I've been looking for the reason I couldn't get it to work for almost 6 months now. Wow. What a pain. /facepalm

Yes, you can have multiple fields search in a single exported filter using Global: Populate filters and Views filter populate module.

Check this answer.


Role expire in drupal 7 issue I have installed Role Expire module but how can I set its expire date?

Can anybody please help me because I don't get any clue to write expire date for a particular role?

From admin, when create users and assign roles i.e. admin/people/create, there is a textbox open where admin can insert the expiry date.


How to add a custom Save &  button to Node Add/Edit form? I added the following code in hook_form_alter() and I get my button on the Add/Edit node form:

$form['actions']['save_add_lesson'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Add a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_node_form_submit'), /* NEED this */
  '#weight' => 1000
);

But, clicking the button doesn't seem to hit hook_node_submit() or hook_node_insert(). I'm assuming I'm missing a hook or something in the button creation...anyone have any ideas?

Then added this function:

function mymodule_node_form_submit($form, &$form_state) {
  // Do stuff before saving the node

  // Call this to save the node
  node_form_submit($form, $form_state);

  // Do stuff after saving the node
}

Got it :D

Adding

'#submit' => array('mymodule_course_form_submit'),

To the submit button worked. Like this:

$form['actions']['save_add_lesson'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Create a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_course_form_submit'),
  '#redirect' => 'node/add/lesson',
  '#weight' => 1000
);

function mymodule_course_form_submit($form, &$form_state) {
    $nid = mymodule_node_save_no_redirect($form, $form_state);

    $form_state['redirect'] = 'node/add/lesson';
    unset($_GET['destination']);
    drupal_static_reset('drupal_get_destination');

    if($nid != -1) {
        $_SESSION['mymodule_course_nid'] = $nid;
        drupal_redirect_form($form_state);
    } else {
        // Failed to save Course...notify user
        drupal_set_message('Failed to save Course Content', 'error');
    }
}


How can I skip the current password validation on the user form? My site requires that I turn off the current password validation on the Account Edit Form when changing / specifying a new password.

In D7 I accomplished this via a hook_form_alter implementation.  With Drupal 8's new form api I am unsure of how I can make this alteration.  hook_form_alter still exists, but the values in the form[#validation] seems to be used differently.

I see in the existing form code that a 'password reset' does exactly what I would like to do, but it's unclear how I can make this modification outside the actual AccountForm Class, or the ProtectedUserFieldConstraintValidator implementation of ConstraintValidator.

Thanks

A working code example for this is the No Current Password module.
Here's the relevant code:

/**
 * Implements hook_form_FORM_ID_alter().
 * Remove the current password field from the user_profile_form form (user/%/edit).
 */
function nocurrent_pass_form_user_form_alter(&$form, &$form_state) {

  // Get the module's configuration
  $config = \Drupal::config('nocurrent_pass.settings');
  $nocurrent_pass_disabled = $config->get('nocurrent_pass_disabled');

  // If the Current password is disabled
  if ($nocurrent_pass_disabled) {

    $account = \Drupal::service('current_route_match')->getParameter('user');

    // If this is not the Superadmin's edit page
    if ( !empty($account) && ($account->id() != 1) ) {

      // Turn off Current password field's validation
      $form_state->set('user_pass_reset', 1);

      // Hide the Current password fields
      $form['account']['current_pass']['#access'] = FALSE;
    }
  }
}


How would I paginate to 5 results in each page this query? I am trying to paginate the results from the table, I saw some examples but those make use of db_select, I chose db_query. Is there a way to get the paging with db_query? I have been trying to translate the code into db_select but no luck, support please! Thanks!
Here is my code!

function rss_list_form($form, $form_state) {
  $header = array(
    'article' => t('Article'),
  );

  $sql = "SELECT * FROM {rss_table}";
  $result = db_query($sql);

  $rows = array();
  foreach ($result as $dbrow) {
    $rows[$dbrow->GUID] = array(
      'article' => '
'.$dbrow->title . '
' . '

' . strip_tags($dbrow->description, '

') . '

' . '' . $dbrow->date . '
' . $dbrow->link . '
',
    );
  }

  $form['rss_select'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('No articles found.'),
  );

  $form['import'] = array(
    '#type' => 'submit',
    '#value' => t('Import'),
    '#weight' => 0,
    '#submit'=> array('rss_list_form_import'),
  );

  $form['update'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#weight' => 1,
    '#submit'=> array('rss_list_form_update'),
  );

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

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

  return $form;

}

The better way to use db_select with called as query extender.

Here is an example

$query = db_select('rss_table')
  ->extend('PagerDefault')
  ->limit(5);

Then theme_pager() can be used for outputting a pager.

For more detailed example check out

Either way to use pagination

 function pager_array_splice($data, $limit = 9, $element = 0) {

             global $pager_page_array, $pager_total, $pager_total_items;

                $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
                $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
                $pager_total_items[$element] = count($data);
                $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
                $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
                return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

 $query = db_select('rss_table','t');
            $query->fields('t');

           $resultget=$query->execute();

           $result = $resultget->fetchAll();
              $limit=5;
              $output = pager_array_splice($result, $limit);
              $html='';

   foreach ($output as $dbrow) {

                    $items[]=(array)$dbrow;
                    $title = $dbrow->title;
                    $description = $dbrow->description;

$html.="         //HTML code here//       ";

 }

  $output1 = theme('item_list', array(
    'items' => $items));

    echo $html;

You can use it as in the form of table too or append it to the form as well. This is the way to use pagination.

Use this code to modify as per desired output.

Hope it works for you!


Programmatically update alt tag on image field I have a Drupal 8 site with a content type that has an image field. For existing nodes of this type, most have image files, but none have alt tags.

I am writing an update hook where I want to set the alt tag value for existing nodes. However, I have not been able to figure out how, nor find documentation.

This is what I have:

$nids = \Drupal::entityQuery('node')->condition('type','sfa_social_post')->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

foreach ( $nodes as $node ) {
  $node->field_sfa_image_file->alt = 'Image for ' . $node->getTitle();
}

Where field_sfa_image_file is the name of the image field.

When I re-loop through the nodes, I get back the value that I set.

$nids = \Drupal::entityQuery('node')->condition('type','sfa_social_post')->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

foreach ( $nodes as $node ) {
  drush_print('Title: ' . $node->getTitle());
  drush_print('Alt: ' . $node->field_sfa_image_file->alt);
}

Which gives me

Title: Instagram Post ID: 1917569620391415985_3017827348
Alt: Image for Instagram Post ID: 1917569620391415985_3017827348
Title: Instagram Post ID: 1917562614863492125_3017827348
Alt: Image for Instagram Post ID: 1917562614863492125_3017827348

So all seems good. However, when I navigate to nodes, I don't see my alt text:

How do I set the alt tag for an existing image field?

As @clive suggested use $node->save();. Without node saving, alt of the image will not show up in the edit form.

$nids = \Drupal::entityQuery('node')->condition('type','sfa_social_post')->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
foreach ($nodes as $node) {
  $node->field_sfa_image_file->alt = 'Image for ' . $node->getTitle();
  $node->save();
}


Insert some data in comment upon comment submit For some reason I cannot find answer to relatively simple question. How to insert some data (for example the "title" filed value) into comment body upon the comment submit. Finally I'd like to have in comment body something like this:

Node title (with some CSS markup) -
Comment body -

Could you please advice the right way to do this?

Since you didn't say which version of Drupal are you using, I'll assume that you're talking about D7.

You need to use hook_comment_presave().

function YOUR_MODULE_comment_presave($comment) {
  // Do this only for new comments.
  if (!$comment->cid) {
    // This code will insert the subject as heading.
    $subject = '<h2>' . $comment->subject . '</h2>';
    $comment_text = $comment->comment_body[LANGUAGE_NONE][0]['value'];
    // Set the value.
    $comment->comment_body[LANGUAGE_NONE][0]['value'] = $subject . $comment_text;
  }
}

However, do bear in mind that you will need to handle somehow editing existing comments as well.

Hope this helps.


Webform Download Results not working I have been trying to get the download results of a webform and it has'nt worked

Here are the steps I have followed

I have checked the temp folder and .tmp files have been generated

I have selected third option of 'Download Range Options' and its working properly.


Some module is adding info below 'Nice Menus' I believe some module is somehow hooking into nice menus and adding a div of content below the menu. However I can't for the life of me find out which one.

Here's what I know:

There is a content type called 'nice_menu_addition'. When creating an item of that content type you chose which menu item you would like it placed beneath, and it shows up there. However, I can't find ANY modules anywhere, or any theme info that shows where this is being done. Any suggestions as to where to look?

suggestion from average drupal guy.... try using the module_implements() with watchdog method to check the available hooks from nice menu or menu docs that can cause the change and track the module...hope it helps you in some way


Use rules on custom content fields I am trying to apply a rule to a certain content type with a taxonomy term selected from a list, this term is from a select list that selects the terms from a certain vocabulary that lists the terms from the vocabulary. I want the rule to only apply when international is selected......I have been at if now for four days, nothing doing. Tried a search but the results I found were not helping. I would really appreciate the help.

Your can probably add a rule of this kind :

The event is : Before saving content
Restrict by type : your content type

Then add a condition : Text comparaison then select your field with the Data selection like this node:field-example:0:name and match the International value. The rules will fire if all theses conditions passes


How can I paginate the Views page itself where all views are listed? At the url admin/structure/views how can I paginate this list of results?

If you have many views I would suggest you go to Views settings (admin/structure/views/settings) and enable Show filters on the list of views. This gives you the possibility to search and filter the list of views in various ways.


How can I get the node ID from a path alias? I want to be able to get the nid but the only information I have is http://example.com/this-is-the-alias.

Is there a way to get either the internal path of /node/*  for that alias if I am not on the page?  Or is there a way to just get the nid from that alias right away?

I'm not sure if there's a direct function, but one route is to use the path alias manager service to lookup the internal path then regex it for a valid node id to perform an object load on:

$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias');
if(preg_match('/node\/(\d+)/', $path, $matches)) {
  $node = \Drupal\node\Entity\Node::load($matches[1]);
}


How to update failed transaction detail in drupal commerce I am using drupal commerce to built a e-commerce site .

My problem is when a transaction is failed or get a late response then the transaction is not created.

Can i create it manually or i have to ? if yes then how?

Or is their any other way to attach my transaction detail to order .

Any help most appriciate. Thank you.

You need to load the failed transaction from order id as shown below:

<?php
  $query = new EntityFieldQuery;
  $result = $query
    ->entityCondition('entity_type', 'commerce_payment_transaction')
    ->propertyCondition('order_id', $order->order_id)
    ->propertyOrderBy('transaction_id', 'DESC')
    ->range(0, 1)
    ->execute();
?>

Then load transaction using commerce_payment_transaction_load($transaction_id) & update transaction object as shown below:

<?php
//Use following line instead of loading transaction in order to create new transaction object
//$transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
$transaction = commerce_payment_transaction_load($transaction_id);
$transaction->amount = $charge['amount'];
$transaction->currency_code = $charge['currency_code'];
$transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
commerce_payment_transaction_save($transaction);
?>

You can set a cron to periodically check failed transaction & check status of same at Payment Gateway & update accordingly.


Using contextual filter in view All,

I have been reading and experimenting, but have not been able to achieve the desired result - please offer some guidance.

My site has two content types: meeting and presenter. At each meeting, there are zero, one, or two presenters. Content type Meeting has a field type of Node reference whose 'number of values' is set to 2. When a Meeting content item is created, it is very simple to link the associated presenter.

The challenge is properly configuring the view. I would like to show each meeting's presenter(s) with the meeting information, whether I am showing just next month's meeting or an archive of past meetings.

I created a view based on Content type Meeting and created a relationship to the linked Presenter (by checking the box Content: Presenter (field_presenter_ref)). Where I am getting stuck, I think, is with the contextual filter. Based on my reading, I should be using Content: NID, but this does not seem to be doing anything for me. Specifically, if I remove date filters, the View shows all presenters from all meetings, not just the one associated with a specific meeting.

Looking forward to learning how to do this correctly - thanks.

In my opinion it's not necessary to add the relationship. When you have added the presenters in the Meeting node by use the node reference. You can just add the Presenters field (node reference field) in the Field section of the view without using relationship. Because the node reference is already taking care of the relationship part.

Does this help in any way?
Let me know.


Cannot use feeds to import into data tables where the primary key is multiple I am using Data Module to create tables in Drupal.
Now, I need to import some data through CSVs, for this I want to use Feeds Module.
My table consists of more than one primary key i.e. a group of fields together forms a primary key.

Is there any way to import the data for such a case using feeds? Coz my understanding is that feeds cannot import data if the primary keys are not restricted into a single column.

The simplest thing to do would be to use Feeds Tamper's Rewrite plugin to combine the unique fields in your source into one field and then map that to the GUID.

https://drupal.org/node/1539224 could use some help as well for supporting this properly.


Revert configuration languages overrides Suppose you have a Drupal 8 multi site installation, with multi language support, and a custom module used across multiple sites.

This module has a view, with the yml file in:

custom_module/config/install/views.view.custom_view.yml

You also have to maintain some strings translations for this view to multiple languages (the view title among others). So for each language, you have:

custom_module/config/install/language/[langcode]/views.view.custom_view.yml

You install a new site enabling the custom module, and then adding languages to the site, and the configuration languages overrides are loaded properly into config table with collection attribute to language.[langcode].

But… then you update the language file, adding missing strings or editing one of existing. Replicating those translations manually into production environment is not an option, because you have dozens of sites using this module… How can you reload these strings translations in a programmatically way for preparing a hook_update_n in the custom module, or via a drush command?

For updating configurations I'm using config_update module, with the following approach:

$configUpdate = \Drupal::service('config_update.config_update');

// Reload existing config
$configUpdate->revert('view', 'custom_view');

// Import a new config
$configUpdate->import('view', 'new_view');

But for reverting translations of those configurations I haven't found any approach yet. Any idea?

Thanks in advance.

Answering to myself, I think I've found the solution:

$langcode = 'es';
\Drupal::service('language.config_factory_override')->installLanguageOverrides($langcode);


How to align teaser images? Is it possible to align (left or right) teaser images that are uploaded through Imagefield in Drupal 7? Is there a clean solution whithout hacking into drupal code?

You should use CSS to style your content. This happens in the theme of your site. The handbook on Drupal.org has a lot of documentation on how this is done.


How to configure programmatically a unique constraint on several fields of a custom entity? How could I configure a unique constraint on several  fields of a custom entity I have already created with drupalconsole.

The purpose is not allowing insert of two record of the same entity having for example same lastname and fisrtname.

As suggested by elstevenson, I used the validation API.

Here the steps.

Create a repository in your module repo.
/src/Plugin/Validation/Constraint
Create a constraint (name = Unique)

namespace Drupal\module_name\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;

/**
* @Constraint(
*   id = "Unique",
*   label = @Translation("Unique ", context = "Validation"),
*   type = "entity:entity_name"`
* )
*/

class UniqueConstraint extends Constraint {
   public $message= 'Unique entity!';
   }

Create a constraintValidator, and we populate the validate method with an entity query to make sure that there is no record having the same value of field1 and field 2:

 namespace Drupal\module_name\Plugin\Validation\Constraint;
 use Symfony\Component\Validator\Constraint;
 use Symfony\Component\Validator\ConstraintValidator;

class UniqueConstraintValidator extends ConstraintValidator {

/**
 * {@inheritdoc}
 */
public function validate($entity, Constraint $constraint) {
 $field1 = $entity->field1->value;
 $field2 = $entity->field2->value;
 $entity_type_id = $entity->getEntityTypeId();
 $value_taken = (bool) \Drupal::entityQuery($entity_type_id)
  ->condition('field1',  $field1)
  ->condition('field2',  $field2)
  ->range(0, 1)
  ->count()
  ->execute();
if ($value_taken)
{
$this->context->addViolation($constraint->message);

}

}
  }
Then configure our constraint in our entity (annotations part):

/**

* Defines the entity_name entity.

*

    * @ingroup entity_name
    *
    * @ContentEntityType(
    *   id = "entity_name",
    *   label = @Translation("entity_name"),
    *   handlers = {
    *     ...
    *     "form" = {
    *     ..
    *     },
    *  ....
    *
    *   constraints = {
    *     "Unique" = {}
    *   }
    * )
    */

Then you should uninstall your module and then reinstall it . (if your entity is populated with data, you have to delete all the date).
In your code (for example in your form) , you have to ensure the validation :

$violations = $entity->validate();
if ($violations->count() > 0)
{
 $violation = $violations[0];

 drupal_set_message($violation->getMessage(),'warning');
}

Hope it will help.


How to pass an array to a template? I am trying to get my first module to work which is supposed to render an array in his own template file.

1) I got an array of variables and return it in my controller

        array(
        '#theme' => 'myTheme',
        '#test_var' => $this->t('Test Value'),
        '#array' => array('key'=>$myArray),
        );

2) in my .module I declare the hook_theme()

  return array(
'myTheme' => array(
  'variables' => array(
    'test_var' => '',
    'array' => array(),
    ),
),

);

3) Then I would like to print the variables
I am sure I missing something, and if I'm missing basic knowledge please let me know. I'm sure something is  wrong in the hook_theme since I don't know how to iterate my array in the template file.

test_var: {{ test_var }}

{{ array }}

If somebody could point me in the right direction, that would be nice :)

edit: the "Test Value" is rendering just fine

The variable names in the render array and theme hook need to match:

array(
  '#theme' => 'myTheme',
  '#test_var' => $this->t('Test Value'),
  '#doubles' => array('key'=>$myArray),
);

Iterating an array in Twig is pretty straightforward:

{% for key,value in doubles %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}


Cache tags for all entities of a certain type I understand how you can add cache tags to a custom query for a particular entity id (or list of them) but is there a way to add cache tags that will invalidate a query if any entity of type FOO is updated/added/deleted?

You could use the module handy_cache_tags, then you would have this type of tags:

handy_cache_tags:[entity_type]
handy_cache_tags:[entity_type]:[entity_bundle]


How to change active link css class (is-active) What the best way to change css class for an active link from 'is-active' to (in my case) 'active'?

Also, need I really to replace it or to append my class? I know the 'is-active' class is hard-coded (here and in several php classes) and it is so strange for me since drupal is overloaded with many abstraction layers and tons of settings. What is it: "legacy of the past" or really well-founded idea?

I need 'active' class just for my current css-framework, but may be 'is-active' used in core or so?

Thank you!

You can override the theme_menu_link function like this:

function theme_menu_link($variables)
{
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = \Drupal::service('renderer')->renderRoot($element['#below']);
  }

  foreach ($element['#attributes']['class'] as &$class) {
    if ($class == 'is-active') {
      $class = 'active';
      break;
    }
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '<li' . new Attribute($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}


When should I use hook_field_attach_presave(), and when hook_entity_presave()? I was looking for a way to act on entity fields before they are saved, and I have noticed the following about hook_field_attach_presave(), and hook_entity_presave():

They take the same parameters, but in a different order.
They are both called when an entity is saved. For example, taxonomy_term_save() contains the following code.

// Invoke hook_field_attach_presave().
field_attach_presave('taxonomy_term', $term);

module_invoke_all('taxonomy_term_presave', $term);
module_invoke_all('entity_presave', $term, 'taxonomy_term');

Similar code is present in comment_save().

field_attach_presave('comment', $comment);

// Allow modules to alter the comment before saving.
module_invoke_all('comment_presave', $comment);
module_invoke_all('entity_presave', $comment, 'comment');

As they get the same parameters, the code I should write to access the entity's fields is the same for both the hooks. This means that, apparently, there isn't any reason to choose one instead of the other hook.

When should I then implement one hook instead of the other? Are there cases where I would implement hook_field_attach_presave()?

It depends on what type of data you are trying to modify.  Some entities are not fieldable. Those entities would never call hook_field_attach_presave() where as they would call hook_entity_presave().

If you are modifying an entity's base properties such as 'title', you should use hook_entity_presave(). If you are modifying the fields attached to an entity, you should use hook_field_attach_presave().

Keep in mind that other modules might be using these hooks as well. They would expect you to be making your modifications to the type of data in its respective hooks.


How do I add an autocomplete to a form element that is not an entity reference? I need to add a auto complete text field in my custom form module. The auto complete values should be retrieved from the database table. Can anybody tell me how to do that?

To add an autocomplete to a form element that is not an entity reference element, you need to use two properties:

#autocomplete_route_name, the name of the route returning the autocomplete array as JSON
(optional) #autocomplete_route_parameters, an array of parameters to pass to the autocomplete route, in the format [<parameter> => <value>]

For example, the autocomplete controller could be implemented from a class similar to the following one.

/**
 * Defines a route controller for autocomplete form elements.
 */
class AutocompleteController extends ControllerBase {

  /**
   * Handler for the autocomplete request.
   */
  public function autocomplete(Request $request) {
    $results = [];

    // Get the typed string from the URL, if it exists.
    if ($input = $request->query->get('q')) {
      $typed_string = Tags::explode($input);
      $typed_string = Unicode::strtolower(array_pop($typed_string));

      // Use $typed_string to load data from the database.

      $results[] = [
        'value' => $value,
        'label' => $label,
      ];
    }

    return new JsonResponse($results);
  }

}

Notice that:

The value entered in the form element is available in $request->query->get('q')
The autocomplete returns an array containing entries with value (the value to use) and label (the value to show), converted in JSON


omega where to make changes? I've installed Omega 7.x-4.2 and created my subtheme and I just want to start practising making changes with page.tpl.php and css but there are just so many files and so far nothing has affected change.

I copied over page.tpl.php found in omega/system folder and placed it in my subtheme/templates then placed styles in my subtheme/css/subtheme.hacks.css but see no changes at all.

Also have noticed in sites/all/themes the path structure is different for omega that is all/themes/omega/(ohm)omega/templates and in other
all/themes/subtheme/templates. I set this up a while ago following documentation and can't remember why it has ended up this way and whether or not that would cause problems. There are no errors just no changes taking effect.

Just all seems so unnecessarily complicated!

A couple of things you can check...

In your subtheme, have you declared omega as your base theme in the .info file?

name = omega sub theme
description = my sub theme
base theme = omega

Have you enabled your subtheme as the default theme in admin/appearance?
Have you flushed the cache after making changes? ( configuration > development > performance > clear cache )
In dev tools, or whatever you use to inspect an element, when you have the source open, what is the path? Is it definitely coming from your sub theme folder?


How to create a views page of discounted products list? I'am using commerce discount module in commerce kickstart 2.11
And need to create a page with a list of dicounted products using views filter and/or search API.
I've tryed without any success.
Please Anyone, any help to do this.

I'm affraid there's no working solution right now.

you can see and follow List all discounted products in commerce discount issue list for further information and workarounds.


Webform block not shown on front-end I'm new to using the Webform module, and started with the Contact form provided on install. I have added a Webform block to the Content region, but it doesn't show up on the front-end at all (even when I remove all restrictions such as only showing on certain pages).
I thought it might be a permissions issue, so I checked that all roles have access to see the form. When I tick "Allow users to post submissions from a dedicated URL" and choose a path, both anonymous and logged-in users can view the form at that URL. It's only when it's a block that it doesn't show up. I have also tried clearing the cache, and placing the block in other regions.
I am using Drupal 9 with Webform 6.0.0.
Edit: After some suggestions below I have also tried:

Another theme: The issue does not happen in the parent theme of my sub-theme, narrowing it down to a possible theme-level issue.
Deleting my theme's overrides of region.html.twig and block.html.twig. The issue persists in my theme.
Placing a HTML comment in block.html.twig before any Twig code, to check when that file is being used (i.e. it might be loaded, but have a problem with the output code). It is not rendered at all for this specific block.

What are some other possible things that can cause the block to not show up?

Rather than checking the block's config in the existing instance, delete it and re-insert it, checking the settings again in the insertion screen. It now shows up for me after doing it this way.


Change page title on user-profile using a field value from Profile2 Normally the /user/uid page shows the username as page-title. I'm using the Profile2 module to leverage more fields to my users, including a 'full name' field which I'd also like to use as the page title.

How would I go about this?

If you actually seek to always use the full name for the user's Profile2 when his/her username is displayed, then you should implements hook_username_alter(). Any well behaving module (contrib and core) should use it.

function MODULE_username_alter(&$name, $account) {
  // Get the user profile
  $profile = profile2_load_by_user($account, 'profile_type');
  if ($profile) {
    $fullnames = field_get_items('profile2', $profile, 'field_fullname');
    if ($fullnames) {
      $name = $fullnames[0]['value'];
    }
  }
}

If you only want to override the username when used as title of the user page, you can alter the menu entries for user and user/%user to change their title callback to a custom one.

function MODULE_menu_alter(&$items) {
  $items['user']['title callback'] = $items['user/%user']['title callback'] = 'MODULE_user_menu_title';
}

function MODULE_user_menu_title($account) {
  if (is_object($account)) { // Updated here
    $profile = profile2_load_by_user($account, 'profile_type');
    if ($profile) {
      $fullnames = field_get_items('profile2', $profile, 'field_fullname');
      if ($fullnames) {
        return $fullnames[0]['value'];
      }
    }
    return user_menu_title($account);
  }
  return '';
}


Running EntityFieldQuery on restricted content (with cron) I’ve got a small issue running the following query:

$qry = new EntityFieldQuery();
$qry->entityCondition('entity_type', 'node')
        ->propertyCondition('status', 1)
        ->propertyCondition('changed', $since, '>')
        ->fieldCondition('group_audience', 'gid', (array) $groups, 'IN' );

When I run this manually as user #1 it is all fine. When I run this through cron (which has no user) the organic group access control appears to forbid returning any results (based on no permissions for the current user I guess). This issue is with the last fieldCondition, when removed, it all works as expected.

Cron runs as the anomymous user. The idea is that it should only call APIs that don't require users. EntityFieldQuery however allows you to either bypass node access checks, or to set the user the query will run as.

Option 1: Set the user to run the query as:

$query = new EntityFieldQuery;
$result = $query
  ->fieldCondtition(...)
  ->addMetaData('account', user_load(1))
  ->execute();

Option 2: Bypass node access by setting the DANGEROUS_ACCESS_CHECK_OPT_OUT tag (since Drupal 7.15 I believe)

$query = new EntityFieldQuery();
$result = $query
  ->fieldCondition(...)
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
  ->execute();

Option 3: You can run your cron code as another user by setting the $user global variable. For instance:

function mymodule_cron() {
  global $user;
  $original_user = $user;
  $old_state = drupal_save_session();
  drupal_save_session(FALSE);
  $user = user_load(1);
  _mymodule_do_some_stuff();
  $user = $original_user;
  drupal_save_session($old_state);
}

Option 1 is the cleanest way to do what was requested - it relies on an existing functionality to run a query as a different user. You can use user 1, or create a custom user who has exactly the permissions you require for your operation.

Option 2 is functionally equivalent to using Option 1 with user 1. It is less flexible than option 1, so there isn't really a case to use it (but included here for completeness).

Option 1 and 2 are limited to entity field query, which is what the OP asked. To do other operations as another user, you need to impersonate that user completely - which is what Option 3 does.


Insert value into field before and after specific string I need help with update function.

I have database table with three fields. One of them is code field with html div and script.
Example:

My problem is, how am i supposed to insert some condition inside script tags and to end it before closing script tag? How should i write db_update to accomplish that?

Thanks in advance.

Sounds like you should be parsing the field with a regex function that matches the content between the script tags. Then you can rebuild your string and update the row.

http://regexr.com/3du5i for an example


how to get backtrace information for php errors in drush I want to get backtrace information for php errors in drush.

Tried out the following patch - http://drupal.org/node/1158322#comment-6249880. Its shows the backtrace info as message(while using browser), but I'm not getting these messages in drush

This should be posted as a Feature Request in the Drush issue queue.  I started that off for you here:  http://drupal.org/node/1804600


How do I print the term names associated with a node? I want to show the term names used in a node. My term field machine name is field_category.

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'content_type');
$entity_ids = $query->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);
foreach ($nodes as $node) {
   dpm($node);
}

dpm() prints the following.

stdClass Object(
[__CLASS__] => Drupal\node\Entity\Node
[in_preview] =>
[values] => Array
 [field_category] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [target_id] => 4
                            )

                        [1] => Array
                            (
                                [target_id] => 2
                            )

                    )

            )

How can I print the term names as term-1,term-2?

You can do this:

foreach($nodes as $node) {
  $categories = $node->field_category->referencedEntities();
  foreach($categories as $category) {
    print_r($category->getName(). ",");
  }
  print("\n");
}


Contextual filter + exposed filter My view have following "EXPOSED" filters with Industry. And Contextual filter of Taxonomy.  So when I do asia/agriculture. %1 should be Asia and it's coming along fine. But %2 should go to Exposed Filter and it should filter out all the nodes with "agricultural" term.

Is it possible in Drupal?

Check out the Views Filter Harmonizer module. It allows you to have a contextual filter argument apply only when there is no corresponding regular (exposed) filter value present.

Here is a quote about it (from its project page):

  Views Filter Harmonizer solves an operational foible with the Views
  module regarding filtering.
  Normally, when a Views field has been assigned both an exposed filter
  and a contextual filter, then both filters get applied to the View's
  results set -- always. This is not configurable behaviour. It's
  hard-coded.

  As a consequence, contradictory search clauses easily occur, causing a
  counter-intuitive user experience with some White Screens of
  Disillusionment. Since the contextual filter sets the "bounds" for the
  page, any filtering by the visitor through the exposed filter on that
  page can only narrow down the results set, not broaden it. In other
  words the exposed filter appears not to be working properly.

  This small module allows you to have a contextual filter argument
  apply only when there is no corresponding regular (exposed) filter
  value present.

  This is most common on initial page load. After that the contextual
  filters will silently retreat and let the exposed filter values as
  selected by the visitor do their thing without interfering.

  This means that you can take advantage of friendly URLs using
  contextual arguments instead of ugly and verbose query parameters. Put
  the URLs anywhere on your site, in emails and in newsletters to take
  visitors to tailored Views pages. Having arrived there, visitors may
  then further filter these pages to their heart's content using the
  View's regular filters you exposed. And they won't experience any odd
  behaviour.


entity_export - where can it be used? I want to make use of the entity_export function for data migration. I see on the doc page http://drupalcontrib.org/api/drupal/contributions!entity!entity.module/function/entity_export/7 that

Note: Currently, this only works for entity types provided with the entity CRUD API.

How would I know if a module fits this criteria? Is it simply if it has the entity module as a dependency?

If the module has been properly written en utilises the full Entity CRUD API there should not be a problem. In most modules this should be the case.

However the Entity module does more (like exposing entities to Views). If the dependency was only used for such a specific case, it might be possible that the module comes with un-exportable entities.

If you want to narrow this down you could search the module for HOOK_entity_info() (change hook to module name) and see what controller class is used. If it is EntityAPIController it is likely to utilise the CRUD API.


How to check the modules installed date? How to check which modules was installed on what date?  I am using Drupal 6. I can not find any answer in Google.

You can't have that information with default core and contrib module.

You can get the time module upload on your server by checking last modify time of module file.

If you realy want to have module install information, you should create a patch that change the module_enable function on includes/module.inc file.


Bulk update pages that use old URL alias by content type We have a content type, Basic Page that recently had the URL pattern changed from www.example.com/page/page-title to www.example.com/page-title. Under the Pathauto settings found at /admin/config/search/path/update_bulk there are options to Select the types of paths for which to generate URL aliases which allows for selecting different entities such as Content. Additionally there is Select which URL aliases to generate where we want Update the URL alias for paths having an old URL alias as the choice.

We don't want to update all Content entities, but rather we want to update by content type.

How would we update URL alias after changing the path pattern by content type either programmatically or through an existing module?

The goal is to be able to do update all Basic Pages URL alias, but not others.

you can disable patterns that you dont want to update. In this way update will only update the patterns belong to content types


Set different page and window titles What I'm trying to do seems simple, and I'm sure it is, I just don't know what theme files need to be modified and how to modify them.

I want to make the user profile page display the user's first and last name (custom fields assigned to the User profile) as the title, rather than their username (which is default).

What I'm assuming can be done is intercept the title variable somewhere and change it to what I want.

How can I do this?

Cheers.

In Drupal 7, the template file that sets the title shown in the browser page is html.tpl.php, while the template that sets the page title is page.tpl.php.

Both the templates don't receive a variable containing the user object to which the page is referring, as those templates are used for every page. If you want to change the titles only for user pages, then you need to get the user object using menu_get_object('user'). The function returns FALSE if the currently shown page is not a user profile page; that is what happens when the viewed page is, e.g., example.com/node/1.


Can't Review Order, button loops back to checkout form '/cart/checkout' I'm having a problem which is prevent me from reviewing my order after completing the checkout form. Once I click on "Review Order" the page essentially refreshes itself because of the loop. Others with the same issue have varying solutions, I've tried a handful so far without any luck.

It seems the issue may be with the session being lost somehow, but I'm not sure what could be causing this. I haven't changed anything related to ubercart in months, yet the problem appeared days ago. Any suggestions or work arounds would be greatly appreciated.

I'm using PayPal Website Payments Standard, Drupal 6.2, Ubercart 6.29.

Thanks.

Thanks to David's response, I was inspired to investigate my upgrade from uc 2.8 -> 2.9 and ran the update.php script. It seems it was not run at the time of the upgrade, so now that it has the problem is solved.


How to add a value to an entity reference field set to unlimited values using entity metadata wrapper Im new to drupal and im trying to perform this operation, can some one help me on how can i add a new value to an entity reference field that its been set to hold unlimited values using the entity metadata wrapper only
this is what i have tried

$ewrapper->entity-reference-field->set($value);

this will overwrite the current value and i want to add to it

$wrapper->field_foobar[] = $additional_value;

Just change field_foobar to the machine name of your entity reference field.

The empty brackets insure a new value is added rather than overwriting existing value(s).

Good luck!


D6 Is it possible to set node reference field and use this value in another field on the same node/add form? I have two node reference fields in a Content Type.
Driver
Manager

Each driver belongs to a certain organisational unit. Every organisational unit has a set of managers. I need the organisational unit to retrieve the right selection of managers in the node reference field Manager.

Now I need to select the driver, save the node and edit the node again. Then I can select the manager from the right set of managers (based on the organisational unit token I supply in the node reference field).

Is there any other way I can do this without implementing a 2-step form?

These two modules are intended for that purpose and have D6 versions.  I think Dependent Fields sounds closer to what you want, but Hierarchical Select Node Reference may work almost as well.

Dependent Fields

  The Dependent Fields module (formerly AHAH Dependent Fields) allows cck based fields to specify another field as a controller field, and react to its changes on the form using AHAH/AJAX without the form re-loading.

Hierarchical Select Node Reference

  This module allows the use of Hierarchical Select form element as a widget for CCK node reference field, both in node add/edit form and in views filter.


How to propely add views grouped filters with exposed filter in one of them I have a views with grouped filters like this

Group 1
field_1_condition
AND
field_2_condition (exposed)

OR

Group 2
field_3_condition
field_4_condition

I am expecting it to work like this:
Filtering is done based on the first group and input comes from user to the exposed  filter field. Then I want the query to check the second group and add all the matching things from there.

The initial query seems to be correct but as soon as I give input to exxposed filter the query is wrong. Views tries to combine similar fields for some reason

Initial query with those groups:

SELECT DISTINCT node.title AS node_title, node.nid AS nid, node.language AS node_language, og_membership.gid AS og_membership_gid, node.created AS node_created, 'node' AS field_data_field_event_date_node_entity_type
FROM
{node} node
LEFT JOIN {og_membership} og_membership ON node.nid = og_membership.etid AND og_membership.entity_type = 'node'
WHERE (( (node.type IN  ('birthday_event')) AND (og_membership.gid IS NULL ) AND (node.status = '1') )OR( (node.status = '1') AND (node.type IN  ('event')) ))
ORDER BY node_created DESC

The query when exposed filter gets input

SELECT DISTINCT node.title AS node_title, node.nid AS nid, node.language AS node_language, og_membership.gid AS og_membership_gid, node.created AS node_created, 'node' AS field_data_field_event_date_node_entity_type
FROM
{node} node
LEFT JOIN {og_membership} og_membership ON node.nid = og_membership.etid AND og_membership.entity_type = 'node'
WHERE (( (node.status = '1') AND (node.type IN  ('event', 'birthday_event')) AND (og_membership.gid = '1') ))
ORDER BY node_created DESC

This is the image of my views filter settings

I am still waiting for a response to do this more elegantly but since I am in a hurry I wrote a query alter to accomplish what I need. Maybe it's helpful to someone

function custom_views_query_alter(&$view, &$query) {
  if ($view->name == 'ts_group_events' && $view->current_display == 'calendar') {
    if (empty($query->where[2]['conditions'])) {
      foreach ($query->where[1]['conditions'] as &$condition) {
        if ($condition['field'] == 'node.type' && $key = array_search('birthday_event', $condition['value'])) {
          unset($condition['value'][$key]);
        }
      }
      $query->where[2]['conditions'][] = array(
        'field' => 'node.status',
        'value' => 1,
        'operator' => '='
      );

      $query->where[2]['conditions'][] = array(
        'field' => 'node.type',
        'value' => array('birthday_event'),
        'operator' => 'in'
      );

      $query->where[2]['conditions'][] = array(
        'field' => 'og_membership.gid',
        'value' => NULL,
        'operator' => 'IS NULL'
      );
    }
  }
}


Display both sort icons on sortable table columns I'm using Drupal's theme table function to build a custom table.

All of the columns on my table are sortable. I would like to visually indicate that they are sortable by putting both an ascending and descending sort icon in the column header.

To indicate which sort is active, I would like to show only one icon, corresponding to the current sort (ascending or descending).

Here's what I have:

Here's what I want:

How can I accomplish this?

So far, the closest I've gotten is overriding theme_tablesort_indicator(), but this will only let me override the icon for the active sort. (Docs here)

I used some jQuery and CSS to accomplish this:


Add VBO checkbox to send Bulk emails in Admin We are using Enterprise Event module in Drupal 7.  I checked the Views and module files but not able to locate the file as from where Manage Registration Page is formed. Please guide me how I can add VBO checkbox to send Bulk emails in Admin > Content > Event > Edit > Manage Registration Tab.

I am using enterprise event module in which people register for upcoming events. Registration module is used for registration. Admin can view registrants for  specific event.  I need to add a checkbox so that admin can send bulk emails to those registrants.

Please help still hoping for some solution.

This is how you do it:

Go to Structure > Views and locate the Test Event view.
Click the Edit button.
Find the Fields display and click the Add button.

Filter the available fields by Bulk Operations and select a field you need, e.g. Bulk Operations: User.

Now the settings for this field show up. Scroll down to Selected Bulk Operations and select Send Email.

Click Apply.
Don't forget to save your view.
Now you should have a checkbox and you can select Send Email from a drop down menu.

I'd personaly would not use the VBO field but the Views Send module which is a bit easier to use. If you have the Views Send module, add the field Global: Send Email instead of the VBO field and proceed as described above.


Display comment titles only Is there a way in Drupal 7 to display only the titles of node comments beneath the node (hopefully threaded), thus allowing users would click on title to see the full comment?  This was essentially the behaviour in Drupal 6.  In Drupal 7, I only see how to list the full comment title and body, or no comments at all.

Thanks for any suggestions.

Drupal 7 does not have this feature.

All you have to do is create your own javascript/jquery (.js) file and do something along these lines.

(function ($) {
     $(".commentbody").hide();
          $(".commenttitle").click(function() {
          $(this).parent().find(".commentbody").slideToggle();
          });

})(jQuery);

Here is an example JS FIDDLE


Use drush instead of vendor/bin/drush I try to get drush to run by calling just 'drush' and not 'vendor/bin/drush', I'm working with OSX Sierra. This doesn't work out as I want hope someone can help me with this.

When i follow the instructions here:
http://docs.drush.org/en/master/install/

When at point 3:
If you want the convenience of calling drush instead of ../vendor/bin/drush, copy the examples/drush.wrapper file to your Drupal root and modify to taste.

I get stuck. I copy the drush.wrapper file to my root and rename it to drush . Then I edit the path to:

cd "`dirname $0`"
vendor/bin/drush.launcher --local "$@"

Because I'm in the root I removed the ../ before vendor. When I save all I stil get:

  bash: drush: command not found

When I try going to: vendor/bin/drush.launcher it runs perfectly. What am I doing wrong?

This isn't really a Drupal or Drush question, but a Bash/shell question: How to run a script in the current directory?

The script must be executable: chmod u+x drush
The script must be in the (executable) path. Since it's not recommended to have the current directory in the path (for very good security reasons), the solutions is to call Drush as ./drush instead of just drush.


Override Field.tpl.php for a specific node/add form Basic Question

In Drupal 7, you can override all the fields of a specific content type by changing the field.tpl.php file name to field--YOUR_CONTENT_TYPE.tpl.php

How can you override the fields that appear on the "node add form" for a content type?

More Info

I am using Drupal Commerce Bulk Product Creation and with this module you create your nodes at yoursite.com/admin/commerce/products/add-bulk/PRODUCT_TYPE.

I want to over-ride the field.tpl.php file for this name, but I am not sure how to do it.

I know you can override the node.tpl.php for this "node add form" by using the following in your template.php file:

function YOURTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'commerce_bpc_create_bulk_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/add/node--add--bpc',
            'render element' => 'form',
            ),
    );
}

Is there a similar code that can be used to override the field.tpl.php file for this node add form?

Implement hook_form_alter() or one of its relatives by setting the #theme key of the form elements.