How to limit the list of nodes in a view based on a text field value? Is it possible to show only Views content that passes a text in a given field?

For example, I have 3 content types and each content type has an identifier field (text field) which is hidden to the public.

So on my main content type, which is an information page, I list information about a football team. And then in the second content type I create results and a review of a match. And I display them as a view on the football team page (content type 1).

Content type 1 has a unique identifier, for example a text field saying "barcelona001". And this is the same on the "match results" content type field. How do I let views filter that, so that it only shows the right information?

If I can do this with a text field that would be great since I need to use a lot of taxonomy fields already to make it all work.

Any suggestions?

Create a new view that displays content of all types.
Add your text field to 'Filter Criteria'. It looks something like this...

Content: My Text Field Name (field_my_text_field_name)
Select 'is equal to' and enter 'barcelona001' to the 'Value' field.
Press Apply (twice).
If you have the value already on some contents text field it should now display a list of matching content in the preview.

You would probably also benefit from contextual filters. Remember first to remove the field from 'Filter Criteria' if you added it earlier.

Choose 'Advanced' from the Views settings page. It should now show you 'Contextual Filters' setting.
Add your field.
Click Apply.
You can now write 'barcelona001' in the 'Preview with contextual filters' field.
It should display the result in preview.
See the 'Path' value in the views settings. You can go to that path and put whatever value you have used in the textfield after the path like this .com/my-page/

I hope this helps!


if isset, is there a better way? Currently I'm retrieving values from entityform_wrapper and checking if the field exists (fields aren't required and fail if don't exist)

Is there a better way than going through each field like this?

if (isset()) {
   $edu_completed = $entityform_wrapper->field_education_completed->value();
}
if (isset()) {
   $edu_hs_name = $entityform_wrapper->field_high_school_info->field_edu_hs_name->value();
}
if (isset()) {
   $edu_hs_city = $entityform_wrapper->field_high_school_info->field_edu_hs_city->value();
}

I use a function I've written called ifset for this purpose:

function ifset(&$var, $prefix='', $suffix='', $else = '') {
    return isset($var) && $var ? $prefix.$var.$suffix : $else;
}

It can simply be used like:

$foo = 'test';
echo ifset($foo); // produces test
echo ifset($bar); // produces an empty string

Or you can supply a suffix, prefix or else values:

$foo = 'test';
echo ifset($foo, 'before ', ' after', 'foobar'); // produces before test after
echo ifset($bar, 'before ', ' after', 'foobar'); // produces foobar

So, in your instance you could write:

$edu_completed = ifset($entityform_wrapper->field_education_completed->value());

This is slightly different to your code a $edu_completed will be an empty string instead of not being set at all.


Hide Block on Particular Page with Bootstrap I have a block called 'calendar' that I display on all events pages. events* such as events/today/, events/all/ etc.

A constraint that I have is that the block must be displayed on all events pages but on one particular page. The block must be hidden when the user is using a mobile device.

My thought process was to simply apply the bootstrap 'hidden-xs' class to the block. But the constraint is not satisfied as it would trigger on all the events pages.

What would be the easiest way to implement this?

Thanks in advance.

You can use combination of media query  to achieve this.Using media query hide the block under mobile resolutions . For example

@media screen and (min-width: 480px) {
.block-class {
    display: none;
  }
}


Update aliases through admin or module? I used the blog module for what I am calling "story" on the site I am building.

The URI and various parts of the site still say "BLog" -- most noticeably when the user attempts to add a new blog.

I have figure out I can just override the URI using aliases through admin, but I am wondering if it would make more sense to simply rename the 'blog' references in the table itself, via a module or one time hack?

Opinions?

EDIT | I also want to change the "forum" module to "forums" making all references plural not singular

Pathauto module fits in exactly to serve your requirements.

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


Contextual view -> entity reference target ID I have the following situation:

I have 2 content types (session and preformance)

Performance has an entity reference to session

I want to create a view that shows me all performances for the session that is referenced by the performance i am looking at right now.

So this is a contextual view that filters on the nid of the performance, and has a relation to the session that is referenced by the viewed performance.

I cannot get the target_id of the session (from field_session on content type performance) to be passed in as a contextual filter.

I tried to use %node:field_session, but that gives me the label of the session, and not the target_id.

I also tried to change the display of the performance content type->field_session to 'entity id', but no luck.

All suggestions are very welcome.

You need to add the proper Context to the variant.

Then you complete the setup.

And lastly you select it in the panel settings for the Contextual view:


Why ajax button calls submitForm? I have no problems with using Ajax in every form element other then button. When I'm clicking this button

  '#type' => 'submit',
  '#ajax' => [
    'callback' => '::ajax_function',
    'wrapper' => 'my-button-wrapper',
  ],

it reloads the page ... well it does what would normal submit button do - calls submitForm(). And I don't need that. I need this button only to call ajax_function()

In Drupal, the submitHandler() method of your form definition will always be called UNLESS you have a custom handler attached to the submit button that is clicked. In the case of #ajax buttons, you add your own custom handler, then rebuild the form in that handler.

'#type' => 'submit',
'#ajax' => [
  'callback' => '::ajax_function',
  'wrapper' => 'my-button-wrapper',
],
'#submit' => ['::ajaxButtonSubmit'],

Then:

public function ajaxButtonSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

By doing this, the default submit handler is not called, and your ajax submit handler is called instead, which then ensures the form is rebuilt instead of reloaded.


Need to run cron as authenticated user Hi on my server I need to be running cron as an authenticated user in order for the directories that I need to access during a specific function to be writable.  How can I make cron or at least part of this cron run be run as an authenticated user for drupal 8.  I found some documentation but only for drupal 7 .
thanks

You can run your custom cron methods as an authenticated user as follows:

use Drupal\user\Entity\User;

/**
 * Implements hook_cron().
 */
function my_module_cron() {
  // Login as user 1
  $user = User::load(1);
  user_login_finalize($user);

  // Your custom cron functions

  // Login as user 0 (anonymous)
  $user = User::load(0);
  user_login_finalize($user);
}


How to build an editable view of two entities linked together? I started using drupal recently and i am stuck building an editableview.

In my view i have a table of users with a field of a content type "survey" associated to theim throught an entity reference field that i added to the user account's fields.
i set up a view of user with a relationship to my entity reference field.

I want to edit the field "active" wich is a field of content type "survey"

At the moment i can edit the field but it will set the value for every content.

i wish to edit the value of desired content not for all the content of this content type.Is their a way to achieve the desired result?

You are making a relation and editing a field of the relationed content "Survey", if a "User" is relationed to the same Survey content, will change on all of them.

If it is a different node "Survey" for each "User", it should't change all of them. I just did a test with your conditions and everything is going great. Could you give more information like configuration, multivalued, etc. of  those fields?


Change from address of user registration email How can I update the from address of the email sent when a user successfully registers to the website. Currently the from address is same as the site administrator email id. Instead I would like to set it some custom email id like do-not-reply@example.com.

I looked at the Mail editor module and from the documentation I understand that it can be used only for updating the subject and body of the email and not the from address.

Any thoughts??

There is one e-mail address that is used as From-address for all mails sent automatically by the system.  By default, this is set to the same as the site administrator email.  To change it, do the following:

Navigate to Administration » Configuration » System » Site Information.
Locate the field "E-mail address". Change it to whatever you want it to be.
Press Save configuration.

Note that will also be used as the From-adress for password resets and other generated mail.

If you require fine-tuning beyond this (to distinguish between different types of auto-generated email messages), you need to write a custom module. In that case, you may use hook_mail_alter to alter the From:-address, based upon some criteria (e.g. the subject field.

For avoidance of misunderstanding: The three steps listed above will not change the site administrator email id.  To inspect and change the site administrator email id, click on the  "My account" link while logged in as site admin, and then press the Edit tab to see it. The  site administrator email id is by default the same email id as the From-address used for email sent by the site itself - but they do not need to be the same.


Question about user email activation I noticed that the user table has a column for status. Does 1 status mean the account has been email activated? and is this the only thing distinguishing a activated account and unvalidated account? Also, I want to make a module that will do something when a user email activates his account. I'm guessing this would be the user hook but what op code would I use to detect when a user email activates his account?

When users create an account, and the email verification has been set as required, the value of the "status" field is set to 1 right after the users enter the username they want to adopt and their email address, if users are allowed to create an account without the approval of an administrator user; the "access" and "login" fields will be 0, until the users don't log in, which happens also in the case they follow the link reported in the email message sent to verify the email address they reported for their account.


Should you use multi-site or multiple Drupal instances to host different content for subpath sites? I want to host a Drupal 7 site that effectively has four different silos of information. The architecture will look like this:

example.com - Blog site with content about the parent company
example.com/foo - Informational site about sub-company "foo"
example.com/bar - Informational site about sub-company "bar"
example.com/fubar - Informational site about sub-company "fubar"

The top site will pretty much be a blog with navigational elements directing people to the sub-sites. The three sub-sites will essentially be the same structure, but have slightly different CSS (different color schemes) and have different information. Logins can be separate, because we actually want to be able to peel away one of the subsites to sell as an asset, if need be.

I'm wondering what the best way to do this would be. Multi-site should keep it easy to update, because the modules and core should be upgraded in lockstep. However, I can't seem to get multi-site to work for these subpaths.

Is multi-site the best way to go here? Or should I just host four different instances of Drupal, one for each site?

(Note, I saw a question about subsites just after I posted this, but it seems that subsites is only available for Drupal 6. Please correct me if that is wrong!)

Subsites should work for Drupal 7 as well (assuming this is what you're working with).  I've found these instructions helpful in the past: http://drupal.org/documentation/install/multi-site

If the company subsites you are running are under one parent company where there is one body of management (a common decision maker), then subsites makes sense.  If they are different companies which may want very different functionalities for their sites, then it may not be wise to combine them into subsites which rely on the same code.


How do I show revision users in a view I would like to create a view that shows the title of all newly revised or updated content with the username of who modified it. The first part is easy, but for the life of me, I can't figure out how to show a the username of who updated it as everything shows the original author, not the user who updated the content.

Any ideas on how to accomplish this?

Have you tried creating a relationship?

Sounds like that might give you the data you need, but you'll need to test it out.


How can I override or disable a parent theme's CSS file? I am trying to override the menu.css file in the default Classy theme through my library file. I have read through the documentation, but anything I tried doesn't work.

What would be the correct markup to override or disable this file?

Add this to your theme's .info.yml to override it with css/my-menu.css from your theme:

libraries-override:
  classy/base:
    css:
      component:
        css/components/menu.css: css/my-menu.css

To disable it (don't load it when loading the classy/base library):

libraries-override:
  classy/base:
    css:
      component:
        css/components/menu.css: false

To get the classy/base key you need for the override, find the *.libraries.yml file where the CSS is declared. The part before the slash is the * in that file (e.g. classy.libraries.yml), and the part after is the top-level key in that file under which the CSS is declared.

In most cases I find it easiest to actually copy the library declaration from the libraries file that declares the asset to maintain the 'css', 'component', keys and indentation.

Note that you can do the same thing for JavaScript assets as well.

See https://www.drupal.org/node/2216195#override-extend for more information.


Sharing drupal file to a external site We have a site external to our drupal site, but have to use images from drupal site using absolute URL(No way we upload the same images to that site). So we have to provide them with absolute URLs of the images which will be used by the site.

And it should also be possible that we change the images. i.e., If we have to change the image, we have to replace the existing image with the new image with same name.

What is the best way can this be achieved? Anyhow there is going to be a content in our drupal site that contains the image. Will the image URL be the same ALWAYS when I remove the image and upload another image with same name?

Give File (Field) Paths a try:

The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.
In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.


Way to allow instantiating derived classes I have a class called MyService, a function to get the only instance of it custom_get_my_service(), and multiple functions a,b, etc that call the instance getter, as you can see below.

All of this is packaged into my module. Suppose I give this module to another developer, he can't change the code, but he needs to override some of my class methods, and all the custom_a, custom_b functions have to use his derived class.

How can I modify my custom_get_my_service() function, in a Drupal best practice way, to allow others to instantiate their derived class instead of my own?

class MyService {}

function custom_get_my_service() {
  $service = &drupal_static(__FUNCTION__, NULL);
  if (is_null($service)) {
    $service = new MyService();
  }
  return $service;
}

function custom_a() {
  $service = custom_get_my_service();
  // Do stuff
}

function custom_b() {
  $service = custom_get_my_service();
  // Do stuff
}

You can do it however you like, really; however PHP will let you.

Basically you need to make a decision at some point in custom_get_my_service() about which class you're going to use. Drupal's paradigm is hooks, so a contrived example might be:

function custom_get_my_service() {
  $service = &drupal_static(__FUNCTION__, NULL);
  if (is_null($service)) {
    $service_class = custom_get_service_class();
    $service = new $service_class();
  }
  return $service;
}

function custom_get_service_class() {
  // Default
  $class = 'MyService';

  $modules = module_implements('custom_service_class');
  foreach ($modules as $module) {
    $function = "{$module}_custom_service_class";
    $class = $function();
  }

  return $class;
}

Then another module would implement the hook:

function another_module_custom_service_class() {
  return 'AnotherClass';
}

Obviously that's a very limited example, which will only let one module override the class, has race conditions, no error checking, etc. But that's the basic idea, I'm sure you can extrapolate from there based on what your module is providing.

You could also look at a DI approach, and have modules pass in their implementations of an interface you define into your functions, which then make the necessary use of them. It kind of depends on your level of experience with OO, and your opinions on 'best practice'.


Organic groups automatic audience selection I am working with organic groups. Within each group, permitted users are allowed to create their own pages.

What my problem is that I need to set the audience for a new page automatically as the group the user is currently in.
This is so that the user cannot manually change the group the post should go into but instead it's automatically and permanently set ( unless an administrator changes it ).

Does anyone know of a way that I might accomplish that?

You can use the prepopulate module to pass the group's gid to the node add form.
For example, the link will looks something like this:

node/add/discussion?edit[group_audience][und]=4

You could then hide the group selection box with css so the user cannot change it.
For a more robust solution you would code a form hook. Here is an example.


Granular role access on a per Entity basis I have a config entity that I would like to grant access to on a role based level. There is going to be one role to access the entities, but how can I assign access on a per entity basis?

My naive thinking is to add a $roles array instance variable, and add each individual role to that, then create a custom EntityAccessControlHandler class, implementing EntityAccessControlHandlerInterface that checks the array for all of the users roles, but that doesn't seem like a very good solution.

but that doesn't seem like a very good solution.

Yes, it is.

What you're saying makes perfect sense, just do it :)

access() (or checkAccess()) is called for each entity separately, you can implement any imaginable logic in there, that's completely up to you.


Search node by Image Field and return image as result rather than the node I want to be able to search for a an item in a multiple value field of a node and return the data of that specific value as the result.

I have a content type called 'Gallery'.  'Gallery' contains an image field that allows for unlimited values.  Each value has an alt value that is exposed to Search API.  I have a view using the "Search Views" module to filter the results from Search API.

I can successfully search for any 'Gallery' based on any of the alt tags of any of the images. The necessary data is exposed as fields to my view, such as:
Gallery Photos: The image file. (indexed) |
Gallery Photos » The image file.: File ID (indexed) (File ID (indexed))

but these fields only return data for the first image of that field in the Gallery.

I've searched high and low for a module or hack solution.  No one has seemed to solve this.  This seems like an important feature, because the way things are looking now, I would have to store each image as a separate node to be able to search for it individually.  And that doesn't make sense for a lot of reasons.

Any help or direction would be greatly appreciated.

The problem you are facing is that Search API has a flat structure, so it cannot save multiple values for fields, as it would require a change in data structure which isn't done during indexing, since it will effect the already indexed results.

If you knew how many values you could get (fx max 3), then you could create entity properties that pointed to the values for image 2 and 3. Otherwise this is beyound the scope of what's possible right now with Search API module (at least to my knowledge.


Profile2 , change page title With profile2 all the profile page titles is the profile type.

How do I override it with a field from profile2?

I was wondering something like this

hook_preprocess_page(&$variables){
if ($page-type == profile2) {
$new_title = field_get_items('profile2', $profile, 'field_new_title');

  drupal_set_title($new_title);
}
}

Of course this script does not work.

This needs to happen just on the profile page, not in the profile listing page.

To change the content title (defaults to the username) you can use this snippet in a custom module:

<?php
function MYMODULE_custom_menu_alter(&$items) {
 $items['user/%user']['title callback'] = MYMODULE_user_page_title;
}

function MYMODULE_user_page_title() {

if(arg(0) == 'user') {
// Load uid from url
$user = user_load(arg(1));
// Load profile2 entity
$profile2 = profile2_load_by_user($user->uid);
// Load fields
$myfield = field_get_items('profile2', $profile2['main'], 'field_myfield');
$output = $myfield[0]['safe_value'];
}

// Fallback to username if no fields are present
if(empty($output)) {
   $output = $user->name;
 }

return $output;

}
?>

Reference : http://drupal.org/node/1262070, Change page title on user-profile using a field value from Profile2


Upgrade breaks Rest Export View in Calendar We have a website that uses Views with a serializer rest export to display events on a monthly calendar. When we upgraded from 8.6.16 to 8.7.3 the calendar display is blank. All the json information displays in the view preview, and using console.log I can see the information load on the page. I can load events in a normal view without any issues. I've spent several days trying to figure out what change may have caused this, my leading theory is that something with date formatting may have changed somewhere, but so far, no luck. Does anyone have any documentation about a date format change between Drupal 8.6 and 8.7?

EDIT: I just noticed the difference by exporting the views preview and running a diff on them. The live site displays dates correctly like this "value":"2019-06-27T00:30:00 while the updated dev site displays dates like this "value":"2019-06-26T17:30:00-07:00" so could something have changed with time zone translations or date fields that is interfering with our code?

My edit gave me a clue to look at the date formatting. In our specific calendar instance there is an event-calendar.js file that was manually converting the dates pre-Drupal 8.7 to UTC with a .field_date_range[0].value+'+00:00',. It appears that Drupal 8.7 does this automatically, so removing that extra bit of code solved the issue and dates are being populated into the calendar correctly now.

EDIT: For those interested, I was finally able to find the drupal documentation about this change in 8.7 here


Contact Forms - Change Recipient Address Dynamically - D8 I'm using the core contact forms module in Drupal 8, and what I need to do is add a select with multiple options, each option needing to change the recipient address.

How can I do this using the built-in module, or do I need a different module?

The contact_storage module has a feature that allows you to create a list that include a key, value and e-mail and then the mail is sent to that.

You can either use that, or you can do it yourself in a similar way. You could use a term reference for example and have a field on your terms for the e-mail. The relevant code is in contact_storage_mail_alter():

$contact_message = $message['params']['contact_message'];
foreach ($contact_message->getFields() as $field) {
  if ($field->getFieldDefinition()->getType() === 'contact_storage_options_email') {
    // One of the Option email item fields. Add the recipient to the message.
    foreach ($field as $delta => $item) {
      $label = $item->value;
      // Obtain the email to add to the message, using the label.
      $email = $item->getFieldDefinition()->getSetting('allowed_values')[$label]['emails'];
      $message['to'] .= ',' . $email;
    }
  }
}

}


How do I set access permissions per field? What I need to do

I have some user account fields that should be administrator-only (read/write/edit).  For example, the IP address used to register.

So, I want to restrict access to administrators.

Current state of field permissions in Drupal 8 (as of Feb 19, 2016)

In Drupal 7, I used the Field Permissions module.  However, a Drupal 8 version is not currently being worked on by the maintainers.
There is a discussion on putting field permissions in Core, but this has been going on for seven years and is marked as "postponed."

You're stuck doing this in code, but the Examples module includes a field_permissions example module.


Override a node page using page manager I know it is possible to override node pages using page manager, then use panels to make new layout by selecting a variant type, and  creating a new variant.

Is it possible not to use the Panels mdoule? I would like to use the Context module, and the default theme regions.

Yes it is possible to use only context module to override layout.

When you first add context @ admin/structure/context/add, you need to select condition as "path" and reaction can be whatever you want. For ex. choose reaction as "Regions" and then go ahead disable region for the sleected "path" (the one you chose above in condition).

Just remember context module will use your existing theme layout and regions (.tpl.php files) unlike in panels where it allows you create your own regions and layout.


Call to undefined function making site unavailable After making a Backup/Migrate copy of source site files, the very source site for unknown reason broke down with this error:

  Fatal error: Call to undefined function link_field_property_info_callback() in /sites/all/modules/entity/modules/field.info.inc on line 30

Most probably it comes from references to the Link module.
I have googled around, but the solutions good for others are not for me, as I cannot access admin to un-install the module. Is there anything I could do here without Drush?

I really do not quite understand the origin of that situation, but I would more like to focus on resolving the effect.

You can try to (re)move the faulty module's directory, at least temporarily. It should prevent the call and let you access the necessary admin pages.


How to import / export content type? In Drupal 6 we had content type export import, I cannot find this in Drupal 7.

Any tips please?

I ended up using the Bundle Copy module.


Setting Panels category for blocks and other pre-existing Content Types? When one adds new content to a Panel, they are given a list of categories, each with various Content Types.

Setting the aforementioned category of a Content Type is easy if you're writing your own plugin...

$plugin = array(
  'title' => t('My Plugin'),
  'category' => t('YOUR CATEGORY HERE'),
);

But what about setting that category for Content Types created by other modules?

I ask because I've created a Menu Block and am wanting to put it in a specific category, where all my other custom CTools Panels Content Type plugins reside.

Any thoughts? I'm using D7, by the way. Thanks!

A kinda hacky way of doing it is to hook into hook_ctools_block_info() like so:

/**
 * Implements hook_ctools_block_info().
 *
 * @see ctools_block_content_type_content_types().
 */
function menu_block_ctools_block_info($module, $delta, &$info) {
  if ($info['title'] == 'Sub Menu Menu Block') {
      $info['icon'] = 'icon_core_block_menu.png';
      $info['category'] = t('Page Content');
  }
}

I just dropped this code in a separate module and I'm off to the races. The only problem is if Menu Block decides to implement its own hook_ctools_block_info function (Indeed, I got the above code from a patch that does exactly that), in which case redeclaration errors will show up. I'll leave this question marked as unanswered for the moment; if anyone can think of a better way of accomplishing the above, I'd be happy to accept that answer instead.


Receive error when printing field Hi i've just started building a site on Drupal 7.31 and i'm following my normal procedure i've used loads of times. One of the things I have on most sites is an introduction just beneath the title.

I add an introduction field to the Basic Page content type and in page.tpl.php I print it out using:

<?php
    if (isset($node)) {
      if ($node->type == 'page') {

        print '<h2>';
        print render(field_view_field('node', $node, 'field_introduction', array('label'=>'hidden')));
        print '</h2>';

      }
    }
?>

It's never caused any problems before, on any previous version but for some reason this time round I get this error:

Strict warning: Only variables should be passed by reference in include()

Any ideas why?

render function receives an arguemnt as reference, you should pass a variable instaed of function:

$var = field_view_field('node', $node, 'field_introduction', array('label'=>'hidden'));
print render($var);


How to expand trimmed body text to full body text in the same Views page? I have a view in Drupal 7 where I am showing the node title and its body as trimmed text, as shown in this screenprint:

I need to show full body text after click on the Read more link, but in the same page. How can I do so?

Consider using the Views Accordion module. Here is an excerpt from its project page:

  ... provides a display style plugin for the Views module.
  It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.

  For Drupal 7 the module integrates the jQuery UI Accordion plugin as a views style plugin. You can configure the options provided by the jQuery UI plugin.


Show child pages in parent node view details in a book I'm using the Book module to maintain the parent-child relationship between content. I want to see all child pages expanded when I see a parent node details page.
How can I achieve it?

I tried with THEMENAME_preprocess_book_tree(), but so far I have not been able to achieve that I wanted.
Is this the right hook to use in my case?

I managed to find a solution. I would like to post it here if somebody looking for similar solutions.

Make a view for the parent page with all needed configurations. In my case, I have the main chapter page as the parent, the content type is 'chapter'. And when I see the view in a page I want to see all subchapters coming under it. The further steps are followed:

Browse to /admin/structure/views and click on "Add view".
Enter a view  name, Select content type from view settings
Check the "Create a block" checkbox only. Then click on
"Save & edit".
On the right-hand side, click on "Advanced" so that the advanced
menu appears.
Click on "add" next to "Relationships" to add a relationship.
Select "1st parent" (the parent book node) and click on "Apply and
configure relationships".
Check the "Require this relationship" checkbox and click on "Apply".
Click on "add" next to "Contextual filters" to add a contextual
filter.
Select "ID" (The node ID) and click on "Add and configure contextual
filters". Choose relationship to "Book 1st Parent"
In the "when the filter value is not available" section, select
 "Provide default value" and in the "Type" drop-down menu, select
 "Content ID from URL"
click on "Apply" & Save the view
Place the just created block in the page by visiting structure >
 block layout


Gravatar does not work with anonymous accounts I enabled the avatars_gravatar submodule from Avatar Kit and configured it to be the only available Avatar Generator in admin/config/people/avatars. The Gravatar is rendered for logged in users, but not for anonymous users that leave a comment.

Is this a configuration issue or do I need to alter a template? I'm using the standard Bartik theme.

Unfortunately anonymous accounts arn't supported at this time, because they are a special case. Avatar Kit is currently written to work with Drupal user entities, which anonymous accounts are not.

Follow https://github.com/dpi/avatars/issues/30 for progress


Getting the node id from the node containing an entityform in submit handler I'm using the module EntityForm to build a form. This EntityForm will be an entity reference field in the content type ShowForm. ShowForm contains the form and some other fields that give some information about what the form will be used for.
Once the EntityForm is filled in, they should be redirected to the ShowForm-node that contained it so they can fill it in again (for someone else). There will be different ShowForm-nodes that all have a reference to this EntityForm, but I have to redirect them to the specific ShowForm-node they filled in the form on.

I've added an extra submit button and submit handler that submits the form and redirects them to a ShowForm-node so they can fill it in once more.
The problem is that I can't find a way to redirect them to a ShowForm-node without hardcoding the id (so it's only useable for 1 ShowForm-node).

For example:

$form_state['redirect']='node/123'

where 123 is the nodeid of the node showing the EntityForm. I'd like to be able to get the nodeid dynamically for redirecting instead of manually putting in '123'.

This is my code so far:

function extra_inschrijving_form_alter(&$form, &$form_state, $form_id){

    if ($form_id == 'generiek_inschrijvingsformulier__entityform_edit_form'){
        $form['submit2'] = $form['actions']['submit'];
        $form['submit2']['#value']='Inschrijven en ook een broer inschrijven';
        $form['submit2']['#weight']=100;
        $form['submit2']['#submit'][1]='extra_inschrijving_default_wp_submit';
    }
}

function extra_inschrijving_default_wp_submit($form, &$form_state){
       //Do some stuff

      $node_id=???
      $form_state['redirect']='node/' . $node_id;
}

Is there a way to get the right value for this $node_id? Is it possible?

(I was thinking about adding a hidden field to the EntityForm and using rules to set it with the nodeid of ShowForm when a ShowForm-node is created, but I can't seem to acces the EntityForm's fields in rules even when I use "has field"-conditions)

I've solved it like this:

I've added a hidden field to the EntityForm called parentid and set that value with the id of the ShowForm-node when the node is created. This way I can use this parentid to redirect to the correct ShowForm-node when submitting a form.


Migrate only taxonomy terms from a specific vocabulary When doing a D7->8 migration, my taxonomy term migration template imports all the taxonomy terms found in the source D7 site. How to filter only the terms that belong to a specific vocabulary? For a node, I simply said:

source:
 plugin: d7_node
 node_type: article

But for terms? Is there something similar?

source:
 plugin: d7_taxonomy_term
 ????

Thanks in advance!

source:
  plugin: d7_taxonomy_term
  bundle: tags


Drupal database and SQL I have done lot of things with Drupal 7. Now I have something to do that can't be done with view interface (in my opinion) and I need to ues php and SQL. Now I am testing in view php field.

I have many node types, i.e. students, past_study etc., with many custom fields.

the first problem I faced was the name of table, I though "node type name" i.e. students, past_study should be use in FROM but after lot of hours wasting I discover each filed has its own table so have to open so many table like this

FROM field_data_field_this, field_data_field_that

Now the main problem is with WHERE clause I have student_code in students node type and a reference field s_code_ref field in past_study. I am not sure how to compere student_code in student node type with s_code_ref.

WHERE student_code = s_code_ref

when s_code_ref is a reference entity field in past_study

What I am doing is to adding a field with complicated calculation from the field of two node types and have to add this in a view with various other field from two node types.

my SQL is something like this

<?php
$result = db_query ('
  SELECT SUM((pstd.field_studyDate_value2 - pstd.field_studyDate_value) + (std.field_joiningDate_value - now()))  AS duration
  FROM field_data_field_past_study pstd, field_data_field_student std

  ');

std has single record for each student, and pstd may have 0 or more records for students.
students name, code, etc are being displaying in the view with relationship of two node type.

my problem is that how to refer the student_code in record line displaying in view and then using that in where clause to calculate the sum for that particular student_code.

so I need something like

WHERE pstd.s_code_ref = the student_code of the current row.

besides I want to know if my approach to calculate this way is right or there is other better ways?

in short I have to calculate total past study duration from one node type (past_study) then add duration of current study from another node type (student) and bringing the total study duration in a field for each student in a view.

Any help guidance will be appreciated.

Solved

Finally I solved the problem with following codes

$eid = $row->id; // a variable to store row id
$sql = "SELECT SUM(field_past_std_date_value2 - field_past_std_date_value) as psd, field_std_pin_target_id as tid
FROM field_data_field_pas_std_date d JOIN field_data_field_std_pin p ON d.entity_id = p.entity_id
WHERE field_std_pin_target_id = $eid";

this bring me the total duration of past study of each student listed in my view. Although the problem is solved there may be better way to writer above squl. if anyone can give comments it will be highly appreciated. I'll continue improving my Drupal skills.


How do I make my homepage slideshow to fit the page width? I have my website built in Drupal 6, and I have used the Views slideshow module for the home page banner which is 960 pixel wide. I need a banner with 100% width to fit the page. Can anybody help me in making it to 100% or kindly suggest any full width banner slideshow module which is compatible with Drupal 6?

Is your website wider than 960px ? ... I have you looked at online CSS tutorials such as Full Screen Background Image Pure CSS Code, or CSS3 cover property for background-images as mentioned here. I think the CSS Only Technique #1 is more what your looking for in your slideshow's inline images.

Anyways, Google will help you alot here. Views Slideshow ships with basic useable CSS, but it's not themed for everyones needs. It's up to you to tweak its CSS as you need. As an example I've previously given here -- taking a Views slideshow and using only css + jquery and changing it to meet client needs.

Sorry I dont know of a module that just does all the themeing for you, views slideshow does do 99% of the work for you by providing a workable slideshow for your site.


Add unlimited field collections in a from of drupal I created a form in drupal for creating a new node. This content type has a field collection with 2 fields, name and amount.
I use the code below  in form and add 5 field collections to form, but when submit the form, only the last field collection is saved in $form_state['values] and 4 elements get lost.
How can I add unlimited field collections to a form by programming?

In my form:

module_load_include('inc', 'field_collection', 'field_collection.pages');
$form['cooking_type']['cooking_materials']  = array();
 for ($i=0;$i<5;$i++) {
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_cooking_materials'));
$form['cooking_type']['cooking_materials'][$i] = array();
field_attach_form('field_collection_item', $field_collection_item, $form['cooking_type']['cooking_materials'][$i], $form_state);
}

in submit form:

$material_name= $form_state['values']['field_material_name']['und'][0]['value'];
$material_amount = $form_state['values']['field_material_amount']['und'][0]['value'];

This is a working code that can be placed directly into your form function. Please see the comments too.

$node = new stdClass();
// Replace the value to the content type's machine name where you have added
// the field collection field
$node->type = 'CONTENT_TYPE';

// Prepare the field collection display array
$form['field_collection_display'] = array();

// Get the field collection field's info/structure and return it to the given variable
// w/c in our case is $form['field_collection_display']
field_attach_form('node', $node, $form['field_collection_display'], $form_state, NULL, array(
  'field_name' => 'FIELD_COLLECTION_FIELD_NAME'
));

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

return $form;

For the "Add another item" display, when you go the the field collection's content manage field settings page it says that the button will only display when it's set to 'Unlimited' w/c isn't your requirement. So you would need to add custom validations to this.

Since this is also custom coding, if you're having a hard time manipulating the field I would also recommend looking at doing the "field collection" functionality by yourself. This is the link https://api.drupal.org/api/examples/form_example!form_example.module/group/form_example/7. You could go to the form_example_tutorial_9 directly if you want.


Setting menu trail of subpage of a node I'm trying to have a subpage for a special content type. Everything is working fine, also the breadcrumb is working now.

Only the active menu trail isn't showing up and I really don't know how to hack into the right process. Are there any special functions helping me with this problem?

I tried menu_set_active_trail(), but having problems with nodes placed in a menu by the user where I cannot get the previous menu trail for the node itself.

I hope you can help.Thanks in advanced!

The function you need is menu_tree_set_path.  It will be released with Drupal 7.9.

If you can't wait, the workaround is to use this code in hook_init:

<?php
$item = menu_get_item();
$item['href'] = '<the href of an existing menu link>';
menu_set_item(NULL, $item);
?>


Removing dozens of Routes from a collection I am using a contrib module that is adding a local task to all entities, where I only want it to be added for Nodes.

So far, I have this written to handle the problem in the short term:

/**
 * Implements hook_local_tasks_alter().
 */
function mymodule_local_tasks_alter(&$local_tasks) {
  foreach ($local_tasks as $key => $task) {
    if (preg_match('/access_by_entity/', $key) && $key != 'access_by_entity.entities:node.access_tab') {
      unset($local_tasks[$key]);
    }
  }
}

Is there a better way to do this? Is this performant? I would rather just not have the routes exist at all, except for this one instance.

I think the way you're doing it is fine, although you could probably add a patch to the original module that adds the option of which entities to affect, so that instead of them being added and removed, it would only add them for the entity types you select.

Ah, I see you've already thought of this!


Fatal error: Cannot redeclare MYTHEME_preprocess_user_picture() If I add the following:

      function MYTHEME_preprocess_user_picture(&$variables) {
      $variables['user_picture'] = theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
}

to my comment.tpl.php (the purpose of which is to use an image style on the comment author's picture,) I get a WSOD with the following message:

Fatal error: Cannot redeclare MYTHEME_preprocess_user_picture() (previously declared in /home3/zc1/public_html/sites/all/themes/mytheme/comment.tpl.php:8) in /home3/zc1/public_html/sites/all/themes/mytheme/comment.tpl.php on line 12

Now, I know this error normally indicates a duplicate of the function. But in this case it seems to indicate that the duplication is in the same comment.tpl.php file. And I can't see it.

Here is the file, with the added code included:

<?php ?>
<div class="<?php print $classes . ' ' . $zebra; ?>"<?php print $attributes; ?>>

<?php
  function MYTHEME_preprocess_user_picture(&$variables) {
$variables['user_picture'] = theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
} ?>
<?php print $picture ?>
<?php print $submitted ?>

  <?php print $signature ?>

<div class="content"<?php print $content_attributes; ?>>
<?php if ($new): ?>
  <?php print drupal_ucfirst($new) ?>
<?php endif; ?>
    <?php hide($content['links']); print render($content); ?>
<?php if ($signature): ?>
<?php endif; ?>

<?php print render($content['links']) ?>

Any idea what's going on?

This is Drupal 7 and I use Bartik.

Any and all help is greatly appreciated. Thank you. :)

Change function signature with 'function bartik_preprocess_user_picture(&$variables)' and put this function in template.php. Don't forget to clear the cache.


Create a script page for handling ajax I am a bit confused on the appropriate way to generate a drupal page for handling ajax posts. For example I'm creating a custom module that has favorites buttons. When a user clicks the button the ajax request sends the data to example.com/ajaxscripts/process.php. I need to create a page at process.php to handle the request but it shouldn't generate the full drupal theme. Rather it should just have access to the core drupal information such as $user and drupal database functionality. How can I create such a page? It seems that tying to use hook_menu() would force a full page rendering.

In your hook_menu, create a menu item with 'type' => MENU_CALLBACK, like so:

$items['YOUR_MENU_PATH'] = array(
  'page callback' => 'YOUR_PAGE_CALLBACK',
  ...
  'type' => MENU_CALLBACK,
);

Then, in your page callback function, you can use the drupal_json_output($some_array) function to convert $some_array to json, and return it, all in one go.

I wouldn't use the .php extension in the menu path.


Invoke custom JS function in AJAX callback? Is it possible to invoke a custom JS function in an AJAX callback?

function MY_MODULE_ajax_callback() {
  // Define a new array to hold our AJAX commands.
  $ajax_commands = array();

  // Create a new AJAX command that replaces the #page text with our own text.
  $ajax_commands[] = [CUSTOM JS FUNCTION]

  // Return our commandS
  return array('#type' => 'ajax','#commands' => $commands);
}

Yes, it is.

Code sample:

$commands = array();
$commands[] = array(
    'command' => 'your_js_callback', // the name of your javascript callback
    'value1'  => 'My first value',
    'value2'  => 'My second value',
);

JS Code:

(function($, Drupal) {
    Drupal.ajax.prototype.commands.your_js_callback = function(ajax, response, status) {
        alert(response.value1);
        alert(response.value2);
    }
})(jQuery, Drupal);


Where is list of theme features in Drupal 8 that can be exposed on the "Settings" page? In my theme.info.yml file, I can expose features to show up in the settings of my theme. It's documented here: drupal.org theming

features:
  - comment_user_verification
  - comment_user_picture
  - favicon
  - logo
  - node_user_picture

I tried to google a list of these, but can't find it. Is there some way I can figure out all the options available here, if there's not an explicit list anywhere?

Here is the answer:

http://cgit.drupalcode.org/drupal/tree/core/config/schema/core.data_types.schema.yml#n172

There needs to be documentation for this. Maybe I'll write it.....


ownership drupal directories Would it be safe to say only the files directory should be owned by apache user ?

I have mine set files apache:root

And all other drupal directories root:root ?

My permissions are set to 755 for everything excepting 444 on settings.php

Actually my files I've set to 775 and have
in www chown -R root:apache html

then chown -R apache:root files

It would be safe with all folders being in 0775 and settings.php in 444.
However, if you would use FTP/SFTP to edit either the themes or any module files You may need to login with the "Owner" user, which may or may not be possible in a shared hosting environment.

So., depending on that you may choose. However, if you use SSh it will be not an issue.


Webform (*) instead of required word I have a situation I want to put (*) instead of "required" word inside the place holder of a webform field is it possible from webform admin.

You can add this (*) in field label with field name or can use with style also.


Adding an extra class to the last element of the navigation/tree menu For one of my projects, I have to create a tree menu, with parents and children, that would be used to navigate through the website. The parents are collapsible. Below is the twig file that I am using to generate the menu:

{% macro menu_links(menu_tree, route_tid, current_depth, max_depth, collapsible) %}
{% import _self as macros %}
{% for item in menu_tree %}
  {%
    set liClass = [
      item.subitem and current_depth < max_depth ? 'menu-item menu-item--expanded block-taxonomymenu__menu-item block-taxonomymenu__menu-item--expanded' : 'menu-item block-taxonomymenu__menu-item',
      route_tid == item.tid ? 'menu-item--active block-taxonomymenu__menu-item--active' : ''
    ]
  %}

    {% if item.image %}

    {% endif %}

      {{ item.name }}{% if item.show_count == true %} [{{ item.nodes|length }}]{% endif %}

    {% if item.subitem and current_depth < max_depth %}
      {% if item.interactive_parent %}

      {% endif %}
      {% if collapsible == TRUE %}

      {% else %}

      {% endif %}
        {{ macros.menu_links(item.subitem, route_tid, current_depth + 1, max_depth, collapsible) }}

    {% endif %}

{% endfor %}

{% endmacro %}

I wanted to know if it was possible to add an extra class to the last li class of the tree menu? I have actually tried to add current_depth == max_depth ? 'item--last': '' in the setliClass and {% if
     current_depth == max_depth %}item--last{% endif %}" in the li class="{{ liClass|join(' ') }}" part, but this is not working.

You should be able to apply an additional loop to iterate by specific menu_level. Here is an example of a twig template that iterates over menu level variable:
How to add classes to menu items in navigation twig template

Then use a condition to set the class within the for loop such as:

loop.last ? 'last'

See all the variables associated with for loops in twig here:
https://twig.symfony.com/doc/2.x/tags/for.html


How can I display a view title with 'No Results Behaviour'? Using Drupal V 7.34 and Views 7.x.38

On the front page I have a view that lists news articles based on publish date being in the last 2 weeks. This works fine.

What I am now wanting is to insert a new view to pull images from Flickr when there are no news articles to show.

So, I created a new view for the Flickr feed, and adjusted the paging as I wanted. I set up the No Results Behaviour to show my new view in the Global View Area.

This works, but the title of the view is not displayed.

How can I show the title of the NRB view?

Many thanks

i believe this is your problem

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

solution is here

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

If you have a view and you want to be able to programmatically change the title of, you can do it by implementing hook_views_pre_render in your custom module:
alter it when particular view or field is not having any result

<?php
function mymodule_views_pre_render(&$view) {
  if ($view->name == 'my_view_name' && $view->current_display == 'my_display_id') {
    // Here you can do any php you want to get the title you need for your view.
    $view->build_info['title'] = "My custom title!";
  }
}
?>

If you are altering the query and you have argument substitutions affecting the title, you can change these in hook_views_query_alter:

<?php
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view_name' && $view->current_display == 'my_display_id') {
      // First substitution - you may want !1 or %2, etc
      $view->build_info['substitutions']['%1'] = $new_substitution;
    }
}
?>

Views Displayed as Pages

Use this:

drupal_set_title('My custom title!');

Instead of:

$view->build_info['title'] = "My custom title!";

or some thing like this in views 3

<?php
/**
 * Implements hook_views_pre_view().
 */
function MODULENAME_views_pre_render($view) {
  if ($view->name == 'my_view_name') {
    if ($view->current_display == 'my_display_name') {
      $view->set_title('my new title');
    }
  }
}
?>


Automating webforms? I am making a website for a museum that involves a questionnaire. I made this questionnaire with the webforms module, which in turn sends the answers to another page to be processed. The people at the museum do not know drupal, let alone php. So when they want to add questions to the questionnaire, it has to be done by me. This is because I also need to change the values that are passed on the next page (via the redirect URL in the webforms module).

To automate the process for them (they probably know enough to be able to add new questions), I wanted to know if there is any way to pass on all the answers from the webforms questions, so that they do not have to fiddle with the php? This way, all answers will be sent, regardless of the questions on the webforms. The page that receives the values has been coded so that it takes any amount of URL-parameters; You do not have to find a way to do that.

You could use the Rules module and the Webform Rules integration module to redirect to a generated URL.

You could create a rule that loops over the results building a custom URL string pointing to your processor script, and then redirect to that URL.

As long as the string is less than about 2000 characters you should be in good shape.

You may want to look into the Form API as this would be much cleaner and possibly simpler with a custom submit handler.

Form API Quick Start Guide
Form API Reference Sheet

If I misunderstood your question I would be happy to try again if you'll clarify.


What is the best way to add a confirmation tooltip to the remove button of a managed_file field? Another Update

I'm trying to implement the solution found here: Intercept click event on a button, ask for confirmation, then proceed, but the remove button still submits normally. I know my JS is targeting the correct element, because I can change other attributes on it like the background color.

Here's my form:

function form_experiments_01() {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'form_experiments') . '/js/form_experiments.js',
  );

  $form['managed_files'] = array(
    '#type' => 'fieldset',
    '#title' => t('Managed Files'),
  );

  $num_docs = 3;
  for ($i = 1; $i <= $num_docs; $i++) {
    $form['managed_files'][$i] = array(
      '#type' => 'managed_file',
      '#title' => 'Managed File ' . $i,
    );
  }

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

  return $form;
}

Here's my javascript:

(function ($) {
  Drupal.behaviors.managedFileAutoUpload = {
    attach: function(context, settings) {
      $('.form-item input.form-submit[value=Upload]', context).hide();
      $('.form-item input.form-file', context).change(function() {
        $parent = $(this).closest('.form-item');

        //setTimeout to allow for validation
        //would prefer an event, but there isn't one
        setTimeout(function() {
          if(!$('.error', $parent).length) {
            $('input.form-submit[value=Upload]', $parent).mousedown();
          }
        }, 100);
      });
    }
  };

  Drupal.behaviors.managedFileConfirmRemove = {
    attach: function(context, settings) {
      var myButton = $('.form-item input.form-submit[value=Remove]', context);

      if (myButton.length > 0) {
        var myClick = null;

        //get a list of jQuery handlers bound to the click event
        var jQueryHandlers = myButton.data('events').click;

        console.log(jQueryHandlers);

        //grab the first jquery function bound to this event
        $.each(jQueryHandlers,function(i,f) {
          myClick = f.handler;
          return false;
        });

        //unbind the original
        myButton.unbind('click');

        //bind the modified one
        myButton.click(function(){
          if(window.confirm("Are You Sure?")){
            myClick();
          } else {
            return false;
          }
        });
      }
    }
  }
})(jQuery);

Update

After some more research I found this question. This is what I was trying to ask but didn't know how to word.

Intercept click event on a button, ask for confirmation, then proceed

I'll implement this solution and post a resolution once I've got it working.

Description

I would like to add a confirmation tooltip when the "remove" button is clicked on my managed_file field.

I would like to do something similar to this:

What is the best way to do that?

Possible Solution?

So far, I'm thinking I could probably use javascript to hide the remove button and instead display my own button. Then when my button is clicked, I can trigger a popup that contains a second custom button to cancel and the remove button that I originally hid.

I'm worried that this solution is a bit messy. Is there a more elegant way to do this? Can I get a similar behavior without hiding the original remove button?

Similar Questions

I'm not sure if these apply to my use-case since I'm working with a managed_file field. So far, I've been unable to implement similar solutions without the default behavior of the remove button interfering.

Confirm delete via AJAX
enter link description here

Resources

Bootstrap-Confirmation.js
Drupal Form API Reference - managed_file

Use this code to delay submit and display popup before submitting.

$("form").submit( function () {
   //display tooltip something
   return true;
 }

Something like this:

$('.form-item input.form-submit[value=Remove]').submit {
  if (window.confirm("Are You Sure?")) {
    myClick();
  } else {
    return false;
  }
}


how to correctly use curl command line with Services module? I try to use following command to create an user:

$ curl -H 'Content-type: application/json'  -d '{"name":"u10", "pass": "123","mail": "user@a.om"}' http://localhost/test/api/user/register

return success:

{"uid":"11","uri":"http://drupal/daxuebao/api/user/11"}

But I try to login:

$ curl -H 'Content-type: application/json'  -d '{"username":"u10", "password": "123","mail": "user@a.om"}' http://localhost/test/api/user/login

It alert me :

["Wrong username or password."]

So, How to correctly use curl command line?

You need to send only username and password. Mail is not required.. Please check the documentation here...

$base_url = 'http://localhost/test_endpoint';
$data = array(
  'username' => 'admin',
  'password' => 'password',
);
$data = http_build_query($data, '', '&');
$headers = array();
$options = array(
  'headers' => array(
    'Accept' => 'application/json',
  ),
  'method' => 'POST',
  'data' => $data
);
$response = drupal_http_request($base_url . '/user/login', $options);
$data = json_decode($response->data);
// Check if login was successful
if ($response->code == 200) {
  // Now recycle the login cookie we recieved in the first request
  $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
  // Get info about a user
  $data = array();
  $options['data'] = http_build_query($data, '', '&');
  $options['method'] = 'GET';
  $response = drupal_http_request($base_url . '/user/32', $options);
}

Below one worked for me

curl -H 'Content-type: application/json'  -d '{"username":"admin", "password": "admin"}' http://localhost/d7/testendpoint/user/login

In your case it should be

curl -H 'Content-type: application/json'  -d '{"username":"u10", "password": "123"}' http://localhost/test/api/user/login


unset the path for the library used by FullCalendar I am using FullCalendar module to display some events. I had to modify the design of the calendar and the only solution was to alter the way javascript of fullcalendar displays events and so . Now i do not want that at an update of the fullcalendar, all the changes i have made to dissapear.My question is how can i unset the path of the current fullcalendar library and set the path to my own customized library ?

When you update a module what ever changes you have done would automatically be over written. if you have just made changes to js then it would be better to add that JS to your theme rather than the module itself.

You could you the hook_js_alter (On Drupal 7) or jsalter (On Drupal 6) in yout theme to remove the module specific js.


Preventing FlexiSlider (Adaptive) to resize beyond a certain minimum height I am using Flexi-Slider and AIS to create a responsive (full-width in this case) Images Slider for a front page on a Drupal 7 install.

I got it working perfectly but I would like to restrict the resizing function when the images reach a certain size. Meaning for example, if the height = 500px, even if the device screen size or resolution is smaller than that, or the user resizes the browser window, I don't want the image to get smaller than that.

Is that at all possible? Anyone has done it or could guide me into it? Thank you everyone for your time.

I hope my auto-reponses to the last 3 or 4 questions I posted, serve to the rest :)

Just wrap the block where your flexislider slide views is contained in a div and give it a min-width with !important and set the height to "auto".

Have not tested this in IE yet tho. Let's see.


Adding a clickable area to the logo At my Drupal 7.4 website with the default Bartik theme and no contributed modules, I have a big logo (715 x 280 px) and no slogan. These are my settings:

I'm trying to figure out the best way to add a sponsored link to the rectangle orange area (with the white example text "Plastikovie okna !!") at the screenshot below:

If a tilted rectangle isn't possible, I can live with a straight rectangle too.

If there is a CSS/JS solution, it is welcome too, but please tell me which CSS and JavaScript files to edit, so that the solution works at every page of my site.

When you add a logo this way, the entire image is a link back to the homepage.    The only answer I can think of is to place a link over the image.   using css the link will be

Float over the image using margin, position, etc
Text indent -9999px;
z-index higher than the logo img
pad the link to be the size of the image

I would probably custom code this in page.tpl.php, however it looks like you are looking for a non-custom code solution.   To do this create a new custom block, with the link being its content (remember to have a input filter that will take  HTML tags).   Move this block into header region.


How to show filtered content as suggestion of "reference autocomplete field" based on a field value of reference content Say, one content type is "CONCEPT" and it has a field named 'STATUS'.
Another content type is "Article" and it has a node-reference auto-complete field named 'CONCEPT FROM'.

Now I want to see only "CONCEPT" contents whose status value is "ACCEPTED" as a suggestion of "CONCEPT FROM" auto-complete field.

Thanks @shawn-conn
His answer is perfect but I can't give vote because of minimum reputation. See following solution in details:

Step 1:
First create one entity reference view
Note: In this view include referenced content type (e.g.: CONCEPT) and it's filter/condition field (e.g.: STATUS)

Step 2:
From MANAGE FIELDS of the required content type (e.g.: PROJECT), Add field that FIELD TYPE will be Entity Reference and WIDGET will be autocomplete then click on the SAVE button.

Step 3:
Now choose Views: Filter by an entity reference view option in MODE field and choose your views that is created in Step 1 in View used to select the entities field from ENTITY SELECTION section of the field settings page.

Step 4:
Click on the Save settings button to save changes.


How to load modal form on page load using ctools? I have an issue to show modal form on page load. This form will have 3 steps to submit. I've found CTools will suit the best. I'm newbie in drupal, that's why I've looked all tutorials ctools. Every example article tells how to show modal form by clicking on link. But I can't find any examples, how to load my modal form not clicking on link. I want to call it through AJAX after the page loads, but I don't know how.

Please, give me some advices.

This post I wrote a while back deals with CTools AJAX events at any time. It involves writing your own Javascript handler and executing it on page load.

    Drupal.CTools.AJAX.refreshElements = function() {
  var url = '/mymodule/ajax/refresh-elements';

  try {
    $.ajax({
      type: "POST",
      url: url,
      data: { 'js': 1, 'ctools_ajax': 1},
      global: true,
      success: Drupal.CTools.AJAX.respond,
      error: function(xhr) {
        Drupal.CTools.AJAX.handleErrors(xhr, url);
      },
      complete: function() {
      },
      dataType: 'json'
    });
  }
  catch (err) {
    alert('An error occurred while attempting to process ' + url);
    return false;
  }

  return false;
};
$(document).ready(Drupal.CTools.AJAX.refreshElements);

Set the URL to the callback URL of your module.  The last line tells the ajax to happen on page load but this could be replaced to happen in response to the exact event you need it to.


How to allow any file extension (or use a blacklist instead of a whitelist) for file fields in Drupal 8? For a file field, it’s required to enter file extensions in "Allowed file extensions".

Is there a way to allow any file extension? Or a way to switch from a whitelist to a blacklist?

What I found

For Drupal 7, there is the module Allow All File Extensions. A Drupal 8 port doesn’t seem to be planned.
For Drupal 7, there is the question How to allow for files of any extension to be uploaded?, where the module mentioned above is recommended.
For Drupal 8, there is the issue Not possible to allow uploading files with any file extension, but it seems to be inactive.

Implement a hook alter on the node form or the field level and  in it change the validator to your custom function:

/**
 * alter form field element:.
 *
 * Implements hook_FORM_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
    $upload_validators = array(
        'my_module_file_validate_extensions_blacklist' => ['jpg jpeg gif png mp4']
    );
    $form['your_file_field_element']['#upload_validators'] = $upload_validators;

}

Alternatively you can change the behavior of the field on any node, or entity by altering the widget form:

function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
   if ( "condition to check if it's your field" == TRUE) {
     $upload_validators = array(
            'my_module_file_validate_extensions_blacklist' => ['jpg jpeg gif png mp4']
        );
        $element['#upload_validators'] = $upload_validators;
  }
}

Then write you own function to do what you want:

function my_module_file_validate_extensions_blacklist(stdClass $file, $extensions) {
  $errors = array();
  $regex = '/\\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  if (preg_match($regex, $file->filename)) {
    $errors[] = t('files with the following extensions are not allowed: %files-allowed.', array(
      '%files-allowed' => $extensions,
    ));
  }
  return $errors
}


What is the D7 equivalent of CCK "content_instance_tablename" in db_query? I am porting a D6 module to D7 which deals with controlling field access of CCK fields. I can now successfully enable my port without any errors but receive a fatal error when trying to create new content.

The issue is the the "content_table_instance" in db_query which as far as I understand no longer exists in D7 due to the CCK --> Fields move. I am having a lot of trouble finding exactly what the alternative of "content_table_instance" is in D7. Any suggestions?

Here is the section of the code:

$result = db_query("SELECT nfi.field_name, nfi.label
  FROM {" . content_instance_tablename() . "} nfi
    INNER JOIN {" . content_field_tablename() . "} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = '%s' AND nf.active = 1 AND nf.locked = 0", $type_name);

Both functions in your code (content_field_tablename() and content_instance_tablename()) just return a string based on the version number of the CCK module.

The Drupal 7 equivalents would be the field_config and field_config_instance tables respectively, as defined in field_schema.

Remember fields can be attached to any entity in Drupal 7 (not just nodes) so you'll need to change your code accordingly.

If you're using this query to get information about the field metadata you might want to use one of the Field Info API functions instead, e.g.

$all_field_instance_data = field_info_instances();

or

$single_field_instance_data = field_info_instance('node', 'field_some_field', 'article');


Entities and Plugins. What's the relationship? As a fairly experienced Drupal 7 developer, I'm thrilled by all the new goodies in Drupal 8, but haven't quite figured out the relationship between entities and the new plugin system.

I've followed a number of tutorials on both topics, but haven't come across how they would fit together? Do they fit together?

I'd be very grateful for an explanation of how these two features coexist and inter-operate within the Drupal 8 ecosystem.

Thanks!

Edit:

My specific use case

To clarify my question: I'm building a module that provides a method for the site owner to display alerts to their visitors. I've created a new custom Content Entity (cleverly called 'Alert') using Drupal Console and custom code.

I've also followed along with several tutorials that describe how to create a custom plugin type and found this idea exciting, but the gap in my understanding is this: when (or if) there would be a use case for combining a custom Content Entity with a custom plugin type. Does anyone have an example?

Thanks!

I am not sure that I quite get your question but in Drupal 8 things like nodes, files and users are entities. They all inherit from ContentEntityBase. Plugins are a way to implement/extend Drupal functionality such as Views filters and Field widgets.

From the docs:

Entity API

  Drupal 7 - entities were generic stdClass objects.

  Drupal 8 - entities are now specifically typed objects, with each entity type defining a class that will be used for instances of the given entity.

  Entity types in core comes in two variants.

  Configuration Entity

  Used by the Configuration System. Supports translations and can provide custom defaults for installations.

  Content Entity

  Consist of configurable and base fields, can have revisions and support translations.

Plugin API

  Plugins are small pieces of functionality that are swappable. Plugins
  that perform similar functionality are of the same plugin type.

  Drupal contains many different plugins, of different types. For
  example, 'Field widget' is a plugin type, and each different field
  widget type is a plugin. The admin user may select from the list of
  field widget plugins to set the widget that a field uses.

After author edit:

Your specific use case would call for a event subscriber approach in my opninion. More specifically an event subscribed to the KernelEvents::REQUEST event. You can check at every page request if there are open Alert entities for the user and display them accordingly.

Your question as to if there are use cases for combined entities and plugins I wouldn't know. I only ever created Views and Block plugins and never combined entities and plugins. Perhaps you could create a Block plugin and show your Alert entities in there?


Providing translations for custom modules I'ld like to provide module specific translations for my custom modules.
I followed the instructions in https://api.drupal.org/api/drupal/core!modules!locale!locale.api.php/group/interface_translation_properties/8.

But if I install the module no translations get imported.
I've searched a lot for examples on the net, but it seems as no one else used it until now.

Here's my module "custom_module"

custom_module.info.yml:

name: 'Custom module'
version: '8.x-1.0'
core: 8.x
project: 'custom_module'
datestamp: 1434014760
interface translation project: custom_module
interface translation server pattern: modules/custom/custom_module/custom_module-%version-%language.po

and a "custom_module-8.x-1.0.de.po"-file with some messages in the module folder.

I had a similar problem that it didn't work but it turned out that my problem was with file permissions that weren't set correctly on the PO file I was trying to import.

I debugged it as follows:

On the following url admin/reports/translations you can see where it looks and what it looks for. (handy for debugging the tokens) Expand the status information for the available language.

Every time you change your info.yml file don't forget to rebuild cache and trigger the translation update manually.


Way To Search Content I am new to Drupal and am currently trying to edit some pages on a site I inherited. The site does not seem well-organized as there is a panoply of URL redirects and aliases. As a result, I am having a difficult time finding the right pages to edit.

Is there a way to just search for the path and have it return the right content to edit? Perhaps there is a module for that?

As an example, I have a page www.example.com/donate which needs to be edited. When I look under aliases and URL redirects, "donate" returns nothing. How can I go about finding this particular page?

Not all Drupal paths end with a content (or node) page. For example, the D7 core Contact module has the path /contact, but in order to "edit" it you need to change administration pages within the admin section (/admin...) or a theme template if you're wanting to change how the HTML is rendered.

The closest thing to what you're looking for is the menu_router (D7) or router (D8) database table. These DB tables contain static/dynamic paths (the path column) with additional metadata about what/how these paths rendered. They should help you discover what controls paths that aren't node or node alias paths.


Entity Reference create problem with REST server using Services i'm building a web services and now i'm writing the documentation for the mobile developer.

When i want to create/modify an entity reference Services 3 ask a stucture like this

"field_organization": {
    "und":[{
        "target_id":"Organization name (69)"
    }]
  }

for a field like this

but, there is another way to give only the nid without the node title? It could be more handy.

I read something like

"field_organization":[{
     "target_id":{
                "target_id":"[nid:69]"
          }
   }]

or like

   "field_organization": {
       "und":[{
             "target_id":{
                 "target_id":"[nid:69]"
               }
           }]
     }

on the official documentation but it didn't work.

Can someone know a method to give only the nid of a Entity reference field?

I found the solution!
The required data structure depends on the input widget, since Services uses the form submit handlers (which may be a major design flaw).
For "Autocomplete/Tagging" the label (id) thingy is necessary. But if you switch to checkboxes it reads "field_reference": { 1:1, 2:2,  ... ,nid:nid} and for select box "field_reference": [1,2,3 ... nid].

The REST-API depends on the widgets the frontend uses ... but at least it works. I guess its upside is that REST-posts are validated just as normal form inputs are. I'll also have a look at the approach implemented http://drupal.org/project/restws


Automatically rotate image on upload I did a Drupal site with a field gallery using nodes as albums containing multiple images.. i am using MultiUpload module to upload whole folders at one time instead of 1 image at the time like the standard image module provides. Most pictures are 1024x768 , but the photographer has also some vertical pictures 768x1024 , and when they are uploaded Drupal automatically takes the tall 768x1024 and rotates them to 1024x768 .. i just want them to be shown tall if they are tall ..

Thank you

If you want to autorotate images based on their EXIF information, you can use the Autorotate submodule provided by Imagecache Actions.

Enable the Autorotate submodule and then add an Autorotate image action to each of your image styles.  This will automatically rotate the images and hopefully give you the results that you expect.

Note that this submodule requires the Exif PHP extension to be enabled.


Path to inline image  inside page.tpl.php to theme/images/ dir? Simply  pasted to page.tpl.php doesn't work. It doesn't find the image and requires full path.

I know I've seen somewhere some PHP code which sets full path to image inside the theme's dir.

The following code will get you the path to your theme, together with your site's base path:

<?php print base_path() . path_to_theme(); ?>

Meaning that you should use something like this:

<img src="<?php print base_path() . path_to_theme(); ?>/images/your-image.jpg">

Note: the path_to_theme() will not have the trailing slash, so you have to add it yourself if your image is in a subfolder.


Automatically importing module-provided translations during installation I have a custom module whose interface strings have all been written in English. This module is not (and will not be) hosted on drupal.org, so I'd like to pack the translations for those texts directly with the module, and for those translations to be automatically imported by Drupal when the module is installed (provided the corresponding language is activated in Drupal, of course).

I've translated those texts in French and exported all those translations in a my_module-fr.po file. I've put this file in the "translations" folder inside my module folder.

As suggested in this answer, I used the interface translation properties in the my_module.info.yml, as follows:

'interface translation project': my_module
'interface translation server pattern': modules/custom/my_module/translations/my_module-%language.po

But when I install my module from scratch, those translations are not automatically imported.

In admin/reports/translations, it says "Missing translations for one project - my_module (1). File not found at modules/custom/my_module/translations/my_module-fr.po".

I've tried several variations for the interface translation server pattern value in the info.yml file, among them:

path relative to the module folder (translations/my_module-%language.po) instead of the Drupal folder
full path to the drupal install folder (since I'm on localhost and Drupal is in a subfolder) (_tests/drupal8/www/modules/custom/my_module/translations/my_module-%language.po)

But I always get the same "file not found" message in the admin report page, and nothing is imported.

What am I missing?

Side question: in the YML declaration above, is it allowed to use a path pattern relative to the module folder, as listed above? This would make a lot more sense to me, as I cannot predict whether the people will install my module in the "modules/contrib" folder, or in another subfolder, or directly in the "modules" folder (and if they install it from the Drupal UI, they may not even know it themselves).

Per the documentation:
https://api.drupal.org/api/drupal/core%21modules%21locale%21locale.api.php/group/interface_translation_properties/8.4.x

  Streamwrappers can be used in the server pattern definition. The interface translations directory (Configuration > Media > File system) can be addressed using the "translations://" streamwrapper. But also other streamwrappers can be used.

There are several examples given for valid server pattern definitions using different stream wrappers.

EDIT

I see what you mean about not wanting to use the translations:// stream wrapper.

Have you tried using the pattern definition exactly as given in the answer you cited?

modules/custom/example_module/translations/%language.po

If you do that, you should also take the name of your module out and just name the file fr.po.

Then make sure that you update translations with Drush:

drush locale-check && drush locale-update && drush cr

If that doesn't work, hopefully someone else can help, because I'm stumped.


How can render a Block on a Contact form Page I want to render a Block on a special content type page and on the contact form page. All works fine, but i didn`t found any way to print the Block also on the contact form page.

i use in the page.tpl.php:

if(isset($node) && $node->type === 'page') {
   ....
}

Hope someone can help! Thx

Following the logic exactly as you have laid it out, you could test for

if (arg(0) == 'contact')

to output the block on the contact page. However, is there a reason you're not using the block admin page to place this block instead? Other options here that might be easier to maintain would be:

place the block in the region you want using the Context module
copy the page.tpl.php file from your theme to page--contact.tpl.php and add your block content there


Attempt to create a field body that does not exist on entity type node I am getting the following error:

  Drupal\Core\Field\FieldException: Attempt to create a field body that
  does not exist on entity type node. in
  Drupal\field\Entity\FieldConfig->getFieldStorageDefinition() (line 286
  of core/modules/field/src/Entity/FieldConfig.php).

Context is that I recently switched from one branch to another and did some config imports.

My guess is that this is related to a field.storage issue? What precisely would be causing this error? I'd provide more information about my content types, but I really don't know at this point where it can be narrowed down to.

I'm not finding any real sources on this particular error.

You attempted to create a field using configuration without creating the field storage configuration.

In the field configuration YAML you can see a field_storage property. That is the id of the field storage configuration that needs to also be imported.


what's inside the includes folder? I made a pretty dumb mistake..I was copying a library called ZendGdata to the includes folder within drupal and thought I copied all the files wrong so I deleted the folder and recopied the sub folder I wanted.  Right after, I got a white screen of death.

I did a bit of research and realized the problem and restored the files from the orginal drupa install, but I'm wondering if there's any problem with it(the site works right now).  Is there any customized code or anything of that nature in the the /includes folder that will effect me later?

No, the /includes does not (if you haven't hacked core) contain anything personalized. That folder contains code that doesn't belong to a (core) module.

The correct place for libraries is sites/all/libraries, see http://drupal.org/project/libraries.


Can't access global user object after drupal_bootstrap I have a stand-alone php script with the following lines at the beginning:

define('DRUPAL_ROOT', '../../../../../');

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

And this is giving me access to all of Drupal's functions just fine, however, when I try to access the global user object, it's as if the user is not logged in (IE the user object says the user is anonymous and has a UID of 0), even though I know they are because when I browse the site normally, the user is logged in.

Why does it not pick up the user's session in my script?

The solution was a one line fix:

define('DRUPAL_ROOT', '../../../../../');
$base_url = 'http://' . $_SERVER['HTTP_HOST'];
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Note the addition of $base_url


Services module: What is 'Index' operation? D7 / Services 3.2

retrieve / create / update / delete are very straightforward, make senses to me that matching 'CRUD', I don't understand what 'index' here does?

Thanks.

'Index' in services module will list out an entity(node, users, taxonomy..)  in descending Order of its created time, vid, name etc based on the arguments that are passed. The common arguments for the Index are

page  - Page number of results to return (in pages of 20).
fields - The fields you want returned.
parameters - An array containing fields and values used to build a sql WHERE clause indicating items to retrieve. (array)
pagesize - number of items to be returned. (Integer)

In case of retrieve, it returns the complete entity object of the passed 'entity_id'

UPDATED:

Sample URLS for Index is

http://domain/endpoint/node?fields=nid,vid&parameters[nid]=7&parameters[uid]=1&page=2
http://domain/endpoint/taxonomy_term?fields=tid,name&parameters[tid]=7&parameters[vid]=1
http://domain/endpoint/user?fields=uid,name,mail&parameters[uid]=1
http://domain/endpoint/node?pagesize=3

For documentation you can see Services: An API for remote applications.


Sending Email verification when registering programmatically I have created multi-step form through custom module. I am using user_save() function to register the user and user_mail_notify() to send the email.

Now I am not sure what should I send in _user_mail_notify() so email verification link will work.

I have account settings in the backend as shown in screenshot

and sending op value as 'register_no_approval_required' in _user_mail_notify() function. I am receiving verification email in inbox but when I click it then it doesn't work.

However it works when we register through default registration form. Please let me know if anything I am missing to add.

When you create a new account using "user_save()", What status you passed "0" or "1", If you required email verification then it should be 'status' => 0, in user_save().


How to set attribute for checkbox field I want to add the attribute data-toggle="toggle" to a checkbox field.

I thought I could use the hook theme_checkbox which is:

function theme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}

So I customised it to:

function mytheme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }

  //*******Added 3 lines below*******
  if ($element['#attributes']['id'] = 'edit-profile-carer-field-profile-active-und') {
      element_set_attributes($element, array('#attributes' => 'data-toggle="toggle"'));
  }

  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}

However, instead of just adding the attribute data-toggle="toggle" to the checkbox field  with the id edit-profile-carer-field-profile-active-und, it is adding the attribute to all the checkboxes on the form.

Can someone tell me what I am doing wrong? How can I target just the the checkbox I want? Or do I need to use another approach to do it?

I'd recommend you do this via a form alter.  But that aside, the reason your code doesn't work is that you're not doing your comparison correctly.

if ($element['#attributes']['id'] = 'edit-profile-carer-field-profile-active-und') {

Should be:

if ($element['#attributes']['id'] == 'edit-profile-carer-field-profile-active-und') {

And you're also not setting the attribute correctly.  So the final function should be:

function mytheme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }

  //*******Added 3 lines below*******
  if ($element['#attributes']['id'] == 'edit-profile-carer-field-profile-active-und') {
      $element['#attributes']['data-toggle'] = 'toggle';
  }

  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}


How to pass views link as a variable to a node? I have had a custom tables and I need them to view using Views in Drupal 7 module and it works.

In the Views module we can output fields as a link and redirect to the page what we need and I did this.

My question: when that link is clicked by the user, I need the link name to go to the specific node that I want as variable and being accessed by that node.

Is that possible in Drupal 7?

Have a look at the Rules Link module to generate a custom link that can trigger a rule (from the Rules module). So that via the Rules module you can then implement your logic about the "specific node and that variable" that you mentioned in your question.

Some more details about the Rules Link module (from its project page):

  This module lets you create links which trigger arbitrary functionality with the help of Rules.

  Features

  Attach the link to any entities.
  Show the link only for certain bundles.
  Narrow the entities on which the link will be shown using the visibility conditions.
  The links are usually displayed using Views.
  For entities that can be displayed, the links can be shown on node view.
  Supports an arbitrary number of additional Rules parameters for passing context via Views.
  3 types of links: Javascript, Normal and Confirmation form links.
  Use individual permissions for each link.


How to create global pattern for terms title (not page title)? I'm trying to override the titles of taxonomy terms. Not the page title, the heading tag at the top of the taxonomy term page.

I found the Taxonomy Title module that created to control the title individually for every term.

  This module was designed to update the heading tag at the top of the
  taxonomy term page. The contents of this H1 (or sometimes H2) tag are
  extremely important for SEO (Search Engine Optimization).

This module seems good but it doesn't give us the option to set global patterns for taxonomy terms, we can only set titles individually for each term.

There is an issue opened about global pattern but there is no solution presented.

How can I create global patterns for taxonomy terms?

Example (from the issue):

A real estate company is listing its offerings and each property is tagged with location.

Then for the location vocabulary I could set a pattern "Properties in the [term] area".

Note 1: the Page Title module doesn't give us the opportunity I wanted but we can set global patterns for page title with that module.

Note 2: It's possible to set global title pattern with the Automatic Nodetitles module for only nodes. I wonder if it is possible to use this kind of module (or piece of code) to set global pattern for taxonomy terms.

As I said above (in the question), there isn't any module for overriding the H1 heading (title).

I could do this as explained here:

I copied (and pasted) the page.tpl.php into my theme folder.
I renamed it page--vocabulary--[machine name].tpl.php

(for me it was: page--vocabulary--cities.tpl.php
Opened the template.php file in the theme folder. And added this function:

(I've already had the preprocess_page function in the template.php file and I didn't add the preprocess_page function again, I added the if (arg(0) ... part. Don't forget to change the THEME to your theme name.)

function THEME_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));
    $vars['theme_hook_suggestions'][] = 'page__vocabulary__' . $term->vocabulary_machine_name;
  }
}

Opened the page--vocabulary--cities.tpl.php file and found that line:

(Your theme's template.php file may be different but the main structure is the same.)

<?php if ($title): ?>
<?php print $title; ?> CUSTOM TEXT
 <?php endif; ?>

Cleared all caches.

Done! It works :)

(Note: This solution is per vocabulary solution and if you've got a large amount of vocabularies this solution maybe not very for you.)


hook_menu() item never reached? I have a module where hook_menu() was already used to process ajax calls, like this:

function bizaudit_menu() {
  return [
    'bizaudit/ajax' => [
      'page callback'     => '_bizaudit_ajax_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
    'bizaudit/autoexec' => [
      'page callback'     => '_bizaudit_autoexec_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
  ];
}

That works pretty well from times, then I just added another item, now to handle some precise route, like this:

function bizaudit_menu() {
  return [
    'bizaudit/ajax' => [
      'page callback'     => '_bizaudit_ajax_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
    'bizaudit/autoexec' => [
      'page callback'     => '_bizaudit_autoexec_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
    'navigate' => [
      'page callback'     => '_bizaudit_navigate_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
  ];
}

But this route seems to be never recognized!
To be sure I changed the callback function like this:

function _bizaudit_navigate_handle() {
  $query_params = drupal_get_query_parameters();
  echo implode('<br>', print_r($query_params, true));
  exit;
}

Using this url 127.0.0.1/apim/navigate should cause the query params to be printed (here empty, but no matter), and nothing else to happen.
Instead I get the normal content of the involved page displayed!
(I didn't omit to clear the cache)

Maybe I'm missing someting obvious?

I think I see your problem

hook_menu is for defining your own page paths in code. It's not for hooking into the processing of a page that already exists. So you've got a conflict where you have 2 pages with the same url and the latter (the node/view page or whatever is it with the same url) is taking precedence over your bizaudit_menu definition. So your code created path is never triggered as Drupal has found another route for your "apim/navigate" path


Overriding views default templates I'm trying to override default views templates using _theme_process_registry() function.
It's ok, but i've got some trouble when administrator trying to redefine output via views_ui interface. When he creates a new template, he obviously starts from default views templates (views/theme folder), so my templates is lost.

I'm trying to do so:

$theme_path = drupal_get_path('module', 'mymodule') . '/theme/default_templates';

/**
 * List all plugins trying to find overriden in our work directory
 */
foreach($plugins as $group_name => $plugins_group) {
    foreach ($plugins_group as $plugin_name => $plugin) {
        if (isset($plugin['theme']) && file_exists($theme_path . '/' .  strtr($plugin['theme'], '_', '-') . '.tpl.php')) {
            $plugins[$group_name][$plugin_name]['theme path'] = $theme_path;
        }
    }
}

but single field template doesn't work, coz its hardcoded in view_plugin_display.inc

// Field templates aren't registered the normal way...and they're always
// this one, anyhow.
$output .= '<pre>' . check_plain(file_get_contents(drupal_get_path('module', 'views') . '/theme/views-view-field.tpl.php')) . '</pre>';

Is anybody know how to fully override views templates to my own module directory?

And the second. I need to create more semantic markup like on  dev.twitter.com.

How to redefine classes_array to get rid of extra classes and div elements?

I'm using drupal 7 and views 3.

Are the templates that are overriding your templates included in a Theme? Themes always take precedence over modules, so any template in a theme will always override the corresponding template from a module. You may want to consider re-phrasing your question to reference the original issue you are solving with your template files.

If you are referring specifically to Views output with your desire to create semantic markup, I would suggest the Semantic Views module.