Drush on Macbook Pro cannot read Dupal Correctly NOW RESOLVED! Tried to get Sass & Compass working on Windows, but ran into too many problems.  Now I have purchased a vintage Macbook Pro (2008).  I finally got Drush working on Windows, but I can't seem to get Drush to work on the Macbook.

ON THE MAC: I am using a MAMP-Stack.  I tried installing Drush-6.0, but it began to ask for 'Composer' and other such further complications.  I installed Pear, but could not figure out the instructions to use Pear to install Drush. So I tried a simple install of Drush-6.0 from a Tar file Download.  I installed it to the '/Applications/MAMP/htdocs' Folder.  It could download Modules and Themes, but Drush could not do a simple Status check or Cache-Clear.  Somehow it could not interact with Drupal.

Next I tried a Zip Download of Drush-5.9.  I removed the previous Drush-6.0 from the 'htdocs' Folder with 'rm -rf drush'.  I installed Drupal-5.9 by pulling the Zip into my  Folder.  Then I did a 'chmod u+x drush' in the working directory of drush.  Then in the same HOME Folder, I edited the .bash_profile and .bashrc Files in Vim.  There is nothing in either of those two files that refers to the previous Drush Path (htdocs) from the previous installation, but now they instead point to the new installation of Drush-5.9 (In the '/Users/MY-NAME/' Folder.

However, when I try to launch Drush, Drush can do a status-report. It reports Drupal, but incorrectly reports the Garland-Theme being used, which is NOT the Default Theme.  By the way this same output happens if I am in the Omega-Theme working directory or the Drupal-Root working directory.

Drush also fails to accomplish a simple 'drush cc' (only the Drush-Cache is available to clear).  Drush cannot do a 'drush pm-list', instead I get an error message about Drush not being able to bootstrap the Drupal Database.

I read the 'read-me' in the Drush-Installation-Folder and tried to follow the prescription for changing my PHP direcory in .bash_profile.  Then trying to follow the instructions for configuring php.ini, I got lost at the point where you try to find out what version of php your Webserver is using (I presume this means MAMP, maybe not).

Now I am at a loss as what to do next to get Drush functional.  Any help is greatly appreciated.

BASH_PROFILE:

# Set Architecture flags

export ARCHFLAGS="-arch x86_64"

#Ensure user-installed binaries take presidence

export PATH=/usr/local/bin:$PATH

export PATH=/Users/ChandraSwami/pear/bin:$PATH

export PATH=/Users/ChandraSwami/Dev:$PATH

export PATH="$PATH:/Users/ChandraSwami/drush:/usr/local/bin"

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php5.4.24/bin:$PATH"

#Load .bashrc if it exists

test -f ~/.bashrc && source ~/.bashrc

:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a
function*

source ~/.profile

END-BASH_PROFILE

RESOLVED. 9/22/2014

I began to discover that the previous method of attempting to change the 'alias' or otherwise redirecting Drush to use MAMP's PHP was the wrong way to go. Especially 'name-distorting' the original MacBook-OS-PHP so that Drush would opt for the MAMP-PHP was causing all kinds of problems with other software, as might be expected. I don't know how this method came to be recommended, but it appears that it is actually a pit-fall.

The way better approach (watch me eat my words in a few weeks), is to rather just upgrade the MacBook-OS-PHP to the same or nearly same version as the MAMP-PHP. Then it does not matter which version of PHP Drush or anything else uses because they are both the same. This overcomes all the issues and is not that difficult to accomplish. At least on my platform which is a MacBook-Pro (2008-Mavericks).

The way that I upgraded my MacBook-OS-PHP was by the CLI-command "curl -s http://php-osx.liip.ch/install.sh | bash -s 5.5".

This is a download from a group of developers in Germany which upgrades your PHP. Check out "http://php-osx.liip.ch/".

Once my System-PHP and MAMP-PHP were almost the same, all my issues with Drush went away. I undid all my 'aliases', 'redirects' and 'name-distortions'. So far all is working well.

Note that on my machine MAMP is using PHP-5.5.14 and my CLI reports with a "php -v" command that MacBook-OS is using PHP-5.4.30 though I am not sure that the version is accurate. In the write up on the PHP-Upgrade it mentions that the version might not be accurate.

By the way this does not OVERWRITE your previous PHP installation but rather just adds a newer installation and directs your system to use it.

I will update if there later prove to be drawbacks in this approach.

RESOLVED (Now Deprecated in favor of the more recent recommended solution.)

Yes it was the fact that there were different versions of PHP at play here.  That was the whole issue.

After reading rooby's & Paul's comments, I checked out "drupal.org/node/1465956#comment-5793124".  Of course my set up was different, but I just tried to do the best I could by substituting my own environment for the details that jorgensean/teckgirlgeek used and IT WORKED!!

I am using MAMP because it is the 'Suggested Best' Stack by Drupal.Org users and MAMP uses (as of 09/15/2014) Php 5.5.14.  On my MacBook-Pro-2008 this is located at "/Applications/MAMP/bin/php/php5.5.14/bin/php" with the last php being the actual PHP file.  That location was chosen by MAMP itself; I did not choose it.

My Drush.php is installed at "/Users/MY_NAME/drush/drush.php" again with the last drush.php being the actual file.  This is my Drush-Install Directory.  My Drupal-Install is at "/Applications/MAMP/htdocs/drupal7".

As I understand, the crux of the issue is that Drush will default to the MacBook-Pro pre-installed version of PHP which conflicts with the version of PHP which MAMP (or whatever your Stack) is using. This Default MacBook-PHP is in the "usr/bin" Directory. I renamed the PHP-file from php to php-2014-09-15 using the "mv php php-2014-09-15" command.

Originally I followed the instruction of modifying the '.profile' hidden file, but later, reading jorgensean's comment, I undid that modification.

What succeeded was altering the '.bash_profile' file in the Root-Directory.  Following the pattern set up by jorgensean.  I added the following two lines:

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php5.5.14/bin:$PATH"

alias drush='/Applications/MAMP/bin/php/php5.5.14/bin/php  /Users/MY_NAME/drush/drush.php'

From my small understanding, the first statement in the .bash_profile sets the PATH to the desired PHP-5.5.14 file and the second statement tells the OS to substitute the MAMP PHP-5.5.14 for the original PHP that Drush is looking for.

Anyone else with this issue will likely have some differences in their configuration and will have to adjust accordingly.

The essence is that you have to block the original MacBook-PHP file by renaming it.  (PS remember what you renamed it, in case you ever have to change it back.  I am not able to say whether this will cause any issues with any other programs other than MAMP & Drush.)  Then modify your .bash_profile in the Root Directory with Vim or whatever to set a PATH to the MAMP-PHP file and alias the Drupal-PHP to point to the MAMP-PHP.

End of story.

Hope this helps someone else and thanx to all those who made this information available!!


Username Token in block doesn't work I'm  using Drupal 7 and installed the Token filter module.

I want to display a welcome message in block; I used <h2>Welcome [user:name]! </h2> as token, but the token is not recognized.

Why isn't the token recognized? Which token should I use?

Try this token instead:

[current-user:name]

This [current-user:name] token works in block title.


hook to alter custom blocks? I am having a problem with my custom blocks rendering, and I want to programmatically manipulate the blocks to troubleshoot the issue.

I used this question to add this hook to my module:

function mymodule_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message($block->getBaseId());
}

However, when I navigate to my site, I see only the base ids of system blocks:

- page_title_block
- system_main_block
- help_block
- local_tasks_block

My site's header and footer are made of custom blocks, so I should be seeing their ids.

How can I programmatically access my custom blocks?

Edit this is my actual code:

$ cat my_block_hooks.module
<?php

function my_block_hooks_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $block->getBaseId() );
}

And here's a screenshot:

You can see that all the system blocks show up, but my custom block does not.

This is the custom block as I have it set up:

And here I have it placed in the layout:

And of course, I've cleared the cache many times to get to this point.

What am I doing wrong?

The type of entity you are dealing with defines the hook you need to implement; in this case it is NOT block but rather block_content, as provided by the "Custom Block" core module.

N.B.: It is generally good practice to use more specific hooks when possible, as it will have a general effect on your code's performance, i.e. your hook implementation will be called less times if it is more specific. In your case, instead of going through all blocks available on any page during page loading, you are going through only custom blocks (block_content entities).

In order to get your hook_ENTITY_TYPE_view()/hook_ENTITY_TYPE_view_alter() implementation to work, you need to replace ENTITY_TYPE with block_content. That should give you the following code (which I tested and works):

use Drupal\block_content\Entity\BlockContent;
...
function my_block_hooks_block_content_view_alter(array &$build, BlockContent $custom_block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $custom_block->id() );
}

And the visual result:

Good luck!

I am going to take a wild guess, but have you tried clearing the cache? Custom blocks normally do not contain dynamic data and as such can be heavily cached. This causes the block output to be rendered without your hook getting called.

In the configuration menu go to development > performance and hit the 'Clear all caches' button. Then go back to the page with your blocks and see if it made a change. Alternatively you can install the devel module to clear the cache from each page directly.


"focusout" jQuery event I am using Drupal 6 and, therefore, jQuery 1.2.6.

When a user clicks inside my text, there is a pop-up that comes up with a few more options in it. I would like this pop up to disappear when the focus is moved to anywhere outside.   This answer on SO comes very close but the focusout event isn't available to me in jQuery 1.2.6.

Has anyone else encountered this issue? How did you work around it?
I would rather not use the jquery update module, as I don't own the site and don't want to be responsible if the update breaks something else.

Add a .mouseleave() event to the popup div

Taking the example code from the SO question you mentioned, see the working version at http://jsfiddle.net/Laxman13/Mw8VD/6/

Will it work as expected with jQuery 1.3.2, because you can install the jQuery_update module. I normally upgrade jQuery on all drupal 6 sites that I work with due to most jquery plugins etc have compatibility with 1.3.x


Making a file downloading system with valid input in a custom drupal 8 form I am trying to create a custom drupal 8 form, that is going to allow user to enter his/her firstname, lastname and email address, and if the user enters these credentials, will be able to download the file that I will upload to cms. This is how my form looks like right now:

namespace Drupal\whitepaper\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;

class WhitePaperForm extends FormBase {

/**
 * {@inheritdoc}.
 */
public function getFormId() {
  return 'whitepaper_form';
}

/**
 * {@inheritdoc}.
 */
   public function buildForm(array $form, FormStateInterface $form_state) {
  $form['iam'] = array(
   '#type' => 'select',
   '#title'=>t('I am:'),
   '#options' => array(
    'dentist' => t('Dentist'),
    'broker' => t('Broker'),
    'engineer' => t('Engineer'),
   ),
   '#required' => TRUE,
  );
  $form['fname'] = array(
   '#type' => 'textfield',
   '#title' => $this->t('First Name:'),
   '#required' => TRUE,
  );
  $form['lname'] = array(
   '#type' => 'textfield',
   '#title' => $this->t('Last Name:'),
   '#required' => TRUE,
  );
  $form['email'] = array(
   '#type' => 'email',
   '#title' => $this->t('Your .com email address.'),
   '#required' => TRUE,
  );
  $form['show'] = array(
   '#type' => 'submit',
   '#value' => $this->t('Download Whitepaper'),
  );

  return $form;
}

/**
 * {@inheritdoc}
 */
public function validateForm(array &$form, FormStateInterface $form_state) {

  if (strpos($form_state['values']['email'], '.com') === FALSE ) {
    $this->setFormError('email', $form_state, $this->t('This is not a .com email address.'));
  }
 }

 /**
  * {@inheritdoc}
  */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  drupal_set_message($this->t('Your email address is @email', array('@email' => $form_state['values']['email'])));
 }
}

Can anyone help with a block of code that if the inputs are valid, when the user click download paper button, will be able to download? I got really stuck and i guess my point of view is not helpful to solve this problem.Thank you advanced.

you can do this with the $form_state->response($response)

  $response = new BinaryFileResponse($file->getFileUri();
  $form_state->setResponse($response);

You could add a redirect to your form, like:

$form['#redirect'][] = 'path/to/your/file.ext';

  In submitForm the form values are valid !

So validateForm has to set errors to prevent the submission of the form.


Changing the tite of your page to match the title of your tabs I have the following function:

function cvminterviews_menu() {

  $items = array();

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

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

  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_dateroomsetup_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

This outputs two tabs at the top of the page. However, when I click on each tab, it has the same page title as the parent menu item "Interview Schedule Overview".

Is there a way to set unique page titles for each tab?

You have to call

> 4.6 – 6   drupal_set_title($title = NULL)
> 7 – 8     drupal_set_title($title = NULL, $output = CHECK_PLAIN)

You'll have to change your code around a little

  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_dateroomsetup_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

to

  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => '_cvminterviews_admin_page',
    'page arguments' => array(
      'variables' => array(
        'form' => 'cvminterviews_dateroomsetup_form',
        'title' => t('my_title')
      )
    ),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

function _cvminterviews_admin_page($variables = NULL) {
  if(isset($variables['title'])) {
    drupal_set_title($variables['title']);
  }
  if(isset($variables['form'])) {
    return drupal_get_form($variables['form']);
  }
}

Then do the same thing for $items[admin/settings/cvminterviews'] & $items['admin/settings/cvminterviews/setup']

When you are changing your code, there is one more problem that you will need to aware of.

There will be 2 tabs on admin/settings/cvminterviews,  one that will be active 'Overview' and 'Interview Schedule Setup'.  'Overview' will link to admin/settings/cvminteviews NOT admin/settings/cvminterviews/overview.  admin/settings/cvminterviews/overview will never be called (unless you type that it into the address bar) because it is the default tab set by 'type' => MENU_DEFAULT_LOCAL_TASK.

I believe in general you tend to keep the same title when using local tasks - the tasks themselves are meant to be actions you can perform on some common object/area, so in that case it does kinda make sense to keep the same title whichever local task you're on.


Block cache not clearing on save? I have some custom block types that display in a region in my site. I have noticed that when changing the contents of these blocks, like an image, text, or title, that when you save and visit the page, the block data is cached and doesn't show the new changes. This is problematic because the client keeps reporting this as a bug, but I can't see where or why it won't update.

Is there a way to have it invalidate when saving a block so that a cache clear isn't necessary? I figured this would be normal behavior, but I have to clear it (while logged in as UID 1 even), and I don't think I am doing anything weird or have a contrib module installed that would interfere with this.

Edit: I am not using Panels or anything - this is core block.

The problem is, that the cache tag block_content:[id] does not bubble up and the tag is missing in the cache entry. Without this cache tag the cache entry can't be invalidated when saving a modified custom block.

Here are two workarounds:

Twig template (Workaround 1)

If you theme a block template and you render single fields

{{ content.field_field1 }}
{{ content.field_field2 }}

then you also need to render the rest of content:

{{ content|without('field_field1', 'field_field2') }}

That's because content contains the cache tag of the block content entity, which otherwise won't bubble up.

Preprocess (Workaround 2)

As an alternative option for rendering {{ content }} you can add the cache tag at the top of variables in preprocess.

mytheme.theme

function mytheme_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'block_content') {
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, $variables['content']['#block_content']);
  }
}

Then you no longer depend on the twig template to render all of content.

You'll find in Drupal\block\BlockViewBuilder::preRender() more workarounds for issues with bubbling up data from the content render array. You could use this code, which there is only applied in special circumstances, for all cache data from block content to bubble up to the top level:

use Drupal\Core\Cache\CacheableMetadata;

function mytheme_preprocess_block(&$variables) {
  $content = $variables['content'];
  CacheableMetadata::createFromRenderArray($variables)
          ->merge(CacheableMetadata::createFromRenderArray($content))
          ->applyTo($variables);
}

But I don't know which side effects that would have in other places. If it would be that easy the block view builder would do this already. So it's better to tackle only that specific problem with the one missing tag and use the first version of the preprocess function.

Setting cache max age to 0 saved my day.

function MODULE_NAME_preprocess_block(&$variables) {
    if ($variables['base_plugin_id'] == 'block_content') {
        $variables['#cache']['max-age'] = 0;
    }
}


How can I make the summary field required? Is there a way to make the summary field required by default in the node form?

It might be easier to create a new field for the summary and just manage it that way, you will then have to remove the summary option from the body field. Otherwise I think you will have to write some code and use hook_form_alter.

Go to admin/structure/types/manage/your_content_type_name/fields; there, you have the option to make this field required.


problem migrating my drupal site PDOException: SQLSTATE[42000] [1044] Access denied for user I have just loaded my drupal 7.32 site to JustHost from my pc (running xampp) copied the files across, and exported and imported the database to JustHost cpanel, i browse onto the website and I get the error message below. I have triple checked my database name and username of the database and password and they are correctly specified in my settings.php file. My database was called 'school2' on the pc, but I'm not sure that will affect anything.

I get this error message:-

PDOException: SQLSTATE[42000] [1044] Access denied for user 'caerleon_prim'@'localhost' to database 'caerleon_prim' in lock_may_be_available() (line 167 of /home4/caerleon/public_html/includes/lock.inc).

Can anyone help?

With JustHost you need to assign the user to the database from the Database Maintenance drop down page. Instructions are on their site too. I did this, and it fixed my problem.


How to make mail messages use the UTF8 character encoding? I am sending mails to users about products, using the SMTP Authentication Support and Mime Mail modules. I set UTF8 as charset in the mail header, but the header is changed from UTF8 to multipart on this line in the mail.inc file:

$message = $system->format($message);

It actually changes the Swedish characters to some strange characters. So that's the problem: I can't display them correctly.

Any suggestions to correctly display them?

Content-Type: multipart/alternative; means that there are parts that can have their own encoding set. If your mail sending modules decide they need multipart, mail should be formatted like that:

MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=boundary

--boundary
Content-Type: text/plain; charset=utf-8

This part uses UTF-8.
--boundary
Content-Type: text/plain; charset=iso-8859-1

This part uses ISO 8859-1.
--boundary--

code sample source here

If you called everything the way module docs tells you to, and UTF-8 data is not in the UTF-8 part, then you just found a bug in one of your modules.

Hi you can also create this functionality using custom hooks.

function add_newsletter() {
 $news_query = db_insert('news_letter')
        ->fields(array(
            'email_id' => $_POST['email'],
            'created' => REQUEST_TIME))
        ->execute();
if($news_query) {
    echo '1';
}else {
    echo '0';
}

$to = "abc_example@gmail.com";
$subject  = 'Mail coming from Subscribe';
$message  = "Hi, please check the below email coming from User Subscribers. User Email Id is : ".$_POST['email'];
$headers  = 'From: '.$_POST['email'] . "\r\n" .
            'MIME-Version: 1.0' . "\r\n" .
            'Content-type: text/html; charset=utf-8';
mail($to, $subject, $message, $headers);
if(mail($to, $subject, $message, $headers))
    echo "Email sent successfully";
else
    echo "Email sending failed";
}


Fetching only first row from database I work with:

$mandator = $this->database->select('Mandators', 'm')
     ->fields('m')
     ->condition('idMandators', $mandatorId)
     ->execute()
     ->fetchAll();

to retrieve my data from database. The result is an array with 1 array item. How can I retrieve always only 1 object, without the array? Like e.g. ->fetchOne?

$query = \Drupal::entityQuery('node')
            ->condition('status', 1)
            ->condition('type', 'my_content_type')
            ->condition('field_ref_au', $nid, '=')
            ->range(0,1)
            ->sort('created', 'DESC')
        ;

You can simply write (example get node) :)

$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n)->fetchObject();

If you want to get a single value you can use fetchField()

Example (get node title):

$node_title = db_query('SELECT title FROM {node} WHERE nid = :nid',
array(':nid' => $nid))->fetchField();


Does having too many cck fields negatively affect site speed and performance? I building a site that could potentially utilize 50 different content types. The most of the content types have more than 40 CCK fields, including multiple field_collections entity_reference.

How can i take care about performance of site Specially for CCK fields level ?

Yes. The more fields you have, the more load you should expect on your database server; that's a given.

What it means in real terms depends on your hardware, configuration and usage - you'll need to benchmark your site in that actual environment to come to any meaningful conclusion. If you get one request a day, for example, your pages are cached, and you have a brand new shiny server, then you probably won't need to think about changing anything.

If you get thousands of requests per second, all your pages are non-cacheable, and your server isn't great, then you might have to think about re-structuring that data so it's more performant (e.g. creating custom field types to combine data from multiple other field types into a single table).

In short, there's no general answer to what you're asking. You need to see what problems your application develops under load, if any, and deal with them then. Premature optimisation is rarely a good idea.

All of that said, Drupal's main defence against this kind of thing is caching. There's a great post here: How do you improve Drupal performance?

This is the sort of question that's almost impossible to answer without benchmarking on your actual hardware. Sure, the number of content types and CCK fields will affect performance, but if most of the activity is browsing by logged out visitors, the page content can be cached, so displaying the pages should put relatively little strain on your server. On the other hand, if they are highly dynamic pages constantly being updated my multiple users, you could find your server is quickly dragged to its knees.


What way should I use to load a file from a module? What way should I use to load a file from a module?

I am writing a module which is divided into 3 parts

Custom core will be in the module which contains basic functions required for project
Custom notification section will handle the notifications to show on site (It has a section on site where user can see all notifications.)
Custom mail will handle mail (Users will get email on each activity.)

So I have now a module file and 2 include files, but I am confused on how to include them in .module file.

There are 3 different methods available, but I am not sure which one is best and what the major differences between them are.

require_once drupal_get_path('module', 'custom_module')
files[] = mail.inc
module_load_include('inc', 'custom_module', 'mail.inc')

I tried them, and they all are working fine for now; I don't have much experience to guess future issues.

module_load_include() is a wrapper around require_once, with some sugar, so those are essentially equivalent. In the Drupal world, it would make sense to use the Drupal-specific function.

The files[] directive is for class autoloading - you don't use it to include files as such, just to make classes in those files available automatically when you need them.

You shouldn't use module_load_include() at the top of a module (or any other) file, it should be used only after Drupal has been bootstrapped. From the docs:

  Do not use this function in a global context since it requires Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file' instead.

The best way for drupal to know you have included files is having it in the files[] directive, as Clive says this is perfect for classes, but you can also use it for any files.

Using module_load_include() you can add some loading logic, you can load also files from another module, and for best performance you can load them from within a function or a conditional structure. That way is only loaded when you are using it.


Generating a random number without duplicates on blog comment A section of my site is a blog where I allow comments. Each comment has a thumbnail associated with it. If the commenter is a user, then their profile photo is used. If they are anonymous I have a pre-determined photo in place. I want to be able to randomly generate a thumbnail for these anonymous users, but also have no duplicates.

I asked this question here and now have a random thumbnail being generated, but the problem is that there are still duplicates. And it looks like because the comment.tpl.php file is being read on each comment that the random numbers are not being remembered.

How can Drupal remember the number so that it doesn't use it again?

My Code:

$numbers = range(0, 19);
shuffle($numbers);

print "
";
print "";
print "
";

Haven't tested this, but I think this should work. Remove your first two lines of code and place the following in your theme's template.php file (replace MYTHEME with the machine name of your theme):

function MYTHEME_preprocess_comment(&$vars){
    $max = 19;
    $numbers =  $_SESSION['MYTHEME_comment_numbers'] ?: range(0, $max);
    shuffle($numbers);
    $vars['number'] = array_pop($numbers);
    $_SESSION['MYTHEME_comment_numbers'] = count($numbers) ? $numbers : range(0, $max);
}

This makes available a $number variable inside your comment.tpl.php file.

Then, replace your last three lines inside comment.tpl.php with:

print "
";
print "";
print "
";

This will remove already used numbers from your $numbers array until there's none left, and then reset to use the full array again.


How do I get a block and its content commited to a Git repo? Let's say I have created a block with some Full HTML (Facebook Feed) text inside. How can I commit the block and its text content into my Git repository, so my co-workers can pull it?

Turn it into a Feature. Bad thing is, it does not work on built-in custom blocks, so you need to use Boxes to get it work.

That way, you can export block as a module, and modules are text files, so GIT accepts them with it's full support.

Then, there is Features to Git module. It claims:

  Features to Git allows trusted users to write features directly to disk, commit
  them to git and push them to a remote. This makes it possible for site
  builders to be able to manage features in git without having to get their hands
  dirty on the command line.

Create a module for that block using the Features module and then commit that module on to the GIT repository of yours.

For more information you could read the README.txt of feature module from.


Add captcha to last step of multi-step form I have a multi_step form which contains four steps. I want to add captcha to last step of the form.

use this code in your template.php, you need to know what the ID of the last form is,

<?php
function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
    if ($form_id == "YOUR_FORM_ID") {
            $form['my_captcha_element'] = array(
                '#type' => 'captcha',
                '#captcha_type' => 'Math',
            );
        }
}
?>

you can also replace the Math with image


Crossdomain.xml on a multisite setup I can't figure out where I need to place the crossdomain.xml (to let Flash communicate).

If I place it on the root of my Drupal installation, the cross-domain-policy is not working because the symlink redirects the user-agent to the multisite folder.

If I place the crossdomain.xml in the multisite folder, it doesn't work either.

What should I try?

I would make up a module with a hook_menu in it with a path of "crossdomain.xml".  In the menu callback, figure out your domain and serve up the proper file with the proper MIME type.  Install the module in "sites/all" and enable for each site that needs it.

I also suspect you could handle it in .htaccess with something like

RewriteCond %{HTTP_HOST} ^www\.host1\.com [NC]
RewriteRule crossdomain.xml crossdomain.host1.xml [L]
RewriteCond %{HTTP_HOST} ^www\.host2\.com [NC]
RewriteRule crossdomain.xml crossdomain.host2.xml [L]
RewriteCond %{HTTP_HOST} ^www\.host3\.com [NC]
RewriteRule crossdomain.xml crossdomain.host3.xml [L]

The docroot is the correct place for it to go. You should not have any symlinks either.


How do I update commerce product display nodes based on SKU (of the referenced product)? I would like to update the product display nodes with taxonomy terms based on the SKU of the referenced product of each node. Is that possible, programmatically?

I know the SKU.
I need to find the product by the SKU of a product display.
1.I update the taxonomy term of the product display accordingly.

I tried to use EntityFieldQuery without success.

If someone could possibly give me an idea on the best approach to do this in DrupalCommerce, or provide a link to the documentation I have missed, it is greatly appreciated. I have lost a day or two googling the wrong questions, apparently.

Although an old thread, for the benefit of others looking, this could be done easily using views_bulk_operations (VBO). No coding required.

Install VBO.
Create a View of product display nodes.
Add a relationship to commerce product.
Add a batch update operations field to the View.
Enable the "Modify entity fields" option in the VBO field settings.
Add an exposed filter for the product SKU
Save
Use the batch update operation to check and set the relevant taxonomy term reference field.

I believe you can do this just fine using feeds and commerce feeds. The sku is commonly used as the unique id.


Behavior for #datepicker onselect not working i have a datepicker in a webform. I want to be notified when a date is selected in the datepicker. In my form template i drupal_add_js a js starting with :

Drupal.behaviors.booking_form_tma = {
    attach: function (context, settings) {
        for (var id in Drupal.settings.date_popup) {
            alert('found');
            var datepicker_settings = Drupal.settings.date_popup[id].settings;
            datepicker_settings.onSelect = function(dataText) {
                alert('selected: ' + dataText);
            };
            $('#' + id).datepicker(datepicker_settings);
        }
    }
};

The behavior attach code gets called only once, after the page gets loaded and never reach the alert: i guess the datepicker is not present in the div at this time. When the datepicker icon is clicked, the datepicker gets injected in a div but the behavior is not called and so nothing happen. None of the alert in the code above are shown.

Why doesn't it work?

jQuery(document).ready(function() {
    jQuery(".datepicker").datepicker({
        showOn: "button",
        buttonImage: "/images/calander.png",
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        maxDate:'0',
        onSelect: function (selectedDateTime){
                //alert("here");
            }
    });
 });

you can also write above code in js file


How to define Meta tags on Views? Is there any module or some configuration that I can define the meta tags for the views page display in drupal 7 using Views 3.0?

The Metatag module has views integration from the box since 7.x-1.0-beta2.

Install the metatags_views submodule and you'll get metatag options in the views UI for any views page display (Paul Querol's comment below).

Most straight forward solution is to add the view as a block inside a node, and then use module like Metatag to place metatags on the node.

Avoids the views integration issue. Also provides benefit of breadcrumbs, menus, pathauto, etc. all easier to set up when page is a node rather than a view.


How can a module detect when the "access denied" page is output? How is it possible for a module to detect when Drupal is outputting the "access denied" page?
I know how to do it with Drupal 6; I need to know how to do it with Drupal 7.

You can set which pages are displayed when 403 & 404 errors occurs (admin/settings/error-reporting).

I guess you can add a new page in your hook_menu(), then set this page as the 403 error callback. When your custom menu callback is hit, you know you're outputting the "access denied" page!

You can use the Panels module for this.

  The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.


Custom Fonts in Drupal I use an Omega subtheme in my Drupal 7 site, and I'd like to change the default font to a custom font. How can I do this?

This question is over 6 months old.  The best solution now for adding custom fonts is to use the @fontyourface module.

Fontyourface module now supports google fonts so no need to add code manually.


"exceeded the maximum file size" error even when uploading small files This error in my Drupal 7 site happens when I try to upload an image through image_field field. This is the error:

  An unrecoverable error occurred. The uploaded file likely exceeded
  the maximum file size (64 MB) that this server supports.

Although I am trying to upload a small 5KB photo, this problem exists. I know this is kind of common problem, but can't understand why this happens for as small images as 5KB!

How I can fix this? At first I thought this issue may have been temporary and does appear to have resolved itself this morning but again it happens.

I found a workaround, as this is a tricky one to nail down.

Don't hit the "Upload" button at all.  Just hit the "Next" button directly.  If that works, you ran into the same problem I did.


on submission of form respective form should open in my form i have to show two radio button and one submit button, for example

candidate(radio)

organization(radio)

submit button.

my requirement is that

if user click/check on candidate and submit then candidate form should be open.

or

if user click/check on organization and submit then organization form should be open.

my code:

<?php
/**@file
*donation.module*/
/**
*Implements hook_menu()*/
function donation_menu(){
$items['donate'] = array(
'title' => 'Donate',
'page callback' => 'drupal_get_form',
'page arguments' => array('donation_donate_form'),
'access arguments' => array('access content'),
'access callback' => TRUE,
);
return $items;
}
/**
*Implements hook_form().
*/
function donation_donate_form($form, &$form_submit){
/*the options to display in our form radio buttons*/
$options = array
'candidate' => t('Candidate'),
'organization' => t('Organization'),
);
$form['officials'] = array(
'#title' => t('OFFICIALS'),
'#type' => 'radios',
'#options' => $options,
'#default_value' => $options['candidate'],
);
$form['name'] = array(
'#title' => t('NAME'),
'#type' => 'textfield',
);
$form['submit'] = array(
'#value' => t('PROCEED'),
'#type' => 'submit',
);
return $form;
}

I'd do something like

function donation_donate_form_submit($form, &$form_state) {
  switch ($form_state['values']['donate']) {
    case 'candidate':
      $form_state['redirect'] = 'donate/candidate';
      break;

    case 'organization':
      $form_state['redirect'] = 'donate/organization';
      break;
  }
}

and from this point I can do two things

Solution 1

Create other two menu items with different form for each

Solution 2

your original form would be called if you don't create any extra menu items (drupal falls back to the longest menu item that match the current URL), then change the existing form depending on the argument like this

function donation_donate_form($form, &$form_submit) {
  $form = array();
enter code here
  // No argument ? we must be in the selection phase.
  if (arg(1) == NULL) {
    $form['officials'] = array(
      '#title' => t('OFFICIALS'),
      '#type' => 'radios',
      '#options' => array(
        'candidate' => t('Candidate'),
        'organization' => t('Organization'),
      ),
      '#default_value' => 'candidate',
    );

    $form['name'] = array(
      '#title' => t('NAME'),
      '#type' => 'textfield',
    );

    $form['submit'] = array(
      '#value' => t('PROCEED'),
      '#type' => 'submit',
    );
  }
  elseif (arg(1) == 'organization') {
    // Candidate form stuff.
  }
  elseif (arg(1) == 'candidate') {
    // Organization form stuff.
  }
  return $form;
}

It depends on how you like your code, and what you are trying to do.

I'm not too clear on what you mean by "candidate form should open".  You did say after they press submit so can I assume you mean they go to the next page in some process?  OR do you mean you want some other dynamic content to load on the same page?

IF you simply want to change the action of the form based on which radio is selected then something like this would do the trick,

<form id="myform" name="myform" method="get" action="" onSubmit="return chooseAction(this, 'officials')">
Candidate:<input type="radio" name="officials" value="candidate">

Organization:<input type="radio" name="officials" value="organization">

<input type="submit" value="go">
</form>

i suppose this might not be what youre looking for if you're looking for how to lay all this out automatically somehow in drupal


How to write Custom Javascript in "drupal commerce" checkout page? In drupal 7, there is a common page in Templates folder i.e., "page.tpl.php". In this page if we write javascript, it works in all pages. Now I need to write custom javascript for "drupal commerce kickstart" checkout page. For Example, If I want to use onchange event function to "Full name" field. Even though If I just use "alert(document.getElementById('edit-customer-profile-billing-addressbook').value);", it is not working any where of the pages written. I tried javascript code in below pages.

profiles/commerce_kickstart/themes/commerce_kickstart_theme/template.php
profiles/commerce_kickstart/themes/commerce_kickstart_theme/templates/ {almost all pages}
profiles/commerce_kickstart/modules/contrib/commerce/modules/checkout/ {almost all related pages}

So please help.. where should I write Javascript code to work in checkout page. Thanks in advance.

As St0ik mentioned, you'll want to use drupal_add_js to add the JavaScript to the page. The real question is, where do you want it to go?

If you want it to show up on every checkout page, use the generic checkout form alter:

// Show on every page of checkout.
function MYMODULE_form_commerce_checkout_form_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

If you want it to only show up on certain pages within the checkout, you can use a more specific form alter to only add it to a certain page.

// Review before payment only.
function MYMODULE_form_commerce_checkout_form_review_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

or

// First page of checkout.
function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

You'll use MYMODULE_form_commerce_checkout_form_PAGE_alter where PAGE is the wanted checkout step.

Use this hook.

function hook_commerce_checkout_page_info_alter(&$checkout_pages){
  drupal_add_js('path to ur module',mycustom.js);
}


Views slideshow - 3 items per slide - how to center them? I've been trawling the web on and off for months searching for an answer to the following:

I'm using Views Slideshow to show a series of logos in rotation. I have set there to be 3 items per slide in the slideshow settings. What I would like is for the three logos to be centred - i.e. an equal amount of space to either side of the logos. At the moment, they float left and I cannot for the life of me find the right CSS to do this, or where to add it.

I would really appreciate it if someone from the community could take a glance at the logo slideshow at the following url:

http://eunic-global.aptalops.com/

Please note that's it's the rotating logo carousel at the bottom of the page I'm having trouble with, not the slider under the main menu.

Best wishes,
A~

#views_slideshow_cycle_teaser_section_eunic_members-block {
margin: 0 auto;
}


How to redirect user for specific pages not found I have developed a module that creates a certain set of pages. What I would like to do is create a specific redirect for those pages if they are not found while keeping the generic Drupal 7 wide redirect for all other pages. Is this possible and how would I go about doing it?

Thanks.

You can try by going on "admin/config/system/site-information"page. There you can give links where to redirect on the "Default 403 (access denied) page" and "Default 404 (not found) page". For example if you type "node", it will take you to front page.

I suggest to try the Redirect or rules module.

Update:

You can create URL redirects manually for each of these pages, but the Redirect module makes this much easier.

Go to "Configuration > Search and metadata > URL redirects > Fix 404 pages" (admin/config/search/redirect/404).

So, you can see that there are a few paths that I have tried to access that do not exist. Next, to each one there is an "Add redirect" operation.

Click "Add redirect"

When Clicking on "Add redirect" link we can specify where we would like users to be redirected when they reach the page that does not exist.

See more how to Fix 404 Pages Using redirect Module.


How to add Javascript in Drupal 7 with jQuery? I am trying to provide the option that users be able to put comment under each paragraph. So at the end of the article, I have something like this:

Comments for paragraph 1

  /* here I show the comment for paragraph 1 */

Comments for paragraph 2

  /* here I show the comment for paragraph 2 */

Comments for paragraph 3

  /* here I show the comment for paragraph 3 */

so  I have added the following to node.tpl.php:

    for($b=1;$b<$number;$b++)
   {
         echo "Commentsfor Paragraph $b:" ."
" . "
" ;

        foreach($cid_numbers as $no)
          {

             $e=($content['comments']['comments'][$no]['#comment']->paragraph_id);
             if($e==$b)
             print render($content['comments']['comments'][$no]);

           }
        }

and it works. But now I want to hide the comments and only when users clicks on a link like:  Comments for paragraph 1, then he be able to see the comments.

In order to do that I have added the following to node.tpl.php file:

and also changed the first code to this:

    for($b=1;$b<$number;$b++)
   {  ?>

<?php echo "Commentsfor Paragraph $b:" ."
" . "
" ; ?>

 <?php
   foreach($cid_numbers as $no)
    {

  $e=($content['comments']['comments'][$no]['#comment']->paragraph_id);
   if($e==$b)
    print render($content['comments']['comments'][$no]);

   }   ?>
 <?php

   }

This is the website that gave me the idea that how to do the hide/show: http://renaudjoubert.com/en/article/how-add-javascript-drupal-7-jquery?utm_source=twitterfeed

But the output looks like this:

comments for paragraph 1

 here it show comments for paragraph 3

comments for paragraph 4

and then when I click on the link "comments for paragraph 1" then  it displays the comments for paragraph 1 and also the link " comments for paragraph 2".
So what is my mistake? Have I put  tag in the right place? Or do you have any suggestion that how can I hide comments and show them when click on the link?

I may be wrong but I would remove your inner foreach and just use your $b variable instead of $no.

Alternatively here is another way to do it:

http://jqueryui.com/accordion/


How do I export my site structure? Since Drupal 8 is days away from release, I've started experimenting with rebuilding my personal site on it. The one feature I am really looking forward to is configuration management in code.

Unfortunately, my taxonomy terms are not exported by the config module. From what I've found googling on the subject, neither are menu items.

Which leaves me stumped. The natural way to set a sites structure (or information architecture) is a combination of content types, taxonomy vocabularies and their terms, and a set of menus. Or, at least, that seems to be the natural way to me.

While googling, I could not find any discussion on this subject.

So, how do I export the taxonomy terms and menu items that define my sites structure?

Edit to add some details:

Assume the site is a magazine. It has Fiction, World Events, Technical, and Letters sections. There will always be a /fiction, a /world-events, a /technical, and a /letters menu items. There are several kinds of content types, each can go into various sections.

So I create a vocabulary for the sections.

sections
- fiction
- world events
- technical
- letters

A taxonomy reference field is added to each content type.

Thus, when content is created it is tagged with the appropriate section terms.

If the site deploys without one of those sections, it is broken. Thus the menu items, and taxonomy terms should be considered configuration. Not content.

From what I've read, the main problem is that terms and menu items can collide if you try to move them between instances. Terms have a incrementing tid. Menu items also have an incrementing id. Though I do see the taxonomy_term_data and menu_link_content tables which seem to map uuid's with term and menu item ids. So, couldn't that be used to make exporting them feasible?

Also, isn't one of the main uses cases for taxonomies defining a site's structure?

I guess what I'm stuck on is that some menu items and some taxonomy terms really should be considered as configuration, not data. As in, if I were coding this instead of using Drupal, I'd hard code them. Thus, they should be exportable so that they can be committed to version control.

And that's why I'm asking "How do I export my site structure?"

For install content, you can use Default Content for D8 (also on GitHub). For ongoing content syncing Entity Pilot is expected to enter public beta this week and there is an active initiative around Deploy module.

Disclaimer: Entity Pilot is my project.

Managing configuration in Drupal 8 states:

  The Configuration Manager module in Drupal 8 provides a user interface
  for importing and exporting configuration changes between a Drupal
  installation in different environments, such as Development, Staging
  and Production, so you can make and verify your changes with a
  comfortable distance from your live environment.

  You can import, export, and synchronize configuration in your site via
  Manage > Configuration > Configuration Synchronization
  (admin/config/development/configuration).

Aparently it supports many types, including taxonomy and menus:


Views: group by content type in an arbitrary order Note: I spend a lot of time in this question explaining, what I've been trying to do, but the end goal is to be able to sort by content type in an arbitrary order.  I'm then grouping on content type, and getting headings in my results as desired.  If you can show me how to do it without hook_views_query_alter() I'd be just as happy, though why my solution isn't working is giving me an ulcer.  I'd prefer to avoid creating a whole bunch of attachments since I'm dealing with about 20 types here, but I think that is the next thing I'll have to try if nobody can help me.

A few other answers here, have gotten me to where I feel I'm close, but I'm getting not results, hopefully someone here can see what I'm doing wrong.

My actual setup is more complex than this.  Basically I have a variable in settings that gives me some details about the different content types I'm dealing with, including a weight value for each.  I'm building my order by clause using those weight values, but that doesn't seem to be the problem, so here is the query taken to it's simplest form:

Given a view that loads a set of nodes of at least two different types, one of which (for the purposes of this function has a machine name of 'brief' and a human readable name of Briefs):

/**
 * Implements hook_views_query_alter().
 */
function MYMODULE_views_query_alter(&$view, &$query) {

    if ($view->name == "view_name" && $view->current_display == "display_block_name") {

        $caseclause = 'CASE node_type WHEN "brief" THEN 1 ELSE 2 END';
        array_unshift($view->query->orderby, array(
            'field' => $caseclause,
            'direction' => 'ASC'));
    }
}

I would expect this to give me the node listing with Briefs listed first, and other types listed afterward.  Instead I get no results.  If I remove the alteration to $view->query->orderby I get results.  I've tried checking for "Briefs" instead of "brief".  I got the column name, by adding it as a sort in the view and seeing what the view itself used, but just in case I've also tried node.type and type as the column name to put in the case statement.  I tried doing all of this with the $query object too, just in case.

I tried adding the CASE clause as $query->addExpression, setting an alias of order_col for the expression, intending to then order by that column, but the whole page stopped showing up.  It is possible I did something wrong on that attempt, if you can make that work, please let  me know.

So here's what I need:  How can I make a CASE statement work in hook_views_query_alter(), or failing that, how can I sort content type by an arbitrary order?

Here's a really brief section of the configuration variable that I have in settings.php that I'm trying to get the weight value from to do my sort.

$conf['pubtype_bundles'] = array(
    'brief' => array(
        'name' => 'Briefs',
        'weight' => 5,
        'description' => 'Issue Briefs, Policy Briefs, and Briefing Notes',
        'help' => '',
        'types' => array(
            'issue' => 'Issue Brief',
            'policy' => 'Policy Brief',
            'briefing' => 'Briefing Note',
        ),
        'typehelp' => '',
    ),
    'book' => array(
        'name' => 'Books',
        'weight' => 10,
        'description' => '',
        'help' => '',
        'types' => array(
            'book' => 'Book',
        ),
        'typehelp' => '',
    ),
);

When you want to do arbitrary sort, U must be having your own sorting routine/algo/criteria?
When you have that then you can add a "global php" field in sort criteria and then u can use a setup code(if required) and then you can write your sorting logic in "sort code".

Though I am not very clear with this

  Basically I have a variable in settings that gives me some details
  about the different content types

What I understood is, you have a settings defined somewhere which has weight and content type relation. Based on this one solution can be:

Create a weight field / setting (assuming there is no configuration for it) in content types, and populate the weight from your settings.
Use this weight field to sort nodes in views.


Programmatically creating a custom block I followed the steps from https://www.webwash.net/programmatically-create-block-drupal-8/.
I have a view already created and I want to render this view in this block.
I can't find a good documentation for build() function.

The reason is that I want to hide the view for a role implicitly included by authenticated role.

How can I display the existing view inside the custom block I've created?

I didn't find a way to display the view and restrict for certain roles.

But I've managed to solve the problem in another way.

I created a script in Admin > Structure > Block > My_Block > Configure > Visibility PHP:

<?php
$match = TRUE;
$heh = \Drupal::currentUser()->getAccount()->getRoles(TRUE);
$hide_from_roles = array('administrator', 'sefii', 'membership');
 if (count(array_intersect($heh, $hide_from_roles)) > 0) {
    $match = FALSE;
}
return $match;
?>


More multiple add to cart buttons drupal commerce I want to be able to have multiple add to cart buttons on 1 page for example for selling music like this. Example!

It appears that you're looking for something that is decribed in detail in Multiple products per Add To Cart form (product kits/packages) also.
And that issue is what was the inspiration for the Commerce Product Bundle module (available for D7, but only as an alfa version for now). Here is a excerpt from its project page:

You can define products that consists of other products. They are all combined in one add to cart form. The form works like the core add to cart form with all the fancy selection and ajax magic. So the customers can make their selections as usual. The difference is, that the products from mulitple reference fields were presented on one add to cart form.
The bundle is then represented by one order line item. This allows the maximum compatibility with other modules such as shipping or payment modules.

Thinking of showing view of related products on product page with add to cart button may make it simpler if not killing specific use case.


Label for Child in Simple Hierarchical Select by using a module While using Simple Hierarchical Select Module, I have 2 levels of Hierarchy for my Phone. Is it possible to label for child by using a module ?

I guess this is possible by Client side hierarchical select.

Let me know if there is any other option.

Thanks.


How do I programmatically update the order status? After Payment is accepted, I need to update the order status to "Completed" from the page controller.

How do I do this, on Drupal 8?

I find no documentation about this; there is an example for Drupal 7.

// Updating Order status.
$orderObj = commerce_order_load($orderID);
commerce_order_status_update($orderObj, 'canceled', TRUE, 'Order Voided');
$orderObj->log = 'Order cancelled programatically';
commerce_order_save($orderObj);

You want to use the State Machine methods of the Commerce Order class.

It would be something like this, but it will depend on what you called your order states.

$order_state = $orderObj->getState();
$order_state_transitions = $order_state->getTransitions();
$order_state->applyTransition($order_state_transitions['complete']);

$orderObj->save();

If you aren't sure, you can always check the $order_state_transitions array to see what options you have.

You can simply use set method.

$order->set('state', 'completed');
$order->save();


hook_theme() to twig template of eform I have an eform printing out some fields. I want to create a module to change layout of the eform using hook_theme(). So, I have hook_theme() in my mymodule.module file and mymodule-form.html.twig file in template folder. Since I'm testing it, I only want to print out one field. But it prints out all of the field which seems like hook_theme() or twig is not working. Here's my code.

mymodule.module

<?php

/**
  * Implements hook_theme()
  */
function gq_theme($existing, $type, $theme, $path) {
 return array(
    'gq_form' => array(
      'variables' => array(
        'first_name_field' => $form['field_first_name'],
      ),
    ),
  );
}

/**
 * Prepares variables for the gq form template.
 *
 * Default template: gq-form.html.twig.
 */
function template_preprocess_gq_form(&$variables) {
  $variables['first_name_field'] = $form['field_first_name'];
}

mymodule.html.twig

{{ first_name_field }}

Also, I only have two files, mymodule.module, mymodule.info,yml, templates/mymodule-form.html.twig in module directory. Are there some necessary files?

Assuming that your template file is in a subfolder of your module folder (it looks like it's in templates), then your hook_theme needs to define the path. So it should look some thing like:

function gq_theme($existing, $type, $theme, $path) {
  return array(
    'gq_form' => array(
      'path' => $module_path . '/templates',
      'variables' => array(
        'first_name_field' => $form['field_first_name'],
      ),
    ),
  );
}

where $module_path is the path to your module.


Do a render foreach loop on a regular field? I have a regular field with multiple values,
If i do

render( $fields['field1'] )

It prints

Field1_value1
Field1_value2
Field1_value3
etc

Am trying to get it to output like this

[Field1_value1]
[Field1_value2]
[Field1_value3]
etc

To add [ and ] to the output.
I thought of using a foreach loop, but the field array is like such

'#title' => 'xxxx',
'#type' => 'xxxx',
...
'0' => <array>,
'1' => <array>,
'2' => <array>,

How can I get it to loop throught the [0], [1], [2] etc only?

Note: I have no control on how many multiple values the field may have, so I have to loop.

Another solution that worked well for me: Display comma-separated list of taxonomy terms?

You can make use of the power of field.tpl.php.

$field_values = element_children($fields['field1']);
foreach($field_values as $field_value) { ... }

I was looking for the answer to this too, and ended up hunting through the render() function. It wasn't too far down the chain: drupal_render() calls element_children().

  element_children

  Identifies the children of an element array, optionally sorted by weight.

  The children of a element array are those key/value pairs whose key does not start with a '#'. See drupal_render() for details.

Why don't you try a regular expression loop after the print? See here.

If you're really experiencing problems with the loop, check out the documentation for preg_replace_callback().


How to place custom module template file in theme folder I am using Drupal 6, and I have created a custom module which is in the  "sites\all\modules\custom" folder; in the same folder there is also the custom.tpl.php file.

I want to place the custom.tpl.php file in the theme folder.

Here is my code:

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

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

  return $items;
}

function custom_page() {
  $result = db_query('SELECT * from node');
  return theme('custom', array('output' => $result));
}

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

function template_preprocess_custom(&$variables) {}

Well you can place in the theme folder or you can leave it in the module. Drupal will look in both places. So if your implementation of hook_theme is a template, Drupal will look for the following files:

themes/bluemarine/custom.tpl.php
modules/custom/custom.tpl.php

If you read the documentation for hook_theme you'll get your answer for the question when you get to the path key:

  path: [...] Ordinarily the module or theme path will be used [...]

Please give path key in theme registry.

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


How to modify the fields of user registration form and user login form? I have user registration and user login form on same page and want to customize the field of both the forms?

Use hook_form_alter() or hook_form_FORM_ID_alter to update anything in the forms:
Example of updating the user login form using hook_form_alter():

function My_Module_form_alter(&$form, &$form_state, $form_id) {
  // Modify the user login form. ('replace the "-" with "_" in form id')
  if ($form_id === 'user_login_block') {
    // Modifying the label and the size of input of username and password.
    $form['name']['#title'] = 'User Name';
    $form['name']['#size'] = '20';
    $form['pass']['#title'] = 'Password';
    $form['pass']['#size'] = '20';

    // Adding extra class to the form.
    $form['#attributes']['class'][] = 'custom-class-name';

    // Adding additional validator to the form for some custom validations.
    $form['#validate'][] = 'My_Module_custom_form_validation';
  }
}


How do I add a media image field? I have installed these modules:

Media Entity
Media Entity Image
Entity Browser

When I try to add an image field, I have no widget for Media like there was in Drupal 7.
I also tried to add a reference to a media, but it doesn't seem to work.

What am I doing wrong?

What you got can do what you want, but it requires configuration and without a UI it's quite hard.

You might want to try adding the file browser module, which uses Dropszonejs to create a nice file browser widget. I have tested it out and it seemed to work just fine, but it wasn't quite mature enough for what we wanted to do at the time.

You have to add new references field (other) and select media. Now you can select media or create per Entity browser :)


How can you remove another modules events? So, I have an event subscriber for Drupal commerce that listens for "commerce_order.place.post_transition" and will send a bespoke order email (due to not being able to change some of the things like subject title in the commerce module).

Commerce also has an event subscriber listening to "commerce_order.place.post_transition" which will send an order receipt email. I need to unsubscribe this event to prevent sending duplicate emails but searching through google and comments sections of articles has lead me to a dead end.

Any ideas?

Remove the event subcriber service from the container:

my_module/src/MyModuleServiceProvider.php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Remove the foo event subscriber.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $container->removeDefinition('foo_event_subscriber');
  }

}

You find the service name in the MODULE.services.yml file of the other module.

More info https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services

and welcome to Drupal Answers.

Assuming you're using Drupal 8, you may try the below code to hide the email fieldset:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    if ($form_id == "commerce_order_type_edit_form") {
        $form["emails"] = [
            "#checked" => FALSE,
        ];
    }
}

Hope that helps.


Change name to menu link dinamically I have a menu:

Parent-1
 - Child-1-1
 - Child-1-2
 - Child-1-3
 - another_child
Parent-2
 - Child-2-1
 - Child-2-2
 - another_child

I needed change the name of Parent-2 item (Parent-2 text is unique), I did it with hook_link_alter() hook:

/**
 * Implements hook_link_alter().
 */
function MY_MODULE_link_alter(&$variables) {
  if ($variables['text'] == 'Parent-2') {
     $variables['text'] = t('New name');
  }
}

I need too to change the names of all child of Parent-2 dynamically. I can't do it with hook_link_alter() hook because in my example there is two elements(another_child) with the same name. Those changes must not be saved in database.

How can I do this?

I can do it implementing hook_preprocess_HOOK hook, specifically hook_preprocess_superfish:

/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_NAME_preprocess_superfish(&$variables) {
  if ($variables['id'] == 'superfish-main-menu') {
    $menu = ($variables['element']['#tree']);
    // ...
  }
}


How can I add Taxonomy Term to a Node's Breadcrumb? The Node has attached a single Term.

Current breadcrumbs rendered

[HOME] >> [NODE_TITLE]

Want to render like this.

[HOME] >> [TERM] >> [NODE_TITLE]

Themers who don't want to use a custom module to implement a BreadcrumbBuilder can change the breadcrumbs in a preprocess hook.

Example how you can add a link before the last link:

function mytheme_preprocess_breadcrumb(&$variables) {
  $breadcrumb = &$variables['breadcrumb'];
  $lastlink = array_pop($breadcrumb);
  array_push($breadcrumb, [
    'text' => 'New Link',
    'url' => '/newlink',
  ]);
  array_push($breadcrumb, $lastlink);
}

If you add a taxonomoy term from a node you would have to add both as cache tags and a cache context on the url to make this work.

Taking a quick peek in contrib modules, as of this writting, there doesn't seem anything that you can use for D8.

Here is a creative quick and easy solution/suggestion:

With Views and bit of Rewrite Results/Template file + CSS you could create your own breadcrumbs view block.


Load external php library in custom module I’ve read a lot of topic on this but i can’t figure why it is not working for me.

I’ve built a custom module. It is working fine since return $output; in my controller class is working : I can see in front-end a page with my custom html.

I’ve written a script outside Drupal in order to test. Basically, i connect to a webervice and retrieve all the datas. It’s working fine.

Now, i want to execute that script inside the controller class.

I need to load an external php library to instantiate an object.

In my test php file (outside Drupal) a simple require_once is working.

require_once('nusoap.php');

But it is not working in my controller class.

So, i’ve activated the library module and do :

$path = libraries_get_path('nusoap') . DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php';

require($path);

It’s still not working.

Error message indiquactes :

  Error: Class 'Drupal\webservices_dc\nusoap_client' not found

I’m sur the file path is correct because if i do this, i can see the content of the file.

echo file_get_contents(DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php');
die();

I’ve also tried this :

in nusoap.php (where there is the class i need to include),

namespace Drupal\webservices_dc;

and in module controller class :

use Drupal\webservices_dc\nusoap_client;

But it is still not working.

Finally, i’ve copied the content of the external php library inside the module controller and it is working.

So i’m nearly sure the issue is related to the loading of that external library.

What is the correct way to load external php library (and wait it is fully loaded) in order to use it in a custom module ?

You cannot require classes with require or library hooks. Nor should you be editing external packages.

You are supposed to require external php packages with Composer. Composer will update the autoloader. Then in your class, you can say:

use ExternalPackage\namespace\Foo;

In the header and Foo class is then usable. Furthermore, you can inject it to the constructor with a little more work.

I would advise using SoapClient instead of nusoap as that is very old.

Regarding SoapClient, here is something I solved recently injecting it proper to my class, because that's the same road you're heading down.

Dependency inject a class with values from a config object?

You can use this inside controller to load the library

$example = array(
  '#attached' => array(
    'library' => array(
      'module/file',
    ),
  ),
);


Setting the mime-type for files stored in the private directory How do I set the mime-type of files being served from the drupal private directory. I have a webm file in the private directory, and the I've added the <video> tag to the page using a tpl file.

I've tried adding

AddType video/webm .webm

to .htaccess. I've also tried installing the module "File Mime" to try to set the right mime type. I've tried adding

function mymodule_file_download($uri){
    return array('Content-type: '.'video/webm');
}

to my .module file. Nothing seems to work. Any help would be appreciated.

Editing includes/files.mimetypes.inc is a core hack, which you should strive to avoid.

Instead, use hook_file_mimetype_mapping_alter():

function mymodule_file_mimetype_mapping_alter(&$mapping) {
  // Add new MIME type 'video/webm'.
  $mapping['mimetypes']['webm'] = 'video/webm';
  // Add new extension '.webm' and map it to the 'video/webm' MIME type.
  $mapping['extensions']['webm'] = 'webm';
}

Figured this out myself: I had to add the webm mimetype in the appropriate places in the includes/files.mimetypes.inc file to get drupal to serve private files with the correct mimetype.


How can I find the form ID of a form? How do I get the form id of my form? I've just begun to make my modules and I'm at a standstill. I got this code from someone else and am trying to customize it:

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form id for the node form') {
    $form['#submit'][] = 'my_custom_submit_handler';
  }
}

Finding FORM ID without installing module

Finding the Form ID is very easy no need to install modules and all

STEP 1: Open you from go to its edit page(OR inspect your form).

STEP 2: if its a node form find "node-form" in the inspect element

 check you are in the form element.

STEP 3: see attached image the highlighted green text is the ID of the form

STEP 4: IMPORTANT Finally if you want to use it in hook_form_alter() replace the hypen with underscore

For example: yourform_id_with_content_type_name_form

Like wise you can find id of any form in drupal all you have to do is inspect->find form element and search for the ID attribute and use it

Hope it helps :)

In Drupal 8 you can get a form id like this.
You have to write this code in your .module file
function modulename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

echo "my form id is : ".$form_id;
}


Clearing cache failed to add the new CSS properties For Drupal 7, I'm using

Cache pages for anonymous users
Compress cached pages.
Aggregate and compress CSS files.
Aggregate JavaScript files.

The problem is when I update the CSS code for one of my CSS file, the code doesn't show in my page.

I have tried to Clear all cache and even run cron, but the new CSS code doesn't get added to the cached and minified version of my CSS.

The only workaround is just to disable "Aggregate and compress CSS files."

Any thought on this will be helpful.

Your Drupal is not able to write inside DRUPAL_ROOT/sites/*/files/css directory. That's why aggregated CSS files are not renewed. Consult your sysadmin to correct permissions and allow Drupal full write access inside DRUPAL_ROOT/sites/*/files and all subdirectories, that should solve it.

Try the AdvAgg module. Go to the status page and check to see if AdvAgg complains about anything.


Remove menu item in template.php drupal 7 After quite a bit of googling I'm asking here which theme_* function I use to remove a menu item.

I already use theme_menu_link to alter 2 of the menu items in this menu but I want this one to dissapear completely.

Wasn't there a field I could add to the array that would hide it or am I thinking of something else?

I think you're looking for:

$element['hidden'] = 1;

Using:
http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7

check that it's the element you want, and set the "hidden" value to 1.   I have not tested this.


Sending yourself a copy of the email I m using Drupal 7 with the Webform module to send email. On a form I have checkbox to send yourself an email copy. When it is checked, there will be a field to enter the email of who sends the email. The email should be send to this address also.

I created a custom module for this functionality. This module file used for creating a send a copy of message to me functionality

function sendmail_webform_form_alter(&$form, &$form_state, $form_id) {
     error_reporting(E_ALL);
     ini_set('display_errors', 1);
     // webform_client_form_52  webform id
     if($form_id == 'webform_client_form_52') {
         $form['submitted']['send_a_mail_yourself'] = array(
         '#type' => checkbox,
         '#form_key' => 'send_a_mail_yourself',
         '#title'=> 'Send a copy of yourself',
         '#weight' => 4, // As your needed
         '#field_prefix' => '
',
         '#field_suffix' => '
',
         '#default_value' => array('yes' => t('send a copy of yourself')),
       );
       $form['#submit'][] = '_sendmail_webform_submit';

       }
     }

   function _sendmail_webform_submit($form, &$form_state) {
     $param = array();
     foreach($form_state['input']['submitted'] as $key => $values) {
        if(valid_email_address($values)) {
             $to = $values; //to email address
        }
        else if($key == 'send_a_mail_yourself' && $values == 1) {
              $send_a_mail = $values;  // Check send a mail to yourself checkbox

        } else {
          if($values) {
               $param[]  = $values;  // All remaining values to store to param array for use of email body
          }
        }
       }

          if($send_a_mail == 1) {
         $from = 'noreply@example.com';
                 foreach($param as $param_values) {
            $body[] = $param_values;
           }

        $to = $to; // Set this email address - emails will be sent to this email address!
        $params = array(
            'body' => $body,
            'subject' => 'Website Information Request',
     );
        if (drupal_mail('sendmail_webform', 'some_mail_key', $to, language_default(), $params, $from, TRUE)) {
            drupal_set_message('Thanks, we will be in contact with more information soon.');
     } else {
            drupal_set_message('There was an error subscribing you. Please try again later');
        }

    }
  }

 function sendmail_webform_mail($key, &$message, $params) {
     $headers = array(
         'MIME-Version' => '1.0',
         'Content-Type' => 'text/html; charset=UTF-8;',
         'Content-Transfer-Encoding' => '8Bit',
         'X-Mailer' => 'Drupal'
    );
    foreach ($headers as $key => $value) {
         $message['headers'][$key] = $value;
    }
      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];
 }

There are two types -  Custom and Component, if You select custom you can write your own like: test@gmail.com. For Component - the submitted form field value will send email. For your requirement simply add another email custom : admin@example.com


Is there any way to change home page on small screen? I want to change the home page for small screen. Is there any way to set the front page according to the screen size by using hook_preprocess_page() or any other?

To actually answer your question (Is there any way to set the front page according to the screen size). No. Especially as you mentioned that you don't want to use JavaScript in a comment to Inizio.

The server by itself has NO idea of the screen size of the client, so the only way to get that info back would be using JavaScript (either implementing drupal.settings or some kind of custom AJAX callback). Any module that you use would alos have to utilise JavaScript.

If you want to change the frontpage based on DEVICE, then that's more realistic, with something like Mobile Detect, Browscap, WURFL (or something similar) but again - not foolproof.

I used Mobile_Detect API and redirect the page using hook_preprocess_page in template.php.


How to create language object from language string (e.g. 'en')? As in question, ofcourse I am asking about Drupal function for this job.

So I need function that get language string as param (e.g 'en','pl' etc) and returns me standard Drupal language object. Similar to global $language.

Use language_list() function:

<?php

function get_langugage_object($language) {
  $installed_languages = language_list();
  return $installed_languages[$language];
}

?>

I would use the following code; with mymodule_get_language_obj($name, FALSE) you get a language object only if it has been enabled.

function mymodule_get_language_obj($name, $all = TRUE) {
  if ($all) {
    $languages = language_list();
  }
  else {
    $languages = language_list('enabled');
    $languages = $languages[1];
  }

  return isset($languages[$name]) ? $languages[$name] : NULL;
}

Notice that on Drupal 7.43 (and possibly, on previous Drupal 7 versions), language_list() returns an array of objects, contrary to what reported in a comment posted in the documentation page.

  When calling:

<?php
  $languages = language_list('enabled');
?>

  You can expect the return value to be:

<?php
$languages = array(
    '1' =>
        array(
            'en' => array('language'=>'en', 'name'=>'English', ... ),
            'fr' => array('language'=> 'fr', 'name' => 'Francais', ... ),
        )
    );
?>

  The index being 1 because it's the value of the 'enabled' column.

With Drupal 7.43, I obtained the following:

Locale module not installed

Output of print_r(language_list('enabled'));

    Array(
      [1] => Array(
        [en] => stdClass Object(
          [language] => en
          [name] => English
          [native] => English
          [direction] => 0
          [enabled] => 1
          [plurals] => 0
          [formula] =>
          [domain] =>
          [prefix] =>
          [weight] => 0
          [javascript] =>
        )
      )
    )

Output of print_r(language_list());

    Array(
      [en] => stdClass Object(
        [language] => en
        [name] => English
        [native] => English
        [direction] => 0
        [enabled] => 1
        [plurals] => 0
        [formula] =>
        [domain] =>
        [prefix] =>
        [weight] => 0
        [javascript] =>
      )
    )

Locale module installed, and Esperanto enabled as additional language

Output of print_r(language_list('enabled'));

    Array(
      [1] => Array(
        [en] => stdClass Object(
          [language] => en
          [name] => English
          [native] => English
          [direction] => 0
          [enabled] => 1
          [plurals] => 0
          [formula] =>
          [domain] =>
          [prefix] =>
          [weight] => 0
          [javascript] =>
        )
        [eo] => stdClass Object(
          [language] => eo
          [name] => Esperanto
          [native] => Esperanto
          [direction] => 0
          [enabled] => 1
          [plurals] => 0
          [formula] =>
          [domain] =>
          [prefix] => eo
          [weight] => 0
          [javascript] =>
        )
      )
    )

Output of print_r(language_list());

    Array(
      [en] => stdClass Object(
        [language] => en
        [name] => English
        [native] => English
        [direction] => 0
        [enabled] => 1
        [plurals] => 0
        [formula] =>
        [domain] =>
        [prefix] =>
        [weight] => 0
        [javascript] =>
      )
      [eo] => stdClass Object(
        [language] => eo
        [name] => Esperanto
        [native] => Esperanto
        [direction] => 0
        [enabled] => 1
        [plurals] => 0
        [formula] =>
        [domain] =>
        [prefix] => eo
        [weight] => 0
        [javascript] =>
      )
    )

The equivalent code for Drupal 8 would be the following one.

function mymodule_get_language_obj($name) {
  $languages = \Drupal::languageManager()->getLanguages();

  return isset($languages[$name]) ? $languages[$name] : NULL;
}

Note that Drupal 8 version of the code returns instances of the Locale class, not the stdClass class.


Adding new menu items to hook_menu I am building a module which already has the function Mymodule_menu() at the beginning of the code. I was wondering if it is possible to use hook_menu_alter() to add new menu items (i.e. building new pages) somewhere down the code.

What I'm trying to do is build a form module whereas when the user presses "Submit", the code inside the form_submit() function will build a new page using the form values the user entered, and then redirects the user to that page.

Is that even possible. Appreciate the help from anyone. Thank you all in advance!

No, hook_menu_alter() is not thought to dynamically add new routes. As any similar alter hook, it is thought to alter the routes defined from other modules.
It would not work for dynamically adding new routes for the simply fact that, similarly to hook_menu() is only invoked in specific cases, for example, when a module is installed, uninstalled, enabled, or disabled.

If you need to have dynamic pages, you need to do what Drupal does for nodes: You define a route with wildcards, which is similar to the node/%node route defined for nodes.
hook_menu() has some example for this kind of routes, under Wildcards in Paths.

For example, a route definition as the following could be used to serve a page like my-module/1, my-module-2, etc. mymodule_abc() would recive the wildcard value as argument, and it could use that argument to access data from a database table, which is essentially what Drupal does when a user visits node/1: It loads the node whose ID is equal to 1 from the node table, and it shows it to the user who requested that page.

  $items['my-module/%'] = array(
    'page callback' => 'mymodule_abc',
    'page arguments' => array(1),
  );

As side note, as said in Auto-Loader Wildcards, instead of my-module/%, you could use my-module/%mymodule_abc, and mymodule_abc_load() will be called every time a page like my-module/1 is accessed, getting the wildcard value (1) as argument; it could then return the object saved in the database from the form submission handler.
See node_load() as example. That function returns the object saved in the database from the form submission handler of the node edit form.

Auto-Loader wildcards are helpful when there are more routes that your module defines. For example, the Node module uses them because the routes it defines using wildcards are node/%node, node/%node/edit, and node/%node/delete. Instead of putting the code to load the node in 3 different page callbacks, it puts the code in a single function (node_load()) automatically called from Drupal.

I also found the thread "Sending results of form to new page" which was talking about exactly what I need.


Why are default values in a checkboxes $form not displayed? I'm having a drupal form (7.x) of type checkboxes.

I have an array of values for my checkboxes.

$options = array(
    'uid'         => 'UID',
    'name'        => 'Name',
    'mail'        => 'E-mail',
    'created'     => 'Created',
    'edit_node'   => 'Edit',
    'cancel_node' => 'Cancel',
);

I have an array of default selected values.

$defaults = array(
    'uid'         => 'UID',
    'name'        => 'Name',
);

And now I try to make the default values selected by default, like this:

$form['dynamic_user_fields'] = array(
    '#type' => 'checkboxes',
    '#title' => t("Dynamic User Fields"),
    '#options' => $options,
    '#default_value' => $defaults,
    '#description' => t("Select the fields to display in the view."),
);

But this is not working, all checkboxes are unchecked by default. Where is my mistake?

What is not working so far: I've seen this related question but the answers do not work.

What I've tried:

(1) using numeric keys does not work.

'#default_value' => array(1, 2),

(2) using array keys does not work.

'#default_value' => array('uid', 'name'),

(3) using array structure does not work.

'#default_value' => array('uid' => 'UID', 'name' => 'Name')

Any ideas?

References

This is the full code I'm Using: views_handler_filter_dynamic_fields.inc#l317
This is a demo site: drupal-7/dynamic-user-fields
Related issue: #1245838 Default fields should be checked initially

I stepped up to maintain this module but the code base is a migrated D6 module.

For form elements expecting multi-value defaults, Drupal expects an array where keys and values are equal to the keys in your options array. Something like the following should work:

$defaults = array(
    'uid' => 'uid',
    'name' => 'name',
);

You may also use $defaults = drupal_map_assoc(array('uid', 'name'));.


How to allow reload value in cck field? I have a problem.
I wish I achieve for my preloading fields Content Type (Type list). (pre loader like a webform).
Loading this list thereby synchronize on a table by the user.

I get to create my field and load the first time. But when you synchronize the table, it is necessary that the field starts to date.

How to allow reload value in cck field?

Thank

I find.

In my instance, I use :

 'allowed_values' => array(),
 'allowed_values_function' => '_get_list_catalogue',


How to enable inactive fields I have a content type with a field that has been set to inactive. This happened after I reverted my feature in an attempt to undo a change I made to the content type.

The error message given is the following:

  This content type has inactive fields. Inactive fields are not included in lists of available fields until their modules are enabled.

I've disabled and re-enabled the feature module, but the field is still inactive.

How can I activate my field?

I've had this quite a few times, I'm not sure what the initial problem is but I've solved it by doing either one of the following:

Disabling the feature and re-enabling it
If above fails disable delete content type then re-enable (not an option if there existing content on the site)
Manually editing the content_field_instance table (D6) and enabling it there.

Check the content_field_instance_delete() function.


ajax form submit multiple times I have a form which consists of one submit button (Add to cart). I made it submit via AJAX but the problem is that when I press the button the second or third (and so on) times, the submit handler doesn't execute. I think this happens because the form_build_id and form_token fields should be rebuilt.

Do you have any idea on how I can achieve this functionality?

This is the code I am using.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['submit']['#ajax'] = array(
      'callback' => 'mymodule_ajax_form_callback',
      'wrapper' => 'my_form_wrapper',
    );

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';
  }
}

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

As reported on drupalcommerce.org, the trick is to clear the form and form state caches in your AJAX callback.

The following is a working code example taken from that post:

function ajax_cart_form_alter(&$form, &$form_state, $form_id) {
  // Add ajax property to Add to Cart button
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['submit'] = array(
      '#value' => t('Add to Cart'),
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => 'ajax_cart_form',
        'wrapper' => 'block-commerce-cart-cart',
        'effect' => 'fade',
        'progress' => array('type' => 'throbber', 'message' => ''),
      ),
    );
  }
}

function ajax_cart_form($form, &$form_state){
  global $user;
  $order_id = commerce_cart_order_id($user->uid);
  $cart =  commerce_embed_view('commerce_cart_block', 'default', array($order_id));
  $commands = array();

  // The next line allows different quantities
  // to be submitted each time
  unset($form['quantity']['#value']);

  // Clear form and form state cache
  $form_state = form_state_defaults();
  $form_build_id = $_POST['form_build_id'];
  form_set_cache($form_build_id, $form, $form_state);

  $commands[] = ajax_command_replace('#block-commerce-cart-cart .view-commerce-cart-block', $cart);
  $commands[] = ajax_command_replace('#block-commerce-cart-cart .cart-empty-block', $cart);
  return array('#type' => 'ajax', '#commands' => $commands);
}

I would suggest using AHAH. It resubmits the entire form when adding the new element so you don't run into the problem you describe above.


"Your command line PHP installation is too old" But it's not? I was trying to install Drush version 7.x-5.9 when it gave me the following error (whenever I try to use the drush command):

Your command line PHP installation is too old. Drush requires at     [error]
least PHP 5.3.0. To suppress this check, set the environment variable
DRUSH_NO_MIN_PHP=1

My HostMonster Info:
Apache version  2.2.26
PHP version 5.4.24
MySQL version   5.5.35-log

I've reverted back to version 7.x-5.4 of Drush and the command line is working but I would like to use the newest version if possible.

The command line version of php (CLI) and the one used by your webserver (reported by hostmonster info) are not necessarily the same. Run php -v in a terminal to see which php command line version is installed.

If you have this problem with connecting to Acquia, it's worth noting that the acquia ssh path given from their console:

ssh user@srv-3923.devcloud.hosting.acquia.com

uses a different user than the remote-user provided by the Acquia drush alias file:

$aliases['dev'] = array(
  'root' => '/var/www/html/site.dev/docroot',
  'ac-site' => 'user',
  'ac-env' => 'dev',
  'ac-realm' => 'devcloud',
  'uri' => 'userdev.devcloud.acquia-sites.com',
  'remote-host' => 'srv-3923.devcloud.hosting.acquia.com',
  'remote-user' => 'user.dev',
  'path-aliases' => array(
    '%drush-script' => 'drush' . $drush_major_version,
  )
);

, which in our case had a different version of command-line php (3.1 vs 2.9). You can verify that this is your problem by doing a drush ssh.

To fix, we had to change the remote-user in the drush file by removing the environment extension.

  'remote-user' => 'user.dev',

to

  'remote-user' => 'user',

I do not know if there is any reason to keep the environment-specific user, but this was enough for us to pull the database through.


Redirect incoming traffic to homepage How can I set Drupal 7 so that all incoming traffic is redirected to the homepage? I need to ensure all visitors go to the homepage, even if they click a link on some other site that links to example.com/section/node-1

You could do this easier in your .htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_URI} !/$
RewriteRule $ / [R=302,L]

Put this at the bottom of your .htaccess file and you're set.

Here are rewrite conditions to redirect all incoming traffic (from another domain) to the homepage. Put this in the .htaccess file.

Don't forget to update the URL with your correct website domain.

RewriteCond %{HTTP_REFERER} .
RewriteCond %{HTTP_REFERER} !^http://([^.]+\.)*yourdomain\.com
RewriteRule / http://www.yourdomain.com [R=301,L]


How to have a three column in node page I want to have a three column in node page, my page width is 940px, and one column is 300px + 20px right margin, so 3 column is 960px, but the main width is 940px, I want to 3 column in one row,  how to do that? how to modify node.tpl.php?

I don't understand why this isn't a simple case of changing your CSS? You're adding 20px to 940px so that equals 960px. You must either use CSS3 (box-sizing: border-box;) or minus your extra 20px from 940px...which would be 920px. Standard box model stuff but maybe I'm missing something in your requirements.

You could change/overwrite the right margin to 13 pixels, for example.


Ajax Link In A FAPI tableselect Row I'm trying to add an ajax link to my tableselect rows and replace part of this form with ajax.

$options = array();
foreach ($result as $camp) {
    $options[$camp->uuid] = array(
        'select_link' => array('data' => array(
            '#type' => 'link',
            '#name' => 'select_link',
            '#title' => t('use'),
            '#href' => 'ajax_use_data_callback/nojs/',
            '#attributes' => array(
                'class'=>array(0=>'use-ajax')
            ),
            '#ajax' => array(
                'wrapper' => 'selected-data-div',
                'method' => 'replace',
            ),
        )),

        ...

    );
}

This triggers an alert with a 404 error and the site's default html. How do I tell this ajax link to be handled like a regular ajax form element?

This can be solved by building a 'select' element with an option for each row id in the tableselect that gets an ajax link. Then we can add links to the tableselect row with '#markup' and use Drupal.behaviors to attach a function that sets the value of the select element and triggers its 'change' event. In the form building function, if $form_state['triggering_element']['#name'] is the new select element, $form_state['triggering_element']['#value'] is the one we want to process.

The select element could then be hidden and the in-row ajax links are still fairly clean. Of course this won't work if javascript is off.

you must declare hook_menu() for ajax_use_data_callback/nojs/ path


Export blocks with features extra I installed the Features extra module to export custom made blocks in my Drupal 7 environment. But for some reason, it doesn't work...

What I do is the following:

I create a custom block
I give it a machine name, description, title and body, just like it's required.
I go to Structure - features - Create feature
I create my feature by clicking the custom block under FE Block
The fe_block dependencies fills in automatically.
I download the feature and place it in /sites/all/modules/features
In my install profile I add this line: dependencies[] = custom_blocks
I try to reinstall the website and... nothing!

The blocks aren't showing up in my Block-page, but the feature is... What am I doing wrong in this process? Do I need to enable something or install an extra module in order to get my custom blocks exported?

Alternative:

Use the Panels module to get the ability to create "Mini-panels" which function as equivalents to the standard Drupal block.

I believe there is much better support for exporting mini-panels into Features, since exportability was a key design component for the Panels module.

Personally, I've been successful using Panels, mini-panels, and Features.

I think that you need to enable your features.
Use drush, it's an interesting tools for drupal

  drush en your_feature_name.