Convert imported strings into array I have imported a .pot file using the _locale_import_read_po function, like this:

$po_files = file_scan_directory('/', '/.*\.pot$/');
if (count($po_files)) {
  require_once DRUPAL_ROOT . '/includes/locale.inc';
  $po_file = reset($po_files);
  $translations = _locale_import_read_po('db-store', $po_file);
}

Now, what I want is to convert all the imported strings into a PHP array.

Is there any way to do that, and how?

Passing 'db-store' as first argument of _locale_import_read_po() will cause the content of the translation file to be imported in the database. To import it in memory, it's necessary to use the following code.

(As usual, replace mymodule with the machine name of the module that contains this function.)

function mymodule_import_translations_in_memory($directory, $pattern) {
  $po_files = file_scan_directory($directory, $pattern);
  if (count($po_files)) {
    require_once DRUPAL_ROOT . '/includes/locale.inc';

    // Allow execution to continue even if the request gets canceled.
    @ignore_user_abort(TRUE);

    // Try to allocate enough time to import all the file.
    drupal_set_time_limit(240);

    foreach ($po_files as $po_file) {
      _locale_import_read_po('mem-store', $po_file);
    }

    @ignore_user_abort(FALSE);
  }

  return _locale_import_one_string('mem-report');
}

Passing 'mem-report' to _local_import_one_string() will cause the function to return all the imported strings, while passing 'mem-store' to _locale_import_read_po() will import the translation in a static variable.

The code I shown works, but if another module called _locale_import_read_po() passing 'mem-store' as first argument, mymodule_import_translations_in_memory() would return the content of the files imported from the other module and the content of the files mymodule_import_translations_in_memory() imported. A more generic code would be the following one.

function mymodule_import_translations_in_memory($directory, $pattern) {
  $po_files = file_scan_directory($directory, $pattern);
  if (count($po_files)) {
    require_once DRUPAL_ROOT . '/includes/locale.inc';

    // Allow execution to continue even if the request gets canceled.
    @ignore_user_abort(TRUE);

    // Try to allocate enough time to import all the file.
    drupal_set_time_limit(240);

    $strings =& drupal_static('_locale_import_one_string:strings', array());

    // Store the old string list to restore it at the end.
    $old_strings = $strings;

    // Reset the string array to an empty array.
    $strings = array();

    foreach ($po_files as $po_file) {
      _locale_import_read_po('mem-store', $po_file);
    }

    @ignore_user_abort(FALSE);

    // Store the value to return.
    $string_list = $strings;

    // Restore the value set before this function was called.
    $strings = $old_strings;
  }

  return $string_list;
}

The code is directly accessing a static variable set by another function, but since there isn't any function to reset its value, that is the only possibility.

In the case of importing a big translation file, keep in mind that loading it all in memory is probably going to cause memory problems. Before doing it, PHP should be set to use more memory than Drupal would normally use.


Can I show email Id entered by user to the visitors? Suppose When a user doing the registration, site will ask that "Do you like to show your email ID?" If the user selects YES then the site will show his email ID and if it selecet no the site will not, I am new to the drupal, so please help me.

Check out the following modules
User Field Privacy

A successor of Profile Privacy for Drupal 7 that works with standard Field API (ie. non-profile) user fields.
In easier-to-understand terms:

All the user fields should have an "alterable privacy" checkbox.
If this checkbox is ticked, the user should be presented with an
additional checkbox for the privacy-enabled fields on user edit forms
to be able to make that fields' values private.
If this second checkbox is ticked for a field of a user, only the
site administrators (members of roles with the "Access private
fields" permission) and the user herself should be able to view that
field's value.

Profile Privacy

This module allows users to set privacy options for their profile fields when using the core profile.module. It does not create any settings pages or configuration screens, and it integrates seamlessly with the existing profile module.


Redirect module does not allow redirection for existing node's path alias I installed fresh Drupal 8 and after that the Redirect module with proper settings. After adding the redirect rule for a path alias it does not work but it saves data properly into the database.

But it works if I add internal path like node/{id}. In this case it works for internal path as well as path alias.

I just wanted to redirect it on the basis of path alias only. Is it possible to add only path alias for the redirection?

I just ran into this also.  You may want to look at https://www.drupal.org/project/url_redirect to see if it fits your needs.


Template name convention for view mini pager I'm trying to understand drupal's theming system and I thought I was doing quite well when, all of a sudden, I tried to create a custom template for the mini pager of the views module. I'm struggling to understand the right naming convention for the file, altough I've read alot during the past two days.

Here is what I've done:
Test template name: myzen

overridden the function myzen_views_mini_pager in my template.php
This works like a charm, the debugger hits the bps, if any.
I tried to inspect the "Theme information" in the advanced section of the
view edit page but I failed to see something related to the mini pager.
I tried to follow this tutorial and I used the dprint trick to list the possible options and I found this:

Array
(
[0] => views_mini_pager__evento_view__block
1 => views_mini_pager__block
[2] => views_mini_pager__default
[3] => views_mini_pager__default
[4] => views_mini_pager__evento_view
[5] => views_mini_pager
)
according to the tut and to what I found I tried to guess the template name, which should be: views-view-mini-pager--evento-view--block.tpl.php but this, obviously, fails. I tried like hundred of other combination (removing the block part, changing the - with _, using only pager instead of mini-pager etcetcetc) and nothing worked.
fun fact is that I can actually make a template for views-view--evento-view.tpl.php (which override the whole view, of course).

Can you help me in figuring out the right naming convention for the mini pager template in that specific block only?

Thank you!

After having Inspected the code more carefully and having read the whole resources I found again I finally found out the I bumped in one nasty corner case.

First of all, reading the code for the views module I found out that the tut I posted in my question was wrong and that the right naming convention for the template file is: views-mini-pager--evento-view.tpl.php (where evento-view is the name of the view).

Then I wanted to try and write a function template (instead of using the .tpl.php file) and I struggled again in finding the right naming convention. Since the views_mini_pager return with theme('item-list', ...) I tried to hook that for my specific view without any luck (mytheme_item_list would work, but changes the html output for every object using the 'item_list'). I finally read more carefully Using the theme layer (Drupal 7.x) especially this:

  Drupal provides a few helpers to build complex HTML constructs easily. These are very useful features, and by using them it is easy to create a consistent look on tables and lists. The downside is that they are not readily accessible to a themer. Instead, they place code that should be at the presentation layer into the logic layer, and only advanced themers are able to do anything with it.
  These functions are more acceptable for administration pages.
  When creating output that is likely to be changed, it is best to avoid the use of these constructs and create the tables and lists with real HTML code. The forum themes are perfect examples of how to accomplish this and still create HTML code that is consistent.
  Function name suggestions with double underscores
  An even bigger problem with using common provided theme functions such as theme('item_list') is that a theme probably does not want to override every theme_item_list() for every list output by Drupal anywhere, but only the one in our module. Therefore, instead of simply theme('item_list'), we can use theme('item_list_mymodule_main', $items) which would make it possible for a theme to implement themename_item_list_mymodule_main() or themename_item_list__mymodule() to override item_list() only for that specific instance.

So I made the mytheme_views_mini_pager function in my template.php returning a theme('item_list__views_mini_pager') hook this with mytheme_item_list__views_mini_pager and all worked like a charm


How can I get image url in a views field, D8 The D8 Views image formatter has only one option: Image. I would like to get the url that's in the markup, not the markup, in my views field output. Do I need to make a custom formatter, or is there contrib code to provide this option? I can't find anything on d.o that looks useful. Also, I don't see any way to rewrite the text using tokens to get the image url.

When setting up your view, under the advanced section you can create a relationship for the image field.

After you added the relationship, you can then add a File URI field, select the created relationship and you are good to go.


what is the difference between hook_insert and hook_node_insert what is the difference between hook_insert and hook_node_insert? How could I use hook_insert in place of hook_node_insert or vice versa

The difference is stated in the hook_insert documentation:

  This hook is invoked only on the module that defines the node's
  content type (use hook_node_insert() to act on all node insertions).

This hook is only fired on the module that defines its own content type for nodes of that content type, so you only should use it in this case for your own content types.


How do I make a list of Users and their total number of posts in a given date? I have D7 and I can already display a list of users with their total number of nodes with Views but how can I make it so that I can choose the date range?
Its like analytics to see if a User has any posts in a given month.

You may want to check if using the Views Date Format SQL module could be a solution for you. Here are some quotes about it (from its project page):

  ... allows to format date fields using SQL.

  The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date.
  This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.

  The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts (disclosure: I'm a co-maintainer) module.


Image File field not getting updated Form function:

$form['upload_photo'] = array(
        '#type' => 'file',
        '#title' => t('Upload Your Photo'),
        '#title_display' => 'before',
        '#states' => array(
            'visible' => array(
                ':input[name="testimonial_type"]' => array('value' => 'Text'),
            ),
        ),
        '#prefix' => '
',
        '#suffix' => '
',
    );

Submit function:

$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_text_testimonial_info'));
$file_d = $form_state['values']['upload_photo'];
                $file = file_load($file_d);
                $file->status = FILE_STATUS_PERMANENT;
                file_save($file);
                file_usage_add($file, 'user', 'TYPE', $file->fid);
                $file_info = image_get_info($file->uri);
                $file_arr = array(
                'fid' => $file->fid,
                );
                $field_collection_item->field_client_image[LANGUAGE_NONE][0] = $file_arr;
                $field_collection_item->setHostEntity('user', $user);
                $field_collection_item->save();

After submit I am getting below error:

Notice: Undefined property: stdClass::$uri in file_save() (line 614 of /public_html/includes/file.inc).
Notice: Undefined property: stdClass::$filename in views_data_export_file_presave() (line 278 of /public_html/sites/all/modules/contrib/views_data_export/views_data_export.module).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] => 1535026403 ) in drupal_write_record() (line 7386 of /public_html/includes/common.inc).

Kindly help me to solve it out

Maybe this can help How to upload file in drupal8 forms with form element type file?

I see for your use case it makes more sense to use Managed file type.

A couple of observations, something you should look at,

It seems you are getting SQL errors due to trying to upload a file which is already present in the table, you should check why this happens and perhaps programmatically change the name of the file if it already exists. See file_save_data
Errors from views, not sure where you are trying to submit this form, but it is clearly breaking something in views_data_export or it maybe because of the next point.
Lastly, check the link above for how to properly handle file uploads in form, it looks like file_save($file); is breaking for you due to missing uri


Drush post command hook not executed I need to run a hook after a drush command in another module has been run to clean up a file on the server, and so based on what I've read here and here I'm trying to implement a post command hook on the node-export-import command.  In mymodule.drush.inc I have a function defined as

function drush_mymodule_post_node_export_import(){
  // Do my magic here
}

but it isn't called at all after running the node-export-import command.  I've played around with other naming variations, but none are getting called.  My module is enabled, and I've cleared cache.  I'm using version 5.9.  Is there something I'm missing?

Thanks.

To see all of the hooks available to you, run your command with --show-invoke, like this:

$ drush status --show-invoke 2>&1 | grep mymodule
drush_mymodule_core_status_pre_validate
drush_mymodule_core_status_validate
drush_mymodule_pre_core_status
drush_mymodule_core_status
drush_mymodule_post_core_status

However, when we do this on node_export commands, we see no results.  Why is that?  Well, unfortunately, some commands do not go through the drush invoke hook process.  If you look at the definition of the node-export-import command, you will see this:

$items['node-export-import'] = array(
  'callback' => 'drush_node_export_callback_import',

In Drush's command.inc, there is this comment in the function drush_get_commands():

    // If command callback function name begins with "drush_$commandfile_",
    // then fix up the command entry so that drush_invoke will be
    // called by way of drush_command.  This will cause all
    // of the applicable hook functions to be called for the
    // command when it is invoked.  If the callback function does
    // -not- begin with its commandfile name, then it will be
    // called directly by drush_dispatch, and no hook functions
    // will be called (e.g. you cannot hook drush_print_file).

If a command provides a callback, then Drush calls that function instead of drush_command, so _drush_invoke_hooks is never called.  This means that, even though you named your hook function correctly, Drush will not call it, and you are stuck.

From here, you have two options:

Post an issue to the node_export issue queue, and request that they stop using the 'command' callback parameter, and let Drush choose the function name to call.  This will make hooks work again.  Using 'callback' is deprecated unless it is necessary (e.g. many commands calling the same function, such as drush_print_file), so hopefully the maintainers will be willing to do this.
Post a feature request to the drush issue queue, and request that Drush call the invoke hooks even if the Drush command uses the callback feature.  This is theoretically possible if the parameters to _drush_inovke_hooks were enhanced to include a replacement function name to call in place of the primary hook function.  This would have to be set up in drush_get_commands(), and then detected and uses in drush_command() where it calls _drush_invoke_hooks.  This didn't seem like a good idea at the time, but if it is common for contrib module maintainers to ignore subtle Drush conventions, it might be worthwhile to go to the extra effort to let folks hook their functions anyway.

Update:  I made a patch for you.  See: https://drupal.org/node/2041109.  You might still want to do #1, as I don't think that we will necessarily backport this enhancement to Drush 5.

Update 2: Above-referenced patch has been committed to Drush-8.x-6.x-dev.  This happened after the rc1 release, but it will be in the next release.

Update 3: This is now available in Drush-8.x-6.0-rc2.


Please help for the moment no way to include chemistry in Mathjax I'm using the Mathjax Module on drupal 7. All working pretty good but when i'm trying to add the chemistry js, it was not the same !! I tried to enable it without success. I have read a lot of documentation, i forget where but i read : if you use "\ce", mhchem will be loaded automaticly.

Apparently it's not the case :

My custom configuration :

MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ['\\(','\\)'] ],
processEscapes: true
},
showProcessingMessages: false,
messageStyle: 'none'
});

Tring to change

extensions: ["tex2jax.js"],

to

extensions: ["tex2jax.js","mhchem.js"],

without success and a lot of other test.

No way to force the js to be loaded. May be there is a trick ?

thanks for helping

You need to add the mhchem.js extension to another part of your configuration, namely the TeX part.
Here is a configuration that worked correctly for me (a modification of the 'default' custom configuration on a clean Drupal7/MathJax environment:

MathJax.Hub.Config({
  extensions: ['tex2jax.js'],
  jax: ['input/TeX','output/HTML-CSS'],
  TeX: {
    extensions: ['mhchem.js'],
  },
  tex2jax: {
    inlineMath: [ ['$','$'], ['\\(','\\)'] ],
    processEscapes: true,
    processClass: 'tex2jax',
    ignoreClass: 'html'
  },
  showProcessingMessages: false,
  messageStyle: 'none'
});

My content looked like this:

$2 + 2 = 4$

$\ce{H2O}$

and gave me this as an output:

Hope this helps!


Ctools modal close breaks page JS I have created a custom module which opens modal with a specific Url Pattern. I'm using the url in a view and it works well.

The only problem is that I also load another piece of jQuery to create a basic accordion which breaks after the modal has been loaded. The javascript is still called but it toggles twice instead of once.

/**
 *  Implements of hook_menu()
 */
function mymodule_menu() {
  $items['modals/%ctools_js/%'] = array(
      'title' => 'Product Modal',
      'page arguments' => array(1, 2),
      'page callback' => 'mymodule_modal_page',
      'access callback' => TRUE,
      'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}
/**
 * A modal static page callback.
 * @param $js
 *   boolean CTools determination whether the user's browser is javascript enabled.
 * @param $nid
 *   string The node ID of passed as an argument from the hook_menu() path
 * @return
 *   string The contents of the node, that will fill the modal window.
 */
function mymodule_modal_page($js = NULL, $nid = NULL) {
  if ($nid == NULL) {
    return 'No node id was sent. Error.';
  }
  if ($js) {
    ctools_include('modal');
    ctools_include('ajax');

  }
  $node = node_load($nid);
  $contents = render(node_view($node, 'modal', NULL));
  return ctools_modal_render($node->title, $contents) ;
}

  /**
   * Implements hook_views_pre_render()
   */
  function mymodule_views_pre_render(&$views) {
    if ($views->name == 'my_view') {
      //add accordion script
        ctools_include('ajax');
        ctools_include('modal');
        ctools_modal_add_js();

        $product_style = array(
          'product-modal-style' => array(
            'modalSize' => array(
              'type' => 'fixed',
              'width' => 400,
              'height' => 400,
              'addWidth' => 10,
              'addHeight' => 10,
              'contentRight' => 1,
              'contentBottom' => 1,
            ),
            'modalOptions' => array(
              'opacity' => .9,
              'background-color' => '#424242',
            ),
            'animation' => 'fadeIn',
            'modalTheme' => 'product_modal',
          ),
        );
      drupal_add_js($product_style, 'setting');
      ctools_add_js('product', 'mymodule');
      ctools_add_css('product', 'mymodule');
      drupal_add_js(drupal_get_path('module', 'ukgproducts') . '/js/product_accordion.js','file');
    }
  }
  }

  /**
  * Implements hook_theme().
  */
  function ukgproducts_theme() {
    return array(
      'views_view_unformatted__my_view' => array(
        'variables' => array('view' => NULL, 'options' => NULL, 'row' => NULL),
        'template' => 'views-view-unformatted--my_view',
        'base hook' => 'views_view_unformatted',
        'path' => drupal_get_path('module', 'mymodule') . '/theme',
      ),
    );
  }

accordion JS

(function($, Drupal)
{
  // Drupal.behaviors is the Drupal onload function:
  Drupal.behaviors.ukgproducts = {
    attach:function()
    {
      $('h2').click(function(e)
      {
        e.preventDefault();
        $(this).closest('.binder').find('.product-list').toggle('slow');
      });
    }
  }
}(jQuery, Drupal));

You should pass the context in and use the once() function to make sure your events are only bound once, and in the right context. Something like:

(function($, Drupal) {
  Drupal.behaviors.ukgproducts = {
    attach: function(context, settings) {
      $('h2', context).once('myaccordian').click(function(e) {
        e.preventDefault();
        $(this).closest('.binder').find('.product-list').toggle('slow');
      });
    }
  };
})(jQuery, Drupal);


How to change the pagination of related entities displayed on a taxonomy term page? On a default taxonomy term page, related contents are automatically paginated by 10.

Let's say those related contents are always nodes and we always display the default teaser view mode.

How can I change the number of node teaser by page without using a module or a view?

The taxonomy module uses the default_nodes_main variable to decide how many to show per page (this happens around line 55 of taxonomy.pages.inc in case you're interested).

Usually you would implement a custom module and provide a form to override that variable for your users. But you don't have to do that, if you just want to set the variable once and be done with it use one of the following methods instead:

Use Drush (drush vset default_nodes_main 20)
Add a PHP snippet somewhere that will be run in your site (you only need to do it once)

variable_set('default_nodes_main', 20);

Use the Devel variable editor


In Taxonomy View, how do I get the count of relationships associated with that term In a View based on a Taxonomy Term, is there a field which shows a count of how many relationships that tag has?

I'm pulling a list of Academic Years in this situation. If there is no Nodes tagged with these years, I'd like to omit them from the list.

You can solve this two ways:

You can create a view of nodes, create a relationship to their taxonomy term, and display the terms. This will only display terms that can be pulled up through a node by views.
You can keep your taxonomy display and add a relationship. Add "Taxonomy: content with term" and the check the box labeled "Require this relationship". This will give you duplicates so you also need to go down to "Query Settings" and check the box for "Distinct".


how to show the foreign characters in tpl.php file I would like to set my website as Multilingual. I typed some Korean words (eg."한국어") in tpl.php file, but when I check my webpage, it shows me some question marks (eg."???").
Here is the code:

한국어

I think it might be somewhere I need to set first. Does anyone know about this? I really appreciate anyone's help.

Make sure that your theme is using the utf-8 character set.  You can see this in the headers of the page:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

You'll also want to make sure that the web server you are using to serve the page is sending the correct HTTP header as the response (you can use the web developer inspector tool in either Firefox or Chrome to see this).  It should be:

Content Type: "text/html; charset=utf-8"

If your browser is set to use a different content-type encoding this might also explain the difference.


How to add filter on node list in a custom module? I am developing a module. In that module I have a page to list all the nodes of a specific type to user.

I need to:

1- show the nodes each on a row with ' Edit | Delete ' link in each row.

2- I also need to show a dropdown to give the user ability to filter the nodes by one of the node field.

I've created the first one but I don't know how to add a custom filter to the output.

Would you help me ?

I am working on Drupal 6.

Thank you.

If you are using Views 3 and within CCK you have listed allowed values for the field in question, you can set it up like this.

Select the field in question with the allowed values option, eg, in Filters, select 'Content: Field Name (field_name) - ALLOWED VALUES'
Click on EXPOSE.
Click in the values and select them all.
Click Limit list to selected items.
Save it.

You should now have an exposed filter with a drop down that limits the view to that field.


How to use the Rules module to flag a node that has just been created? I need to automatically flag a node after it has been published. All nodes of a certain content type will be flagged.

In order to solve that problem, I have installed the Rules module hoping that I would be able to automatically flag the nodes that are created. Rules module does not come prepacked with flag actions.

Is it possible to flag an item that has just been created?

FYI, after a lot of search I discovered that Rules2 support in Flag for Drupal7 is already in dev. I tried it and it works well!

There is also a patch as stated here: http://nodeone.se/blogg/learn-flag-with-nodeone-part-7

Not easy to google out! :P
Bye!


Webform many dropdownlist results saved under one unique field I'm working with webform to collect information on car relliabilty level.

I've set one dropdownlist to allow user choosing a car brand. As a car brand is selected, only the coresponding dropdownlist, with car models, is showing up (done with Webform Conditional).

All is working fine, but I realize each model dropdownlist is saving data in its own field in the database.

I want to analyse results by car brand and car models.
What would be the best way to proceed?

Saving all models in one fields, when data are submitted? Maybe with a hook
Merging all car models after data submission in one unique field?

My test: http://fiabilidad-coche.blg.lt/?q=node/10

Any help or hint would be greatly appreciated.

Ok, I found a solution: I've used a presave hook. This hook is saving all values submitted by users in a hidden field called "model". A loop will be needed to read the 56 listboxes and save the only value the user have selected.

To do my test I've created a test webform, with only one listbox and one hidden field (this field created automatically my needed field "model" in my database). That speed up a little my tests:

First at all I've created a custom module with a "presave" hook
In a new directory named "duplicated_data", I have create two files:
data_duplicate.info
data_duplicate.module

In the info file I've declared my module

name = Data Duplicate
description = Duplication Data for Webform
core = 7.x
package = Webform
dependencies[] = webform

In the module file I've written my php code

<?php
function data_duplicate_webform_submission_presave($node, &$submission) {
  $component_id = 1; // dropdownlist cid = 1
  $mem = $submission->data[$component_id][0]; // retrieve the submitted value
  drupal_set_message('datos :'.$mem); // print the result
  $component_id = 2; // cid = 2
  $submission->data[$component_id][0] = $mem; // save the data in the hidden field
}
?>

Now I need to activate my custom module.
Each time I make a choice in my dropdownlist/listbox and click on submit, the results will be saved in the database in both fields.

For my production webform , I need to create the loop in order to read all the 56 listbox values and save in my field "model" only the value from the selected listbox. It will be easy to catch it, because it will be the only one, different from NULL.

Hope it will be help somebody else!


Overriding "/user" page with Feature (Drupal 7) I am trying to learn about creating a reasonable workflow between a development site and a production site and I have decided to use the Features module to help accomplish this task.

Standard "/user" page allows me to click "forgot my password" or "create new account", but I want more options and I'd like to override that page with feature module. I am not sure is this a good approach, but with this feature I will have ability for users to create accounts, login to the website, and manage their account profile.

I have added dependencies and Strongarm variables, but I don't know how to make it use "/user" path.

Thanks,
Michael

Features is the way to move configuration data between different environments, or at least the most typical. But in your case you need to move functionality, not simple configuration (as what you want to achieve can't be done just modifying configuration).

Features takes some Drupal objects as Views, permissions, roles, content types, panels and so on an put them into code that can be later imported to another Drupal instance. This is considered configuration because even when  this kind of objects add functionality to the site you have added it configuring some modules.

So, if you can manage to achieve your desired functionality (I suppose using Panels and others modules) you may export that configuration using Features. And I say may because not all configuration can be exported this way (most yes).

In your case probably you'll need a custom module that menu_alters the /user URL and uses a custom page callback that adds what you need. But what you need is too broad to explain in an answer here.


Moving the Up/Down Vote Widget to end of content I am brand new to Drupal but not to OOPHP.  I am assuming responsibility for a site which uses Up/Down Vote 6.x.

The issue is that the posts are very long and hold many many images and it doesn't look like the module supports any widget position other than at the top of <div class="content">.

I would like to move it to just above the footer links of the node, after the content.

I have been googling this without success.  Can anyone advise me or direct me to the relevent docs?

Widget is getting displayed using hook_node_view code in vud_node.module...

/**
 * Implementation of hook_node_view().
 */
function vud_node_node_view($node, $view_mode, $langcode) {
  // avoid showing the widget in some node builds
  $exclude_modes = array(
    NODE_BUILD_PREVIEW,
    NODE_BUILD_SEARCH_INDEX,
    NODE_BUILD_SEARCH_RESULT,
    NODE_BUILD_RSS,
  );
  if (in_array($node->build_mode, $exclude_modes)) {
    break;
  }
  if (($can_edit=user_access('use vote up/down on nodes')) || user_access('view vote up/down count on nodes')) {
    $node_type = in_array($node->type, variable_get('vud_node_types', array()), TRUE);
    $widget_showmode = variable_get('vud_node_widget_show', VUD_NODE_DISPLAY_BOTH);
    $tag = variable_get('vud_tag', 'vote');
    $widget = variable_get('vud_node_widget', 'plain');
    $vote_on_teaser = (bool)variable_get('vud_node_widget_vote_on_teaser', TRUE);
    $teaser = $a3;

    $widget_message_code = VUD_WIDGET_MESSAGE_ERROR;
    if (!$can_edit) {
      $widget_message_code = VUD_WIDGET_MESSAGE_DENIED;
    }
    elseif (!$vote_on_teaser) {
      $widget_message_code = VUD_NODE_WIDGET_MESSAGE_TEASER_DENIED;
    }

    if ($node_type) {

      switch ($widget_showmode) {
        case VUD_NODE_DISPLAY_TEASER_ONLY:
          if ($teaser == 1) {
            $node->content['vud_node_widget_display'] = array(
              '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, !$vote_on_teaser || !$can_edit, $widget_message_code),
              '#weight' => -10,
            );
          }
          break;
        case VUD_NODE_DISPLAY_FULL_ONLY:
          if ($teaser == 0) {
            $node->content['vud_node_widget_display'] = array(
              '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, !$can_edit, $widget_message_code),
              '#weight' => -10,
            );
          }
          break;
        case VUD_NODE_DISPLAY_BOTH:
          if ($teaser == 1) {
            $readonly = !$vote_on_teaser || !$can_edit;
          }
          else {
            $readonly = !$can_edit;
          }
          $node->content['vud_node_widget_display'] = array(
            '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, $readonly, $widget_message_code),
            '#weight' => -10,
          );
          break;
      }

    }
  }
}

Implement hook_node_view_alter in your custom module and change the weight to higher value so that it will be displayed at bottom...

In Drupal modules extends permissions by defining them using hook_permission.. You can find list of permissions in "admin/people/permissions" ..

For vote up / down set permissions in above page.. See screenshot below..


Create a link using the render API Back in Drupal 7, I was able to create a link  (Ajax enabled) like this:

$page['profile']['links']['videos'] = array(
        '#type' => 'link',
        '#title' => t('Videos'),
        '#href' => 'profile/videos/' . $uid . '/nojs',
        '#attributes' => array('class' => array('use-ajax', 'profile-button-videos')),
        '#prefix' => '
',
        '#suffix' => '
',
      );

Though there are plenty of examples about how to create a link from a URI, or external URL; and how to attach attributes, I can't find a shred of documentation on how to append something as simple as "nojs" on the end of the URL...

My code so far is this in Drupal 8 (and it works). But, it lacks the /nojs on the end.

Note: I an not using the the Forms API; strictly Render Elements.

$url = Url::fromRoute('people.profile', ['uid' => $uid]);
    $render_array['people']['bio'] = [
      '#title' => $this->t('Publications link'),
      '#type' => 'link',
      '#url' => $url,
      '#attributes' => array('class' => array('use-ajax', 'profile-button-bio')),
    ];

The end result should be a link that looks something like this:

  /profile/publications/{uid}/nojs

You will not be able to use a route, as /no-js would be its own route. Instead, you should use Url::fromUri. You should be able to use:

Url::fromUri('internal:/profile/publications/' . $user->id() . '/nojs');


Omega theme sidebar padding I've started using the Omega theme, and wanted to apply a vertical gap in between my blocks in the sidebar on the right called sidebar-second. I went into the themes settings, and added an additioanl css in "Additional region classes" but its applied it the whole of the sidebar, and I still have no gaps. I have tried inspecting in firebug, and if I amend 'region-inner' it works but applies to all regions including main content etc. I just wanted the ones in the Sidebar Second. I'm afraid I dont know enough css to - can someone point me in the right direction?

I have fixed this now by adding:-

.region-sidebar-second .block-inner {
  background-color: white;
  border: 1px solid #CCCCCC;
  border-radius: 10px 10px 10px 10px;
  padding: 10px 20px 20px;
  position: relative;
  margin-bottom: 20px;
}

Sorry, it was a lack of knowledge of css causing the problem.


How to display only content assigned to a user? I have created a content type with a CCK field named 'executor' of 'User reference' type. So the admin can select a different user as an executor in creating content.

I want to create a page using views to display all tasks a user is assigned to as executor. But I don't know what I should put in fields and filters.

Create views by filtering the content type which you want to list in there.

Then add a argument in the view, which will be the field you are using to reference the user in your content type.

Supply UID of currently logged in user as default arguments & your content will be filtered for logged in user.

User will see all the fields values added by you on the page, fields are totally dependent upon your selection which you can add in views.


Optional multiselect field, hide the - None- option I am working on a form made mostly of multi-select fields, which are optional for the user to choose.

The multi-select fields work fine in general; however I really need to hide the -None- option in the multi-select fields which are not required for user to select. I can override it and change the text but thats not the point, since user can still select the -None- value in the process of selection, even tho it wont show after node is saved.

It just looks a bit confusing, even though it works as it should; users can select both the -None- option along with other options available and that makes the whole form different from what I want.

Here is an image of an example field showing what I mean.

I tried searching through the CCK module, but I couldn't really find anything.

To get rid of "- None -" from selected field of a selected form, use:

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    unset($form['field_name'][LANGUAGE_NONE]['#options']['_none']);
}

Of course for many fields it's inconvenient, but if they all share common parent (fieldset), you can iterate using foreach like:

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    foreach( element_children($form['fieldset_name']) as $key => $child) {
       unset($form['fieldset_name'][$key][LANGUAGE_NONE]['#options']['_none']);
    }
}

This is not a ready code, just a sketch. Hints to make it work:

Unset elements of original $form, not $child generated by foreach.
Test if what you want to unset is there at all.
dpr() or var_dump() to see what's the exact structure you are working with.

You will need to wrap these into a Drupal custom module. Read Module developer's guide, especially Creating Drupal 7 modules, and hook_form_alter() API reference if you need more backgroung.

Inspired by this answer.


Multisite setup with drush Is it possible to set up multisite with drush including folder creation and database setup?

For the first site:

drush qd --sites-subdir=<directory name>

For each successive site:

cd DRUPAL_ROOT_CREATED_ABOVE
drush qd --use-existing --sites-subdir=<directory name>

These will create sqlite databases.  Add --db-url with valid database credentials to use a pre-existing database.  Also add --db-su and --db-su-pw to make Drush create the database for you.

Haven't tried some of the steps in this workflow in a while; report any problems back in the Drush issue queue.  Also, you might want to use drush master instead of 6.x.  There's a issue in the queue that hasn't landed yet that makes drush qd better.

UPDATE: Drush quick-drupal does not appear to be well suited for multisite usage.  For subsiquent sites, call drush site-install with --sites-subdir and --db-url options.  See drush help si for more information on options that may be useful here.

For example

drush si --sites-subdir=<folder> --db-url=mysql://db_user:str0n6passw0rd@localhost/db_name


How to redirect all variations of a domain to https version? Google has started punishing non https sites both in SEO and their browsers. So I guess we must make sure that all our clients are using https

Assuming that I have a domain example.com I would like to redirect all the variations of this domain to the https version.

There can be six variations
example.com, www.example.com, http://example.com, http://www.example.com, https://example.com, https://www.example.com.

I want to make sure that all these variations redirect to https://www.example.com.

example.com is the naked version of www.example.com. In the settings for the domain, add an A name pointing to IP of your server.

Add a C Name that points to the www version at the same IP.

If you are running Apache, in the virtual host settings add both Servername and ServerAlias.

<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com

This will make sure that your server listens both the naked domain and normal domains and points them to you code folder for execution.

Make sure the .htaccess file contains the following lines.

  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

This code just sets a flag called protossl, if you have visited using https. This will ensure that you don't have infinite redirections between http and https as mentioned in the comments.

Comment out all other settings related to http and https redirection, and add the following lines.

#
# Rewrite http(s)://example.com to https://www.example.com
#
RewriteCond "%{HTTP_HOST}" "!^www\." [NC]
RewriteCond "%{HTTP_HOST}" "!^$"
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#
# Rewrite http://www.example.com to https://www.example.com
#
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This code was provided by https://www.drupal.org/u/mdrescher on
https://www.drupal.org/forum/support/post-installation/2018-04-15/forcing-to-https#comment-12723535.

These changes will make sure that all six variations example.com, www.example.com, http://example.com, http://www.example.com, https://example.com, https://www.example.com are redirection https://www.example.com


Programmatically remove content from a group In order to add a node to any group in Drupal 8, I use the following code.

$group->addContent($node, 'group_node:article');

Now, for removing content from a group, I have tried $group->removeContent($node, 'group_node:article'); and $group->removeContent($node); without success. All I obtained is the following error message.

  Error: Call to undefined method Drupal\group\Entity\Group::removeContent() in Drupal\my_valetop_extras\Plugin\WebformHandler\CustomWebformHandler->submitForm()

Finally, I have managed to remove content from a group using this code.

$type = 'group_node:' . $node->getType();
$current_node = $group->getContent($type, ['entity_id' => $node_id]);
$content = array_values($current_node)[0];
$content->delete();

But  believe I can remove a single node from a group with a simple line of code.

How can I achieve it?

I believe that function was overlooked by the developers. In the issues queue for the Group module, which is what your error message refers to, I can see that the inverse of addMember(), removeMember(), was added later in the project's life. It seems reasonable to suppose that the inverse of addContent() was also overlooked, with the only difference being that it has remained unimplemented to this day.

There are no functions with names hinting at content-removing behaviour evident in the module's GroupInterface definition, so I recommend opening a new issue with the project to let them know about the gap.


#default_value not being displayed in form Here's a function that returns a form:

function myfunc($str)
{
    $form = array();
    $form['header text'] = array(
        '#markup' => '
blah blah blah
',
    );
    $form['new_str_value'] = array(
         '#type' => 'textfield',
         '#title' => 'New String Value',
         '#size' => 60,
         '#maxlength' => 128,
         '#required' => TRUE,
         '#default_value' => $str,
    );

    return $form;
}

The textfield displays correctly with the right size and label, but it is not populated with an initial value. Any ideas? Should I be rendering or building the form in the function before returning it, or setting the value in $form_state ... or something?

Any help much appreciated!

Assuming Drupal 7...

The signature for form functions needs to follow a strict pattern; Drupal will pass along $form and $form_state as the first two args, and anything else as subsequent args.

So assuming $str should be the first custom arg to the form, the signature should look like this:

function myfunc($form, &$form_state, $str) {


Single click function in a Drupal behaviour? The following in a Drupal behaviour is working fine:

  $('.trigger', context).click(function(e){
    e.preventDefault();
    $('.target').toggleClass('open');
  });

However I know that I should be using the once function. Is the following correct? It does work but so did the code above so im not sure how to check if its been done with best practices.

  $('.trigger', context).once('toggle-name', function(){
    $(this).click(function(e) {
      e.preventDefault();
      $('.target').toggleClass('open');
    });
  });

If you don't use .once() then your code will still work but - depending on whatever else happens on the page - your click() function may be attached multiple times to the same element, which is less efficient and may cause undesired effects if, as in this case, you are using a toggle function in your callback.

Because you are limiting the scope of your selector by context, multiple attachment is less likely, but you should definitely use once() if you want your code to be robust.


Node referencing: How do you display a node with all its references? Ingredients:

Drupal7 + References + Views module installed
2 content types: magazine issue + magazine articles (for each issue)
Article c-type has a reference field: issue_no which displays the
issue it belongs
I made a Views to display me a plain list of issues only.

Requirements

When I click on the issue in the issue list I want to see all its references nodes(=articles) attached
I need to highlight the latest issue in the list by creating a separate page VIEW on the frontpage that contains articles of the latest view.

I would appreciate any help.

Here is a prinscreen on my content type > manage display

Install views and have it manage your home page, then add a content type filter so that it only shows issues on your home page. This will stop your home page being a mix of articles and issues.

Then, go to each content type and go to "manage display", in there you can specify the format, by default this is set to title (link). You also have an option for "full rendered node" which will display the whole referenced content inline.

Alternatively you could use views and create a block with the nid as a argument so it displays references content in a way you can choose fields to display etc


Echo taxonomy description based on specific value of a field in a custom template I'm trying to check the value of a field on my content type that is a list of taxonomy terms to see if it matches a specific taxonomy term, then if it does match, echo the description field of the taxonomy term I checked. Else, if it does not match, then nothing is to be printed out.

Here is the code I've been experimenting with, but thus far have been unsuccessful getting to work properly:

if ( isset($facil->field_facility_type['und']) &&
 $facil->field_facility_type['und'][0]['value'] == "Hospital")) {
foreach ($facil->field_facility_type['und'] as $description ) {
    echo '
 Say something wild and crazy!
'.$description["value"].'';
    echo '
';
}

}

I'm confused on how to get it to check the value of the field of taxonomy terms, of which the specific one I'm trying to target for this piece is one of about 15 different terms.

So, here's what we ended up with:

$fterm = taxonomy_term_load( (int)$facil->field_facility_type['und'][0]['tid'] );
        $fname = $fterm->name;
        $description = $fterm->description;

        if( $fname == 'Hospital' ) {
            if( !empty($description) ) echo '<div>' . $description . '</div>';
        }


How to add a profile tab via views On the profile page that is /user/1 for e.g how to add tab MY ADS to be /user/1/myads?

Create a view page and add a menu item entry: "Default menu tab" to "Menu tab" and select "User Menu" in dropdown in your view.


Redirecting user-login-form on certain page The scenario is :

I've implemented a menu using hook_menu and in that page it checks if user have access to creating certain content type (called request) if he/she does have access it will load content creation page using drupal_get_form else it checks if user is not logged in, in this case it loads user_login_block, again with drupal_get_form function, finally if user is logged in and still does not have access to create content type, it shows a message about that.

the problem is :
I want user redirect to this same page after login, it redirects to user/uid by default.

This is the code for my page provider function :

Global $user;
$content = "";
if(user_access('create request content')){
module_load_include('inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'request';
$node_form->language = LANGUAGE_NONE;
$form = drupal_get_form("request_node_form", $node_form);
$content .= drupal_render($form);
}
else
if($user->uid == 0) {
  $login_form = drupal_get_form('user_login_block');
  $login_form['redirect'] = drupal_get_destination();//What I did to get form redirected, but no chance
  $content = '
For better controlling on your project flow consider signing in before submitting your file.
';
  $content .= drupal_render($login_form);
}
else
  $content = "Unfortunately only user of role customer can submit a request.report any problem by sending email to --------";
return $content;

I also tried Login Destination but it neither worked.

There are several methods to redirect user to specified url after login

You can use Rules

Events: User has logged in.

Condition: User has role

Actions: Page redirect

Another one with drupal api:

   function hook_user_login(&$edit, $account) {
     $edit['redirect'] = 'yourpath';
  }

if it not worked try to change $GLOBALS['destination'] with

function hook_user_login(&$edit, $account)  {
  $GLOBALS['destination'] = 'yourpath';
}

Also you can use Login Redirect module

  Overview A simple module providing a method to redirect users
  according to an URL-defined parameter after logging in. Allows
  redirects toward non-Drupal location.

  Features

Lightweight and minimal configuration. No module dependencies!
Allows custom URL parameter name
Filters XSS URL input


Use username password on different subdomain I now have a website which is using drupal. This is the 'main' website on the www domain. I would like to build a small gimmick which is only accessible to my users. This gimmick site is probably not using drupal at all.

Is there a way to duplicate the login procedure for my subdomain so that only users from my main site can use the gimmick site?

thanks in advance

Yes,there is no problem using  drupal user table, you just need implement you site and  connect to data base that Drupal install on it and then just need use user table ,
only one note remain that the password  saved with md5 method in  user table.
I thing is not complex, the summery of answer is connect to db use uid(or name) and password field of users table .

as sample code :

<?php

$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="drupaldb"; // Database name
$tbl_name="users"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = md5(mysql_real_escape_string($mypassword));

$sql="SELECT * FROM $tbl_name WHERE name='$myusername' and pass='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// want to want
echo "congratulation ,you login";

}
else {
echo "Wrong Username or Password";
}
?>


How to use a token in "Behavior without results" of a view? I want to retrieve the ID token of the group in "Behavior without result" of a view. How to do ?

It only offers me (site and view).

The token does not work.

The url does not take ID into account:

/group//join

You have to check the checkbox and then use the token you want BUT you have to be careful because you are in the case you do not have any results and the {{ id }} will use the first result of your view as said on the description.

So you have to use your contextual filter : {{ arguments.id }} and it will work as you want.


selecting all field_data_body for all content types We are trying to search all text_long or text_with_summary fields for all content type nodes.  I can do it for the field_data_body.  I need to expand this for all content types using text_long and text_with_summary.  I would like to iterate all nodes for all content types and select all fields in the node with the text_long and text_with_summary field type.

Here is what I use for selecting just the body.  I use a cursor to search each db which is why I have a v_db variable.  Don't worry about v_db and @j is the search string I pass to the select statement.  I wish there was a nice GUI for visualizing joins.

select "',v_db,'", ',v_db,'.node.nid, LEFT(',v_db,'.node.title,30), LEFT(',v_db,'.body.body_value,300) from ',v_db,'.node INNER JOIN ',v_db,'.field_data_body AS body ON node.nid = body.entity_id WHERE body.body_value like ',@j);

thanks

I needed to do something a bit similar a while ago, and used the drupal field definition tables to identify the field type (text/long et al) and work from there to the nodes. I suggest you do likewise.

You could consider using the mysql fulltext search facilities - it is much faster and much more capable than 'like'.

Of course, the drupal way would be to configure the search module properly...


JS Javascript into a single node / page I have a form that works fine outside of drupal where it called a script  ..../default.js However this does not work inside drupal 6 when i copy the code from ym html/php file.

I have seen this line

 drupal_add_js('globals/default.js');

Is this all I need to add to get the JS read? I have the php filter in Drupal 6 set to allow pretty much all tags for the administrator.

Sounds to me like you're trying to call the drupal_add_js() function from within a node edit form (or maybe the body of a form).  Instead of that, just change the body's input filter to HTML (or whatever filter you have that allows <script> tags) and call the external JavaScript there as you would in any HTML page.  You don't need to use PHP for that.

I would add that that probably isn't best practice.  Using drupal_add_js() is, but you should use drupal_add_js() in page templates (e.g., node.tpl.php) or in preprocessor functions (e.g., hook_preprocess_node()).

As an aside: be very careful of the PHP input filter, it has major security implications.


How to generate images for profile picture in Drupal 7? Let's say I've a site with hundreds of users. I would like to provide a profile picture to users who don't have a picture on their profile.

How can I do that?

I could achieve that by the Identicon module.

This module generates and displays identicon images in place of the user picture for users who do not have a picture.
The generated identicons are pixel style images. The number of pixel blocks that the images contain can be configured. You can choose whether the generation is based on the user's email address or the user id. If the generation is email-based, users will get a new image if they change their email address. On the other hand, they get the same image even if they cancel their account, and register again using the same email. If the generation is user id based, changing the email address will not change the identicon, but if the user account is cancelled, the user will not get the same image when they re-register.

Checkout the similar modules Gravatar and User Pic Kit


How do I get the submitted value for a field? I have a custom submit handler:

function submituserform(array $form, FormStateInterface $form_state) {
  $email = $form_state->getValue('field_email');
  drupal_set_message('Thank you for for submitting your application. You will receive a confirmation at ' . $email . ');

  $redirect_path = "/confirmation";
  $url = url::fromUserInput($redirect_path);
  $form_state->setRedirectUrl($url);

}

I get Array as value for the email. How do I get the email from field_email?

You can also do this in following way:

function submituserform(array $form, FormStateInterface $form_state) {
  $element = $form['field_email'];
  $email = $form_state->getValue($element['#parents']);


What are the available image sliders? I want to know what sliders are available for Drupal 7, and which ones can be used in blocks.

See handbook page Comparison of Rotator / Slider modules.


How can I suppress "CSS file not found" errors on production? "One or more CSS files were not found or does not exist" errors are being displayed to users on production.  Of course I should fix the source of these errors, but in the meantime, I would like to suppress this error message.

On admin/config/development/logging, I have set Error messages to display to None.  Is there some other step I need to take to suppress these errors?

I have also cleared all caches (Drupal, Redis, Varnish) but the error (only present on some pages) is still being displayed to authenticated (non-admin) users.

I would first ask, are you logged in as super admin? I believe if you are logged in as super admin the message will display regardless of the setting in development/logging.

If you are not logged in as admin and are viewing the page anonymously did you clear your browser cache. If the messages are still being displayed, is your site being cached via varnish? You may need to clear the varnish cache or simply add an extra query parameter to the end of the url to make certain you are viewing an unvarnished page. Ex: www.example.com/homepage?extraquery

This is generally unadvisable but when push comes to shove and you need to hide something quickly on the production site, you can alway hide the error message box with css until you actually fix the error. AGAIN, i would only use this as a last resort and if deadlines are rapidly approaching and there just is no other option.

You could do something like .error {display:none;} in your global.css file or wherever seems more suitable.

Good luck


How to add an existing custom field to a new content type In my new module I am writing, I am creating a new content type.  In this new content type, I want to attach custom fields for a media player: the media player from MediaFront and a File field with a Media File Selector widget type.

As I understand it, these fields are already defined; I just need to create an instance of each field.  How do I create an instance of each field, and then configure the extra parameters?

I haven't come across any good tutorials on how to do this.

This has been asked before, for a brief example see Clive's answer here. The easiest thing to do is:

create your field and attach it to an entity with the UI logged in at: Admin -> Structure -> Content Types -> Manage Fields
use the code snippet in the below link, supplying your own $entity_type, $field_name and $bundle_name to get the field_create_instance() code outputted directly for you to copy/paste into your modules' hook_install().
...if you get good enough to know the Drupal Field API to build these $settings and $config arrays for fields without this code snippet -- more power to you .... I still use this code snippet myself, it saves time.


Deleted 'Glossary View' by mistake D8 Is there any way I can get back the default Glossary View which I deleted by mistake?

If you are exporting and importing your configuration, you can simply re-import config from your last export. If you are not doing that already, you should definitely learn how to do so.

If you don't have the view exported, one way to get it back is to create another Drupal 8 site in your local development environment and then go to the config single export page (/admin/config/development/configuration/single/export) and choose Configuration type View and Configuration name Glossary.

Then go to your other site and choose "Import" and import the code.

For reference, here is my export (Drupal 8.4-rc2):

uuid: 350860b2-753f-4774-b504-5cc14b62c099
langcode: en
status: false
dependencies:
  config:
    - system.menu.main
  module:
    - node
    - user
_core:
  default_config_hash: '-pCFOVfbt__jaohFffTLnVavh4OBC6CjREAnchiRomQ'
id: glossary
label: Glossary
module: node
description: 'All content, by letter.'
tag: default
base_table: node_field_data
base_field: nid
core: '8'
display:
  default:
    id: default
    display_title: Master
    display_plugin: default
    position: 0
    display_options:
      query:
        type: views_query
        options:
          query_comment: ''
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_tags: {  }
      use_ajax: true
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: mini
        options:
          items_per_page: 36
          offset: 0
          id: 0
          total_pages: 0
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          tags:
            previous: ‹‹
            next: ››
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: Title
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: node
          entity_field: title
        name:
          id: name
          table: users_field_data
          field: name
          label: 投稿者
          relationship: uid
          plugin_id: field
          type: user_name
          group_type: group
          admin_label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: user
          entity_field: name
        changed:
          id: changed
          table: node_field_data
          field: changed
          label: 前回の更新
          type: timestamp
          settings:
            date_format: long
            custom_date_format: ''
            timezone: ''
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: node
          entity_field: changed
      arguments:
        title:
          id: title
          table: node_field_data
          field: title
          default_action: default
          exception:
            title_enable: true
          default_argument_type: fixed
          default_argument_options:
            argument: a
          summary:
            format: default_summary
          specify_validation: true
          glossary: true
          limit: 1
          case: upper
          path_case: lower
          transform_dash: false
          plugin_id: string
          relationship: none
          group_type: group
          admin_label: ''
          title_enable: false
          title: ''
          default_argument_skip_url: false
          summary_options: {  }
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          entity_type: node
          entity_field: title
      relationships:
        uid:
          id: uid
          table: node_field_data
          field: uid
          plugin_id: standard
          relationship: none
          group_type: group
          admin_label: author
          required: false
      style:
        type: table
        options:
          columns:
            title: title
            name: name
            changed: changed
          default: title
          info:
            title:
              sortable: true
              separator: ''
            name:
              sortable: true
              separator: ''
            changed:
              sortable: true
              separator: ''
          override: true
          sticky: false
          grouping: {  }
          row_class: ''
          default_row_class: true
          uses_fields: false
          order: asc
          summary: ''
          empty_table: false
      row:
        type: fields
        options:
          inline: {  }
          separator: ''
          hide_empty: false
          default_field_elements: true
      header: {  }
      footer: {  }
      empty: {  }
      sorts: {  }
      filters:
        langcode:
          id: langcode
          table: node_field_data
          field: langcode
          relationship: none
          group_type: group
          admin_label: ''
          operator: in
          value:
            '***LANGUAGE_language_content***': '***LANGUAGE_language_content***'
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            reduce: false
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: language
          entity_type: node
          entity_field: langcode
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }
  attachment_1:
    id: attachment_1
    display_title: 添付
    display_plugin: attachment
    position: 2
    display_options:
      query:
        type: views_query
        options: {  }
      pager:
        type: none
        options:
          offset: 0
          items_per_page: 0
      defaults:
        arguments: false
      arguments:
        title:
          id: title
          table: node_field_data
          field: title
          default_action: summary
          exception:
            title_enable: true
          default_argument_type: fixed
          default_argument_options:
            argument: a
          summary:
            format: unformatted_summary
          summary_options:
            items_per_page: 25
            inline: true
            separator: ' | '
          specify_validation: true
          glossary: true
          limit: 1
          case: upper
          path_case: lower
          transform_dash: false
          plugin_id: string
          relationship: none
          group_type: group
          admin_label: ''
          title_enable: false
          title: ''
          default_argument_skip_url: false
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          entity_type: node
          entity_field: title
      displays:
        default: default
        page_1: page_1
      inherit_arguments: false
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }
  page_1:
    id: page_1
    display_title: Page
    display_plugin: page
    position: 1
    display_options:
      query:
        type: views_query
        options: {  }
      path: glossary
      menu:
        type: normal
        title: Glossary
        weight: 0
        menu_name: main
        parent: ''
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }


How to use custom tables in any views? I have created a custom table in drupal database. I need to use this table data in views . For this I have used schema module but its displaying only new views. But I need to use these table data in all views in our site.

Any suggestions?

You can use hook_views_query_alter and alter the views query by merging your custom query with the views SQL query itself.

Also there is an option in "advanced" section - theme suggestions
There you can write your custom query to fetch results into tabular format.


How can I enable unauthenticated user to activate himself? How can I enable unauthenticated user to activate himself? not to wait for administrator activation.

Provided we're talking about Drupal 7:

Navigate to: Administration » Configuration » People »  Account settings.
Under: "Registration and cancellation. Who can register accounts?", check the radio button for "Visitors".
Click "Save configuration" at the bottom of the page.


Can't edit settings.php in Drupal 7 - Premission Denied - Can't Write to File via Cpanel File Manager Trying to edit settings.php via Cpanel File Manager

I can CHMOD the file to anything I want and back but can't write to it.

I get the following message:

  Could not write /home/testing/public_html/sites/default/settings.php: Permission denied

Do you think Apache suEXEC has anything to do with this?

As others have mentioned, you must set the permissions on the /sites/default folder. The default permissions are set to 0555, set them to 0755 for editing. Don't forget to restore the default values afterwards!


"Page not found" when accessing a custom module I have created the custom registration module for drupal8. I define the path on routing.yml file but when access that module on browser side I got "Page not Found" message.  Here the sample code.

custom_form.routing.yml

    custom_form.register:
path: '/custom_form/my_form'
defaults:
 _form: '\Drupal\custom_form\Form\Formsettings'
 _title: 'Registration page'
 requirements:
  _permission: 'view user registration form'

custom_form.module

error_reporting(E_ALL);
ini_set("display_errors", 1);
/**
*@file
*custom_form.module
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implementation of hook_permission()
*/

function custom_form_permission() {
  return array(
    'submit custom_form' => array(
      'title' => t('Submit custom_form'),
      'description' => t('Submit the custom_form Form'),
    ),
  );
}

/**
* Implementation of hook_menu()
*/
function custom_form_menu() {
$items=array();
    $items['custom_form/my_form'] = array(
     'title'=> 'My Example Form',
     'route_name' => 'custom_form.register',
     );
    return $items;
  }

As stated, YAML has very specific spacing rules.

custom_form.register:
  path: '/custom_form/my_form'
  defaults:
    _form: '\Drupal\custom_form\Form\Formsettings'
    _title: 'Registration page'
  requirements:
    _permission: 'view user registration form'

Try that spacing, and Formsettings will need to be a form controller in custom_form/src/Form if it isn't already - you didn't link to it.

Both hook_permission() and hook_menu() are no longer used, so you'll want to remove them from the code base. (though I don't think they will stop it from loading properly.)


Responsive images with multiple fields I'm working on a site that has (and must have) three image fields for out three breakpoints. We could call them field_img_mobile, field_img_tablet and field_img_desktop

Is there a way (a module?) that could load the image field corresponding to the breakpoint?

I think Picture module help you to solve your query.

Please check Responsive Images in Drupal with the Picture Module.

OR you can try these also :

Flickr
Responsive images and styles


How do I correctly add cache information for breadcrumb parts? Visiting a node Foobar a breadcrumb gets created which adds the parent menu structure like so:

$currentPluginId = $menu_link->getPluginId();
$trailIds = $this->menuActiveTrail->getActiveTrailIds('main');

foreach (array_reverse($trailIds) as $key => $value) {
  if ($value && $value !== $currentPluginId) {
    // @todo add cache per item
    $instance = $menu_link_manager->createInstance($value);
    $breadcrumb->addLink(
      new Link(
        $instance->getTitle(),
        $instance->getUrlObject()
      )
    );
  }
}

$breadcrumb->addCacheContexts(['route.menu_active_trails:main']);

So the breadcrumb looks like:

  Home > John Doe > Foobar

But if the node/ menu item of John Doe changes, the breadcrumb for Foobar stays the same.

dpm($instance->getUrlObject()->getRouteName());
dpm($instance->getUrlObject()->getRouteParameters());

gives me:

  entity.node.canonical

and

  array(
      [node] => 25 )

How can I use that for adding each breadcrumb part as cache context/ tag?

Look at \Drupal\book\BookBreadcrumbBuilder::build() for an example. You'll want to add the cacheability metadata (or at minimum the cache tags) of the node/menu item John Doe.

So:

$breadcrumb->addCacheableDependency($entity);

You could have easily figured this out yourself: you're building a \Drupal\Core\Breadcrumb\Breadcrumb object… which implements RefinableCacheableDependencyInterface, and that interface lists all things related to cacheability.

I highly recommend you read https://www.drupal.org/developing/api/8/cache and all documentation it points to.


Showing a node with a Views? I have a bundle "Text" and bundle "Protocol". The "Protocol" bundle has a field of Entity Reference type which links the "protocol" node with texts that were accepted during that protocol. (I.e. the join is somewhat like "Protocol"->"Text") Also Protocol has following fields: a protocol number (integer) and a date (date-iso)

While viewing "Text"-type node there will be shown information about the corresponding protocol:its number and acceptance date (mention them above).

So the question is: is it a good practice to show this pages via Views? Owing to its Relations feature, obtaining of information related to the corresponding protocol is really easy. But idea itself seems to me being of kinda "bad Drupal way", because there is a standard way of displaying nodes in Drupal.

If the Views is really bad idea, then how should I obtain the protocol's number and date, from tpl.php (or preprocessor function)? Any variants?

Views can be a little heavy, and if you don't need the module it's lighter just to drop it.

If you just want to grab some info for a template, you could also do it with Entity Field Queries.


SQL function with EntityFieldQuery Is there a way to use SQL functions with the EntityFieldQuery class?

What I am trying to do is something similar to the following code:

$query_user = new EntityFieldQuery;

$query_user
->entityCondition('entity_type','user')
->fieldCondition('MD5(user+pass)',null,$user_token,'=')

The interesting part is the EntityFieldQuery::fieldCondition() call.
Obviously this it isn't working, otherwise I would not ask this question.

No. The whole point of EntityFieldQuery is that it is SQL-agnostic, so you can switch from MySQL to MongoDB for example, and it still works.


How do I add a site to a multi-site I am trying to convert my installation to a Drupal multi-site.
I have the original site (www.original.com) with a settings.php file under the sites/default folder. I want to add a new site by adding the following files.

sites/original2.com/sites.php
sites/original2.com/settings.php

I can access both URLs, but they use the default.settings.php file.
I have not changed anything in NginX as both URLs are resolved from Drupal on my docker instances.

You have the sites.php file in the wrong spot, it should be at sites/sites.php, it should not be inside any of the site directories, such as sites/original2.com/sites.php.


User added with Drush not working So, I have to work on a D8 site I don't have a user account for. So, when I brought the code and database over to my local environment, I thought this would be an easy fix for drush.

My local dev environment is an Ubuntu server running on WSL, with php 7.2, and Drush version 8  I used the Drush ucrt and urol in the terminal, and both returned successes. I also had to temporarily deactivate the basic_auth service as the login pages weren't accessible after the move. Finally, when I tested the new user and password, it didn't work. I cleared the caches, re-set the password again, and then finally had the account blocked from too many failed attempts.

What's going on here? why didn't this work? and what do I do to make it work? I'd rather not add the user in Mysql, as I haven't seen a good tutorial for this.

what i personally usually do with local databases is overriding the admin password:

drush uinf 1

will help you to get the user 1 name (just to be sure it is 'admin')
in that case :

drush upwd admin --password=MY_LOCAL_PASSWORD

then go to /user and try it :)


Override html.twig.html within custom module According to this Drupal 7 answer, I'm looking for a Drupal 8 solution to simply print the page content within a custom html.twig.html.

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class CustomModuleController extends ControllerBase {

  public function content() {

    return [
        '#theme' => 'custommodule_page',
        '#type' => 'page',
    ];
  }
}

This approach seems to be working, but I am not sure how I can remove the core and theme CSS components.

You can completely take over the printed page if your return value is an extension of Symfony's Response class.

Here your return value is a render array so Drupal assumes it is to be rendered in a normal HTML page.

This complex looking diagram shows the flow of request to response:  You can read more about the diagram here: https://www.drupal.org/developing/api/8/render/pipeline

The first takeaway on that docs page is

  Routes whose controllers return a Response object bypass the pipeline below. They rely directly on the Symfony render pipeline.

In other words, most of the complexity of that diagram covers the case where the return value of a controller is NOT a Response object. Returning a Response object cuts out what Drupal normally does to wrap the render array in the html.html.twig file.

There are a lot of examples in core of direct returning of a response object. Here is one:

public function testFeed($use_last_modified, $use_etag, Request $request) {
  $response = new Response();

  $last_modified = strtotime('Sun, 19 Nov 1978 05:00:00 GMT');
  $etag = Crypt::hashBase64($last_modified);

  $if_modified_since = strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE'));
  $if_none_match = stripslashes($request->server->get('HTTP_IF_NONE_MATCH'));

  // Send appropriate response. We respond with a 304 not modified on either
  // etag or on last modified.
  if ($use_last_modified) {
    $response->headers->set('Last-Modified', gmdate(DateTimePlus::RFC7231, $last_modified));
  }
  if ($use_etag) {
    $response->headers->set('ETag', $etag);
  }
  // Return 304 not modified if either last modified or etag match.
  if ($last_modified == $if_modified_since || $etag == $if_none_match) {
    $response->setStatusCode(304);
    return $response;
  }

  // The following headers force validation of cache.
  $response->headers->set('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
  $response->headers->set('Cache-Control', 'must-revalidate');
  $response->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');

  // Read actual feed from file.
  $file_name = drupal_get_path('module', 'aggregator_test') . '/aggregator_test_rss091.xml';
  $handle = fopen($file_name, 'r');
  $feed = fread($handle, filesize($file_name));
  fclose($handle);

  $response->setContent($feed);
  return $response;
}


User profile form make custom form required I'm trying to use a hook to make a user field (company name) required based on assigned roles so:

if($form['#id'] == 'user-profile-form') {
  dsm($form);
  if (!in_array('BPSA user', array_values($user->roles))) {
    $form['field_dealership']['#type'] = 'hidden';
    $form['field_company_name']['und']['#required'] = 1;
    $form['field_company_name']['und'][0]['#required'] = TRUE;
  } else {
    $form['field_company_name']['#type'] = 'hidden';
  }
}

It's not working and I can't find any other 'required' form elements?

Ps I know this would only rewrite if the user was not a BPSA user.

Thanks,

Steve

Try the following code to set a field to required.

$form['field_company_name']['und']['0']['value']['#required'] = TRUE;


Taxonomy term page $content is empty but shows up later I have a taxonomy override page called taxonomy-term--listing-category.tpl.php.

As far as I'm aware I'm supposed to (as per documentation) use <?php render($content); ?> when the part in my template comes to spill all the items (teasers) associated with the taxonomy term.  I'm fine with this.

Except it's empty.

Let me be clear, there are 14 items associated with this term, and they do show up, after my template in the HTML structure, as if I missed it in my template and Drupal is trying to pick up my slack.

Using Xdebug (hooked into my phpstorm) I have discovered that the $content array is 0, it's empty. None of the node items associated with the taxonomy term is available to display IN my template, they simply don't exist in any registered variable.  And as such, shows up AFTER my template.

What gives?

I was stuck on this myself and went hunting for the answer.

From my understanding, taxonomy_term_page generates data for a page. Therefore, the $build variable outputs its content to a page template and that's why you see it after the theme template.

The $content variable in the theme template, taxonomy-term.tpl.php, should contain the description or any fields you have created for the term.


xmlrpc() error: (-1001) unable to parse URL during Drush command I have an odd error coming from Drush when I perform module updates and other commands (it's most consistently comes from module updates). Near the end of the command execution this message pops up:

  xmlrpc() error: (-1001) unable to parse URL

Some cursory Googling produces that its likely an error popping up in drupal_http_request. I'm not sure where however since I'm not too familiar with the Drush code base.

I ran drush with the --debug switch for more information but that didn't tell me much other than this message typically pops up after the drush_cache_command_clear() being executed.

What is causing this error?

Turns out the issue was the APC module. After some testing I was able to isolate the issue during cache clear.

[shawnconn@host www]$ drush cc all
'all' cache was cleared.                                                                                [success]
xmlrpc() error: (-1001) unable to parse URL                                                                                [error]
[shawnconn@host www]$ drush dis apc
The following extensions will be disabled: apc
Do you really want to continue? (y/n): y
apc was disabled successfully.                                                                                [ok]
You need to enable the APC module for remote cache clearing to work. Run drush pm-enable apc.                                                                                [error]
[shawnconn@host www]$ drush cc all
'all' cache was cleared.                                                                                [success]
[shawnconn@host www]$


How to get the part of URI and pass it to as a argument? I can access current path using method \Drupal::request()->getRequestUri(); as shown below.

    function bartik_preprocess_node(&$variables) {
        $variables['current_path'] = \Drupal::request()->getRequestUri();
    }

Now, this is giving me path, /drupal8101/user/1 if I am on the user1 profile page. (Complete path of site:http://localhost:8888/drupal8101/user/1), which is working right.

So, if I want to put any argument in the twig file, it is fulfilling only for /drupal8101/user/1, that is understood.

    {% if current_path == '/drupal8101/user/1'%}
       .............
    {% endif %}

In above case it is working fine, But what can I do to get that condition worked for all users like /drupal8101/user/*.

In short, I want following kind of thing,

    {% if current_path == '/drupal8101/user/*'%}
       .............
    {% endif %}

Probably what you want to do, is to make some logic for the route name instead of the path.

So the user profile page has the route named entity.user.canonical which has the path /user/{user}. So if you compare on the route name, you will get all user profile pages. This also makes it very easy to limit your selection so you can do something different for the user edit page etc/

Anyways to get the current route you can do

$variables['current_route'] = \Drupal::routeMatch()->getRouteName();

\Drupal::routeMatch() is a shortcut for the current_route_match service.


Drush and mysql database (with MAMP) connection problem I have a problem running some drush methods involving database connection.
I run the free version of MAMP.

If I run methods like si or pml I get no problems

But if I run the drush archive-dump method I get this error message:

Database dump failed.

look the capture:

The problem seems to be in mysql.sock location. I found a solution from here:
http://www.razorsql.com/docs/support_mysql_mac_mamp.html

Short answer

  One way to change the socket location is to edit the MAMP start and stop scripts so that the mysql.sock location is the default. This can be done by editing the following files:

  /Applications/MAMP/bin/startMysql.sh

  /Applications/MAMP/bin/stopMysql.sh

  Replace

  socket=/Applications/MAMP/tmp/mysql/mysql.sock

  with

  socket=/tmp/mysql.sock

How I solved the problem

I did

drush ard -v

to see what was going on.

Executing: mysqldump --result-file /tmp/drush_tmp_1352892897_50a381e13a71d/... --no-autocommit --single-transaction --opt -Q  ... --host=localhost --user=... --password=...
Database dump failed.

So I copied the mysqldump command and copied it to the command line and hit enter.

mysqldump: Got error: 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) when trying to connect.

After this I tried several methods to solve the socket issue after I found the solution from www.razorsql.com.


what is the purpose of site_key? In ROOT/modules/update/update.fetch.inc, there is the following code.

$site_key = drupal_hmac_base64($base_url, drupal_get_private_key());
$url = _update_build_fetch_url($project, $site_key);

_update_build_fetch_url() contains the following code.

  // Only append usage information if we have a site key and the project is
  // enabled. We do not want to record usage statistics for disabled projects.
  if (!empty($site_key) && (strpos($project['project_type'], 'disabled') === FALSE)) {
    // Append the site key.
    $url .= (strpos($url, '?') !== FALSE) ? '&' : '?';
    $url .= 'site_key=';
    $url .= rawurlencode($site_key);

    // Append the version.
    if (!empty($project['info']['version'])) {
      $url .= '&version=';
      $url .= rawurlencode($project['info']['version']);
    }

    // Append the list of modules or themes enabled.
    $list = array_keys($project['includes']);
    $url .= '&list=';
    $url .= rawurlencode(implode(',', $list));
  }

This function generates the URL to fetch information about project updates, returning a URL like http://updates.drupal.org/release-history/examples/7.x?site_key=FuSSIDdX3JtCJQV7F1hWK6WopklCLf0jjHFDC1Nevys&version=7.x-1.x-dev&list=ajax_example%2Cexamples.

Why does Drupal need site_key? How do I know the value of $base_url from site_key?

It's a unique value that allows to identify the site asking for updates. It is used on Drupal.org when giving the number of site using a module, which is shown in every project page.

Without that value, Drupal.org could not report the number of sites using a module, since it could not understand which site is asking for updates.

Since site_key is a crypted hash derived from $base_url, you cannot get the value of $base_url from its hash; that is how hash works. Hashes are used to save the passwords in the database; nobody can get the value of the password from the hash saved in the database.


Flags - Recreate the 'poke' function I need to create a flags view that displays a list of users that have "poked" the current user with D7, Views 3 and Flag 3. I've read through this question and drupal.org/node/296971, neither instruction seems to work or at least I am not able to get the settings right.

To define the functionality:

Users are presented with a list view of other users
Users click the "poke" flag link on a single user
Users then browse to /pokes/ and view all other people that have poked them

This is either a difficult setup or I'm missing a couple settings (the latter is extremely likely). Any hints or thoughts?

I created a test site with Flag and Views module enabled and so far, I could create a view to display users who have poked me.

Create a new Flag to flag users. This don't have to be a global flag. Flag text could be "Poke" and unflag text could be "remove".

  Users are presented with a list view of other users
  Users click the "poke" flag link on a single user

Create a view on users table
Add a new relationship: Flags: User.
Uncheck "Include only flagged content "; Choose the poke flag; By: Current user.

You will see a new field "Flags: Flag link". Add it.

You will now get a view that shows users and a flag link to flag them. Modify the View as you wish.
http://paste2.org/CGZshUFN

  Users then browse to /pokes/ and view all other people that have poked
  them

This is a really tricky part.

Create a new View on users table.
Add a new relationship: Flags: User flag.
Uncheck "Include only flagged content "; Choose the poke flag; By: Any user.

Add a new contextual filter: Flags: Content ID
Under contextual filter settings, choose the just-added relationship and set to user the current logged in user ID.

Now we have access to a list of user IDs that has flagged the currently logged in user.
Add a new relationship: Flags: User
Under this relationship's settings, check "require this relationship".
Add a new field: User: name and choose the relationship created in step #7.
Add a new relationship: Flags: User flag (yes, you are added one already in step 2 but go ahead).
Under this relationship's settings, choose the the user relationship created at step #7. Uncheck "include only flagged content"; By: current user.

Add a new field: Flags: Flag link and choose the relationship created at step #10.
http://paste2.org/tkWg99vp

Above step 12 will add the "flag back" type link that the user can see a list of users who have flagged the current user and a link to flag them back.
You will need many Views template tweaks to adjust the wording of the View to suit your need.

Good luck!


How to get absolute url with different domain language prefix What is the best way to get absolute url with correct language prefix?
The url() function accepts language parameter but it seems that it is not using it to generate the prefix - only to get translated alias. I don't care about aliases - I need correct domain prefix.

When I'm on http://en.example.com/something and use this code:

<?php
$all_languages = language_list();
url('something-else', array('language' => $all_languages['nl'], 'absolute' => true));
?>

I will get this: http://en.example.com/something-else (en prefix).

How can I get this: http://nl.example.com/something-else (nl prefix).

This was pulled from my theme file, but as long as you have access to $node and $language, it will do the trick:

<?php
    if (isset($node))
    {
?>

        <?php
            $nodes = translation_path_get_translations("node/" . $node->nid);
            $path  = "";
            if ($language->language == "en")
            {
                if (array_key_exists("nl", $nodes))
                {
                    $path = drupal_get_path_alias($nodes["nl"], "nl");
                }
        ?>
        <a href="http://nl.example.com/<?php print $path; ?>">Change to NL
        <?php
            }
            else
            {
                if (array_key_exists("en", $nodes))
                {
                    $path = drupal_get_path_alias($nodes["en"], "en");
                }
        ?>
        <a href="http://en.example.com/<?php print $path; ?>">Change to EN
        <?php
            }
        ?>

<?php
    }
?>

The URL's are hard coded with the path information calculated.