Remove duplicate values in a column after join in drupal 7 I am using this db_select query.

$query = db_select('taxonomy_index', 't1');
    $query->distinct();
    $query->join('node', 't2', 't1.nid = t2.nid');
    $query->join('taxonomy_term_data', 't3', 't3.tid = t1.tid');
    $query->fields('t1', array('tid'));
    $query->fields('t3', array('name'));
    $query->fields('t1', array('nid'));
    $query->groupBy('t1.nid');
    $query->condition('t2.type', 'article', '=');
    $query->condition('t3.vid', '2', '=');
    $query->orderBy('t2.created', 'DESC');
    $query->range(0, 20);
    $result = $query->execute()->fetchAll();
    print_r($result);

After running this query
my output is

tid  name   nid
1    apple   200
5    orange  165
9    grapes  130
5    orange  106

My expecting output is

 tid  name   nid
    1    apple   200
    5    orange  165
    9    grapes  130

No need to repeat duplicate rows like  5 orange 106 again. How this can be possible?

Can you try with the result you are getting and avoid the duplicates using below codes.

 $used_tids = array();
 foreach ($result as $row) {
        if (!in_array($row->tid, $used_tids)) {
          $new_result[] = $row;
          $used_tids[] = $row->tid;
        }
      }
      // new filtered results after avoiding duplicates
      $results = $new_result;


how to stream video on-site generated from link preview in a text area? I am using opengraph filter module to generate preview from url. It is working perfectly. Now if a user has shared a video or image through url on the site and the preview is generated, when someone clicks on that preview, it takes the user to the link page (external website). What I want is, it should open on my site i.e embed on my site so that user can see the picture or video, generated from link preview, on my website. Currently, there is a video filter module which converts links to embeded videos, but it requires users to use this format [video:url] when sharing videos, but this format [video:url] for sharing a video link is not desirable, so leave it. I just mentioned it for reference/information.

Opengraph Filter module provides this: template_preprocess_opengraph_filter()

You can implements it in your custom module or theme for reading the video url. Then you can use the video url to output the player.

function mytheme_preprocess_opengraph_filter(&$variables) {
  $key = 'video';
  if (isset($variables['metatags']['og'][$key])) {
    $video_url = $variables['metatags']['og'][$key];

    // more code to operate $video_url.
    // dpm($video_url);
  }
}

You can start with it. It would be a long story if you want to load the video after clicking the thumbnails. I would suggest you to split the question into multiple specific questions for different step. It is more easy for other to provide answer and also for those who is looking for answer. Thanks.


Drupal Remove jQuery, and jQuery UI and add migrate plugin with Updated jQuery and UI I am trying to use drupal_add_html_head to add script elements to the head tag, however, this is important that these script tags are not self-closing because that is not the correct way to add them.

How do I do this:

$html5jquerymigrate = array(
    '#tag' => 'script',
    '#attributes' => array(
        'src' => libraries_get_path('jquery.migrate', true) . '/jquery-migrate-1.2.1.min.js',
    ),
    '#prefix' => '',
    '#suffix' => '',
);

drupal_add_html_head($html5jquerymigrate, 'html5jquerymigrate');

But instead of getting it printed out like this:  <script src="/sites/all/libraries/jquery.migrate/jquery-migrate-1.2.1.min.js" />

How do I have it print out in the head like the following instead?

<script src="/sites/all/libraries/jquery.migrate/jquery-migrate-1.2.1.min.js"></script>

Ok, there was no 1 step solution to this problem.  So here's what I did in case anyone else wants to know.

This is a 3 STEP solution to adding jQuery 1.9 and jQuery UI 1.10 functionality to Drupal 7.  Not sure about other versions of Drupal.

1 - Needed to remove Drupals old jQuery library of version 1.4 and replace with version 1.9, so in my theme, I added the following function:

In template.php

function MYTHEME_js_alter(&$js) {

    $js['misc/jquery.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';

    // Adding this ensures that the UI functionality gets added at all times!  Even when logged out of the site, since we have functionality on the site that requires this when logged out!
    if (!isset($js['misc/ui/jquery.ui.core.min.js']))
    {
        drupal_add_js('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js');
    }
    else
        $js['misc/ui/jquery.ui.core.min.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js';
}

2 - Now that this is done, before we can really take advantage of Drupal with any other jquery library that is greater than 1.8 (which sucks), we need to add in the migrate plugin found here:  http://blog.jquery.com/2013/05/08/jquery-migrate-1-2-1-released/

I have the Libraries Module installed, so I just put the JS in my Libraries folder called: jquery.migrate

3 - Than I added this to template.php file for my theme:

function MYTHEME_page_alter($page) {
    drupal_add_js(libraries_get_path('jquery.migrate') . '/jquery-migrate-1.2.1.min.js');
}

Now I can use all of the greatest and newest technologies in jQuery 1.9 and beyond while still being able to have Drupal 7 not crash on me!  AMEN!  HALLELUJAH!!!!


How to keep cache_form small I have noticed in mysql that cache_form.MYD table is 14GB. Why did it grow so big? Is it safe to empty it? and how can I avoid this happening in the future?

Thanks

This is a known issue in Drupal 6 and 7 for that matter. It is not cleared when running cron. You can safely delete all rows that has expired.

DELETE FROM {cache_form} WHERE expire < now();

should do the trick.


Need to add a JS file into  using a custom module with custom twig template I have created a custom module and created a config page which we need to input the url on that page.

Created a twig template within my custom module:

<script src={{ js_file_url }}>test</script>

In my .module file

<?php

/**
 * @file
 * Add the url to the header section.
 */

/**
 * Implments hook_page_attachments_alter().
 */
function custom_module_page_attachments_alter(array &$attachments) {

  $js_file_url = \Drupal::config(' custom_module.settings')->get('url');

  $renderable = [
    '#theme' => 'my_template',
    '#test_var' => 'test variable',
  ];

$attachments['#attached']['html_head'][] = [
    [
      '#theme'  => 'my_template',
      '#js_file_url'   => $js_file_url,
    ],
  ];

}

function  custom_module_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'variables' => ['js_file_url' => NULL],
    ],
  ];
}

My output:

<><script src=http://google.com>test</script></>

Expected Output is

<script src=http://google.com>test</script>

How to get rid of empty tags =>  <>,

By default $attachments['#attached']['html_head'][] is adding the '#tag' even if i dont declare it.

Can someone help me, please.

You can attach custom tags to any render array from where it bubbles up into the HTML head. In the following sample I'm adding structured data when a certain block is viewed. $value then contains what's being printed between the opening and closing script tag.

/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function MYMODULE_block_view_system_breadcrumb_block_alter(array &$build, BlockPluginInterface $block) {

  // Get JSON-LD.
  if ($json_ld = \Drupal::service('easy_breadcrumb.structured_data_json_ld')
    ->value()) {

    // Prepare script tag.
    $structured_data = [
      '#tag' => 'script',
      '#attributes' => ['type' => 'application/ld+json'],
      '#value' => $json_ld,
    ];

    // Add script tag.
    $build['#attached']['html_head'][] = [
      $structured_data,
      'easy_breadcrumb_structured_data_json_ld',
    ];
  }
}

I hope you get the idea how this can easily be adjusted to get your custom snippet into the head. You can keep your logic in hook_page_attachments_alter but then let it look more like in the following snippet. Maybe you don't even need any #value at all.

/**
 * Implements hook_page_attachments_alter().
 */
function MYMODULE_page_attachments_alter(array &$attachments) {

  if ($js_file_url = \Drupal::config('MYMODULE.settings')->get('url')) {

    // Prepare script tag.
    $my_script = [
      '#tag' => 'script',
      '#attributes' => ['src' => $js_file_url],
      '#value' => 'test',
    ];

    // Add script tag.
    $attachments['#attached']['html_head'][] = [
      $my_script,
      'MYMODULE_my_script',
    ];
  }
}


Pass a multi value argument to a panel view Is there a way to pass a multi value argument from panels to a panel view?

I have a node with an entity relation field on it and load this node as context in page manager.

I have also a view which accepts a multi value argument (contextual filter). Not multiple arguments I mean an argument where you have multiple nids normally separated by comma if you would enter them in the url.

I want to pass the nids from the entity relation field on the node loaded as context to the view I load in a panel on the same page.

Maybe it is more understandable by describing it step by step.

I created a page manager page with a path /admin/something/!nid
The node identified by !nid is loaded as a context so I have all the
field values on the node.
The node has a field that stores a small amount of other nodes as references.
I want to pass the nids of the referenced nodes to a panel view as argument number one.
I have done this with one nid but have no idea how to do it with multiple ones.

Any ideas? Thanks!

The entity context provided by CTools uses tokens to provide keywords for the given context.

So if you implement your own token which uses a node object as data source it will end up among your node context keywords, and you can pass it to the view as an argument.

Check out this answer to get an idea how to implement tokens.

Your token replacement method should extract the referenced node IDs from the loaded node, and concatenate '+' or ',' between them (it depends on how your argument is configured in the view).


How to get Drupal 7 installed in a sub-folder / sub-directory properly? Currently i'm trying to installing a drupal 7 installation in a subfolder of another drupal public_html folder, but it doesnt seem to work. I am getting a redirect loop error in chrome. I already modified the .htaccess in the parent drupal installation to ignore the sub-folder and i also set the $base_url in the sub-directory drupal installation.

When I do this, provided I have a clean install, I do not modify anything. Take the domain http://diw.ifi.uio.no/, where Drupal is installed in both /www/, and /www/gruppe01/, etc. (I just create the number of subdomains I need for various experiments). My DocumentRoot is set to be /www/. I just direct my browser to http://diw.ifi.uio.no/ for the main site, and  http://diw.ifi.uio.no/gruppe01/ for the first subfolder site, etc. and it works - just like that.

Have you tried starting with a clean install and just install Drupal in the subfolder using the standard install procedure without changing .htaccess? (While not always necessary, I recommend that you have $base_url set correctly in the site's  settings.php.)

In my experience, Drupal works fine out of the box when installed in a subdirectory of a vhost. The fact that there is another Drupal in the DocumentRoot does not make this any different, as long as each Drupal site has its own .htaccess, it will not try to read the .htaccess in any superior directory.

Examples:

http://diw.ifi.uio.no/
http://diw.ifi.uio.no/gruppe01/


Adding priced options to products in Drupal Commerce For something that's pretty basic this seems overly complicated!  I'm working on updating a computer store from Ubercart to Drupal Commerce. Computers can be custom built so there are multiple options to choose. If I have to create a SKU for each variation I will go absolutely crazy!

So I've tried:

bundling modules - but they doesn't allow you to choose options
commerce pricing attributes - but it doesn't seem to work anymore "The "hunziker" approach to Drupal Commerce is not supported nor recommended by the creators of Drupal Commerce. Thus, any problems you might have with the modules is "by design" unfortunately." - Commerce Attribute price is not updating in cart
Commerce Customizable Products - seems the most promising but after following the "pizza store" video multiple times even with a clean install - everything works A-OK till the rules. When I get to the part where I am adding in the rules, I can add in the "Entity has field" part properly, but when I add the loop, I don't have the option for just "commerce-line-item:field-foo". It ends the commerce-line-item:field-foo with a colon and wants you to pick more. no matter what combination I try I end up with a rule error about lists: "Error: The data type of the configured argument does not match the parameter's list requirement".

I'm absolutely going nuts with this!! It shouldn't be this hard... should it?

The process I'm following for Customizable products is as follows (adding an Antivirus choice to a custom computer content type):

Install Customizable Products
Add a custom line item  Store > Configuration > Create New Line Item Type called “Custom Computers”
Create a Taxonomy, called "Computer Antivirus"
Add price field to taxonomy (with currency) called "Price" – Field Type “Price” > Currency CDN
Add a few taxonomy terms with prices
Add a Taxonomy term reference field "Computer Antivirus" to custom line item type, Store > Configuration > Line Item Types > Custom Computers

• Manage Fields

• Add new field “Antivirus” – Term Reference – Checkboxes

• Choose “Computer Antivirus” Taxonomy Vocabulary

• Include this field on Add to Cart Forms…

Set up products to use new line type. Configure the display of the add to cart form on the custom product type to use the custom line item type

•   Structure > Content Types

•   Choose Manage Display on the Content type you need to change

•   Edit the Product – Add to Cart form > Choose the Line item type “Custom Computer”

•   SAVE!!!

The custom options will now appear below the product
Change the price

•   Create a Pricing rule

•   Store > Configuration > Product Pricing Rules

•   Add new Rule named “Antivirus Rule”

•   Add a condition: Entity has field - Data Selector: commerce-line-item - Value: field_antivirus

•   HERES WHERE THE PROBLEM IS  - Add a Loop:- Data Selector: commerce-line-item:field-antivirus - Current List Item: change name

•   Add an action to the loop: - Commerce line item: Add an amount to the unit price - Amount Value: switch to data selection: pizza-topping: field-price:amount
 - Price Component Type: Fee - Value: Round the half up

I've been working with this about 4 weeks now with no solution. Can anyone shed some light on whats wrong?

Oh and no - I didn't set the term reference field to unlimited values because I only want them to pick one value from the list

I believe that is the problem... either you make it unlimited; even though, you will use it once

OR leave it at 1, but don't use a loop, just add action (for Amount Value data selection use commerce-line-item:field-price:amount)


Link field sanitizes query string from foo.cgi?123456 to foo.cgi?0= On my Drupal 8 site I have a custom content type that contains, among other fields, a link field. When I create a node and add the following external URL as one of the values of the link field:

http://www.isfdb.org/cgi-bin/title.cgi?1580

the rendered page contains this mangled query string:

http://www.isfdb.org/cgi-bin/title.cgi?0=

Is this the result of some misconfiguration on my part? How can I get the rendered page to use the correct URL?

I should probably mention that the D8 site is the result of a migration from a D7 site. On the old D7 site, the same URL was rendered correctly. The new Drupal 8 site uses Drupal version 8.6.1.

I have tracked down the problem deep into Drupal Core itself. The problem actually consists of two bugs, not just one!

EDIT: For the first bug I have submitted a new Drupal Core issue (issue 3007243). For the second bug I have contributed my analysis to the discussions of two existing Drupal Core issues (issue 2987114 and issue 1464244).

Let's start at the beginning. The Link module works with the Drupal Core class Url. At the appropriate time, the Link module gets the URI from the Url object by invoking its toString() method. For external links, this method makes use of the Drupal Core class UnroutedUrlAssembler, by invoking its assemble() method, which in turn invokes another method buildExternalUrl.

Bug #1 is in buildExternalUrl: The method contains this line:

$options['query'] = NestedArray::mergeDeep($parsed['query'], $options['query']);

This is wrong because it doesn't preserve integer keys! Remember that the query parameter in my URL is numeric (1580, see the OP)? The above line causes the 1580 to be discarded, instead the result is the 0 (zero) that we have seen in the mangled query string. The correct line would be this. The all-important thing is the TRUE parameter which tells NestedArray::mergeDeepArray() to preserve integer keys.

$options['query'] = NestedArray::mergeDeepArray(array($parsed['query'], $options['query']), TRUE);

Unfortunately this is not the end of the road. Where does the "=" character in the mangled query string come from? The assemble() method of the UnroutedUrlAssembler class first breaks down the URI into its individual parts like this:

$parsed = UrlHelper::parse($uri);

Then it reassembles the URI, piece by piece. The query string gets reassembled with this line:

$uri .= '?' . UrlHelper::buildQuery($options['query']);

The UrlHelper::buildQuery function generates "key=value" pairs from the entries in the supplied array ($options['query']). It omits the "=value" part if - and only if - the value of an array entry is NULL (the check is made with the PHP function isset()). As I have found out, for my example URL the value of the array entry is NOT NULL, it's an empty string - and that's what causes the "=" character to be generated.

But where is the empty string coming from? The function UrlHelper::parse() uses the PHP built-in function parse_str() to break down the query string into its parts, and that PHP function is the culprit! Here's the proof:

php -r '$query="1580"; $arr = array(); parse_str($query, $arr); echo "isset: " . isset($arr[1580]) . "\n"; echo "+" . $arr[1580] . "+\n"; echo "gettype: " . gettype($arr[1580]) . "\n";'
isset: 1
++
gettype: string

So to ultimately fix the problem, either parse_str() would have to change its buggy query string parsing, or the Drupal function UrlHelper::parse() would have to use some other function to parse query strings.


Custom tokens breaking on node save with "node entity cannot have a URI" error I'm getting a crash on node save when my node contains a custom token.  I'm using the Token Filter module to display tokens in node content.

To make the tokens I followed this tutorial, which is similar to the Token documentation.

Now, with Drupal 8.8, when I save a new node that contains one of my custom tokens, I get a WSOD with this error:

  Drupal\Core\Entity\EntityStorageException: The "node" entity cannot
  have a URI as it does not have an ID in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 846 of
  core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

But the real error appears to be from token:

Drupal\Core\Utility\Token->generate('ebook', Array, Array, Array, Object) (Line: 196)
Drupal\Core\Utility\Token->replace('
Test [ebook:custom-type] 2

', Array, Array, Object) (Line: 130)
Drupal\token_filter\Plugin\Filter\TokenFilter->process('
Test [ebook:custom-type] 2

', 'ja') (Line: 118)
Drupal\filter\Element\ProcessedText::preRenderText(Array)
call_user_func_array(Array, Array) (Line: 100)
Drupal\Core\Render\Renderer->doTrustedCallback(Array, Array, 'Render #pre_render callbacks must be methods of a class that implements \Drupal\Core\Security\TrustedCallbackInterface or be an anonymous function. The callback was %s. Support for this callback implementation is deprecated in 8.8.0 and will be removed in Drupal 9.0.0. See https://www.drupal.org/node/2966725', 'silenced_deprecation', 'Drupal\Core\Render\Element\RenderCallbackInterface') (Line: 781)
Drupal\Core\Render\Renderer->doCallback('#pre_render', Array, Array) (Line: 372)

Weirdly, if I remove the token from the body field when I save the node, the node saves properly-- and then I can edit the node and add the token back in without any error. The error only occurs when the node is saved and it has a token in it.

Drupal tokens like [site:name] work fine; it's just my custom token that causes an error.

Here's the relevant code:

/**
 * Implements hook_token_info().
 */
function MYMODULE_token_info() {

  $ebook_type = [
    'name' => t('Custom Tokens'),
    'description' => t('Tokens to make upgrading to D9 harder.'),
  ];

  $ebook['custom-type'] = [
    'name' => t("Custom type"),
    'description' => t('Apples or oranges'),
  ];

  return [
    'types' => ['ebook' => $ebook_type],
    'tokens' => ['ebook' => $ebook],
  ];

}

/**
 * Implements hook_tokens().
 */
function MYMODULE_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {

  $replacements = [];

  if ($type == 'ebook' && !empty($data['node'])) {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'custom-type':
          $replacements[$original] = MYMODULE_token_set_custom_type($data['node']);
          break;
      }
    }
  return $replacements;
}

function MYMODULE_token_set_custom_type($node) {
  $alias = $node->toURL()->toString();
  preg_match('(/.*/)', $alias, $matches);
  if ($matches[0] == '/apples/') {
    return "Apples";
  }
  else {
    return "Oranges";
  }
}

How do I resolve this?

If the token is being generated before the node has been saved, this will cause a WSOD, since no URI can be created for the node. Entity URIs require an entity ID to built the path to the entity.

As such, I'd change your code to:

function MYMODULE_token_set_custom_type($node) {
  if ($alias = $node->toURL()->toString()) {
    preg_match('(/.*/)', $alias, $matches);
    if ($matches[0] == '/apples/') {
      return "Apples";
    }
    else {
      return "Oranges";
    }
  }
}


Where is the best place for cache bins (Drupal 7)? At Drupal 7, I have read about various solutions for storing the cache bins and avoiding having them at the standard drupal database.
The methods are:
- Memcache
- Mongodb
- APC
- Filecache module?
any other method that you know?

What are the advantages/disadvantages of each method and the corresponding performance gains?

First, cache tables is a term specific for a relational database, the generic term is cache bin or simply cache.

This is quite a big question but I can try to give you some hints...

Memcache

The memcached backend for Drupal 7 was rather buggy until very recently, but a lot of issues were fixed recently (some by me, more by catch) and it should work fine now. Memcache allows to have multiple cache servers, it is very fast.

MongoDB

I can't say much about this, haven't used it as a cache backend. Not as fast as Memcached, but might get interesting in the feature, as it will provide native support for the upcoming cache tag API (which will only be part of Drupal 8).

APC

Probably the fastest solution because the cache is read directly from memory within the same process. However, I've had stability issues in the past when using this as the cache, it doesn't allow to store that much data (as it blows up the apache processes memory-wise) and it gets problematic once you have multiple web servers (because you can't clear the cache on the other servers).

Filecache

Slower than Memcache/APC but allows to store large amounts of data. I'd look into it if your caches start to get too big for memcache.

My recommendation: Memcache

Note that some cache tables (cache_update) can't be moved out of the database, because they're not a real cache and use separate API functions and some others should be kept there too (cache_form: again not a real cache, must not be cleared as it contains information about built forms including their data)


Sending system e-mails do not work in spite system says it sends e-mail So, my Drupal 7 does not dispatch those messages (notify user on registration and such) in spite the system says it sended e-mail. Other scripts (like send the web page by email) work well, though!

I am on dedicated unmanaged (i manage it ;) ) Debian server with LAMP, and for e-mail I installed Postfix.

If someone got clues i would be grateful!

If the system log reports it is sent, mostly likely it was sent. Perhaps those mail went to SPAM box? If that is the case, check if you have Reverse DNS set up for your domain.

Besides, you can utilize 3rd party email service (such as Gmail) as your Drupal mail system.
Check out SMTP module.


What is the difference in State API and Config API? It is a bit confusing to understand the difference in State API and Config API in Drupal 8. I went through the documentation of both on drupal.org but it is not clear to me yet.

Do we define both State config and Config variables in config/install directory?
And How are they both distinguished?

Configuration is a place to store information that you want to synchronize from development to production. This information is often created during site building and is not typically generated by regular users during normal site operation.

You should use the State API, not Configuration API, for storing local variables that shouldn't travel between instances.

The State API provides a place for developers to store information about the system's state.

State information differs from configuration in the following ways:

It is specific to an individual environment.
You will never deploy to deploy it between environments.
You can reset a system, losing all state. Its configuration remains.

Hope that helps.

Thank you :)


Does changing the order of questions reflected in past quiz results too? I have two quick questions about implementing the quiz module:]

I have the questions in a particular order and about 100 people have taken the quiz.  We have implemented the quiz results download module.  If I CHANGE THE ORDER of the questions (make question #3 the new question #1) will the results (old one in particular) automatically UPDATE or will we have ‘MIXED’ data – some with the old question numbers and some with the new ones?
As you know, there is an option to present responses (answer choices) in random order.  We had NOT checked that box.  If we now check that box, will the old data get automatically updated?

Here is a copy/past from the answer to issue # 2862591

It depends on your revisioning configuration.
Out of the box, Quiz will version changes so that your old results are not affected.
If you were to change the Quiz/Questions in any way, you may see issues with reporting since the quiz and question version IDs have changed, so new users will be taking a different version of the Quiz. But, this means that all data is preserved.
If you turned revisioning off, reordering the questions or selecting "random order" should not affect old results or reporting as the question IDs remain the same. But you have to be more careful since changing something like removing an answer or question will definitely affect old results.
I'd suggest trying on a test copy of your DB just to make sure.

I'm posting this as a wiki answer, hoping for it to marked as accepted, so that this question is no longer considered as unanswered also.


How do I render a submit button so that it's disabled initially and enabled by JavaScript? We have a form that includes a React JS frontend component. The component collects some required information, which the React component then supplies to the backend by populating a hidden form field.

To ensure that a user cannot bypass entering the required data through the component, we need to satisfy the following requirements:

Before the React component loads, the "Submit" button needs to be disabled. This ensures that a user can't submit the form just by disabling JS or just clicking the button before the page finishes loading.
After the React component loads, any time that the required values get cleared, the "Submit" button needs to be disabled.
Once the required values are supplied, the "Submit" button should be enabled.
It must not be possible to submit the form if the hidden value is empty.

I've tried rendering the form like this:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];

    $form['selected_values'] = [
      '#type' => 'hidden',
    ];

    $form['actions'] = [
      '#type'   => 'actions',
      '#weight' => 100,
    ];

    $form['actions']['submit'] = [
      '#type'         => 'submit',
      '#value'        => $this->t('Submit'),
      '#button_type'  => 'primary',
      '#disabled'     => TRUE, // Controlled by JS on the frontend
    ];

    return $form;
  }

And then in JavaScript, I have an onValueChange() event callback that looks like this:

function onValueChange(value) {
  if (value.trim() === '') {
    $(submitButton).prop('disabled', true);
  }
  else {
    $(submitButton)
      .prop('disabled', false)
      .removeClass('is-disabled');
  }
}

I also tried:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];

    $selected_values = form_state->getValue('selected_values');

    $form['selected_values'] = [
      '#type' => 'hidden',
    ];

    $form['actions'] = [
      '#type'   => 'actions',
      '#weight' => 100,
    ];

    $form['actions']['submit'] = [
      '#type'         => 'submit',
      '#value'        => $this->t('Submit'),
      '#button_type'  => 'primary',
      '#disabled'     => !empty($selected_values),
    ];

    return $form;
  }

Both of these approaches demonstrate the same problem -- clicking the "Submit" doesn't submit the form; it just seems to rebuild the form. With the second approach, it looks like the incoming selected values are always empty during the form render; they don't get applied to the form state until after the form is constructed.

How can we ensure that the "Submit" button starts out disabled, while requiring the necessary values?

Using #disabled on the submit button is the wrong solution because it communicates to the Drupal form API that the button is not expecting input. In other words, it causes Drupal to act as if the button were not there at all. Hence, clicking the submit button has no effect. This all makes sense from a security perspective, because normally you wouldn't want crafty users disabling backend logic just by using developer tools to force a disabled or read-only form element into being enabled.

Instead, the solution is two-fold:

Render the button as disabled via HTML attributes, so that the button is only disabled in the browser but is still considered an active button on the backend.
Mark the hidden field as '#required' => TRUE so that it's not possible to bypass the form even if the user is crafty with Dev Tools.

Here's what that looks like in practice:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];

    $form['selected_values'] = [
      // Though this field is hidden, it's required. So, the title is still
      // shown if/when the field is ever NULL during submission.
      '#title'    => $this->t('File selection'),
      '#type'     => 'hidden',
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type'   => 'actions',
      '#weight' => 100,
    ];

    $form['actions']['submit'] = [
      '#type'         => 'submit',
      '#value'        => $this->t('Submit'),
      '#button_type'  => 'primary',
      '#attributes' => [
        // This button is programmatically enabled/disabled via JS on the
        // frontend.
        'disabled' => 'disabled',
    ];

    return $form;
  }

The frontend logic for enabling the button stays the same. The difference here is that the button is only disabled in the rendered HTML rather than being disabled in the backend form. In addition, if a crafty user enables the button by removing the disabled attribute on the HTML DOM element, they'll just end up with a validation error that says:

  File selection field is required.

Separately, as for why the second approach failed to enable/disable the "Submit" button based on the incoming values, this is because Drupal builds the form first before processing the incoming values so that it knows which form elements need to be invoked to process the input. So, at the time that the form builder is invoked, there is nothing yet in form state values. Hypothetically, it might be possible to get the raw input via $form_state->getUserInput() and then control whether or not the button should be enabled based on that; but, this approach may have security implications.


Create description for taxonomy term view I am after a description which is similar for all taxonomy terms based on a schools location.

So I've created a few views based on continents at http://www.explorefreediving.com/freediving-schools-in-africa and then just added a description for that view and will be doing the same for the other continents.

"Improve your snorkeling, spearfishing and freediving with one of the many schools and freediving training courses held by apnea instructors across Africa."

I am now after a similar description for every country taxonomy term which is what I use to categorise the freedive schools.

So if you click on Egypt to the right when you are looking at Africa http://www.explorefreediving.com/school-location/africa/egypt you get sent to a taxonomy term and the same with other locations too

I want to be able to insert a description for the hundreds of taxonomy term school locations (countries) without having to manually do it? The most I know I could do is set up a description in each header and use tokens but is this the right approach? If it is, how do I do that exactly? I usually have problems with tokens and using the right ones.

If it is the right approach, doesn't that mean I will have that description across all taxonomy terms because the same view is used?

There are at least two ways to do this:

1. Views

In your views admin page, add a Global: Text area to header. Then check off Use replacement tokens from the first row. You can see the tokens (patterns) below under Replacement patterns. Your custom text my be like that:

"Improve your snorkeling, spearfishing and freediving with one of the many schools and freediving training courses held by apnea instructors across %1."

2. page--vocabulary--[machine-name].tpl.php

You could create a custom vocabulary tpl.php page and add your custom text. Details come from that answer:

Copy (and past) the page.tpl.php into your theme folder.
Rename it page--vocabulary--[machine name].tpl.php

(page--vocabulary--location.tpl.php etc.)

Open the template.php file in the theme folder and add this function:

Don't forget to change the THEME to your theme name and if you have already had the preprocess_page function in the template.php file and do not add the preprocess_page function again.

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

Open the page--vocabulary--location.tpl.php file and find that line:

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

Then add what you want:

(with your css class, spans etc.)

<div class="term_description"
"Improve your snorkeling, spearfishing and freediving with one of the many schools and freediving training courses held by apnea instructors across <?php print $title; ?>."
</div>

 - Clear all caches.


How can I break into my own Drupal site? I was doing a Media module tutorial. Half way through it I decided to install the tutorial companion files and foolishly replaced my files. In the companions readme it says the admin login is username - admin and password - admin.

But it is not! Now i’m completely locked out. Can someone tell me how I might break in to my tutorial site? I have access to the DB via PHPMyAdmin.

I was thinking a MySQL update command to the password field for the admin. Can someone tell me what I could use to reset the admin password?

I changed the admin email address then requested a new password but it has not fired off an email.
I believe the password encryption method is sha1().

If you're using Linux:

Install drush if you haven't already
Go to /install_directory/sites/mysite
Type sudo drush uli
Copy the link to your browser

Drush is extremely useful for many things.  The above will log you in as user 1, after which you can reset your password in the usual way.


Programmatically add custom meta description via metatag module I'm trying to add a custom meta tag description for a custom module using the metatag module.

I tried this without success:

function mycustommodule_metatag_metatags_view_alter(&$output, $instance) {
  if ($instance == 'mycustom:entity') {
    $output['description']['#attached']['drupal_add_html_head'][0] = array(
      array(
        '#tag' => 'meta',
        '#name' => 'desription',
        '#value' => $my_custom_description,
      ),
      'description',
    );
  }
}

Instead of directly altering the metatag, you might want to look into creating a custom token: As described in this article

This will give you more freedom and flexibility. Then you can just use that custom token in the backend of metatags and configure it for content types that you like.

/admin/config/search/metatags

If you however, still prefer to use the hook in the op, don't forget that those are cached, you will need to clear all caches before it might appear.


Delay ajax from firing immediately (AJAX links api) Problem

I'm trying to add a bunch of CSS3 page transitions to my site. To do this, I'm loading the pages with AJAX using the AJAX Links API module, but I want to delay the AJAX call to allow for the animations.

However the ajax click handler seems to come straight from jquery.min.js, rather than module as I expected so I can't work out how to delay it. Does anyone know how to delay the ajax link click handler? (i.e. wrap it in a setTimeout.)

Details

I can prevent normal link clicks with:

  Drupal.behaviors.dsmooth_state = {
    attach: function (context, settings) {
      $('a.notajax').click(function (e) {
        e.preventDefault();                   // prevent default anchor behavior
        var goTo = this.getAttribute("href"); // store anchor href

        // funky animations go here.

        setTimeout(function(){
             window.location = goTo;
        },800);
      });
    }
  };

However the Drupal AJAX framework, uses a separate click handler for AJAX which is obviously not effected by this.

The AJAX Links API module defines the following click handler, however wrapping it in a setTimeout does nothing. I'm presuming that somehow this click handler sets the other one? I'm not really sure.

var ajaxLoading = false;
  Drupal.behaviors.ajaxLinksApi = {
    attach: function () {
      var trigger = Drupal.settings.ajax_links_api.trigger,
        negativeTrigger = Drupal.settings.ajax_links_api.negative_triggers;

      // match the elements from the positive selector
      var $elements = $(trigger);

      // remove elements if the negative trigger is specified
      if (negativeTrigger) {
        $elements = $elements.not(negativeTrigger);
      }

      // add the click handler
      $elements.click(function(e) {
        e.preventDefault();
        var selector;
        if(!ajaxLoading) {
          ajaxLoading = true;
          var url = $(this).attr("href");
          var id = $(this).attr("rel");
          if(id) {
            selector = $(this).attr("rel");
          } else {
            selector = Drupal.settings.ajax_links_api.selector;
          }
          ajaxBefore(selector);
          ajaxLink(selector, url);
        }
      });
    }
  };

//EDIT removed chrome information. I think I misunderstood what Chrome was putting out. It seems to list all event listeners as coming from jquery.min.js

Ok so this was in fact a JS problem and not related to Drupal, I was in the correct place and writing some bad JS.

If you are trying to delay the AJAX clicks on the AJAX Links API module, you need to add a setTimeout and an extra variable to the JS defined in ajax_links_api.js

  $elements.click(function(e) {
    e.preventDefault();
    //This gets altered by setTimeout function, so save now.
    var store = this;
    var selector;
    setTimeout(function(e){
      if(!ajaxLoading) {
        ajaxLoading = true;
        var url = $(store).attr("href");
        var id = $(store).attr("rel");
        if(id) {
          selector = $(store).attr("rel");
        } else {
          selector = Drupal.settings.ajax_links_api.selector;
        }
        ajaxBefore(selector);
        ajaxLink(selector, url);
      }
    },800);
  });


Redirecting old file URLs (no pattern) running Drupal 7.65.

Our previous website manager moved us from Drupal 6 to Drupal 7 and cleaned up the file structure on our server.

While all the files that are now on our website have clean and organised URLs, and all general URLs on our website are now clean, Google still has indexed our old URLs.

e.g.:

  old: domain.com/program-name

  new: domain.com/programname

and

  old: domain.com/sites/default/files/documents/owl-final-final3.pdf

  new:
  domain.com/sites/default/files/folder1/folder2/owlguide.pdf

So if someone googles 'program name' or googles for our 'owl guide', the Google result takes them to the old URLs (broken links) rather than the new URLs.

Is there a way I can redirect these broken links to e.g. a search page on our website, rather than the "404 page not found" page?

For some of the old URLs to our pages (e.g. /program-name rather than /programname) I've been able to set up URL aliases to redirect people but don't know how I can do so for the files when there are so many that I wouldn't be able to work out.

Sorry if I haven't used the right words, I'm not a web developer! I looked into Pathologic but don't think it addresses the problem we're having...

Goto http://YOURSITE/admin/config/system/site-information and under "ERROR PAGES
" change "Default 404 (not found) page" to your search page. In this way, Drupal will redirect all 404 pages to the page that you have provided.


Fivestar appears on content type, but can't vote I have problem with Fivestars module, (Drupal7).

It is configured in field and appears on content type page, but cannot vote
(like voting is disabled - when inspecting with firebug, i see no Javascript activity over stars, and no any possible javascript conflict.)

Permissions are set correctly.

What in the world could cause this ?
(it seems more-less like plug-and-play module :D )

When adding the FiveStar field,

If you choose "Rated while viewing" , that means all users can rate the node (with permissions) can rate the node. This is ideal to allow users to rate how well the article was writtem etc).
If you choose "rated while editing", it will make the rating field disabled (static field) for other users than the node author. This is ideal for review nodes to allow the reviewer to leave their ratings while making the node or any other entity.


Programmatically assign a node to an organic group How can I programmatically assign a node to an organic group?

I have tried the followings and non of them worked (assuming $target_group is the group ID that I want the $node to be assigned to):

$node->og_groups = array($target_group => $target_group);
node_save($node);

,

$group = node_load($target_group);
$node->og_groups[0] = $target_group;
$node->og_groups_names[0] = $group->title;

What is the proper way to do this?

Assuming Drupal 7, you want to use the og_group function in the API

/**
 * Set an association (e.g. subscribe) an entity to a group.
 *
 * @param $gid
 *   The group ID.
 * @param $values
 *   Array with the information to pass along, until it is processed in
 *   og_entity_presave(). Keys are:
 *   - "entity type": Optional; The entity type (e.g. "node" or "user").
 *     Defaults to 'user'
 *   - "entity" :Optional; The entity to set the association. Defaults to the
 *     current user if the $entity_type property is set to 'user'.
 *   - "state": Optional; The state of the association. Can be:
 *     - OG_STATE_ACTIVE
 *     - OG_STATE_PENDING
 *     - OG_STATE_BLOCKED
 *   - "save": Optional; TRUE if fields value should be saved. Defaults to TRUE.
 *   - "force reload": Optional; Determine if og_load_entity() should be used on
 *     the passed entity. This can be used when you pass an entity that has been
 *     saved yet to the database, but you want to assign it groups. Defaults to TRUE.
 *     // TODO: Adds docs on rest of keys.
 *
 * @return
 *   The entity with the fields updated.
 */
function og_group($gid, $values = array()) { ...

For your code, this would look like:

$values = array('entity type' => 'node', 'entity' => $node, 'state' => OG_STATE_ACTIVE);
og_group($target_group, $values);
node_save($node);


Image styles not generated with Drupal 7 on IIS 6 I've developed a site that uses various image styles to export images to an iPhone (linked from a XML export document). This worked perfectly fine on my own development server with Linux/Apache.

The site is now currently hosted on a shared hosting environment, which uses Windows/IIS6. (yeah, strange; it is not my decision as you can assume ;).)

The problem now is that the image_style URLs for new images (existing images work) lead to a 404 error page, which is directly served by IIS. However, clean URLs worked fine out of the box and "normal" 404 pages are displayed by Drupal.

So, an URL like http://example.org/does_not_exist shows the typical site not found error, served with Drupal but http://example.org/sites/default/files/styles/command_image/public/Chrysanthemum_0.jpg shows the IIS 404 page.

The site is using the public file system for these images and the path is correct; it does work fine for existing images, which I uploaded together with the rest of the site during the initial deployment on that server.

Do you have any idea?

Ok, I figured it out.

The problem was that there were two .htaccess files. One in the top level, that contains most of the configuration and one in sites/default/files, which is security related (avoid execution of php files and similar) and contains just this:

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

Now the difference seems to be that in Apache, both files seem to be combined (the one in sites/default/files inherits everything from the top-level one). This does not happen with the ISAPI_Rewrite module that seems to handle the Apache/IIS .htaccess compatibily.

I fixed this by copying the content of the top-level directly into the file in sites/default/files, below the existing content. Additionally, I had to change the RewriteBase so that it included the index.php file in the correct directory.

The header of the changed .htaccess file now looks like this:

# From the original .htaccess file, do not remove.

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

#
# Apache/PHP/Drupal settings:
# (copied from /.htaccess)
#

Content of the top level .htaccess file here comes here...

And the part that I changed now looks like this:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
RewriteBase /YOURFOLDERHERE

So when Drupal is installed in a sub directory, insert your folder name. If not, you can leave this part commented out.

I found this thanks to the (unecessarly long) blog post at http://www.caspianit.co.uk/imagecache-wrong-path/

Note: Simply deleting the .htaccess file in sites/default/files did work too, however, that removes the security relevant SetHandler setting. I however doubt this has any effect in IIS anyway...


Display total in views I'm using Drupal 7 with views 3.

I am listing the fee of students in a view developed using views 3. How can I show the total of fee for all records displayed at bottom as Total Fee. I tried Views_calc module, but this module is with some errors and notices.

Thanks in advance for your help.

Used this hook

function fee_management_views_pre_render(&$view) {
  if($view->name == 'payment_schedules' && ($view->current_display == 'receive_payments')) {
        $total_payable_amount = 0;
        foreach($view->result as $key => $payment) {
            $total_payable_amount += $payment->fee_schedule_instalments_amount;
        }
        $view->attachment_after = "<div> Total Payable Amount: $total_payable_amount</div>"; // does not work with fee_management_views_post_render

    }
}


How to get main menu to highlight the link to the current page? My theme, Riley, highlights menu item of the page that you're on. (for example). I suspect this is a function of Drupal and not specific to the theme. First question: is this generally true?

If the answer to the first question is no and it is theme specific, then I can try to ask the theme makers the next question. Otherwise, my next question is, when I have multiple menu links that link to the current page, it will highlight the last link. How can I get it to highlight the first link instead? I am comfortable modifying PHP code.

For example, Menu Tab 1 contains link to current page P1 and deep within Menu Tab 2 also contains a link to P1, then it will only highlight the P1 link in Menu Tab 2.

Any thoughts / suggestions would be appreciated!

Setup: Apache 2.2, PHP 5.3, Drupal 7.34, PostgreSQL 9.2

normally this is accomplished via css in the theme, with the active attribute:

li a.ctive {
  ...
}

it is not core functionality. You could look at the different -child pseudo-elements to tweak it, or use some JS, but I think that portion of the question would be off-topic here - you are better off asking on stackoverflow


How to extend the user registration in Drupal 7 I want to run a set of php code(not drupal code) after the user submits the registration form.

user enter details
submit the form drupal
writes form data to db
execute custom code
comes back to default registration tanakyou page of drupal

For this how will i extend the default user module of drupal without touching the core user module codes.

can i define a custom module and execute its resources

you can add any action you want after user registered by implementing hook_user_insert.


Contextual filter using any term ID I want to set up a view with a contextual filter that will work with any term id (without selecting a specific category). I could only find some old, dated mentions of this. So I'm not sure if this is really possible currently or not.

Sorry I wasn't trying to be vague. My view was based on an entity, rather than content, like a node. So I wasn't seeing the "Has taxonomy term id" option in the list of contextual filters. I was only seeing specific taxonomy fields as options. I found that core does not offer that by default for other entities.

I did find a module that provided the functionality I was seeking:
https://www.drupal.org/project/taxonomy_entity_index

I will also say that this module seems to expect entities to have bundles. If not there is an error. I'm going to submit a patch soon.

Hopefully that will help others. I will take my 2 downvotes and go home now.

(I'll also include this issue link for having the functionality in core: https://www.drupal.org/project/drupal/issues/1040786)


Where do I add HTML content into a block? I have created a custom block, but there is no option to add content or any body part.

How do I add content to a block?

I think you first want to define the fields of a block content type. You'll find this at this url:

www.mysite.com/admin/structure/block/block-content/types

In the admin UI this is not so easy to find like the node content type at the top  level of the admin structure. The block content types are two or three levels deeper in the block layout. To access above link make sure you have the Custom Block module enabled.


How to set the value of a date field via Rules? One content type in my Drupal page has a date field. After importing start hour, start minute and duration (Integer values) from an XML file, I want to set date field of the node via Rules. It seems that I cannot access the start date and duration of the date field.

Is there a solution to set the start date, end date, repeating, etc. ?

Before you will be able to create a Rules Action like "Set a data value" for your date field, you have to make sure to add a Rules condition Entity has field (related to the  field for which you want to set a value). And make sure to add that Entity has field condition BEFORE other Rules Conditions in which you might want to refer to this field.

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says:

  The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


Using OR with EntityFieldQuery I have never had the need to do this before today, but it doesn't seem like you can make OR queries with EntityFieldQuery, since db_or is used for select queries.

An example would get to all entities that has a date field where the value is null or after today.

Am I missing something or some trick or is this simply not supported?

I have seen a solution of this problem. The idea is to use addTag() in query and implement hook_query_TAG_alter(), where you have good old SelectQuery object.


How can I get the page title? drupal_get_title() has been removed from Drupal 8. How I can get the page title in Drupal 8?

If you check the change records you should find the following: drupal_set_title() and drupal_get_title() were removed.

You'll have to read the change notice for all of the info, but here is a starting point:

  drupal_get_title()

  As titles on routes now can be set on various ways (see above),
  drupal_get_title() has been removed. In its place you should call the
  title_resolver service.

  Drupal 7

<?php
  $title = drupal_get_title();
?>

  Drupal 8

<?php
  $request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  }
?>


tableselect form doesn't work I can't get form-table of '#type' => 'tableselect' to work.  I've lifted the example from 8.3.x core/lib/Drupal/Core/Render/Element/Tableselect.php Tableselect. The table works and there are no log messages.

What happens is the page reports that there are no users found (ie. the table is empty) even though the $form array has the row data in it.

If I change the type to '#type' => 'table' the table is populated as expected.

This is the code I am using.

namespace Drupal\simpleForm\Controller;
use Drupal\Core\Controller\ControllerBase;

class DisplayTable_1 extends ControllerBase
{

    public function description_one()
    {
        $header = [
            'first_name' => $this->t('First Name'),
            'last_name' => $this->t('Last Name'),
        ];

        $options = [
            1 => ['first_name' => 'Indy', 'last_name' => 'Jones'],
            2 => ['first_name' => 'Darth', 'last_name' => 'Vader'],
            3 => ['first_name' => 'Super', 'last_name' => 'Man'],
        ];

        $form['table'] = array(
            '#type' => 'tableselect',
            '#header' => $header,
            '#options' => $options,
            '#empty' => $this->t('No users found!!!'),
        );

        return $form;
    }

}

Any help would be appreciated.

Found the issue: the #type' => 'tableselect has to be built inside a class that extends FormBase.

This Works:

  class DisplayTable_1 extends FormBase {
    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $options = [
            1 => ['first_name' => 'Indy', 'last_name' => 'Jones'],
            2 => ['first_name' => 'Darth', 'last_name' => 'Vader'],
            3 => ['first_name' => 'Super', 'last_name' => 'Man'],
        ];

        $header = [
            'first_name' => t('First Name'),
            'last_name' => t('Last Name'),
        ];

        $form['table'] = [
            '#type' => 'tableselect',
            '#title' => $this->t('Users'),
            '#header' => $header,
            '#options' => $options,
            '#empty' => t('No users found'),
        ];

        // Add a submit button that handles the submission of the form.
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
            '#description' => $this->t('Submit, #type = submit'),
        ];
        return $form;
    }

    public function getFormId() {
        return 'fapi_example_input_demo_form';
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Find out what was submitted.
        $values = $form_state->getValues();
        foreach ($values as $key => $value) {
            $label = isset($form[$key]['#title']) ? $form[$key]['#title'] : $key;

            // Many arrays return 0 for unselected values so lets filter that out.
            if (is_array($value)) {
                $value = array_filter($value);
            }

            // Only display for controls that have titles and values.
            if ($value && $label) {
                $display_value = is_array($value) ? preg_replace('/[\n\r\s]+/', ' ', print_r($value, 1)) : $value;
                $message = $this->t('Value for %title: %value', array('%title' => $label, '%value' => $display_value));
                drupal_set_message($message);
            }
        }
    }
}


Timezone Dropdown List in User Account Doe anyone know how to change the timezone dropdown list in the user account/registration?
So which file is the menu/settings located in? (Assuming I am using Garland theme if that matters, and the variables will still be stored as a string, ie America/Chicago). Alternatively, how to change the user registration/account settings page so I can key in my own dropdown form.

Thanks!

[The reason is that it is quite difficult to find some locations in the US on it (It would make sense to make the American cities easier to find in their own section rather than in a collective North & South & Central America). So I want to be able to set in some choices manually or at least make it more intuitive (such as sorting by GMT +/-, I understand the issues with timezone, unix time, etc ...meaning they depend on the political area and jurisdiction, along with DST in some states and not so in others, ie Indiana, Arizona etc...)]

I was thinking of changing the format to this:

'America/Denver' => '(GMT-07:00) Mountain Time (US & Canada)',
'America/Chihuahua' => '(GMT-07:00) Mexico/Chihuahua',
'America/Phoenix' => '(GMT-07:00) USA/Arizona',
'America/Regina' => '(GMT-06:00) Canada/Saskatchewan',
'America/Tegucigalpa' => '(GMT-06:00) Central America',
'America/Chicago' => '(GMT-06:00) Central Time (US & Canada)',

User register forms are built by the User module, but the timezone widget is added by the Locale module through locale_form_alter() (an implementation of hook_form_alter()).

The Drupal community suggests leaving the core files alone (see Do not hack core). If you want to change the form, just write your own implementation of hook_form_alter(), and add/edit the available values using the form API and the "select" form field.

There is a nice tutorial at Brenda Boggs blog.


"Demonstrate Block Regions" not showing I did a minimal install, with a desire to get rid of some of the stuff my site-to-be won't need.

The problem I have... is I can't seem to get Demonstrate Block Regions working. It shows up on a "Standard" install... but not the "Minimal" install on 7.

Top one is Standard install. Bottom one is Minimal.

What module or setting am I missing?

You are missing the System help block.

That is what is displaying the current help tips:

SS http://tardis1.tinygrab.com/grabs/99f4a5fef70efc8f19ddb137c664c7cf22b0599ff5.jpg

When you activate the block the help tips will be displayed whenever possible.


Custom module blocks: where to put html code? I have a custom module that implements hook_block_view. I would like to know where should I put extensive html code for a block content.

For example:

$block['title'] = t('TEST');
$block['content'] = '
';
$block['content'] .= ... 50 LINES OF HTML.
$block['content'] .= '
';

What I did so far was to create a .tpl.php file and put all this code there, and then only call:

$block['title'] = t('TEST');
$block['content'] = theme('user_custom_block');

Is it correct?

If yes, so far, so good. But what if I have a "complex" logic inside of this block content?

For example:

$block['title'] = t('TEST');
for...
  $block['content'] = '
';
  if:
    $block['content'] .= ... 50 LINES OF HTML.
  endif;
  $block['content'] .= '
';
endfor;
etc
etc

Is this still ok to use in a .tpl.php file? If not, which approach should I use?

Should I use something like this?

/**
 * Implementation of hook_block_view().
 */
function custom_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
      $block['subject'] = t('Block Name');
      $block['content'] = custom_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function custom_contents() {
  return '

        Hello World, this is a example custom Block

    ';
}

You could improve that with 2 different options:
1) Creating a theme function
2) Creating a template file (tpl)

The tpl may be a cleaner option, but they are both similar. In both cases, you should pass preprocessed variables instead of putting the logic inside the theme function/tpl file.

Also, note that the literal strings should go through the t() function.


The new version of my module depends on more modules than the old version ... how to ensure module users install them? I am updating an existing module I have developed. The new version requires a "helper" module that the old version did not (fwiw, specifically "Nodereference Count"). How do I ensure that when people upgrade from the prior version of my module to the new version, they make sure to install the newly required helper module first?

Is there something I should put into hook_update_n function?

Thanks.

You could use hook_requirements(), which should allow you to display an error when the module is installed/updated.

Alternatively, if that doesn't work you can implement hook_init() to run a check for the modules and react accordingly.

Update: I've just run into the same issue myself and here is the code that I have used:

/**
 * Implements hook_init().
 */
function MYMODULE_init() {
  if (!module_exists('ctools')) {
    module_enable(array('ctools'));
    if (!module_exists('ctools')) {
      drupal_set_message(t('MYMODULE has been disabled as the required !ctools module is not present.', array('!ctools' => l(t('Chaos tool suite'), 'http://drupal.org/project/ctools'))), 'error');
      module_disable(array('MYMODULE'));
    }
  }
}

This will try to enable the required module and if it is unable to do so it will display an error message to the user and disable the my module.


Collapsible fieldsets in form using button How can I make a button collapse a fieldset in my custom form? I tried the following which did not seem to work:

$form['stepone']['next'] = array(
    '#type' => 'button',
    '#value' => t('Next'),
    '#name' => 'nextone',
    '#weight' => 1,
    '#submit' => array('collapse_next'),
    );

The function is:

function collapse_next($form, &$form_state){
    if(isset($form_state['values']['nextone'])){
    $form['stepone']['#collapsed'] = TRUE;
    $form['steptwo']['image']['#collapsed'] = FALSE;
    return $form;
    }
}

you may use jquery for this. give some id to your button and on button click trigger the default fieldset collase or use toggle to hide show fieldset. Hope this help!


How to specify in a form field's #ajax setting that the entire form should be rebuilt I have a form with 3 sequential selects at the top, each populated as a result of the selection in the one prior.

After the third select is choice is made, a large number of fields segregated into two vertical tabs should be populated.

In the form, I set the default value of each of the fields to an associative array element, which is empty when the form is first built.
When the third select choice is made, its callback
a. obtains an associative array of the values needed for the form
b. stores them in $form_state['storage']['mykey']
c. sets $form['rebuild'] to true (for good measure)
d. returns $form
In the form function, prior to the field definitions, I set the associative array used for the default values to $form_state['storage']['mykey']

I can see in xdebug that $form_state has the data in the correct place prior to returning, but when execution returns to the form function, $form_state no longer has a ['storage'] key.

AJAX CALLBACK

function my_ajax_callback($form, &$form_state) {
  $form_state['storage']['draft'] = my_mysql_get($form_state['values']['id']);
  return $form;
}

FIRST LINE OF FORM FUNCTION (most fields use $r for default_value)

  $r =  !isset($form_state['storage']['draft']) ?  array() : $form_state['storage']['draft'];

A breakpoint at the callback reveals that it is reached, and that $form_state['storage']['draft'] is populated at the point of returning.

A breakpoint at the equate reveals that ['storage'] is no longer in $form_state, but this is only reached (in the form function) if I return only a field from the callback, not the entire form. I really need the entire form, because 17 of 20 fields on the form need to be rebuilt at that point, to get the default value into them.

FORM FIELD WITH AJAX CALLBACK

  $form['info'] = array(
    '#type' => 'select',
    '#title' => 'Player',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => info_options($form_state['values']['key1'], $form_state['values']['key2']),

    // ajax to bind this select to the players select
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'my_ajax_callback',
      'wrapper' => 'my_form_id',
    ),

The workflow in an AJAX callback with a non button element is:

Submit data is received, form is constructed and validated.
If no validation errors are detected form is rebuilt. This means that the form function is called again (the form that returns the form structure).
AJAX callback function is called. The task of this function is only to return the data to the browser. No persistent calculations should be done here.

You have to detect if tou are in an AJAX form request in your form function. If yes, calculate your date. Then, construct your form accordingly. Last, return the right form fragment (or the whole form) in your AJAX callback function.

Form function:

 $form['info'] = array(
    '#type' => 'select',
    '#title' => 'Player',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => info_options($form_state['values']['key1'], $form_state['values']['key2']),

    // ajax to bind this select to the players select
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'my_ajax_callback',
      'wrapper' => 'my_form_id',
    ),

// If all selects have values get data to populate elements in vertical tabs.
if (all_select_have_values()) {
  $form_state['storage']['draft'] = my_mysql_get($form_state['values']['id']);
}

// Then add the rest of form elements.
$r =  !isset($form_state['storage']['draft']) ?  array() : $form_state['storage']['draft'];
...

In callback just return your form:

function my_ajax_callback($form, &$form_state) {
  return $form;
}

You are losing the values in $form_state because you are adding data to the $form_state in the callback function. AJAX calls are procesed by ajax_form_callback(). This function first calls drupal_process_form(), and then the AJAX callback function. $form_state is saved (when condition apply) at the end of drupal_process_form function.


Cache SOAP search results from external web service I've inherited an older Drupal 6 site which calls an external SOAP web service which not only takes a while to query and display results (approx. 5 seconds) but also re-queries the web service when any parameters are changed (e.g. results per page or ordering).

I am considering what efficiency improvements I can make (such as not re-querying the web service when some parameters are changed) but that will involve caching the initial responses, etc.

Was looking for suggestions that I might not have considered, importing the results into nodes isn't really an option due to the potential number of results

I suppose you could hack together a module that queries the external site and then populates an Apache Solr search database, then you could simply use the Apache Solr Search module on read-only to look at the data on your site...


views_get_current_view performance Does this function views_get_current_view inside views header or footer (to count rows number for example) means running the same view twice?
 Or is it somewhat simplified version of running full view? Thank you.

That function is just a wrapper for this function:
https://api.drupal.org/api/views/views.module/function/views_set_current_view/7.x-3.x
which will just return a reference to a static code cache.

Conclusion: no view gets run, it's just grabbing a copy of what's already been created.

In general, views is very efficient in such cases.

But I'd tend to agree with @berramou that you might have a better way of accomplishing what you really, really want.


Adding a full screen background image to Drupal 7 / Bartik theme Has anyone managed adding an image as background to a Drupal 7 with default Bartik theme?

Maybe using a fullscreenr plugin for jQuery?

I'm not sure where to store that code best and do I need to include jQuery or is it already included (I suppose it is included, but you can't call $() for some reason there? What does it mean to be changed in fullscreenr code below?)

And how can I call $.fn.fullscreenr (or whatever should be called to plant the background image) in Drupal?

Thank you! Alex

/**
* Fullscreenr - lightweight full screen background jquery plugin
* By Jan Schneiders
* Version 1.0
* www.nanotux.com
**/
(function($){
    $.fn.fullscreenr = function(options) {
        if(options.height === undefined) alert('Please supply the background image height, default values will now be used. These may be very inaccurate.');
        if(options.width === undefined) alert('Please supply the background image width, default values will now be used. These may be very inaccurate.');
        if(options.bgID === undefined) alert('Please supply the background image ID, default #bgimg will now be used.');
        var defaults = { width: 1280,  height: 1024, bgID: 'bgimg' };
        var options = $.extend({}, defaults, options);
        $(document).ready(function() { $(options.bgID).fullscreenrResizer(options); });
        $(window).bind("resize", function() { $(options.bgID).fullscreenrResizer(options); });
        return this;
    };
    $.fn.fullscreenrResizer = function(options) {
        // Set bg size
        var ratio = options.height / options.width;
        // Get browser window size
        var browserwidth = $(window).width();
        var browserheight = $(window).height();
        // Scale the image
        if ((browserheight/browserwidth) > ratio){
            $(this).height(browserheight);
            $(this).width(browserheight / ratio);
        } else {
            $(this).width(browserwidth);
            $(this).height(browserwidth * ratio);
        }
        // Center the image
        $(this).css('left', (browserwidth - $(this).width())/2);
        $(this).css('top', (browserheight - $(this).height())/2);
        return this;
    };
})(jQuery);

Are you actually trying to use fullscreenr because you want a full screen background image that re-sizes with the browser? Or do you just want to have a background image?

If you're just looking to use a background image, you don't need jQuery. You can just edit the CSS. Though, if you're changing a builtin theme like Bartik, you should actually create a subtheme instead of editing the builtin theme's files.

If you actually need fullscreenr then you need to add the javascript files for the plugin and your file that calls the fullscreenr method to your theme's .info file (again, you should not edit the builtin theme's files, you should create your own subtheme). In the example below, I'm just editing Bartik's files (don't do this, use a subtheme). You should add the following to the theme's .info file

stylesheets[all][] = jquery/fullscreenr/css/fsbg-style.css
scripts[] = jquery/fullscreenr/js/jquery.fullscreenr.js
scripts[] = js/fullscreenbg.js

In this example, I added a jquery folder to the theme's folder and put the fullscreenr folder containing the plug-in into the jquery folder. I also slightly renamed the style.css file that comes with the plugin (in addition to deleting all the extra option stuff from that file). I put my code for actually calling the plug-in into the js/fullscreenbg.js file. The code looks like (details on why it's wrapped like that in the Drupal docs for changes from D6 to D7):

(function ($) {
  // You need to specify the size of your background image here (could be done automatically by some PHP code)
  var FullscreenrOptions = { width: 1024, height: 768, bgID: '#bgimg' };
  // This will activate the full screen background!
  jQuery.fn.fullscreenr(FullscreenrOptions);
}(jQuery));

I think this was the part you were really having trouble with.

There are some other minor things you need to do to set up the fullscreenr plug-in. I highly suggest getting it to work on a very basic html page outside of Drupal before putting it into a Drupal theme so you know you're at least using the plug-in correctly. Also, keep in mind that Bartik has a lot of other stuff going on with background colors and such on various parts of the page, so just adding the background image without editing the theme's CSS is not going to appear to make any difference.


Need help with template_preprocess_node I have a block with a select box and submit button. The main purpose of the select box is to store a variable in the session. I used template_preprocess_node to filter contents based on user selection.

function blackout_preprocess_node(&$vars) {
  $node = $vars['node'];

  // define a variable to hold your rendered content
  $newContent = "";

  if($_SESSION['myid'] == '1' && $node->field_field1[0]['value'] != '') {
    $newContent = $node->field_field1[0]['view'];
  } else if($_SESSION['myid'] == '2' && $node->field_field2[0]['value'] != '') {
    $newContent = $node->field_field2[0]['view'];
  } else {
    $newContent = $node->body;
  }
  if (strlen($newContent)) $vars['content'] = $newContent;
}

Everything is working fine except I have to click submit twice to reload the page contents or I have to move to another page to see re-loaded content. How can I reload content with just one click?

Blocks are rendered in hook_preprocess_page. At that time, all implementations of hook_preprocess_node have already been executed, so you cannot influence how the node is displayed (apart from messing with the HTML in $vars['content']).

If you use Drupal's Form API to implement the select list and the submit button, Drupal will redirect you after submitting the form, so you do not need to reload the page manually. See Post/Redirect/Get for why it is generally a good idea to redirect after a HTTP Post.


reseting the hook_update_n status of a module I'm extending a module I've previously written and it needs some schema changes which I implement in hook_update_N.

I've updated the module's version from 7.x-1.0 to 7.x-1.1 and implemented the foo_update_7100 and it works fine.

The problem is that I've made a mistake inside foo_update_7100 and now that I've fixed it I cannot rerun the 7100 update. I need to create a 7101 one but that doesn't make sense because all my changes are not committed yet.

I've tried reseting the status of the hook_update_n via:

update system set schema_version=-1 where name='foo';

> Query OK, 1 row affected (0.01 sec)
> Rows matched: 1  Changed: 1  Warnings: 0

Then I do drush cc all but drush updatedb -y still gives me "No database updates required".

How can I solve this instead of simply incrementing the hook_update_N number?

FYI, in Drupal 8, the system table has been removed, and this information is now stored in the key_value table.

UPDATE key_value SET value='i:8000;' WHERE collection = 'system.schema' AND name = 'module_name';

(As noted above, the actual value should be less than the hook_update_N() you want to repeat, but higher than or matching the last update that does not need to be repeated.)


How do I create a dynamic link for a block? I have two dynamic links that I want to put in a block, e.g. http://domain.com/series/naruto/addreview ("series" is the content type, and "naruto" is the node title), http://domain.com/node/add/album/1 ("1" is the node ID).

I want to change the URL depending on what node is being viewed. How can I do it?

You can get the node id from the url, since all nodes are displayed at node/[nid]. So if you in your block do

$nid = arg(1);
$node = node_load($nid);

You will get the node which has the title and the nid that you can use in your links. You would need to check that the block is on a node page as well by doing:

if (arg(0) == 'node')


Show all nested menu links in Drupal 7 How do I display all nested links in

 format in Drupal 7? The default code only displays the 1st level links even though they are arranged in the Drupal admin menu as nested:

<?php if ($main_menu): ?>

 <?php print theme( 'links__system_main_menu', array('links' => $main_menu) ); ?>

<?php endif; ?>

Only the 1st level is displayed in the ff. menu setup:

-Fruits
---Apples
---Oranges
---Lemons
-Cars
---Big car
---Small car
---Fucked up car
-Whatever

The default $main_menu variable in page.tpl.php is set to menu_main_menu(), which is a contextual view of the main menu tree.

To get your desired output, you need to get the entire menu tree using menu_tree_all_data() and menu_tree_output().

To do this in your theme, create template.php if you haven't already, and add a new preprocess function for the page template:

function THEMENAME_preprocess_page(&$variables) {
  // Get the entire main menu tree
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Add the rendered output to the $main_menu_expanded variable
  $variables['main_menu_expanded'] = menu_tree_output($main_menu_tree);
}

Then, in page.tpl.php, you can just use:

<?php print render($main_menu_expanded); ?>

to get a expanded, nested unordered list of the main menu.

For a little more flexibility, you might want to consider the Menu Block module, which will let you create blocks of expanded menus out of the box with its Expand all children of this tree option as well as a host of other options for segmenting menu trees.


Change data on form submit handler I have a form alter handler like this.

function toyotaec_form_webform_client_form_seleccionar_alter(&$form, &$form_state) {
    $concesionarias = concesionarias();

    $form['actions']['submit']['#value'] = 'Enviar';
    $form['submitted']['concesionaria']['#options'] = $concesionarias;
    $form['#validate'][] = 'toyotaec_form_webform_client_form_seleccionar_validate';
    $form['#submit'][] = 'toyotaec_form_webform_client_form_seleccionar_submit';
}

Actually, this code is not a hook_form_alter but a function called by the actual hook. The hook calls this function passing &$form and &$form_state also by reference.

After this, I have the corresponding handlers. Both handlers are called as expected. The handler I want to focus in is as follows:

function toyotaec_form_webform_client_form_seleccionar_submit(&$form, &$form_state) {
    $values = $form_state['values']['submitted_tree'];
    $input = &$form['submitted'];

    $concesionaria = trim($values['concesionaria']);
    $redirigir = trim($values['redirigir']);
    $modelo = trim($values['modelo']);

    //obtenemos cual es la concesionaria (por marca, descartamos las ciudades)
    $mconcesionaria = current(explode('-', $concesionaria));

    //las redirecciones diferidas van a tener una salvada incluyendo la url.
    //las redirecciones directas no van a tener salvada.
    $form_state['values']['submitted']['3'] = _redirect_bystore($mconcesionaria, $redirigir, $form_state, $concesionaria, $modelo);
}

For the last line, I also tried assigning $form_state['values']['submitted_tree']['url']. This url field is the 3rd field and I have to keep track of it, but even when the data is stored in the array (confirmed by using dpm() on it), the form result has a blank url field.

For this, I'm using Webforms in Drupal 7.

My question is: how can I alter the submitted data? It seems that - for the submit handler - form state is not passed by reference.

You're accepting $form_state by reference, so the changes you make will definitely persist onto the incoming variable when your function loses scope. The variable/calling function doesn't control whether it's a reference here, your function signature does. The FAPI doesn't use the old pass-by-reference style (e.g. foo(&$bar), which has been deprecated and removed), so you're in control of that.

Chances are the webform submit handlers are running before yours, so the changes you make aren't actually used by anything, despite being correctly added to the array.

To get around it, simply use a validate handler instead. This will run before the form submission, and changes you make to $form_state['values'] will be available to the webform's submit handlers (as well as your own if you need to do extra processing).

I think you can probably use exactly the same code as in your submit handler.


Code comments in TPL file that wont be rendered in HTML? Can I add code comments to my template files that won't be publicly shown in the HTML?

You can use PHP comments, those will be ignored by the template engine and not rendered to HTML:

<div class="something">
  <?php /* This won't be visible in the source. */ ?>
</div>


Blocks aren't being assigned to a region Is there any reason that these blocks wouldn't be assigned to the regions specified?  The only way I can get these to appear is to set them manually.  Kinda defeats the purpose of defining a region in the first place.

function custom_module_block_info() {

  $blocks = array();
  $blocks['footer_touts'] = array(
    'info' => t('Footer Touts'),
    'status' => TRUE,
    'region' => 'footer',
  );

  $blocks['carrousel'] = array(
    'info' => t('Carrousel'),
    'status' => TRUE,
    'region' => 'hp_content',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '<front>',
  );

  return $blocks;
}

(Luis already answered eir own question, in the comments above, but I thought I'd add something here; all kudos to Luis though.)

The status property returned by a module's implementation of hook_block_info() must be TRUE. This is slightly unintuitive because when enabling blocks in the UI, one only has to choose the region—however, in doing so a block's status is also changed. Programmatically, we must set both status and region properties. (I'm not sure there would ever be any reason to set one and not the other.)

When doing this to an already-enabled module, it would seem that clearing the block cache (drush cc block) is not enough, nor is dis- and re-enabling the module; it must be uninstalled and reinstalled for the change to take effect (drush dre custom_module if you've got Devel).

Note also that Drush seems to get confused when doing this with a region that doesn't exist in the default theme (reporting that "The block Carrousel was assigned to the invalid region hp_content and has been disabled."). This is not true; the block is enabled.


Send a CSV file to the user on FAPI form submit I have a FAPI form that collects some information from the user, then generates a CSV file. The intent is when the user clicks 'export' on the form, the CSV is downloaded straight away.

However, when the submit handler calls the CSV-generating function, the form just redirects, rather than serving the CSV.

Is there any way to make this form serve the CSV to the user directly, without generating a temporary file?

I guess the code in this blog post http://sirkitree.net/node/23 will help. Essentially you need to use exit() or die() at the end of your submit handler to prevent redirect.

  $file = $header ."\n";
  foreach ($accounts as $row) {
    $file .= $row ."\n";
  }
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="users.csv"');
  die(print $file);


Permission for anonymous user I got custom registration form under /user/register URL but anonymous user gets denied access what type of permissions should I set.
 I tried:

 requirements:
   _permission: 'access content'

and

requirements:
   _permission: 'none'

or I deleted it completly but it didn't help.

'access content' should be good in general, check it under "people/permissions" to seem if also anonymous users have right to "access content".
You can also declare:

_access: 'TRUE'

In this case you don't need the permission part, this one should definitely work!


Creating/registering a user (of a custom profile type) when a certain webform is submitted? Before all else - Here's my current code.

function hook_webform_submission_insert($node, $submission) {

  $password = user_password(8);

  //set up the user fields
  $new_user = array(
    'name' => $form_state['values']['e_mail'],
    'mail' => $form_state['values']['e_mail'],
    'pass' => $password,
    'status' => 0,
    'init' => $email,
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      6 => 'custom role',
    ),
    'field_dealer_fname'=> $form_state['values']['first_name'];
    'field_dealer_lname' => $form_state['values']['last_name'];
    'field_dealer_company' => $form_state['values']['company_name'];
    'field_dealer_phone' => $form_state['values']['phone'];
  );
 $account = user_save(null, $new_user)

    ->execute();
}

I'm very new to Drupal, but intermediate experienced in Web dev in general. I just recently inherited a client from a previous employee before I joined, and he exclusively used Drupal (7, at that.)

Anyways, he previously had a system to set up a new user through this user-submitted webform, but that functionality apparently died 2 months ago in some sort of host migration. Now, I'm trying to figure out a way to accomplish this task with the already existing webform (v 3.27) and database.

That being said, from what I've found, I'm trying to use a webform Submission Hook to call the (Webform) values

first_name,
last_name,
company_name,
phone,
e_mail

to fill the adjacent (Custom) user profile fields of "Dealer_profile" (along with the default ones)

field_dealer_fname
field_dealer_lname
field_dealer_company
field_dealer_phone

So, referring back to my code, my thought process is:

//create a random 8 char password
  $password = user_password(8);

I was thinking this would be the equivalent of saying "these profile values = this user submitted value"

//set up the user fields
  $new_user = array(
    'name' => $form_state['values']['e_mail'],
    'mail' => $form_state['values']['e_mail'],
    'pass' => $password,
    'status' => 0,
    'init' => $email,
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      6 => 'custom role',
    ),
    'field_dealer_fname'=> $form_state['values']['first_name'];
    'field_dealer_lname' => $form_state['values']['last_name'];
    'field_dealer_company' => $form_state['values']['company_name'];
    'field_dealer_phone' => $form_state['values']['phone'];
  );

and ultimately, save this information and execute the hook?

 $account =    user_save(null, $new_user)

    ->execute();

However, I feel like the hook itself is also wrong. This whole hooking thing in Drupal is a little odd to me, coming from mostly Wordpress use. Unfortunately the documentation is a little barebones, or in some way difficult for me to figure out how these things actually work. I was also just kind of thrown into this, and just have to figure everything out! Help is appreciated!

First you can add your code and add inside sites\all\modules\webform\includes\webform.submissions.inc in functions named "webform_submission_insert" , and check if it works or not , also as per below image in $submission variable you will get all webform submitted values .

Also , if you want to Get Webfrom submitted data by userid wise use below code anywhere.

module_load_include('inc', 'webform', 'includes/webform.submissions');
$values = webform_get_submissions($nid, null, $user->uid, 1);

if you want to Get Webfrom submitted data by node id , as below code 105 is node id.

module_load_include('inc', 'webform', 'includes/webform.submissions');
$submissions = webform_get_submissions(105);


Add conditional stylesheet to URL alias I am attempting to add a conditional stylesheet to my user registration form which has an alias called "signup"

This is the code I am using, however this does not seem to work.  I have tried loads of other different ways but I cannot seem to find any clear documentation on how to do this.

Any ideas on this?  The simpoer the better, my code seems to be quite complex for something so simple.

Thanks

function mytheme_preprocess_page(&$variables, $hook) {
$matches = "signup";
$path = drupal_get_path_alias($_GET['q']);
$page_match = drupal_match_path($path, $matches);
if ($path != $_GET['q']) {
$page_match = $page_match || drupal_match_path($_GET['q'], $matches);
}
if ($page_match) {
drupal_add_css(drupal_get_path('theme', 'mytheme') . '/style.css');
}

Also tried this to no avail

function mytheme_form_alter(&$form, &$form_state, $form_id) {
global $user, $theme;
switch ($form_id) {
    case 'user/register':
      $form['#attached']['css'] = array(
        drupal_get_path('theme', 'mytheme') . '/css/new.css',
      );
    break;
 }

You're right, that is overly complex.

First of all, make sure your mytheme_preprocess_page() function is actually getting called by adding print & then exit statements. If it's not getting called, clear your theme registry by clearing the site's cache.

Once you're sure the preprocessing function is getting called, this will do the trick for you:

if (preg_match('#user/register#', $_GET['q'])) {
  drupal_add_css(drupal_get_path('theme', 'mytheme') . '/style.css');
}

$_GET['q'] always contains the 'internal' Drupal path, not the alias. The internal path for the normal registration form is user/register, so that's what you want to check for.


HTML tags are stripped off from emails I am using HTML Mail, Emogrifier, Pathologic and Echo modules to theme the outgoing Drupal emails into a template based presentation.

So far, I guess it has not been too hard, but I am having a hard time getting the HTML Mail test message to allow HTML. I am using the Full HTML filter on the test message edit, and using Unfiltered for Post filter setting.

I get my test message, but its stripped of <h> tags and <p> tags and anything that isn't an anchor, <code>, <span>, or list. Does anyone know why?

I tried editing various filter formats and nothing affected it. It would seem like it keeps using Filtered HTML no matter what I select, but even still, it is not showing <h> tags and <p> tags.

My Drupal setup relies on some other modules, but otherwise I have the same set up. I am not an expert (critics, take note!), but have you tried creating a new input format which ONLY contains the emogrifier filter?
I have all my standard filters in one input format that gets applied to all content types, and then I have a seperate input format which applies emogrifier as the post-filtering process in HTML Mail.
Just a suggestion. Daniel.


Anonymous sessions breaking login for Drupal 7 This is my first official post so bare with me if i do not have all the information you may need.

Being a beginner of Drupal from a PHP background I am struggling with SESSIONS.

First, there are conflicting information I am reading on how one should set sessions, some say it we should use a unique key, like so:
$_SESSION["uniquekey"] = array();
$_SESSION["uniquekey"]["variable"] = 1;

Others say this is sufficient:

$_SESSION["variable"] = 1;

Secondly, I have managed to set Anonymous sessions without problems, this sets the UID to 0 in the sessions table, the problem I am experiencing is when I login.

Login is succeeding but I am getting "you have no authentication etc" and therefore unable to access the CMS.  FYI in the session table, it has inserted another session with UID set as 1.  I am having to destroy the anonymous session to access the whole CMS but from what I understand the login form should regenerate?

I am setting the sessions in template.php and logging in user /user

Would appreciate if some people can share some light on how one can set sessions without breaking the login?

Your help would be much appreciated

Cheers

If you are actually trying to override the default behaviour of assigning uid, you need to explain why. In order to access the already determined uid information created by Drupal, use this in template.php or a .tpl.php:

<?php
  global $user;
?>

To see what information is already available in $user, make use of the Devel Module:

  Helper functions for Drupal developers and inquisitive admins. This
  module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries).

specifically, the dpm() function.  This can be added just about anywhere as:

<?
  php global $user;
  dpm($user);
?>

This will present a breakdown of the $user array and all the information it contains.


Access CiviCRM event fees via Drupal Views I'm trying to access the Regular Fees data inside of Drupal Views 3. I can see the Fee Label but can't see how I pull in Regular Fees? I've looked at Price sets and setting up a relationship but this seems overly complex for whats required. Wondering if anyone has attempted this/had any joy? Using Drupal 7.42 and CiviCRM 4.7.1

Try using Views Field View following: https://www.ostraining.com/blog/drupal/views-field-view/

You'll need to create the context on Price Set ID in Price Fields, not Price Set.

I don't think this is an efficient way to do this.


Is there a way to switch the Search form (used in the block) to do a Facet Search instead? I am using Faceted Navigation for Search and I want to switch the standard Search block to do a faceted search directly rather than the current situation where I have to switch to faceted search after the standard block shows up.

Is there a module for that, or can it be fixed somewhere in the options?

As stated below I originally understood your question.  Here is how you change the default search page to the one with faceted navigation:
In admin/config/search/settings you can turn off default node search and make faceted your default as shown in the below screen shot.

The Search API module allows you to choose other search methods, including using something like SOLR server for search, which also does faceted queries.


Configure CKEditor plugin I have the autosave plugin for CKEditor enabled and working, but I want to change from some of the default settings (specifically save detection selectors and autosave_delay) and can't get the settings to "stick".  I have been editing ckeditor.config.js (in modules/patched/ckeditor/) and, while that's executing, the settings changes aren't making it to the editor instance running on the page.  I've also hacked at ckeditor.utils.js because I was able to get closer to the actual instance but I know that isn't best practice and I'll regret it down the road.

Drupal7 fyi

You can define (extra) config options in a CKEditor profile. Go to example.com/admin/config/content/ckeditor then select the editor profile(s) in which you have enabled autosave and go to the "Advanced Options".

In the "Custom JavaScript configuration" field you can override config options like

config.autosave_saveDetectionSelectors = "a[href^='javascript:__doPostBack'][id*='Save'],a[id*='Cancel']";
config.autosave_delay = 5;

No need to alter any of the javascript files.


Display fields only once (Views) I would like to show a table of products. I grouped them by nid. In the table header views shows me the nid. Instead of this, I would like to add fields of the node to be displayed once like: node title, image, price.

I attached two illustrations:
Screenshot 1: This is what Views shows me.

Screenshot 2: This is what I would like to have

You can use attachment for this. In Views UI push add and choose attachment. Add the fields as you want them to be displayed. Also look under Attachment settings in the attachment display, choose which view to attach to, before / after etc.


Is there a live backend demo of drupal commerce? Is there a live Drupal Commerce backend demo site?  I would like to take a look before trying to download and install it.

Go to https://simplytest.me
Fill in "commerce kickstart"
Select the latest version: 7.x-2.41
Click "Launch sandbox"
Follow the step-by-step on-screen instructions, including the database configuration screen. You will notice that all fields are already filled in so you can just press "Next".