Drupal Mysql SSL Connections Cannot seem to find solid literature on using mysql-ssl connections with either Drupal 6 or Drupal 7. Piece of cake with wordpress. Is this a possibility, if not why?

The Drupal 7 database layer uses PDO which prior to PHP 5.3.7 did not support MySQL with SSL.

Assuming you're using PHP 5.3.7 or later there is a patch available for Drupal to allow "arbitrary PDO options" to be used, which would include the ability to specify an SSL option.

See this discussion for a fair bit more information and links to the issues on php.net.

EDIT

For Drupal 6 you can change the mysql_connect() line in includes/database.mysql.inc to:

$connection = @mysql_connect($url['host'], $url['user'], $url['pass'], TRUE, MYSQL_CLIENT_SSL);

Although you should really turn this into a patch and apply it to the includes/database.mysql.inc file as hacking core is never a good idea.


How can I display a Browser Prompt for Confirmation before executing ajax callback for a button element? I have a button type element in a form. It has an ajax callback to some function that performs a delete operation. Everything works perfect.

I want to add a browser prompt when user clicks on the delete button. The prompt should ask user to confirm the delete action and only after the confirmation should the callback function be executed (using ajax of course).

How can I do this?

Following is the code for button element:

$form['delete'] = array(
  '#type' => 'button',
  '#value' => t("Delete"),
  '#element_validate' => NULL,
  '#ajax' => array(
    'callback' => 'delete_something',
    'wrapper' => 'delete-message',
  ),
  '#limit_validation_errors' => array(),
);

function delete_something(){
  //Some Code
}

This one should help you the same way you want to achieve the functionality.
Instead of ajax callback I have created a ctools modal which will return the delete and cancel button..

"delete/nojs/1" where 1 will be the Item which you want to delete.

use this in your form.

$form['delete'] = array(
  '#markup' => ctools_modal_text_button(t('Delete'),"delete/nojs/1", t('Delete'), 'ctools-modal-modal-popup-small'),
);

create a menu item.

function custom_module_menu() {
  $items = array();
  $items['delete/%ctools_js/%'] = array(
    'type' => MENU_CALLBACK,
    'title' => t('Delete'),
    'page callback' => 'delete_something',
    'page arguments' => array(1,2),
    'access callback' => TRUE,
  );
  return $items;
}

and call this function.

function delete_something($js = NULL) {
  if (!$js) {
    return drupal_get_form('delete_form');
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    'title' => t('Delete'),
    'ajax' => TRUE,
  );
  $output = ctools_modal_form_wrapper('delete_form', $form_state);
  if (empty($output)) {
    $output[] = ctools_ajax_command_reload();
  }
  print ajax_render($output);
  drupal_exit();
}

function delete_form($form_state = NULL){
  $form['message'] = array(
    '#prefix' => '
',
    '#value' => t('Are you sure want to delete?'),
    '#suffix' => '
',
  );
  $form['submit']['delete'] = array(
    '#prefix' => "
",
    '#suffix' => "
",
    '#value' => t('Delete'),
    '#type' => 'submit',
    '#submit' => array('delete_form_submit'),
  );
  $form['submit']['cancel'] = array(
    '#prefix' => "
",
    '#suffix' => "
",
    '#value' => t('Cancel'),
    '#type' => 'submit',
  );
  return $form;
}

function delete_form_submit($form, &$form_state) {
 //some code to delete
}


#states not working properly in IE 9 I am using #states form API to do the show hide animation of one element based on the values of another form element.like follows,

$price['#states'] = array(
    'visible' => array(
        ':input[id="edit-field-paid-event-und"]' => array('value' => 1),
    ),
);

It's working fine in all the browsers except in Internet explorer 9 and 10. Any solution for this.

I found the answer from this Link. So Internet Explorers never accepts element value as integer. I changed my code as follows it's working for me,

$price['#states'] = array(
  'visible' => array(
    ':input[id="edit-field-paid-event-und"]' => array('value' => '1'),
  ),
);


how it's possible to load nodes by taxonomy terms Here im loading nodes by "type" article, i want to call nodes by another id , but this id is in another table, should i join tables , or it is some other way to do this

$type = "article";

          $build = array();
          if ($nodes = node_load_multiple(array(), array('type' => $type))); {
              $build['nodes'] = node_view_multiple($nodes, 'teaser');
          }

In Drupal 7 conditions are deprecated, it is preferable to use EntityFieldQuery to retrieve a list of entity IDs. You can see more here:
About EntityFieldQuery

In this answer you can see an example: What's the proper use of EntityFieldQuery?

In Drupal 8 you can do something like that:

$nids = \Drupal::entityQuery('node')
->condition('your_taxonomy_field', 'your taxonomy id')
->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

I hope it helps


drupal_goto not working in hook user login I have $u variable which stores the path in hook user login to redirect users to the page.

drupal_goto($u);

I am not being redirected to the page- path $u.
drupal_goto not working.
I have tried everything increased te weight of the module,even tried with $_GET['destination'].

Instead of using drupal_goto(), try passing the path in $edit['redirect'] in hook_user_login as below:

<?php
/**
 * Implements hook_user_login().
 */
function hook_user_login(&$edit, $account) {
  // To check if the form is not the user reset form.
  if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
    $GLOBALS['destination'] = 'PATH_YOU_WANT_TO_REDIRECT';
  }
}
?>


Collection per content type I just started experimenting with the mongodb module and its fields storage module on a clean drupal install and it all seems to work fine.
But what I noticed is that the content of the 2 custom content types is stored in the same collections (fields_current.node and fields_revision.node).

Wouldn't it make sense to have a separate collection for each content type? As queries are often per content type, it should reduce the scope of your query?
Is there a possibility to do that with the current version of the module, or am I just not getting it?

My question got answered on drupal.org:

  Posted by marcingy on August 16, 2013 at 7:03pm:

    This is mirroring how core storage works. fields_current.node contains the data for the current revision. There is a collection per entity type which is the smallest division in core in terms of storage.

I guess I will have to build in the flexibility myself :-)


Moving file structure and documents from Static site to Drupal I have a static site that we have created content types for and moved most of the content over. There are links leading back to the old static site documents. I am looking for a good way to bring these docs into the drupal fold. I understand i'll need to update the path to the doc, but if we can keep the majority of the structure and just update to /default/files/directory/subdirectory/file.ext that would be great.

How does one most successfully import large amounts of documents?

What you could have done is use the Migrate module. It allows you to read from various sources (db, files, csv, etc.) and feed them to Drupal (db, files, csv, etc). It's essentially just a pipeline of read->process->save.

What I would do is create 2 migrations, one for the files and one for the pages. You migrate files first which essentially just tells Drupal they exist by creating records of them in the DB and where they are. During migration, Migrate creates a mapping table which tracks the source id (module-generated, you decide, usually by filename or hash) and destination id (entity id) of the content.

Then you migrate the pages. Migrate allows you to do processing on content before it gets saved to Drupal. Using the data from the mapping done in the file migration earlier (the entity ids), you simply need to look for the urls in the page content, use it to find the id Drupal assigned to it when it was migrated (there are APIs for this), generate a url from that ID, and replace the url in the content.

Migration is easier done than said actually.
This section extensively explains how to use Migrate. In addition, check out Migrate Extras and Migrate D2D as additional tools. Also, the Migrate module itself has examples in the source code which you can check out. And... a lot of trial and error.


End date shown on calendar I'm using the Calendar, and Date modules to create an agenda on a website. However, when I create an event with a start and end date, it also shows the event on the next day. While this is useful for true multiple day events, it is not for party that start late and end late, as I want them to only show once (at the start date).

Is it possible to fix this?

For clarification: I'm using the Date (ISO format) field.

I would check your date/time settings, specifically the sites default time zone.  I have seen similar errors when that is set incorrectly.


Can I use a token within a custom token? I am trying to create a custom token that modifies another token.

$theDomainName = "[domain-name-raw]"; //Pull in the other token
$removeCounty = str_replace(" County", "", $theDomainName); //Replace " County" with nothing
$countyPlus = str_replace(" ", "+", $removeCounty); //Replace " " with "+"
return $countyPlus; //Return modified token as new custom token to be used through out site

If I use [domain-name-raw] for $theDomainName, my result is the original token (e.g. "Cerro Gordo County"). If I type what [domain-name-raw] should output for $theDomainName (e.g. "Cerro Gordo County"), my code works fine (it outputs "Cerro+Gordo"). What is going on?

I am using Drupal 6.

You could use something like token_replace() to get the other token value within your own token, but you shouldn't try to alter an already created token, as that will mess up when you really want to use that token.

You need to define you own token, and handle the output of that token. But in doing so, you will most likely find that it will be easier to get the raw values from the PHP values supplied instead of using token_replace() or something similar.

You need to look at hook_token_list() and hook_token_values() to define your custom token.


How to change the database drupal forms send to It's super easy using php and SQL but how do you change the default database drupal 6 saves posted data in the forms? To an external database?

I would try reading through How to connect to multiple databases within Drupal (notably, the Drupal 6 section towards the end.

Basically, in your settings.php file, convert the $db_url to an array, and add the secondary database:

e.g.

$db_url = 'mysql://drupal:drupal@localhost/drupal';

becomes

$db_url['default'] = 'mysql://drupal:drupal@localhost/drupal';
$db_url['db2'] = 'mysql://user:pass@localhost/db2';

Then create a submit handler that either compliments or overrides an existing form submit handler and use db_set_active to connect to the secondary database, save the data, and then switch back.

e.g.

function MYMODULE_MY_EXTRA_SUBMIT_HANDLER($form, &$form_state){
  // Switch to db2
  db_set_active('db2');

  // Do all your form processing and database transactions

  // Connect back to default Drupal database
  // *Note* If your primary db is keyed with "default", then you don't need to
  // pass an argument to db_set_active().
  db_set_active('default');
}


CSS order in Drupal 8 libraries.yml From what I read about Drupal 8 themes there does not appear to be anything to order CSS file loading. As you know, CSS cascades down to a specific order when there is a conflict with an element. Since I have a class that is named the same as Twitter Bootstrap which is loaded from the CDN from the page.html.twig, I can usually modify a bootstrap class by having the CSS file that loads last as that can trump the bootstrap class that loads earlier. I have not discovered how to set an external library like Twitter Bootstrap in the libraries.yml file so it's in my page.html.twig file. So here is my THEME.libraries.yml

global-styling:
  version: 1.x
  css:
    theme:
      css/reset.css: {}
      css/style.css: {}
      css/htme-elements.css: {}
      css/tabs.css: {}
      css/messages.css: {}
      css/block-editing.css: {}
      css/wireframes.css: {}
      bootstrap/bootstrap.css: {}
      bootstrap/bootstrap.min.css: {}
      css/layout.css: {}
      css/default.css: {}

The default.css should load last which has the class I would like to override in bootstrap, but after

drush cache-rebuild

I find that the element is choosing the bootstrap element. OK, let me put the default.css element highest in the stacking order in case Drupal is putting in a different order. But after rebuilding my cache again, I find that bootstrap still "wins."

The closest thing in the Drupal docs was to perhaps add stylesheets-override in my THEME.info.yml

stylesheets-override:
  - system.theme.css

How should I set the order so that I can use the external Bootstrap files and load in my default.css last?

You can create a separate library for external bootstrap stylesheet, which will give you flexibility to load bootstrap css before loading global-styling css. Here's how to do it:

YOURTHEMENAME.info.yml

# Defines libraries group in which we can add css/js.
libraries:
  - sp/bootstrap // ADDED - note: this should go before your global-styling
  - sp/global-styling
...

YOURTHEMENAME.libraries.yml

# note: bootstrap library should go before global-styling
# use { type: external } for external resources
bootstrap:
      css:
        theme:
         '//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css': { type: external }
global-styling:
      css:
    ...


Use a database specific function in dbtng (e.g. uuid in db_insert) I have a table that contains a char(36) field for a uuid. It seems like I can insert data into that field with a mysql query like: INSERT INTO mytable (uid, event_guid) VALUES (1, uuid());. I'd like to make a query like that in DBTNG syntax, but I believe I will just insert the string "uuid()" into the column.

db_insert('mytable')
  ->fields(array('uid' => $uid, 'event_guid' => 'uuid()'))
  ->execute();

So...do I just use db_query? Is there some magic in dbtng to handle this?

Here's what I ultimately did:

db_query("INSERT INTO {mytable} (uid, event_guid) VALUES (:uid, uuid())",
array(':uid' => $uid));

And that works to use the mysql uuid() function in an insert.

I've created an issue to add this to Drupal 8 http://drupal.org/node/1858188


Adding HTML class attributes to Entity Reference field links in View I have a view ("Tasks") that pulls in Task nodes, complete with sorting and filtering. Each Task can have multiple nodes attached via the "Related Articles" field (field_related_articles). I am trying to loop through each node (which can be a Video, Document, Article, etc.) and assign each link a class name depending on the type.

For example, a "Document" node attached to a Task would display a hyperlink with the document class. Video nodes will be video, and so on.

Here is my preprocess that is targeting the specific field:

function mytheme_preprocess_field__node__field_related_articles(&$variables) {
  $items = $variables['items'];

  foreach ($items as $index => $item) {
    $content_type = $item['content']['#options']['entity']->type->entity->label();
    $class_name = slugify($content_type); // custom function

    $variables['items'][$index]['attributes']['class'] = [$class_name];
  }

}

When I inspect the $variables array, I see the following, which looks okay to me (but I can't be sure):

As you can see, the attributes object now has a class value for each items value (I have two). However, in the HTML, the classes do not show up:

Is there something I'm doing wrong?

So I finally figured out the problem.

I wasn't supposed to touch the $variables['items'][…]['attributes'] object, I was supposed to create a $variables['items'][…]['content']['#attributes'] array instead and put the class name(s) there.

Having done so, that now works.


Removing div wrapper container of paragraph field and get only the plain text in twig I have a paragraph template in my custom theme as paragraph--home-page-carousel.html and when I write like this

{{ content.field_home_slide_snippet[0]|raw }}

I get in HTML source code this

    FIELD CONTENT

what should I do to remove the div wrapper?

You shouldn't do {{ content.field_home_slide_snippet[0]|raw }}. You should do {{ content.field_home_slide_snippet }} and edit the twig template for field--field-home-slide-snippet.html.twig to have no HTML wrappers. Copy field.html.twig to your theme and edit as needed.


Drupal 8, get value of field user in proper way, not an array In a custom module, I load an user and I want get some field value

I do this :

$value = $user->get('field_value')->getValue();

but $value contain an array, not the value. I must do ugly command for get the value:

$value = reset(reset($user->get('field_value')->getValue()));
// or
$value = $user->get('field_value')->getValue()[0]['value'];
// $value = 4

There isn't any Drupal way for get the value of a field, not an array ?

Thanks =)

The method getValue() is used to get an array:

$array = $user->get('field_value')->getValue();

If you want to get a skalar use:

$value = $user->get('field_value')->value;

Both methods look similar, but do different things:

The method getValue() is to get the complete array of a field, which is quite useful for multiple value fields or multiple properties.

The method ->value gets the property with the same name.  Most standard fields use value as the main property.


Drupal console "settings:set" not working or I am doing it wrong I wanted to use Drupal console to change some settings on a site:

To set the default 403 page to "/user/login"
To set user registration permission to "admin only"

Following the instructions here, which gives this example:

drupal settings:set  application.language es

I tried the following:

drupal settings:set user.settings.register admin_only
drupal settings:set user.settings register:admin_only
drupal settings:set user.settings.register "admin_only"

In all cases, I got a green bar saying that the setting had been successfully set. But looking at the site showed that it had not. Also doing drupal config:edit user.settings showed that it had not (but when I changed it in the editor, it did update successfully in real life).

The exact same thing happened with:

drupal settings:set system.site.page.403 /user/login

Am I doing something wrong, or is this an unimplemented part of drupal console?

The "drupal settings:set" command updates the Drupal console's own settings rather than the configuration of the running Drupal site.

If you want a one-liner to update configuration, then you can use Drush for this job, eg:

drush cset user.settings register admin_only -y


JS script in theme is ignored for anonymous users It just discovered that my script.js in my theme is ignored for anonymous users. But only on certain pages. When logged in everything works on all pages. When logged out things only work in some content nodes. For example I have a navigation menu outside of the system menu. It's an exposed block from a view, that I use as a navigation menu to mirror the taxonomy (the taxonomy module does not work for me). I use the theme's script.js to collaps and expand menu items as appropriate. But this is ignored when logged out on most pages (but as I said it works when visiting some content nodes). What is this?

I also discovered that flexslider doesn't wok when logged out. But it works in content nodes... I must be missing something.

I have tried adding:

drupal_add_library('system', 'jquery', 'ui.sortable', 'ui', 'drupal.collapse');

... in my template.php (in template_process_page, and I also tried to add it in template_preprocess_html).
In the Firebug "Net" tab I can see that my script,js is loaded together with jquery and a whole bunch of js files. So if everything is loaded, why is it ignored on certain pages when logged out? Any ideas?

Edited... I also have tried to add break points in my script.js file and it is clear that the script is ignored all together on certain pages.

Worked it out! I post an answer myself in case anyone else has the same issue. Hopes it helps somebody.

I had to add the jquery.cookie library in my template.php

drupal_add_library('system','jquery.cookie');

And it seems you were right to add only one library at a time, Namari, it didn't work until I tried that. Thanks!


How can I custom sort a views display containing multiple content types to list the newest item from each content type sequentially? I have a Views block display where I've collected content items from 3 different content types, filtered by a shared Taxonomy term. My sort criteria currently is "Post date (desc)" and "Type (asc)". I have the Pager displayed and a limit of 6 items to a page.

The current results are:

Page 1
First Newest item from content type 1
Second Newest item from content type 1
Third Newest item from content type 1
Fourth Newest item from content type 1
First Newest item from content type 2
Second Newest item from content type 2

Page 2
First Newest item from content type 3
Second Newest item from content type 3
Third Newest item from content type 3
Fourth Newest item from content type 3
Fifth Newest item from content type 3
Sixth Newest item from content type 3

Page 3
Etc.

The desired results are:

Page 1
First Newest item from content type 1
First Newest item from content type 2
First Newest item from content type 3
Second Newest item from content type 1
Second Newest item from content type 2
Second Newest item from content type 3

Page 2
Third Newest item from content type 1
Third Newest item from content type 2
Third Newest item from content type 3
Fourth Newest item from content type 1
Fourth Newest item from content type 2
Fourth Newest item from content type 3

Page 3
Etc.

Is this something that requires a custom module with hook_views_query_alter? If so could someone help me out with how I should build the expression in my module?

You just need to set a correct order in your 'sort criteria', post date first, then content type.


Drupal 8 Title tag - head-placeholder I am using a custom theme with Stable as a base.

I am trying to figure out how to set the <title> tag and I'm having a hard time.

I noticed in html.html.twig there is the following:

<head-placeholder token="{{ placeholder_token|raw }}">

How does the page title find it's way into the above?

I found a way but I'm not sure if it's ideal:

function THEME_preprocess_html(&$variables) {
  $variables['head_title']['title'] = 'title here';
}

Logic can be added for each page:

$path = $current_path = \Drupal::service('path.current')->getPath();
if ($path === '...')

Then, in html.html.twig:

<title>{{ head_title.title }}</title>

instead of

<title>{{ head_title|safe_join(' | ') }}</title>


Integrating Drupal into an existing site to manage comments I am involved in a project that wishes to post a wide range of products, and allows users to review these products. I don't want to use Drupal for the design, layout, etc. I am only interested in using Drupal for managing all of the user generated reviews. Is this integration possible, or recommended?

Could anyone please point me in the right direction for more information about the subject?

Though this is an old question, and it probably depends on what your project is using other than Drupal, from what I hear there are some decent "hybrid" CMS options out there.
You can combine Drupal with NodeJS or AngularJS.
Since you said you don't want Drupal for the design, that is called "headless/decoupled Drupal".
Here is some more information: Headless Drupal: The What, Why and How


Does DrupalWebTestCase::drupalGet() use the permissions of DrupalWebTestCase::$loggedInUser? I'm trying to test the permissions of a particular role, and this code:

$this->drupalLogin($this->editor_user);
$this->drupalGet($node->path['source']);

returns a 200 (OK) status, when I'm expecting a 403 (forbidden).

Does DrupalWebTestCase::drupalGet() ignore the permissions of the currently logged-in user, and if so, how can I test page view permissions?

Permissions to access the page are considered. ContactPersonalTestCase::testPersonalContactAccess() uses the following code to check users has permission to access the right contact pages.

  // Test allowed access to user with contact form enabled.
  $this->drupalLogin($this->web_user);
  $this->drupalGet('user/' . $this->contact_user->uid . '/contact');
  $this->assertResponse(200);

  // Test denied access to the user's own contact form.
  $this->drupalGet('user/' . $this->web_user->uid . '/contact');
  $this->assertResponse(403);

  // Test always denied access to the anonymous user contact form.
  $this->drupalGet('user/0/contact');
  $this->assertResponse(403);

  // Test that anonymous users can access the contact form.
  $this->drupalLogout();
  user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('access user contact forms'));
  $this->drupalGet('user/' . $this->contact_user->uid . '/contact');
  $this->assertResponse(200);

$this->web_user, and $this->contact_user are initialized using the following code.

$this->web_user = $this->drupalCreateUser(array('access user contact forms'));
$this->contact_user = $this->drupalCreateUser();

If the permissions assigned to the test user would not be considered, the first test would fail, as only users with the "access user contact forms" permission can see the contact page of another user, and by default users don't have that permission.


How can I list all the pages of a Drupal site in csv format? My goal is to get a .csv file list of the titles/urls for all "pages" in a Drupal site, including all Views, panel pages, and nodes, etc.

Potential incomplete solutions:

Using the xmlsitemap module to generates xml then convert it to .csv format. This gets content types and menu links, but not views pages or panel pages or other cases. The downside here is that it only outputs the urls. It'd be nice to also have the titles.
Querying menu_links or menu_router tables. These list all the drupal paths, but not node paths or anything that requires the variable substitutions, ie "node/%".

I'm curious if there is a more straight forward way to do this. Any thoughts?

I wrote a dirty script to query the node, menu_router, and menu_links tables: https://gist.github.com/dooug/b102a683d4e4854defba

This could be improved upon. The upside is that it includes "path,title" of all nodes, panel pages, view pages, etc. The downside is it includes all admin pages. Also, it includes lots of duplicates between the menu_links and menu_router tables. Please fork with your suggestions.


How can i make my solr search case sensitive? I am using search api and search api solr module,
currently my search is case insensitive with following configration.

<fieldType name="text" class="solr.TextField" positionIncrementGap="100">
<analyzer type="query">
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>

if i remove <filter class="solr.LowerCaseFilterFactory"/> it becomes case sensitive.
How can i have both the thing?

Original answer from: https://stackoverflow.com/questions/10205688/how-to-make-field-search-not-case-sensitive-in-solr-using-solrnet

You could use a copyfield that converts the field in question to lowercase.

Similar problem/solution: https://stackoverflow.com/questions/2053214/how-to-create-a-case-insensitive-copy-of-a-string-field-in-solr


General Approach in Zen-Theming: 3 different fixed-width layouts based on viewport-size I am building a zen-subtheme which should have 3 breakpoints depending on viewport-size, but none of the layouts has sidebars, there is a small horizontal navigation for all layouts.
By default, Zen provides a responsive-sidebars.scss and fixed-width.scss - since i need media-queries on one hand but no fluid sidebars etc. on the other hand, i don't know, what's the best way to go.

Zen 5 has mobile/responsive built-in, and it works really well. I found the conversion from Zen 3 fixed to Zen 5-Responsive fairly easy, and I went with the dev version (Jan 2013). As suggested, you could take out all the sidebars, but they don't really get in the way.

I had to spend some time learning responsive images, in particular responsive background images.


How to create a module to allow for multiple instances of the same module with different variable parameters How do you create a module to allow for multiple instances of the same module block with different variable parameters. I know how to create global parameters but that will apply to that block across the site.

this is an image of opening up the settings for the block on the panel

Generate your blocks same way block module does: appending an id. Then store your configuration indexed by this id. You can store your values in a custom table (see schema api and install file syntax) or in the variable table (using variable_get() and variable_set()).

Whenever an operation with a block happens you receive the block id. Use the block id to access or set your configuration data. For example, the code for rendering a block should be the same for all your custom blocks, but you feed that code with different configurations that you read from your custom table or variable table using the provided block id.


CAS-protected webform does not submit I have a form that was created using Webform 7.x-4.0-rc3. The completed form submits successfully, form values are stored correctly, notification emails are generated, and the confirmation page is displayed.

I want to ensure that only CAS-authenticated users can access this form. With CAS 7.x-1.4 installed on my site, I've updated the CAS configuration and added the form page's URL to the "Require CAS login for specific pages" list. Redirection to CAS and CAS authentication work as expected.

However, the completed form will not submit for a CAS-authenticated user. By dumping $form_state during the execution of drupal_build_form(), I can see that after the user completes the form and submits, $form_state contains none of the values of the completed form and drupal_build_form() treats it as a newly loaded form.

Somehow the interaction with the CAS server when the authenticated user submits is causing the form to be reinitialized, but I don't know where/how.

Anyone have suggestions for how to attack this? Thanks in advance....

It sounds like your relying on CAS to provide an access check to the URL path. Webform supports limiting access to a webform by drupal Role.

If your user has authenticated via CAS and is logged into the site simply limit the webform access to users with Authenticated Users or any non-Anonymous user role.


Media Browser in WYSIWYG editor doesn't allow uploads for non-admins As admin everything works as expected. I can upload images. As a non-admin user I can use the "Web" and "Library" functions but not the file upload function.

I have it enabled:

And the user has the correct permissions applied:

There are two things need to be configured for WYSIWYG editor.

First settings can be found on admin/config/media/browser. Either you check all available plugins like you have done in screenshot or leave all unchecked for allowing all. That's already done by you.

Next is to check permissions, where you have to give Add and upload new files, view own files etc permissions (like my screenshot below)

Another permission to check is Use media browser, which you must have done & so that it's appearing. Once these are in place, it should work for the role you are checking.


Module configuration translation I cannot find any good examples on how to make a module configuration translatable. Could someone give me a starter example to build off with?

In config there are only few field types that are translatable by default text, label and i think date_format(you can check the schema types to see which field types exactly are translatable by default). You can also make any value translatable by adding the translatable: true flag to the field. Now, copy your config/install directory into config/install/language/LANGCODE and edit each one of those config files and keep only the translatable fields..and translate those :)

If you want to provide translations for you module so t() function will pick them up, that is a bit strange in D8 compared to D7 but to put it simply you have to edit your module's info file and put in the following lines:

'interface translation project': yourprojectname
'interface translation server pattern': relativepathtotranslationsdirectory/%project-%version.%language.po


How to check whether one's current User Points are negative with the Rules module? My question is pretty straightforward: how can I check whether a user's current amount of User Points is negative with the Rules module? I'd like to create an action that should be activated when the user is granted User Points. The event is set, but I don't know how I can set the condition.

Edit: I enabled the PHP filter module in order to get the 'Execute custom PHP code' option in my Rule's conditions. (I didn't know that I had to do this before...) I used this code to check whether the user's User Points are negative:

global $user;
$num_pts = userpoints_get_current_points($user->uid, 'all');
$neg_pts = $num_pts < 0;

Unfortunately, it's always evaluated as 'false', even when the amount of User Points is negative. I've also tried this:

$num_pts = userpoints_get_current_points([userpoints-transaction:user]->uid, 'all');
$neg_pts = $num_pts < 0;

But that didn't work either (same reason). I don't get any error messages in both cases.

Are these code snippets wrong? How does the correct one look like?


Ajax Callback Function in Submit Button Doesnt Work I have a submit button in my form and I want to implement it using ajax:

function myid_user_page_form(){

   drupal_add_library('system', 'drupal.ajax');

   $form = array();

   $form['id'] = array(
       '#type' => 'fieldset',
       '#title' => t('ID Information'),
       '#prefix' => '
',
       '#suffix' => '
'
   );

   $form['submit'] = array(
      '#type' => 'button',
      '#value' => 'Save',
      '#ajax' => array(
         'event' => 'click',
         'callback' => 'myid_user_page_form_ajax_submit',
         'wrapper' => 'myid_search_id_number_wrapper'
      ),
      '#attributes' => array(
        'id' => 'myid_save',
    ),
);

function myid_user_page_form_ajax_submit($form, &$form_state) {
    watchdog('Wow','Wow');
}

After executing the code above, the page still has it's refresh after it's clickfunctionality. The ajax doesnt work and no Wow message log in my watchdog table from my database, which means the ajax callback function isn't called. Where am I missing?

It is because you are changing the id attribute of the button.
The ajax in Drupal automatically attaches the javascript event listener to the submit, but it expects the button the have the automatically generated id.
Adding or changing the class attribute should not affect it though.

All the suggestions TerryCB made in the comments are also valid.


Manually invoking Ajax Commands when an ajax callback is not an #ajax form callback My original post caused some confusion, so I'm re-writing it for clarity.

In Drupal, if you have an #ajax callback in a form, you can do something like this:

function my_ajax_callback(array &$form, FormStateInterface $form_state)
{
  $response = new AjaxResponse();
  $response->addCommand(new AlertCommand(t('This is from an ajax callback'));
  return $response;
}

This in turn triggers Drupal.ajaxCommands.prototype.alert(), which is located in ajax.js.

Alternatively, I can create an ajax callback of my own, that has nothing to do with a form. example.routing.yml:

mymodule.ajax
  path: '/mymodule/ajax'
  defaults:
    _controller: 'Drupal\my_module\Controller::ajaxCallback'
  # (remainder not shown)

I can create an AjaxResponse in this callback:

class Controller extends ControllerBase
{
  public function ajaxCallback()
  {
    $response = new AjaxResponse();
    $response->addCommand(new AlertCommand(t('This is from an ajax callback'));
    return $response;
  }
}

In this case, debugging has shown me that the AjaxResponse returns my command to the browser, but Drupal.ajaxCommands.prototype.alert() is not triggered.

Further debugging has shown me that ajax commands are only triggered if the AjaxResponse comes from an #ajax callback in a form, not if it's from a non-form ajax callback.

So my question is, does anyone know how to invoke ajax commands when the commands are returned from non-form ajax callback?

Like @Gaius I don't know exactly what @Jaypan wants to achieve. This example might help to make this clearer:

        var response = JSON.parse(content);
        // Create a Drupal.Ajax object without associating an element, a
        // progress indicator or a URL.
        var ajaxObject = Drupal.ajax({
          url: '',
          base: false,
          element: false,
          progress: false
        });
        // Then, simulate an AJAX response having arrived, and let the Ajax
        // system handle it.
        ajaxObject.success(response, 'success');

Normally you set an URL in Drupal.ajax() and then use ajaxObject.execute() to run the Ajax request. This example from big_pipe.js only simulates the Ajax request and then runs the Ajax commands contained in content.


Hiding the site domain name from the content writers I'm in dilemma. I'm hiring content writers etc for my new sites who risk getting fired from me for not meeting my expectations. I want to keep my site names confidential from the world because of competition and other concerns.

What is the best way to hide the domain name also allowing them to add the content(articles, forum posts etc) straight-forwardly at my production site ?

I was thinking to symbolic link( on my Centos hosting) another idle domain name to point to my site. I'd use relative urls in my site content so Pathauto would take of this. So the content writers would see this idle domain when working on my site.

A site can be visible from multiple domains. For example I can install the same site on my localhost PC. Secondly there are more than 50 million sites. For new sites it'd take a couple of months for a site to start appearing in the top 100 results in Google. How'd a naive person find the site in short time? Hiding the domain name means suppose I've a site name myjobs.com I want to make it visible in somejunk.com domain too and editors will add content in this site.

As long as you have your server configured properly (ie, have your ServerName and ServerAlias directives set right for Apache), then this should work our of the box as long as you don't explicitly set the cookie domain or base URL in your settings.php.  A potential complication is if you have any rewrites for canonical URLs on your site.

However, I think your best approach is to use the Domain Access module to run two sites out of the same installation.  Have one affiliate be for the live domain, and the other affiliate be for the authoring domain.  Then separate the content / themes as needed.  When content is OK, just move it from the authoring affiliate to the live affiliate.


Query pager not showing for administrator I am having an interesting problem with paging the results of a query. The pager is visible to all users except those who are assigned the built-in 'administrator' role. I have tried the code on two separate Drupal installs and the result is the same: the administrator cannot see the pager. The markup is not visible in the page source.

I have tried my solution using both EntityFieldQuery and db_select, but the problem persists. Here is the code for the EntityFieldQuery version:

function build_area_table() {
  $header = array(
    'area_name' => array(
      'data' => 'Area',
      'type' => 'property',
      'specifier' => 'title',
      'sort' => 'asc',
    ),
    'level_range' => array(
      'data' => 'Level range',
      'type' => 'field',
      'specifier' => array('field' => 'field_area_level_range', 'column' => 'value'),
      'sort' => 'desc',
    ),
  );

  $query = new EntityFieldQuery();
  $query = $query->pager(5); # I have more than 5 rows being returned
  $query = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'area')
    ->propertyCondition('status', 1)
    ->tableSort($header);

  $result = $query->execute();

  $nodes = null;
  // $result['node'] contains a list of nids where the title matches
  if (!empty($result['node'])) {
    // You could use node_load_multiple() instead of entity_load() for nodes
    $nodes = node_load_multiple(array_keys($result['node']));
  }

  // do something to output your results here.
  $td = array();
  foreach ($nodes as $area) {
    $td[] = array(
      'area_name' => array(
        'data' => l($area->title, 'node/'. $area->nid),
        'class' => array('area-name'),
        ),
        'level_range' => array(
          'data' => $area->field_area_level_range['und'][0]['safe_value'],
          'class' => array('level-range'),
        ),
    );
  }

  $areaTable = array(
    'area-table' => array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $td,
      '#empty' => 'No areas to display.',
    ),
    'area-pager' => array(
      '#markup' => theme('pager')
    ),
  );

  return $areaTable;
}

The table is rendered using Drupal 'render' in the template page. Does anyone have any ideas as to what the problem may be? I have read some posts regarding changing the pager ID, but any changes I make do not seem to have any effect.

EDIT: I am not using the Views module, which seems cause a conflict with pagers as reported by many other people.

Thanks!

Looks like I found the answer. It appears easier (and more efficient) to use the db_select instead, at least for the number of fields I am sorting on. As suspected it was the pager colliding with another pager on the page, although I am not sure what pager this could be. The pager seems to working fine for all users now that I added '->element(0)' to the db_select. Here is some code:

function build_area_table() {
  $header = array(
    'area_name' => array(
      'data' => 'Area',
      'field' => 'n.title',
      'sort' => 'asc',
    ),
    'level_range' => array(
      'data' => 'Level range',
      'field' => 'flr.field_area_level_range_value',
      'sort' => 'asc',
    ),
  );

  $query = db_select('node', 'n')
            ->extend('PagerDefault')->element(0) # fix displaying pager for all users
            ->extend('TableSort');
  $query->join('field_data_field_area_level_range', 'flr', 'n.nid = flr.entity_id');
  $result = $query
    ->fields('n', array('nid', 'title'))
    ->fields('flr', array('field_area_level_range_value'))
    ->condition('type', 'area')
    ->limit(2)
    ->orderByHeader($header)
    ->execute();

  # build the table
  $td = array();
  foreach ($result as $area) {
    $td[] = array(
      'area_name' => array(
        'data' => l($area->title, 'node/'. $area->nid),
        'class' => array('area-name'),
        ),
        'level_range' => array(
          'data' => format_area_level_range($area->field_area_level_range_value),
          'class' => array('level-range'),
        ),
    );
  }

  $areaTable = array(
    'area-pager' => array(
      '#markup' => theme('pager')
    ),
    'area-table' => array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $td,
      '#empty' => 'No areas to display.',
    ),
  );

  return $areaTable;
}

I could probably achieve the same using EFQ, although I can't find an EFQ version of '->element()'. I tried specifying the element via theme like so:

theme('pager', array('element' => 0))

but there would need to be some kind of check based on the user role, as 0 works for administrators but not for other roles and vice versa. Hopefully this can save someone else some time as well!


Drupal CRM Core releases I'd like to install CRM Core module for one of my clients. But I cannot decide which release to use - stable or development. The Recommended release (7.x-0.964) looks more confusing to me while the Development release (7.x-1.x-dev) looks more logical. But I don't know if there any risks of using Development release in production.

Could you please advise the right way to go.

Thanks in advance!

The fact that the stable release has an unusual version number doesn't mean there is anything wrong with it.

It's just the way they are doing there releases.

If you look at all the crm core releases you can see that the first stable release was 0.9.

I would guess they have done this so that they may be able to get more people using it and fix any issues that arise before having a 1.0 release.

So 1.0 will be the next major release.

Then they use versions 0.91, 0.92, 0.93, ... as the intermediate level releases and for minor releases in between those they use numbers like 0.911, 0.912, 0.913, ....

When choosing a version of any module this would be my advice:

Use the latest stable release.

If you encounter any problems with latest stable then check the issue queue for possible fixes and if you need a patch to apply to latest dev or latest dev has already fixed the problem then try using it.

Remember though to test to make sure everything still works as it should as the dev version may have introduced new issues even though it fixed your previous issue.

Also take a database backup before updating module versions in case the newer version is broken and you need to roll back.

Another reason you might want to use dev would be if you know that there are new features in dev that you want that aren't in the latest stable.

But really, if there is a stable release (especially a recommended stable), don't use the dev version instead of the stable release unless you have a good reason to.

Unusual version numbering is not a good reason.


Edit access by checking the field? Is it possible to check the privileges for a particular field? For example, I have a field in the material field_access associated with the user who accepts an ID of the user. How to check access to edit the material through it? Currently editing is possible only if the user specified in the authors.
(Google translate. Sorry for that)

Maybe you're looking for this module : Field Permissions

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


Page title always displaying "Error" I am porting the Disqus module to Drupal 8.

The new routes are working fine, except for the page title, which always displays "Error" instead of the desired title. I have already implemented hook_menu().

What am I doing wrong?

There is something wrong in the error handling with recoverable fatal errors.

They're not displayed but the affect the page title. Have a look at the watchdog output, there you should see some PHP errors.

This is a bug, so not really a good question for here, but for the time being, might help others.

Opened https://drupal.org/node/2100123


Embed a "node add" form in a page I'm looking for a way to embed a "node add" form on a landing page.
I was using Form Block, but it appears to bring many error because I was using a development snapshot version.

You can use:

module_load_include('inc', 'node', 'node.pages');
$form = node_add('nodetype');
print drupal_render($form);


Change size of the time textbox I want to change the size of the time textbox but I can't find a way to do it.

    $form['feld']['start'] = array(
        '#type' => 'date_popup',
        '#title' => 'Start',
        '#size' => 10,
        '#date_formant' => 'd.m.Y',
        '#date_year_range' => '0:+1',
        '#default_value' => date('Y-m-d H:i'),
        '#date_timezone' => 'Europe/Rome',
        '#date_increment' => 15,
        '#required' => TRUE,
);

'#size' => 10 only effects the date textbox.

This is an example.

How do I alter also the size of the textbox used for the time?

Looking at the source code it appears that both date and time have a #size key. I don't have time to test this, but you might be able to access it from the 'time' element of the field.

$form['feld']['start']['time']['#size'] = 10;


allow users to continue the survey (webform) if closed by accident I wonder if there is a way of let users continue with survey (webform) in case they close the browser or the tab. For example:

I have a very long webform survey, it has like 30 questions, if Users start answering the survey today I need to let them continue with it if they close it and reopen it tomorrow.

example the url ot my survey is "node/1"

so if user begins the survey and closes it, then tomorrow he must be able for login and go to "node/1" and continue with the survey, right now users have to start over if they close the tab.

any idea? suggestions?

Thank you

It's simple. Go to your webform and add page break type wherever you want to split the form.

Then go to Form Settings and check Automatically save as draft between pages and when there are validation errors. or Show "Save draft" button.

If you want to go further, meaning if you want to save a draft when user closes the browser. check Use AJAX to auto save a draft


Showing previous and next pager links regardless of the page one is in Drupal hides the previous link  of a pager if you are the first page,and the next link if you are on the last page. Is there way I can keep the links from disappearing, just in a disabled state? Can I do this without using php?

Probably not, to do this you would have to use theme_views_mini_pager().

Reference: http://drupalcontrib.org/api/drupal/contributions%21views%21theme%21theme.inc/function/theme_views_mini_pager/7

Example:

if (empty($li_previous)) {
   $li_previous = "&nbsp;";
}

That is whats doing it...


How remove whitespace on field in twig? I try to print field value in a node--template.html.twig without whitespace.
This field is a select in admin page.

Location|Location
Achat|Achat

This is how my value is print :

  {{ content.field_type }}

  field.html.twig :

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

I try some twig argument like

  {{content.field_type|trim}}

But when i print like this, it's empty.

So where are this whitespace ? same if i try to test the value in if else condition :

This doesn't work because of whitespace :

  {% if  content.field_type == "Achat" %}

This work :

  {% if  content.field_type|render|trim == "Achat" %}

So for test a value it's ok, but for print the value if i use

  {{content.field_type|render|trim}}

i got same result with whitespace.

So if someone can tell me where is add this whitespace and how remove this in twig.
I use the boostrap theme, but i don't see anything who add whitespace.

It sounds to me that you have a template, probably field.html.twig that is adding this space. You can enable the twig debug to see which templates' files are used.

Also, I think it's better to test the value on node.field.value instead of content.field as it's done for the rendering only.

Note that the twig operators as {% for ... %} also add spaces, so you should add - as well in there for e.g.:

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


ajax_deliver returns json instead of content I have a panel with two columns. In the left is a views with teasers, in the right the full body text of a node.
If you click on a link in the views the content in the right panel should be replaced with the body text (and images).
Here the code of the module:

<?php
function customNews_menu() {
        $items['customNews/%/%node'] = array(
                'access arguments' => array('access content'),
                'page callback' => 'customNews_ajax_callback',
                'access callback' => 'user_access',
                'page arguments' => array(1,2),
                'type' => MENU_CALLBACK,
        );
        return $items;
}

function customNews_ajax_callback($js, $node) {
    if ($js == 'nojs') {
        drupal_goto('node/' . $node->nid);
    }
        $div_id = 'customNewsContent';
        $vnode = node_view($node);
        $vnode['is_ajax'] = true;
        $output = '
'.theme("node", $vnode).'
';
        $commands = array();
        $commands[] = ajax_command_replace('#'.$div_id, $output);
        $page = array('#type' => 'ajax', '#commands' => $commands);
        ajax_deliver($page);
}
?>

When I run it I get the following back in the browser:

[{"command":"settings","settings":{"basePath":"\/drupal\/","pathPrefix":"","ajaxPageState":{"theme":"seeleben","theme_token":"wdFHgqik_Sx4kvKrKXtT9tAndWxYgNr2-cO6lfT09gg"},"colorbox":{"opacity":"0.85","current":"{current} of {total}","previous":"\u00ab Prev","next":"Next \u00bb","close":"Schlie\u00dfen","maxWidth":"98%","maxHeight":"98%","fixed":true,"mobiledetect":true,"mobiledevicewidth":"480px"}},"merge":true},.........

What do I do wrong?

You are almost there!

You are opening a serious security hole in your site, allowing anyone who has access content permission to access all nodes bypassing node access system.

Assuming you need to use ctools's Ajax framework extension, you obviously need to have ctools module enabled.

1. Change your menu loader to this:

$items['customNews/%ctools_js/%node']

This will make Drupal pass the second %ctools_js argument to ctools_js_load function that returns TRUE if nojs was changed to ajax.

2. The link.

Ctools won't change all "nojs" occurrences in the page. You need to create a special link using ctools_ajax_text_button function, or by adding classes to the link.

<?php
  ctools_include('ajax');
  ctools_include('modal');
  ctools_modal_add_js();
  print ctools_ajax_text_button(t('Read more'), 'customNews/nojs/1'); //1 is the node ID. Replace accordingly. You need to use "nojs" here.
?>

3. Almost there!

Your code should work now. However, make sure you have proper node access checks before showing anything. SA-CORE-2-14-005 was touch enough.

if ($js == 'nojs') {
        drupal_goto('node/' . $node->nid);
    }

Can be changed to:

if (!$js) {
  drupal_goto('node/' . $node->nid);
}

The importance of this "special link" is that ctools's JS registers all anchor tags in Drupal.ajax that follows the class name convention. For my own use, I have a small function that returns the proper link so I don't have to include ctools's ajax.inc file.


Highlighting primary link for specific content types If I have a navigation item called 'News' in my primary links, how would I go about highlighting it for all news content type nodes?

Thanks!

For Drupal 6 you have the choice of using the Menu Trails module, or the Menu Position module, which is available for both 6 and 7.

Both modules let you define criteria for where nodes should appear in the menu structure (eg, based on node type, and taxonomy).


Secondary Menu Tab (local task) I was wondering if there is any good documentation out there on building second level tabs using the menu system. Here is some of the menu code in my module:

  $items['admin/settings/cvminterviews'] = array(
    'title' => 'Interview Scheduler',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'cvminterviews_overview_page',
    'access arguments' => array('administer cvminterviews'),
  );

  $items['admin/settings/cvminterviews/overview'] = array(
    'title' => 'Overview',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'cvminterviews_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10
  );

  $items['admin/settings/cvminterviews/interviewers'] = array(
    'title' => 'Interviewers',
    'description' => 'Interviewers',
    'file' => 'cvminterviews_admin_interviewers.inc.php',
    'page callback' => 'cvminterviews_interviewers_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

  $items['admin/settings/cvminterviews/interviewers/import'] = array(
    'title' => 'Import Interviewers',
    'description' => 'Import Interviewers',
    'file' => 'cvminterviews_admin_interviewers_import.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_interviewers_import_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

I would like to have

  admin/settings/cvminterviews/interviewers/import

Be a secondary tab to:

  admin/settings/cvminterviews/interviewers

but the above code doesn't seem to do anything with it. Any thoughts?

I needed to add the following to my code:

  $items['admin/settings/cvminterviews/interviewers/interviewers'] = array(
    'title' => 'Interviewers',
    'description' => 'Interviewers',
    'file' => 'cvminterviews_admin_interviewers.inc.php',
    'page callback' => 'cvminterviews_interviewers_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

The important part is to make this the exact same callbacks as the 'admin/settings/cvminterviews/interviewers' menu item, but with one more level, and assign the MENU_DEFAULT_LOCAL_TASK type.


In editing content, can I show source formatted HTML Might there be a way to show properly formatted HTML when in CKeditor's source view? Is there a way to color code the HTML and Javascript source for my more advanced content editors?

I have turned on Apply Source Formatting which has helped some.

Syntax highlighting is your keywords.  I uncovered this for you.
http://code.google.com/p/ckeditor-syntaxhighlight/wiki/Installation

There is most likely more plugins available but you will need to add a plugin to achieve what you are looking for.


'Views Field' issue in NO RESULTS BEHAVIOR - Hide if empty not working 'Hide if empty' configuration of views is not working properly as a result all the empty fields are showing.

Is there any work around to force fully hide empty fields in the views result (Page/block) neither using the configuration under 'No Results behaviour nor using views-php/block-php?

Your questions does not give much information about your view, but if you want to hide the complete output of a row (when using a table) you can do this:

  You can add filter criteria corresponding to the field on which you
  want to hide  the row . Suppose you want to hide the row if content:
  body is empty then you can add filter criteria as Content:Body not
  equal to "" (where value field should be left empty). This will
  automatically hide the row if the specific field is empty .

source: Hide row in view if any field is empty


How to make tokens display correctly? I created a blog site and I used the Display Suite module to create a layout for the article content type. In one of the regions I created a custom code field that had "Posted by [user:name] on [node:created:long]".

After creating it I noticed that only the date was showing up and not the user token. I tested this out with several of the user tokens and none of them seemed to work. The only thing I can think of is that users tokens aren't supposed to work in Display Suite, but I couldn't find any proof one way or another.

The second issue is involving the number of views to a particular node. When I go to drupal.org, there is a list of tokens. The one I am trying to use is [node:source:total-count], but nothing appears. I read that it might be a more in depth process than a simple token.

The token used to get the user who wrote the content is not [user:name]. This is the username of a user account that you are trying to view, so this might not be available on the node page as we are not referring a user.

To display the author name you should use [node:author:name].

If you install the token module you could go to the Help > Token (admin/help/token) page and see the available tokens.

For more details and a list of the available tokens, see this page.

EDITED As per suggestion in comment.


Drupal 7 PHP version migration from PHP 5.3 to PHP 5.6 Our current Drupal 7 site runs on PHP 5.3 environment. But the server provider insisting to upgrade the PHP version to PHP 5.6 as they are about to end the support for PHP 5.3 and PHP 5.5 .

Is there any known issues for an existing Drupal 7 site migration into php 5.6?

Any tools/modules to check the version compatibility of current Drupal 7 in PHP 5.6 ?

Other than this any suggestion or advices prior to the migration ?

Is there any known issues for an existing Drupal 7 site migration into php 5.6?

For Drupal core specifically, that information will be in the issue queue. A quick search for "5.6" brings up no results. It it helps, I've been running D7 on 5.6 for ages now with no problems.

Contrib modules might be a different story, you'll need to check each of those individually, unless they offer that info specifically on the project page, or through a minimum PHP version specified in the module's .info file.

  Any tools/modules to check the version compatibility of current Drupal 7 in PHP 5.6 ?

Not Drupal-specific tools (it wouldn't make sense for there to be since this just a plain PHP question). You can probably make good use of something like PHPLint. Personally I would start with IDE tools (switch the language version to 5.6, run a validator, then check the current issue list for errors)

  Other than this any suggestion or advices prior to the migration ?

The only sane advice is for you to treat this as any other upgrade, whether that be code or server - make sure the site is fully tested in a development environment before pushing anything live. Have a plan in place to downgrade quickly on the live servers in case something goes wrong. If that's not an option (i.e. you don't control the server software), then re-double your testing efforts, and make sure server config is as identical as you can get it before pushing anything live.


drupal ahah not working I'm trying to make a ahah form. the problem is the ahah is ignored. when i check the classes on the submit button, it doesn't have the 'ahah-processed' class. The really interesting thing is that ahah is working perfectly on my site, and even on a nearly identical form I created. this is how i'm creating the ahah submit button:

$form['ri_email_submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#weight' => 1,
        '#submit' => array('ri_email_form_submit'),//none JS version
        '#ahah' => array(
          'event' => 'click',
          'path' => 'ri_email/ajax',
          'wrapper' => 'email-friend-wrap',
          'method' => 'replace',
          'effect' => 'fade',
          'progress' => array(
            'type' => 'bar',
            'message' => t('Loading...')
          )
        )
        );

I checked the menu path, it's correct.

UPDATE: this is the menu callback:

function ri_email_ajax() {
    return drupal_json(array('status' => TRUE, 'data' => '
Your email has been sent.
'));   }

by the way, i discovered that it didn't work when i invoked drupal_get_form() from page.tpl.php, but it does work from node.tpl.php

there is something missing with the javascript that is supposed to handle the ahah

Can you post the callback function generating the page at 'ri_email/ajax'?

It should look something like this:

<?php
  function awesome_ahah_callback() {
    $thing_to_process = $_POST['thingfromform']
    /* do stuff, including generating some kind of $processed_data variable */

    drupal_json(array(
      'status' => TRUE,
      'data' => $processed_data,
    ));
    exit();
  }
?>

If you aren't generating the thing you want to send back through AHAH with drupal_json and then calling exit() then I don't think it will work.


Is there a module that saves the node while you are creating it? I have a blog, I write blogposts everyday. Today I was creating a blog post, I was almost finished, but for some reason my computer turned off. I lost all that I had in my article I have to write it again.

Is there a module or something that saves the node while you are creating it?

Looks like you need the Autosave module. Here is an excerpt from its project page:

The Autosave module automatically saves a snapshot of your content type form using AJAX. If the user's browser or machine dies while editing a node; the edits will be presented to the user the next time they return to the node. The user may toggle back and forth between the last saved version and the version with the edits that were lost and select which of these they would like to continue with.
How often a form is autosaved as well as which content types to enable autosave for are admin configurable.


Recommendation On Search Form For People We want to develop a 'Directory' of People in our organisation (a View) with search form that lets authenticated users search for one another by last name or User ID.

I'm looking for recommendations on the best way to do this as we will have literally thousands of 'People' and I don't want the standard widget with 'people' which I fear would be dreadfully slow. All I need is a text field and the SQL equivalent of...

Lastname LIKE('FRA%') OR UserID LIKE('FRA')

...where the user typed 'FRA' into the form. They would get all users (People) with a last name starting with 'Fra'.

Is there a pre-built module that someone can suggest that does this, or can someone provide some (basic) guidance on how to implement this on a View?

I looked at the default Search User tab and I didn't see a way to theme this to include various fields we will need such as the user's photo and so on.

TIA

I would recommend using the views module.

This is kind of a duplicate of your other question How to implement 'Starts With' for exposed filter of User ID, where I explained how to do what you want with views.


How to add custom email to account user emails? There are a few email templates in account user emails page: "/admin/config/people/accounts".

How can i add custom emails from my own module? I would like to have&edit all email templates in the same place.

This form is defined in core user module, user.admin.inc file:

/**
 * Form builder; Configure user settings for this site.
 *
 * @ingroup forms
 * @see system_settings_form()
 */
function user_admin_settings() {

Particularly, line 444 starts email template section:

$form['email'] = array(
    '#type' => 'vertical_tabs',
  );
  // These email tokens are shared for all settings, so just define
  // the list once to help ensure they stay in sync.
  $email_token_help = t('Available variables are: [site:name], [site:url], [user:name], [user:mail], [site:login-url], [site:url-brief], [user:edit-url], [user:one-time-login-url], [user:cancel-url].');

  $form['email_admin_created'] = array(
    '#type' => 'fieldset',
    '#title' => t('Welcome (new user created by administrator)'),
    '#collapsible' => TRUE,
    '#collapsed' => (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) != USER_REGISTER_ADMINISTRATORS_ONLY),
    '#description' => t('Edit the welcome e-mail messages sent to new member accounts created by an administrator.') . ' ' . $email_token_help,
    '#group' => 'email',
  );
  $form['email_admin_created']['user_mail_register_admin_created_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => _user_mail_text('register_admin_created_subject', NULL, array(), FALSE),
    '#maxlength' => 180,
  );

As you can see, there is no foreach, no external hook call, nothing. Just raw fields hardcoded. The only way is to add your fields using hook_form_alter(). Make sure you also add your validators and submit handler to take care of your new fields, because user module will not do it for you.


How to set default reply-to address in webform? I am using Webform Reply to module to set Reply to address for mails sent from webforms. This feature works fine but for each webform creation I have to set Reply to address because by default it will select  Default: No Reply-To address option. But I want to select a default address as xyz@mail.com . So how can i achieve that?? For reference see image below:

in your form, create an email field  that contains the email you want to have for your reply-to.  now hide it(don't display..making it private might suit, or use css).  This hidden email field value will be accessible in the component pulldown


Problem in dependency injection in drupal custom module service I face with a problem in defining service in drupal 8.0
my service is :

services:
  tracking.middleware:
    class: Drupal\mkt_tracking_v2\Middleware\TrackingMiddleware
    arguments: ['@kernel','@config.factory','@request_stack']
    tags:
      - {name: http_middleware, priority: 1000}

the problem is: the object that passes to TrackingMiddleware aren't based on the arguments definition.

as I get this error :

  Thu Apr 04 01:51:23.919189 2019] [php7:notice] [pid 28435] [client 127.0.0.1:51962] TypeError: Argument 2 passed to Drupal\mkt_tracking_v2\Middleware\TrackingMiddleware::__construct() must implement interface Drupal\Core\Config\ConfigFactoryInterface, instance of Drupal\Core\DrupalKernel given, called in /home/hossein/Project/Drupal/8.7/web/core/lib/Drupal/Component/DependencyInjection/Container.php on line 274 in /home/hossein/Project/Drupal/8.7/web/modules/Marketing/mkt_tracking_v2/src/Middleware/TrackingMiddleware.php on line 41 #0 /home/hossein/Project/Drupal/8.7/web/core/lib/Drupal/Component/DependencyInjection/Container.php(274): Drupal\mkt_tracking_v2\Middleware\TrackingMiddleware->__construct(Object(Drupal\Core\StackMiddleware\NegotiationMiddleware), Object(Drupal\Core\DrupalKernel), Object(Drupal\Core\Config\ConfigFactory), Object(Symfony\Component\HttpFoundation\RequestStack))\n#1 /home/hossein/Project/Drupal/8.7/web/core/lib/Drupal/Component/DependencyInjection/Container.php(171): Drupal\Component\DependencyInjection\Container->createService(Array, 'tracking.middle...')\n#2 /home/hossein/Project/Drupal/8.7/web/core/lib/Drupal/Component/DependencyInjection/Container.php(480): Drupal\Component\DependencyInjection\Container->get('tracking.middle...', 1)\n#3 /home/hossein/Project/Drupal/8.7/web/core/lib/Drupal/Component/DependencyInjection/Container.php(230): Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array)\n#4 /home/hossein/Project/Drupal/8.7/web/core/lib/Drupal/Component/DependencyInjection/Container.php(171): Drupal\Component\DependencyInjection\Container->createService(Array, 'http_kernel')\n#5 /home/hossein/Project/Drupal/8.7/web/core/lib/Drupal/Core/DrupalKernel.php(1412): Drupal\Component\DependencyInjection\Container->get('http_kernel')\n#6 /home/hossein/Project/Drupal/8.7/web/core/lib/Drupal/Core/DrupalKernel.php(693): Drupal\Core\DrupalKernel->getHttpKernel()\n#7 /home/hossein/Project/Drupal/8.7/web/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))\n#8 {main}, referer: http://drupal.local/admin/modules/uninstall

  but as i define the class in this way the constructor parameters is right :

 public function __construct(HttpKernelInterface $app,ConfigFactoryInterface $configFactory,RequestStack $requestStack) {
    $this->app = $app;
    $this->configFactory = $configFactory;
    $this->requestStack = $requestStack;
  }

did I do any mistake in service definition?

From the looks of the core middleware services, the HTTP kernel is automatically provided to the constructor. You don't have to specify it (and even if you did, @kernel is Drupal's kernel, so might not be what you meant).

As an example, ReverseProxyMiddleware's constructor signature:

public function __construct(HttpKernelInterface $http_kernel, Settings $settings) {

And its services entry:

http_middleware.reverse_proxy:
  class: Drupal\Core\StackMiddleware\ReverseProxyMiddleware
  arguments: ['@settings']
  tags:
    - { name: http_middleware, priority: 300 }

Note no explicit @kernel, yet it's the first constructor argument.

So in theory you just need to change you service definition and clear caches:

class: Drupal\mkt_tracking_v2\Middleware\TrackingMiddleware
  arguments: ['@config.factory','@request_stack']
  tags:
    - {name: http_middleware, priority: 1000}


How to display taxonomy terms of a particular vocabulary in views I am trying to display taxonomy terms of a particular vocabulary in views terms field, but I am lost as to how to do it. I have done the same thing in full view mode using template.php.

Answer revised
Create a view of type Node
Add a display of type block or page according to your need
Add your desired fields(CCK) along with a field Taxonomy: Term
Add a filter Taxonomy: Vocabulary and select is one of operator and choose the particular vocabulary name.

This solution will include taxonomy terms associated with content node but filter according to the defined vocabulary in filter.


Make top level terms un-selectable in hierarchical taxonomy? I have a taxonomy like this:

Color
-blue
-green

Size
-large
-small

I need to use 1 vocabulary not 2. However I need 'Color' and 'Size' to not be selectable. If I create a hierarchal taxonomy is there a way to make certain (the top level) terms un-selectable by nodes?

Using  Hierarchical Select module you can do that and configure it to Force the user to choose a term from deepest level, see the below screenshot.

and also take a look at this Taxonomy Term Reference Tree Widget module, I think it have the option to select only child term and I'm not sure about this module.


uploaded files and images not showing When i upload a file, be it a avatar picture or image, the file loads however does not display.

I have checked the permissions on my hosting environment and it seems that everye uploaded file gets a 664 permission and apache as owner.

How can i give the uploaded files the proper permission automatically?

To fix the files permission, your folders and files needs to be readable and writable by Apache user.

Example commands to fix your permissions
(assuming www-data is your Apache user, prefix with sudo if required):

chgrp -vR www-data "$(drush dd %files)" "$(drush dd %private)"
chmod -vR ug+rwX "$(drush dd %files)" "$(drush dd %private)"

You need to have drush command available. If you don't have drush, just replace above sub-commands in double-quotes with proper locations to your %files and %private folders.

Then as Drupal admin go to Reports -> Status Report and check for file-system related warnings.


Template Files - PHP or HTML I notice most (if not all) templates are written in HTML with PHP snippets where required.

I've been writing a few PHP heavy templates, and instead of writing HTML and encasing almost every line in  tags, I have opted for writing PHP, using the print function to render HTML.

Is there any reason I should be writing in mostly HTML instead?

I imagine there's more overhead using PHP to render the HTML, but is there enough to worry about?

Second to that, is there any reason templates encase every line in  tags instead of just the opening and closing tags are required?

e.g.

<?php if($a == $b) {?>
   <?php print 'a equals b';?>
<?php } else {?>
   <?php print 'a does not equal b';?>
<?php } endif;?>

vs

<?php if($a == $b) {
   print 'a equals b';
 } else {
   print 'a does not equal b';
 } endif;?>

Overhead, if there is any, is of little concern. This is pretty much a stylistic concern. As such, the important part is a consensus among developers so there is clear readability expectations.

drupal.org has documentation when it comes to template coding standards. In this case, little-as-possible PHP tags usage is preferred (the concern here is readable HTML rendering, not code execution) with use of PHP's alternative control structure:

<?php if ($a == $b):?>
   a equals b
<?php else: ?>
   a does not equal b
<?php endif; ?>

See the documentation for further style guidelines with templates.


jQuery UI filter, Full HTML and hook_block_view_VIEW_NAME_alter I have installed jQuery UI Filter and jQuery plugins to get text with accordion effect. It works perfectly when the content is inserted in a node, with a special tags language. However, when I try to get the text rendered in a block with hook_block_view_VIEW_NAME_alter, as I am just the $data["content"]["#markup"] property, it is not working and it is displaying the special tags without rendering them: [accordion], etc.

Must I get the effect by using clean jQuery instead of the modules? Is there a way of saying that I want to apply the "Full HTML" properties to the content-markup text of the block?

I was able to make it work with the modules installed ( jQuery plugins , jQuery UI filter and jQuery UI filter accordion). The trick was to include the following Javascript in the template yourtheme_preprocess_page() and in the HTML use the div with id="accordion" of the official example ( https://jqueryui.com/accordion/ ).

drupal_add_js(' jQuery(function() {
var icons = {
  header: "ui-icon-circle-arrow-e",
  activeHeader: "ui-icon-circle-arrow-s"
};
jQuery( "#accordion" ).accordion({
  icons: icons
});
jQuery( "#toggle" ).button().click(function() {
  if ( jQuery( "#accordion" ).accordion( "option", "icons" ) ) {
    jQuery( "#accordion" ).accordion( "option", "icons", null );
  } else {
    jQuery( "#accordion" ).accordion( "option", "icons", icons );
  }
});
  });', array('type' => 'inline'));


User login using a token or ID (no password) How I am able to create a form/link to let assigned/special users to log-in to the system without entering their username and password?

I want them to be able to use a link/token to login to system instead.

This is mainly for development purpose and I am aware of the security risks on the live website

Thank you in advanced

If security's not a concern (and make sure it really isn't!) then you might as well do it the simplest way possible.

This would involve a small custom module that provides a path to log in users by their ID.

function MYMODULE_menu() {
  $items['insecure-login/%MYMODULE_insecure_login'] = array(
    'title' => 'Insecure login',
    'access callback' => TRUE, // Might as well be, no point in authenticating
    'page callback' => 'MYMODULE_insecure_login',
    'page arguments' => array(1)
  );

  return $items;
}

function MYMODULE_insecure_login_load($uid) {
  // Don't let user 1 login with this method
  if ($uid == 1) {
    return FALSE;
  }

  // Just return the user ID
  return $uid;
}

function MYMODULE_insecure_login($uid) {
  if ($account = user_load($uid)) {
    global $user;
    $user->uid = $uid;
    $user->name = $account->name;
    $user->timezone = $account->timezone;
    user_login_finalize();
    drupal_goto('user');
  }
}

Users will be able to login by visiting http://example.com/insecure-login/USER_ID

I've tested this and it worked, but it felt very wrong. The above code is just a proof of concept if you like, I can't really recommend that you use it.

Please, please double check your thinking before using any method like this; you're obviously aware of the security implications but I can't sign off this post in good conscience without encouraging you to think about it a little more ;)


How do I load templates within templates? Ok so I am writing a custom module and am trying to undestand how Drupal manages theming output.

I have registered my theme function, ie

mymodule_theme() {
    return array(
        'mylist' => 'templates/mylist-template',
        'arguments' => array('data'=>NULL)
    );
}

The mylist-template contains a HTML table with a heading row, such as:

        ID
        Name

    <?php print $rows; ?>

As you can see here I want to output x number of rows using another template file such as list-rows.tpl.php, ie:

    1
    My Name

How do I achieve this? At the moment I have a menu item with my table function, let's say:

 function mymodule_table() {
     $output = theme('list','');
     return $output;
 }

This works fine but im not sure how I would implement my rows

You need to (properly) define two theme hooks. One for your table, and the second for your rows. Then, in the preprocess function for your table, you can call the row template for each row in your data array, something like:

function MODULE_theme() {
  return array(
    'mylist' => array('arguments' => array('data' => array())),
    'mylist_row' => array('arguments' => array('id' => NULL, 'name' => NULL)),
  );
}

function MODULE_preprocess_mylist(&$variables) {
  $rows = array();
  foreach ($variables['data'] as $item) {
    $rows[] = theme('mylist_row', $item['id'], $item['name']);
  }
}

If you want to display a nice and themed table, you don't need to implement your own theme hooks using templates, the table theme hook provided by core should be fine. It is a complete and flexible solution for most table output needs.

function MODULE_table() {
  $header = array(t('ID'), t('Name'));
  $rows = array(
    array(1, 'foo'),
    array(2, 'bar'),
    array(3, 'foobar'),
  );
  return theme('table', $header, $rows),
}


User registration with content profile + data manipulation on submit I'm actually using a type with content profile in my user register form, and I'm trying to manipulate both the user and node data after submitted and inserted in database. I'm supposed to use hook_user with $op insert/after_update/update, but I dont get any data from my content profile node, just the user data, and I also tried hook_nodeapi also with $op insert/update, but got no success too.

I have a custom module, and also tried to change the weight in system, to be executed before the content-profile module.
This is driving me nuts!

Do you have any idea on how I can manipulate that in the user register submit?

I use hook_nodeapi() with the operation ID ($op) equal to "insert" (conditionally for the content profile content type) and then get at the user data with $account = user_load(array('uid' => $node->nid)).
Then, I do as I please with both the $node and $account data.


How to get the autocomplete feature for a taxonomy term profile field visible on the registration form? I have Profile2 and Profile2 Registration Path modules enabled, I set up two different profiles, and for one of them I created a field which is a taxonomy term with the Autocomplete term widget (tagging).

When adding a user within the administration interface, I have the autocomplete widget working, but for anonymous users trying to create a profile the widget is not even attached to the field... I know it is not attached because a field with the widget has a "autocomplete" class and an icon for ajax status in background, but the field on the registration form has no class..

How to add this widget ? Is it a permission issue ? or adding the class to the field through hook_form_FORM_ID_alter() could be enough ? (I don't have the field in the $form array though...

Turns out it is a permission issue : adding the permission for anonymous users to View published content solves my problem as I do not have any reason to not let them see the website content

I guess for websites where content is for registered users only, this permission would not be granted and the widget would not be used on the taxonomy term field.. Maybe the Content Access module could help those use-cases


Return webform in a node I have a custom filter added for a content type 'sample'. On selecting the custom filter for the node body, it checks for webform tokens like [webform:1234], by exploding it checks whether it is a webform or not. If it is a webform, it loads that node and render the same to the node body. Here is my code please have a check.

function landing_page_filter($text, $filter, $format, $langcode, $cache, $cache_id) {
  preg_match_all('/\\[([a-zA-z0-9_]+:[a-zA-z0-9_]+)+\\]/m', $text, $match);
  $matches = $match[0];
  foreach ($matches as $token) { dpm($token);
    $token_name = str_replace(array( '[', ']' ), '', $token);
    $type = explode(':', $token_name);
    if ($type[0] == 'webform') {
      $nid = $type[1];
      $node = node_load($nid);
     $form = drupal_render($node);
    }
  }
  return $form;
}

Rather than loading a page based on nid and then returning the loaded output as an HTML , use drupal_goto function like below :

drupal_goto('node'/.$nid);


How can I translate months of date field? How to translate date field in Drupal 8?

I am not able to figure out how to translate months of date field into french language .

I have created a view of content news listing in which news content are listed, i have added date field from backend with custom date format (22 may, 2018) in views,enabled translation for date field also created custom date format for both languages, but month are showing in default language english.

By default its showing in english language (jan,feb,march....).

So I just want to translate the months of date fields into french language like April=avril , I am using default core translation module that is provided by Drupal 8.

You're not supposed to do this yourself.

What you need to do, is to enable the core Language and Interface translations, select French as the site's language, and update the site's tranlations (this will take some time if its the first time you do this).  After doing all that, all long date fields should display the month names in French.

This is how it looks at my siste:


Views, if image field exists show it, else show this I was wondering if this this possible using Views with Views conditional.

I need to check whether an image field has content, and if not just show some html + a token from a computed field.

Which condition should I use in Views Conditions? And is it possible. Thanks guys

You can use "Rewrite the output of this field", can put an token inside the output and if I'm not wrong there's an check-mark "if the field has values".


how to duplicate a form action programatically when a form action takes place, it posts the fields and also redirects to that page, right?  I need to make a custom form do the same, I have successfully made it post the fields in my drupal 8 custom module , using an http request with guzzle, but how do i make it redirect simultaneously as well?

In your submit handler:

$form_state->setRedirect($route_name, $parameters, $options);

Or if you have a URL object:

$form_state->setRedirectUrl($url);

Reference:

FormState::setRedirect
FormState::setRedirectUrl


Having problem with namespace I am writing a custom module, I am trying to use the validateExtensions() method defined from the Drupal core File module inside the FileItem.php file, in my own controller, using the following code.

use Drupal\file\Plugin\Field\FieldType\FileItem;

//Some other Use statement

class someclass extends FormBase {
  $instance = new FileItem();
  //Some Code
  '#element_validate' => array(array(get_class($instance), 'validateExtensions')),

It gives the following error:

  Recoverable fatal error: Argument 1 passed to Drupal\Core\Field\FieldItemBase::__construct() must be an instance of Drupal\Core\TypedData\DataDefinitionInterface, none given

The answer is in the error message:

FieldItemBase has a constructor, and it waits a parameter (actually multiple), but it doesn't get any:

$instance = new FileItem();

Even though the constructor function can't be find in FileItem, in this case you have to investigate which parent has it. You will find out that "FieldItemBase" has it.
I don't know why you want to use this like this, but things like Controllers, Plugins, Services were mean to be to get instantiated by Drupal.


fields.title.content in views-view-fields--n--block.html.twig won't display This is what I wrote into views-view-fields--n--block.html.twig.
The second and third fields are displayed properly (here I used the machine name). But how do I get the title which is automatically there with every content type?

 {{ fields.title.content}}

{{ fields.field_news_bild.content }}

{{ fields.body.content}}

please help!

Just found out that my title fields' name is title_1.

this is what brought the solution:

    {% for key, field in fields %}

key: {{ key }}

    {% endfor %}

This shows all fields from the view in the template file.


Webform - Submit values from Drupal 7 from to external url I am a self-proclaimed newbie to creating forms in Drupal.  I have a form hosted on a Drupal 7 website (using the webform module) and need to submit the form values to an external url. I've been researching this for awhile now and wrote a custom module that uses the webform module to submit externally using hook_form_alter and custom submit handler/function (code pasted below).

I've been using the following pages as guides, but I haven't been able to get the form to work:
https://drupal.org/node/1357136
Using drupal_http_post() to submit to external site: What am I doing wrong?

Can someone let me know if I'm on the right track?  Any guidance would be helpful!

<?php
function webform_extra_form_alter(&$form, &$form_state, $form_id)
{
   //only want form with nid 1171 to submit externally
   //Note that "webform_client_form_1171" means modify the Webform form for the node with NID "1171". Adjust to match whichever webform node's form you're modifying
   if($form_id == 'webform_client_form_1171')
       {
            $form['#action'] = url('https://[url path to external site]');
            $form['#attributes'] = array('enctype' => "application/x-www-form-urlencoded");
            $form['#submit'][] = 'webform_extra_submit';
       }
}

// Adds a submit handler/function for the app signup form (Webform ID #1171)

function webform_extra_submit($form, &$form_state)
{
     // Changes can be made to the Webform node settings by modifying this variable
    //$form['#node']->webform;

    // Insert values into other database table using same input IDs as external db
    $option['query'] = array(
        $firstName => $form_state['values']['firstName'],
        $lastName => $form_state['values']['lastName'],
        $email => $form_state['values']['email'],
        $name => $form_state['values']['name'],
        $phone => $form_state['values']['phone'],
    );
    $url = url('https://[url path to external site]', $option);
    $form_state['redirect'] = $url;
   //$form['#action'] = url('https:[url path to external site]');
   //$url = 'https://[url path to external site]';
   //$headers = array('Content-Type' => 'application/x-www-form-urlencoded',);
   //$response = drupal_http_request($url, $headers, 'POST', http_build_query($form_state['values'], '', '&'));
}
?>

In Drupal forms, form_alter hooks can be used to change almost anything in the form. Additional submit handlers can be handled, validation can be done, elements can be added, etc.

But for all of these to work, Drupal need to be the responsible party in both form build phase and the form submit phase.

When you set $form['#action'] = url('https://[url path to external site]');, you are actually removing Drupal from that latter responsibility.

Check the altered form - you will see that the form tag's action is set to the external site.
When the form is submitted, browser sends all its data to that external site, and Drupal no longer can validate or perform submit functions in the form. I think this is the misconception happens.

If you don't want Drupal to validate the form, record the webform submission or do anything after the form submission and let the remote site do everything for that submission, your code will work just fine. You can remove $form['#submit'][] = 'webform_extra_submit'; part and the webform_extra_submit function itself.

However, if you do want to record the submission and submit the data to that remote site as well, you can do it like this:

function webform_extra_form_alter(&$form, &$form_state, $form_id)
{
   //only want form with nid 1171 to submit externally
   //Note that "webform_client_form_1171" means modify the Webform form for the node with NID "1171". Adjust to match whichever webform node's form you're modifying
   if($form_id == 'webform_client_form_1171')
       {
            $form['#submit'][] = 'webform_extra_submit';
       }
}

// Adds a submit handler/function for the app signup form (Webform ID #1171)

function webform_extra_submit($form, &$form_state) {

    $options = array();
    // Array keys are matching the key that the remote site accepts. URL encoding will be taken care later.
    $options['data'] = array(
        'firstName' => $form_state['values']['firstName'],
        'lastName' => $form_state['values']['lastName'],
        'email' => $form_state['values']['email'],
        'name' => $form_state['values']['name'],
        'phone' => $form_state['values']['phone'],
    );
    $options['data'] = http_build_query($options['data']);
    $options['method'] => 'POST';
    $url = 'https://[url path to external site]';

    // Put your additional headers here. Cookie can be set as well.
    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');

    $options['headers'] => $headers;

    // Submits data to the remote server from the drupal server. User will remain in the Drupal form submission chain.
    $response = drupal_http_request($url, $options);

}


Taxonomy term listing of nodes with the term in a paragraph I found similar questions but not an actual answer...
This is my setup In Drupal 8:

  Node

    Paragraph

      Taxonomy term reference

I would like to use the default taxonomy term view (taxonomy/term/%) to display a list of node teasers in which the paragraph contains the term. I'm probably passing the wrong contextual filter but I couldn't figure how to fix it.

As per you comments you need some thing like the following to change the Title to a taxonomy term.

/**
 * Implements hook_views_pre_render().
 */
function MODULE_views_pre_render(Drupal\views\ViewExecutable $view) {
  // Get the machine name of your view and replace below.
  if ($view->id() === 'myview_machine_name') {
    $tid = $view->args[0];
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
    // overide the title with the term name.
    if (is_object($term)) {
      $view->build_info['title'] = $term->getName();
    }
  }
}


URL aliases and bidirectionality I have responsibility for a number of Drupal 6 and Drupal 7 sites and I'm curious about a difference I've noted among them.

URL aliasing is enabled on all of the sites, so that a user who navigates to 'some/readable/path' is directed to 'node/123' but continues to see the 'some/readable/path' URL alias in the browser's address bar.

On most of the sites, if the user requests 'node/123', that URL is displayed in the browser's address bar. On a few of the sites, however, the user who enters 'node/123' sees 'some/readable/path' in the address bar.

I was not aware that this sort of "bidirectional aliasing" was possible; it doesn't seem to be default behavior. Is there a module which provides this bidirectional capability? If it is default behavior, how is it enabled?

By default in Drupal if you have node/7 with an alias of some/readable/path then a user can go to either of those URLs and it will load the page.

For SEO reasons it is considered bad to have the same page viewable at multiple URLs.

For this reason a very large number of drupal sites use the redirect module.

The redirect module forces users to always access a node from the same URL so if a user navigates to node/7 it will redirect them to the aliased URL instead.

It is likely the difference between the sites you are looking at is the redirect module.


Rendering a form using \Drupal::service('entity.form_builder')->getForm($entity, 'default') is returning a plain form, before hook_form_alter I'm rendering a form programmatically. The following code works:

$addressForm = \Drupal::entityTypeManager()
  ->getStorage('profile')
  ->create(array('type' => 'customer', 'uid' => $uid));
$finalform =  $this->entityFormBuilder()->getForm($addressForm);

However, it is rendering the form before hook_form_alter() has been called.

For example, in hook_form_alter() we added a #after_build callback method and custom validations, but the changes made in these functions are not reflected in $finalform.

How do I ensure hook_form_alter() changes are made to the rendered output?

.module file

function custom_profile_form_profile_customer_add_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  $form['formtitle'] =  array(
    '#type' => 'markup',
    '#weight' => -100,
    '#markup' => '
Old Address Form
',
  );
  /* ....
.... */
}

function custom_profile_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_FORM_ID_alter') {
    $group = $implementations['custom_profile'];
    unset($implementations['custom_profile']);
    $implementations['custom_profile'] = $group;
  }
}

.routing.yml

I have created a new route for the Address page in /modules/custom/custom_profile/custom_profile.routing.yml,

commerce_add_address.get:
  path: '/checkout/{uid}/customer/add'
  defaults:
    _controller: '\Drupal\custom_profile\Controller\newAddressBook::commerce_add_address'
  options:
    parameters:
      uid:
        type: integer
  methods:  [GET,POST]
  requirements:
    _permission: 'access content'

Controller

in src/Controller/newAddressBook.php file

public function commerce_add_address($uid) {
  //To get profile Add Address form
  $addressForm = \Drupal::entityTypeManager()
      ->getStorage('profile')
      ->create(array(
        'type' => 'customer',
        'uid'  => $uid
      ));

  $finalform = $this->entityFormBuilder()->getForm($addressForm);
  $build['#theme'] = 'usernewaddress';
  $build['#data'] = array();
  $build['#data']['form'] = $finalform;

  return $build;

Ensure that your implementation of hook_form_alter() runs at the right time via hook_module_implements_alter().

  This hook is invoked during
  \Drupal::moduleHandler()->getImplementations(). A module may implement
  this hook in order to reorder the implementing modules, which are
  otherwise ordered by the module's system weight.

But pay attention when using possible variations of hook_form_alter().

  Note that hooks invoked using \Drupal::moduleHandler->alter() can have
  multiple variations(such as hook_form_alter() and
  hook_form_FORM_ID_alter()). \Drupal::moduleHandler->alter() will call
  all such variants defined by a single module in turn. For the purposes
  of hook_module_implements_alter(), these variants are treated as a
  single hook. Thus, to ensure that your implementation of
  hook_form_FORM_ID_alter() is called at the right time, you will have
  to change the order of hook_form_alter() implementation in
  hook_module_implements_alter().

See? Right now you are checking for if ($hook == 'form_FORM_ID_alter') which won't work. Fix it by replacing it with if ($hook == 'form_alter').

If that doesn't work try to change your module's weight via module_set_weight().