Contextual filters with Entity reference I have two content types called Basic Page and Contact Info.

There are around 5 nodes from Contact Info with some contact info (phone/fax/email/IM) in the body field.
In Basic Page content type there's an Entity Reference field that refers to Contact Info. So that for each page there would be a main contact person. When someone create a Basic Page node they can pick a Contact Info node from the dropdown (out of the 5 Contact Info nodes).

  Basic Page -> Contact Info (Basic Page content type refers to Contact
  Info content type)

Then I created a block view (added to the sidebar of Basic pages) which displays the contact info associated with that node.

Added a Relationship in the view (Entity Reference: Referenced Entity)

Right now it's displaying all 5 contact info nodes, not just the one associated with that particular basic page node. I tried to tweak the Contextual filter and relationships but couldn't get it to work.

I have a feeling that the solution lies in the php code that goes in Provide default value -> php code section.

Any help appreciated.
Thanks

The contextual filter should be "content:nid"

The options should be set as follows...

  The Relationship should be your "Entity Reference: Referenced Entity"
  relationship

  Under "When the filter value is NOT available" check "provide default
  value" and select "Content ID from URL"

  Apply changes and save view.

I think this is the same thing Renee was saying, just in other words.

Hope this helps - I recently lost a weekend to figuring this out ; )


How to make node title translatable? I have a content type in D8 that requires translation, however at the moment I appear to be only able to translate the individual fields and not the title.

The language selector is available on the content type edit page, but there seems to be no way of selecting to translate the title:

Other fields have a checkbox that allows them to be translatable:

Any ideas? Thanks in advance!

The title is set as translatable by default (in the entity definition). Somehow you've disabled translation for this field. You can check the translatable fields for content entities here:

/admin/config/regional/content-language

This includes all fields, also the base fields, which you can't configure in Manage Fields of the content type.


Redirect to main view URL when no contextual filters are set I have a view in drupal 7 with no contextual filters at all set.

Let's say it is a simple list of nodes of the type "item" and that the url is http://example.com/listofitems

I also have pathauto patterns set for the individual nodes. So if an item titled "my item" is created the url would be http://example.com/listofitems/my-item
This is important to know because I don't want to set another view for the path listofitems/%.

Given that no view or URL alias exists for listofitems/foo I expected that this URL would give a 404 error: http://example.com/listofitems/foo

Instead it shows the full view with no errors.  This is confusing and bad for SEO.  If a bot hits http://example.com/listofitems/foo/bar/foo/bar/foo/bar/blahblahblahblah they should get a 404 message.  Or better yet, they could get a 301 redirect to the main view url.  In any case, they should not be allowed to stay on the non-existant URL and see the view with no errors.

How can I accomplish this?  Is there a trick I'm missing or a reason that this is the default behavior?

The problem lies in Drupal's menu system, which for the most part asserts itself as a safety mechanism, so if you or someone else mis-spells a URL it will give you the next best option.

Admin Menu Example

admin/structure/blocks = Manage Blocks Page

admin/structure/blockss = Structure Page

Drupal does this so it won't "disrupt" the user-experience, but it can also be a confusing if you don't know what just happened.

It's generally there to prevent human error and other problems that arise when managing a live website.

The Options

Keep the default set, so users are accommodated and instead focus on structuring the robots.txt (and perhaps .htaccess) file correctly, so you can let Search Engines know what's happening.
Look into the Rules and Context contributed modules to see if you can create a solution using those interfaces. You may or may not be able to find a solution there, but it might be a good start.
Create a module, which will handle non-existent URL's and correctly reroute them to 404 page.


Slow loading of text in WYSIWYG with TinyMCE 3.5 in Chrome Browser On an node edit page with WYSIWYG (TinyMCE) it takes over a second for the text to show up, see this video.

FireFox doesn't seem to have this issue.
Has anyone chrome across this?

turned out to be an issue with CSS_Injector module, this is the fix.


ajax_command_invoke Question related to Commerce + Colorbox + AJAX I am displaying a Drupal Commerce node with AJAX add to cart functionality in a popup, with the Colorbox Node module.  In my custom form callback, I have the following code.

// Form callback function
function ajax_module_form($form, &$form_state){
  drupal_add_js(drupal_get_path('module','colorbox' . '/colorbox.js'));
  $commands = array();

  $commands[] = ajax_command_invoke('colorbox-node', 'colorbox.close');

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

I am trying to use Drupal's ajax_command_invoke to close the Colorbox window after AJAX form submission is complete, but cant seem get it to work. I tried 'parent.colorbox.close' as well but doesnt seem to work. The colorbox link has iframe and sample link is -

example.com/node/45434345?width=500&height=500&iframe=true and link class is .colorbox-node

Also the Colorbox module setting - invoke on all pages is also active.

Any lead/help is greatly appreciated.

I'm editing my answer to directly address your question first:

ajax_command_invoke takes a css selector as its first argument.

 node-colorbox

isn't a css selector (or at the very least, not a valid one).

In addition, ajax_command_invoke does not allow for the execution of arbitrary javascript, but only allows for triggering registered jQuery events.  If you want to create a custom jQuery event for colorbox, you will have to manually create it and attach it to the colorbox object, using Drupal.behaviors.

http://www.sitepoint.com/jquery-custom-events/ should get your started.

Colorbox seems like it might be a good solution for your use-case, but it really isn't.  If you want a good floating window with ajax forms and automatic closure, using the chaos tools modal system is a better bet.  It supports what you're looking for right out of the box and makes working with forms easy.  In addition, almost everyone uses ctools, as it is a dependency for many different modules.

http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 should get you started.


Cant display error message in custome form! I have create one form which have two fields.

$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#maxlength' => 20,

    '#required' => TRUE,

);
$form['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone'),
    '#maxlength' => 20,
    '#required' => TRUE,
);

In page.tpl.php file displayed both fields. Now i have press submit button without enter any value in text box error message will displayed.

But in my page.tpl.php file cant display error message!

How can i show all error message?

Hope this will help you.

In Drupal 7, just add this line in your custom template file

<?php if ($messages): print $messages; endif; ?>


Administrator role can't edit html source in tinymce I have created and administrator role that has full HTML editing capabilities when creating a node. The issue I am having is that when they click on the button to edit html source button (in tinymce) the resulting dialog doesn't show any source. As user 1, this works with no issues. I thought this was a permission issue of some sort but I can't find where this would be set. This is on a Drupal 6 install. Can anyone tell me what I need to do (and where to go) to fix this?

Thanks.

I found out the issue is that the person logging in as an administrator was using Internet Explorer 11. Once they changed browsers to either Firefox or Chrome, everything worked as it should. Microsoft should really get out of the browser business.


Create a menu item with arguments I am trying to manually create a menu link item in the User Menu that contains a wildcard, But I cant make it work.  I can get it to work if I have a static path, but I cant get it to work with wildcards args

function hook_menu() {
  $items['user/%user/bookmarks'] = array(
    'title' => 'My Bookmarks',
    'description' => 'Link to My Bookmarks',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'user-menu'
  );

  return $items;
}

When I tried to use user wildcards first, I too came across this problem; and after some trial and error, found that the %user wildcard doesn't work with the menu type MENU_NORMAL_ITEM, instead it works if the type is MENU_LOCAL_TASK.

So, the code should be:

function hook_menu() {
  $items['user/%user/bookmarks'] = array(
    'title' => 'My Bookmarks',
    'description' => 'Link to My Bookmarks',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_LOCAL_TASK,
    'menu_name' => 'user-menu'
  );

  return $items;
}

Usually, this menu type is rendered as a tab in user menu.

I didn't get enough time to figure out why it doesn't work with MENU_LOCAL_TASK, but when I do find the reason, I'll post it back.


Ajax form that changes a button value When a user pushes a button element marked with ajax, I would like the callback to modify the button value (text shown on button), and have it updated both in the browser and the form state. Updating in the browser is easy by return an ajax_command_replace call. But I'm not having any luck with getting the form updated to remember the updated button value the next time the button gets pushed.

It seems the way the ajax form is built, that the initial value of the button gets hardcoded where the callback function in the javascript page gets defined, which probably explains why the button element returned to the ajax callback does not match with the value it shows in the browser (after I changed it with the ajax_command_replace).

But I can live with that, as long as I can get the form (or form_state) to actually remember the new value of the button element from a previous invocation of the callback.

I've also tried modifying the form/form_state values in the form validate hook, but without success.

So, despite already knowing this does not work, the following code tries to illustrate what I'm trying to do:

function testajax_callback($form, &$form_state) {
  $form['mybtn']['#value'] = 'New value';
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace('#mybtnwrapper' => drupal_render($form['mybtn']))
  );
}

Any help on how to do this the Drupal 7 way would be appreciated.

update 1:

Got a hint on the Drupal Forums. The following code is probably more according to Drupal 7 design and style:

function betapp_testajax_callback($form, &$form_state) {
  $form['mybtn']['#value'] = 'New value';
  return $form['mybtn'];
}

function betapp_testajax_form($form, &$form_state) {
  $form['mybtn'] = array(
    '#type' => 'button',
    '#id' => 'mybtn',
    '#prefix' => '',
    '#suffix' => '',
    '#default_value' => 'Default value',
    '#ajax' => array(
      'callback' => 'betapp_testajax_callback',
      'wrapper' => 'testajaxwrapper',
      'method' => 'replace',
      'effect' => 'fade'
    )
  );
  return $form;
}

The code manages to change to appearance of the button (button value), but when pressing the button with the updated value, the old one is still the one sent, so effectively, no values in the form has changed, only the button appearance.

It may have something to do with hardcoded values in the callback definitions in the html page (which is only loaded once). I find entries such as these:

{"callback":"betapp_testajax_callback","wrapper":"testajaxwrapper","method":"replaceWith","effect":"fade","event":"mousedown","keypress":true,"url":"\/d7\/system\/ajax","submit":{"_triggering_element_name":"op","_triggering_element_value":"Default value"}}

If _triggering_element_value is used regardless of the actual value of the element, that explains why the new value is not picked up. Maybe the _triggering_element_value should be looked up at runtime when the callback gets activated?

Any ideas on workarounds/fixes?

The short solution to my original question can be coded like this:

function betapp_testajax_callback($form, &$form_state) {
  return $form['mybtn'];
}

function betapp_testajax_form($form, &$form_state) {
  dd('');
  dd('betapp_testajax_form');
  $form['mybtn'] = array(
    '#type' => 'button',
    '#id' => 'mybtn',
    '#default_value' => 'Ignored default value',
    '#prefix' => '',
    '#suffix' => '',
    '#ajax' => array(
      'callback' => 'betapp_testajax_callback',
      'wrapper' => 'testajaxwrapper',
      'method' => 'replace',
      'effect' => 'fade'
    )
  );
  $prevval = '(blank)';
  if (isset($form_state['values']['mybtn'])) {
    $prevval = $form_state['values']['mybtn'];
    dd('prevval : ' . $prevval);
  }

  $form['mybtn']['#value'] = 'Newval ' . rand(0, 100);

  dd('newval  : ' . $form['mybtn']['#value']);
  return $form;
}

which lead to output like:

betapp_testajax_form
newval  : Newval 48

betapp_testajax_form
prevval : Newval 48
newval  : Newval 62

betapp_testajax_form
prevval : Newval 62
newval  : Newval 0

betapp_testajax_form
prevval : Newval 0
newval  : Newval 59

My usage requires a little bit more; whenever a button is changed, there are other elements that should be updated as well. But I think I managed to pull it together (looks correct for now anway), and in the spirit of sharing, here's what I managed to glue together:

function betapp_testajax_callback2($form, &$form_state) {
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace('#mybtn', drupal_render($form['mybtn'])),
      ajax_command_replace('#inp', drupal_render($form['inp']))
    )
  );
}

function betapp_testajax_form2($form, &$form_state) {
  dd('');
  dd('betapp_testajax_form');
  $form['mybtn'] = array(
    '#type' => 'button',
    '#id' => 'mybtn',
    '#default_value' => 'Ignored default value',
    '#prefix' => '',
    '#suffix' => '',
    '#ajax' => array(
      'callback' => 'betapp_testajax_callback',
      'wrapper' => 'testajaxwrapper',
      'method' => 'replace',
      'effect' => 'fade'
    )
  );
  $prevval = '(blank)';
  if (isset($form_state['values']['mybtn'])) {
    $prevval = $form_state['values']['mybtn'];
    dd('prevval : ' . $prevval);
  }

  $form['mybtn']['#value'] = 'Newval ' . rand(0, 100);

  $form['inp'] = array(
    '#type' => 'textfield',
    '#value' => $prevval,
    '#id' => 'inp'
  );
  dd('newval  : ' . $form['mybtn']['#value']);
  return $form;
}

This code updates the original button, and sets the input field to the previous value of the button. My case requires modifying other buttons, but hopefully that will work. If not, I'll bug you on this thread again.

Thank you.


Show a block within node content (field template) based on context/taxonomy? I've created a block using Views that I want to display only on nodes that have a specified value for a taxonomy field (no taxonomy info in the URL). The catch is that I want to display it within the main content (between certain fields), not above or below the main content. I've tried doing this in various ways, but none of my attempts have quite gotten what I needed.

Using one method, I managed to use pre-processing functions and the specific field template for the field (field--body--story.tpl.php) to get the block to show up in right place, but it showed for all the nodes of that content type. I tried evaluating for other fields' values within mytheme_preprocess_field, but those field values don't seem to be available within that function? (They don't show at all using dsm($vars) on the page, I think because the display of that field is hidden.)

Using another method, I used the Context module to get the block to show up only on the nodes of that content type that had that field set to the desired value, but then I could only get it to show above or below the main content, not between specified fields within the main content.

I'm new to Drupal (but am otherwise an experienced web developer), so I'm probably over-complicating this and/or not understanding some major concept. I'm sure there is an elegant way to do this, but I just can't get it (at all, much less elegantly). What am I missing?

you can do what i did before :

-1 install computed field module and enable it.

-2 you have to call the specific views that you want in computed field like this way

<?php
$view = views_get_view('your_views_name');
$view->set_exposed_input();
$display_id = 'default';
$view->set_display($display_id);
$view->render();
$entity_field[0]['value'] = ($view->preview());
?>


Assign email on user registeration I have a custom user email field,
I want when the user signs up to automatically set the email for he/she.

For example, when the username field is user1 I want set the email to user1@mydomain.com and save it in email field.

How can I do this?

If you'd like to customize the user registration form, you're probably looking at a custom module to take care of this; an invocation of hook_form_alter() can step in and alter the behavior of the user registration form. For example, adding the following functions to MYMODULE:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  // Disable the email field
  $form['account']['mail']['#access'] = FALSE;

  // @TODO: Override validation functions in $form['#validate']
  // that check the mail field

  // Replace the user registration form submission with
  // the function MYMODULE_form_user_register_form_submit
  $form['#submit'] = array('MYMODULE_form_user_register_form_submit');
}

// Alter the disabled mail field before
// submitting registration form to user_register_submit()
function MYMODULE_form_user_register_form_submit($form_id, &$form_state) {
  // add '@mydomain.com' to the submitted username field
  $form_state['values']['mail'] = $form_state['values']['name'] .  '@mydomain.com';
  user_register_submit($form_id, $form_state);
}

This only get you partially there, as overriding such key functionality requires many scenarios to validate now that a key assumption is gone (e.g. what happens when someone enters an email for a name, what happens when a user needs to recover password, etc.).

It might be helpful to look at the source code of the Optional mail on register module to see how that is accomplished so you can under how modules can override Drupal's user registration functionality.


Can I automatically expand my paragraph item after the node creation? I am using Drupal 7.x and have created a new content type with fields and a paragraph. Now when I create a new node I can fill in the fields and add a new paragraph item but I want to be able to fill my 1st paragraph item immediately instead of clicking on the add paragraph first (so it should expand already the moment I create the node).

Is there a configuration setting I am missing or a module that offers this kind of functionality?

I have done this before, I found out that the only way to do this is with jQuery. I did like this:

/**
 * @file
 * JS code for node/edit pages
 */

(function ($, Drupal) {

  'use strict';

  $(document).ready(function () {
    $('TARGET').click();
  });

})(jQuery, Drupal);


"Your command line PHP installation is too old" When trying to run Drush on my shared hosting account I get this error:

  Your command line PHP installation is too old. Drush requires at least PHP 5.3.0.
  To suppress this check, set the environment variable DRUSH_NO_MIN_PHP=1

When I type php --version, it tells me that I am running PHP 5.2.6.

The .bashrc file has the following lines

export COLUMNS
alias drush='/usr/bin/php ~/public_html/drush/drush.php'
alias php='/usr/bin/php'

How I can fix this?

I had a similar problem and I was able to specify what version of PHP Drush will use by adding the following to my .bash_profile file:

export DRUSH_PHP=/usr/local/php53/bin/php

That got mine working.  I had tried a more general approach where I specified PHP 5.3 for my command line generally, but this didn't work.  Specifically targeting Drush is what it took for me.


How to create a scheduler for updating a boolean value using Rules? I am displaying a boolean value as 'New' along with published content title.

Now I need like, the 'New' tag should be displayed for a period (ex: 3 months). After this period I need that content as it is, but 'New' tag should be removed.

It's defined in node.module like follows

define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);

AFAIK, you can't redefine this value. I think you need to change and use your value in all the places.

I'll check and If I found better option I'll update my answer :)


Include selected language in a href I have a few hardcoded links in a block on my homepage.

Info

But I want them to include the selected language.

e.g. Wen french is selected I want it to link to

Info

How can I do this?

You need to use l function to print links in Drupal... It has support for language

global $language;
print l("Info", "info",  array('language' => $language->language));


is there a way to display a message for views if there are no results? I am using user relationships and activity feed, which displays actions from a existing view.  If no view exists, it means either they have no friends or their friends have no activity so is there a way to have a message displayed for no results?

For Drupal 7 / Views 3 the answer would be:

Check the "Advanced" Options on the right side. There you can add a "NO RESULTS BEHAVIOR".


filter vocabulary from vocabulary I have several vocabularies; let's assume they are the following ones:

v1, with terms v11,v12,v13
v2, with terms v21,v22,v23
v3, with terms v31,v32,v33

I have a product category. When you hit the product category, I want that a page appears showing drop down menus of the above vocabularies, and the drop down containing their terms.

How can this page be called from the click on the product category?
Now the main problem I want to solve is when the page containing the drop down menu appears, and the user clicks on a particular term of a vocabulary, that action filters some terms in the other drop down menu. For example, if v11 is selected in vocabulary v1, then with v2 only terms v22 and v23 are allowed, and in v3 only v31 is allowed so when you select term v11 the other menus should only show the allowed term. Also when a term is selected, the below section of the page should show only those products (teaser or table) satisfying the attributes as selected in the terms. And we have two choices in vocabulary v2 we can select either v22 or v33 which will further filter the search criteria of products in that category.

An example can be seen on this site.

In the left side menu, go to detection and ranging, and hit on laser measurement technology. The page which appears has several drop down menus; I want to acheive the same functionality.

Essentially, you want a hierarchical 'drill down' through taxonomy to narrow a search? If I'm interpreting this correctly, you're looking for something like Hierarchical Select, a module that does just that in the form of an input widget. I don't have personal experience with the exposed filter implementation, but it sounds like it exists.

http://drupal.org/project/hierarchical_select

http://drupal.org/node/720268


Downloading, and loading Google analytics script locally and daily with Drupal Cron I'm using Drupal Google Analytics module for some time; It works perfectly and gives me the data I need.

Yet, since instilling it, I get the following notification on Google Pagespeed Insights:

Do you know a way to load the script locally and daily in Drupal so to prevent this notification?

Is there a way to make add a automation to Cron to download the famous ga.js script daily from Google, load it, and then, the next day, delete it, and repeat the process?

This has been built into the Google Analytics module for sometime. In the configuration form, under Advanced Settings there's a Locally cache tracking code file checkbox. It will persist a local cached version of the JS code for day before a cron run will re-cache it.


Image Annotations in Drupal 7 What's the best way of creating image annotations in Drupal 7?

Ideally, I would like to re-recreate something like in Concept Feedback, where you can post annotations on an image and then display the annotations as a list below the image, grouped by category.

Image Annotate (view demo here), lets you annotate images. The annotations are also displayed as comments on the node (under the comments section). Unfortunately, it the Drupal 7 version is incomplete and not actively developed. The module also doesn't allow you much control over how comments are displayed and you can only annotate one image per a ndoe.

Photonotes (view demo here) is another similar module (although it only displays annotations on the image). It to is only in development for Drupal 6.

JQMap Highlight works on Drupal 7, only lets you post tooltips on images (as opposed to true annotations).

Does anyone have other suggestions.

Thanks!

Imagefield Marker is a new D7 module for image annotations.


Importing uid of the author into article nodes fails My custom Drupal 7 to Drupal 8 migration correctly follows dependencies and first migrates users, then articles. The problem is that it fails to import user IDs into the 'uid' field and leaves it at '0'. For uid processing, I use the following YAML snipped. Note that 'luxus_users' is the user migration that works fine.

process:
    uid:
         plugin: iterator
         source: uid
         process:
           target_id:
               plugin: migration
               migration: luxus_users
               source: uid

I hoped would work for me as similar one for file migration already works for me.

field_logo:
     plugin: iterator
     source: field_logo
     process:
       target_id:
         plugin: migration
         migration: luxus_files
         source: fid

The difference is that the fid you're migrating is part of a reference field with an internal structure, which makes 'iterator' appropriate. For nodes, however, uid is a simple property, not a field array, so you can map it more directly:

process:
  uid:
    plugin: migration
    migration: luxus_users
    source: uid


Is there a way to clone a feature in Drupal/Open Atrium? I want to create a clone of the Notebook feature and would like to do it without copying the files and doing a find/replace on the text. Is there an easy/built-in way to clone a feature and provide it with a new name?

Try http://drupal.org/project/features_clone.  From the project page:

  Features Clone is a Drush command that allows quick cloning of a Feature. It can be used to rename or fork (e.g. to start a new feature off of an existing one) a Feature installed on a Drupal site.


How to debug 404 on user/login user/register user/logout? I have a Drupal 8 site on 8.4.2.  When I upgrade it to 8.5.1, after running the database updates, the paths /user/register, /user/login, and /user/logout return a 404.

I can log in with Drush (drush uli myuser), so it is possible to actually log in, but the log in page is not displayed.
I tried uninstalling my custom modules, but the problem persists.
I looked at /admin/reports/dblog, but it just says "page not found" as the error for /user/login.

This question about a similar problem was closed as off topic because it was too specific; my question is about "how can I debug this?" not "what is the cause of my problem?"

@AndrewKillen:

  Checked with Devel and it says "Unable to load route for url
  '/user/login'" when checking the user.login route.

How this could be debugged (on an working example, because I don't have a broken site):

Enable Xdebug and go to the url: /devel/routes/item?path=/user/login

Drupal\devel\Controller\RouteInfoController::routeDetail:

  public function routeDetail(Request $request, RouteMatchInterface $route_match) {
    $route = NULL;

    // Get the route object from the path query string if available.
    if ($path = $request->query->get('path')) {
      try {
        $route = $this->router->match($path);

Set a breakpoint for the last line and step into match($path). Then after a new request with the path info is created you get to:

Router::matchRequest:

  public function matchRequest(Request $request) {
    $collection = $this->getInitialRouteCollection($request);
    if ($collection->count() === 0) {
      throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $this->currentPath->getPath()));
    }
    $collection = $this->applyRouteFilters($collection, $request);

    if ($ret = $this->matchCollection(rawurldecode($this->currentPath->getPath($request)), $collection)) {
      return $this->applyRouteEnhancers($ret, $request);
    }

getInitialRouteCollection() results in three possible matches:

user.login
user.login.http
entity.user.canonical

The second one is filtered in applyRouteFilters() because this is POST only and for JSON. The entity route is removed after the compiled routes are matched in matchCollection() because "login" is not a valid user.

And so the route user.login is the last one remaining and returned. If not you have to check where on this way the route is not collected or filtered out.


Hide a field in a view if it is empty I customised the output of a field (using Rewrite the output of this field) but if the field is empty, only the customizations and not the content appears. I want to hide both the customizations and the content if the field is empty

Check if the screenshot settings work for you,this the setting for the field you want to hide when empty. It provides option to hide the rewritten content as well.


Repeated Attempts to register accounts I have a site with a many users, and public registration is not allowed, I'm the only one who can create accounts. I'm pretty new to drupal, and looking in the log messages I see this FREQUENTLY! What is this all about? Is someone trying to hack my site (sorry for the newb-termanology) but is this some sort of sqli or something I should be worried about? This happens often, and I'm wondering if my site has any vulnerabilities I should be worried about.

Thanks for helping shed some light on the situation!

page not found  02/20/2013 - 2:56pm register'). Anonymous
page not found  02/20/2013 - 2:56pm .url('user/register').  Anonymous
page not found  02/20/2013 - 2:56pm register'). Anonymous
page not found  02/20/2013 - 2:56pm .url('user/register').  Anonymous
page not found  02/20/2013 - 2:56pm register'). Anonymous
page not found  02/20/2013 - 2:56pm .url('user/register').  Anonymous
page not found  02/20/2013 - 2:56pm register'). Anonymous
page not found  02/20/2013 - 2:56pm .url('user/register').  Anonymous
page not found  02/20/2013 - 2:56pm register'). Anonymous
page not found  02/20/2013 - 2:56pm .url('user/register').  Anonymous
page not found  02/20/2013 - 2:56pm register'). Anonymous
page not found  02/20/2013 - 2:56pm .url('user/register').

I wouldn't call it "hacking", but someone (person or automated script) is definitely trying if you accidentally "left the door open". They found out that you didn't. Don't worry about it... As long as you keep your site up-to-date with security updates!


Show articles on new page Is there a way to not promote articles on to the front page and instead gather them under a main menu link?

Like main menu link -> myArticles and on click all articles written will be shown there?

Yes that would be relatively easy. How I would do that:

Edit the main menu: yoursite.com/admin/structure/menu/manage/main-menu and add menu item named My Articles (linking to a view is what I would do but you can choose to link it to anything you want - or nothing)

Edit the article content type: yoursite.com/admin/structure/types/manage/article

in Publishing Options deselect Promoted to Front Page
in Menu Settings:

check Main Menu under Available Menus
select My Articles (or whatever name you chose) in Default parent item

Then every time you create an article select provide a menu link. This will obviously work best for new sites where you don't have to go through and edit old articles to be in the menu.


drush sql-dump gives warning When I ran drush sql-dump --result-file, it came back with a warning and a success message.

system(): Cannot execute a blank command exec.inc:36                 [warning]
Database dump saved to                                               [success]
/my/homedir/drush-backups/unknown/20150113014628/_20150113_014628.sql

However, I checked inside the directory and no .sql backup file can be found. I have also read this issue, but I am not using drush aliases.

How can I fix this and backup my database using the command line?

I was following the docs, which told me to execute the command in my 'From your Drupal directory', so I executed the command on my Drupal installation root directory.

I have a multi-site set up, and running it inside my site directory /sites/mysite/ worked.


Providing "translations" based on region rather than language We are using FAPI to create some custom forms (actually extending the registration form) and want to provide different form labels based on a Country of Residence. For example if in Australia they will be asked to enter "City/Town/Suburb" but if they're in New Zealand the label will be "City".

Is this something that can be done and managed with Drupal's base translation modules? My understanding so far is that most of this functionality is at the language level rather than "regional" settings. If not, what would be a plan for managing this in a maintainable way?

Thanks.

The addressfield module does this.  You can check their code to see how you can implement such a feature in D7.


colorbox does not seem to work anymore after upgrade from 7.x-1.6 to 7.x-2.9 I upgraded colorbox from 7.x-1.6 to 7.x-2.9 and now, I lost functionality of loading the pictures in a box. my page is http://www.quaaoutlodge.com/content/lodge and the centered picture in the middle, used to load nicely in a colorbox frame before the update but this does not work anymore now. The link looks like:

The link is being "auto-created" as follows:
In my Content type, I have added a Field myImage that allows me to upload and insert the image into the content. The Format of the field, I set to Colorbox. I setup my image styles as follows:

Content image style: Hide
Colorbox image style: Original image
Colorbox gallery type: Per page gallery
Colorbox caption: None

And don't understand how this isn't working anymore after the upgrade...
Whaty's wrong with this I'm wondering? Should I rollback to 7.x-1.6 or can I fix this?

EDIT A
The colorbox module is installed & enabled and it says A light-weight, customizable lightbox plugin for jQuery 1.4.3+. Looks like I'm using jQuery 1.4.4:

EDIT B
I just copied modules/colorbox/ to libraries/colorbox/ but that didn't change much. You say the "JS lib" is not included on the page? I have

and

in my source code, the second line refers to jQuery 1.8

i think you need to update the colorbox library too !

right now - the JS lib is not included in the page ...


How to delete old images uploaded via FAPI Consider the following bit of code in my custom module... It allows a user to upload an image, saves the fid as a variable, and in a custom submit function, it makes sure that the file in the file_managed table is saved permanently.

This all works great, but when my users are uploading a file, then saving, then removing that old file and uploading another and saving, all of these files are left in the file_managed table, with a status of 1.

function MYMODULE_admin() {
  $form = array();
  $form['style']['business_logo_fid'] = array(
    '#title' => t('Business Logo'),
    '#type' => 'managed_file',
    '#description' => t('Upload a logo for your business in one of the following formats: jpg png jpeg.'),
    '#default_value' => variable_get('business_logo_fid', ''),
    '#upload_validators' => array(
    'file_validate_extensions' => array('jpg png jpeg'),
    ),
    '#upload_location' => 'public://',
  );

  $form = system_settings_form($form);
  $form['#submit'][] = 'after_save_ui';
  return $form;
}

function after_save_ui($form, &$form_state) {

    $business_logo_fid = variable_get('business_logo_fid');
    if ($business_logo_fid) {
        $business_logo = file_load($business_logo_fid);
        $business_logo->status = FILE_STATUS_PERMANENT;
        file_save($business_logo);
    }

}

How do i mark these old images as unused after a new one has been saved in its place? Is there something I can do to get the fid from the old file and mark its status as 0 before the new one gets saved? or is this something that Drupal handles already for me?

Its always the way! You spend an hour fussing over it, but when you actually write the question down, you think of it in a different way!

Its a bit long winded, but my complete example is this...

 function MYMODULE_admin() {
      $form = array();
      $form['style']['business_logo_fid'] = array(
        '#title' => t('Business Logo'),
        '#type' => 'managed_file',
        '#description' => t('Upload a logo for your business in one of the following formats: jpg png jpeg.'),
        '#default_value' => variable_get('business_logo_fid', ''),
        '#upload_validators' => array(
        'file_validate_extensions' => array('jpg png jpeg'),
        ),
        '#upload_location' => 'public://',
      );

      $form = system_settings_form($form);
      $form['#submit'][] = 'after_save_ui';
      return $form;
    }

    function after_save_ui($form, &$form_state) {

        // Save the Business Logo Permenantly.
if (isset($form_state['values']['business_logo_fid'])) {
        $new_logo_id = $form_state['values']['business_logo_fid'];
        $old_logo_id = $form_state['complete form']['style']['business_logo_fid']['#default_value'];
          if (($old_logo_id != 0) && ($new_logo_id != $old_logo_id)){
            $business_logo_file = file_load($old_logo_id);
            if (!empty($business_logo_file)) {
              file_usage_delete($business_logo_file, 'webfroth_booking_ui', 'business', $business_logo_id);
              file_delete($business_logo_file, TRUE);
              drupal_set_message(t('Old Logo Removed.'));
            }
          }
          if (($new_logo_id != 0) && ($new_logo_id != $old_logo_id)){
            $current_business_logo = file_load($new_logo_id);
            if (!empty($current_business_logo->fid)) {
              $business_logo_file_id = $current_business_logo->fid;
              variable_set('business_logo_fid', $business_logo_file_id);
              file_usage_add($current_business_logo, 'webfroth_booking_ui', 'business', $business_logo_file_id);
              $current_business_logo->status = FILE_STATUS_PERMANENT;
              file_save($current_business_logo);
              drupal_set_message("New Logo Uploaded Successfully.");
            }
          }
        }
    }

This works great, but it CANT be the standard way to handle this everytime I want to use an image field in a custom module surely? Seems like a massive hassle!


Plain Unstrucutred HTML Content Types, How to Pull image from them in Views This is a plain unstructured node with no CCK structure or anything like that (the site includes thousands of posts so it is impossible to retroactively go back and re-insert the images in using CCK).

How can I pull the first image in the node out and use that image within a view as a thumbnail image? (It's a related posts view)

I'm not 100% sure how to create a view theme, the drupal documentation on it is really confusing and I can't find a good tutorial on how to create a custom view theme either.  So since I think that is the best solution if you know how to do that, could you point me to a tutorial or something that actually teaches you how to create your own themed view (one that makes sense).

Thanks for any tips or advice.

you will need to only create one view theme. That will be a theme for the BODY field of your node. It's actually super simple.

create a PHP file in your theme folder called views-view-field--YOURVIEWNAME--body.tpl.php
your file has one variable you need to worry about, $output and that's the HTML. Write your PHP code to isolate the very first image tag and then this site has a nice example of how to do that

I think the code in this file would end up looking like this

  $first_img = '';
  $numMatches = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $output, $matches);
  if($numMatches){
    $first_img = $matches [1] [0];
  }else{ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  echo '<img src="' . $first_img . '" alt="thumbnail" class="thumb"/>';

add some CSS to make the thumbnail, or alternatively you can use theme with imagecache I think.
refresh your template cache

You're done!


Pagination for inline entity form I'm using Drupal 8 and have question about Inline Entity Form module.

Is it possible to introduce pagination in inline entity form module somehow?

Ideally, I'm looking for already available solution, but I'm fine if I will have to extend the module for this. But I'm not sure how it can be done.

Any pointers and help would be much appreciated.

I'm not ruling out mystery module that I am unaware of,  but I can give some insight.

The first obvious choice is the API, just reference the hooks in :   /modules/contrib/inline_entity_form/inline_entity_form.api.php

You can also add a FieldWidget in your module like: YOUR_MODULE/src/Plugin/Field/FieldWidget/IEFPagination.php,  then you would select it under Manage Form Display.

namespace Drupal\YOUR_MODULE\Plugin\Field\FieldWidget;

use Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormComplex;

/**
 *
 * @FieldWidget(
 *   id = "ief_paginated",
 *   label = @Translation("IEF - Paginated"),
 *   field_types = {
 *     "entity_reference"
 *   },
 *   multiple_values = true
 * )
 */

class IEFPagination extends InlineEntityFormComplex {

 public function formElement(\Drupal\Core\Field\FieldItemListInterface $items, $delta, array $element, array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {

    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    /* Adjust element here */

    return $element;
}

 public static function buildEntityFormActions($element) {

    $element = parent::buildEntityFormActions($element);

    /* Or here */

    return $element;
 }


PHPUnitTest is missing the file_managed table? My PHPUnit test is throwing an error saying that my file_managed test database table does not exist. What module do I need to include for that test table to get created? I would think it should be the file module, but I've already got that listed in my $modules array.

This is a Kernel test and I've been trying to fill up the modules array with everything I can think of that might actually get that table created.

  public static $modules = [
    'system',
    'path',
    'user',
    'file',
    'file_test',
    'node',
    'field',
    'media_entity',
    'entity',
    'image',
    'graphql',
    'graphql_core',
    'custom_graphql_file_upload',
    'custom_graphql_field'
  ];

Here's the error:

Invalid GraphQL query. Errors: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'contenta.test87607590file_managed' doesn't exist: INSERT INTO {file_managed} (uuid, langcode, uid, filename, uri, filemime, filesize, status, created, changed) 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, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array

I'm trying to test a graphql file upload to make sure the file entity gets created as expected. I have a lot more tests I want to write and lot more that needs to be solved with multi-part/form data, etc, but I need to figure this out first I think.

Here's the full test
https://github.com/justinlevi/graphql_custom_file_upload/blob/feature/PHPUnitTest_WIP/tests/src/Kernel/MutationFileUploadTest.php

All other code posted as well on the WIP branch.

Ugh... Forgot to install the entitySchema.

This is how to do it in the setup method

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->installConfig('system');
    $this->installConfig('graphql');
    $this->installConfig('file');
    $this->installConfig('image');
    $this->installConfig('user');
    $this->installEntitySchema('user');
    $this->installEntitySchema('file');

    Role::load(RoleInterface::AUTHENTICATED_ID)
      ->grantPermission('execute graphql requests')
      ->grantPermission('create media')
      ->grantPermission('view media')
      ->grantPermission('access content')
      ->grantPermission('bypass node access')
      ->grantPermission('create url aliases')
      ->save();
  }


Taxonomy terms follow/unfollow module (even for anonymous users) I want a subscriptions/notifications like module which works for anonymous users too.

Users should be able to subscribe to a taxonomy term, and then be alerted if content is created for that term.

Subscriptions work great but the lack of support for an anonymous user is quite disappointing. I don't get why we can't send a verification mail for any anonyomous user based subscription.

Any Drupal Module which does that?

You can use my sandbox module
Total Subscription

This module is in the Drupal project applications' issue queue.

It will provide the functionality as per your requirement.


How to display something conditionally in template file depending on the current path I would like to do  on page.tpl.php conditionally depending on the current path. I'm using Auto Assign Role and have two paths for registration.

Reading this tutorial, as far as I've understood I can make a template file that overrides the registration page. However I would like to display different things on two deferent paths. How can I do this?

Drupal core's template suggestions allow for naming page templates based on the path of the page. So, theoretically, if you had www.mysite.com/registration-a, then you could use the the page template name page--registration-a.tpl.php and so forth.

However, if this does not work, you can create a page preprocess function in your theme or module that adds some template suggestions based on the path.  For example:

function THEME_NAME_preprocess_page(&$variables) {

 if($arg[0] == 'registration-a'){
 $variables['theme_hook_suggestions'][] =  'page__registration_a';
 }

 if($arg[0] == 'registration-b'){
 $variables['theme_hook_suggestions'][] =  'page__registration_b';
 }

}

this would allow you to use page--registration-a.tpl.php and page--registration-b.tpl.php, etc.

For reference, $arg is an array that contains the different parts of a URL, so if you had the path mysite.com/registration/customer, then $arg[0] would be 'registration' and $arg[1] would be 'customer'.


User logout automatically when the browser is closed I need to logout a user if the browser is closed. I'm using Drupal 8.
I tried setting a session cookie in php. But the problem is the cookie should be 'httponly' and 'secure'.

Please suggest me the right method or is Drupal having such settings to achieve  this.

Thanks.

Okay, I changed the cookie_lifetime: 2000000 to 0 in local.services.yml file.

Then set the cookie in php by giving the last 2 arguments as 'true' ,this makes the cookie to be httponly and secure.

Thanks for your reference.


How can I create a Views RSS of members only content? We have a website with a members only content in the form of a forum.

I have already created the RSS feed and I can see that when I load the feed URL in a web browser that it is working. The problem is that I can only see it when I am logged into the website itself, and therefore when I load it into my web based reader, or Microsoft Outlooks RSS feed; that it can not see any posts.

The views screenshot I used is below:

Does the fact that a user needs to be logged into the website to view the content prevent me from doing this?

EDIT: I have been editing drupal/modules/system/system.api.php to include suggestions below including changing 'forum/%forum_forum' for the explicit 'forum/rss.xml' - it loads the xml but with no content when I am not logged into the website itself.

EDIT 24/09: After a bit of a break I have come back to this one for a fresh look.

I installed Custom Menu Permissions as advised, found the forums/rss.xml and forums/%forums_forum/rss.xml and allocated them to a custom permission which I then allowed for both Anonymous and Authenticated users.

I flushed all the caches and tries while logged off. Still nothing.

I can see the rss feed still while logged in, so I know it is there. That would discount anything stopping it being produced.

I also ensured that I had removed my custom hook_alter code as suggested below to ensure there were no conflicts.

Any further assistance to the right direction would be appreciated....

Yes. The forum/%forum_forum route created by the Forum module does a user_access() check for the access content permission; any subpath of this route (e.g. your RSS view, forum/%forum_forum/rss.xml) will be checked as well.

You can override this via a hook_menu_alter() implementation:

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['forum/%forum_forum']['access callback'] = 'MYMODULE_forum_override';
}

function MYMODULE_forum_override() {
  return preg_match('/^forum\/(\d+)\/rss.xml$/', request_path());
}


Loading dependencies from the vendor directory in a module using composer I am using composer for managing dependencies in my drupal module. I specified my dependency in the composer.json file placed in my module's root directory. After running the composer install comand it installs all the dependencies correctly; however, the autoloading does not seem to work.

I have checked several threads here that deal with the problem and found that most of them suggest using the composer manager module that's available even though on the module's page on drupal.org it says that it's deprecated due to Drupal's improved use of composer since version 8.1

Here's my composer.json file in my module's root diretory:

{
"name": "activit/facebook_ratings",
"description": "Display a feed of your Facebook fanpage's ratings on your website.",
"type": "drupal-module",
"require": {
    "facebook/graph-sdk": "^5.4"
},
"license": "MIT",
"authors": [
    {
        "name": "Robert Balasko",
        "email": "rbalasko@activit.sk"
    }
]
}

and a factory class in the root of src directory that tries to load a class from the graph-sdk.

<?php namespace Drupal\facebook_ratings;

use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Facebook\Facebook;

class FacebookConnectorFactory {

  private $logger_factory;

  public function __construct(LoggerChannelFactoryInterface $logger_factory) {
    $this->logger_factory = $logger_factory;
  }

  public function getFacebookService($app_id, $app_secret) {
    if (!$app_id || !$app_secret) {
      $this->logger_factory
        ->get('facebook_ratings')
        ->error('Undefined App ID or App secret');

      return FALSE;
    }

    return new Facebook([
      'app_id' => $app_id,
      'app_secret' => $app_secret,
      'default_graph_version' => 'v2.6',
    ]);
  }

}

The result is a class not found error when I run my code. Shouldn't the dependency be autoloaded or am I doing anything wrong?

Thanks a lot.

Composer Manager is just a small wrapper around the Merge Plugin which we have in core nowadays.

Register your module in the root composer.json of your project, look for extra > merge-plugin > include. It should look like this:

"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php."
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/facebook_ratings/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }
}

modules/facebook_ratings/composer.json is the path to your composer.json. It depends on where you have your module.

Run composer install afterwards.


How to render a custom entity in a controller? I created a custom entity called foo. This entity has a unique name field as well as the standard id key. I would like to build a page where the user can see the entity rendered similarly to how it would be on the admin page, but instead of referencing it by the id, I would like to use the name.

I have the following in my controller:

public function content($name) {
  $output = [];
  //Add a couple things to the $output array
  $output['first thing'] = [/*stuff*/];

  $sql = "SELECT id FROM foo WHERE name=:name";
  $sql_params = [':name' => $name];
  $results = db_query($sql, $sql_params)->fetchAll(PDO::FETCH_ASSOC);
  $render_array = [];
  if (count($results) > 0) {
    $id = $results[0]['id'];

    $entity_type = 'foo';
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $controller = \Drupal::entityManager()->getStorage($entity_type);
    $entity = $controller->load($id);
    $build = $view_builder->view($entity);
    $render_array = render($build);
    $output['entity'] = $render_array;
  }
  return $output;
}

However, I receive an error: User error: "entity" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core\lib\Drupal\Core\Render\Element.php).

What do I need to do differently to make my entity render to the page?

Controllers should return a render array (or a custom response), you almost never need to render anything yourself outside a template.

Just replace this:

$build = $view_builder->view($entity);
$render_array = render($build);
$output['entity'] = $render_array;

with:

$output = $view_builder->view($entity);

to return a render array and let Twig handle the rendering.

But going further, you don't need to (and shouldn't) go into the database directly for this; the entity type manager works for all entity types, including your own, and entity storage classes have methods to help with this.

(As an aside, that service should also be injected rather than loaded from the static Drupal class method, your controller class is container aware).

Once that's available the code would be simplified to something like this:

public function content($name) {
  $build = [];
  $entity_type = 'foo';

  $storage = $this->entityTypeManager->getStorage($entity_type);
  $entities = $storage->loadByProperties(['name' => $name]);

  if ($entity = reset($entities)) {
    $build = $this->entityTypeManager->getViewBuilder($entity_type)->view($entity);
  }

  return $build;
}

To go one step further, you can add a loadByName() method to your entity class with a slight variation of the above, might save you some time and repetition further down the line.


Contextual filter Term OR Empty I have a view using taxonomy CONTEXTUAL FILTERS.

taxonomy vocab 1 terms AND
taxonomy vocab 2 terms

Both are set to get the taxonomy id from the url, limited to a specific taxonomy vocabulary and share any of the terms.

But on taxonomy vocab 2, I would like to have an additional filter to pull content without any vocab 2 terms at all.

something along the lines of

has taxonomy vocab 1 terms AND
has taxonomy vocab 2 terms OR
has NO taxonomy vocab 2 terms

I can do this with two separate views:

VIEW 1

has taxonomy vocab 1 terms AND
has taxonomy vocab 2 terms

VIEW 2

has taxonomy vocab 1 terms AND
has NO taxonomy vocab 2 terms

but I would like to combine the results.

Edit: if I have this set of content with terms, and the Contextual argument is term 1 I want the first and third to be shown in Views results:

content 1 | term 1
content 2 | term 2
content 3 | no term selected

You can draw some clues from this question: Views contextual filters for NULL value You should use Computed field or some other way of introducing custom PHP into your Views (custom module is the best option).

If you use more than one Contextual and need to have the OR operator between them you can use the Views Contextual Filters OR module.

There is also a patch for the D7 version you can expand on: Add an "OR IS NULL" option to contextual filters.

But since you're using two vocabularies and need to maintain the AND between the two contextuals you won't be able to use the "OR" module and you'll have to come up with a custom code solution for the second contextual that takes care of the both "there is specific term" and "there are no terms" in one contextual filter, so you can combine it with the contextual for the Vocabulary 1.


Create submittable review form I want to be able to allow users to rate businesses on various factors such as staff helpfulness and quality of clothing. I've been told that the best way to create the content type for the review form would be through the use of integer fields. I have now set up that content type, but am not really sure how to allow users to view/submit the review.

When I create content with the type "review," all that is displayed to the user is a comment section. They cannot see any of the selectable fields created in the content type, let alone submit them, because no values were defined by myself when the content was created. How would I go about making a displayed version of the form, with the menus exposed (in a similar fashion to exposed filters in Views, I suppose).

After the displayed form is created, I need a way to allow it to be submitted. Obviously, the review form would be useless if the information can't be submitted into the database to be later displayed in the reviewed business's page.

EDIT: A suggestion below suggests using webform, but as far as a I can tell, there is not a way to display the results of the form within another node. So, although webform presents a way to submit reviews and for me to see the results, there is no way to display them without manually inputting the average ratings into the  nodes that the reviews are related to.

I recommend checking out the Webform module.  It seems like the best way to handle this type of functionality.


Add Html code to Menu Title in Bartik I am trying to add my own image menu names (I prepared png files) instead of menu titles (Navigate, Category, Home etc.). How can I do this? Which files should I need to check? I know Html Menu module but it does not work on menu titles.

Thank you.

Firstly I'd say menu titles should be text, for accessibility, maintainability and SEO reasons.

If you must, you could consider using CSS background images by checking the classes or IDs on those menu elements and adding CSS rules target them.


How to show all content type images in a gallery I would like to realize a View that shows, randomly, 5 images taken from Image field in y content type.
I've tried but i only see the images from a single record, i would need to show ALL of them together. Is it possible?

Follow below steps to resolve your issue.

Create a new view of type files.
Add Filter File:Mime Type and select the condition as Contains any word.
Give all image extensions in the value like jpeg jpg png etc
Rewrite the results of the File Path field and add img tag with src as file path.

Using above instructions you can list all images in Drupal independent of any content type or image field.


Map generated from custom address fields I have a seemingly simple problem, but I've been stuck with it for some time now.

I have a big database of nodes of one content type. There are addresses there made of text fields: one field for street, one for city etc. Province is a predefined taxonomy. I'd like to use 4 of these fields, including province, to get a string that can be geocoded as lat/lon for a map.

I also need these fields to be useable in Views (e.g. as filters like a province filter, as tokens etc.). It is doable in GMaps + Location (Views module recoginzes each locative entry as a separate field), but GMaps is seemingly an obsolete module, and it forces me to use predefined provinces which is not cool.

Also, I need to display a small map when a user displays one of the nodes, and the other for the home page with all the locations marked and ready to get filtered out by exposed filters.

I thought maybe geocoded Field Collection is an option for me, but the separate elements of such a field are strangely not visible in Views module as filtering/sorting criteria. I also tried the Computed Field, but there is a bug which prevents its text output from being geocoded. ( http://drupal.org/node/1679926 -- bug desc.)

Am I missing something? Are there any other simple ways to get a map made of custom fields as address elements?

Regards!

You could use the Geofield and the Geocoder modules. The fist module allows to store geographic data in a field; the second one to extract the geographic data from another field, including an image field.
When you add a new field to an entity (for example, a node), you need to select Geofield as field type, and leave Geocode from another field as widget.

Clicking on the Save button, you will be then asked to change the field settings (which just allow to change the storage backend). After clicking on the Save field settings button, you can choose from which field the geographic data are extracted, including an image field.

The Geocoder module once allowed to select multiple fields from which the geographic data would be extracted, but that was a bug, reported in
Geocode from field allows multiple selections and fixed. If you are reading blog articles or tutorials that suggests you can select multiple fields from which the geographic data are extracted, they are all referring to older module versions.


How to make existing fields available to be created as instances on other content types etc.? I have created a custom module that simply creates a set of standard fields via a .install file. It's very simple, basically:

foreach (my_fields_fields() as $field) {
  if (!field_info_field($field['field_name'])) {
    field_create_field($field);
  }
}

function my_fields_fields() {
  return array(
    'field_my_first_name' => array(
      'field_name' => 'field_my_first_name',
      'type' => 'text',
    ),
    ...

On enabling the module, I can see that the fields have tables in the database. However, if I navigate to admin/structure/types/manage/article/fields and drop down - Select an existing field - in the Add existing field section, the fields are not present.

I don't want to create any instances of my fields in my module (do I?) because it is for other users/systems to create field instances if they want to.

How do I get Drupal to make my fields available? Thanks.

An 'existing field' in that context is one that already has an instance, it doesn't refer to the existence of the field type. Until an instance is created, it doesn't exist as such.

Your field will be available to add as a new field as usual; if you want it to appear under 'Add existing field' section, you'll need to create an instance of it first.


Wrong Currency symbol in view filter I have a view with BEF which is generating a criteria box like this below

I have no clue where this $ sign is coming from and how to remove it or change it.

Update

I investigated further and what I have noticed is that the currency symbol is linked to the theme settings. There is a field in the theme settings to accept currency code which was by default EUR. That I changed to INR which is not working but when I change to JPY it shows proper japan yet currency symbol. This confirms that this is the place where we need to look at.

Can some one help me where to start from?

Your currency symbol is most likely coming from the field definition. Check the "prefix" value for the field in question at admin/structure/types/manage/<content_machine_name>/fields/<field_machine_name> replacing the items in <> as appropriate.


Programmatically enable Mollom protection for a form I want to enable Mollom protection for a number of forms in my development environment, and then export that configuration to QA and to Production without touching the Admin interface in QA or production.

I can export the Mollom settings via Features + Strongarm, but it doesn't appear to export the configuration for forms protected by Mollom.

I see that I can use hook_mollom_form_list and hook_mollom_form_info to make new forms available in the UI with default values, but I can't get hook_mollom_form_info to fire without enabling protection for the form in the UI.

I am trying to add a captcha to the registration form and password reset form, do text analysis on comments, and do text analysis for my custom node submit form. It appears that the mollom module already has definitions for all of these forms, but I don't see any way to enable them.

I didn't find a better way, so I did inserts directly into the DB.

In mymodule.install:

function mymodule_update_70001() {
  # CAPTCHA on registration form
  db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'user_register_form',
      'mode' => 1,
      'checks' => 'a:0:{}',
      'discard' => 1,
      'enabled_fields' => 'a:0:{}',
      'strictness' => 'normal',
      'module' => 'user',
    ))
    ->execute();

  # CAPTCHA on password reset form
  db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'user_pass',
      'mode' => 1,
      'checks' => 'a:0:{}',
      'discard' => 1,
      'enabled_fields' => 'a:0:{}',
      'strictness' => 'normal',
      'module' => 'user',
    ))
    ->execute();

  # Text analysis of comments
  $response = db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'comment_node_mynode_form',
      'mode' => 2,
      'checks' => 'a:2:{i:0;s:4:"spam";i:1;s:9:"profanity";}',
      'discard' => 0,
      'enabled_fields' => 'a:2:{i:0;s:7:"subject";i:1;s:27:"comment_body][und][0][value";}',
      'strictness' => 'normal',
      'module' => 'comment',
    ))
    ->execute();

  # Text analysis of submission
  $response = db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'mynode_node_form',
      'mode' => 2,
      'checks' => 'a:2:{i:0;s:4:"spam";i:1;s:9:"profanity";}',
      'discard' => 0,
      'enabled_fields' => 'a:4:{i:0;s:5:"title";i:1;s:19:"body][und][0][value";i:2;s:32:"field_projectpage][und][0][value";i:3;s:33:"field_downloadpage][und][0][value";}',
      'strictness' => 'normal',
      'module' => 'node',
    ))
    ->execute();
}


Search box for views and tags I want to be able to have a search box so that when you search, the result is displayed in a view. I want to search for tags in nodes.

The reason I want to display this in views is because I only want to display 3 fields and I want to display it in a 3x3 grid with a pager.

I don't want to be using Apache Solr because the output of the search is quite ugly and I can't customise the fields I want to display etc... Also I want to keep the layout consistent with the rest of my views.

I found this http://drupal.org/project/apachesolr_views but it requires views 3, and I don't feel comfortable upgrading.

Is there any way to have some sort of search box for views that would search for tags? and what module would you recommend me for tagging my content?

I'm using Drupal 6.

Thanks.

You create a search box for Views by adding a filter and then setting it to be "exposed". This creates a form by which the user can set filter values such as tags.

You don't need any special module for tagging under normal circumstances as the core Taxonomy module works perfectly well.


How to configure access for creating a custom LMS? I am looking to create a LMS either in an existing Drupal install.

Anonymous users can browse course information and also preview certain Modules & Slides (see below). They will be able to buy access to a Course and then view the all the Course content. There will be a multiple different Courses, each need to be purchased separately at different prices.

Course hierarchy:

Course > Module(s) > Topic(s) > Slide(s)
Course is what the user will pay for access
Modules and Topics are the only for categorisation and may only have a Small description
Preview content will be by only a select few Modules per Course - being able to see the slides within chosen module
Slides are where the learning content is - mostly videos and PDFs
Slides may also be a Quiz

Once purchased, the display of the course content will be with the full course hierarchy in a sidebar so the user can navigate through the course and view the content of each slide in the main content panel by selecting the Slide.

Question: There are a few choices out there, however I have seen posts about Organic groups. Is this the best way to categorise the Course Content, or should I use Taxonomy? (As the how user view the course information will be with the full Course hierarchy in a side bar and selecting Slides will show the Slide content in the main section)

I am very familiar with Drupal basics, but I would like to know how to restrict user access to only their own purchased content?

What would be your solution to set this up?

I recommend you have a look at the Group module, which may be considered as a possible alternative to the Organic Groups module, and which you seem to be familiar with already.

Have a look at my answer to "What are the features of the Group module versus Organic Group module?" for details about:

How both modules compare to each other.
Integration with various modules that you might want to take advantage of also.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Podcast "Using the Group module as an Alternative to Organic Groups in Drupal 7 and 8".

Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 2            ! Customers  ! 5             ! Lead
 2            ! Customers  ! 6             ! Prospect
 2            ! Customers  ! 7             ! Licensed Customer
 2            ! Customers  ! 8             ! Sales
 2            ! Customers  ! 9             ! Support
 2            ! Customers  ! 10            ! Accounting
 2            ! Customers  ! 11            ! R&D
 3            ! Project    ! 12            ! Project Manager
 3            ! Project    ! 13            ! Developer
 3            ! Project    ! 14            ! Customer

Group Types

The above example consists of 3 group types:

Class.
Customers.
Project.

Group Roles

For each of the 3 group types, there are specific Roles defined, some more details about some of them:

for the Class group, these are the 2 roles that are configured:

Instructor.
Student.

for the Project group, these are the 3 roles that are configured:

Project Manager.
Developer.
Customer.

These are the Group Specific Roles: these roles can be configured per group type and will only be available on groups of that group type. As an example, for group type "Class", the defined roles are Instructor and Student (which are not available for the other group types.

On top of the group specific roles, there are also Special Global Roles: These are the special (hardcoded) roles named Outsider (= a signed in user that did not join a group) and Member  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role Anonymous is related to a user that is not signed.

Groups

Each of the configured group types can have any number of Groups.

Examples of groups:

for the Class group type, there could be these Groups:

Getting started with Drupal.
Drupal for site builders.
Become an expert in using the Rules module.

for the Customers group type, there could be these Groups:

Service Requests.
Order Processing.
Sales Orders.
Relationship Management.

Permissions

For each of the configured group types, you can then also configure for each Content Type which Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

PS: this answer applies to either D7 or D8.


Save a user field without calling hook_user_update I'm building a module that has to sync users with another, non-drupal, db. When the hook_user_update is run I check to see if the user has an account in the other db. If they don't then it creates a record there and returns their id from that system. The problem I have is now I need to store that new id in a custom drupal field as well. I don't want to assign it and call user_save inside of hook_user_update because I don't want to run another instance of hook_user_update before the other has finished running. So, is it possible to just save a single user field without having to call user_save thus triggering hook_user_update?

field_attach_update() may do what you need

https://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field_attach_update/7

A comment on the API doc page mentions using it to update a node's fields without updating the node.

If your custom field isn't part of the user object, you may just need to use drupal_write_record to write your field data.


Remove count from glossary view I have a situation where I need to remove (via client request) the letter count in the header of a view based on Glossary view. How might I remove the numbers (in parenthesis)

Previous question history: Paginate views by first letter of Node title

Go to the Attachment details of the Glossary view
Under Contextual Filters (you may need to click Advanced to see it) click on "Content: Title"
Uncheck "Display record count with link"


How can I make a block that holds all the information about an articles author? I would like to add a block into the side bar of all article nodes that contains a mini profile of the user who authored the article. I was wondering if there is an easy way to do this. Thanks

You should investigate the Views Module.  Watch the series at Nodeone.se regarding using the views module called "Taming the Beast" to learn how.


When I add a context filter, my view is wrapped in a div I created a view block to display a button (join / leave) above my groups. When I add a context filter to my view, it is wrapped in a div without "class" and "id".

1) I added to my view the following context filter:

(Group content User) User: User ID

2) When the filter value is NOT available: Provide a default value: User ID of the logged in user

Here is the result :

       Rejoindre le groupe

If I delete the context filter, the div envelope would disappear, but that's not the view I want:

 Quitter le groupe

 Quitter le groupe

I encounter this problem with other block view, it's really weird. An idea ?

Check the twig template (by turning on twig debugging) that is generating the div for your contextual filter. Then alter it with an ID or Class tag.

Let me know if you need help turning on twig debugging.

Find the twig template that is generating that div, copy it and rename it with one of the FILE NAME SUGGESTIONS. The add the following code to the div.

<div{{ attributes.addClass('my-class') }}></div>


How can I do an OR operation on the values of a solr field? Say I have a facet on countries, I'd like to be able to click on more than one country (say US and UK) and get results tagged "US" OR "UK".

Currently If I click on "UK" on the facet block, the other terms disappear if this was a "single solr field".

And if it was a multi-valued solr field, the other terms don't disappear but an AND operation is done.

How can I change the default behavior to allow OR operation on both "single" and "multi-valued" solr fields?

I'm using the Apache Solr Search Integration module version 1.6.

Can't say for sure if this is in 1.6 but if you configure the country facet block you'll get the option to use AND or OR inside the facet.


Webform display for specific roles Suppose we have 20 webforms A user which has Admin role as well User1 role should  only view its corresponding webform (eg: weform1 and webform2)rest webform should not display at(admin/content,/admin/content/webform) when he logged in as a user which is having User1+Admin role.

How to achieve this?

As per my knowledge you need to do little customization to achieve this.

Check the roles
Perform your require action(permission)

code to check logged in user has both roles?

global $user;
$roleA = 'administrator';
$roleB = 'user1';
$roleC = 'some other role';
$user_roles = array_values($user->roles);

    if (in_array($roleA, $user_roles) && in_array($roleC, $user_roles)) {
      // Do something.
    }
    elseif (in_array($roleA, $user_roles) && in_array($roleB, $user_roles)) {
      // Do something.
    }
    elseif (in_array($roleB, $user_roles) && in_array($roleC, $user_roles)) {
      // Do something.
    }

Second option.

You can look Rules module.


How to add Mini Panel I can´t mini panel in panel page because this not showing in content of panels.

I have mini panel module enable but... How can I enable mini panels in content panels??

Thanks for your answers.
Already solved the issue.

You have selected a layout Panopoly, I changed it to one of the "Extra laytous panels" and matter settled.


CiviCRM Membership form with login I would like to sell subscriptions on a site and have the person logged in automatically.

I have setup the contribution page and it works fine. The person at the end of the process doesn't get a drupal account or become logged in. We created a custom module to create the person's account at the end of the process. We haven't found a way to log them in though.

Ideally the person can register/pay/be logged in as one step. We are afraid that if we get them to register a drupal account, confirm the account and then pay the membership we will lose a lot of people as it is 'too complicated'.

To programatically user from code, you need to replicate what user_login_submit and user_login_finalize are doing:

function user_login_submit($form, &$form_state) {
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;

  user_login_finalize($form_state);
}

function user_login_finalize(&$edit = array()) {
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')->fields(array('login' => $user->login))->condition('uid', $user->uid)->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);
}

Just replace $form_state['uid'] with UID you generated in earlier step, and maybe use other way to redirect.


PHP Select options in CCK field I want to create a CCK field with options determined by PHP. On the content admin page,  in the Allowed Values PHP code the example it gave was

return array(
  value_1 => label_1,
  value_2 => label_2
  ...
);

However, I want one of the options to be the user's name, so I used something like:

global $user;
$name=$user=>$name;
return array( 'main_guy' => 'No', $name => 'yes' );

For some reason, it won't accept quotes or dollar signs. If I delete the first two lines, and remove the quotes and dollar signs (return array(main_guy => No, name => yes);), it works ok.

Any ideas?
 That would be the same as the standard, non-dynamic list options.

Your PHP is incorrect :(

The second line should read $name = $user->name;.


Including files in template.php. failed in some cases (when using some contrib modules) In template.php, in theme__preprocess_page function, I am including files (as my template.php grew big, I decided to separate some operations for readability) like this:

 function THEME_preprocess_page(&$variables) {
// .. skipped non-related code
 include  $_SERVER['DOCUMENT_ROOT'] . "/" . path_to_theme() . "/template_includes/file1.inc";

}

But sometimes some contrib modules complain about this. Currently I have an issue where Print module gives the following message:

Warning: include(): Failed opening
'/var/www/drupal/sites/all/modules/contrib/print/template_includes/file1.inc' **for inclusion** (include_path='.:/usr/share/php:/usr/share/pear') **in THEME_preprocess_page() (line 80 in** /var/www/drupal/sites/all/themes/THEME/template.php).

What causes paths mess?

If you read the docs for path_to_theme(), there is this tidbit:

  It can point to the active theme or the module handling a themed implementation. For example, when invoked within the scope of a theming call it will depend on where the theming function is handled. If implemented from a module, it will point to the module. If implemented from the active theme, it will point to the active theme. When called outside the scope of a theming call, it will always point to the active theme.

The Print module invokes preprocess functions within its own preprocesss functions (look at the code), so I think that is why yours is getting called with a scope other than your theme.

You should really do your include as

include drupal_get_path('theme', 'YOURTHEME') . '/template_includes/file1.inc';

or

include dirname(__FILE__) . '/template_includes/file1.inc';

There is debate in the Drupal community which is best.

Personally, I think including code within a function is a really bad practice, and would recommend splitting out whole functions into separate file(s), and doing the include at the top.  If you go that route, then you using the second form is best.


Adding jQuery Timeline to Drupal I have found this awesome jQuery Timelinr that I have customized for my Drupal site but am now at a loss at how to insert it. It is only going to be on one page. Does it need to be in a block? Do I have to make a custom module? Any assistance would be greatly appreciated!

There are many ways to do it. Easy one is to add it on your theme's .info file: scripts[] = js/your_jquery_plugin.js
But then its everywhere.

You can add it in a block. Check that your text-filter is set to PHP (May need to be active in the modules: PHP filter). Then add drupal_add_js()


Lat/long gets reset after updating At the moment I'm having some struggles with the location module in Drupal, well I'm not really sure that it's the location module that is causing the problems.

The best I can explain it with a little code. There is a module which connects to a backoffice and gets venues with lat / longitudes.

I do the following:

    dpm($node->field_address[LANGUAGE_NONE][0]);
    node_save($node);
    dpm($node->field_address[LANGUAGE_NONE][0]);

Before updating the node the values are in the object

    array(6) {
      ["street"]=>
      string(16) "Street 1"
      ["city"]=>
      string(7) "Middle earth"
      ["postal_code"]=>
      string(7) "12345"
      ["latitude"]=>
      string(8) "52.000"
      ["longitude"]=>
      string(7) "4.000"
      ["location_settings"]=>
      array(1) {
        ["form"]=>
        array(1) {
          ["fields"]=>
          array(2) {
            ["latitude"]=>
            array(1) {
              ["default"]=>
              string(8) "52.000"
            }
            ["longitude"]=>
            array(1) {
              ["default"]=>
              string(7) "4.000"
            }
          }
        }
      }
    }

After saving the node the lat / long is reset to int(0).
The lat / long in the location settings is still in tact.

I've search a long time to debug this, i was thinking maybe there's a hook that resets the value, but I just can't find it. I'm fairly new to Drupal so any help will be appreciated :)

Thanks!

Found the solution.

The lat/long came from a different source and when the location module tried updating the lat/long I got NULL/NULL, because I was on the max amount of requests to google.

Solution was to set the 'source' column in the location table to 1, so the module thinks the value is overruled by the user. The lat/long doesn't get updated / reset to null anymore.


Add JavaScript at the bottom of a page How can I add JavaScript scripts to bottom of a page, in my template?

I think you can do it with drupal_add_js(); it seems that the scope key option is your friend!


Creating Views rows with specific classes? I have created a view and it gives me lots of default css classes for the rows of my unformatted list. I have added the token [type] in the style options for the page under 'Row class'. So now my list items are wrapped in the following div:

You can see the class 'article' is added according to the node's content type. But, I need to give specific rows, like the third occurence of class 'article' row, their own 'static' unique css classes, like:

views-row-[number] will not do because it changes depending on how many rows there are in the view (not always the same in this view) i.e. the third from last row will sometimes be views-row-10, sometimes it will be views-row-13. How do I find out what other tokens are available to me (I'm looking for ones that will create unique classes), or is there another way that I can create a unique, unchanging, class?

I have tried using pseudo css classes to target the desired rows, like :nth-of-type(N).

Solution

To make classes unique, append an incrementing number to the required classes with jQuery. CSS pseudo class selectors are helpful too, as are tokens. There does not seem to be one solution that will fit every situation: a mix of approaches is required.

Add to template.php in your theme's root folder (or how ever you want to implement your jQuery):

/**
 * Implements template_preprocess_views_view().
 */
function YOURTHEME_preprocess_views_view(&$vars) {
    $view = $vars['view'];
    if ($view->name == 'VIEWNAME') {
        drupal_add_js('
            (function($) {
                $(function() {
                    $("div.article").removeClass("article").addClass(function(index) {
                        return "article-" + index;
                    });
                });
            })(jQuery);
        ', 'inline');
    }
}

You need to modify views-view-unformatted.tpl.php.

In your views, in the third column click on theme and choose the how specific should be you file, for the full view or for that display. Copy into your theme folder and rename it.

You can find more info here http://api.drupal.org/api/views/theme%21theme.inc/group/views_templates/7

    <?php if (!empty($title)): ?>

<?php print $title; ?>

    <?php endif; ?>
     <?php
     $i = 1;
     $num_rows = count($rows);
     $num_rows = $num_rows -2;
     ?>
    <?php foreach ($rows as $id => $row): ?>
    <?php
     if ($i == $num_rows){
       $classes_array['YourCLass'];
     }
     ?>
     <div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>
      <?php print $row; ?>
      <?php $i++;?>

    <?php endforeach; ?>

Flush cache


Route restrict access for current user How do I restrict access to the route by current user in Drupal 8?

I want to create a new tab in user profile path: '/user/{user}/my-cool-tab', which should be accessible by current user only. For example:

path /user/5/my-cool-tab should be available only for UID=5
path /user/7/my-cool-tab should be available only for UID=7
etc.

Which way is the simplest and correct for that?

You need an access check where you compare the passed user id with the current user, here's an example from simplenews:

public function checkAccess(UserInterface $user) {
  $account = $this->currentUser();

  return AccessResult::allowedIfHasPermission($account, 'administer simplenews subscriptions')
    ->orIf(AccessResult::allowedIfHasPermission($account, 'subscribe to newsletters')
      ->andIf(AccessResult::allowedIf($user->id() == $account->id())));
}

Note that this includes and admin permission check, for admins that can actually see the page for other users.

If you do not need that, you could also just make your route /my-cool-page and use the current user for whatever you are doing. With D8's routing system, you can even make local task appear on the user page if you want to.


How to print block from template? I have block template. How do I output this block on front page just by calling render($page[region_name]), where region_name is the name of a region to which the block is assigned.

Edit: I want to print the whole region assuming it contains only this block.

<?php print render(block_get_blocks_by_region('region_name')); ?>


How do I programmatically create a view in a custom module? I currently have a custom module that lets you create an entity.  The list page for this has gotten to be really long so I decided to create a view for this to allow filtering.  If this were a new module that I was about to install then I could just throw the .yml file into config/staging, but since it has to be done as an update I cannot just put the .yml file there.

It looks like it needs to be created all in code in an update hook.

Is there an easier way of doing this?

Place the YAML file in config/optional as you would normally do to create the view on install optionally when Views is enabled.

Then use an update hook to check whether the view exists when updating the module and create it in PHP by reading the YAML file:

function dblog_post_update_convert_recent_messages_to_view() {

  // Only create if the views module is enabled and the watchdog view doesn't
  // exist.
  if (\Drupal::moduleHandler()
    ->moduleExists('views')) {
    if (!View::load('watchdog')) {

      // Save the watchdog view to config.
      $module_handler = \Drupal::moduleHandler();
      $optional_install_path = $module_handler
        ->getModule('dblog')
        ->getPath() . '/' . InstallStorage::CONFIG_OPTIONAL_DIRECTORY;
      $storage = new FileStorage($optional_install_path);
      \Drupal::entityTypeManager()
        ->getStorage('view')
        ->create($storage
        ->read('views.view.watchdog'))
        ->save();
      return t('The watchdog view has been created.');
    }
    return t("The watchdog view already exists and was not replaced. To replace the 'Recent log messages' with a view, rename the watchdog view and uninstall and install the 'Database Log' module");
  }
}

Source: dblog_post_update_convert_recent_messages_to_view


How to restrict access to a path like user/%/flag? I have created a views to display flagged content. But the flag page is accessed by all users. I want users to access only their own flagged page.

You need to create custom Views access plugin for this.
First, you need to create mymodule.info file with next code

name = Mymodule
description = Custom code
core = 7.x
package = custom
dependencies[] = views
files[] = mymodule_access_plugin.inc

Second, add mymodule_access_plugin.inc in the your module folder  with next code

<?php

/**
 * Access plugin that provides property based access control.
 */
class mymodule_access_plugin extends views_plugin_access {

  function summary_title() {
    return t('Custom access plugin');
  } // summary_title()

  /**
   * Determine if the current user has access or not.
   */
  function access($account) {
    return mymodule_access($account);
  }

  function get_access_callback() {
    return array('mymodule_access', array());
  }

}

Third, implement  hook_views_plugins in your mymodule.module file

<?php

/**
 * Implements hook_views_plugins()
 */
function mymodule_views_plugins() {
  $plugins = array(
    'access' => array(
      'test' => array(
        'title' => t('Custom access check'),
        'help' => t('This is a custom access plugin'),
        'handler' => 'mymodule_access_plugin',
        'path' => drupal_get_path('module', 'mymodule'),
      ),
    ),
  );
  return $plugins;
}

function mymodule_access($account = NULL) {
  global $user;
  if (!empty($account->uid) && $account->uid == $user->uid) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

Fourth, clear caches and apply your custom access plugin in views


Debugging Imagecache related module I'm trying to create a custom module that builds on top of imagecache and imagecache_actions to dynamically add an overlay to image thumbnails based on fields of the node its attached to.

I used hook_image_default_styles and hook_image_effect_info with a callback to my custom effect function. I have it working under most circumstances, but I have a bug thats causing it to fail under some specific circumstances.

The problem I'm having is that there is no way to debug it. Normally for debugging, I run eclipse with zend debugger to set breakpoints and step through lines of code.

I've set breakpoints for the above functions. Cleared the existing files from the style directory, and loaded the page in the debug mode. All my other breakpoints will get hit, but for some reason its able to generate the image without hitting those breakpoints. I know its being called because (1) the image with overlay is being generated properly, and (2) every once in a while it was hitting the breakpoints - but not consistently, and now, not at all.

Does anyone who is familiar with imagecache know how this might be happening? Maybe it is somehow generating the images in a different php request than the standard page load?

Does anyone who uses a debugger know why this might occur, or has anyone seen this behavior before?

It seems you are connected to page rendering process. Images are created with separate php calls, one for each image. If you want to connect to image generation call, disable retrieving images in your browser, load HTML, get image url with safety token and hit it directly, debugging.


Interface translation of custom fields When I translate field labels via admin/config/regional/translate/translate then my changes are happening in the frontend - but this does not work for fields which I created myself. Those fields are available for translation in the same spot but changes to them have no effect - it always uses the original text.

In my case it's about some additional fields in the registration form. I have de/user/register and fr/user/register and the pre-existing fields are in the correct language and if I do changes to them, then they are applied. But if I provide translations for the fields which I added, then they just don't show up.

I am using Drupal 7.14. On the picture, you see the custom field "wohnort". The first one has been there right after the creation of the custom field; the second one only after the Field Translation module and the i18n pack.

Here is Internationalization pack for building multilingual sites in Drupal: i18n.
To translate field labels you need “Field translation” module from this pack. After you enable it new tab “Translate” appears on field edit page.

Update

That's strange that you can see your field labels on admin/config/regional/translate/translate page, so I started an issue #1672694. I think it's a bug.

Update 2

Fixed since Drupal 7.22


Is `watchdog-show string` broken in 7.56? On a test instance, drush watchdog-show shows, among three other entries, a message starting with "Notice: Undefined property:". However, both of the following commands print nothing at all:

drush watchdog-show "Notice"
drush watchdog-show "Undefined property"

drush watchdog-show ":" does print the message, but also other irrelevant message. So how do I search watchdog messages like it says in the documentation:

  drush watchdog-show "cron run succesful"  Show a listing of most recent 10 messages containing the string "cron run succesful".

?

No. Or maybe yes - broken for all versions of Drush. The problem is that Drush only searches the message column of the watchdog table, not the variables column too. A watchdog entry is built-up by a message - format string - where a variable can be inserted. If the text you are looking for is in the variable part, Drush won't find it.

Yes, this is very annoying. There is a related Drush bug - see https://github.com/drush-ops/drush/issues/408 Maybe you should comment and ask for re-opening?


Disable all notice errors on a drupal 6 site I'm updating a drupal 6 site and getting hit with alot of notice errors. how can i silence these non vital errors. Usually just get undefined index and warning/notice messages

Its not so much a Drupal 6 question, but a PHP question.

In your settings.php file I sometimes do the following on my Drupal 7 sites:

// Drupal Bootstrap is overriding even htaccess values for this. I want the
// notices but not for them to display in production.
ini_set('error_reporting', 'E_ALL ^ E_NOTICE');


VIEWS: How can i Related (CONCATENATE) current_user to content fields? DRUPAL ROCKS!

I need your help! in a website i am currently working with. i have 700 active users with the following users field:
-Name, Sure name, last name, worker number.

And i created a content type called: Turns.With the fields: title, body, full name, turn's date, worker number.

One of the main goals of this website is that in the moment that the user logs in he will have a button that say my turns, and he will just see his "turns".

i need to be able to related in a view, some how, user's worker number with turns (content, node) worker number field in order to show just user "turns".

view=user(work number field) + turns(work number field) and off course display all the turn fields.

any help will be really really appreciated...

love drupal!

You can create a Relation (on the right side), Here you can link to a author. Create a filter that filters on the current loged in user. This should do the trick.