Cannot import database. An error occuring in wamp server I am using Drupal.  I export the sql database from the wamp server and make a new database where I am importing it.  It's approx 6 MB. I increase the upload_max_size and clear the cache before exporting, but this error is occurring. Then what I do

SQL query:

INSERT INTO cache_menu (cid, data, expire, created, serialized) VALUES ('links:management:tree-data:en:.......

To make this on-topic on a Drupal Answers, you should have asked: How do I migrate a Drupal configuration from a WAMP server?

I'll pretend you did that, and suggest you take a close look at the Backup and Migrate module.

It knows about Drupal-specific stuff (such as what tables are not worth migrating), and is also very simple to use.


How to use more than 2 versions on jquery? I want to use bootstrap theme and it requires jquery 1.9, but when I set 1.9, ajax enabled views do not work. I am using views 3.14. There are few contrib modules which require older version of jquery. So in jquery_update I can set "default drupal" for admin pages and 1.7 for the site.

How to get 1.9 as well for my site with no conflicts?

I have found jquery multi module during search, but do not know if it is what I am looking for.

Secondly, Can I use this module with jquery update enabled?

Since you need to run multiple versions of jQuery for different contrib modules I would say the jQuery multi module would be the easiest solution (although I don't know the specifics of your requirements).

The 7.x-2.x branch of jQuery update is supported with jQuery multi.

For example, you could use Drupal default jQuery for admin pages, jQuery 1.7 for non-admin pages and jQuery 1.9 for the specific plugins/modules that require it.
Or alternatively you can use 1.9 as the main version and 1.7 for specific plugins/modules.
Whichever works best for your site.

Usage instructions for the jQuery multi module can be found in its README.txt file when you download it.


Why xmlsitemap module implements hook_node_comment_delete this way? Does someone know why xmlsitemap.module implements every hook_node_comment_ hooks, with a StdClass casting for the object passed in param ?
example :

/**
 * Implements hook_comment_delete().
 */
function xmlsitemap_node_comment_delete(stdClass $comment) {
  xmlsitemap_node_comment_update($comment);
}

(xmlsitemap_node.module l.95)

A teammate overrides some Drupal default comment behaviours by declaring a new entity, with CustomComment as "entity class" name.

Then, when we want to delete a comment, this xmlsitemap's casting fires an error because the loaded comment is not anymore a StdClass object, but a CustomComment object.

Do I have to hack that module ?
Any Idea ?

It seems like the author of that function might just have been a tiny bit over-zealous in trying to strongly-type the $comment parameter.

The hook_comment_delete() docs don't really give any indication that it should be implemented in this manner; but if you look at the signature for the Drupal 8 version of the function, you'll see the parameters are typed. It might be that the author was following that 'pattern' when creating the function (rightly or wrongly). That's a complete guess though.

I haven't seen hook parameters being typed like this in any other contrib modules that I can think of, so it's probably an isolated incident (although this format is consistent across most of the hooks for the xmlsitemap node module).

I think the best way forward would be to create a patch that fixes the issue, and perhaps submit it to the XmlSitemap issue queue for others to review.


Convert a date with format (2017-05-27) to save in node created field I've been looking around for a little while for what I thought would be a simple question to answer but I cannot seem to find the answer.

The question is: How can I convert a date with the format 2017-05-27 into a Drupal safe format for saving into the database?

I have looked inside Drupal\datetime\DateTimeComputed but I'm not sure that is the right place. Any help would be appreciated.

The node created field is a Timestamp Field. Use the php function strtotime() to convert the string to a Unix timestamp:

$timestamp = strtotime('2017-05-27');

and store the value in the created field:

$node->created->value = $timestamp;

You can also use the method setCreatedTime():

$node->setCreatedTime($timestamp);


How to post node tags using REST API? There is no problem with a node creation with filled in title/body/custom text field fields using REST API. We just need to send a post request with the following body:

{
  "_links": {
    "type": {
          "href": "http://localhost/drupal/rest/type/node/page"
    }
  },
  "title": {"value": "Does it work?"},
  "body": {"value": "node body"},
  "field_test": {"value":"hello"}
}

Where "field_test" is a plant text field.

But how to create a node with filled in tags field?

I've tried to post a node using the following post request body:

{
  "_links": {
    "type": {
          "href": "http://localhost/drupal/rest/type/node/page"
    }
  },
  "title": {"value": "Does it work?"},
  "body": {"value": "node body"},
  "field_tags": {"value":"tag1"}
}

It creates the node, but without tags ("field_tabgs") value.
Any help?

They are relations, so firstly you need to create the tags with the taxonomy REST service.

/taxonomy/term

You must take into account they are entities ( node and taxonomy_term ) and the field_tags field only stores the reference to the entity taxonomy_term.

Once you have created it, you will have to add the tags in the following way in your node definition.

Don't forget change the term_id ( in my case 1 ) and the uuid :

{
  "_links": {
    "type": {
      "href": "http://localhost/drupal/rest/type/node/page"
     }
  },
  "title": {"value": "Does it work?"},
  "body": {"value": "node body"},
  "_embedded": {
    "http://localhost/drupal/rest/relation/node/page/field_tags":
      [
        {
          "_links": {
          "self": {
            "href": "http://localhost/drupal/taxonomy/term/1?_format=hal_json"
          },
          "type": {
            "href": "http://localhost/drupal/rest/type/taxonomy_term/tags"
          }
        },
        "uuid": [
          {
            "value": "ff61ea71-2540-47fe-a4bb-384b12d4de47"
          }
        ],
       "lang": "en"
      }
    ]
  }
}

More information in the following link.


Add #theme_wrapper after drupal_render() is called I have a render array:

$element = array(
   '#theme' => 'custom_theme_func',
);

drupal_render($element);

I have a preprocess function in which I'd like to add theme wrappers to this render array:

function my_module_custom_theme_func(&$element)
{
    $element['theme_wrappers'] = array('some_theme_func');
}

The problem that I'm running into is that some_theme_func() is not being called.  If I add it to the list of theme wrappers before I call drupal_render(), however, it works.

There are two errors in your code:

If you use '#theme' => 'custom_theme_func' to reference the theme function, Drupal will look for theme_custom_theme_func(), not my_module_custom_theme_func().
The argument a theme function gets is always $variables, an array that in your case probably contains $variables['element'].
What exactly that array contains depends from the definition given in the implementation of hook_theme(). For example, theme_status_report() is defined as:

'status_report' => array(
  'render element' => 'requirements',
  'file' => 'system.admin.inc',
),

The array it gets contains $variables['requirements'].

theme_image() is defined as:

'image' => array(
  'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
),

The array it gets can contain $variables['path'], $variables['width'], $variables['height'], $variables['alt'], $variables['title'], and $variables['attributes'].

As for setting #theme_wrappers, setting them in the theme function doesn't have any effect, as the theme function doesn't receive the $variables array as reference; therefore, it cannot change its content, and pass those changes back to drupal_render().

As zdecibel said, you can use the preprocess function to set the theme wrappers, even if it is probably better to define them directly in the code you shown at the beginning (the first 3 lines), as you are not dynamically changing the theme wrappers. (At least, that is what you shown in your code.)


Why I've got Fatal error of undefined validation function in my form? I get the error in below code, it is strange, why it occurred?

In hook_menu

$items['share/%'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ym_alter_sharing_content'),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);

and:

function ym_alter_sharing_content($form, $form_state) {
  module_load_include('inc', 'node', 'node.pages');
  $nid=arg(1);
  $form = node_add('share');

  //$form['field_nid']['und'][0]['value']['#value']=$nid;
  //$form['#submit'][]='ym_alter_sharing_submit';
  //form_load_include($form_state, 'inc', 'node', 'node.pages');
  return $form;
}

but it return me:

  Fatal error: Call to undefined function node_form_validate()

Where is the problem?

Change page callback form drupal_get_form to function, because if you use drupal_get_form in call back it return form and in your function you create another form, it means form in form and make conflict.

$items['share/%'] = array(
    'page callback' => 'ym_alter_sharing_content',
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);


How to select multiple values from a list block and perform search? I am a newbie to Drupal.

I have created a block that contains tags of the important topics on my website so how do I insert a search option for the user so that he can select multiple tags from that block and perform the search operation.

Assuming it's a view, you have to do a couple of things after constructing the view.

Click on the Filter Criteria as seen in the screenshot below:

Click on Expose this filter, Grouped filters and Allow multiple selections in this order (they will only appear if you click in this order). Please see the screenshot below:


Removing the breadcrumb from frontpage I'd like to remove the breadcrumb from the frontpage and haven't been able to find a solution in the configuration settings of the theme or custom breadcrumbs. So I am thinking of modifying the page.tpl.php

Do you see a problem with this?

Replace:

<?php print $breadcrumb; ?>

With:

<?php if ($_GET["q"] == variable_get("site_frontpage",
"node")){}
else if ($breadcrumb) {print $breadcrumb;} ?>

You don't have to do it the hard way. There is a variable (bool) $is_front that you can use in this case.

<?php if (!$is_front && $breadcrumb) {
  print $breadcrumb;
}
?>

You can read more about page.tpl.php variables here.


Preprocess view does not work? I have a very basic problem:
I installed the views module and created a view...and of course the develop module.
But why does

function bartik_preprocess_views_view(&$vars)
{
  dpm('hi');

}

Not givimg me HI in template.php ? If i write that into the bartik_process_page() it works...

Add a page display with an URL for your specific view, then on that page it will work and please don't forget to clear the drupal cache.


Why is my site's homepage loading in static mode? I am using the AdvAgg  module and all of its submodules, configured it using the configuration in AdvAgg README file.

After doing so, the site's mobile view got problem. So I disabled all from AdvAgg one by one to see what really caused the problem but haven't found one. Note that I was clearing my cache every time when I edited or did something. I then tried to totally uninstall eveything, including CSS and JS files from AdvAgg. But when I went to homepage there's no style at all. I checked the other pages but it looks normal to me. Also mobile view is back to normal.

I checked the source code for homepage and it is using an old CSS file which is produced by AdvAgg (sites/default/files/advagg_css/.css, which BTW is just a shortcut name for the css file since it is very long). That directory doesn't exist anymore since I already uninstalled AdvAgg. I enabled and configured AdvAgg again hoping everything will go back to normal but homepage still no style. My conclusion is homepage is loading in static mode.

Homepage was assigned to a certain page so I edited it but nothing's change in homepage. I decided to just copy the style from other pages, rename it to the one used by homepage and then upload it through ftp to the same location pointed by home's css.

Now, the site is back to normal but it is loading in static mode. How am I suppose to change it? Is there anything I've done wrong? I also have an error in status report regarding AdvAgg's HTTP request for js files not getting though. By the way, this is the site www.growplants.org. It is supposed to be the same with this page www.growplants.org/grow-plants as it is assigned to homepage.

I was able to solved this problem by updating drupal core to latest version. If you were able to encounter problem like this and you have the latest version of drupal try to downgrade it to replace corrupted core files and update it again to latest version. I don't know what really caused the problem but this will solve the problem. Just run drush pm-update in your drush and it will update all modules and drupal core latest releases. If you only want to update drupal core run drush up drupal. If you want to downgrade drupal add the version drush up drupal-7.x.


How can I alter variables sent to a paragraph bundle template within a module? I need to preprocess the field values of a paragraph bundle to "send" additional variables
to the template (paragraphs-item--xxxx--full.tpl.php). I want to avoid putting too much php logic into the paragraph template.

I am searching for something similiar to the node_view hook for a paragraph item. Is there a fitting mechanism or maybee a module providing such an hook?

Drupal 7

I don't know if this will help you directly, but I found this code snippet on DropBucket and it helped me do something similar:

/**
 * Implements hook_preprocess_entity().
 */
function wwvs_slices_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    $edge = field_get_items('paragraphs_item', $variables['paragraphs_item'], 'field_edge');
    if ($edge && $edge[0]['value']) {
      $variables['classes_array'][] = 'slice--edge';
    }
  }
}

In my usecase I wanted to augment the paragraph entity with an ID using the url-safe version of the title field used in that paragraph. Here's my implementation:

/**
 * Implements hook_preprocess_entity().
 */
function foo_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    if(isset($variables['elements']['pp_title']['#items'][0]['value'])){
      $title = $variables['elements']['pp_title']['#items'][0]['value'];
      $title = strtolower(drupal_clean_css_identifier($title));
      $variables['attributes_array']['id'] = $title;
    }
  }
}

I hope this is helpful!


Best way to add Vcard to node I have a content type with CCK fields that make up contact information.  I was asked to add a VCard / Add to outlook feature.

I have a few ideas on how to do this but not sure which one is good.  My only actionable idea at the moment is to edit a template file for where it is displayed and create the vCard link within there.  However, I also use these in views and I'm not sure if that would translate to the view (I think not)

Is there such a thing as a field that is totally generated? For instance, I could add a vcard field that would then take you to the generated vCard?

I know that there is a module for this but it seems to only work with user profiles.

Like you said, there is a vcard module for user profiles, but there is also a vcard module for cck fields; you might want to try the module on a local test site, and check if there isn't any issue, as the usage statistics of this module is very low.


Restrict content to a user role in a template file I want to restrict a single node to anonymous users in Drupal 8. I don't want to use any module for it as its useless for single restriction as per me.

I know that I can do it with something like this.

{% if user.hasPermission('myPermission') %}
     //my template HTML
{% else %}
    //some login for the customer
{% endif %}

I don't want to restrict the content via permission, instead I want to restrict it with something like

{% if user.hasRole('authenticated') %}

Is this possible with a theme hook or do I have to use a module?

To check in twig if the user is authenticated you can use the default variable logged_in:

{% if logged_in %}

The user is authenticated".

{% endif %}

This works because the user module provides the variable in preprocess for all templates:

/**
 * Implements hook_template_preprocess_default_variables_alter().
 *
 * @see user_user_login()
 * @see user_user_logout()
 */
function user_template_preprocess_default_variables_alter(&$variables) {
  $user = \Drupal::currentUser();

  $variables['user'] = clone $user;
  // Remove password and session IDs, since themes should not need nor see them.
  unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);

  $variables['is_admin'] = $user->hasPermission('access administration pages');
  $variables['logged_in'] = $user->isAuthenticated();
}

Generic roles

If you want to check a generic role, you can't use hasRole(), because this method is not available for accounts. You would have to use getRoles() and check if the role is in the returned array:

{% if 'example_role' in user.getroles  %}

The user has the role "example_role".

{% endif %}


Get a list of all the blocks I need an array of all blocks in the site

For example, if I display the array, it should output the block info or block titles e.g Search, User etc

Try this piece of code from a similar question

global $theme;
$all_regions = system_region_list($theme);
$blocks = array();
foreach (array_keys($all_regions) as $region) {
  $blocks += block_list($region);
}


What's wrong with the way I use variables in my function? I have a function that looks like this:

function mymodule_privatemsg_message_validate($message) {
  $uid = $vars['message']->author->uid;

  //if root or help user, message should always go through regardless of length
  if ($uid !== '1') {
    if ($uid !== '3') {

      if (empty($message->thread_id) && strlen($message->body) < 200 ) {
    form_set_error('[body][value]', t('My custom message.'));
      }
    }
  }
}

However, I received a comment that "As side note, you are using $vars, but that variable has not been initialized from the function, nor is a function's parameter."  I don't understand what this means or what I'm doing wrong.  Could someone explain this to me?

For a variable to be available in the scope of a function, it needs to have been initialised (or it needs to have been initialised in the global scope and imported into the local function using global).

At the moment there's nothing declaring or passing the $vars variable in...it hasn't been initialised, thus you get the warning.

You're passing a variable to the function called $message, which suggests your code should be:

$uid = $message->author->uid;

The confusion with $vars/$variables might be caused by the fact that it's sort of the standard name for the only argument passed to theme functions, e.g.

function MYTHEME_preprocess_node(&$vars) {
  // Use $vars


Create a node on user account creation. Display link to user on first login I need to capture addtional private information about a users company
when they register (one time).

What i am currently doing.

Creating new node on account creation with rules.
Add a view that filters by node author, and display it on the users profile, with a edit link.
The user can then edit the node that he is the author to on his profile page.

This works

I want to display a link or auto redirect to the node once the user has logged in for the first time.

Been busy with this for a long time. Any advice or Pointers.

Assuming you are using Drupal 7, I'd advice you not to do this.

Drupal users are now entities and field-able.

In Admin > Configuration > People > Manage Fields tab, you can add new fields to the profile. With Profile2 module, you can have even more control over these fields (this will become a new entity type, with option to have separate tab in user edit page, etc).

If you are using Drupal 6, while being prepared to upgrade your site to Drupal 7 or 8 in near future, you can use Content Profile module to do this.

Also, if you need to automate these data/fields with user registration, give a try to Rules module.

Profile2 and Content Profile, as well as core profiles have Views support so you can show these profile fields in user with a 1:1 relationship (if you create a new node without binding it to the user, how do you find the correct node from pool ?).


Add Artwork to pushtape Player I want to add artwork song cover(image) to pushtape player.

This will be shown in the current playing song inside pushtape player block.

The image will be loaded from Image Field in the content type field_image

The module showing the current node title in the block and the module work in soundmanager2 library.

The player uses JS to load the current track title into the pushtape player block based on the audio link for the current track. Basically all the script does is take the inner HTML of the original audio link and copies it to the global player block in .pt-current-track-title. Anything between the audio's link tag will show up as the current track title.

Track title

So what you could do is find whatever is generating the .pt-link link markup and add a small img tag next to the track title and upon playback it would get copied to the global pushtape control block when it is the current track.

  Track title

You might want to add some additional span markup to make it easier to style.

Also if you want to learn more, check out the pushtape-player.js github page for more details about how the script works. The Drupal module is basically just a wrapper for it.


Setting base_url in a multidomain setup? I have functionality that relies on having $base_url set in the settings.php file, but I have a multidomain site in order to keep languages separate.

The sections of my site are www.mysite.com and www.de.mysite.com. If I set base_url to "www.mysite.com" I get German language content on www.mysite.com.

How do I set the base_url for a multi-domain, multi-lingual setup so that things like my image style generation can work correctly?

This is a single install, not multisite.

I guess you need separate settings.php file for each site.
You can create special folder for each domain in your sites directory and set custom $base_url in each settings.php file.

.
+-- all
¦   +-- modules
¦   +-- README.txt
¦   L-- themes
+-- default
¦   +-- default.settings.php
¦   +-- files
¦   L-- settings.php
L-- de.mysite.com
    L-- settings.php
L-- ru.mysite.com
    L-- settings.php

Documentation about site folders: http://drupalcode.org/project/drupal.git/blob/c5d6e6334fb7a71ecf1dbc7e06a7de8ad9547b27:/sites/default/default.settings.php#l25


How do I pass an object from javascript to PHP? I set up a hook_menu like this:

$items['fleet/construct'] = array(
  'page callback' => 'construct_fleet',
  'type' => MENU_CALLBACK,
  'access arguments' => array('access content'),
);

Then I set up a js file with this:

$.post({
  url: '/fleet/construct/',
  data: {new_ships: [1,2,3,4], destroyed_ships: [5,6,7,8]},
  success: finalizeFleetResponse
});

How do I access the data from inside my menu callback function?

You are using a POST, it is the same way you, use

$new_ships = $_POST['new_ships'];
$destroyed_ships = $_POST['destroyed_ships'];

Read more on php POST.


Is it possible to dynamically select between two different template files for the same content type? We are rolling out changes on a content type with a new theme and field structures for existing content.
Is it possible to dynamically select one of two template files for a content type?
For example, if a field on the content type is checked then use node--product.html.twig but otherwise use node--product-old.html.twig.

Yes. You can implement hook_theme_suggestions_HOOK_alter() to set up different templates based on the field.
In your case, you want to add templates for nodes, so the theme hook is node. As such, you would implement the following:
function hook_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $node = $variables['node'];
  if ($node->hasField('some_field') && $node->some_field->value == 1) {
    $suggestions[] = 'node__product';
  }
}

With this code, when some_field does not exist, or does not have a value of 1, the default node.html.twig template will be used, and when some_field has a value of 1, the template node--product.html.twig will be used. Adjust accordingly.


How to auto purge old unapproved comments? I would like to know if there is any way to automatically purge old unapproved comments on cron run.

The requirement is -- I have turned on email notification on new comments. I would like to approve only the genuine comments and leave the rest for auto-delete on passing certain time.

Of course I already have mollom, captcha and http:BL to fight spam.

I'm not sure if there is a module which does that. However, you could do that with the help of some custom coding inside hook_cron:

function MODULE_cron() {
  // Find out the comment ids of the comments that are unpublished
  // and are older than 30 days.
  $comments = db_query('SELECT cid FROM {comment} WHERE status = :status AND created < :created', array(':status' => 1, ':created' => strtotime('today - 30days')))->fetchAll();
  $cids = array();
  foreach($comments as $comment) {
    $cids[] = $comment->cid;
  }
  comment_delete_multiple($cids);
}

You can change the time to fit your requirements. This will ensure that on cron run the comments which are older than 30 days and are still unpublished get deleted.


How to increase meta tag description field to 320 characters? We are using metatag v8.x-1.5 on our D8 site (v8.5.3). When filling out the metatag description field, we enter any where from 180-320 characters into the field. However, when the page is displayed it is cutting off after 135 characters.

How can we increase the number of characters that are displayed?

Steps to reproduce:

Enter "Compellingly re-engineer bleeding-edge interfaces whereas interoperable quality vectors. Uniquely incubate one-to-one action items before best-of-breed catalysts for change. Interactively." into the Metatag Description field.

Current behavior:

<meta name="description" content="Compellingly re-engineer bleeding-edge interfaces whereas interoperable quality vectors">

Expected behavior:

<meta name="description" content="Compellingly re-engineer bleeding-edge interfaces whereas interoperable quality vectors. Uniquely incubate one-to-one action items before best-of-breed catalysts for change. Interactively.">

I had to write a hook_page_attachments_alter for this

function mymodule_page_attachments_alter(array &$page) {
  foreach($page['#attached']['html_head] as &$html_head) {
    if($html_head[1] == 'description') {
      $html_head_content = $html_head[0]['#attributes']['content'];
      if(Unicode::strlen($html_head_content) > 320) {
        $html_head[0]['#attributes']['content'] = Unicode::truncate($html_head_content, 320);
      }
    }
  }
}


How do I alter the path of an uploaded image/file such that it includes the path of the node I attach it to via an image field? I added an Image Field to my Node content type. Now, when I upload an image "image1.jpg" that is attached to a node mysite.com/note/123, I want the uploaded image's path to be mysite.com/node/123/image1.jpg. How do I achieve this? I've tried to change the subfolder of the image with a token. I used the token [current-page:path], but that doesn't return the node where I'm attaching to, but the last page that was visited. (Which might be the node edit form or something completely different with ajax, say)

Seems you are looking for a File (Field) Paths module:

The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.
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.

Be aware that it's not yet stable. Test intensively before using in production environment. On the other hand, I don't know anything better and I know for a fact it may work all right.


product variation switcher Hy Drupal Masters!

My question is about commerce module.
I managed to do the followings:

create taxonomies (for creating menu and categorizing products - type - , AND for classifying products in other context - package)
create product types
create the appropiate content types to product types
creating product variations(variations based on 2 fields in content types: "type" and "package" )

For example
I have 3 menu-category with products: prod1(products of category: prod1-1, prod1-2, prod1-3), prod2(prod2-1, prod2-2, prod2-3), prod3(prod3-1, prod3-2, prod3-3)

Each product in one category has 3 variation: small, medium, large
At the moment, if I click one of the categories, the product list appear with the good products, and each product has only one variation.
(eg. I click prod1, I'll see the products, like: prod1-1small, prod1-2small, prod1-3small)

How I expected...but:

I wold like to place a selector(select list or checkboxes, I don't mind) to the top of the product list under each category that is containing small, medium, large elements. Than if I select "medium", the product list needed to change according to the selection.(I would like to see the: prod1-1medium, prod1-2medium, prod1-3medium)

In a product details page I could do this, but in a product list page, I couldn't.

I am using drupal 7

Please somebody help me!

I have a solution for this.

First: I have just created one product type, with the field 'somethingTermReference'(term reference), wich will be the base of the production switcher.

Second: I created content types for every product category, for displaying them. Each content type has a type field with distinct values.

Third: I created views for every product category and there are 3 filter criterias for each view: published content, content type(actual product category), and one exposed filter on a product reference 'somethingTermReference' field.


Cant make postal code only required I am using the adress field module and like to make only the postal code field required.
The rest of the fields i like to hide.

The hiding of the fields are no problem however i am having problems with making only the postalcode field required.
I can hide the whole field with:

<?php
 function my_form_user_profile_form_alter(&$form, $form_state,  $form_id) {

  if ($form_id == 'user_profile_form') {

  $form['field_adress']['und'][0]['#required'] = TRUE;
      }
    }
      ?>

but then this is not working

$form['field_adress']['und'][0]['locality_block']['postal_code']['#required'] = TRUE;

What am i missing?
Without succes i have tried solutions as:
In here
and here

You can make the address field not-required and write a custom validate function to check for the postal code. Like this:

<?php
function my_form_user_profile_form_alter(&$form, $form_state,  $form_id) {
  if ($form_id == 'user_profile_form') {
      $form['field_adress']['und'][0]['#required'] = FALSE;
      array_unshift($form['#validate'], '_my_postal_validate');
  }
}

function _my_postal_validate(&$form, &$form_state) {
    if (strlen($form_state['values']['field_adress']['und'][0]['postal_code']) < 2) {
        form_set_error('field_address', t('You must enter a postal code'));
    }
}
?>

See form_set_error to set better form errors.

If you support non US addresses (without a postal code), make sure the postal_code is available or you'll get warnings.


how to add the value of a (list text) field as a class I have a CT on which I have a field called monetary-type which is of type List (text) and its "Allowed values list" is:

EUR|Euros
USD|Dollars
GBP|Pounds

When this field is rendered from a view (FORMAT: Show: Fields) it's being rendered as:

  Dollars

When rendered from a node view it shows as:

  Dollars

For both those 2 cases I'd like to also have a class with the selected value, in this case value-USD, appended into the classnames of the wrapper.

What is the easiest (non intrusive) way I can achieve this? Ideally without having to touch existing views or node displays.

I use https://www.drupal.org/project/zurb_foundation if it matters.

For view field, please implements template_preprocess_views_view_fields()

Reference: https://www.drupal.org/node/1407442#comment-6509858

Code Example

// assume the field name is 'field_text' and
// view name is 'text and view display id is 'page'
function mymodule_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'test' && $view->current_display == 'page') {
    foreach ($variables['fields'] as $id => $object) {
      if ($id == 'field_text') {
        $field_output = $view->style_plugin->get_field($view->row_index, $id);

        if (!empty($field_output)) {
          if ($object->element_type) {
            $class = '';
            if ($object->handler->options['element_default_classes']) {
              $class = 'field-content';
            }

            if ($classes = $object->handler->element_classes($view->row_index)) {
              if ($class) {
                $class .= ' ';
              }
              $class .=  $classes;
            }

            $class .=  ' ' . drupal_html_class("value-$field_output");

            $pre = '<' . $object->element_type;
            if ($class) {
              $pre .= ' class="' . $class . '"';
            }
            $field_output = $pre . '>' . $field_output . '</' . $object->element_type . '>';
          }
        }
        $variables['fields'][$id]->content = $field_output;
      }
    }
  }
}

For node field, please implements template_preprocess_field()

Code Example

// Assume the field name is 'field_text'
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];
  if ($element['#field_name'] === 'field_text') {
    $value = $element['#items'][0]['value'];
    $variables['classes_array'][] = drupal_html_class("value-$value");
  }
}

Note 1: I would recommend using lower case for class name.
Note 2: view_field_name is different from node_field_name


Permission to create new users but not to manage them I need to create a permission that allows any user to create other users without allowing them to manage all users (ie without granting them 'administer users' permission).

My approach was altering menu 'admin/people/create' but it - for unknown reason - doesn't work. Even though the permission for the menu is granted the menu item with link for is invisible and when I go to the specific url it - if I don't have 'administer users' permission - just redirects me to current user profile page.

    /**
 * Implements hook_menu_alter().
 */
function fm_users_more_menu_alter(&$items) {
  $add_new_user = &$items['admin/people/create'];

  unset($add_new_user['access callback']);
  unset($add_new_user['access arguments']);

  $add_new_user['access callback'] = 'fmu_add_user_access_callback';
  $add_new_user['access arguments'] = array(1);
}

/**
 * Callback that manages access to create user page.
 */
function fmu_add_user_access_callback($arguement) {
  dsm('test23');
  return true;
}

It does the same - redirects you to current user profile page - with User register form.

  $register_new_user = &$items['user/register'];

  unset($register_new_user['access callback']);
  $register_new_user['access callback'] = 'fmu_register_user_access_callback';

/**
 * Callback that manages access to create user page.
 */
function fmu_register_user_access_callback() {
  dsm('test23');
  if (user_register_access() || user_access('create users under self')) {
    return true;
  }
  else {
    return false;
  }
}

Don't forget to also give those same users the permission to access administration pages -- otherwise they'll be denied anytime they try to access any URI beginning with admin.

Also, I don't think it's necessary (or even desirable) to unset the menu items like that... You should just be able to do this:

function fm_users_more_menu_alter(&$items) {
  $items['admin/people/create']['access callback'] = 'fmu_add_user_access_callback';
  $items['admin/people/create']['access arguments'] = array(1);
}

Finally, remember to rebuild the menus after making such a change.


Adding content when creating a node I'm currently building a system to create rapports for a set of possible units. So far I have built a set of content types in CCK that acts like templates where the templates fields are used to add structures that the users creating the rapport will fill out.

I have, in my template, a list of "key value names" that will then be added to the rapport and the user can fill them out.

The Template:
a, b, c

The rapport:
* a = x
* b = y
* c = z

where x,y,z is entered by the user generating the rapport.

I found this here on drupal.stackexchange.com and I guess it's on the right track. But I don't understand what I would fill in 'hooks' with and how to limit the action to only trigger on(/before) node creation. There is also a number of sub-nodes that needs to be created based on the templates, but that part I haven't research yet, if it is connected please include information about it in your answer if possible.

Per the question you linked to, the Rules module will do this very well and can be used to call your custom actions when criteria are met during pre-save, validation, or other stages you might need.

It's worth pointing out that, since you want custom nodes created, you're likely to already need to be writing custom code. In this case a better approach might be to write an implementation of hook_nodeapi() (Drupal 6) or hook_node_{operation}() (Drupal 7) that means you can fire your own custom code at specific points during node creation.

Take a look at this question about how to make nodes programatically, and also this article with more detail about the process in Drupal 7 (only in Google cache). Extract of the article:

  1 Initialize a node object

 $node = new stdClass(); // We create a new node object $node->type =
 "page"; // Or any other content type you want $node->title = "Your
 title goes jere"; $node->language = LANGUAGE_NONE; // Or any language
 code if Locale module is enabled. More on this below * $node->path =
 array('alias' => 'your node path'); // Setting a node path
 node_object_prepare($node); // Set some default values. $node->uid =
 1; // Or any id you wish

  *We set LANGUAGE_NONE for $node->language, if you don’t have the locale module enabled, the node will not be assigned any particular
  language. So that's why we put here the constant LANGUAGE_NONE. In
  Drupal, nodes and fields can exist in more that one language, so if
  your site is multilingual you should specify the language code for
  your field. You can configure languages and get language codes by
  going this path in Drupal administration: Configuration -> Regional
  and language -> Languages.

  2 Add a body field

// Let's add standard body field
$node->body[$node->language][0]['value'] = 'This is a body text';
$node->body[$node->language][0]['summary'] = 'Here goes a summary';
$node->body[$node->language][0]['format'] = 'filtered_html'; // If
field has a format, you need to define it. Here we define a default
filtered_html format for a body field

  3 Add custom fields

// Let's add some CCK/Fields API field. This is pretty similar to the
body example  $node->field_custom_name[$node->language][0]['value'] =
'This is a custom field value'; // If your custom field has a format,
don't forget to define it here
$node->field_custom_name[$node->language][0]['format'] = 'This is a
custom field value'; // And etc. you can add as much fields here as
your content type has. The sky is the limit... and the server specs,
of course ;)

  4 Add file / image fields

// Some file on our system $file_path =
drupal_realpath('somefile.png'); // Create a File object $file =
(object) array(   'uid' => 1,   'uri' => $file_path,   'filemime' =>
file_get_mimetype($file_path),   'status' => 1, );  $file =
file_copy($file, 'public://'); // Save the file to the root of the
files directory. You can specify a subdirectory, for example,
'public://images'  $node->field_image[LANGUAGE_NONE][0] =
(array)$file; //associate the file object with the image field:

  5 Add a term to a node

$node->field_tags[$node->language][]['tid'] = 1;

  field_tags here is the name of a term reference field attached to your
  content type, 1 is a term id you wish to assign to a node. Simple!

  6 Save a node

$node = node_submit($node); // Prepare node for a submit
node_save($node); // After this call we'll get a nid


Filter search results based on user field I have previously created a view to search my different content types and it behaves like I want it to.

Now, I would like to limit the search results based on a user profile field. Each content type has an access level field. The access fields are tiered as follows:

A: every one can see it
B: only authenticated users can see it
C: only authenticated users with a certain profile property can see it

C users can see everything.
B users can see B and A content.

My first attempt at this was using a contextual filter and this sort of works. However, it only returns nodes that match the access tier.

I did this with PHP contextual filter code:

$memberAccessLevel = 'Public';

if (!empty($argument->field_membership['und'][0]['value'])) {
    $memberAccessLevel = $argument->field_membership['und'][0]['value'];
}

return $memberAccessLevel;

My question is, how can I set up the view so that tier C members can see all content?

Okay, I found the answer. If my keys are A,B,C, I can return A+B+C to return all nodes marked with either A, B, or C. Basically, you need to concatenate the keys you want with + and that will achieve the desired effect.


How to display node details and call function in *.html.twig I work in D8, I create a custom module first_module. By modules create a url and display all nodes by *.html.twig file.

Write code in controller.php

public function contentthree() {

  $connection = Database::getConnection();

  $query = $connection->select('node', 'n');
  $query->fields('n', ['nid', 'type']);

  $groups = $query->execute()->fetchAll();

  foreach ($groups as $group) {
    $events[] = [$group->nid, $group->type];
  }

  return [
    '#theme'  => 'first_module_display',
    '#events' => $events,
  ];
}

In *.module

function first_module_theme($existing, $type, $theme, $path) {

  return [
    'first_module_display' => [
      'variables' => ['events' => NULL],
      'template'  => 'first-module-list',
    ],
  ];
}

function _get_node_details() {

  $output = 'Welcome D8';

  $output .= 'Node Details';

  return $output;
}

and create templates first-module-list.html.twig and display data

{%for key, data in events %}

{%for key1, data1 in data %}

   {{ data1 }}

{% endfor %}

{% endfor %}

work fine and showing data correct. But, my question is how to call function _get_node_details() and how to render node details in first-module-list.html.twig files?

I think I would have implemented this feature differently. Let me just answer the specific question, and then I will tell you an alternative approach.

Custom 'functions' in Twig

The easiest thing for you could be to Implement a twig macro.

However, macros could be limiting. To have all the PHP power you can create a twig extension function

If you are in a rush and are into bad practices, then there is the twig tweak php filter, so that you can do this:

<div class="bad-practice">
     {{ 'return _get_node_details();'|php }}
</div>

Alternative implementation using Drupal views

Create a Drupal View, with a Block Display.
Place the new Block, using the Block Layout.
If you need to do a heavy alteration use a hook_views_data_alter().


Inline Entity Form - How to Theme the referenced form edit screen with a tpl.php file? Inline entity form (IEF) is a module that lets you create other nodes/entity inside of a node edit form (or reference them).

I would like to theme the form edit screen using a tpl.php file. (By form edit screen, I mean the place where the inline form is displayed for the user to input data and not the display that shows the finished form (e.g. so the 'edit' part and not the 'view' part),

This thread explains how to change values of the fields of the IEF creation screen. But it doesn't show how to use a tpl.php.file.

This tutorial and this tutorial explain how to theme forms. However, their knowledge doesn't seem to apply to Inline Entity forms (mainly because IEF forms don't use a form element).

I found the following answer here: http://site-machines.ru/blog/temizaciya-inline-entity-form-v-drupal

===========================

When using Inline entityform time to time it is necessary to make it more beautiful, more than matching the concept of the site. There are several ways to implement this, segodyan I will talk about one of the - the use of theming template.

As   Inline entityform is the usual form, so it has a minima must be some hook_alter. See the documentation that is the way to be in the module - inline_entity_form.api.php. The documentation found the right hook - hook_inline_entity_form_entity_form_alter.

At the entrance is just fed our inline form.

The next step is adding theming function

/ **
  * hook_inline_entity_form_entity_form_alter
  * /
 function sm_inline_entity_form_entity_form_alter (& $ entity_form, & $ form_state) {
   // Added theme function
   $ Entity_form [ '# theme'] [] = 'inline_entity_form_entity_form_'.  $ Entity_form [ '# bundle'];
   dpm ($ entity_form);
 }
I almost forgot to say the magic is done in our template.php form.

I told him what happened, what we've done in the previous paragraph? We've added a feature to our temizaitsii inline form, not just for one but for all. devel dpm () function module will help us to examine the insides of our Inline form

The next step in our magic, it template.php create hook_theme and declare it a template for our inline form

/ **
  * Implements hook_theme ().
  * /
 function sm_theme ($ existing, $ type, $ theme, $ path) {
   $ Items [ 'inline_entity_form_entity_form_shoes'] = array (
     'Render element' => 'form',
     'Template' => 'inline-entity-form-entity-form-shoes',
     // This will set to module / theme path by default:
     'Path' => drupal_get_path ( 'theme', 'sm').  '/ Templates / inline_form',
   );
   return $ items;
 }
Just be sure to create our template file and we put him on the scullery indicated in the 'path' hook_theme.

Then I inserted the following code template

<-! Start inline-entity-form-entity-form-shoes.tpl.php ->

<-! @ See sm_theme adn template.php ->

Then we look at what we will give dpm (), continue using drupal_render output fields in the required manner


How to show language specific search result in Solr search We have configured solr search in one of our site.The site is multilingual and having 5 languages content in it.

The problem we are facing is, when user language is selected as french and any searches are performed then the search result is not showing french content at top.

We want the users current language content to be populated at top.
Any module or solr settings which we missed.

use entity translation ...Regarding Entity Translation introductions:

Enable language fallback
Display shared labels
Select which entities can be translated: Node;Commerce product
Details for Commerce product: Selected Author's language and no
checkboxes at all

Languages selection/detection (admin/config/regional/language/configure):

Selected/added all necessary languages, still leaving English as
default, manually added en prefix for English default, to make clear
separation, as I am using prefix for language separation
User interface text language detection: URL; Default
Content language detection: Interface (moved to top manually); URL;
Default

Commerce product type settings (admin/commerce/products/types/product/edit):

Enabled via Entity Translation

admin/commerce/products/types/product/fields
Replaced regular Drupal Title field with Title module, and in this
field settings checked, that this is the only field in Product type
I'm going to allow translation.

Product display node content type settings from admin/structure/types/manage/{your-display-type}
Published options > Multilingual support - selected: Enabled, with
translation (NOT Enabled, with field translation, as I'm going to use
i18n for language and node separation).
My title field in this display node, which is overridden by Title
module is left for field translation, as these are per field
settings, not per content type.
There are no any other fields let for entity translation in product
display node, even product reference field (used with inline entity
form).

Basically that's all. Taxonomy term translation is handled by i18n modules and Taxonomy vocabulary has Translate... (NOT Localize...) settings - different name for each language tied into translation sets.


Modifying Webform checkbox markup I've already managed to modify checkbox markup for a bit but there's still something that I can't access. Current markup is as follows and here you can see the duplicate text of which last one should be removed:

            <input type="checkbox" id="edit-submitted-payment-methods-1" name="submitted[payment_methods][1]" value="1" class="form-checkbox checkbox require-one-edit-submitted-payment-methods">

            In cash (to a member or representative)

    In cash (to a member or representative)

Well, solution was to remove "fake" label and wrapper div which was moved upper to wrap "control-label". All done in THEME_NAME_checkbox(&$variables){}.

            <input type="checkbox" id="edit-submitted-payment-methods-1" name="submitted[payment_methods][1]" value="1" class="form-checkbox checkbox require-one-edit-submitted-payment-methods">

            In cash (to a member or representative)

    In cash (to a member or representative)


Join a select form with the number of the database to check I have this select form:

$options = array(
      'twenty' => '20',
      'hundred' => '100',
      'five_hundred' => '500',
      'thousand' => '1.000',
      'five_thousand' => '5.000',
      'ten_thousand' => '10.000',
      'hudred_thousand' => '100.000',
      'million' => '1.000.000',
      'two-million' => '2.000.000',
  );

  $form['number_select'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#description' => t('Select the number of values that you want to check.'),
  );

I want according to what number the user has selected to limit the same number how i can solve this problem?

my DB code is this:

function something_cron()

  $number = variable_get(number_select)
  $query = db_select('watchdog', 'wa')
    ->orderBy('wid')
    ->fields('wa', array('variables', 'type', 'severity', 'message', 'wid',
    'timestamp'))
    ->condition('wid', $last_id, '>')
    ->range(0,$number);
  $result = $query->execute();

  // Loop through each item and add to $row.
  foreach ($result as $row) {
    someother();
  }

Change your options to this:

$options = array(
      '20' => '20',
      '100' => '100',
      '500' => '500',
      '1000' => '1.000',
...
  );

Then you can use the value directly. It'll be a number. Also you need a #default_value:

#default_value => variable_get('number_select', '20')


Custom Field Type is missing in Feeds Importer I've got a problem with feeds importer. I've created a custom field type, and added a field with this field type to my content. If I try to import data via feeds importer, in mapping, this field is missing. Do I have to tell my custom field type that it is useable within feeds-importer?

You might need to create a target for your custom field type with the help of hook_feeds_processor_targets_alter and here is a code sample for doing so:

<?php
function MYMODULE_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name)
{
    foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance)
    {
        $info = field_info_field($name);
        unset($callback);
        if ($info['type']=='MYFIELDTYPE1')
        {
            //The callback for this field type goes here.
            $callback = 'TARGET_SETTER_FOR_MYFIELDTYPE1';
        }

        if ($info['type']=='MYFIELDTYPE2')
        {
            //The callback for this field type goes here.
            $callback = 'TARGET_SETTER_FOR_MYFIELDTYPE2';
        }
        //Add cases for each field type here
        //...

        if (isset($callback))
        {
            $targets[$name] =array(
                'name'=>check_plain($instance['label']),
                'callback' => $callback,
                'description' => t('The @label field of the node.', array('@label' => $instance['label'])),
            );
        }
    }
}
?>


form_set_error not working in node form validation I'm frustrated right now. This very reduced module code shows the problem:

<?php

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ('pic_node_form' == $form_id && !path_is_admin(current_path()) ) {
    $form['#validate'][] = '_mymodule_pic_add_form_validate';
  }
}

function _mymodule_pic_add_form_validate($form, &$form_state) {
  form_set_error(null, t('Keep calm bro'));
  // die("foo");
}

function mymodule_node_validate($node, $form, &$form_state) {
  form_set_error(null, 'test');
  // die("bar");
}

pic_node_form is the node add form for the content type pic. That form is exposed (hence && !path_is_admin(current_path())). There is an image upload field involved.

The form_set_error doesnt do anything and nodes keep getting submitted. The die() functions actually work when I remove the //, so the functions do get invoked.

The form itself is placed via block:

function _mymodule_get_block_content($delta) {
  if ('pic_add_form' == $delta) {
    global $user;
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array(
      'uid' => $user->uid,
      'name' => (isset($user->name) ? $user->name : ''),
      'type' => 'pic',
      'language' => LANGUAGE_NONE,
    );
    $form = drupal_get_form('pic_node_form', $node);
    $form_rendered = drupal_render($form);
    $markup .= $form_rendered;

    return $markup;
  }
}

Any ideas what I am doing wrong?

If you check the source of form_set_error(), you will see that if you don't supply the name of the form element for which you are setting the error, error messages will not be set.

As long as the first argument is NULL, form will be submitted. Your code was being executed, but it didn't stop the submission.

What you need to do is to pass the name of the field for which you want the error to show. This goes as the first argument for form_set_error().

Example:

form_set_error('YOUR_FIELD_NAME', t('Your message'));


My custom module does not show persian or arabic texts! I am developing a custom module. When I try to use Persian or Arabic text it does not show the text properly! The texts are shown in black square.
should I add anything?

As you see I installed Farsi language and menus are in Farsi but my custom text in module is not shown!

You have to install Locale module. Then you have to configure Arabic language.

To get our languages hooked in, let's enable the core module, Locale.
Go to Languages section in admin -  admin/config/regional/language:
Click Add Language button

Then select Arabic form the drop down and save.

That's all you have to do :)


drupal module defines front page using hook_menu...What does it need to return? I am using hook menu to define the front page (/front) and I found out if I return '' it renders the theme with all the blocks.

If I return content, is that what gets rendered into the Main Content block? What is the purpose of returning data from this function?

function dc_mad_marchness_menu()
{
    $items['front'] = array(
        'title' => 'Home',
        'page callback' => 'dc_mad_marchness_front',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function dc_mad_marchness_front()
{
    return '';
}

Yes, if you return either a string or a render array from a page callback function, it will be rendered in the main content region on the front end (well, under normal circumstances anyway. There are possible exceptions).

There's an in-depth description of page callback in the hook_menu() docs which is a bit long to reproduce here. I'd recommend giving it a read through.


ubercart checkout causes node to update On a site I manage we have a view of recently updated products. The problem is that once a user purchases a product, that product is updated, which shoots it to the top of the list.

As far as I can tell there's no reason for a node update to be triggered simply because the product was purchased.

My first thought was the stock. However, uc_stock is directly calling db_query on uc_product_stock table and not touching node, or is it doing a node_load/node_save.

The closest I've found is that the update is triggering the nodeapi hook with the 'update' op. nodewords is picking it up as an update operation and I can see it in the dblog.

Any ideas?

Perhaps install and enable devel, and then look at the SQL queries to get the offending query which might give you clue about some other module that's doing an update.


How I can include Commerce SKUs in search result? How I can include Commerce SKUs in search result?

I am using “Search API and Search API Solr” modules.

Any suggestions?

Add a field or attribute to your index

Most likely, you need to add the SKU field to your index. Since most search api implementations of Commerce index display nodes AND their connected products, you will need to use: https://www.drupal.org/project/commerce_search_api for connecting referenced product properties with your display nodes.

Then, you will need to add the SKU field to your product display index. A good step-by-step for this is here (search for "define index fields" on the page): http://www.webwash.net/drupal/tutorials/intro-search-api-part-1-how-create-search-pages

Add an indexed field or attribute to search results

Finally, if you want to managed the fields that appear in search results, you will need to modify the view and/or the display mode being used to render the results.

Commerce allows "field injection" for display nodes that allow you to inject default product properties on display. But note that if you search for "Red Shirt" and the display node that has this product is by default "Blue Shirt" then, when that node is rendered, it's likely going to render the "Blue" and not "Red" SKU.

Probably need to create a hook_form_alter() that can determine if the add to cart form is being generated inside search results and trying to make it understand which SKU should be a part of the result.


Webservice endpoint with hook_services_resources() I've stumbled upon some limitations of the services module. I wanted to create the following endpoints:

public/events/
public/events/categories
public/events/resources
public/blogs/

I wanted to place all the above under a single endpoint with path "public/".
However, in the hook_services_resources the following is invalid:

/**
 * Implements hook_services_resources().
*/
function kw_api_services_resources() {
  $service_resources =
   'event/categories' => array(
      'operations' => array(
        'index' => array(

I ended up using two endpoints public/events and public/blogs. Is there a way to get around this? Meaning to user deeper than 1 level URLs.

Example from the module itself, the child is defined in the relationships:

'events' => array(
  'operations' => array(
    'retrieve' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_retrieve',
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node to get',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('view'),
      'access arguments append' => TRUE,
    ),
    'create' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_create',
      'args' => array(
        array(
          'name' => 'node',
          'optional' => FALSE,
          'source' => 'data',
          'description' => 'The node data to create',
          'type' => 'array',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('create'),
      'access arguments append' => TRUE,
    ),
    'update' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_update',
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node to get',
        ),
        array(
          'name' => 'node',
          'optional' => FALSE,
          'source' => 'data',
          'description' => 'The node data to update',
          'type' => 'array',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('update'),
      'access arguments append' => TRUE,
    ),
    'delete' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_delete',
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('delete'),
      'access arguments append' => TRUE,
    ),
    'index' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_index',
      'args' => array(
        array(
          'name' => 'page',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'The zero-based index of the page to get, defaults to 0.',
          'default value' => 0,
          'source' => array('param' => 'page'),
        ),
        array(
          'name' => 'fields',
          'optional' => TRUE,
          'type' => 'string',
          'description' => 'The fields to get.',
          'default value' => '*',
          'source' => array('param' => 'fields'),
        ),
        array(
          'name' => 'parameters',
          'optional' => TRUE,
          'type' => 'array',
          'description' => 'Parameters array',
          'default value' => array(),
          'source' => array('param' => 'parameters'),
        ),
        array(
          'name' => 'pagesize',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'Number of records to get per page.',
          'default value' => variable_get('services_node_index_page_size', 20),
          'source' => array('param' => 'pagesize'),
        ),
      ),
      'access arguments' => array('access content'),
    ),
  ),
  'targeted_actions' => array(
    'attach_file' => array(
      'help' => 'Upload and attach file(s) to a node. POST multipart/form-data to node/123/attach_file',
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_attach_file',
      'access callback' => '_node_resource_access',
      'access arguments' => array('update'),
      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node to attach a file to',
        ),
        array(
          'name' => 'field_name',
          'optional' => FALSE,
          'source' => array('data' => 'field_name'),
          'description' => 'The file parameters',
          'type' => 'string',
        ),
        array(
          'name' => 'attach',
          'optional' => TRUE,
          'source' => array('data' => 'attach'),
          'description' => 'Attach the file(s) to the node. If FALSE, this clears ALL files attached, and attaches the files',
          'type' => 'int',
          'default value' => TRUE,
        ),
        array(
          'name' => 'field_values',
          'optional' => TRUE,
          'source' => array('data' => 'field_values'),
          'description' => 'The extra field values',
          'type' => 'array',
          'default value' => array(),
        ),
      ),
    ),
  ),
  'relationships' => array(
    'resources' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'help'   => t('This method returns files associated with a node.'),
      'access callback' => '_node_resource_access',
      'access arguments' => array('view'),
      'access arguments append' => TRUE,
      'callback' => '_node_resource_load_node_files',
      'args'     => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node whose files we are getting',
        ),
        array(
          'name' => 'file_contents',
          'type' => 'int',
          'description'  => t('To return file contents or not.'),
          'source' => array('path' => 2),
          'optional' => TRUE,
          'default value' => TRUE,
        ),
        array(
          'name'         => 'image_styles',
          'type'         => 'int',
          'description'  => t('To return image styles or not.'),
          'source'       => array('path' => 3),
          'optional'     => TRUE,
          'default value' => FALSE,
        ),
      ),
    ),
  ),


Write Drupal Code online Is there any website that allows to write and test Drupal Code online ? Like this one for PHP writecodeonline.

There's Simplytest.me, but that's really for testing existing module to see if you like them (e.g. never used Panels before, select Panels from the list and hit Launch Sandbox to give it a go).

You could set up a test site with Devel and hit devel/php.  However this isn't really any different from running a local sandbox site and doing the same thing.

Apart from that, I've not seen anything like what you're looking for.  Sorry :(


Dynamic value in Twig or preprocess based on config and getHost() I need to dynamically change a value in Twig templates by selecting a configuration value (defined in a custom module) based on the current environment.
I did the following in a Form class, which works fine:
  /**
   * Generate parent site Base URL per environment.
   *
   * @return string
   *   The parent site Base URL used in all templates site-wide.
   */
  public function getBaseUrl() {
    $host = $this->requestStack->getCurrentRequest()->getHost();
    $config = $this->configFactory->get('clientname_cta_base.settings');
    switch ($host) {
      case 'resources.clientname.com':
        // Set $base_url to Production environment.
        $base_url = $config->get('prod_base_url') ?? [];
        break;
      case 'uatresources.clientname.com':
        // Set $base_url to UAT environment.
        $base_url = $config->get('uat_base_url') ?? [];
        break;
      case 'qaresources.agencyname.com':
      case 'qaresources.clientname.com':
        // Set $base_url to QA environment.
        $base_url = $config->get('qa_base_url') ?? [];
        break;
      default:
        // All other environments, including local, link to Dev.
        $base_url = $config->get('dev_base_url') ?? [];
        break;
    }
    return $base_url;
  }
  /**
   * Generate CTA destination URL per environment.
   *
   * @return string
   *   The CTA destination URL used in all templates site-wide.
   */
  public function getCtaUrl() {
    $config = $this->configFactory->get('clientname_cta_base.settings');
    $cta_url = $this->getBaseUrl() . $config->get('default_link_dest') ?? [];
    return $cta_url;
  }

This displays the desired URL paths in two disabled fields when the SettingsForm is loaded:
    // Active URL configuration (read-only).
    $form['clientname_cta_base_computed_base_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed base URL (Preview)'),
      '#default_value' => $this->getBaseUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];
    $form['clientname_cta_base_computed_cta_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed CTA URL (Preview)'),
      '#default_value' => $this->getCtaUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];

I could even store these updated values in configuration when the SettingsForm is submitted -- but that will not quite get me what I want.
These values need to be computed dynamically by selecting config based on the value of $host at runtime -- importing the Dev environment's computed config values to the QA environment won't do. So I am looking for a way to call the module's public methods (getBaseUrl() and getCtaUrl()) in either theme preprocess or Twig templates.
Is this approach possible? Should I have used theme settings instead?

In case you wondered, I resolved this by adding my methods to a service class, as @Hudri suggested in comments.
I can call those methods in a Form or other OO class by dependency injection of the Drupal\clientname_cta_base\Cta\Base service class:
    // Active URL configuration (read-only).
    $form['clientname_cta_base_computed_base_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed base URL (Preview)'),
      '#default_value' => $this->ctaBase->getBaseUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];
    $form['clientname_cta_base_computed_cta_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed CTA URL (Preview)'),
      '#default_value' => $this->ctaBase->getCtaUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];

The example above does not include all the dependency injection setup in the Form class, or the service class setup, services YAML config, and other steps that are well documented elsewhere.
In theme preprocess, dependency injection is not available, so I get the computed values via \Drupal::service('cta.base') like so:
/**
 * Implements template_preprocess_page().
 */
function clientname_preprocess_page(&$variables) {
  $service = \Drupal::service('cta.base');
  $config = \Drupal::config('clientname_cta_base.settings');
  $variables['computed_base_url'] = $service->getBaseUrl();
  $variables['computed_cta_url'] = $service->getCtaUrl();
  $variables['default_link_text'] = $config->get('default_link_text');
}

Note that for configuration values that are not dynamically generated, I can just access them directly in theme preprocess via \Drupal::config('clientname_cta_base.settings').


How can I load custom module JavaScript on content type edit form? I'm trying to load jQuery on the admin edit form of a content type.

To accomplish this, I developed a module "exclusivetabs" with the following directory structure:

|-- exclusivetabs
    |-- exclusive_tabs.info.yml
    |-- exclusive_tabs.libraries.yml
    |-- exclusive_tabs.module
    |-- js
        |-- cse_banner_header.js

The contents of the relevant files are as follows:

exclusive_tabs.libraries.yml

exclusive_tabs:
  version: 1.x
  js:
    js/cse_banner_header.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

exclusive_tabs.module

<?php

/**
 * Implements hook_form_alter().
 */
function exclusive_tabs_form_node_form_alter(&$form, &$form_state, $form_id) {
  /* @var Drupal\Core\Entity\FieldableEntityInterface $node */
  $node = $form_state->getFormObject()->getEntity();

  if ($node->getType() == 'unit_landing_page') {
   /* var_dump($node);*/
    $form['#attached']['library'][] = 'exclusive_tabs/cse_banner_header';
  }
}

cse_banner_header.js

(function($, Drupal) {

/* Add span to wysiwyg button classes for alignment
------------------------------------ */
Drupal.behaviors.calloutControl = {
        attach: function (context, settings) {
                console.log("I'm loaded!");
                $('#callout-link-options .single-link').click(function () {
                        $('input[type="checkbox"]').attr('checked', true);
                        console.log("I'm checked!");
                });
                $('#callout-link-options .multi-link').click(function () {
                        $('input[type="checkbox"]').attr('checked', false);
                        console.log("I'm unchecked!");
                });
        }
};

})(jQuery, Drupal);

The module loads on the specific content type edit form as intended; my trouble is that I haven't figured out how to get the jQuery to load from the cse_banner_header.js file. I also checked the running scripts in the browser, and from what I can tell, the js file does not load on the page.

What am I missing? How can I get the js file to load on the page?

You need to change this line:

$form['#attached']['library'][] = 'exclusive_tabs/cse_banner_header';

to:

$form['#attached']['library'][] = 'exclusive_tabs/exclusive_tabs';

As your library name is exclusive_tabs and not cse_banner_header the correct way is 'your_module/library_name' check Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.


Multiple menu locations in taxonomy menu I've used taxonomy menu version 7.x-1.5. Due to this module I can only added taxonomy menus into single menu location.

But I want to add a taxonomy menu into multiple menus. Is it possible? If yes, how to do this?

I've attached image. Please look it.

You can manually add menu items that link to the taxonomy terms as many times as you want - but that Taxonomy Menu option will only manage a single one.

You could potentially write a custom module that automatically inserts the same item into other menus at the same time - but that might be more complicated than you want.


problem with Single Page Website module I wanted to try out the Single Page Website module for Drupal 7

I followed the instructions and all seemed to work well, except my anchor links wouldn't work i.e. it wouldn't scroll down the page when I clicked on them.

What might have been the problem there? The only anchor that seemed to work, was the link to a view.

Any ideas where I might have gone wrong or what I might have missed? Any experiences?

I had this issue when I was testing out this module as well.

Solution: Create an Alias for each piece of content.

Each node/page you want to include on the single page, visit and add the alias. As admin, visit say, your default page you wish to have at the top, click Edit, and create the alias. In MY experience, once I did this for the pages for the Single Page using the single_page module, it worked.


Bulk deletion of rules? I was testing with rules and now I got around 50 rules. Just wondering if Is there any way to bulk delete rules and components

The rules module provides a function called rules_config_delete().

You can call this with an array of rules ids to delete multiple rules in one go:

rules_config_delete(array(3, 4, 5, 6));


Change frontpage pagination to use a more/previous style The standard pagination on my site looks like this:

I'd like to alter the config (or install a module, etc) that will help me use this simpler type of pagination:

How can I reconfigure my site to use this kind of pagination? Do you know of a module that will let me choose this style?

You just need to use theme_pager()

Place this function in your template.php file and clear theme registry:

/**
 * Implementation of HOOK_pager().
 * $variables: An associative array containing:
 *  tags: An array of labels for the controls in the pager.
 *  element: An optional integer to distinguish between multiple pagers on one page.
 *  parameters: An associative array of query string parameters to append to the pager links.
 *  quantity: The number of pages in the list.
 */
function YOURTHEME_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];
  global $pager_page_array, $pager_total;

  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ Previous Posts')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('More Posts ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {

    // PREVIOUS
    if ($li_previous) {
      $items[] = array(
        'class' => array('pager-previous'),
        'data' => $li_previous,
      );
    }

    // NEXT
    if ($li_next) {
      $items[] = array(
        'class' => array('pager-next'),
        'data' => $li_next,
      );
    }

    // OUTPUT
    return '
' . t('Pages') . '
' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pager')),
    ));
  }
}


Get term weight in node object for ordering with EntityFieldQuery Is it posiible to expose taxonomy term weight in node object ?

I need to sort nodes using EntityFieldQuery by term reference field, but weight is not exposed to node object so i can say for example

->fieldOrderBy('field_custom_terms', 'weight', 'ASC');

and sort nodes by weight of terms.

No, this is not possible. You can only order on actual field values, the term weight would require a JOIN to a non-field table and EFQ is not capable of doing that.

You will have to create a manual SQL query to do this. Note that Drupal by default maintains the node <-> term associations in the taxonomy_index table, that one is easier and more reliable to query than a field data table.


How can I override taxonomy term page? I have created a Vocabulary (categories) with terms (term1, term2, term3..etc). After that I created a content type (Product) with fields title, description, image. Also, created field called "product type" which is a term reference (categories). Furthermore, I am displaying  all terms list in page like term1 term2 term3 with link.

When I click on term1 I want to display related products name, description, image with full details link. I am currently displaying only term related product title with read more link only.
[![enter image description here][1]][1]
Please Advice.

You could install Views module, create a list of products, and filter based on taxonomy (Contextual filter).


field_image_cache missing from all content types I've had a strange thing happen to a Drupal 6 site. All images are missing from the site. Looking at the Edit screen for a node shows that the ability to edit and upload an image for any node is missing.

Further checking the content types shows that under 'Manage Field' the 'Image' field [field_image_cache] has be removed for every content type.

As far as i can see all the correct modules are still enabled.

Anyone got any ideas?

Just thought I would update this one, just in case anyone else has a similar problem.

Turns out that the database was erroring and running out of disk space. Which meant the queries couldn't be completed. This ended up corrupting the database and I had to restore from a backup.

Once the restore completed all images and ability to Edit them returned to the site.

Hope that helps.


How to strip  tags from teasers? I have nodes with text and images in the body field. I wish to remove the images from the teaser texts, currently created with the "Summary or Trimmed" field display option.

Is there a hook or similar for altering the field before it's output in the teaser? Or would this require writing a custom field formatter?

I have had good luck using the Smart Trim module. (This module is now available for Drupal 7 and 8.)

Choose the Smart Trimmed field formatter and check the Strip Out HTML checkbox to remove the image tags (and other formatting that you probably don't want in a teaser text).

It also gives you some other handy formatting options (limit to number of words or characters, add "read more" links, etc) and makes the formatting options available for fields in Views, as well.


How to remove the word "New" for the new comments When I add a new comment, the word "New" is printed at the top:

I don't need it. This word can be removed by editing the file /modules/comment/comment.tpl.php:
//remove these 3 lines, and the word will disappear
<?php if ($new): ?>
  <?php print $new ?>
<?php endif; ?>

But I don't think, that changing core modules is a good idea.
How can I remove the word without changing the core files?

copy /modules/comment/comment.tpl.php to your theme folder e.g. sites/all/themes/mytheme/(templates/)comment.tpl.php.

That theme file will override the comment.tpl.php from core, in that file you can remove this block:

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

This way is perfectly fine, you are not changing/ hacking core. The theme system was meant to be used that way :)


Drupal\Component\Plugin\Exception\PluginNotFoundException: The "glossify_taxonomy" plugin does not exist. In Drupal 8 when we upload the module we will get this kind of issue very often.

I have installed glossify and its submodule glossify_taxonomy and configured. we have created some content in production.

After some days we felt we don't need glossify module. In our local instance we have uninstalled the module using composer and exported configuration and pushed to production and configuration also imported.

whenever we have try to create content or else try to access existing content we are getting plugin not found exception.

We have fixed it by first removed all the configuration, deleted all the content and removed the modules from contrib directory

But in production we can't do this every time. Please suggest how to safely uninstall the module.

thank you everyone for the answer in advance.

There are two approaches (if you don't want to reinstall the module's source code to production and work through the same steps to fully uninstall it).

If you have command line access to the webserver, you could try using drush to uninstall the module on production. Run drush pm-uninstall glossify_taxonomy and then drush pm-uninstall glossify
If that fails, you could schedule a content freeze, download the database to your local instance, and manually set the module as "disabled". Unlike Drupal 7's variables table however, each module does not have it's own row of data.  Instead all module enabled/disabled states are aggregated and saved in the row of data where cid = core.extension within both the config and cache-config tables. To disable the module without fully uninstalling:

load the exported database from prod locally and:
Open ‘config’ table
Search row with ‘core.extension‘
Download Blob object
Unserialize Data (http://www.unserialize.me/ is a quick online tool to serialize and unserialize)
Unset the glossify & glossify_taxonomy modules or remove them from the array.
Serialize Data
Upload Blob object
Save the edited record
Open ‘cache-config’ table and repeat steps 2-8
Export the modified local database
Before making changes on production, keep a backup of the database for quick reversion if needed.
Import the modified local database back to prod
Test to see if you continue to observe the Missing Module warning/error.


What complications are there if I switch Mysql to MariaDB? Any Drush issues? I have a heavy Mysql drupal 7 site and I was thinking about switching Mysql over to Mariadb, but I wasn't sure what issues I would run into. From what I'm reading Mariadb seems to be just a drop in replacement for Mysql and there doesn't seem much to fiddle with. I was wondering if Mariadb would affect drush commands?

As you say, Maria DB is a drop-in, completely transparent replacement for MySQL. Its releases coincide with the same major/minor version of MySQL so it's pretty much always in tandem as far as features are concerned. It reads the standard MySQL binary data files, uses the standard systen my.cnf, and even has a drop-in replacement for InnoDB.

The idea is that as far as your application is concerned it thinks it's connecting to a MySQL server. It uses MySQL drivers, issues full MySQL statements, and receives responses exactly as the MySQL server would send. Your app(s) won't know the difference.

I've been using Maria for a while now for Drupal sites (also using Drush extensively) and haven't had a single problem to date. If you're running *nix upgrading is just a two minute job.


Is it possible to add CSS to the user edit page? EDIT:I'm using a custom theme and attempting to edit the style on a specific field on the user edit page.

Dooug is correct. My question was answered here How to Override CSS for a core module?

I want to perform some styling and add CSS to the user edit page. Is this possible?

This depends on which theme you are using for your admin theme. If you are using a custom theme for the admin theme, you can add CSS in that custom theme. Otherwise, this is possible in a custom module via hook_css_alter().

Can you provide more information?

Are you using a contributed theme or sub-theme as the admin theme?
Which version of Drupal are you using?
Does the CSS only need to be loaded on the user edit page? What are you trying to change on the user edit page?

I highly recommend reviewing the Drupal documentation on theming: https://www.drupal.org/node/341246

Here are some similar questions:
How to Override CSS for a core module?
How to override some admin theme CSS rules?

Good example solution: http://purewebmedia.biz/article/2014/04/23/adding-your-own-css-admin-theme


Loading a View Through Ajax - Slideshow not showing I have a view in node-view mode that has another view (a view slideshow) embedded into that view. I am using jquery and setTimeout to slideDown the hidden div that contains the view a few seconds after the page loads. The problem that I am running into is when the div slides down to show the view, the slideshow is not showing.

Here's my jquery

Drupal.behaviors.landing = function (context) {
if($('#portslide-wrap').children().children().next().hasClass('portfolio-direct')){

    setTimeout( function getSlide(){
        $('#portslide-wrap:not(.landing-processed)', context).addClass('landing-processed').each(function(){

            $('#portslide-wrap').slideDown();
            $.scrollTo('165','0');
            Drupal.attachBehaviors(context);

        });
    }   ,700)
  };

}

Are you using a Drupal module like Views Slideshow to create your slideshow?

Usually slideshows will need to dynamically calculate the height/width of the content in the slides in order to render correctly. If the slideshow is hidden when the slideshow's javascript is loaded, then there will effectively be no content for the slideshow's javascript to render, thus the slideshow will never render correctly.

Does the slideshow render with no problems if you remove your CSS and/or JS that hides (and then slides down) the slideshow?

I haven't dealt with this sort of issue directly, but hopefully I can point you in the right direction. I would guess that somewhere you are using JS or CSS to hide the #portslide-wrap div (i.e. display:  none;) until it is ready to slide down? I would suggest trying to hide that div behind some other element using z-index rather than display:none(so that the slideshow can render while being obscured) and then hide it using JS after the slideshow has processed (probably a class like "slideshow-process" is added to a wrapping div, which you can use to hide the slideshow via CSS).


Translate custom string from programatically defined block Alright, this one is probably easy but I found online documentation only little helpful and couldn't figure it out myself.

I run a custom module that renders a custom block programatically via function hook_block_view(). Assume that $block['content'] = 'Hello';. The custom string 'Hello' does not appear in the list of translatable strings (config/regional/translate/translate) but I want to display it in, say, Spanish ('Hola') when the site language is set to Spanish.

How do I translate it / make it appear in the list?

In order to make strings translation possible you need to pass it through the t function.

$block['content'] = t('Hello');


How do I pass a variable from a custom module to its template file? I need to know the simplest method to pass variable from custom module to its template file.
I have created the custom.module and placed custom.tpl.php in the module folder.

function custom_menu(){
  $items = array();

  $items['custom'] = array(
    'title' => t('custom!'),
    'page callback' => 'custom_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_page() {

    $setVar = 'this is custom module';
    return theme('custom', $setVar);
}

i have added theme function but it is not working, can any one suggest me what is wrong with this code

function theme_custom($arg) {
  return $arg['output'];
}

function custom_theme() {
  return array(
    'Bluemarine' => array(
        'variables' => 'output',
        'template' => 'Bluemarine',
     ),
  );
}

Independently from the Drupal version for which you are writing the module, there are two errors in your code:

You define "Bluemarine" as theme function, but then you call theme('custom'), which would call the "custom" theme function
If you define "custom" as a theme function that uses a template file, then theme_custom() is never called

If you are writing code for Drupal 6, then the code should be similar to the following one. I take the assumption the name for the theme function is custom.
function custom_menu(){
  $items = array();

  $items['custom'] = array(
    'title' => t('custom!'),
    'page callback' => 'custom_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_theme() {
  return array(
    'custom' => array(
      'arguments' => array('output' => NULL),
      'template' => 'custom',
     ),
  );
}

function custom_page() {
    $output = 'This is a custom module';
    return theme('custom', $output);
}

function theme_custom($output) {
}

The template file will have access to $output, and to any variables set in template_preprocess_custom(), if your module implements it.
For example, you could implement code similar to the following one:
function template_preprocess_custom(&$variables) {
  if ($variables['output'] == 'This is a custom module') {
    $variables['append'] = ' and I wrote it myself.';
  }
}

With this code, the template file has access to $output and $append.
As example of theme function that uses a template file, you can look at theme_node(), which is defined in node_theme(), and that uses node.tpl.php as template file; the preprocess function implemented by the Node module for that theme function is template_preprocess_node().


How to use TinyMCE 4.5 with the WYSIWYG module? I am using the WYSIWYG module on Drupal 7, but the only TinyMCE editor I can use is version 3.5. I would like to use the version found here. How can I install this?

The previous version of the WYSIWYG module didn't support TinyMCE, but it does now.


On a Drupal user application form, is it possible for the user to lookup existing users? I'm looking to add a user lookup form to my Drupal site's application form. One question would ask the applicant/registrant to look up an already existing user on the site. What's the best way to go about something like this in Drupal?

Yes it is possible but would require some custom code.

Assuming you already have a form element where your autocomplete search would take place, in a hook_form_alter() or hook_form_FORM_ID_alter() you could use something like:

  // Add ajax autocomplete.
  $form['name_of_your_text_element']['#attached']['js'][] = 'misc/autocomplete.js';
  $form['name_of_your_text_element']['#autocomplete_path'] = 'ctools/autocomplete/user';

Note that you will probably need to adjust some permissions in order to allow anonymous users to see your users' information. Check /admin/people/permissions if you need to fine-tune something there.

You also need to have the ctools module enabled in order to use this functionality.


Leveraging field_get_items variable in a custom field template I can use a template preprocess function for node to simply get the alt tag of an image field image using the venerable field_get_items as such:

function MYTHEME_preprocess_node(&$vars, $hook) {
// Global node.
  $node = $vars['node'];

 $field_image_items = field_get_items('node', $node, 'field_image');
  // Load individual data from 'field_image'.
    $vars['alt_caption'] = $field_image_items[0]['alt'];
}

Then in node.tpl.php, I can render the alt tag of the image from the variable we created above as:

<?php print $alt_caption; ?>

... and that works great.

However, I'd like to customize the template for the image itself so when I create a field--field_image.tpl.php template, sure enough the image renders fine but if I add the $alt_caption variable, that does not render. I'm guessing this will simply not work or there is an extra step I need to do for the variable to render in this new template.

You need TEMPLATE_preprocess_field() function at template.php

You can use this preprocess function in same way as you are doing for NODE. Like -

function MYTHEME_preprocess_field(&$vars) {
  if ($node = menu_get_object()){
    $node = $vars['node'];
    $field_image_items = field_get_items('node', $node, 'field_image');
    $vars['alt_caption'] = $field_image_items[0]['alt'];
  }
}

Then go to your TPL made for your particular field and print it where ever you like just like you have mentioned --

<?php print $alt_caption; ?>

And it will work like charm!! I have implemented like this several times.

But yeah...don't forget to clear your cache after this implementation.


Programmatically create a node with a menu link I created a node programmatically with the following code.

$data = array(
  'type' => 'inception_article',
  'title' => $msg->name,
  'body' => array(
    'value' => $msg->body,
    'format' => 'full_html'
  )
);

$node = Node::create($data);
$node->save();

I would now also like to create the menu link for the node, but I cannot figure out how to do that in Drupal 8.

How can I programmatically create a menu link for a node I create?

You can save menu link Separately using the below code on node save.

 $menu_link = MenuLinkContent::create(array(
      'title' => 'Menu Title', // Menu title is your title of menu, in this case node title
      'path' => '/path/to/node', // Menu link something like '/node/'.$nid, replace $nid with your node id
      'menu_name' => 'navigation',
      'weight' => 0,
      'bundle' => 'menu_link_content',
 ));

 $menu_link->save();


redirect after login in drupal without impacting the password reset functionality The problem:

When using hook_user_login to redirect a user to the correct language this is also triggered during password reset. And the hook params do not provide a way to deal with this.

This How can I redirect users on login based on their chosen language? post details multiple not working concepts.

And i can't comment cause of the silly reputation thing, while i'm a developer for over 10 years... (getting tired)

I guess the form alter is the ONLY way.

hook_user_login is as you'd expect for when someone goes from anonymous to authenticated. This happens by using the login form and by using a password reset link.

Having a look on Drupal's API site is always worthwhile as people have usually commented on comment occurances like this. For example on https://api.drupal.org/api/drupal/modules%21user%21user.api.php/function/hook_user_login/7.x it has exactly what you're describing and recommends using something like:

if((!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset')){
  //your redirect code
}

But also using form_alter would also be perfectly fine really as you want to target a specific action of logging in via a specific form


Invalid translation language (fa) specified I'm trying to add "fa" language in a Drupal 8 installation. I added it from admin/config/regional/language. Everything is OK and the language added successfully and added in language switcher in front-end. But when I click on it, I get this error:

InvalidArgumentException: Invalid translation language (fa) specified. in Drupal\Core\Entity\ContentEntityBase->getTranslation() (line 748 of core/lib/Drupal/Core/Entity/ContentEntityBase.php).

Note: This is not a clean installation. The Drupal I have is a working site with some modules which I want to add Persian as its 6th language. Any suggestions?

Thanks.

Basically, this error appears when some translation methods like $entity->getTranslation('LANGUAGE_CODE') or $entity->addTranslation('LANGUAGE_CODE') are called and there is no translation of the entity in the specified language.

The solution is to check if the entity hasTranslation using $entity->hasTranslation('fa') before calling the getTranslation or addTranslation like this:

if ($entity->hasTranslation('fa')) {
  $translation = $entity->getTranslation('fa');
}