How to force Local Task Menu to display on specific pages I’ve made a tabbed display out of my Local Task Menu as imaged.

Some of the extra buttons are ‘pages’ as made with ‘pages manager’  .  Here you can assign the page to the Local Menu; when doing so by this method the created page also shows with these user tabs.

However a couple of pages ( one created by the Nodequeue and the other a Custom Module made by myself ) ; with these I’ve assigned to MENU_LOCAL_TASK  in hook_menu_alter   .  And although they show up in the menu when clicked on they no longer have the Local Task Menu.  Does anyone know a way I can force these pages to show it ?

Many thanks

I managed to solve this be engineering a fix with ( https://www.drupal.org/project/local_tasks_blocks )

There is a patch here at https://www.drupal.org/node/2141653 for 'Fixed path for displaying tabs'  which sounds like the same issue I had .  However the patch didn't work for me.

Checking the value of $tasks['#primary'] ; I concluded that if I could keep this array for a session then I could use the Local Tasks Menu on all the pages I wished while the User is logged in.  Ie something like

if (empty($tasks['#primary'])) {

// 1.  Check the cookies if we have one then use that
if (isset($_SESSION['usertasks']['primary'])) {

$tasks_primary = $_SESSION['usertasks']['primary'];
$tasks['#primary'] = $tasks_primary;
}
else {
$usertasks = &$_SESSION['usertasks'];
// well need to create a new instance of this array so we don't    effect it for the page we're on
$tasks_primary = $tasks['#primary'];
$usertasks['primary'] = $tasks_primary;
  }
}

My next step is to make a patch for this if anyone else may find it of use.


Getting og membership type in template.tpl.php I want to obtain the organic groups role-id of a node/comment-author in node.tpl.php and comment.tpl.php.

I can't find an array that provides this information.

I want to add a class based on the authors membership type.

Dummycode:

<div id="header" class="<?php if ($author->rid == 7): print 'class-7'; endif; ?>">

How to do this for nodes and comments?

Note: for normal (non-organic-group) roles I use:

<?php if(in_array('administrator', $user->roles)): print 'admin-type'; endif; ?>

Which works ok, I want similar usage for organic group roles.

Found the anwser:
This goes in node.tpl.php (tested on Drupal 7, Organic groups 7.x-2.3)

<?php if (og_context()) {
  $group = og_context();
  $userid = user_load($node->uid);
  $roles = og_get_user_roles('node', $group[gid], $uid = $userid->uid, $include = FALSE);
  }
?>

Then use it with something like:

<?php if(in_array('test member', $roles)): print 'Testuser'; endif; ?>

For comments it's a little different:

<?php if (og_context()) {
  $group = og_context();
  $roles = og_get_user_roles('node', $group[gid], $uid = $comment->uid, $include = FALSE);
  }
?>

Works only on pages where groupcontext is available!


What invokes Bootstrap overrides.css? I have a purchased theme that I've cloned, to which Bootstrap is set as the base theme.
I've done the standard rebranding procedure of renaming all of the files and functions to match the new theme name [theme2].
It's mostly working, except that /themes/bootstrap/css/overrides.css is loading in theme2, and its causing a few issues.
It doesn't load in the original theme1, and everything is fine.

It doesn't seem to matter if CDN is on or off.

What invokes Bootstrap overrides.css?

Any thoughts?

The default Drupal Bootstrap 3 subtheme has all the required LESS files, which includes the overrides.less file. This file, and all others, is rendered into the style.css file by the LESS processor HOWEVER this can change if your processor is wrongly configured, so make that the first thing to check. Then check that your theme .info file is only referencing the css/style.css file and not any other css files.

https://www.drupal.org/node/2052931


How can I rewrite a date field "End Date" to be "present" if no value is entered? I have a date field for an item in which I am entering a range of years. I have created a view which displays the start date and end date as individual fields. Typical output looks like this:

  Title: Pop Art
  Start Date: 1958
  End Date: 1970

However, there are several items which do not have an end date because they are ongoing. Even though for the end date field's "No Results Behavior" I have "No results text" set to the word present it renders the start date in place of my rewrite text:

  Title: Contemporary Art
  Start Date: 1970
  End Date: 1970

I want it to do output like this:

  Title: Contemporary Art
  Start Date: 1970
  End Date: present

How can I get the end date to render as the word "present" when no end date is specified?

Note: in my final view I will output the date range as, "1970-present." Above, I formatted my examples as "label: value" for clarity.

When there is no end date specified for a node it takes both the dates same. The module consider it a one day event.

However, in your case you are making it ongoing by not mentioning the end_date so no results behavior is not going to work. I would suggest to use some global php like this

<?php
if($row->field_date == $row->field_date_1) {
   echo "Present";
} else {
  echo $row->field_date_1;
}
?>

Make sure to include this php field after both start and end date fields, and make the end date fields hidden.


Hook_form_alter in Views header PHP code I have a content type called 'Checklist' which I bring forward using Views, in it's node-edit form.

I wrote PHP code within the header in order to do this, here it is:

<?php

    $view = views_get_current_view();
    $arg0 = $view->args[0];

    $nodeToLoad = $view->result[0]->nid; //I get the node to load from Fields within my view
    module_load_include('inc', 'node', 'node.pages');

    $node = node_load($nodeToLoad);
    dsm($nodeToLoad);
    $edit_page = drupal_get_form('page_node_form', $node);

    $edit_page['additional_settings']['#access'] = FALSE;
    $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';
    print drupal_render($edit_page );

    function redirect_submit($form, &$form_state){
        $form_state['redirect'] = 'www.google.com';
    }
?>

I'd like to remove the 'Delete' button of this form(which normally deletes the content).
I have read that this is easily done with hook_form_alter() but my code resides within the header of a View and I'd like to keep it that way.

Is there a way to do this?

Found a solution, but if there is a better way I'd like to hear more.

$edit_page['actions']['delete']=false; //removed delete button
$edit_page['title']=false; //removed title display as well


How to create field template for displaying taxonomy terms as list in full content page? We have a content type displaying taxonomy term input as one of its fields. The goal is to display the one or more terms as an unordered list. That is not an option available in the Manage Display tab, and the default display does not break the entries into separate lines:

Editing the theme's template.php file by changing

$output .= ($variables['element']['#label_display'] == 'inline') ?
'
' : '
';

to

$output .= ($variables['element']['#label_display'] == 'inline') ?
'
' : '
';

we get the desired bulleted list:

– but that is not desired as the default in other content types.

How can this display be customized to be unique to this content type? From some reading it is understood that a custom field tpl.php could do this, but help is needed in understanding how to set that up for this unique situation. Can anyone suggest a path?

--Thanks--

Use template_preprocess_field()
You can try something like this in your template.php:
/**
 * Implements template_preprocess_field().
 */
function YOURTHEMENAME_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#object']->type == 'YOUR_CONTENT_TYPE_NAME') {
    $output = '';

    // Render the label, if it's not hidden.
    if (!$variables['label_hidden']) {
      $output .= '
' . $variables['label'] . ':
';
    }

    // Render the items.
    $output .= ($variables['element']['#label_display'] == 'inline') ? '
' : '
';
    foreach ($variables['items'] as $delta => $item) {
      $output .= '
' . drupal_render($item) . '
';
    }
    $output .= '
';

    // Render the top-level DIV.
    $output = '
' . $output . '
';

    return $output;
  }
}

Once implemented, try flushing you theme cache, it should work.


How to handle Custom Validation in inline entity Form? I'm using Drupal8's inline entity form and is having issue with writing custom validation. I found few links and wasn't helpful at all. Does anyone know how to handle this?

You have to use inline form alter for custom validation in module shown below

/**
 * {@inheritdoc}
 *
 * Implements hook_form_alter().
 */
function module_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {

  // Added custom validation
  if ($entity_form['#bundle'] == 'bundle_name') {
    $entity_form['#element_validate'][] = '_custom_validate_function';
  }
}

And implement that validation like below.

/**
 * Custom validation.
 */
function _custom_validate_function(&$form, FormStateInterface $form_state) {

 $triggering_element = $form_state->getTriggeringElement();
 $values = $form_state->getValues();
 // or you can use $form_state->getValue('field_name')
 // Validate your functionality

 // Set Error for form
 $form_state->setError($form, t("message"));
 // Note: $name may be unknown in $form_state and
 // $form_state->setErrorByName($name, $message) may suppress the error message.
 // hence use above $form_state->setError()
}


Body classes still showing 'page-node-#' instead of title or menu word I'm trying to get either the title of a page or the menu entry to be listed as a class in the body tag. I came across a posting here utilizing this code:

function THEMENAME_preprocess_html(&$vars) {
  $path = drupal_get_path_alias();
  $aliases = explode('/', $path);

  foreach($aliases as $alias) {
    $vars['classes_array'][] = drupal_clean_css_identifier($alias);
  }
}

flushed all caches but my body tag still looks like:

<body class="html not-front not-logged-in no-sidebars page-node page-node- page-node-47 node-type-page section-content">

So instead of that page-node-47, I'd like to see 'about-us' or whatever the path or title of the page is. I guess the path would be a better option for a class name but I'm not picky on that matter right now.

I do have Pathauto and clean urls installed and working. And in my html.tpl, I do have this:

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

I noticed that your function is named THEMENAME_preprocess_html(). If you don't have THEMENAME replaced with the name of your theme, the function won't be called and your classes won't get added.


Make the Main Menu have dynamic links based on url My main menu has links to common things: HOME | PHOTOS | VIDEOS ... etc. Home points to /, PHOTOS points to /photo-galleries and VIDEOS points to /videos

The client has added a new feature request and I'm trying to figure out how to handle this. The site has a couple of general topics, let's say baseball, football and soccer.

When I browse to the main home page /, then the menu should point to /photo-galleries and /videos.

However, when I browse to the "baseball filtered" home page /baseball then I'd like the photo galleries menu link to point to /photo-galleries/baseball and the videos link to point to /videos/baseball.

This "filtering" should follow them through out the site, so once they are on /videos/baseball then all of the menu links should continue to have the baseball element on them.

I'm unsure how to approach this problem and I feel like there should be an elegant way to handle this and I'm not the first person to have this problem.

I understand how to setup my various Views on the different pages so they have contextual filters and only show the content items with the baseball tag, but my big question is about how to handle re-writing all of the URLs of the menus and the content URLs.

Help? :)

3 (updated) options (or a combination thereof) for you to consider:

The drupal module Menu Token provides the ability to put variables in your menu options -- and used in conjunction with your existing context filtered views, may work for you if it allows you to construct the menu options you need based on other tokens that it makes available to you.
The other option is to consider an alternative approach (sorry! :) ). This would be faceted filtering. Follow the tutorials here: http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages
This is possible on even the most modest of hosting as it does not require Solr (but it can use it if you need that functionality later).
(added in update) Drupal module Menu Trail By Path

I think option 1 (perhaps in conjunction with option 3) might be the closest to what you are looking for though.


How to override entity:link() function? I have an entity with entitylisthandler.

In entitylisthandler, i have a function to build row like:

public function buildRow(EntityInterface $entity) {

    /* @var $entity \Drupal\mymodule\Entity\xyz*/
    $row['id'] = $entity->id();
    $row['config_name'] = $entity->link();
    //$row['first_name'] = $entity->first_name->value;
    $row['ctype'] = $entity->ctype->value;
    return $row + parent::buildRow($entity);
  }

In @line 3:

$row['config_name'] = $entity->link();

I'm calling link function here which calls entity canonical link.

How to change this default value 'canonical' to some other link like 'delete-form'?

This is the Drupal core link function which I'm trying to override in entitylistbuilder file.

public function link($text = NULL, $rel = 'delete-form', array $options = []) {
  return $this->toLink($text, $rel, $options)->toString();
  }

I have changed its argument from 'canonical' to 'delete-form', but it won't work.

You should not change the core function. What core does, if $rel is not set, it uses 'canonical'. If you want to use 'delete-form' instead, put this as an argument when using the link function:

$row['config_name'] = $entity->link(NULL, 'delete-form');

BTW, link() is deprecated, so use toLink() instead.


How can I send HTML newsletters? I have developed websites using Drupal since 1998. Getting Simplenews to send HTML formatted emails in D8 has been the most frustrating experience I've had in all those years. I am very upset. I find the current state of D8 documentation to be quite shoddy overall, not just Simplenews. Here's a glaring example of what I'm talking about: I'm building a D8 site using D8 modules. I go to the README file in the simplenews directory and I'm reading all about how.

  You can customize the theming of newsletters. Copy any of the *.tpl.php
      files from the simplenews module directory to your theme directory. Both
      general and by-newsletter theming can be performed.
      Theme newsletter body:

  simplenews-newsletter-body.tpl.php (for all newsletters)
  simplenews-newsletter-body--[newsletter_id].tpl.php
  simplenews-newsletter-body--[view mode].tpl.php
  simplenews-newsletter-body--[newsletter_id]--[view mode].tpl.php

Here's some news for the module developers: None of that exists in the D8 module! WTF, really? These are D7 instructions. Not very helpful esp since that README file contains some of the most complete and detailed instructions on this aspect of simplenews-- if you're using the D7 version, that is..

I have spent an all-nighter and several full days on configuring this. I'm using sipmplenews Version: 8.x-1.0-alpha2, mailsystem Version: 8.x-4.1, mimemail Version: 8.x-1.x-dev and smtp Version: 8.x-1.0-beta2. No matter what recipe I follow from the myriad of posts on this subject, this is what my HTML email messages look like when they arrive in my inbox: HTML tags visible and absolutely no formatting.

Testing 1234
 Testing 1234

View this message in your browser HERE.

 MICHAEL “SKEETER” PILARSKI

 <img alt="Friends of the Trees Masthead" src="example.com/sites/default/files/images/top-fts.jpg" style="width: 100%` ...

If anyone has this working or if there is a sympathetic developer out there, hear my plea: Someone please create a step-by-step basic simplenews configuration that anyone can follow to get simplenews to successfully send HTML formatted emails from a D8 website. If it was a configuration that was just enough to get it to work (with a designated theme and any other variables set), user customization could follow once a successful email has been sent This whole thing has worn me out.

Outdated documentation is one of the reasons why Simplenews is only in Alpha. Sorry you had a frustrating experience, but a lot of work of porting modules and writing documentation is done in (my) free time. It is one of the many contrib modules that I help maintain.

You're more than welcome to help improving the module and documention so the next person will be able to figure this out faster. Patches or simply  by writing documentation on drupal.org.

The template extension is now .html.twig, which you should quickly see in the templates folder of the module.

Also, the very first paragraph on the project page contains this:

  Simplenews publishes and sends newsletters to lists of subscribers.
  Both anonymous and authenticated users can opt-in to different mailing
  lists. HTML email can be sent by adding Mime Mail module for D7 and
  Swiftmailer for D8.

Swiftmailer requires a composer dependency and is a bit more complicated to install due to that, but it is what we've been using in our projects and should work well.

Also, make sure you enable HTML in the newsletter settings. And possibly try the latest dev versions if you have problems.


How to pull commerce_customer_address into the invoices view? I'm using Drupal Commerce for a hotel booking site so it's not following the typical Commerce use case. It works very well except for an issue I'm having where the Billing Info is not being automatically populated with the Account Info. This works in Commerce but not the way I'm using it. I spoke to some Commerce peeps and they confirmed this. As a work around and since I'm not using the Billing Info fields anyways, I thought why not just use the Account Info fields?

Well the problem is that I can't seem to call on commerce_customer_address in the invoices view. I don't see it in the relationships section. Does anyone know how I can do this? As a proof of concept, I added an entity reference field to orders and was able to manually pull the address from Account Info. I'd like to automatically pull this info.

Thanks.

If I read your situation properly, it sounds like you want to establish a relationship from an order to the user account that created it and include a field from the user account in the Views results. If so, the solution is the core Drupal Commerce relationship Commerce Order: Owner. With this relationship, you should be able to put any property or field of the user account responsible for the order into your Views results.

This relationship is a part of the admin Orders View by default, so perhaps there's something else going on in your case. If so, it would be helpful to know more about your customizations.


Customize what fields show on Views Exposed Filters Block I have configured an exposed form block, filtering by taxonomy list. What I need to do is simply display a field image before the taxonomy name. The actual display is  <Taxonomy Term Name> and what I need is <Taxonomy Term Logo> <Taxonomy Term Image>. I have looked on some places, but I couldn't get anything to work.

How can I achieve this?

Simply rearrange the fields i.e. put field image before the taxonomy name. You can get the rearrange button at right side of FIELDS in view configuration.


Where are templates from hook_theme stored in the database I have a module, called "bundles", there I created a file "attached_email.tpl.php" and a hook_theme:

function bundles_theme($existing, $type, $theme, $path)
{
    $path = drupal_get_path('module', 'bundles');

    return array(
        'attached_email' => array(
            'template' => 'attached_email',
            'path' => $path,
            ),
        );
}

I have 2 databases for this website: lwt (default) and lwt_test (for test data). I have written the template, cleared caches and imported test data into lwt_test DB. But the template is unavailable there. When I call:

theme('attached_email', $data);

From lwt database, it gives the output. But when I switch to lwt_test:

db_set_active('lwt_test');

nothing is given. I can only conclude, that there is some piece of data, stored in lwt database, missing in lwt_test database. And that's why Drupal doesn't see my new template.

Update

When I use this code:

print theme('attached_email');
db_set_active('lwt_test');
send_attached_emails($bundle_id, $users);
db_set_active();

It gives the correct result (probably the template is cached after the 1-st call).

Normally, db_set_active() is used to query external data.  I have never heard about it being used to switch between two full Drupal databases from within the same active codebase / website.

I suspect one or two things is happening: you are having cache problems and/or you are having registry problems.

When you clear caches via the UI or drush, the full registry gets rebuilt, which includes theme functions and their template files.  That information will get stored in whatever database is active at the time.

If you switch databases, the cache and registry will be pulled from the newly active database.   In addition, any new cache entries will be written to the new database.

So, I think your problem is that the wrong cache and/or the wrong registry is being queried when you use the Drupal API and you are getting stale data.

The proper way to accomplish this is to set up a dev/staging/live environment, where code goes forward from dev -> staging -> live, and databases go backwards from live -> staging -> dev.  There are lots of articles on the net, and a few questions here, about how to do this.


Possible to set user privileges on part of the text? In my node I have embeded a view using php snippet in body field. When regular user edits it I don't want him to accidently delete the snippet, is there a way to hide or lock that part of the text from that user so no matter what he does the snippet will remain there? Should I add a custom field just for it or are there a better options?
Also note, that the snipped could be placed in the middle of the body field content.

Thanks!

No, there are no ways to do this. And there shouldn't be. First of all, read PHP in database: bad practice but - this addresses exactly the situation you have here. Long story short: don't do it. Turn off PHP module if you don't need it.

And why you don't need it? Because there is Viewfield module.

  Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Exactly what you want to do, but without any snippets in user editable texts.


Can a module install a theme? I would like to know if it is possible to make a module install a separate theme as well. Should I just ask that whoever installs my module also downloads that theme to have a better experience?

Yes, it is possible. You can create a MY_MODULE.install file, add a HOOK_update() where you can call theme_enable and variable_set() to set it as the default theme.

Here is an example:

/**
 * Enable my_new_theme and set as default.
 */
function MY_MODULE_update_7001() {
  $themes_to_enable = ['my_new_theme'];
  theme_enable($themes_to_enable);

  // Set the theme as default.
  variable_set('theme_default', 'my_new_theme');
}


While migrating D6 to D7, should sites folder be replaced? I am trying to migrate Drupal 6.29 to 7.22. Part of migration I have deleted all files & directories except sites in D6 site. Now I downloaded Drupal 7.22. D7 version also has sites folder, so do I need to replace sites folder or not?
In documentation I read like while copying the sites folder which files need automatically will be replaced, when I am copying sites it is asking for replace or not. Totally confused, can anyone help on this, it would be greatly appreciated!

The upgrade documentation is quite precise about this step:

  Update to the latest available version of Drupal 6.x

  [...]

  Remove all old core files and directories, except for the 'sites' directory
  and any custom files you added elsewhere.  [...]
  If you uninstalled any modules, remove them from the sites/all/modules and
  other sites/*/modules directories. Leave other modules in place, even though
  they are incompatible with Drupal 7.x.
  Download the latest Drupal 7.x release from http://drupal.org to a
  directory outside of your web root. Extract the archive and copy the files
  into your Drupal directory.

 cp -R drupal-x.y/* drupal-x.y/.htaccess /path/to/your/installation

Executing the above shell command, will copy all the content of the drupal-x.y directory recursively to your installation directory. This will silently overwrite all files in your installation that are also in the drupal-x.y directory and create directories that are not already there. If there is a directory in both, say sites/default/files, only those files will be overwritten that are also in the source, and no files will be deleted from a directory, that is why you had to remove the core files in step 9. This is the default behaviour of cp. If you want to know more about how this works you could read man cp.

If you are not on unix or you don't have shell access to your server, you have to emulate this behavior (at the moment I cannot think about a copy function either on Windows or Mac that behaves differently, e.g. replacing a folder with files inside with an empty folder), because it is the recommended one, using the admin interface you have.


A user field's text format defaults to "- Select -", how do I force it to an allowed option? I have added a field, "Bio" to the user profile. All user roles have permissions for "Filtered Text", and the field text format settings are limited to "Filtered Text" only, with override default order on. I've set it to default to "Filtered Text" in the Default Value field as well.

When I edit my profile as an authenticated user (who only has permissions for "Filtered Text"), the selector refuses to default to "Filtered Text", as demonstrated in the screenshot:

How can I force this to default to Filtered Text, or moreover why is it not defaulting?

I have tried altering the field's text format in hook_form_alter, with the line:

$form['field_bio']['und'][0]['format'] = 'filtered_html';

but it still defaults to "- Select -"!

Is there another way to force, on the form, a default value in a hook?

The text format is added in an after build function somewhere. This is off the top of my head so might need some tweaking, but the idea will be very similar:

function MYMODULE_form_some_form_alter($form, &$form_state) {
  $form['field_bio']['#after_build'][] = '_MYMODULE_some_form_alter_textformat_options';
}

function _MYMODULE_some_form_alter_textformat_options(&$element) {
  $element[LANGUAGE_NONE][0]['format']['#default_value'] = 'filtered_html';
}


Use Bootswatch.com themes with Drupal Twitter bootstrap I would like to know the easiest, simplest and quickest way to use anyone of the bootswatch.com free themes. There are some great themes there, better than I could spend a good 4+ hours trying to do. I'm merely looking to 'experiment' with CSS styles, swatches and the like. Can someone tell us how we can simply 'drag and drop'. I've tried what I thought it would be but it doesn't seem to do what I want it too, I'm not looking to spend hours on this, just to experiment with D7 for a few visual ideas. I have revieed the drupal.org Themeing documentation but that routed a little too long winded at this stage.

I appreciate there are some general paths that need changing in the CSS file and that JS needs to be correctly pointed to. My recent efforts only result in my backend Admin going a little wayout and I presume that simly 'deleting/over writing current CSS files in  the CSS folder isn't exactly the 'quick' way to do things. My long term reason is so I can have a number of preset themes to work with which I prefer and can quickly 'drag and drop' new theme ideas with outspending hours for something which is only for 'eye candy' visuals.

I would rather to it 'hand coding' style rather than a easy 'module' option for those why may suggest in advance.

Thanks in advance.

Use the theme bootstrap

Download Bootstrap place it in the bootstrap theme folder as mentioned in the theme page. Update jquery to 1.7 you might have to use the Jquery Update (Use the development version of JQuery Update and not the stable one as the development version has option to update it to 1.7. You can do that by going to admin -> jquery Update

By default the theme uses the bootstrap.css So you can simply replace that css file with the new one you download from bootswatch and you are good to go...


Is it possible to get  form submission diff with Diff module Diff module, from what i've seen works with node revision differences, not node edit submission diff.

Is diffing any entity-related form submission possible programmatically through Diff module API? Suppose i alter node_form_submit() in my module and i want to record in watchdog the watchdog message the diff if this is a node edit event.

I try with diff_entity_diff($old_entity, $new_entity, $context) but i get no title changes and i'm not sure how to render this output.

Or in other words, which is the best way to get the diff of the submitted values of any form? (compare form_states)

Thanks

Problem is - diff compares entities and their revisions. But node_form_submit() happens before revision is created. If you will inspect node_save, you will see no hooks are called after actual save.

To get your code executed and be sure revision is there, it would be tempting to use Rules, but existing bug "After updating existing content" runs before content is saved. shows it has just the same issues as hooks. Maintainers say:

  We just rely on the hooks drupal provides us here.

So now you have 2 options:

Give up on using diff module and just borrow some of it's code (it's open source after all)
On save, set a hidden field "test with diff" to true, and on cron make actual testing. With */5 minutes CRON it will be almost as good, as instantaneous test.


cron_last vs node_cron_last variable I wanted to get the time of last node update (any node). So, then I thought I could simple pick last cron run time ( because I am using feeds module to pull the RSS feeds so nodes will be updated on every cron run ). but then I discovered another variable "node_cron_last".

Can anyone explain me the difference between two variables, what value they contain?

The only place node_cron_last is set is in _node_index_node(), which is run when indexing a node for search results.
Its purpose, per the comments:

Save the changed time of the most recent indexed node, for the search results half-life calculation.

cron_last is simply used to

Record cron time.

per drupal_cron_run()
Given that REQUEST_TIME is used for all values (cron variables + node changed date) in the same request, you might well expect those two variables to contain the same value.


Commerce usps won't get rates Drupal 7, commerce shipping 2.0, and usps shipping method. Configured the product types with weight and dimension physical field. All products have weights and dimensions. All USPS services checked. The username and the connection address are set. The shipping service pane is in the correct sequence in checkout (after shipping info). At shipping services during checkout I get "No shipping rates found for your order. Please continue the checkout process."

I had added the weight and dimension fields to the existing products using defaults. I needed to save each product for these to take effect. Works now.


Drush cc all 'Killed' With a D6 instllation I am seeing 'Killed' returned whenever I try to clear the Drupal cache.

Verbose output gives me this:

Initialized Drupal 6.30 root directory at /var/www [notice]
Intialized Drupal site default at sites/default [notice]
Undefined variable: may_cache feed_field.module 12 [notice]
Killed

The string "Killed" doesn't exist in the Drupal 6.30 codebase.

You might have a custom/contrib module which is responsible, or perhaps a Drush extension.

If that's the case, to find it:

grep -nr "Killed" /path/to/drupal/root
grep -nr "Killed" /path/to/drush/extension/folder

(The extension path will probably be ~/.drush)


Cron runs in all server instances We are facing really big issue with the cron. Our site is running on 2 ec2 instances under the load balancer. We have lot of cron tasks which are performed every day. But the problem comes when the cron run, during this time all instances start processing the cron jobs, and site will not be accessible for the users. Here all the instances are sharing the same db including the staging instances(another 2 instances). I don't understand that, why all instance's CPU utilization is going high when cron run(all 4 instances).

Because of this behavior, what we are planning now is, to move the cron to a separate server, there it will perform all the jobs. But I'm not sure how I can achieve this.

How can I move the cron job to a separate server?

Instead of moving cron, you need to look into what parts of cron are so CPU itensive and why it takes such a long time to complete.

You can start by logging executed tasks, how when they start, finish and a comment about what they do.


How may I simplify the registration process I Try to use RNG to allow student user to registrer for company interviews (the events). I set up a View on my event to allow student to register for an interview.

It seems a bit complex because they had to click on a link (register) to a page where they have to click on a create button under a select Identity where there is only one mandatory "My account" radio ?

Is there a better way to do that with RNG, or maybe a more suitable module, I am indeed trying to create a n,n relationship between user and event.

I give a try to basicCart module, but I don't need the order part.

You could do it using Flag and Views.

Once you create a node flag, then all the user needs to do is click on the node flag to register to the event/interview.

If you need to know which users have registered for an event, in Views, simply add a relationship of flag (can't remember the exact relationship name, but I am sure you can figure it out, might be "users who flagged").


How to display date/ time of current user base on time zone? Is it possible to display date/time of current user in his/her profile page. It should be base on his/her time zone settings. How can I achieve this goal?

You can modify the user pages (view/edit/etc) with the user templates, like the user profile template In the template's top documentation there's some good info like:

 * Use render($user_profile) to print all profile items, or print a subset
 * such as render($user_profile['user_picture']). Always call
 * render($user_profile) at the end in order to print all remaining items.

So you can first dpm the $user_profile array and find out the user's timezone, then add php code after the print render($user_profile); to print the date/time according to the timezone value you retrieved from the user profile array.


multiple sort comments in drupal like what you can see in this site, I want to have 3 tabs for comments.

oldest first

newest first

sort by likes

I've tested creating views and show in tabs but this way in too heavy!

is there a better way?

Quick Tabs

  The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*. You can
  create a block on your site containing multiple tabs with
  corresponding content.

Make 3 view blocks of each, and then create a quick tab of views and enable ajax so the other tabs load only when they get clicked.


What is causing this duplicated node issue? I have the following error: When I create a new node from the new data of my external database (inserting a new row in the external database), the new node is duplicated (but it doesn't have type, language, user); this causes the following error:

  Invalid argument supplied for foreach() en /path/web/my_proyect/sites/all/modules/cck/content.module on line 1284.

With my other module, I first extract all the rows of my external database, and convert them in nodes.

I don't know why; I debugged my code, but I don't understand that it is causing the problem.

This is the code of my module.

/* Implement of Hook_cron */
function node_db_extension_cron(){
  inspectAddHoteles();
  drupal_flush_all_caches();
}

function getHotelFromDrupal() {
  $type = '[my_type]';
  $query_nid = "SELECT count(nid) count FROM node WHERE type LIKE '%s'";
  $result_start = db_query($query_nid, $type);
  $cantidad = 0;

  while ($row = db_fetch_object($result_start)) {
      $cantidad = (int) ($row->count);
  }

  return $cantidad;
}

function getHotelFromExternal() {
  db_set_active('external');

  $result = db_query("SELECT count(id) count FROM [my_table]");
  $cantidad = 0;

  while ($row = db_fetch_object($result)) {
      $cantidad = (int) ($row->count);
  }

  db_set_active('default');

  return $cantidad;
}

function inspectAddHoteles() {
  global $user;

  $cantd_actual_hotel = getHotelFromDrupal();
  $cantd_final_hotel = getHotelFromExternal();

  /* With the count of nid of drupal and id of db external, i verify if exist new rows  because the count of nid of content and id of rows of my db externa should be equals if don't exists new rows on my db external */

  if ($cantd_actual_hotel < $cantd_final_hotel) {
    db_set_active('external');

    $cant_add = $cantd_final_hotel - $cantd_actual_hotel;
    $query = "SELECT * FROM [my_table] ORDER BY id DESC LIMIT %d";
    $additional = db_query($query, $cant_add);

    db_set_active('default');

    while ($row = db_fetch_object($additional)) {
      $node = new stdClass();
      $node->uid = $user->uid;
      $node->type = 'my_type';
      $node->title = $row->title;
      $node->body = $row->body;
      $node->created = time();
      $node->changed = $node->created;
      $node->promote = 0;
      $node->sticky = 0;
      $node->format = 2;
      $node->status = 1;
      $node->language = 'es';
      //All field of my content type

      $nodo_1 = node_submit($node);
      node_save($nodo_1);
    }
  }
}

The function node_submit() contains the node_save() function. So you call it twice.


Where can I download the Windows installer for Drush? I cannot find the link where to download Drush windows installer.
Can anyone tell me if there is or how to do?

I am using Drupal 8.1 and Windows 7.

You need to install it using composer as specified here:

https://github.com/drush-ops/drush/blob/master/docs/install.md

After installation, make sure to run and use the drush command inside Git's shell only (the shell environment bundled with Git for Windows)


Link Taxonomy with Node via Feeds, Entity Reference and Views I have a JSON feed that basically describes various objects described in an object lets say for example different cars.
In the feed, there is an object_type attribute that is just a number. Those numbers refer to different car brands which are described in a list object.

Thus the JSON Path is similar to:

$.object.object_type
$.list.id
$.list.name
// Where if 'object_type' == 'id', then display: 'name'

I've created 2 Feed Importers using JSONPath and was able to add my 'objects' (cars) to a custom node item (car_item) as well as to add my 'list' (of car brands) to a taxonomy vocabulary (brand_vocab). However I don't seem to be able to actually 'link/relate' them together.

For the brand_vocab, I have added an Entity Reference field (field_brand_id) and set the Target Type to be a Taxonomy Term (using Mode simple).
For my Feed Importer for car_item's, I`ve added the mapping for the json query to link to field_brand_id and set it to id for the query.

In fact, the taxonomy terms don't contain the filled in results for the id even though when I debug the Importer it all works fine.

Ideally I want my custom view to have a drop-down filter of the taxonomy terms (car brands) for the different custom nodes (car items). I have the view set-up, with the taxonomy vocob (brand_vocab) as a drop-down, just the filter doesn't work as the link between the node and taxonomy isn't working yet.

UPDATE: 10/01/2012

Ok so at the moment I have:

Feed Importer

Object (Cars)

Set as Custom content Type: Cars
Mapping for: name
Mapping for: brand

Object Type (Car Brands)

Set as Tax Term: object_type
Mapping for Term Name: name
Mapping for Term GUID: guid

Content Type

Cars

name
brand = Entity Reference
Target Type: Taxonomy Term - object_type

Now viewing the actual node for the Cars - I have the right Car Brand showing up as name and not the 'id' which is what I want.

However, the taxonomy term is not actually added to the Content type.

That and I have 2 Entity References that I need to use (Object Type and Category Type), however the content type shows both as the same term! So it seems to be that Entity Reference just checks the ID and then displays that and not the ID and Vocabulary (since I selected one ER to be for 1 Vocab bundle, and the other to be for another Vocab bundle).

What am I missing?

OK so I decided to scrap the Taxonomy Vocabulary and use new Content Types instead.

Haven't been able to figure out a good way to link multiple Taxonomy Vocabularies to Content Types via importing in Feeds and using Entity Reference with Views.


Contextual Filter / Relationship I'm having difficulty with setting up a view in Drupal 7. I'm going to use a sports example as a way to illustrate my problem:

I have three content types:
1. Team
2. Roster
3. Player

On the ROSTER editing page, I select which TEAM this roster belongs to, via Entity Reference.

On the PLAYER editing page, I select which TEAM this player belongs to, via the SAME entity reference field.

I've created a view, specifically a block, that lists the players on the roster page. However, right now, it's displaying ALL players. I know this is what contextual filters/relationships are for.

However, I get lost in the contextual filter and relationship settings. I've read a lot of documentation about each, impressed by all the different explanations and demos, but can't seem to find the right configuration that works for my problem.

I'm trying to filter the players on the ROSTER page, based on the TEAM that is selected both in the ROSTER and PLAYER content types.

Any help, suggestions, advice is appreciated. Thank you.

a roster lists the players on 1 team, correct? If the view is at a url like roster/TEAMNAME you want a listing of players where the contextual filter on teamname provided by argument 1 in the URL, or else 404 or hide the view.

If the roster is not on a URL but say a block on 1 players page (showing the rest of the player roster for his team) then I would add a Views Field View to the player content type that uses the player's own team as the argument to the View I describe above.

Contextual filters are good when you provide the context for the view (like a URL, or another field). relationships just help you to get more information into your view (like additional fields).


hook_cron_queue_info stopped I'm trying to use Drupal Queue and Cron to execute a task.
In the following example I:

select all the users
create an item in the queue for each of them
define the function that has to be run for the items of the queue

What happen is that at some point the system stops running the queue and the only way to start again the process is to kill it. (I'm using Ultimate cron to controll Cron processes).

I understood that after some time the system should stop the script and start it again at the following cron job. Am I wrong?

Here there is the code:

 function mymodule_cron() {
        $sql = db_query("select u.uid, u.mail FROM {users} u WHERE u.status=1");

    $queue = DrupalQueue::get("testlogging");

    $number_of_rows = $sql->rowCount();
    if ($number_of_rows > 0) {
        foreach ($sql as $record) {
            $queue->createItem($record);
        }
    }
}

function mymodule_cron_queue_info() {
    $queues = array();
    $queues['testlogging'] = array (
      'worker callback' => 'log_user',
      'time' => 300,
    );
    return $queues;
}

function log_user($record) {
    watchdog('MyModule', 'queue info: uid = ' . $record->uid . " " . $record->mail);
    sleep(2);
}

If you are sure that your execution do not produce programming errors, the problem may come from the fact that Drupal only executes queue items when running Cron. Taking into account that Drupal Cron is limited by time and PHP memory, your queue items may not be fully processed in a single Cron run.

You can refer to this issue I created some time ago about a very similar problem.

In short, I solved it by processing queue items every X minutes.


How to add profile image into user profile I am using D6. I want that users are able to upload their profile image like gmail, Facebook. How can i do this?

In Drupal 6 the, goto solution for this is the Content Profile module which allows you to add CCK fields to your user profile (in Drupal 7, the fields API allows you to do this in core):

  This module builds user profiles as content (aka nodes), which opens
  the opportunity to use all the powerful modules for content for user
  profiles too, e.g. the Content Construction Kit (CCK). It's intended
  to be simple and useful, but extensible by further modules.

You will also want to install the imagefield module to be able to add an image upload CCK field.


Wrapping a rendered file from Media with a link This is a question related to How to set Media Styles in Media 7.1.2 / Media 7.2.X?.

I am using Media 1.2 in a Drupal 7 site to add some fields to images (caption, credit, etc).

If I have an image field set up to display as a Rendered file with a particular view mode, eg

I have my display set up the way I want to show the proper fields for this view mode.  In the file display, eg

is there a way to wrap the image in a link to the media/fid page?  I am not seeing how to do this from the UI, and Theme Developer isn't giving me any useful info for which theme functions and preprocess/process functions are being invoked between the one for the whole image field (as far as the content type is concerned) and the image itself (the actual <img/> element).

At this point, I do not want to switch to Field Collection, but would entertain switching to Media 2.x if that is my only option.

OK, here is the working code.

The Media module implements hook_file_formatter_info() to set up a callback for rendering images.

As is the Drupal way there is a hook_file_formatter_info_alter() to change the default behavior.  So, I took the default callback from file_entity.module and cloned it into a custom module.  I then wired this up with the alter.  My custom callback has some additional logic to check for an image style, and then wrap the element with a link.

The only real quirk is that the default implementation of theme_link() assumes it is a leaf element, so you need to render out the image element first.

As a side note, this is also how you would get alt/title text onto the images, which is missing by default.

function MYMODULE_file_formatter_info_alter(&$info) {
  if (!empty($info['file_image'])) {
    $info['file_image']['view callback'] = 'MYMODULE_file_formatter_file_image_view';
  }
}

function MYMODULE_file_formatter_file_image_view($file, $display, $langcode) {
  // Prevent PHP notices when trying to read empty files.
  // @see http://drupal.org/node/681042
  if (!$file->filesize) {
    return;
  }

  // Do not bother proceeding if this file does not have an image mime type.
  if (strpos($file->filemime, 'image/') !== 0) {
    return;
  }

  if (file_entity_file_is_local($file) && $image = image_load($file->uri)) {
    if (!empty($display['settings']['image_style'])) {
      $element = array(
        '#theme' => 'image_style',
        '#style_name' => $display['settings']['image_style'],
        '#path' => $file->uri,
        '#width' => $image->info['width'],
        '#height' => $image->info['height'],
      );
      if ($display['settings']['image_style'] == 'MYSTYLE') {
        $element = array(
          '#theme' => 'link',
          '#text' => drupal_render($element),
          '#path' => 'media/' . $file->fid,
          '#options' => array(
            'attributes' => array(),
            'html' => TRUE,
          ),
        );
      }
      else {
      }
    }
    else {
      $element = array(
        '#theme' => 'image',
        '#path' => $file->uri,
        '#width' => $image->info['width'],
        '#height' => $image->info['height'],
      );
    }
    return $element;
  }
}


How to network Organizations? I'm running OG 2.7.

I need to make it so ORG A can connect/ network with ORG B.

ORG A says "I'm affiliated with ORG B and want to show that connection." Currently, they would just select from an entity reference field containing a list of all ORGS, pick ORG B, and then ORG B would show up on ORG A's page as "in their network".

The problem is, ORG B may not agree that ORG A is affiliated and thus would want to approve or deny the affiliation. So I'm looking for a way to provide the same networking effect with approve/ deny functionality.

I've searched high and low for any glimpse of a way to achieve and have found nothing. Any help would be greatly appreciated, even if it's just pointing me in the right direction.

Thank you in advance

AFAIK there's no module which does this out-of-the-box for organic groups - the User Relationships module does this for users (https://www.drupal.org/project/user_relationships).

To achieve with groups, you could set up a similar system with flags and rules, i.e. someone can flag a group as a 'friend' or whatever, when they do, a rule sends a confirmation link to the friended group and they can then say they are friends with the other group (also using a flag). But I don't see why you'd do that as every person on the site is a user so you'd need to work out who has the ability to 'friend groups'.

A general observation - if you've looked around a lot for the functionality and it's not there, and it's fairly generic functionality (like 'friending') then you may be thinking in the wrong way about the problem and the problem may be solved by thinking about it different architecturally - I've been using Drupal for 8 years now and not had issues finding modules which fit to do the stuff I want to do.

HTH

Steve


How do I render content generated by a controller in a custom block? To render a form in a block, I can use the following code.

class LoremIpsumBlock extends BlockBase {

  public function build() {
    // Return the form @ Form/LoremIpsumBlockForm.php.
    return \Drupal::formBuilder()->getForm('Drupal\loremipsum\Form\LoremIpsumBlockForm');
  }

How can I render in a block the output of a controller? Is it possible, or do I have to duplicate the controller class code in the block class?

The example in the documentation is too simple and it shows how to render a literal string.

class HelloBlock extends BlockBase {

  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}

@4k4 is correct in their answer that it is preferable to refactor the shared code into a separate class (probably a service).

However, if that is not an option (because you are building on core or contributed code that you cannot change) it is still possible to re-use the output of a controller that uses dependency injection (DI). To do so, inject the class_resolver service into your block and use it to get a controller object. Your block code would look something like this:

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a custom block containing the output of a controller.
 *
 * @Block(
 *  id = "controller_block",
 *  admin_label = @Translation("Controller block"),
 * )
 */
class ControllerBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * Class Resolver service.
   *
   * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
   */
  protected $classResolver;

  /**
   * Constructs a new ControllerBlock object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param string $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
   *   The class resolver service.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    ClassResolverInterface $class_resolver
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->classResolver = $class_resolver;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('class_resolver')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    // Assuming that \Drupal\my_module\Controller\MyController::build is a
    // public function that returns the controller output.
    $controller = $this->classResolver->getInstanceFromDefinition('\Drupal\my_module\Controller\MyController');
    return $controller->build();
  }

}


Show content of type A in content of type B based on shared taxonomy term using views I want to show content of type A (products) in the middle of contents of type B(Producers), however I do not want to use Node reference since it's an overkill to make it happen with lots of products.

So far I have a Vocabulary which both content type share, so I thought if I choose a single taxonomy term when creating the contents of each type, I can relate them using views to each other based on that shared taxonomy.

Anyways so far no luck, I appreciate any helps.

Add a block view to show content of type A (products), add a contextual filter Content: Has taxonomy term ID, provide default value with PHP:

$node = node_load(arg(1));
return $node->field_term['und'][0]['tid'];

You can add safeguards, like is_int(arg(1)), is_object($node), $node->type == "product", etc. You don't need to if you add the block to a region and set it to be displayed on nodes of type B (producers) only.


Navigation links in a region rendering vertically I am trying to place a block, that contains a navigation menu, within the Navigation region of a Bootstrap themed Drupal 7 site.

The menu is drawn vertically, I assume from the fact that it's a block within the region, and it's overwriting some of the CSS..

It also seems that the UL that is generated for the menu doesn't have the necessary "nav navbar-nav" classes.

Is my only option to override the region.tpl.php, block.tpl.php and the definition for UL (which I have yet to find)?

You can copy the responsible template file from bootstrap theme and put it in sub theme. I think you will find your template under Menu folder in tempaltes of bootstrap theme (parent theme)
You will find these files and you have to modify one of these in order to achieve what you said.

menu-link.func.php
menu-local-action.func.php
menu-local-task.func.php
menu-local-tasks.func.php
menu-tree.func.php

Thanks


Start with multiple entity reference items In Drupal 8, I have created an entity reference to an "author" taxonomy on a content type. The form display settings are set to autocomplete. By default it starts with one field and you can click "Add another item" to add more. Yet usually we are adding content with multiple authors, so to make the form more user-friendly, would it be possible to start with four fields by default?

To add clarity to the question, the field currently starts like this by default:

I want it to start like this:

Any suggestions?

Try  Unlimited fields settings module may help you.


How to create a catalog site with views and taxonomy? I'm trying to setup a site where users can download pdfs that are sorted into different categories based what type are. I've coded out what I want in a html version (which is currently live here) but I need to make this into a CMS (first time for me in Drupal, I've been using other CMSs such Wordpress).

Here's the structure I'm after (also would like to have the URL aliases mention below):

Displayed on Main Download Page (url: domainname/downloadpage):

(Probably a block)

First Top Category

First Sub Category
Second Sub Category
Third Sub Category

(Also a block)

Second Top Category

First Sub Category
Second Sub Category
Third Sub Category

Displayed on Top Category Page (url: domainname/downloadpage/firsttopcategory):

(A block but doesn't have to be)

First Top Category

First Sub Category
Second Sub Category
Third Sub Category

Displayed on Sub Category Page [already worked this out- just trying to link/incorporate it] (url: domainname/downloadpage/firsttopcategory/firstsubcategory):

First Sub Category
[in a table]

Download Name  Field1 Field2  Download Link

Name  Field1 Field2  Download Link

I've already worked out how to create a content type for this, all I need to get this structure into place. This has been a good help but I can't seem to get the way I need it with what I'm after. If you could point me in the right direction in order to archive this, it would be very much appreciated.

Have a look at either of these modules, both have an official D7 version (quotes included are from their project pages):

Taxonomy Menu Block

  Taxonomy Menu Block allows you to make blocks containing unordered lists that represent the structure of your vocabularies, creating a menu out of your taxonomies (without using Drupal's menu system).

  Taxonomy Menu Block combines the idea of Taxonomy menu with the workings of Menu block:

  Make multiple menus per vocabulary.
  "Split" the taxonomy into different menus.
  This allows, for example, the creation of one menu with only the top items (parents) of a vocabulary and another menu with only the sub-items (children).
  Make a menu out of a specific branch of your vocabulary only.
  Follow the active trail, also for nodes coupled to a term with a term reference field.

  Taxonomy Menu Block also comes with its own theme function and a few hooks (see the .api.php file) that allows you to alter the generated data to your needs.

Taxonomy Block

  This module displays a list of taxonomy terms in a block from a single vocabulary.


Remove search form from search result page in Drupal 8 What's the best way to remove the search form from the search result page in Drupal 8?

There is not much you can customize in core search. So you probably need to override Drupal\search\Controller\SearchController::view and remove this line:

  $build['search_form'] = $this->formBuilder()->getForm(SearchPageForm::class, $entity);

Put your extended class into the route search.view_node_search in a RouteSubscriber.

But I don't think it's worth the effort. You can either simply hide the form in CSS or if you want a fully customizable search solution use Search API.


File upload is not working We are using the file upload field in a custom drupal form, it was working for one (1) year but now it's not. It is working for administrators but not for anonymous users.

I am using the following code.

$allowed_exts = array('jpg jpeg gif png txt doc xls xlsx pdf ppt pptx pps odt ods odp docx zip rar');

      $form['file1'] = array(
        '#title' => 'Attachments',
        '#description' => t('Allowed Files - jpg jpeg gif png txt doc xls xlsx pdf ppt pptx pps odt ods odp docx zip rar'),
        '#attributes' => array('id' =>'file_attachment'),
        '#type' => 'managed_file',
        '#upload_validators' => array('file_validate_extensions' => $allowed_exts,)
      );

try to set the location

'#upload_location' => 'public://',


How to theme Commerce Customer profile? In a Commerce project, I added some custom fields to the customer profile, and I’m using Addressbook. The customer profile is now displayed in the address book tab of each user page.

I need to change the display of this address book. Until now :

I changed basic display settings of the fields in the "Manage Display" form, and this had a surprising effect : setting a label as hidden removed completely the default theming of all the view.
I tried to use hook_field_formatter_info() and hook_field_formatter_view() as per that Clive answer : this is great but it alters only the native AddressFields, not the custom fields of the customer profile.
In the Commerce Addressbook Defaults  view, source of the display, there's only one field in the view : Commerce Customer Profile: Rendered Commerce Customer profile.

I could call the fields one by one in the view, but what if I want to alter directly the  Rendered Commerce Customer profile field ? Where is it built, and how can I theme or alter it?

Generally speaking you can theme field output like other Drupal output. If you use devel_themer* you can normally see the template used and suggestions available. By default fields use theme('field') which by default has a number of suggestions:

// Add specific suggestions that can override the default implementation.
$variables['theme_hook_suggestions'] = array(
  'field__' . $element['#field_type'],
  'field__' . $element['#field_name'],
  'field__' . $element['#bundle'],
  'field__' . $element['#field_name'] . '__' . $element['#bundle'],
);

For example, the first suggestion allows you to override the template/function used for a particular type of field. In this case we could create MYTHEME_field__addressfield() and it would be used for addressfields only. You can add your own suggestions as well.

There are some field API routes as well though. You can use contrib or custom formatters (some of which in turn provide their own theme functions that you can override). Formatters can have settings that might give the results you want. You can add extra settings with a contrib module if you want to extend a formatter. There are also some field-specific hooks that might be useful:

hook_field_attach_view()
hook_field_attach_preprocess_alter()

* As you say devel_themer is heavy. It massively changes the markup, and often messes up your JS. I only ever switch it on when I need it and then switch if off immediately afterwards, YMMV!


How do I backup my site w/o the command line? Nearly all the documentation on backing up my Drupal site seems to require using the command line.  My hosting service does not provide command line access.  How do I backup my site without using the command line?

I'd go with the Backup and Migrate module. You can either start backups manually or have it run automatically on cron run. Then you can just download your /sites/ folder and you should have a full backup of everything (assuming your files, modules and themes are all in /sites/ like they should be.)


Subtraction of two column in views How to subtracts two column in view?
for example:
 say column A and Column B need to subtract i,e [column A - column B]= column C.How can I achieve this is there any module available for it?

Add another field, select Math Expression from Global group, then in there put something like [field_1_total] 2 [field_2_total]

there is not need any addition module


How do I synchronize users and their roles between sites? I've set up a multi-site Drupal installation. The main site is example.com and we also have a.example.com and b.example.com.

I own example.com, and I rent a.example.com out to Person A, and b.example.com out to Person B. They pay their site rent using the UberCart role-purchase feature on my site. I need a way to set up my site so that Person A and B can log into example.com and pay their site rent, and have the upgraded role transfer over to a.example.com and b.example.com as well, automatically so that after a month if Ubercart downgrades their role I don't have to go in and manually unassign them.

Things I've tried:

Shared users table. This doesn't work because I don't want Person A to be able to see people who have signed up for b.example.com and a shared user site means everyone can see everything.
Domain Access. This works ok but is really shaky, and I'm planning on moving up to z.example.com and onward in the future, so unless there's a way to keep things more separate than I was able to, I don't think this is feasible. For example, if each site has an 'about us' page then I would see 26 "About Us" pages from my uid=1 account. Additionally, I didn't see any way of separating the UberCart module as much as I would like. Ubercart Marketplace is a no-go because I'm not taking any commission like it was designed to do, and UC_Domain hasn't been upgraded to drupal 7 yet.
Account Sync. This seemed like the closest, but the plugin appears broken, I get tons of XML-RPC errors when I try it, and generally it doesn't work as described, and seems to only sync the first account before breaking. Google searching the errors brings back nothing apart from warnings that XMLRPC is potentially dangerous.
Bakery. This seems great but it doesn't share roles across subsites unfortunately. I've been trying to add that in, but before I spent the time I wanted to see if there's some other way that I can go about this

If anybody needs clarification on anything let me know, I really want to get this solved and can't find anything online.

Hope the question is for Drupal 7 or lesser. If it's for Drupal 8, the solution is close to impossible. And for future Drupal versions, as per the current plan for Drupal 9, multi-site option itself shall not be available, which mean sharing user role using Drupal's default options, is clearly impossible.

In Drupal 7 or lower, in the multi-site setup, it's very easily possible to configure each site to use different databases for their contents, and share the same table (from same database) just for users, roles, sessions, etc. If you don't want to share users, but want to share only roles, even that is possible. For this, the settings.php for site A and site B has to be as below:

settings.php for Site A:

/*
 * Database Settings for 'Site A'
 */
$databases['default']['default'] = array (
    'database' => 'site_a_db_name',    // Specify Site A's main database name
    'username' => 'site_a_db_username',
    'password' => 'site_a_db_password',
    'prefix' => array(
        'default' => 'site_a_prefix_',    // Prefix for all tables in Site A's main database (specified above), other than for the tables specified below
        'role' => 'shared_db_name.shared_prefix_',              // Shared database name and prefix for the 'role' table
        'users' => 'shared_db_name.shared_prefix_',             // Shared database name and prefix for the 'users' table
        'authmap' => 'shared_db_name.shared_prefix_',           // Shared database name and prefix for the 'authmap' table
        'sessions' => 'shared_db_name.shared_prefix_',          // Shared database name and prefix for the 'sessions' table
        'profile_fields' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_fields' table
        'profile_values' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_values' table
    ),
    'host' => 'localhost',
    'port' => '3306',
    'driver' => 'mysql',
    'collation' => 'utf8mb4_general_ci',
);

settings.php for Site B:

/*
 * Database Settings for 'Site B'
 */
$databases['default']['default'] = array (
    'database' => 'site_b_db_name',    // Specify Site B's main database name
    'username' => 'site_b_db_username',
    'password' => 'site_b_db_password',
    'prefix' => array(
        'default' => 'site_b_prefix_',    // Prefix for all tables in Site B's main database (specified above), other than for the tables specified below
        'role' => 'shared_db_name.shared_prefix_',              // Shared database name and prefix for the 'role' table
        'users' => 'shared_db_name.shared_prefix_',             // Shared database name and prefix for the 'users' table
        'authmap' => 'shared_db_name.shared_prefix_',           // Shared database name and prefix for the 'authmap' table
        'sessions' => 'shared_db_name.shared_prefix_',          // Shared database name and prefix for the 'sessions' table
        'profile_fields' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_fields' table
        'profile_values' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_values' table
    ),
    'host' => 'localhost',
    'port' => '3306',
    'driver' => 'mysql',
    'collation' => 'utf8mb4_general_ci',
);

As shown in the above code, under 'prefix' array, we can specify separate database and prefix for each different table used in the site. Other than those tables exclusively specified in the 'prefix' array, for all other tables, the prefix specified as 'default' shall be used.

In Drupal 8, user/role/session sharing is not as easy as in Drupal 7, because in Drupal 8, many of the informations, including the user roles, are part of a shared table (that shared table is meant for storing many different variable values, and roles are just part of that).


$fields is undefined - custom theme creation I'm attempting to create a custom template for a view. The template file I'm creating is being loaded (if I add some static html it renders).

I'm having trouble accessing values from the view. The tutorial I'm using advises using

dpm($fields);

To output the available fields.
This is coming up as an undefined variable.

Googling suggests using $rows instead of fields but this was also undefined in this case.

The $fields variable will be available for theming only if you have selected to display fields  instead of content, check under format section of view.

Secondly, the $fields variable is not available if your template file is views-view.tpl.php, you have to use views-view-field.tpl.php or if you want theme only a specific field, you can use views-view-field--fieldname.tpl. php.


With enabling modsecurity_crs_41_sql_injection_attacks all submit form return forbidden 403 I installed and activated the module mod_security. then I enabled the modsecurity_crs_41_sql_injection_attacks.conf.

For each form, when I submit, I have an error 403 forbidden

Error log:

[Wed Nov 15 16:53:03.324516 2017] [:error] [pid 27760] [client] ModSecurity: Access denied with code 403 (phase 2). Pattern match "([\\\\~\\\\!\\\\@\\\\#\\\\$\\\\%\\\\^\\\\&\\\\*\\\\(\\\\)\\\\-\\\\+\\\\=\\\\{\\\\}\\\\[\\\\]\\\\|\\\\:\\\\;\\"\\\\'\\\\\\xc2\\xb4\\\\\\xe2\\x80\\x99\\\\\\xe2\\x80\\x98\\\\`\\\\<\\\\>].*?){4,}" at ARGS_NAMES:field_cl_address[0][format]. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "159"] [id "981173"] [rev "2"] [msg "Restricted SQL Character Anomaly Detection Alert - Total # of special characters exceeded"] [data "Matched Data: ] found within ARGS_NAMES:field_cl_address[0][format]: field_cl_address[0][format]"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [hostname "www.d8.dev.xxxx"] [uri "/node/add/occlient/19784"] [unique_id "Wgxw738AAQEAAGxw91sAAAAO"]

Can anyone explain the cause?

I found the solution by consulting the log:

[Wed Nov 15 16:53:03.313249 2017] [:error] [pid 27752] [client 54.208.242.36] ModSecurity: Access denied with code 403 (phase 2). Pattern match "(^[\\"'`\\xc2\\xb4\\xe2\\x80\\x99\\xe2\\x80\\x98;]+|[\\"'`\\xc2\\xb4\\xe2\\x80\\x99\\xe2\\x80\\x98;]+$)" at ARGS:field_cl_ref_no[508752]. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "64"] [id "981318"] [rev "2"] [msg "SQL Injection Attack: Common Injection Testing Detected"] [data "Matched Data: '\\x22 found within ARGS:field_cl_ref_no[508752]: '\\x22()"] [severity "CRITICAL"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"] [hostname "www.d8.dev.xxxx"] [uri "/node/add/occlient/19784"] [unique_id "Wgxw738AAQEAAGxoJOMAAAAH"]

[Wed Nov 15 17:19:51.286111 2017] [:error] [pid 28380] [client] ModSecurity: Access denied with code 403 (phase 2). Pattern match "(?i:(?:\\\\A|[^\\\\d])0x[a-f\\\\d]{3,}[a-f\\\\d]*)+" at ARGS:form_token. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "55"] [id "981260"] [rev "2"] [msg "SQL Hex Encoding Identified"] [data "Matched Data: E0X10B found within ARGS:form_token: xCyRB87OqEoGB47ngDdQJ0gVaIa5fy4JtgE0X10BVW0"] [severity "CRITICAL"] [ver "OWASP_CRS/2.2.9"] [maturity "8"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"] [hostname "d8.dev.xxxx"] [uri "/node/1369392/edit"] [unique_id "Wgx3N38AAQEAAG7cNtYAAAAK"]

I disabled the rules id 981173 and 981260 in vhost and then it turns

<Directory /var/www/html>
                Order allow,deny
                Allow from all
                Options +FollowSymLinks +ExecCGI
                RewriteEngine On
                AllowOverride All

            <IfModule security2_module>
                    SecRuleRemoveById 981245
                    SecRuleRemoveById 981248
                    SecRuleRemoveById 981173
                    SecRuleRemoveById 981231
                    SecRuleRemoveById 950901
                    SecRuleRemoveById 981260
            </IfModule>

    </Directory>


How to replace drush_download_file in Drush 9 drush_download_file() existed in includes/drush.inc for Drush 8 and below, but this has been removed in Drush 9 as far as I can tell.

Is there a standard way that file downloads should be executed in custom commands written for Drush 9?

With Drush 9 dropping support for the drush dl command, the need for keeping a download function was dropped.

The remnants of drush_download_file() were dropped into the SyncViaHttpCommands.php example class to demonstrate creating a custom a Drush commandfile. You could copy that as a template if you're looking to mimic the old drush_download_file(), or you could use the Guzzle client or some other PHP function; use what works best for your command's download needs.


How to get the name of the month in local language in Drupal? I want to display in a tpl.php file:

  30 maart 2015, 11: 34

Currently i'm using below code

    <?php print  date("j-F-Y H:i") ?>

1) How to get the name of the month in dutch instead of english?

2) How to add the comma easily ?

Don't use the PHP date function, use the Drupal API: format_date. To add the comma, make it part of the pattern. To match your example 30 maart 2015, 11: 34, the pattern is j F Y, H: i:

$timestamp = strtotime('2015-03-30 11:34');
print format_date($timestamp, 'custom', 'j F Y, H: i', NULL, 'nl');

For this to work, you need to have the core locale module enabled and Dutch translations on your site should be up to date (check that the names of months are translated inthe translation UI).  The module Localization Update will help you with updating translations if you need to.

You can skip the last argument ('nl') if the default language of your site is dutch.


Get all the nodes with matching taxonomy terms in a view Display I have a view which shows all the page elements.

So, in five displays of view, it shows Hero area, description, sidebar etc.

The last display has to show all the nodes which has similar taxonomy terms of this current node.

For example, if Taxonomy is Interests, and I have selected Basketball, Chess, Baseball, then I am hoping to output all nodes with the same interests.

I am trying here to get all nodes within my display. Is it possible?

Many Thanks.

If my understanding is correct, you have a view of content each with references to the taxonomy vocabulary Interests. If this is the case, then you can easily add a filter to your view with the selected terms in that taxonomy.

To allow users to select which term elements render on the page, make it an exposed filter (perhaps select or multiselect).


AWS S3 Bucket - File Explorer Field I'm looking for a file field module that will allow me to select files from an AWS S3 Bucket, but not upload them.

A client of mine is going to be uploading csv files via ftp from a different location and he wants users of a lesser role to be able to select the files from within the website.

I know that Scald will probably serve those needs, but not without a lot of setup and headaches.

Anyone know of a way to accomplish this?

You want to have a read only access for your users, correct?
It's not so difficult to implement in Amazon S3.

First of all, you need to set up an IAM user and apply read only permissions for it. AWS provides pre-defined policy template. More information here:
http://docs.aws.amazon.com/IAM/

Once you created a user, you can connect to your storage using tools such as CloudBerry Explorer. When you client authanticats using key pairs assigned to the read only user you created, they will be able only to download files.
You can download CloudBerry Explroer here:
http://www.cloudberrylab.com/free-amazon-s3-explorer-cloudfront-IAM.aspx

Regards,
Vlad,
CloudBerry Lab


What is a one line mysql query that can update all body fields of matched nodes? I am trying to do a bulk node update that affects 100+ nodes. I want to set each of these node's body field to a specific string. Say I want to affect all content types: "basic page".

Since my sql skills aren't up to par with join statements. I only got this far:

UPDATE field_data_body SET body_value = 'This is my string.' WHERE type = "basic_page" left join node;

In drupal 7 it is a bit simpler.
You don't need the join.

UPDATE field_data_body
   SET body_value = 'This is my string.'
 WHERE entity_type = 'node'
   AND bundle = 'basic_page';

You must clear the drupal cache after updating content directly in the database.

Also, if you are using revisions, note that you have just changed the latest revision without creating a new revision.
This may not matter to you but it's worth noting.


Send Email with Different Accounts I've been searching but didn't find much.

Is there any module or way to send emails with Drupal, but using different email accounts?

For example, I have a site which will have 3 different email accounts to send email.
User A creates a node, the user will receive an email from the email account 1.
User B takes an action, he or she will receive an email from the email account 2.
Etc.

To sum up:

Is there any module to hold different email accounts in one drupal site and send email with them?

I've seen some modules to hold different email accounts for the users, but not for the site.

Thanks in advance.

Nice question  you are right  no module for that . but  you can configure it by rules
like
after saving node
add action - sand e-mail userA
on this add conditions according to your need
like  account type userA
I think this is the possible way for that


Change .gitignore file for sites/default/files/config I'm checking out the new configuration management module for Drupal 7. It's effectively a back-port of the new configuration management that's in D8, and looks like it's going to be a great alternative to the use of Features for storing configuration.

https://drupal.org/project/configuration

I have a test github repository where I'm playing with the module. I'd like to put my code and configuration in this repo, and I'd quite like to keep the default location for the config files (sites/default/files/config).

I realise that this is more a question about .gitignore files than Drupal. However, how can I change my .gitignore file so that I can add the config files to my repo?

The current gitignore is here. (This is the excellent .gitignore file provided by github as a default for Drupal projects).

The simple change of adding !sites/default/files/config/* to the end of the file doesn't seem to help.

EDIT: I also tried this, with no luck:

!sites/default/files/config/*.inc

I'd be grateful for any tips on how others manage to solve this problem. Thanks!

You can do that if you ignore the content in "sites//files/" directory and not the directory itself "sites/*/files/", I think this is not the best way to do it but that is what I have managed to find.

Ignore all the content in "sites//files/" except for the config directory

# Ignore paths that contain user-generated content.
sites/*/private
sites/*/files/*
!sites/*/files/config

or you can only ignore the config/*.inc

# Ignore paths that contain user-generated content.
sites/*/private
sites/*/files/*
!sites/*/files/config
sites/*/files/config/*
!sites/*/files/config/*.inc

remember to replace the default "sites//files" with "sites//files/*" in the .gitigonre file.

Another way is to forcefully add the files you want to commit, this will add the files in the directory and track there changes,  but will not detect new files added in the future.

git add -f default/files/config/


Apply text filter (not text format) in Twig Is it possible to apply a specific text filter (not a whole text format) to a string in Twig?
(Or at least in template preprocess, if not possible in Twig)

Use case:

I've a special block for hand-picked, trusted editors that allows them to inject unfiltered HTML (for social widgets like Facebook posts, TripAdvisor reviews, etc) into the homepage. Basically it is just a custom content block with a text field, and printed using |raw to avoid style and script tags being from filtered:

{{ content.body.0['#text']|raw }}

This does already work as expected.

Now I've got the additional requirement to apply the text filter from the LinkIt module on this field. The editors want to provide a link to a node, and the link to the node should be printed using the correct language prefix and the SEO-friendly URL alias. E.g. I've got a text field containing something like

Link with correct language prefix and SEO-friendly URL-alias

and I want to run the LinkIt replacement on that field and then output it, but without filtering or escaping any of the JS or CSS.

If those HTML are mostly or all static, you could consider implementing your own tokens via hook_token_info() and hook_tokens() in your custom module.

This way, you would avoid any potential risks, and accidentally malformed markup... and would have to full control on the replaced and returned markup.

Your authors would add a token like this in the content: [custom:facebookpost:12345]

... and your token could return an embedded Facebook post markup in return.

In my experience this method works much better than any other alternatives, mostly because:

those embed widgets usually have custom tags and/or tag attributes which may not be compatible with CKEditor settings, text formats, etc.
embedding those widgets directly, would make maintaining content much harder on the long run.
provider(s) may change the embed markup. (Consider updating 100s or thousands of content entries via find & replace vs. updating the embed markup in token definition only)
and it's not a hack.


How to export cck field list from Drupal 6 to CSV files for import in Drupal 7? I am migrating a D6 site to D7 using migrate_d2d_ui but find that the cck fields for my various content types are not automatically migrated.

I would like to build a csv file containing the D6 cck field structure (name, type, length, #values, help text, etc) so that a csv file can be built for each content type and imported into D7, perhaps using feeds, to build out the full D7 content type and field structure.  Hopefully, migrate_d2d-ui can be mapped to bring over the content once the full D7 structure is built out.

I have investigated Features, Views Data Export, Feeds, Content Copy, and Bundle Copy, but have not found a combination that works with both D6 and D7 platforms.

Any suggestions for creating and importing this csv file or do I need to manually recreate each field in D7?

Thanks.

I gave up on this approach and ended up using the features module because I could not find a complete or workable solution using csv export/import.


how to make URL aliases of nodes created via form include node title of original page? Say I have a content type called "X", and every node of Content type "X" has a form that will create content type "Y"

How do I go about setting up the URL alias of content type "Y" so it will be something along the lines of "www.drupal.com/(Node title of X)/(Node title of Y).com

Thanks for any help!

try 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.

Once set up, you can have it assign the path based on the title of the current node (X) and the field value you assign to the title of node (Y).  If you are using nodetitle or something to automatically assign the title for node (Y), you will have to run some custom code when content type (Y) is created in order to assign its alias.


Custom external read-only databases with Drupal, how to use views to communicate with the external database? I have a pretty detailed relational database that I would like Drupal to communicate with (Read Only). Now, I know that I can create custom modules to output the data but I am not sure I will be leveraging Drupal's benefits using in that fashion (it seems like a hack). I do not plan on moving the data to Drupal either (too large in size and also more than 80 tables).

Is there a way that I could use views to get the data out from my external database without interfering with the Drupal core? I am sure that Drupal developers run into this issue many times, I would like to have a pointer as far as where to look. Is that possible? has anyone ever done this?

I have already used Google in an attempt to find a solution. I even tried the entity module, entity api, data module a few other API and modules without success.

Just need a workflow/pointer or simply a successful website that is using Drupal in that fashion.

I am using Drupal 7 and I will be willing to go to Drupal 8.

Yes there is a way to use views to get data out of an external database. You will need the hooks_view_data()

There is however the limitation the view can not cross databases I believe.

To solve this, you can write a custom module

<?php

function yourmoduleame_views_views_api() {
   return array(
      'api' => 3,
   );
}

function  yourmodulename_views_views_data() {
   $data['arTable']['table']['group'] = t('yourtable Data');
   $data['arTable']['table']['base'] = array(
      'field' => 'id',
      'title' => t('your title'),
      'help' => t('help text'),
      'database' => 'databasename',
      'weight' => -10,
   );

Where databasename is one of your db_names defined in settings.php.

For more information, look at this post


Canonical URL for Front Page - without path I've been looking for a solution to the Front Page URL issue that meets the following criteria.

Allows me to keep the Canonical and Description Tags from Meta Tags Quick on Views sub-pages.
Allows web client users to change the meta description on the front page through the Meta Tags module.

I use both the Meta Tags and Meta Tags Quick modules for views tagging and automation on standard nodes. Unfortunately I haven't been able to set the /welcome page canonical URL to a forced "http://www.website.com/". I continue to get "http://www.website.com/welcome" for the front page.

I've tried removing the path alias. I've tried setting path specific meta tags with the 'quick' module. I've input the details into the standard Meta Tags module under global front page.

Maybe there is some combination that I'm missing. Any ideas?

Additional: I've been using the Redirect Module on the site - if that matters.

Solution: Alright - after extensive poking around the issue was that I added Canonical URLs as a [current-page:url:absolute] to the GLOBAL settings rather than the Content.

This meant that the GLOBAL Front Page override was overridden by the other elements.

Worked for me, for now. Apparently I can't post the solution that I found with my team because I'm a new user. I don't plan to come back this week and will forget to publish a fix if I don't put it here. Get used to it.


How to use views to filter specific workflow state in current month I have a system that is heavily workflow dependant. I have a content type called 'Profile' with 3 states :

Lead
Prospect
Customer

I would like to know how to create a views contextual filter of all Profiles that changed to the Customer state in a given month i.e. which Profiles Customer this month.
D6 Views 2.x has this option but I cannot find it in D7 Views 3.x

Thanks

You may want to check if using the Views Date Format SQL module could be a solution for you. Here are some quotes about it (from its project page):

  ... allows to format date fields using SQL.

  The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date.
  This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.

  The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts module.


How to implement moderation of data entered through user profile pages? I am in need of a means of moderating data entered through a user's profile page, or at least for certain specified fields, both upon initial submission and after any revision. These are fields that have been added to the basic user profile (example.com/user/#), editable through the "my account" link -- fields that can be added through Home » Administration » Configuration » People » Account settings.

The most important fields to moderate involve text entry fields and selected taxonomy terms. By moderation, I mean administrative approval of the changes before they go live on the site. My preference would be for the old data to remain visible pending approval of the new data.

I hired a web development company to create a site that includes a directory, with the explicit instruction that moderation of directory data was necessary. They nonetheless set the site up such that the information is provided through fields on users' profile pages and did not incorporate any means of moderation.

I have seen a potential work-around that involves the installation of the Profile2 and Profile2 Moderation modules, but simply implementing those modules does not fix the problem and creating new profile pages would unfortunately risk breaking the site.

If you have any ideas, I would be very grateful to hear them.

What I've done in a similar situation was this:

Turn on moderation of users /admin/config/people/accounts ie:

Who can register accounts?
--> Visitors, but administrator approval is required
Install Views Bulk Operations https://www.drupal.org/project/views_bulk_operations
Create a view that shows the moderated users by default (but you can use an exposed filter to change this). Include the fields that you want the administrator to be able to see (your text entry and taxonomy referred to above). Set your view to the VBO options and enable the operations for approving (or blocking) users.

Hope this helps!


How To Get Views Argument as a Like / Contains Instead of Equals I have a view that I need to filter using the logic Field_a Contains url_argument_1. Or in SQL Field_a LIKE '%url_argument_1%'. The problem I am having is only filters let me use the "Contains" operator and only Arguments let me access url_argument_1. How can I combine them?

Just for clarity url_argument_1 is Argument #1 that is passed into the view from the URL. Also, if at all possible I want to avoid writing a custom module. I prefer to do this via the views interface.

Solution would be to filter results by argument value. Unfortunately, this doesn't seem to be doable in Views at the moment. Not via the Views interface, anyway.

However, by altering exposed filter form to set current argument value as filter default value, users have managed to get such functionality to work: http://drupal.org/node/360780

I don't know what state it is in, but you may want to have a look at this module, which is supposed to do just that -- enable using argument placeholders (%1, %2) as filter values: http://drupal.org/sandbox/itangalo/1086472 (git only)


PDO datetime exception when saving a Computed Field (but no datetime in my query) This one has me stumped. I get the following error when trying to create/edit a node with a computed field, which is an INT:

  PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect
  integer value: '' for column 'field_film_civicrm_event_code_value' at
  row 1: INSERT INTO {field_data_field_film_civicrm_event_code}
  (entity_type, entity_id, revision_id, bundle, delta, language,
  field_film_civicrm_event_code_value) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6); Array (
  [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 363
  [:db_insert_placeholder_2] => 364 [:db_insert_placeholder_3] => film
  [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und
  [:db_insert_placeholder_6] => ) in
  field_sql_storage_field_storage_write() (line 451 of
  /data/disk/o1/static/drupal-7.23/modules/field/modules/field_sql_storage/field_sql_storage.module).

Here is my code for the computed field:

list($id, $vid, ) = entity_extract_ids($entity_type, $entity);

$result = db_query("SELECT
                    ce.id AS CiviEventID
                    FROM node n
                    INNER JOIN civicrm_event ce ON n.title = ce.title COLLATE utf8_unicode_ci
                    WHERE n.nid = :nid
                    AND n.vid = :vid
                                        LIMIT 1",
                  array(':vid' => $vid, ':nid' => $id));

if ($result->fetchField() === NULL)
{
$entity_field[0]['value'] = 0;
}
else
{
/*$entity_field[0]['value'] = 0; */
$entity_field[0]['value'] = $result->fetchField();
}

I'm using a computed field to get a CiviCRM event code where its event name matches my node title. It previously matched the Civi event date to a node date field as well, but I removed that when troubleshooting. This worked normally two weeks ago. Since then I've applied updates to Ubuntu and PHP, and the Entity and Date modules, but haven't changed my computed field code (until troubleshooting for this post). If I hard-code the value to 0, the node saves without error.

The error shows the correct nid and vid, but also shows empty for my computed field (I'm assuming due to this datetime error). When I run the query directly against the DB I get the correct result, so my query syntax isn't broken.

I'm running this all on Linode using the BOA stack from Omega8cc. Drupal is 7.23 currently. Any advice for troubleshooting or a solution?

UPDATE: I've modified the db_query to its simplest form ("SELECT 1 FROM NODE LIMIT 1") and the fetchField() still doesn't return a value. But if I set the value without using a query at all, it saves.

In the end, something in the BOA or Entity update affected fetchField(). I resolved it by explicitly setting the index like so: fetchField(0).

I added a comment to api.drupal.org to hopefully help the next person who has the problem.

https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/DatabaseStatementBase%3A%3AfetchField/7


Add a DB record for taxonomy with Rules I actually import terms from Feeds Xpath and copy them to a Content taxonomy field. But this term isn't recorded in the term_node table as expected by checking the checkbox.

So can I use Rules to "force" this recording in the term_node table from the data stored by CCK Content Taxonomy ?
If yes, how can I do that ?

thanks