7 - Sorting in a view seems to not be alphabetical? I've set up a Drupal 7.18 site with Views 7.x.35. I've created a content type "Course" and included it's content type as an entity reference in a "Product" content type.

I have a view for listing courses and it sorts alphabetically just fine. However, I have another view products, with a course column, and its alphabetical sort is not alphabetical. I would like advice on 1) why this is so and 2) how to make it alphabetical.

Things I've tried:
* Clearing caches via Admin section
* Removing all other sort criteria from view
* Removing and re-adding the field

I am attaching an image depicting the behavior and another showing the view setup. I'm happy to provide more detail as appropriate. TIA!

Here's links to the photos (sigh, first post, lack 10 points to post images)
Error behavior: http://www.flickr.com/photos/24745111@N00/8389442182/in/photostream

View admin pane: http://www.flickr.com/photos/24745111@N00/8389442184/in/photostream

Since the course field is an entity reference the sort would be working on the node id and not the node name. can you check this.

What you could do is add the node title instead of the node entity field. and create a relationship to the node title to the entity reference field. Now the sort should work properly.

EDIT : Adding the steps mentioned in comment

Add Content:Title to the view.
Go to advanced, add a relationship to the content type.
Go back to that title field configuration and select the relationship from the drop down.
Go the the format settings and make the new field sortable.


Custom messages for user_pass_reset I would like to customize the messages for one time login links (i.e. password reset links). In some cases, I redirect the user to the login page. In these cases, it does not make sense to have "Please request a new one using the form below."

Is there a hook or module I can use to add some logic to that message? (I can do a global override with String Overrides, but am looking for more conditional messages.)

I am using Drupal 7.

If you mean the email message for a password reset. You can use hook_mail_alter to change the email contents before it's sent out to the user.

If you mean the form the user sees on the webpage, then you can use hook_form_alter to change the verbiage shown on the screen.

Edit

override the displayed form with the reset button to goto your own form_submit action. In your custom module action, simply copy and paste user_pass_reset function body into your own function and tweak it as needed to change the messages (careful).


How do I add an field containing image links? I need a list of images in a view that all link to a third party page.

In the field formatting/rewriting options, you can check "Output this field as a link" and then enter your third party external link.


Configuration Management is broken between two site environments, I have no idea how to fix it I started working on a d8 site two weeks ago; there are two site environments: @dev and @staging, on different servers. I have been developing the site locally (adding views, pages etc.) and using the configuration exporter to export a compressed config file from @dev which I then import @staging. I occasionally use the single export/import tab to pass configuration upstream.

Mostly it's been working fine until recently. I somehow broke the site when I added a specific view. Now whenever I try to import into @staging i get the same error, regardless of what I'm importing:

  The configuration cannot be imported because it failed validation for the following reasons:
  Configuration views.view.view_name depends on the module that will not be installed after import.

A while ago I created a module (using drupal console) with the purpose of inserting a block, but it failed (probably because I gave the module the same name as the theme I'm developing). I removed this module, but not before enabling it on one or more of the sites - it's the only thing I did that broke the site (prompting a restore from an earlier database version).

I just want to fix the configuration syncing between the two sites, because I can't go on re-configuring both versions of the site for each and every change. That's so D7.

I'd be happy to provide any other information needed to help diagnose/solve the issue. I use git to synchronise themes between the two files, filezilla to copy site files from @staging -> @dev, drush to install any modules (eg. drush en ds) to @dev and git to transfer those changes to @staging. Occasionally I'll synchronise databases from @staging -> @dev (because content entry - handled by another internal team - has begun).

Aaaaaargh! After banging my head against the wall I found the issue. I checked the yml output (either single export tab; the /sync folder; or in the compressed export file) and found the 'broken' line:

dependencies:
  config:
    - core.entity_view_mode.node.teaser
    - node.type.leistungen
  module:
    - null
    - node
    - user

I removed the '- null' entry and retried the import - it worked fine.

MegaDoh!


drush pm-update of 6.27 to 6.28 yields this error: Allowed memory size of 67108864 bytes Possible Duplicate:
  “Allowed memory size” errors on common tasks

we put our site into maintenance mode,
temporariliy removed some symbolic links that have confused drush in the past,
and tried to do this:
[~/drupal-6.25]# drush pm-update

where we got this error:

Refreshing update status information ...

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 199690 bytes) in /home/kettles/drupal-6.25/modules/update/update.module on line 549
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Allowed memory size of 67108864 bytes exhausted (tried to
allocate 199690 bytes) in
/home/kettles/drupal-6.25/modules/update/update.module, line 549
[~/drupal-6.25]#

The directory is called drupal-6.25 but really holds a 6.27 install.

Thanks,

See this thread.

What you need to do basically is to increase the memory in your php.ini file. Start with 128M and if you are still getting that error, try with more.


Getting hook_menu() to respond to a URN I have a site that can respond to URNs.  For example, I need to be able to serve up a response to

http://example.com/urn:myscheme:foo:bar:12345

So, I need a router item that can match against the "urn" or "urn:myscheme" portion, and get "foo:bar:12345" as the argument (either exploded or not).

Can hook_menu() be configured this way?

I have tried

$item['urn'] = array(...);
$item['urn:'] = array(...);

without any luck.  I can do this with a hook_url_inbound_alter() trick, but am curious whether it can be done directly.  For the purposes of this question, I can't use path aliases.

Would love to be proven wrong, but I don't think that's easily possible using hook_menu().

Core only considers / as a separator, and matches on string, so urn:, urn:myscheme and urn:myscheme:foo:bar:12345 can only be represented as completely different paths.

The guts of it happens in menu_get_item():

$original_map = arg(NULL, $path);

$parts = array_slice($original_map, 0, MENU_MAX_PARTS);
$ancestors = menu_get_ancestors($parts);
$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

The call to arg() splits the path by /, which is hardcoded:

$arguments[$path] = explode('/', $path);

When menu_get_ancestors() returns for a path like urn/myscheme, it has two elements in the array: 'urn' and 'myscheme'. The same call for urn:myscheme returns an array with a single element, 'urn:myscheme'.

Those ancestors are used directly in the query to match the path in menu_router, so for the path urn:myscheme, you'll get this query:

SELECT * FROM {menu_router} WHERE path IN ('urn:myscheme') ORDER BY fit DESC

Try the same thing with urn:myscheme:foo:bar:12345, and as far as Drupal's concerned, it's a separate path that has to be handled by a different router item, as the query will be:

SELECT * FROM {menu_router} WHERE path IN ('urn:myscheme:foo:bar:12345') ORDER BY fit DESC

Without resorting to replacing menu.inc (which I think is pluggable if I remember rightly), hook_url_inbound_alter() will probably be the best best.


Responsive image style with srcset and without sizes Using this tutorial for example I found out how to use responsive image styles in Drupal 8 without <picture> (which is pretty straight forward anyway).

However this approach forces you to use sizes. The article says

  The default here 100vw is hard-coded for a good reason, it's a pretty sane default and works well in most situations.

which I completely disagree with. I find that in most cases you simply want to provide higher resolution images of simple s for devices with a dppx that is greater than 1.

So how do I achieve something as simple like

with responsive image styles in Drupal?

Define your own breakpoints group with "multipliers" settings in YOURTHEME.breakspoints.yml  (see D8 Docs)
Go to Admin > Configuration > Media > Responsive Image Styles and add a new image style.
When creating the responsive image style, select your breakpoint group created in (1.). When your YAML is correct, you should see a separate detail set for every multiplier (=dppx).
Select type " Select a single image style." and select your corresponding image size. Repeat for every DPI group defined in your breakpoints.yml
In your node's display settings, for your image field, select the responsive image formatter and choose your responsive image style created in (2.)


Ways to speed up a simpletest? I'm trying to speed up my test.
I have to use simpletest_clone.
I've read something like "copy the database to memory" but i did some research and didn't found how.
Aaand if i want to do more than one test with the same database there is somehow a thing that let you use the same database cloned for the first case i tested to be still loaded to run the next test case?
because if i want to run 4 or 5 test case using simpletest_clone it may take years if i let it clone and drop the database for every case

There are few ways of speeding up the Simpletests:

Consider upgrading your PHP to >5.5 with cache benefits of OPCache.
For PHP <=5.5 try to implement PHP caches such as XCache, APC, eAccelerator.
Install and configure memcached.
Patch your Simpletest to exclude testing of disabled modules.

See: Tests of disabled modules shouldn't be parsed, Strengthen tests by not autoregistering non-test namespaces of disabled modules
Use SimpleTest Clone

(consider patching the module to exclude some big tables while cloning).
Optimize your MySQL instance e.g. via MySQLTuner-perl.
For sites that have lots of slow queries, disk access is often the bottleneck. So speed up by moving MySQL temporary directory to tmpfs., How to setup mysql on tmpfs?
Test only specific Simpletests groups that you need.

Other option to consider:

Try to identify the bottleneck and upgrade your hardware.
Break down simpletests into groups and run on separate machines.
Forget about the speed by integrating Simpletests with Continuous integration (CI) such as Jenkins, Travis CI, AWS, etc.
Use alternative test frameworks (e.g. PHPUnit), see: [meta] Replace the testing framework with PHPUnit and possibly rewrite Simpletest.

Use alternatives:

Behat (recommended)
PHPUnit (which has been added to Drupal 8)
Selenium web driver or Selenium IDE (which is slow as well:)


Set title bar programmatically I have to set, programmatically, the title value of pages, only for browser title bar (this value is stored in a metatags_quick field)
If I use "drupal_set_title" I change also the title displayed in page, I've only to change the window title.

You can use hook_preprocess_html() to override this value:

function MYTHEME_preprocess_html(&$vars) {
  $vars['head_title'] = 'Some other title';
}

The title for the content won't be affected by that, just the <title> tag.


theme_hook_suggestions and tpl.php if ($variables['node']->type == 'netrunner_card' && $variables['view_mode'] == 'full')
{
    $blinksFileName = $variables['node']->field_card_type['und'][0]['taxonomy_term']->name;
    $blinksFileName = str_replace( " ", "_", $blinksFileName);
    $blinksTemplateName = 'node__netrunner_card__' . $blinksFileName . '__full';
    $variables['theme_hook_suggestions'][] = $blinksTemplateName;
}

I can't get the tpl to load! Ive got two tpl files currently for two types of cards.

'node--netrunner-card--Runner-Identity-Card--full.php'
'node--netrunner-card--Operation--full.php'

and I even tried:
'node--netrunner-card--Runner_Identity_Card--full.php'

Nothing. I'm so confused at this point I don't know where else to go...
Any help would be appreciated.

The solution was to rename my template files so that the extension was tpl.php instead of just .php. Once I renamed the files to add the tpl the files started working instantly.


Only show block if View or nid has certain term referenced to it I have a tricky one here and looking for some suggestions.

I have a Page view which uses a contextual filter on the nid (which is in the URL).

These nodes have a term reference field which contain various terms.

I have a block which I only want to be displayed on this page if the node has this specific term referenced to it. Bare-in-mind this is not the actual node page, this a dynamically created page/view based on the nid in the url.

Did you try php code? If you enable 'PHP filter' module, you can add php code under 'Pages restricted to certain pages' option in block configuration and write your code like

<?php
$relative_path = request_uri();
if (some condition)   {

    return TRUE;
   }

 else
    return FALSE;

?>


How does Drupal 7 determine the output of user menu? I have the built in User Menu being displayed in a region of my template with the following code:

render($page['user_menu']);

Drupal seems to automatically handle where thsis should be output. Generally it outputs in the /user/* pages.

However, I have recently started working on a custom module that had added a new menu item to /user/my_module but when I visit the page the User Menu is not displayed.

Could someone tell me how Drupal manages the output of the User Menu or possibly how to get it to display on this page/path?

You need to set menu_name for your menu item to user-menu, see userpoints_menu() for an example (the myuserpoints menu item).


Is there a way to get a value of a multi value field of an entity reference (reference a field value of a referenced term)? I hope that maybe someone had a similar use case and has an idea how to solve it: I have content type that has an entity reference field to a vocabulary. With that I would like to achieve it to not only reference to the term itself in the manage display (in my case a country name), but also choose a certain value of a multiple value field of that term (one of the several historic names of that country). I created a hack with an additional list field in the content type (choose historic name 1, 2, 3...), but this is no good solution because as soon as I modify the order of the field items (e.g. because of adding one), the name is displayed wrongly all over the website. So there is the need to directly reference the field value of the referenced term itself.

You can do this in a custom field type based on the core reference field, adding  a second property and dynamically filling the options of the select list depending on the first property.

For the multi-value part of your question a non-coding solution would be a paragraph containing both fields. Adding the dynamic behavior can then be done in a form alter hook or you can try Business Rules and adjust this recipe to your requirements: https://www.drupal.org/docs/8/modules/business-rules/advanced-usage/dependent-field


change the language of my main page I have a website http://www.apisnatura.com  with the modulle MULTILINGUAL - INTERNATIONALIZATION.

I manage to create the pages of each language and when i click any language icon the main menu changes and the rest of the pages also change.

My question is... how do i change the main page content after clicking the different language icons with the relevant language.

I been looking around and i am getting crazy looking for a solution.

Any help will be great to carry on changing the content for this web.

Cheers

Check if you have activated these modules.
Views translation and  Block languages (i18n_block).

Then You need to change those blocks language settings in configuration. follow this: https://www.drupal.org/taxonomy/term/39286

tick "make this block translatable" and select the languages.
it will allow you to translate a block in to a language you want. you might need to create separate blocks for each language.

In a View check if "Field Language" selected as "Current user's language" in Advanced area.

also use a filter for the view "Content: Language (= Current user's language)"

This will populate the content by detecting the users selected language.
"


How to pass an array or an object from a module to a theme I have used hook_menu() with a page callback as follows:

function profilecb_menu() {
  $items['profilecb'] = array(
    'title' => 'Profile CB',
    'page callback' => 'pcb_exe',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

The callback code is the following:

function pcb_exe($id) {
  $ar = array('arg1'=> 'value1', 'arg2'=> $id);

  return $ar;
}

I have been able to make the callback function return a single string; when I try to return an array, I get an error.

All I need to do is to make the callback function do some tasks, like connecting to the database, and return to a template a complex array of useful information.

How can I do that?

In Drupal 6, a menu callback needs to return a string that contains the HTML to output together the output of other modules; alternatively, it can print the output and call exit().

If you need to pass an array to a theme function, then the output returned from the menu callback should be output from a theme function to which the menu callback passes an array.

function pcb_exe($id) {
  $ar = array('arg1'=> 'value1', 'arg2'=> $id);
  return theme('pcb_exe_output', $ar);
}

In Drupal 7 (and higher versions), the output of a menu callback is normally an array that has the format used by drupal_render().
It still possible to pass an array to a theme function, but the parameters passed to a theme function changed.

function pcb_exe($id) {
  $ar = array('arg1'=> 'value1', 'arg2'=> $id);
  return theme('pcb_exe_output', $ar);
}

In this case, there is no noticeable difference, as the parameter passed to the theme function was already an array.
The parameter passed to a theme function since Drupal 7 is an array containing all the values required from the theme function. See the code of theme_vertical_tabs() as example:

function theme_vertical_tabs($variables) {
  $element = $variables['element'];
  // Add required JavaScript and Stylesheet.
  drupal_add_library('system', 'drupal.vertical-tabs');

  $output = '
' . t('Vertical Tabs') . '
';
  $output .= '
' . $element['#children'] . '
';
  return $output;
}


Use Url Argument in contextual filter for Block View I have a View which uses contextual Filter to compare my URL last Argument with Taxonomy term. This Works when my view is Page but doesn't work in block mode. This is my View Below.

Attaching my view and Site Description along this.
My Pdf Category View is placed as a block.

When I Preview by entering the brand name emax in the view, it give me proper results but it doesn't fetch from url(RAW Value from URL). Correct me if i failed to mention anything wrong.

I found the solution for this issue. I used PHP code by selecting "Provide Default" and Select PHP code as below to extract arguments from URL and provide a filter to your view.

$path = drupal_get_path_alias();
$path = explode("/", $path);
return $path[2] /* Since explode function return array of url arguments, select required arguments starting with 0.*/


Strategy for deploying Panels with features I've been exporting Panelizer configuration to features and pushing up to production.  My strategy so far has been:

Config is created on local and pushed up via features
Content, such as Fieldable Panels Panes instances are created directly on production.

However, this is now causing issues.  When I revert a Panel/Panelizer feature, it reverts back to my local settings and removes any content panes I've added on production.

A couple of ideas I have for managing content panes:

Use UUID features to push up any content panes.  Trouble with this is that the content panes are now in the dev/stage/live workflow and any changes on production will be reverted with the next drush fra.
Pull down a fresh copy of the database before doing any further edits to a feature, that way when a feature is recreated on local, it will contain the new content panes.

How do you manage content panes when using features?

We have very similar problems - not only with features but in other areas as well. The best solution we came up with so far is close to your second one:

Drupal 6 & 7 - Yin/Yang Multisite Staging
https://www.drupal.org/node/942540

So here you'd switch with the new DB version into the Staging system and use the Staging as the new Live version. But I don't feel too comfortable about this + it might not work everywhere if the two Servers are different.

In a way less complex evironment with small changes I'm doing the following: Every night the DB will be copied from Live to Dev. In this environment I'm sure I only have small changes in Dev which take usually minutes to an hour max. and I've got a fresh DB every day and can start from there.


Permission Issue with created actions and VBO I’ve created a new action in a custom module using hook_action_info()

/**
 * Implementation of hook_action_info().
 */
function recruiteractions_action_info() {
  return array(
    'applicationentity_recruiterfillposition' => array(
      'type' => 'application', // <-- New entity type here
      'label' => t('Application Postion Fill Action'),
      'behavior' => array('changes_property'), //<-- Triggers an entity save.
      'configurable' => FALSE,
      'vbo_configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}
function applicationentity_recruiterfillposition(&$entity, $context = array()) {
  $app_wrapper = entity_metadata_wrapper('application', $entity);

 $app_wrapper->field_job_status->set(‘1');
 $app_wrapper->save();

}

After enabling in VBO this all works fine and as it should.  The issue being when i set this to the role I need it to be set on.

the ‘Actions permissions (VBO) module is activated. and I can see the action; and have ticked the roles needed but with no joy.

I’ve also checked the ‘field_job_status’ permissions for the role I wish to allow to make changes.

On Drupal hook_action_info page https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_action_info/7  there is a post regarding 'behavior's impact on permissions and specifically mentions VBO.  however I'm not sure on what I need to do.  Has anyone got any examples for this.

The solution here was to set the permission I want in the access_callback of the custom entity itself.

so in my case the hook_entity_info

'access callback' => 'myentity_access_callback',

then added this in a function

function myentity_access_callback($roles = array()) {  // $op, $application = NULL, $account = NULL
 global $user;
 $roles = array(
   'administrator', 'anotheradminrole',
 );
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}


Trying to migrate user data into multi value term reference field FYI: I'm using the module Migrate 7.x-2.5

I'm trying to migrate users from a custom built PHP website, backed by a mysql database, into Drupal.

Each user can have multiple statutes assigned to him. In the source database I have a table 'users' with a column 'stat_id'.

+---------+---------+
| user_id | stat_id |
+---------+---------+
|       1 | ;2;     |
|       2 | ;26;    |
|       3 | ;3;     |
|       4 | ;27;28; |
|       5 | ;19;2;  |
+---------+---------+

The name of the statutes is stored in the table 'users_statuut'.

+---------+----------------------------+
| stat_id | statuut_nl                 |
+---------+----------------------------+
|       1 | Doctoraatsstudent          |
|       2 | Postdoctoraal onderzoeker  |
|       3 | Administratieve medewerker |
|       6 | Diensthoofd                |
|       7 | Laborant                   |
+---------+----------------------------+

In Drupal I created a term vocabulary 'statutes' with the names of all the statutes.
And I added a term reference field to the user profile that can select multiple values from this vocabulary.

What I can't figure out is how to migrate the data from the source table into Drupal.
I've already managed to migrate simple fields like username, email, password,... so that's working, but I have no idea how to get the statutes into the term reference field.

Any help is really appreciated.

Use a callback with a separator to transform the source value to the destination value. For example:

  $this->addFieldMapping('statuut_nl', 'stat_id')
   ->separator(';')
   ->callbacks(array($this, 'computeValue'));

  protected function computeValue($value) {
    $allowed_values = array(
      2 => 'Postdoctoraal onderzoeker',
      ...
    );

    return ($allowed_values[$value]);
  }


How to Skip the Workflow Launch by admin/user in Drupal-Commons using Maestro Module? I have installed and configure the "Maestro" Module in Drupal Commons.

In Maestro Module every time we should Load the Workflow and it will go through step by step:

Admin: Publishing Workflow Load
User1: Assigend to add new Content
User2: Review Content
User3: Publish Content

How can I remove first step? When user creates new content, it should automatically go for review.

My Workflow

Using the rules module Can I define any rule when New Content is created means click on "Add Content" Workflow automatic Load....

A solution we have used where we needed to have a menu item launch a workflow for expense approval using an entityform. The menu URL just needed to pass in the maestro workflow template_id

The callback function for the menu hook launches the workflow and then executes past the START task in the maestro template, to the first interactive task for the user (fill out form). It redirects the user to the task console and automatically opens the expense form to be filled in. The following code can be added to a custom module and re-purposed for your use.

/**
 * Implements hook_menu()
 */
function MODULE_NAME_menu() {
  $items = array();

  $items['pi_workflow/launch_eform'] = array(
    'title' => 'Launch Entityform Workflow',
    'page callback' => 'nextide_launch_eform_workflow',
    'page arguments' => array(2) ,      // Passing in wildcard which should be the maestro workflow template_id
    'type' => MENU_CALLBACK,
    'access arguments' => array('maestro taskconsole')
  );

  return $items;
}

/* Launch an entityform workflow where the first task
 * after the start task is the entityform task.
 * User will be redirected to the taskconsole and launch the first task (open form for editing)
 */
function nextide_launch_eform_workflow($template) {
  if (intval($template) > 0) {
    $sec_token = drupal_get_token('maestro_user');
    $new_process_id = maestro_launch_workflow($template, $sec_token);

    // Run the orchestrator to execute the first task after the start task which is the interactive entityform task
    maestro_orchestrator();
    $maestro = Maestro::createMaestroObject(1);
    $process_data = $maestro->engine()->getQueueHistory($new_process_id);

    $task = MaestroTask::createTaskObject($process_data[1]->id);
    $data = $task->prepareTask();
    $task_data = unserialize($data['serialized_data']);

    // Default will be to redirect user to the task console unless overlay module is available
    $link = 'maestro/taskconsole';
    $options = array();
    // Test that we have valid process data and then test for the task we are looking for to get the task id
    if (is_array($process_data) AND isset($process_data[1])) {
      // If overlay module is enabled and user has overlay permission, open entityform up in overlay
      if (module_exists('overlay') && overlay_get_mode() ) {
        $options = array('fragment' => "overlay=eform/submit/{$task_data['entityform_id']}/maestro/" . $process_data[1]->id);
      }
    }
    drupal_goto($link, $options);
  } else {
    drupal_set_message(t("New Process Code FAIL! - No Template ID Given"));
  }

}


Content not displaying for anyone other than Admin I have a problem with Drupal 7. I recently set up Context module to display some blocks on given conditions and everything seemed to be fine. However, when I logged out every text in a block within a Mini panel disappeared on front page, and on every internal page content body (title still visible) is gone too.
I flushed the cache several times. In permissions anonymous and other users have "view published content"(this is a lazy translation from french) enabled. In didn't apply any kind of user role condition in Context, nor do I have any css/js error in console. Other than those which are only alerts:

Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead[En savoir plus]jquery.min.js:1
L’utilisation de « getPreventDefault() » est obsolète. Utiliser « defaultPrevented » à la place.

Please help me through these darks times...I'm running out of options
Thx in advance

Ok,
So...In fact I verified the permissions of a body field of a block within a mini panel (yeah right...) and there were no permissions for anonymous user to view. So I checked that for only one block and somehow it all went right without changing anything else. So there's that.

Thx anyway for your precious time.


Use selected NID from Entity Reference field to populate second Entity Reference field I have three content types:

organization profile
internship posting
hours submission

The 'hours submission' content type has two entity reference fields:

Entity reference for 'organization profile' nodes
Entity reference for 'job posting' nodes

I'd like to pass the NID from the first entity reference such that the second entity reference is filtered (only shows nodes that are associated with that NID).

The 'job posting' content type is tied to an 'organization profile' via an entity reference field.

Any help or guidance would be appreciated.

My solution is to:

Pre-populate and disable the first entity reference field with a node ID
Add an extra path component with the same nid and have the second field use an entity reference view with default: Path Component 4

So the URL looks like /node/add/hacky/123?field_solution=123.

While hacky, it has uses, especially if you want to filter fields that don't have a connection. In that case the URL could be /node/add/hacky/123/456?field_solution=789.


How to get a field value of custom block? I have a custom block type, called "Features block". I added a field as alternative title (field_block_alt_title is that machine name).

I would like to display this alternative title on frontpage programmatically.

Now, I have this code so far that is displaying the title of blocks:

<?php

use Drupal\Component\Utility\Html;
use Drupal\Core\Render\Element;

function neft_preprocess_region(&$variables) {
  if ($variables['region'] == 'flick') {
    $titles = array();
    $ids = array();
    $block_ids = Element::children($variables['elements']);
    foreach ($block_ids as $block_id) {
      $block_title = Drupal\block\Entity\Block::load($block_id)->label();
      $titles[] =  Html::escape($block_title);
      $ids[] = 'block-' . Html::getUniqueId($block_id);
    }
    if (count($titles) && count($ids)) {
      $tabs = '
';
      foreach ($titles as $key => $title) {
        $tabs .= "
$title
";
      }
      $tabs .= '
';
      $variables['tabs'] = $tabs;
    }
  }
}

Fields of custom blocks are in block content. So you have to load the block content first, before you can get the field value:

$block = \Drupal\block\Entity\Block::load($block_id);
$uuid = $block->getPlugin()->getDerivativeId();
$block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);
if ($block_content) {
  $field_value = $block_content->field_block_alt_title->value;
}


Menu with argument from views I want to create menu block for each user on sidebar.
In it there would be links like Videos, Images, Bio.

So i made view with argument and url is usertype/%/videogallery

It is working fine, but how can i add this as a menu item so when someone visits user3 profile the url in the block menu is leading to Videos, Images Bio with url usertype/user3/videogallery

Just use views to create a block with your "menu" links and then make it show up in the sidebar for all "usertype/" and "usertype//*" pages.

That view will also need a contextual filter "userid from url" similar to your other view. You can "rewrite the url" to create the links.


Drush enable/disable Devel modules I love admin-menu's Enable Developer Modules menu item.  How can I toggle this from the command line?

Admin menu already has a configuration of "developer" modules set up in settings.php.
I can access this array with drush vget admin_menu_devel_modules (well sort of, that returns two entries).  Now I want to 'pipe' those items to drush enable.  I know that's not literally possible but this is my thought process.

How can I script this command?

I prefer to have a custom module that has dependencies for all the developer modules I need. I also set up this module to have some strongarmed variables (such as turning off preprocessing of css/js and any page caching), and enables a few developer blocks using Context (such as execute php and context inspector). This allows you to simply drush en/dis the one module to turn on/off all of your developer utilities.

Here's my Lullabot devel module that you can look at for an example.


how can i add user avatar to admin menu What function do I need to use for adding the image in the admin menu?

Above menu is rendered from toolbar.tpl.php inside toolbar module.

All you need to is override above toolbar.tpl.php by copying it to your themes folder and modify code to add image.

<?php

/**
 * @file
 * Default template for admin toolbar.
 *
 * Available variables:
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. The default value has the following:
 *   - toolbar: The current template type, i.e., "theming hook".
 * - $toolbar['toolbar_user']: User account / logout links.
 * - $toolbar['toolbar_menu']: Top level management menu links.
 * - $toolbar['toolbar_drawer']: A place for extended toolbar content.
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_toolbar()
 *
 * @ingroup themeable
 */
?>
<div id="toolbar" class="<?php print $classes; ?> clearfix">

    <?php print render($toolbar['toolbar_home']); ?>
    <?php print render($toolbar['toolbar_user']); ?>
    <?php print render($toolbar['toolbar_menu']); ?>
    <?php

    $variables = array(
      'path' => 'path/to/img.jpg',
      'alt' => 'Test alt',
      'title' => 'Test title',
      'width' => '5px',
      'height' => '5px',
      'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
      );
      print theme_image($variables)?>
    <?php if ($toolbar['toolbar_drawer']):?>
      <?php print render($toolbar['toolbar_toggle']); ?>
    <?php endif; ?>

  <div class="<?php echo $toolbar['toolbar_drawer_classes']; ?>">
    <?php print render($toolbar['toolbar_drawer']); ?>


How to rewrite paths delivered by solr search (to view instead of node) How can i rewrite the path of results delivered by solr search? Or is it possible to configure it the way i need?

The content of that particular website is organized in views. I do not want users to navigate to the node-view mode of the content, instead i want to redirect them to the specific views-page. Is there a way to show only views-pages as search-results? Or do i have to rewrite the links somehow?

If you're using Apache Solr Views, or Search API Solr Search with Views, you can re-write the field in the usual Views way. Otherwise, you may need to fiddle with the search result template in your theme, which I realize is ugly.

A better choice would be to override the node display entirely, for example using Panels and creating a Page at node/% that overrides all node display for the appropriate content types. You can then customize the presentation of your nodes using Views that take the current node ID as an argument. This sort of thing is also possible using Display Suite, although that's a more complex solution. If you really always want people to see your node as presented by a View, you may as well solve this directly instead of by tweaking the search results.


Adding functionality to a form button that would load user details / corresponding field data for "autofill" I have a form that has a address field holding inputs for:
name
address
phone etc.

I've added a button on this form/field: Load my data which I would like to load user details/data.
On click it should load a corresponding address field from user's profile by ajax and use it to fill in form fields.

Form can have multiple address fields so it should know which address field needs to filled with user data.

Button isn't shown to anonymous users of course.

Take a look at how Commerce Addressbook solves these same requirements: https://www.drupal.org/project/commerce_addressbook.

There is a demo video on the project page: https://commerceguys.com/blog/commerce-module-tuesday-commerce-addressbook.

I think if you dig through the module code of that module, you'll find all the logic and code examples you'll need to pull off a similar solution on your custom form.

If you want to see this in action on a local setup, I recommend installing commerce kickstart with commerce addressbook to see how the addresses are organized.

Good luck, Jason


Print author details for a node How do I print the author details for a node? In particular, I am interested to the following values.

Author picture
Name
Description

In Drupal 7, I would use this code.

<?php print $author_data['picture'];?>
<?php print $author_data['name']; ?>
<?php print $author_data['description']?>

What is the equivalent in Drupal 8?

This is what worked for me in the node template for any custom field:

{{ node.uid.entity.field_name.value }}

I'm using Drupal 8.3.7

EDIT:
This is what I'm doing for the profile picture.
I'm creating a rendering object so I can specify a theme and an image style:

            {% set imagestyle = {
              '#theme':      'image_style',
              '#style_name': 'user_avatar_80x80',
              '#uri':        node.uid.entity.user_picture.entity.uri.value,
              '#attributes': { class: 'authorImg' },
            } %}

{{ imagestyle }}


Do You Implement hook_help()? How should I implement hook_help()?  Should I output the content of the README.txt file, or inline text?

I think this really depends on what you need.

For page specific help, returning translated text does appear to be the norm from the modules I have surveyed, and does follow the Help text standard (for core and contrib).

For the text on the admin/help page, I think that using the README.txt is best, since that should really be a "one-stop-shop" for help with the module, and you don't want to have to track your changes in two places.  It is also a pain to format that much text with code.  However, this does make translation hard.

I have not seen a "standard" way to handle the README.txt.  If you look at the Module documentation guidelines, they give this example for Drupal 6:

function mymodule_help($path, $arg) {
  switch ($path) {
    case 'admin/help#mymodule':
      // Return a line-break version of the module README.txt
      return filter_filter('process', 1, NULL, file_get_contents( dirname(__FILE__) . "/README.txt") );
  }
}

and there is a comment for a Drupal 7 version:

function mymodule_help($path, $arg) {
  switch ($path) {
    case 'admin/help#mymodule':
      // Return a line-break version of the module README.txt
      return check_markup(file_get_contents( dirname(__FILE__) . "/README.txt") );
  }
}

Personally, the version I like what Features does:

function features_help($path, $arg) {
  switch ($path) {
    case 'admin/help#features':
      $output = file_get_contents(drupal_get_path('module', 'features') .'/README.txt');
      return module_exists('markdown') ? filter_xss_admin(module_invoke('markdown', 'filter', 'process', 0, -1, $output)) : '<pre>'. check_plain($output) .'</pre>';
    // ...
  }
}


How to use date_make_date() in drupal 7? I am porting custom module from drupal 6 to drupal 7
I have the following code:

 $local_date = new DateTime($dateTxt);
 $iso_date_string = date_format_date($local_date, 'custom', 'Y-m-d\TH:i:s');
 $utc_date = date_make_date($iso_date_string, $user_timezone_name, DATE_DATETIME);

What can be the alternative for date_make_time() in drupal 7?

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

  this error is due to a change in the Date API module, instead of
  date_make_date you need to use the new DateObject class. see "D7
  Changes" here: http://drupal.org/project/date

  I fixed this as follows, but not sure if I'm using the DateObject
  properly.

  Edit this block of code in agenda.module, line 354

  // If the Date API is installed, we can do better at DST times   if (module_exists('date_api')) {
    $start               = date_make_date($event['start timestamp'], NULL, DATE_UNIX);
    $event['start time'] = date_format_date($start, 'custom', $block->timeformat);
    $end                 = date_make_date($event['end timestamp'], NULL, DATE_UNIX);
    $event['end time']   = date_format_date($end, 'custom', $block->timeformat);   }

replace with

  // If the Date API is installed, we can do better at DST times   if (module_exists('date_api')) {
    $start               = new DateObject($event['start timestamp'], NULL);
    $event['start time'] = $start->format($block->timeformat);
    $end                 = new DateObject($event['end timestamp'], NULL);
    $event['end time']   = $end->format($block->timeformat);   } alternatively, just comment out the whole block.

I looked in the above node but not sure about the new DateObject() ?

new DateObject()

The alternative to the date_make_date function in D7 is the DateObject, which extends the PHP DateTime class.

To make your code work properly, you'd do something like this (untested):

$local_date = new DateTime($dateTxt, $timezone); //$timezone can be string or object
$iso_date_string = $local_date->toIso(); //returns the ISO string for the date
$utc_date = clone $local_date; //don't want pass by reference
$utc_date->setTimezone(new DateTimeZone('UTC')); //set the new timezone to return
$utc_date_iso = $utc_date->toIso(); //returns $local_date converted to UTC as an ISO string.

I'm not totally sure what you want to do, but this, hopefully, will get you on the right path.


$form array in views-exposed-form.tpl.php has #printed set to true? I'm not doing anything to it in any other functions, but every #printed is set to TRUE when it reaches the .tpl. Any ideas why this is?

#printed is set by drupal_render, so if the actual form element is rendering into a string the $form has #printed, try it out on any other drupal form theming.


How to insert user registration data to non-drupal table I installed drupal 7.34 with oracle database. Now i need to save user registration data to another non-drupal table. User authentication also need to do with these non-drupal database field. Is there any method to generate the per-existing set of users in non-drupal database as drupal users.

This looks similar to what happens when someone tries to access CiviCRM tables from Drupal when the CiviCRM tables exist in different database containers.

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

Are these tables in the same database container or just on the same database server?

You may want to look at How to use separate databases for Drupal tables?

It might also be worth looking at http://wiki.civicrm.org/confluence/display/CRMDOC44/Creating+a+Drupal+user+for+every+CiviCRM+contact

That gives both a manual process of generating Drupal users from a CSV export as well as the drush method.


How to remove block from the page based on cookie value? We have a block (myblock) that is only displayed on 4/5 content types. When a cookie, mycookie, is set and has a value of allow, I want to load the block on the page, but if the value is not set to allow, then I want to remove it from the page. The cookie is set through a third party Javascript library.

How to remove block based on cookie value?

Setup:

Under block layout, we load the block on 4/5 content types.
Using twig template (myblock--name.html.twig), we add some css to the myblock

I'll assume this is not a block plugin, right (or at least you dont have access to modify it)? If it is or you can modify it, you should add the logic below to your build() method inside your block class.

Is the cookie you're looking for generated from Drupal? Assuming it is, you should be able to do something like this:

HOOK_preprocess_block__myblock__name(&variables) {
  if (!\Drupal::request()->cookies->get('mycookie') == 'allow') {
    $variables = [];
  }
  // Don't forget about cache context for cookie!
  $variables['#cache']['contexts'][] = 'cookies:mycookie'
}


how to prevent a theme from using templates of a sub themes (placed inside the parent theme dir)? my folder structure looks something like this:

 themes
└─  foo
   ├─  bar
   │  ├─  templates
   │  │  └─  node.html.twig
   │  └─  bar.info.yml
   ├─  templates
   │  └─  page.html.twig
   ├─  foo.info.yml
   └─  foo.libraries.yml

now I run a multisite. one site is using the foo theme and the other uses bar.

The site using the foo theme also invokes the template
/theme/foo/var/templates/node.html.twig

Why is that so?
I thought the foo theme only invokes templates inside its own templates folder? I expected this to be the point of the templates folder. Is that assumption wrong?
can I prevent this behavior without moving the subtheme somewhere else?

Themes are not allowed to be placed inside one another, as oppose to modules. Even though it works, there are undesired side effects.


What is the best (secure) way to run PHP code on a Drupal 8 system? I am pretty new with Drupal. I have installed Drupal 8.17 on my webserver and now I am configuring it.

It runs on Ubuntu 16.04 with Apache 2.4 and PHP-7.0, the DBMS is PostgreSQL 9.5.

I would like to execute some PHP code is some pages. I have read that there was PHP Filter in Drupal 7, but it is now moved to modules and it warns user than:

  Warning
  Enabling this module can cause security and performance issues as it allows users to execute PHP code on your site.
  There are better alternatives out there that do not expose such vulnerabilities on your site.

But I cannot find any alternative over the web. Then I found Drupal SE, and I am asking for user advice: What is the best way (I mean secure way) to run PHP code on a Drupal 8 system?

I must connect another PostgreSQL DB, perform query on it and display results in Drupal. Essentially this will be done in pages that only administrator can read an modify.

Some Drupal devs are keen on never putting PHP code in the Database, but this means you will have to know the intricacies of Drupal 8 in order to figure out how to expose what you need by creating a custom module. This can be a time sink if you just want to do something super simple.

But if you aren't that hardcore, turning on the PHP is fine if you just don't have the time or need to create a custom module to say print something out from the $user array.

I personally just use the PHP module on my sites. It's quick and efficient vs making a custom module. Obviously deciding on which approach to take depends on the site and client your working with. Does it have valuable user data? Does it have millions of user hits a day? Or is it just a purely informational site with only a few hits a day? Do you think the client would mess around with other parts of the site or are they just purely just updating content?


Argument 1 must be an instance of Drupal\tcdev\Controller\UserAuth, instance of Drupal\user\UserAuth given I want to programmatically log in a user with a custom controller. I want to pass my data with $_POST to the route (I pass data from a mobile application); if username and password are correct, the method/function should return TRUE.

The route is the following one.

tcdev.login:
  path: '/tclogin'
  defaults:
    _controller: 'Drupal\tcdev\Controller\MYCenterController::login'
    _title: 'Login call back'
  requirements:
    _permission: 'access content'

The code for the controller is the following one.

namespace  Drupal\tcdev\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyController extends ControllerBase {

    /**
     * \Drupal\user\UserAuth definition.
     *
     * @var \Drupal\user\UserAuth
     */
    protected $userAuth;

    /**
     * {@inheritdoc}
     */
    public function __construct(UserAuth $user_auth) {
        $this->userAuth = $user_auth;
    }

    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('user.auth'));
    }
    }

    public function login() {
        $uid = $this->userAuth->authenticate($_POST['user'], $_POST['pass']);
        $acc = User::load($uid);

        //return new Response('Hi ' . $uid);
    }

}

It returns me the following error:

  TypeError: Argument 1 passed to Drupal\tcdev\Controller\MyController::__construct() must be an instance of Drupal\tcdev\Controller\UserAuth, instance of Drupal\user\UserAuth given, called in /Users/yms/Sites/devdesktop/gttc/modules/tcdev/src/Controller/MyController.php on line 32 in Drupal\tcdev\Controller\MyController::__construct() (line 23 of modules/tcdev/src/Controller/MyController.php)

Where is my mistake?

Inject the user.auth in your controller:

$auth = $container->get('user.auth')

[edited to clarify injection basics:

In public static function create(ContainerInterface $container) add $container->get('user.auth') to the return new static(...) statement.

In public function __construct(...) add the $auth to the signature at the correct position. Then add a private (or protected) variable $auth to your controller and assign the value from __construct to it.

You may simplify that by using drupal console or drush. They can create the boiler plate code for you.

If you don't want to use injection, you may use $auth = \Drupal::service('user.auth');

But this has drawbacks in testability.

[end edit]

then call the authenticate func:

$uid = $auth->authenticate($username, $pass);

With the $uid load the user:

$acc = User::load($uid);

Then set the user into the session:

  \Drupal::currentUser()->setAccount($acc);
  \Drupal::logger('user')->notice('Session opened for %name.', array('%name' => $acc->getUsername()));

Should work. But I don't think that it is a good idea to pass around the password in the URL of your tcdev.login...

Edit: Sample Code (generated by drupal generate:controller)

namespace Drupal\preosuser\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\UserAuth;

/**
 * Class AuthController.
 *
 * @package Drupal\preosuser\Controller
 */
class AuthController extends ControllerBase {

  /**
   * Drupal\user\UserAuth definition.
   *
   * @var \Drupal\user\UserAuth
   */
  protected $userAuth;

  /**
   * {@inheritdoc}
   */
  public function __construct(UserAuth $user_auth) {
    $this->userAuth = $user_auth;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('user.auth')
    );
  }

  /**
   * Checklogin.
   *
   * @return string
   *   Return Hello string.
   */
  public function CheckLogin($name) {
    return [
      '#type' => 'markup',
      '#markup' => $this->t('Implement method: CheckLogin with parameter(s): $name'),
    ];
  }

}


How to implement view with nodes grouped per taxonomy term I have a content type 'Event' which has a 'Category' content taxonomy field (single selection against respective 'Category' vocabulary). If vocabulary has 3 terms, I want to implement a listing where all 3 terms will always be displayed, along with the newest event for each category (sort by publication date in descending order). Something like this:

Category 1

Title of newest event for category 1

Category 2

Title of newest event for category 2

Category 3

Title of newest event for category 3

What is the best way to implement this with views in Drupal 6?

You must use the group option in the style display. In group option you must select the field taxonomy term. And then you must Exclude from display the field taxonomy term.


What should be the path to the file while using #attached in a custom_module_block_view()? I have created a custom module and was trying to add javascript file to a block using #attached method which was described here. I am confused with the Path/to/file as I have tried to give a full path which is "/var/www/html/sites/all/modules/custom_module/js/file.js". and shorter path "js/file.js"

but it doesn't load.

It just say file_get_contents("/var/www/html/sites/all/modules/custom_module/js/file.js"): unable to load, no such file or folder present /var/www/html/common.inc .....

Why I am getting the file_get_contents error when I am not using this method?

You should use drupal_get_path() function to construct the path of your asset file (in your case the JS file).

To include the YOUR_MODULE.js file which sits in a subfolder js, part of your custom module

$block = array
(
    'subject' => t('My block title'),
    'content' => array(
        '#markup' => '<p>' . t('This is some text that will go in the block.') . '</p>',
        '#attached' => array(
            'js' => array(drupal_get_path('module', 'YOUR_MODULE_NAME') . '/js/YOUR_MODULE.js'),
        ),
    ),
);


Leaflet views: how to zoom on the marker while clicking on it in order to get the popup I am using the module Leaflet and its sub-module "Leaflet views"" in order to get a map displaying markers based on taxonomy terms.

I am able to show a popup displaying the term page while I click on a marker.

Now, my actual requirement is when I click on the marker, the map is zoomed on the clicked marker (zoom of maximum 3 levels) and just after the popup is displayed. So, my map behavior on the marker click event contains two steps: zooming and popup opening.

How can I hook the module in order to enrich my views?

Install and enable jQuery update. Set the jQuery version to >= 1.7.

Create a module, then create a zoom.js JavaScript file and paste this:

(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      $(document).bind('leaflet.feature', function(e, lFeature, feature) {
        lFeature.on('click', function(e) {
          var lMap = Drupal.settings.leaflet[0].lMap;
          lMap.setView(e.latlng,8);
        })
      });

    }
  }
})(jQuery);

Use your module name instead of MYMODULE

Then use drupal_add_js() in your module to include zoom.js. Note the weight option:

  drupal_add_js(drupal_get_path('module', 'MYMODULE') .'/zoom.js',array('group' => JS_DEFAULT, 'weight' => -5));


Drupal 7 comments spam with Captcha installed I have a multilanguage - multidomain website developed in Drupal 7, and the database have been flooded with spam comments, even if I have Captcha module (image) installed. The spam comments are from 60 different IPs, and I have seen attempts to add node and add user (which is blocked) in the incidents reports.

So I cannot block so many IPs at the risk of them being dynamical and loosing potential users.

What could I do to prevent the spam and also to prevent the attacks? Thanks

"to prevent the attacks" - not much can be done here. If an attempt to access node/add page ends with access denied page, its ok. You cant prevent users from entering urls in their browsers.

As for spam in comments, try some different modules for Captcha (Google reCaptcha with noCaptcha for example).
For different aproach, Honeypot can help limiting "robots" behavior.


How to access a custom field in a field twig loop? I have a content type article which have a field repeatable "related content"

I use a field twig where I have this  loop

{% for item in items %}
    {{ item.content }}
{% endfor %}

It works very well : it displays title of the article and a link to the content.

I would like also to display some subfields associated with this content but I'm not successful.

I’ve tried things like  :

{{ item.content.field_date_mise_a_jour_article.value }}

but obviously it doesn’t work. item.content only contains url and title.

How can I do that ?

In node--article.html.twig, i can access the related content subfield like that :

{{ node.field_suggestion_articles.entity.field_date_mise_a_jour_article.value }}

How can I do the same in

field--field-suggestion-articles.html.twig

As you are creating the twig template for a field and try to access the fields / data that is not available, you can write your custom code in preprocess function and you should use the template_preproces_field and create custom variable with desired data and use that variable in custom twig template.

In preprocess function

$variables['myVariable'] = 'My Desired Data';

In Twig use the variable which will print 'My Desired Data'

{{ myVariable }}


working with LDAP authorization hook While I have been able to use the LDAP authentication hook
(hook_ldap_authentication_allowuser_results_alter) to perform additional authentication,
I have not been able to use what I thought was the LDAP authorization hook
(hook_ldap_authorization_maps_alter, defined in the LDAP authorization module, file ldap_authorization.api.php) - the hook never gets executed.

The purpose is to assign user roles to newly created, LDAP-authenticated accounts (therefore I need a Drupal ID). We can't currently use LDAP-Drupal user role mappings because our LDAP does not contain the necessary information to determine the role; instead we need to tap a different database to determine this, and I was hoping that there would a hook somewhere during account creation.

I've been down this route a few times (looking at using LDAP integration module) each time I ended up writing my own LDAP integration.  Everyone implements differently, I just take the pieces I like from the LDAP module out there (6 or 7) and use your own code to do it.  As a general rule, anytime the rubber hits the road with integrating Drupal with user authentication / authorization systems in an organization I brute force them together via a custom / forked module.  You'll always know your own auth system's specific needs, D.O. will not :)


Exporting webform information programmatically I have a Drupal site that uses the Webform module. It has many options for downloading the results via the Drupal interface but it doesn't have anything out the box to get the data programmatically (JSON ect).

Is this possible? Authentication will still be require i.e only Drupal users for the site should be able to access this information via the JSON request.

You might have to create your own.
It would probably be worth submitting back as a new module too.

All you would have to do is implement hook_menu() to add your menu callback.
In hook menu you can set access arguments to make sure no one case use it unless they have a particular permission.

You can add your own custom permission using hook_permission().

Then the callback function could use webform_get_submissions() to load the submissions for a given webform and return them using drupal_json_output()

You could pass in a webform nid argument either via the url, using something like 'get-webform-submissions-json/%node' as your menu path, which would automatically validate the nid and load the node for you. For more information on that see http://drupal.org/node/224170
You could also just pass it in as a query parameter and use $_GET['nid'] in your callback function, however then you need to validate it yourself.


corresponding textbox for each user reference item I have a special node type [I call it members] that includes a user reference field. The amount of user references that can be added to each members is unlimited.

But I need to add an extra information for each user that is added to each members node.

I am searching for a solution to put a text box input beside the node reference auto complete input.
I mean each auto complete user reference field has a corresponding text box input.

Even when the manager click on add another button and new auto complete line is appeared at the end of rows, the new corresponding text box input must be located beside it.

Please help me

How can I do this.

I'd use field collections.
In your members content type, create a field (say members collection) with multiple values. Then proceed to the field collections admin and add:

the user reference field
the textbox field

These two fields while creating the content type will now be 'one' with an 'add more' button under each.


How do I turn off notices only? I want to show only warnings and errors but I want to turn-off notices. How can I turn off notices?
In my settings.php, I have this code:
$config['system.logging']['error_level'] = 'verbose';

What value should I put there?

This configuration aligns with the options at Manage > Configuration > Development > Logging and Errors (/admin/config/development/logging).
There are 4 error level options available. The levels with their corresponding values, i.e. the actual value for $config['system.logging']['error_level'] are:

None: hide
Errors and warnings: some
All messages: all
All messages, with backtrace information: verbose

For example, to only display errors and warnings, replace your current line with:
$config['system.logging']['error_level'] = 'some';


Unable to render posted date in node--article.tpl.php I'm attempting to render the posted date of an article in a specific way. I understand that there is a

Display author and date information.

Checkbox in the content type editor. However I don't believe that would resolve my issue. I'm using the domain access module and the articles on the domains using a different theme cannot be altered. Certainly not how they're displayed anyway.

Is there a way to programmatically grab the posted date from within the template? Is there something similar to

print render($content['body']);

That I can use to render that information? Or is there a function I can call that contains that information?

I was able to render the date by performing

print format_date($node->created, 'article');


Webform with Content Access module not allowing access for the authenticated user role I've run in to an interesting problem that I've not been able to solve yet.

I've got a webform that is restricted to only be able to be accessed by users with a certain role, called "member".

But upon testing I see that users with this 'member' role are not allowed to access the webform unless I have the content access per node allow for anonymous users to access it as well. When I allow "anonymous" access to the webform,  I can actually get it to come up for the member role.

When a logged in "member" tries to access the webform I'm getting the "accessed denied" page.

On the actual form itself under webform > Form  settings I've got the "submission access" set to allow my "member" role, but not anonymous users.

I've looked at the general user permissions too, and everything seems to be in place:

checked: view published content
checked: Access own webform results
checked: access own webform submissions

I've enabled access control on the webform content type itself, and allowed anonymous as well as authenticated (and "member") access to all webforms generally.

I'm using the Content Access module to attempt to restrict access to this particular node/form to authenticated "members". Both authenticated and member roles are checked so as to allow access.

That role is assigned upon a user completing their checkout, and I've double-checked to make sure it's appropriately assigned and it's in place. This part works fine.

I cannot have this webform open for anonymous users.

Any ideas as to what's keeping this node from being able to be accessed?

I did have a similar issue, using Content Access module and getting Access Denied in a Role I created. My problem was that my Role did not have the "View Published Content" permission enabled. After enabling it, it works. But thanks for the detail explanation, it helped solve my issue.


Is there some way to arbitrarily set the active trail? I have a menu as such:

Home
Performances
News
Learning
...

I have a content type called 'Event' and when viewing a node of the event type I want to set the 'Performances' menu item as active. How would I go about doing this?

menu_set_active_trail() doesn't seem to work :s

If you're using Drupal 7.9 or later you can use the menu_tree_set_path() function, e.g.

menu_tree_set_path('main-menu', 'performances');


Adding error class to Webform fields I have a Webform which I'm validating implementing the _validate event (i.e. altering $form["#validate"] by adding a custom validator which accepts &$form and &$form_state).

In my code I have something like this:

if ($nombre && !CasabacaS3SValidaciones::validarLongitud($nombre, 30))
{
    form_set_error('columnas][datos_personales][nombre', t('El nombre no debe superar 30 carácteres'));
    //what should I put in THIS LINE, replacing this comment, to add the error class?
}

I have no clue about adding the "error" class (e.g. fields marked as required have class "required", and also class "error" when the field is not set). How can I alter the field (take this example field in the form_set_error and assume input variables are &$form and &$form_state) so I can add the error for display?

NOTE: I'm seeking to add the "error" class to the fields, and NOT to the wrapping divs (i.e. those divs having form-item class).

(If a quick solution involves themes, please attach a link so I can read about because i'm banging my head about drupal yet, i'm a total n00b :s).

You could use a preprocess functions in your theme for this. You can add preprocess in your template.php.

function mytheme_preprocess_textfield(&$vars) { // OR preprocess_field.

  $vars['#attributes']['class'][] = 'test' ;
}

Check the $vars parameter for values that may help you determine the logic. For examples, just search your code base for preprocess_textfield or preprocess_field. For more inf


How do I define a Drupal variable using phpmyadmin? According to this issue, I need to drupal_weight_select_max to 1000 in my Drupal installation. It suggests several methods:

Use Drush (Not an option for me as it's on shared hosting)
Define it in a module (Beyond my skillset)
Define it in settings.php (which seems to break my site. i.e. site doesn't load and I get WSOD)

If this can be done in phpmyadmin, can you please tell me in plain english, step-by-step how I can do this?

The variables are stored as serialised PHP strings so adding one to the database manually might just be a pain. You can do it quite easily though, just follow these steps:

Download and install the Devel module
Navigate to http://mysite.com/devel/php
Put this code in the textfield:

variable_set('drupal_weight_select_max', 1000);

Press the 'Execute' button.

If you do want to do it directly in PHPMyAdmin you can get away with a running a single query:

INSERT INTO variable (`name`, `value`) VALUES ('drupal_weight_select_max', 'i:1000;')
  ON DUPLICATE KEY UPDATE `name` = 'drupal_weight_select_max', `value` = 'i:1000;';

and then flushing your caches.


Bulk saving nodes with a file field I'm in the progress of creating a bulk upload function for a Drupal site. Using flash I'm able to upload the files to a specific url that should be able to handle the files.

What I want to do, is not just to upload the files, but create a node of a specific type with the file saved to a file-field that has been setup with CCK. Since these are audio files, it's important that file-field handles the files, so additional meta data can be provided with the getid3 module.

I've taken a look at the code/doc, but wasn't able on the first round to figure out how to handle this. Ideally, there is some function that I've missed, that can handle most of this for me.

If any one has experience with this I would apreciate some pointers on how to approach this matter.

It's pretty straight forward, setup your content type with the required fields, then you want to use code similar to this:

$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = $mime;
$file->filesize = filesize($filepath);

$file->uid = $uid;
$file->status = FILE_STATUS_PERMANENT;
$file->timestamp = time();
drupal_write_record('files', $file);

$node = new StdClass();
$node->type = 'type';
$node->body = 'body';
$node->title = 'title';
$node->field_file = array(
  array(
    'fid' => $file->fid,
    'title' => basename($file->filename),
    'filename' => $file->filename,
    'filepath' => $file->filepath,
    'filesize' => $file->filesize,
    'mimetype' => $mime,
    'data' => array(
      'description' => basename($file->filename),
    ),
    'list' => 1,
  ),
);
$node->uid = 1;
$node->status = 1;
$node->active = 1;
$node->promote = 1;
node_save($node);


How do I set the value for field_stock? I use module commerce_stock on Drupal 8.

I get back product data and I create a product with its data. I have to create a field field_stock (Stock level) in variations, which I create with the following code.

$variation =  ProductVariation::create(['type' => 'default', 'sku' => 'sku1', 'status' => TRUE, 'price' => $price]);

How do I add the value to field_stock?

I found a solution to add the value to field_stock (Stock level).

$variation =  ProductVariation::create(['type' => 'default', 'sku' => $json['22107'], 'status' => TRUE, 'price' => $price]);
$variation->save();
//Stock
$stock = ['stock' => ['value' => 100]];
$var = \Drupal::entityManager()->getStorage('commerce_product_variation')->load($variation->id());
$var->set('field_stock', [$stock]);
$var->save();

My field_stock in database is empty but this code create a commerce_stock_transaction in database with my quantity.


Form submission in modal is throwing an error I have a Form which on submit calls another form via ajax and embeds it into a modal popup (Drupal8 standard) and when I click on submit of that modal form , I get a Drupal ajax error (I think it's due to the fact that ajax tries to find the from on the wrong page).

Here is how the submit button of the first form looks:

$form['table'][$pid]['edit'][$cid] = [
      '#type' => 'submit',
      '#id' => 'edit_'.$cid,
      '#name' => 'edit_'.$cid,
      '#value' => $this->t('Edit'),
      '#ajax' => [
        'callback' => [$this, 'customAjaxModalForm'],
        'event' => 'click',
      ],
  ];

And here's the customAjaxModalForm method, which calls the other form and modal.

public function customAjaxModalForm(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $modal_form = \Drupal::formBuilder()->getForm('\Drupal\accounts\Form\ContactsForm');
  $response->addCommand(new OpenModalDialogCommand('Edit contact', $modal_form, ['width' => '800', 'height' => '300']));
  return $response;

}

Now the submit of the ContactsForm looks exactly as the submit above, as I need to send a few responses to the client (.js).

The rest of the code is pretty straight forward so I only supplied the most crucial parts.

How my code works, is: you go to a page, controller handles the request, it calls the first form (the form only has a textfield  and three submit buttons, the other two submit buttons work - do their job) the rest you know.

Any ideas? I am at a loss.

Ok, after a a few hours tinkering and extensive googling, i sadly found the answer i was looking for (but not hoping for).

How to open a popup form from a view link?

Turns out, in D8 this is impossible.


Adding web font from Fonts.com I made a test.html file to test web fonts bought on Fonts.com.

@import url("http://fast.fonts.com/cssapi/3bcaa9a7-xxxx...xxxx.css");

This worked without any problem. But when I add this to my global.css file in my Drupal Template, it doesn't work. Other things from global.css are all ok... So the file gets loaded.

Any other simple way to do this without the use of a module?

Oh my god... It had to be something stupid. This was the sollution:

On Fonts.com go to "Manage Web Fonts", and add a domain. The HTML I tested was on my localhost, the Drupal wasn't.

Glad I found the answer when I was walking outside...


hook_uc_add_to_cart in template I'm using Drupal 7 + Ubercart 3 and am trying to run a piece of code just before the user adds a product in cart. hook_uc_add_to_cart seems to be the right function to use for it. So I'm trying to utilize it using the following syntax in template.php file of my template

function tbw_uc_add_to_cart($nid, $qty, $data){die('here: ' . $qty);}

where tbw is my template name. I've flushed all caches but the above code does not work as it doesn't die() when I add a product to cart. I suspect the problem is that this hook can't be implemented in a template because the documentation only talks about using it inside a module, i.e., Some modules need to be able to hook into the process of adding items to a cart....
Can anybody please shed some light on why it is not working and guide me in the right direction. Thanks.

I suspect the problem is that this hook can't be implemented in a template

Correct :)

Only hook_theme(), preprocess hooks, and alter hooks can be implemented in template.php. For any others, including this one, you'll need to write a custom module.


form_set_error highlight offending field? form_set_error supposedly takes the name of the offending form element as the first param.

I have a form element that is named "field_reviewer_terms_of_service[value]" (as taken from firebug). My code that sets the error is:

    form_set_error('field_reviewer_terms_of_service[value]', t('You must agree to the Terms of Service.'));

The error shows up in the messages, but doesn't highlight the form element itself. What am I doing wrong?

Edited with HTML of form element:

 <input type="checkbox" class="form-checkbox required error" value="1" id="edit-field-applicant-terms-of-service-value" name="field_applicant_terms_of_service[value]"> I agree to the Terms of Service

Don't put the [value] inside, it should work with only

form_set_error('field_reviewer_terms_of_service', t('You must agree to the Terms of Service.'));

See the documentation for form_set_error().
You may have to use some [value inside your field if it is multivalued, see this comment but we need to see the HTML ouput for your field.


Show custom page while the server processes a form Form submit handler sends some time consuming requests to other servers. I need to show custom page with some simple content like timer/progress-bar/images while server will process submitted data.

Not sure how this could be properly done in Drupal 6.26.

Found useful batch tool (set_batch()), but didn't figure out how to replace default progress-bar with custom page and content.

Checkout the module loader , it may solve your problem

A similar module hide_submit


When should I use an existing field? While adding new fields to a content type, When should I resue an existing field? for example if I need an image field for my content type is it always a good idea to re-use an existing image field?

Consider the benefits and drawbacks of reusing fields:

Performance: There's a slight performance gain from reusing fields. However, for most sites with moderate numbers of fields, it's a negligible difference.
Maintainability: In theory, if you re-use the same field for the same purpose on multiple content types, then if you decide to change its functionality later, you only have to change it in one place. Similarly, if you want to theme it the same way across entities, you only have to use a single selector. In practice, this rarely happens, and more often the converse is true- you've used the same field in multiple places, and then realize that they actually need to behave differently.
Setup: Obviously, it takes less time to re-add an existing field than to add a new one.
Portability: If you export fields with Features, it's best to not reuse them between entities unless absolutely necessary. Technically, there's nothing wrong with reusing fields (since you can export field bases and field instances separately), but in practice it tends to just lead to confusion and circular dependencies. If you choose not to reuse fields, then you have the luxury of being able to prefix them with the content type / bundle they are attached to, e.g. "field_article_image", "field_page_taxonomy", etc..., which eases portability and maintenance.

In case it's not clear from my tone there, my preference is to never reuse fields unless it's totally, completely, 100% clear that they really are, and forever will be, used for the same purpose.


How to remove delete link from admin manage fields ui I have created a new entity type and progamatically added the fields it requires. My issues is that on the Manage Fields UI (the same interfaced used for managing fields for basic pages/articles), in the operations column there is an option to delete the field. How do I remove prevent the delete link from appearing?

I have googled and looked at the FAPI documentation but don't see an option for this. Anyone know how to do this?

this function will do one of two things - remove the link from the screen, or limit it's effect to doing nothing, depending on what you want to accomplish.

This will work on the Body of an Article - you will need to adjust names appropriately for the content type and field names.

Keep in mind however this will not prevent them from accessing the delete functionality using the url: example.com/admin/structure/types/manage/article/fields/body/delete - you would need to either override the menu, use an access restriction module or something like Rules to prevent users from manually deleting the field.

function MODULE_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'field_ui_field_overview_form' && $form['#bundle'] == 'article')
  {
    unset($form['fields']['body']['delete']);  // remove the link

    $form['fields']['body']['delete']['#href'] = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '#';  // make the link have no effect
  }
}


How to get rid of Deadlocks and Lock time out type issues? I read multiple blogs, tried to google, it but didn't find any satisfaction from any solution. I have the following issues :

PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: DELETE FROM {cache_field} WHERE (cid LIKE :db_condition_placeholder_0 ESCAPE '\\') ; Array ( [:db_condition_placeholder_0] => field\_info:% ) in cache_clear_all() (line 163 of \includes\cache.inc).

PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) )

I tried to solve this by increasing innodb_pool_buffer_size and wait_timeout in my.ini but didn't worked.

I changed my cache table's engine from Innodb to MyIasm. The issue gone but it is not a perfect solution. The table engine will be changed after an upgrade of drupal. This issue doesn't affect anything on the site but I don't want this to occur.

Any solution guys?

Read and follow this post; it assumes InnoDB.

In particular, see the part saying to add the following to the settings.php file.

$databases['default']['default']['init_commands'] = array('isolation' => "SET SESSION tx_isolation='READ-COMMITTED'");


View broken after upgrade to D6.33 I'm working on upgrading an old site. I've just upgraded from 6.17 to 6.33. Most things seem to be working, including some views, however one view is throwing the error below. I agree that there's no node_data_field_image table in the db, but there isn't one in the pre-upgrade backup, either. Any ideas?

Unknown column
    node_data_field_image.field_image_imceimage_title
in field list query:

SELECT DISTINCT
    node.nid AS nid,
    node.title AS node_title,
    node.uid AS node_uid,
    node.type AS node_type,
    node_revisions.format AS node_revisions_format,
    node.created AS node_created,
    node_data_field_image.field_image_imceimage_path AS node_data_field_image_field_image_imceimage_path,
    node_data_field_image.field_image_imceimage_width AS node_data_field_image_field_image_imceimage_width,
    node_data_field_image.field_image_imceimage_height AS node_data_field_image_field_image_imceimage_height,
    node_data_field_image.field_image_imceimage_alt AS node_data_field_image_field_image_imceimage_alt,
    node_data_field_image.field_image_imceimage_title AS node_data_field_image_field_image_imceimage_title,
    node.vid AS node_vid,
    node_revisions.body AS node_revisions_body,
    node.sticky AS node_sticky,
    DATE_FORMAT((FROM_UNIXTIME(node.created) + INTERVAL -14400 SECOND), &#039;%Y%m%d&#039;) AS node_created_day
FROM node node
LEFT JOIN node_revisions node_revisions
ON node.vid = node_revisions.vid
LEFT JOIN content_field_image node_data_field_image
ON node.vid = node_data_field_image.vid
WHERE (node.type in (&#039;news&#039;)) AND (node.status = 1 OR (node.uid = 1 AND 1 &lt;&gt; 0) OR 1 = 1)
ORDER BY node_sticky DESC, node_created_day DESC LIMIT 0, 5

in /home/rsage/rs_upgrade/sites/all/modules/views/includes/view.inc on line 810.

If you have a backup of pre-upgrade version, how about your import your faulty view from there. The export-import feature in Views is usually very robust. If the import is successful, there is not point in banging your head as to why this error is coming.


How to add static content before the feed on the front page? I want my front page to contain some static content (a short description of our association), and after that the normal feed of articles fed by "promote to front page".  How can this be achieved?

I know how to add content to the front page feed and I know how to change the front page to another page, but I couldn't figure out how to get both static content and the front page feed.  (It seems such obvious and often-wanted functionality for a front page...)

there are multiple ways to do this:

1. Use the default block system

Create a new block admin/structure/block/add and insert your headline (or none) and the body text. Under Visibility settings select Only the listed pages and insert <front>. Select under region the region where the block shall be shown, or do this at admin/structure/block after saving the block.

2. Use panels + page manager (ctools)

Create a new panel page and make this page your frontpage, put the feed you want to be displayed inside of the main area, add a custom content pane before that feed/ view.

3. page.tpl.php

inside of your templates page.tpl.php you can add a codeblock for your custom content, drupal_is_front_page will help your here:

<?php
if (drupal_is_front_page()) {
  //your custom code
}
?>

reference for bartik: page.tpl.php with bartik you could use the $is_front variable as well for detection.


How to limit number of displayed images within one field under views? I've created a content type News with different fields, one of the fields is field collection that allows administrator to upload unlimited images with a detailed description text.

I used Views module to display a list of news on the homepage, now I want to limit the number of displayed images within field collection to max 2 per news and when users clicks on the news to see full detail page they will be able to see all images that have been added by administrator.

Is there a way to limit number of items in the frontend but keep unlimited in the backend (admin)?

When you use field collection in Views, go to the settings of field collection field in views and follow these steps :

1. There is a setting named "Multiple Field Setting"
2. Enter the number of pictures in the textfield you want to show in Field 'Display'

and you also specify Start from to where to start.


Making jCarousel view responsive Using the example on [this][1] page, I have the following jQuery code:

(function ($) {
  Drupal.behaviors.gsdOmega4ExampleBehavior = {
    attach: function (context, settings) {
      var jcarousel = $('.home-jcarousel');
      console.log('executed');
      jcarousel.on('jcarousel:create jcarousel:reload', function() {
        console.log('never executed');
      })
      console.log('executed');
  };
})(jQuery);

The 'jcarousel' object is being referenced correctly.  I don't understand why jcarousel.on() is not being executed

Most likely because on() didn't exist before jQuery 1.7, and Drupal ships with...well, not 1.7.

The standard solution is to install jQuery Update and select 1.7 as the version for the site.

For future reference, check for JS errors in the browser console - there will be something very similar to this in there:

  Object [object Object] has no method 'on'


Ubercart : How to display product information ( of certain brand ) as XML? Can the Ubercart module display product information of certain brand as XML ?

I have looked into Ubercart module settings, but I can't find anything useful.

Find the steps to create XML for certain product:

Enable the catalog module
add Brand as a term
Create products and assign it to certain brand
uc_catalog view is available for to show the listed product in certain brands
make that view as RSS feed using View RSS module


Delete old columns from table using hook update I need to delete some old columns of existing table. How to do it using hook_update or Is there some other way to delete old columns in .install file .

Thanks

You can use function db_drop_field()

/**
 * Implements hook_update_N().
 */
function mymodule_update_7001() {
  db_drop_field('my_table', 'my_column');
}


How do I unlock a field? In Drupal 7 it is possible to use:

$field_name = 'field_name';
$field = field_read_field($field_name);
$field['locked'] = 0; // 0: unlock; 1: lock.
field_update_field($field);

How to do this in Drupal 8?

You need to load the related field storage config entity and change the locked status:

\Drupal::entityTypeManager()
  ->getStorage('field_storage_config')
  ->load('node.field_foo')
  ->setLocked(FALSE)
  ->save();

This is just an example - you should inject the entity type manager instead of calling the global version if contexts allows.


Replace default submit handler when using drupal_get_form() in D7 I'm having issues calling an existing form from the commerce_coupon module which runs a default submit handler callback (commerce_coupon_form_submit).

My form builds off of that form and simply tries to replace the default '#submit' value to call my own submit function instead of the default commerce_coupon one. I'm using drupal_get_form so my code looks like the following:

$form = drupal_get_form('commerce_coupon_form', $coupon);
$form['#submit'] = array('mymodule_coupon_submit');
return drupal_render($form);

That is the code from inside a function that is supposed to return the rendered form. The problem is the default commerce_coupon_form_submit submit handler is still running and my own function doesn't get called. I think this has something to do with the form_id or form_state still being commerce_coupon_form.

I've found related problems on stackexchange but responses were directed for other versions of Drupal. I'm using D7 so please bear that in mind.

I'm adding a little more detail that may help get a better answer for this. The original commerce_coupon_form seems to try to use a button-level #submit handler as there is the following before the form is returned:

$form['actions'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('form-actions')),
    '#weight' => 400,
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save coupon'),
    '#weight' => 40,
  );

but the actual #submit handler isn't assigned so the default drupal handler is being set at the root of the form. I've tried assigning a button-level submit and overriding the root drupal assigned submit to a blank array but that doesn't seem to work. I'm trying to track down documentation for drupal or the function that sets the default #submit so I can figure this out. If you can point me in the right direction I would appreciate it.

The problem is when the form builder builds the form up again when it's submitted, your function won't be called so it doesn't know about the changes you've made.

hook_form_alter() (and hook_form_FORM_ID_alter()) were written for exactly this purpose, I'd advise using one of those, e.g.

function MYMODULE_form_commerce_coupon_form_alter(&$form, &form_state, $form_id) {
  $form['#submit'] = array('mymodule_coupon_submit');
}

It's worth bearing in mind that other modules' hooks might run after yours and change that array again. To avoid that have a look at How to update a module's weight.


How can I save two logos for a custom theme? I need to save two custom logos in a custom theme and use them on the site. Can I somehow create a custom field in theme settings or maybe save the path to another logo in one of the .yml theme files?

Created theme-settings.php in custom theme root, there created new function, it renders new fieldset and a managed_file field

function theme_name_form_system_theme_settings_alter(array &$form, FormStateInterface $form_state) {
  $form['options_settings'] = [
    '#type' => 'fieldset',
    '#title' => t('Theme Specific Settings'),
  ];

  $form['options_settings']['add_logo'] = [
    '#type' => 'managed_file',
    '#title' => t('Additional logo'),
    '#upload_location' => 'public://logo/',
    '#default_value' => theme_get_setting('add_logo'),
    '#states' => [
      'visible' => [
        ':input[name="File_type"]' => ['value' => t('Upload Your File')],
      ],
    ],
  ];
}


How to add custom fields in Apache Solr's search result? I'm trying to add some custom fields(image field, text field) in Apache Solr's search result.
I ended up found the code below; however, I don't know:

Where to put this code (is it template.php?)
How to get the information to display them.

`

function mymodule_apachesolr_update_index($document, $node, $namespace) {
  // When indexing nodes, add field from my custom content type.
  if ($node->type === 'my_contenttype') {
    // Grab the image URI and the description.
    $image_uri = $node->field_image['und'][0]['uri'];
    $description = $node->field_description['und'][0]['safe_value'];
    // Add the image and description to the document in the solr index.
    $document->addField('ss_my_contenttype_image', $image_uri);
    $document->addField('ts_my_contenttype_description', $description);
  }
}

function mymodule_apachesolr_query_prepare($query) {
  // Add the image.
  $query->addParam('fl', 'ss_my_contenttype_image');
  // Add the description text.
  $query->addParam('fl', 'ts_my_contenttype_description');
}

I appreciate any advice.
Thank you.

If you have D7 and latest Solr search integration module then you can follow these steps:

Create a custom module with the following code (If your field is single value text then you should add "ts_" prefix to its name.)

function mymodule_apachesolr_query_alter($query) {
  $query->addParam('fl', 'ts_field_name');
}

Add the following function in the template.php file

function YOUR_THEME_preprocess_search_result(&$variables) {
  $variables['ts_field_name'] = $variables['result']['fields']['ts_field_name'];
}

Display the field in search-result.tpl.php

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

This is a quick way that doesn't use any  theme function like theme_apachesolr_search_snippets() for search results snippets.

You can find more information here:

http://archive.org/details/ApacheSolrSearchMastery_250
http://www.slideshare.net/AcquiaInc/apache-solr-search-mastery


How to minimize conflicts in hook_update_N implementations with multiple developers? I work on a team with multiple developers and we use hook_update_N functions in a "miscellaneous" module to make updates such as module or theme enabling/disabling, performing miscellaneous database updates, one-off variable assignments, and more. We often encounter conflicts when having code reviews, since multiple feature branch pull requests get approved around the same time, many with hook_update_N implementations that use the same number (N). The process of resolving the conflicts is slow because each conflict has to be resolved in series.

One option would be to have each developer create their own "glue" module and put their hook_update_N implementations in that module's .install file, but it seems wasteful to run multiple modules as a workaround for this problem.

Anyone have a good solution to avoiding or minimizing the conflicts?

A low tech solution I can think of would be to set up a wiki page where developers can "reserve" hook_update_N numbers for that site, and set up a procedure that everyone has to go to that page first and check for the next available number before starting work on an update hook.


Why does not hook_block_view_MODULE_DELTA_alter work? I'm implementing a hook_block_view_MODULE_DELTA_alter for the user login block.

function mymodule_block_view_user_login_alter(&$data, $block) {
    drupal_set_message($block->module);
}

According to the block table, the module is user and delta is login.
But, the hook was not invoked and the message was not printed out as expected. I'm using D7.

That hook is called right before a specific block is rendered. If the block isn't present in the page, the hook is not invoked. Replace that hook with hook_block_view_alter(), and it will get invoked for every block shown in the page.

Bear in mind that Drupal caches the hooks implemented from a module; if you alter the code of an enabled module, Drupal will not know the module has a new hook. Disable the module before editing its code, and re-enable it after editing its code; in that way, Drupal will clear its cache, and notice there is a new hook, using it when necessary.


How can I rewrite the values of facets shown in the Current Search block? I am using the Facet API for Solr search on my site.

The Facet API Bonus module provides a Rewrite items filter:

  Filter "Rewrite Items": Filter plugin to rewrite labels or other data
  of the facet items by implementing a new dedicated
  hook_facet_items_alter (in a structured array, before rendering). Very
  handy to rewrite list field values or totally custom encoded facet
  values for user friendly output.

My site has three facets for boolean fields that have "Yes" or "No" options by default.  Using this filter, I have rewritten them so that what is being selected is more clear:

function mymodule_facet_items_alter(&$build, &$settings) {
  switch ($settings->facet) {
    case 'field_friends':
      foreach($build as $key => $item) {
        if($item['#indexed_value'] == '1') {
          $build[$key]['#markup'] = t("Wants friends");
        }
        else {
          $build[$key]['#markup'] = t("Doesn't want friends");
        }
      }
    break;
    case 'field_money':
      foreach($build as $key => $item) {
        if($item['#indexed_value'] == '1') {
          $build[$key]['#markup'] = t("Wants money");
        }
        else {
          $build[$key]['#markup'] = t("Doesn't want money");
        }
      }

This works for the facets.  But the problem is, if the user clicks Wants friends and Doesn't want money, then the Current Search block shows Yes and No (the unmodified facet values).

How can I rewrite the values of the facets show in the Current Search block too?  As it is now, if a user selects multiple Yes and No values, they will have no idea what is actually being applied.

The feature is not available by default, but there is a patch to add this to Facet API.


Email Notification to Store Owner When Order Complete During early development I had it working so the store owner would get an email when an order was completed. I just realized this isn't working anymore. Where are the settings related to this? Is it supposed to use the store's email, or something else?

You didn't mention the versions so I assume you are using Drupal 8 with Commerce 2.
You can use Commerce Reaction module as it allows you to select the Commerce event and have a reaction when it is dispatched.
It provides a plugin to send HTML, and twig template emails with nice integration with the Token module.


How do I stop the node from caching Sometimes when I run below code in the hook_preprocess_menu() of a node, I am getting a previously loaded node instead of my current node.

\Drupal::routeMatch()->getParameter('node');

What should I do to stop this?

If you add node data in a preprocess hook, then you need to add the cache tag of the node:

$variables['node_title'] = [
  '#markup' => $node->getTitle(),
  '#cache' => [
    'tags' => $node->getCacheTags(),
  ],
];

If this node is from a route match, then you need to add a cache context for the route as well:

$node = \Drupal::routeMatch()->getParameter('node');
$variables['node_title'] = [
  '#markup' => $node->getTitle(),
  '#cache' => [
    'tags' => $node->getCacheTags(),
    'contexts' => ['route'],
  ],
];