Warning: strlen() expects parameter 1 to be string, array given in drupal_validate_utf8() I have been getting this error: Warning: strlen() expects parameter 1 to be string, array given in drupal_validate_utf8().

After troubleshooting I was able to figure out line that cause this error that is on a if stament.

  if (empty ($form_state['num_boxes'])) { // Line with the problem.
    $form_state['num_boxes'] = count($boxes) + 1;
  }

After researching I believe that have to deal something with filter_xss_admin. However, it seem unclear to me of how to implement with my code.

Update 1 - Apparently, the code that I provide did not show the error. I have provide more code.

/**
 * Form builder.
 */
function custom_module_overview_form($form, &$form_state) {

  $form['#tree'] = TRUE;
  $boxes = variable_get('custom_module_package_sizes', '');
  if (empty($form_state['num_boxes'])) {
    $form_state['num_boxes'] = count($boxes) + 1;
  }

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

  for ($i = 0; $i < $form_state['num_boxes']; $i++) {
    $form['sizes'][$i] = array(
      '#type' => 'fieldset',
      '#title' => t('Package'),
      '#description' => t('Enter the dimensions of the packing box.'),
      '#attributes' => array('class' => array('physical-dimensions-textfields')),
      '#attached' => array('css' => array(drupal_get_path('module', 'physical') . '/theme/physical.css')),
    );

    foreach (physical_dimensions() as $key => $dimension) {
      $form['sizes'][$i][$key] = array(
        '#type' => 'textfield',
        '#title' => filter_xss($dimension)['name'],
        '#size' => 15,
        '#maxlength' => 16,
        '#field_suffix' => '&times;',
        '#prefix' => '
',
        '#suffix' => '
',
      );

      if (isset($boxes[$i][$key])) {
        $form['sizes'][$i][$key]['#default_value'] = $boxes[$i][$key];
      }
    }
    unset($form['sizes'][$i][$key]['#field_suffix']);

    $form['sizes'][$i]['unit'] = array(
      '#type' => 'select',
      '#options' => physical_dimension_unit_options(FALSE),
      '#prefix' => '
',
      '#suffix' => '
',
    );

    if (isset($boxes[$i]['unit'])) {
      $form['sizes'][$i]['unit']['#default_value'] = $boxes[$i]['unit'];
    }
  }

  $form['packing_add_more'] = array(
    '#type' => 'submit',
    '#value' => t('Add More'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#submit' => array('custom_module_admin_add_more_submit'),
    '#ajax' => array(
      'callback' => 'custom_module_admin_add_more',
      'wrapper' => 'boxes-fieldset-wrapper',
    ),
  );

  $form['packing_submit'] = array(
    '#type' => 'submit',
    '#prefix' => '
',
    '#suffix' => '
',
    '#value' => t('Save'),
  );

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

  return $form;
}

Update 2 - I believe that the issue is in this block

foreach (physical_dimensions() as $key => $dimension) {
          $form['sizes'][$i][$key] = array(
            '#type' => 'textfield',
            '#title' => filter_xss($dimension)['name'], // Removing this line would make the page disappears.
            '#size' => 15,
            '#maxlength' => 16,
            '#field_suffix' => '&times;',
            '#prefix' => '
',
            '#suffix' => '
',
          );

On the line '#title' => filter_xss($dimension)['name'],

How can I fix this issue ?

To solve this issue I had to change this line  '#title' => filter_xss($dimension)['name'], to this On the line '#title' => filter_xss($dimension['name']),


build an admin view of all available rules (rules module), a better rules UI is there a hook to build an admin view of all available rules (rules module) to build a better rules UI? it may be a table view, so we can apply filters and groups, and order them, like in weight, tag, event, etc. I have sites with 30-40 rules running and sometimes (too many) is difucult to figure out a map of a time-event-order-actions taken on site, seeking a better planification and manteinace. A view with the available elements could help a lot.
code is welcome.

I am not aware of any hooks but rules_filter looks promising.


nested views of main CT and sub CT What I want to achieve is nested view.

Say I have Content Type 'main' en Content Type 'sub'

How can I create a view that looks like this:

main 1 title
main 1 fields
    sub 1 title
    sub 1 fields

    sub 2 title
    sub 2 fields

    ...

main 2 title
main 2 fields
    sub 4 title
    sub 4 fields

    sub 5 title
    sub 5 fields

    ...

...

Do I need references?

more context:
I know there is something like entity-reference and also the use of tags.
For every sub I placed 'main 1', 'main 2' or 'main 3' as a tag.
I also let every sub refer to content 'main 1' , 'main 2' or 'main 3' with the entity reference (set on main)
I tried already by creating a view of 'main' and a block view for each 'sub' with tag as extra filter. I don't know though how to make the view 'main' implement each 'sub' view and place it in each main node.
Is this clear or do you need more info? If so, which ?

Have a look at the Views Accordion module, and its related Community documentation.

By "grouping fields", the group header can be used as accordion header. And Views allows for one field to include the content of multiple fields, so you can utilize this views feature for this purpose (Combined fields).

Does this help somehow?


Using views how to display taxonomy term description in D6? How can I display taxonomy term description next to taxonomy term in a views field?

Create a new view of the type 'Term'. (D6: Select Term radio button while adding new view, D7: Choose Taxononomy Terms in 'Show' select box)

Then choose the fields

Taxonomy: Term Term
Taxonomy: Term description

that's it, and you can choose  a suitable Style for the display


Drupal 8 Migrate Plus - CSV Row Number as key In the Drupal 7 migrate module, you can use 'csvrownum' as the mapping key when migrating content from a CSV (https://www.drupal.org/node/1152158). For the Drupal 8 version, I am not sure what the equivalent is. Here is my yml file configuration (migrate plus):

id: timesheet_data
label: Importing Timesheet
migration_group: csvimport
migration_tags:
  - node
  - csvimport
source:
  plugin: csv
  path: 'somepath/timesheet.csv'
  header_row_count: 1
  keys:
    - csvrownum
  column_names:
    0:
      name: Name of Contact
    1:
      address: Address
destination:
  plugin: 'entity:node'
  default_bundle: timesheets
process:
  title: name

I tried this approach thinking it might be similar to the drupal 7 migrate module. I also tried not specifying  a key, both resulted in an error.

I couldn't find a way to do this, but I found out you can specify multiple keys to make the row more unique for mapping.

keys:
- name
- address

When I applied more keys as a mapping, all the records imported since it was more unique.

Hopefully this helps someone else.


What does it mean if expire is set to null in a cache table? I am looking at the documentation for the expire field in the cache tables and the documentation in CacheBackendInterface.php says:

@param int $expire
One of the following values:

CacheBackendInterface::CACHE_PERMANENT: Indicates that the item should not be removed unless it is deleted explicitly.
A Unix timestamp: Indicates that the item will be considered invalid after this time, i.e. it will not be returned by get() unless $allow_invalid has been set to TRUE. When the item has expired, it may be permanently deleted by the garbage collector at any time.

When I look in a cache table, for example cache_render, I see that many entries have NULL in the expire column and I noticed it only get clear on a complete cache clear, such as after running drush cr.
What does a null value set for the expire column in a cache table mean?

Any value for the expire column that is different from CacheBackendInterface::CACHE_PERMANENT (-1) is considered a timestamp, indicating when the cache entry could be deleted. In the case of NULL, the value means the cache entry could be deleted in any moment.
As @4k4 said in his comment, data in cache tables are deleted when cron tasks run, and that doesn't necessarily means immediately.
The only issue with NULL is whether a module is using a not initialized variable which is expected to contain the expiration time. In that case, the cached value is kept in cache less than required.


Open filters in pop-up I have a search field in my view and also some other filters like filtering between 2 dates or filtering between 2 prices.

Now I have something like this:

When I click on Uitgebreid zoeken ... the div pops open like this:

Now I would like to replace the div that pops open when you click on the link with a pop-up. The pop-up should contain all the filters and the apply button.

But I don't now how to start with this. What would be the best solution?

A custom Views template for the exposed form might do it.

wrap it in a div, and use either a custom jQuery or third party pop-up script within the tpl.


Remove authentication in custom REST API resource I have a custom module to create a custom Rest API resource. I want to remove the authentication and make it without required authentication.
In my file custom_moudle/config/install/rest.resource.custom_resource.yml

this is my code

id: custom_resource
plugin_id: custom_resource
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - basic_auth

This is working fine but with authentication. When trying to remove this lines

supported_auth:
  - basic_auth

I got an error. So what is the correct way to remove this authentication?

REST module plugins must have an authentication plugin. Try using the cookie plugin, which is the default one that core uses.


How to import userpoints? The User Points module doesn't have migrate integration yet.
Looking at the API I can probably use userpoints_service_add to assign "starting point" values for each user in a batch script.

Is there an option to update the "starting point" value for a user when I go live? Or do I have to calculate the difference and just add an adjustment?

You want to use userpoints_userpointsapi(), not the service wrapper.

The system is designed to only ever allow new transactions in order to change the total amount of points a user has. So yes, if you want to set it to a fixed value, you need to calculate the difference from the actual amount of points a user has and grant him the difference.


theme table from drupal 6 to drupal 7 I try to rewrite the node output and i don`t get it. This script produce only

without any content.

$rows = array();
$cols = array();

$cols[] = '
' . $node->title[0]['value'] . '
';

$colnum = 0;

foreach($node->field_body as $col){
  $colnum++;
  $cols[] = '
' . $col['value'] . '
';
}

$rows[] = array('data' => $cols);

print theme('table', $rows)

Variables to theme functions must be named:

print theme('table', array('rows' => $rows));

See the documentation for more details.


How do I separate custom template from the administration theme? I have made a custom template for the user_profile_form. I made a module and in the module I added the hook_theme function:

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

  $items['user_profile_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('module', 'myuser'),
    'template' => 'user-account-form',
  );

  return $items;
}

This works as suspected but the theme is also applied in the administration theme. How can I have a custom template for the profile form and retain the original layout from the administration theme?

You can sniff the user's role and/or permissions and then conditionally change the template.

You can test permissions with user_access('view the administration theme') and depending on the result, assign your custom template.


Display formresults in same block as form I have created a module that writes a block with a very simple form in it.

The purpose of it is calculating distance between 2 adresses, one fixed, one asked by the form.

Now I can't get the results to show in the block itself, and I can't find any tutorials on how to do that.

The block shows, the form is in it also, but when i submit a postalcode it seems that nothing happens (also the postcode input field resets to emtpy).

the code that retrieves the distance works also (tested on commandline).

How can I approach this?

The code for my block:

  function reiskosten_block_view($delta = '') {
  $block = array();

  switch ($delta) {
  case 'reiskostenblock':
  $block['subject'] = t('Reiskosten berekenen');
  $block['content'] = drupal_get_form('reiskosten_form');
  break;
  }

The code for submitting the form:

function reiskosten_form_submit($form, &$form_state) {

/* REPLACE SPACE OR HTTP-REQUEST WILL BE MALFORMED */
  $postcode = str_replace(' ','',$form_state['values']['postcode']);

  $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=1024AA|Netherlands&destinations=$postcode|Netherlands&mode=car&language=nl-NL&sensor=false&key=myKey";

$data = drupal_http_request($url);
$result = drupal_json_decode($data->data);

$destination = $result['destination_addresses'][0];
$distance = $result['rows'][0]['elements'][0]['distance']['text'];
$duraton = $result['rows'][0]['elements'][0]['duration']['text'];

  drupal_set_message("$distance");
  $form_state['rebuild'] = TRUE;
}

I want the output of $result to be shown below the submitbutton. It is driving me crazy this one, been puzzling for 5 hours now on this thing (what should be relatively simple imho).

edit:
I also validate on postalcode with:

function reiskosten_form_validate($form, &$form_state) {
  if ( empty($form_state['values']['postcode']) ) {
    form_set_error('postcode', t('Postcode mag niet leeg zijn'));
  }
}

It doesn't throw an error so it seems to me that 'postcode' has a value and the function should be processed.

Solved it. Solution:

in function reiskosten_form_submit($form, &$form_state) {

$result = drupal_json_decode($data->data);
$form_state['results'] = $result;

in function reiskosten_form($form, &$form_state) {

$form['destination'] = array(
  '#markup' => '<div>' . $form_state['results']['destination_addresses'][0] . '</div>',
);

Wrap t in an if to see if the values are there and the magic happens. Pfff


Views Contextual filter: php code for getting the value from url Im trying to set up a Contextual filter in drupal views based on the URL.

The contextual filter is operating with a text field that sets the node alias.

I have it working with "RAW value from URL" based on the position (parentpage/childpage/grandchild-page), but the position could change (only parents and child for example), so do i need to use the "PHP code", or is there a better way?

What i want to happen:

"If last section of page url, (grandchild-page), matches field set in contextual filter, then true (show fields).

Though the solution you have implemented worked but my suggestion is to use the request_uri() instead of the $_SERVER['REQUEST_URI'] because of the following reasons:

$_SERVER['REQUEST_URI'] is only available on Apache, whereas request_uri() generate an equivalent using other environment variables.
Apache does nothing by default to sanitize the $_SERVER variables so directly using it without passing through the check_plain should be considered unsafe.

So its better to get the URL like this:

  $current_url = check_plain(request_uri());

Example: if the url is http://www.example.com/param1/param2/param3 than the $current_url will contain /param1/param2/param3.

Rest you can build the logic to get the last params, there are numerous ways of doing that.


Twig Template for a Custom Block Plugin I'd like to have a custom twig template for custom block plugins from my custom module.

My custom block HeaderText contains

public function build() {
    return array(
        '#title' => 'Test',
        '#color' => $this->configuration['color'],
        );
}

It is located in myplugin/src/Plugin/Block/HeaderText.php

I have a template block--HeaderText.html.twig located in myplugin/templates which only contains test code

{{ title }}

{{ color }}

However the template isn't used. Following a guide I also added the following to myplugin/myplugin.module

function myplugin_theme($existing, $type, $theme, $path){
    return array('myplugin' =>
        array(
            'variables' => array(
                'title' => 'Default title',
                'color' => null
                ),
                'template' => 'block--HeaderText'
            )
        );
}

Which did not work either. And even if the previous code did work, I have multiple plugins within that module and that code seems to apply to every block which I don't want to do. I'd like each block to have a unique template.

This issue I ran into was I did not specify '#theme' in the Block Plugin.

I added

public function build() {
    return array(
        '#theme' => 'myplugin',
        '#title' => 'Test',
        '#color' => $this->configuration['color'],
        );
}

and it worked


Display bare HTML from hook_menu() What would be the cleanest way to route URLs to functions and return only the HTML output from those functions (a.k.a. the menu callback)?

If I use hook_menu() the string that's returned will be the HTML within the rest of the site. I want the page to display only the string returned from the menu callback.

Should I use drupal_set_header() in the same way drupal_json() does? Is this not inefficient having fully bootstrapped Drupal, and then changing the header at the last minute?

I want the fastest code path possible since this is going to be for widgets on external sites.  I could start with a standalone .php file and bootstrap what I need but the hook_menu routing is nice.

How should you do this?

To show only the output of the callback, and not the complete page Drupal would render, output the HTML using print or echo; if you return the HTML output as string, Drupal will render the normal Drupal page, which includes the HTML your callback returns.

The code contained in index.php that causes this behavior is the following one:

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

drupal_set_header() is used from drupal_json() to change the content type of the output (the "Content-Type" metadata); normally Drupal will set it to "text/html" which is not appropriate for what returned from a callback returning JSON; in that case, the content type that allows the requester to handle the output correctly is "text/javascript."


Is there a way to make a body field automatically become the first comment on a node? Im on d7, I want my body field (or any textfield attached to a content  type really) to automatically become the first comment on its node. Any suggestions?

Without coding, I'd go for the module Rules :
You can create action that are triggered after certain events, under certain conditions.
In your case you can try to create a rule like this one :

Event : When a Node is Created
Conditions : You probably want to filter the node type maybe ?
Action : Create an entity

Select Comment as your entity type
Node referencing the comment : Use the available token "node" (the newly created node that triggered your rule)
Comment body : Use the available token node:body

And you're done .. 0 code, 1 module, 2 mins to setup your rule :-)


Add block programmatically in the right region I have followed the instruction to create a new block here which is basically the same as here on SE. My block is indeed created but the region is wrongly set to "none" instead of "Content Post".

In my module events.module file:

function events_block_info () {
    return [
        'events_list' => [
            'info'       => "Events list",
            'region'     => 'content_post',
            'visibility' => BLOCK_VISIBILITY_NOTLISTED
        ]
    ];
}

function events_block_view ($delta = '') {
    $result = false;
    if ($delta == 'events_list') {
        /* ... do my stuff .... */
    }

    return $result;
}

This creates a block but the region is set to "none". The drawback is I have to go on each environment and change the region manually back to "Content Post". It is inefficient.

I also find it extremely weird that the creation of a block is done this way. I would expect instead that the creation takes place in the module.install file in the hook_install() function. Maybe there is way?

I think you need to set 'status'.
eg.

function events_block_info () {
    return [
        'events_list' => [
            'info'       => "Events list",
            'status'     => TRUE,
            'region'     => 'content_post',
            'visibility' => BLOCK_VISIBILITY_NOTLISTED
        ]
    ];
}


Construct the src in a javascript tag from node fields I have a drupal 7 instance where I would like to create nodes that call reports from a separate site using javascript.

Currently I construct the HTML tags myself which look something like this:

<script type="text/javascript" src="http://URL.goes.here/JsAPI?reportUUID=[REPORTID]&amp;yfFiltera5d74aca-4396-41c2-9376-d68fd57de81a=[FILTERVALUE]&display=[DISPLAY]&canChangeDisplay=[CANCHANGEVALUE]&showPageLinks=[SHOWPAGESVALUE]&showInfo=[SHOWINFOVALUE]&showFilters=[SHOWFILTERSVALUE]&showSections=[SHOWSECTIONSVALUE]"></script>

Note that there are a bunch of parameters in the url shown in square brackets: [VALUE]

What I want to do is have a node creation interface for admin users that allows them to set all of the parameter values and constructs that URL, then constructs a string using those parameters and uses it as the node's output when viewed.

I haven't been able to find any kind of module for this, maybe I am describing it wrong - or maybe it's a very rare use-case.  Any ideas would be wonderful, even if it's 'hire a developer, this has never been done before'.

You can do this in a node.tpl.php file in your theme or to be specific to one content type.

Duplicate the default node.tpl.php file found in /modules/node/ and rename it to node-NODETYPE.tpl.php NODETYPE being the machine name of the node which you can find at structure -> content types, in the CMS.

Install the devel module and enable it, then do a dpm($node); in your copied node.tpl.php file to get the variables you need. Of course you would need to have a custom theme so it doesn't get overridden on an update.

To do this in a module you'd need be somewhat familiar with hooks.

And since the dpm is called after the output is rendered you need to reload the page twice.
Don't forget to clear cache after you add in the node.tpl.php to your theme.


Date picker libraries are missing in specific page I am adding jquery date picker feature using date field in profile edit page it is working fine .

But when i am adding same jquery datepicker in custom module, datepicker function is not working.

After seeing view page source i have found these three libraries are including in profile edit page where date picker is working.

<link rel="stylesheet" href="/core/assets/vendor/jquery.ui/themes/base/datepicker.css?q7wdca" media="all" />
<script src="/core/assets/vendor/jquery.ui/ui/widgets/datepicker-min.js?v=1.12.1"></script>
<script src="/core/modules/locale/locale.datepicker.js?v=8.6.15"></script>

But i am not able to figure out why these libraries are not including in custom form page.

Do you have a custom theme? If so, the easiest way to ensure jquery.ui.datepicker loads on every page is to list it as a dependency in your theme libraries file. E.g.

# @file /themes/custom/my_theme/my_theme.libraries.yml

# My theme global library.
global:
  js:
    js/my_theme.js: {}
  css:
    theme:
      css/my_theme.css: {}
  dependencies:
    - core/jquery
    - ...
    - core/jquery.ui.datepicker

Alternatively, you can add it via a theme or custom module.

/**
 * Implements hook_preprocess_page().
 */
function my_theme_or_module_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'core/drupal.date';
}


I want to subscribe an user to a Mailchimp list as soon as their account is activated I want to subscribe an user to a Mailchimp list as soon as their account is activated. I've created a module to use hook_user_presave() and am trying to call mailchimp_subscribe_user() after that.

function mymodule_user_presave(&$edit, $account, $category) {
  if ($account->uid // user is not new
      && $account->status === "0" && $edit['status']==1) { // user is being activated
        $list_id = 1;
        $list = mailchimp_get_list($list_id);
        $mergevars = mailchimp_lists_load_user_mergevars($account, $list);

        watchdog('mymodule_log', 'account->uid '.$account->uid);
        watchdog('mymodule_log', 'list->id '.$list_id);

        mailchimp_subscribe_user($list, $account->mail, $mergevars, FALSE);

        watchdog('mymodule_log', 'got this far!');
  }
}

$account-uid has a valid value and so does $list_id. The problem that does show is up is this

Notice: Trying to get property of non-object in mailchimp_subscribe_user()
            (line 103 of .../sites/all/modules/mailchimp/mailchimp.module).
Notice: Trying to get property of non-object in mailchimp_subscribe_user()
            (line 105 of .../sites/all/modules/mailchimp/mailchimp.module).
Notice: Trying to get property of non-object in mailchimp_subscribe_user()
            (line 116 of .../sites/all/modules/mailchimp/mailchimp.module).

The lines-

$double_optin = $list->settings['doublein']; //line 103

$success = $mcapi->listSubscribe($list->mc_list_id, $email, $merge_vars, 'html', $double_optin, TRUE);  //line 105

mailchimp_cache_clear_user($list->mc_list_id, $email); //line 116

And is there any better way to achieve this?

Try below code ... You are missing 5th argument in mailchimp_subscribe_user

function mymodule_user_presave(&$edit, $account, $category) {
  if ($account->uid // user is not new
      && $account->status === "0" && $edit['status']==1) { // user is being activated

        $mcapi = mailchimp_get_api_object();
        $list_id = 1;
        $list = mailchimp_get_list($list_id);
        $mergevars = mailchimp_lists_load_user_mergevars($account, $list);

        watchdog('mymodule_log', 'account->uid '.$account->uid);
        watchdog('mymodule_log', 'list->id '.$list_id);

        mailchimp_subscribe_user($list, $account->mail, $mergevars, TRUE, $mcapi);

        watchdog('mymodule_log', 'got this far!');
  }
}


Display Suite Fields not showing I created a bootstrap sub theme and and have enabled display suite.  I have enabled ds extra fields and chose a layout for my content type for full view display.  When going to the full view page of my content none of the ds fields are showing.

I have enabled title, author, post date, submitted by but none of these are showing.  Is there something special you must do to get ds to work on a subtheme?

Which version of Drupal are you using? If 8.3 you may wanna update to DS 8.x-3.0-beta3 which no longer requires the layout plugin module, instead uses "Layout Discovery" in core.

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


How to use Form_submit hook? I have a form, automatically generated by a content type. I want to run a form_submit function to input/change some data to get saved in the database.

The content-type already has these fields setup, but I want them to be determined in a form_submit function rather than via user input.

I can get a form submit function, but I don't know how to add to the array of values being submitted without having to write the whole query myself.  What variables do I need to grab and how to alter them to do this?

To be more specific.. in the form_alter, this does what I want. $form["field_org_id"]["und"][0]['value']['#default_value'] = $org->id;

But how do I do the equivalent out of site in the form_submit? (this is a content-add form and hoping not to rewrite the entire query)

You have to use hook_form_alter or hook_form_FORM_ID_alter
Add your submit handler to $form['#submit'] like this $form['#submit'][]='my_submit'
And write your code:

function my_submit($form, &$form_state) {
  // your code
}


How can I specify language for Parent Item options on node create/update page? The site in question is running Drupal 7 and has a sub-folder structure for the languages. E.g. http://site.tld/ for default language and http://site.tld/en/ for english.

The editors can choose if they want their admin interface in either language by logging in on the user page for any available language.

My problem now is that on the node create/update page, Drupal seems to use the global $language to determine what options to retrieve for the Parent item under Menu settings, rather then using the current node's language.

So if an editor is editing a node in the default language but on the english interface, only english menu items will be in the select list mentioned above. When saving the node, the Parent item will be reset to the base of the menu and the previous menu structure will be lost.

What I want is a way of altering the chosen language for when that option list is being built. I suppose one way would be to use hook_form_alter and rebuild the options for that field, but that doesn't feel like the right way of doing it.

Is there another way of solving this issue?

UPDATED

It doesn't necessarily need to work perfectly. I guess one way would be to have one language neutral menu and then localize the menu items instead. That would bloat the main menu though, especially when there are multiple languages.

Yet another hack would be to do as @reptilex suggested in his answer and then overwrite the admin translations with one language. I'd prefer not to though.

I have a similar problem, I have decided that I don't want to ajax reload the form when the language is changed because things like entity relationships (which is my current problem) don't work even then.

My advice is to force the language of the editing / adding node to be the same as the interface. For creating/ adding this is easy you set it for the content type when you edit the multilingual settings. The translation interface redirects correclty and the content creation too (it expects you to be in the language you want to create).

So with that option you would be on the safe side, EXCEPT when you are in pages like "find content" and use the edit link or write the url by hand.
What I am trying to do now is to force a redirect when you try to edit the link by a url like /node/223/edit. This is something that should be possible with hook_menu_alter.I would force a redirect to [language of the content]/node/223/edit.

I would have thought that there was a better possibility but I have found none. I will be monitoring this question to see if someone has a better idea or there is a much better solution out there.


Add banned words list to the site I want to add a banned words list to the site. and if a user used one of the banned word in node form (title and body), comment form (title and body), user username in the registration form, then the user should get an error message that you are using a banned word in your {field-name}.

And the form should not be submitted if the banned words are present.

How can I do this?

I have checked some modules like wordfilter but it does not provide the functionality for usernames and also it replaces the strings not giving the error message.

Try the Profanity module, here is a quote about it from its project page:

  An alternative to Wordfilter and Phonetic Word Filter, this module
  provides...

  Filters any Entity!
  The ability to create multiple word lists.
  Features exportable.
  An input format filter for either replacing matched words with a repeated character or phrase.
  Super quick no regex processing (for simple matching).
  A function to use for custom form item validation/detection.
  Tokens for title/label properties per Entity allowing you to specify which lists to process with.
  A rule condition for "Text contains profanity" so you can do clever things    when bad words are detected (add to moderation queue).
  Ability to filter Entity titles before view/render.
  A view field for each Entity title, profanity filtered.
  Validation to prevent users registering with a username containing profanity.
  Works with Search API by providing a filtered entity title property to be indexed.
  Integration with Search API Views to provide a field for profanity filtered    Excerpt.

Note that it has Rules integration so you can send emails etc.


Webform Conditional auto un-select I am using Webform 7.x-4.0-alpha6.

I have configured a number of radio options in a "parent" component. When each of the radio buttons are selected, different "child" components showup. Each child is unique to each radio button in the parent. Like the following:

parent =>
radio#1
radio#2
radio#3

child=> [radio#1]
radio#1-option#1
radio#1-option#2
radio#1-option#3

child=> [radio#2]
radio#2-option#1
radio#2-option#2

child=> [radio#3]
radio#3-option#1
radio#3-option#2
radio#3-option#3
radio#3-option#4

What I am trying to achieve is allowing no more than one option to be selected across all the lists of radio buttons.

So, if I select radio#1-option#1 under parent=>radio#1 and I happen to change my mind and select radio#3=>option#4 under parent=>radio#3, I want radio#1-option#1 to be automatically deselected/unset.

Try Webform Conditional module, this has some extended conditional rule on radio button and other form elements:

  Webform already has support for conditional fields on multi-page forms. For example Field C on Page 2 can be dependent on Field A on Page 1. This module adds the ability to have conditional fields on the same page. This module adds the ability to have Field B on page 1 be dependent on Field A also on Page 1.


Adding static pages to Drupal as is I want to add a static page to drupal.
To be specific, for example,

  ....

    Hi there
    Link

No sidebars. No Drupal anything. Just a nice page some words.
I would like to have the base tag in the header
(e.g., <base href="http://example.org/'>) set for me.

The simplest solution is to add a html file somewhere in your drupal folder. Apache or whatever web server you use will serve it as is.


How to handle simultaneous editing and deletion of nodes? This is a slightly different version of the question about what happens when two people are editing and saving the same node.  My version involves node deletion instead of editing:

Alice starts to edit the node (/node/123/edit).
Bob starts to edit the same node (/node/123/edit)
Alice deletes node 123 via the Delete button on the form and the followup "are you sure" page.
Bob, not knowing the node has been deleted, hits the Save button on the form.

Currently, Bob gets a 404 error back from the server -- "The requested page '/node/123/edit' could not be found."  This makes good sense, since the node has in fact gone away, but in a perfect world I would trap the doomed request and send back something a little more helpful, perhaps redirecting the user to a more reasonable page.  Is there any way to do this, short of major surgery on the forms API?  I can't think of one, to be honest -- it's the web server here that's unhappy, not Drupal -- but I thought I'd ask...  Maybe there's a hook out there that I don't know about?

A better solution may be to use content locking to prevent double editing.

for example: http://drupal.org/project/content_lock


Create Famous button in article type with value stored in database I have two user roles: editor and publisher.

I want to add a Button in article which says Make This Famous. This button is only visible to Publisher and when the Publisher clicks it, it'll ask for confirmation and if confirmed, the article will be Famous.

Once the article is famous the Button would be disabled for Publisher and the text/label would change to Already Famous. But for Admin The same  Button would still be active with text/label Make This Infamous.

I want the process to be like:

Editor can create articles and publish it
Only Publisher can make the article famous by clicking the Button displayed in article.
Once article is made famous only Admin can make it infamous.
Once the article is famous, it'd display in article saying This content is Made Famous by Username of the Publisher On the Date made famous. This is just like Submitted by in Drupal.
For Anonymous users, If the article is not Famous, it'd not display anything about famous, it'll just display the article as it is.

I have been looking for this for few days, used Workflow and Workbench Module, but those are big and complex solutions. I am not looking for content revisions and those things, just a simple Button which can make the content famous and store the time in database, so, it'd display nicely in articles.

Is there any simpler module or easy way I can accomplish this?

Sounds like you might want the flag module.

You can create a "Famous" flag, where certain roles can flag items and administrators can remove the flag.

It allows you to set the text for flagging and unflagging, so you can have "Make This Famous" or whatever you like.

The only part I'm not sure about off the top of my head is showing who flagged the content as famous.
I'm not sure if there is a setting for that, however there is views integration so you could create a view that shows who has flagged the current node and put it as a block on the page.
Since only one person can make something famous in your system there will only ever be 1 result so you will get what you require.


adding new validation method using HookEventDispatcherInterface::FORM_ALTER event I'm trying to add a new validation method for 'user_login_form' using HookEventDispatcher module and events:

class MyFormEventsSubscriber implements EventSubscriberInterface {

public static function getSubscribedEvents() {
      return [ HookEventDispatcherInterface::FORM_ALTER => 'alterForm'];
  }

public function alterForm(FormAlterEvent $event) {

    if ($event->getFormId() == 'user_login_form') {

      $form = &$event->getForm();
      $form['#validate'][] = 'my_api_authentication';

    }
  }

  function my_api_authentication(&$form, FormStateInterface $form_state) {
    $test = 1;
  }
}

But i never reach my_api_authentication function. How i need to refer it and where should be suposed to be implemented ?

May be i should manage with hook_form_FORM_ID_alter instead FORM_ALTER HookEventDispatcherInterface event ?

You can do it that way too:
in Oriented object way don't call the method like 'my_api_authentication' it should be [$this, 'myApiAuthentication'] and also the method should be Camel Cases, try with the following:

class MyFormEventsSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    return [HookEventDispatcherInterface::FORM_ALTER => 'alterForm'];
  }

  public function alterForm(FormAlterEvent $event) {
    if ($event->getFormId() == 'user_login_form') {
      $form = &$event->getForm();
      $form['#validate'][] = [$this, 'myApiAuthentication'];
    }
  }
  function myApiAuthentication(&$form, FormStateInterface $form_state) {
    // Your code validation here.
  }

}


Add more rows to the title field The title field only has 1 row for text.  I want to expand it vertically with more rows.

How to add more rows?

/**
 * hook_form_FORM_ID_alter() function implementation.
 * @param unknown_type $form
 * @param unknown_type $form_state

 */
function yourmodule_form_article_node_form_alter(&$form, &$form_state) {
    // Add your own function to the array of validation callbacks
    $form['title'] = array(
            '#type' => 'textarea',
            '#title' => 'Title1',
            '#required' => 1,
    );
    return $form;
}

I have created for article node type. You can use same for other node typw also.
I have used hook_form_FORM_ID_alter() API function.


Commerce Module - Changing product in a display node makes the image revert back to default I am having some trouble with the D7 Commerce module.

I have a t-shirt product type with three fields; 'shirt size','shirt color' and a image. Each shirt that is a different size but the same color uses the same image. Shirts with different colors use a different images.

For one product display node, I select a small,medium,large shirt size for both white and black colors. So 6 products total for one node. This way the user can select color and size for the shirt on a single page.

When a user selects a different color the image changes to that color version of the shirt, which is great. However whenever the user chooses a different size after already picking a non-default color, the image reverts back the the default color+image. So the user would have to select the color again. Or
even worse, not realize that the color changed and order the wrong color.

How can I make it so the color+image doesn't change back to default when a different size is chosen?

Haven't found a solution to this, but a workaround I am using is to disable the 'enable as attribute' of both list fields, this makes it so there is only one list in the add to cart form. The list will have a option for each product that the node references, so if you have a lot of products, this can create a long list.

To do this, go to producttype > manage fields > edit (list field) and turn off 'enable this field to function as an attribute field on Add to Cart forms.' Then save. You have to do this for each list field.

I will edit if I find a direct solution.


Any other ways I can stop the  page from being cached by boost? My drupal 7 site has Boost module (7.1.beta1, the version previous to the current release) installed and I didn't change any settings from the stock install. I saved the settings configuration with the <front> exception, generated the htaccess code, added it to my root htaccess file, turned Drupal core cache for anonymous users off... Everything works, ie, pages get cached to the boost cache directory and anonymous browsing is served from the boost cache. Only problem is that the front page is being cached even when my boost setting exception using the default <front> should be preventing the front page from being cached. I apologize if this is a redundant thread,I searched but mostly people have the opposite problem (ie, they want the front page cached-whereas I don't). I've also cleared the cache via /performance tab after enabling it and made sure there wasn't a boost cache for the front page .

Does anyone know why the boost exception setting isn't working for the front page? Is there perhaps another way to hack boost for this one page to not be 'boosted'? Thanks.

What is the actual url of your front page?
If your frontpage is the default ( /node ) then you need to add both 'node' and '' to your exceptions list.
Boost treats them differently and keeps a copy of each page in the cache.

You can inspect the cache files that boost creates (these are actually plain html files) in the cache apache root folder.


Lots of generated queries I enabled devel to Display query log

UPDATE: this problem only happens for logged users

I found that the Frontpage generate 900 queries.

**67** of them generated by the **Locale** module

and

**480** of them are of the type: **DrupalDatabaseCache::set**

How can I track this problem?

I read that I should disable the i18 module, but I can't do this since it is a multilingual site and I there are other modules that need the i18 module.

This only happens in the Frontpage in other pages the queries downs to 300.

Problem was in theme. I change to the site Bartik theme and the problem was gone.

I'm using the commerce kickstart distribution if that helps someone. I run into other issues in the past with the frontpage in this distribution. I just remember that and that is why I thought it could be a problem related to the theme. The theme of this distribution has some lines in the preprocess file and that imho may be the source of the problem.

I my situation I will use other theme since I don't need a responsive theme at all.


Integrating Commerce Feeds and Physical Field. (Drupal Commerce) I'm importing over 40K of products from a .csv file.  The file includes weights and dimensions (height,width,length).  I use physical field module to define my fields for weight and dimension. I'm having problem mapping weights and dimensions from my .csv file to my product table where I define the weights and dimensions as Physical Field (Physical Field Module) because it's not showing as the target field.  I will appreciate any help. Thank you in advance.

If you can't find Physical Field integration with Commerce Feed module for mapping your fields such as height, width or length, please have a look on a discussion started by bmx269 at http://drupal.org/node/1293820. Apply the patch & you will be able to find the field to map with your CSV file header.

Good luck...


Adding a views block to a menu? Or adding a menu to a views block? I need to create a dropdown menu which consists of the menu items and also a views block of recent nodes. Yes this is technically a megamenu, but how would one build it without a megamenu using only menus and views only?

How do you make a views show up inside a menu? I'd imagine you would need an extra module for it.
But if you built a views block and did an entity menu call into the views header, that would work too right?
Or maybe I'm going about the long way of doing it and should just use a megamenu module, which one would be best?

Of those 3 options which would work best with the least amount of work involved?

To make views show up inside a menu you can use Menu Views. If you only require the functionality your described it's the simplest and easiest way to do it.


Move images from a image field to another field Some months ago I developed a D8 based website for a customer with an image field with multiple values, displayed as a Bootstrap Basic Image Gallery.
Now, my customer has changed his mind so now he wants to set the possibility to insert either an image or a video, so I decided to use Paragraphs to let him choose if he wants an Image or an embed Video.
The problem is that the customer has over 1000 nodes with an average of 3-4 images per node, so if I change the field to a Paragraph one, the images previously saved in the Image field are not moving to the Paragraph field.
Is there a way to "migrate" the images from an Image field to a Paragraph referenced Image field?
P.S: As you may understand, re-uploading the images again might be, if I can say, a PITA

Welcome to SO, MineDoodler!
A little bit ago I found the same problem, so I developed this piece of code. (Note that I started a little bit ago with developing, it is possible to achieve this easier).
Read the comments to understand the code.

use \Drupal\node\Entity\Node;
use \Drupal\paragraphs\Entity\Paragraph;
use \Drupal\file\Entity\File;

function migrateImages() {
  // Get all products
  $query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'productos');
  $nids = $query->execute();

  $allNids = [];

  // In my case, i had a keyed array (First element was [213] => "157") so I turned into ([0] => "157")
  foreach ($nids as $nid) {
    $allNids[] = $nid;
  }

  // Go through every node
  for ($i = 0; $i < count($nids); $i++) {
    $nodeID = $allNids[$i];

    // Load node.
    $node = Node::load($nodeID);

    // Get current paragraphs (if already has any).
    $current = $node->get('field_prod_media')->getValue();

    // Go through every image this node has.
    foreach ($node->field_prod_img as $item) {
      // Create new paragraph
      $paragraph = Paragraph::create(['type' => 'YOUR_PARAGRAPH_TYPE']);

      // Load image
      $file = File::load($item->target_id);

      // Save image
      $paragraph->set('IMAGE_FIELD_IN_PARAGRAPH', $file);

      // Force the new "alt". I've done this because it wasn't saving the alt.
      $paragraph->field_img->alt = $item->alt;

      // Check if it's new and save it.
      $paragraph->isNew();
      $paragraph->save();

      // Add to the current paragraphs the new one.
      $current[] = array(
        'target_id' => $paragraph->id(),
        'target_revision_id' => $paragraph->getRevisionId(),
      );
    }

    // Set again all paragraphs, with the new ones.
    $node->set('field_prod_media', $current);
    $node->save();
    dpm("node ".$node->label()." has been saved!");
  }
}

Took the idea from #7 in this post and developed by my knowledge.
I forgot to mention that this code was executed in the Devel PHP, in the Devel module.


Drupal 7: customise archive view to show only blogs from one user How can I customise the archive view in views 3 so that each user blog page has an archive relating to that page. The default view is for the whole site.

Add a "User" relationship, then just add the corresponding contextual filter. If absolutely necessary, you can set the contextual filter to always use the default value, and set it to be a raw value from the url, and set the number to wherever the username is in the url path.

Example:
url = http://mysite.com/user/USERNAME/blog/archive
raw value from path number = 2 (/user/USERNAME -- it's the second part of the path)


How to maintain a Drupal project on GitHub I maintain several modules on drupal.org. Having spent years doing things "the drupal way" (remember CVS?) I'd like to make my life a bit easier and use GitHub.

While there may be political reasons this could be undesirable, are there any technical reasons? I imagine one-way syncing could be as simple as a cron job that does a fast-forward push from a github repo to the corresponding drupal.org repo.

Is that all there is to it? Are there existing tools to facilitate this?

Technically, this post on SO covers pushing/pulling from multiple git remotes. In your case, it sounds like you'd set up 2 remotes (git.drupal.org & github.com), pull/push from github.com as needed, then push to git.drupal.org when you're ready to publish updates.

As far as the politics, checkout this thread on g.d.o. It might contain some thoughts/insights from other people who are in the same situation you're in.


Taxonomy view - showing term searched for in header I've enabled the Taxonomy View template and used the taxonomy term page module to specify this view should be used when clicking on one of the taxonomy terms.

The page itself is working & looking great, but I'm struggling to show the vocabulary and term used in the header region.

Current view setup:
https://www.dropbox.com/s/j38nsznel93eoz3/Screenshot%202014-10-22%2022.56.28.png?dl=0

I'm hoping to use one view for all the different vocabularies - but wanted to show in the header e.g.

All articles tagged [author name]  - where the vocabulary used is 'author'

or

All articles tagged [project] - where the vocabulary used is 'project'

Anyone give me a pointer?

I think @Neograph734 has eluded to the answer here.

If you add a field for taxonomy term name but don't display it (exclude from display), you can add a header field of type "Global Text" and render the term name from the collection of tokens that are representing the fields.


How to get archived events based on end date for a content type with a start date and end date field? Create a content type Event with fields for Start date and End date. Validate the creation of events where Start date cannot be in the past and End date cannot be less than start date. Create a View where the Start date & End date are exposed filters and end date validated as in content creation page. The View should also filter expired events (i.e. Content with expired End date) and displayed in a similar view display named Archived Events

Archived events get based on an end date.

Go to view named archived events. Then click the end date exposed filter in FILTER CRITERIA. Check Filter type to expose is single filter. Then below operator drop down box choice is less than. Next drop down box choice enter relative date. Below now shows Relative date text box give now.
Then click on Apply button.


Select fields in multiple tables / change output value / compare fields i want compare (=) two fields in two tables. In the first field, i have only a nid (e.g. 55) and in the second field, the value is formatted with "node/%" (e.g. node/55).

How can I created the join query for compare these two fields ?

I have tested this with this code without success :

$uid = arg(1);
$query = db_select('field_data_field_users', 'alias1');
$query
    ->condition('user_id', $uid, '=')
    //->addExpression('node/(fdfur.entity_id)', 'alias2'); // > not functionnal
$query->join('menu_links', 'ml', 'ml.link_path = alias1.entity_id');
// ml.link_path = alias1.entity_id > node/55 = 55 > no match...
$query
    ->fields('alias1', array('entity_id'))
    ->fields('ml' , array('language'))
    ->fields('ml' , array('link_path'))
$results = $query->execute();

Here an image that explains my problem

I start from the user id and I want to get the datas of the menu links. The first db_select in the custom table is ok, i get the related nids with the user ids, but I can't to get the datas of the menu link.

Have you any idea to resolve my problem ?

Thanks for your help.

I suspect this is what you are looking for

db_query("SELECT * FROM node LEFT JOIN url_alias ON url_alias.alias=concat('node/',node.nid)");


User-submitted reviews of multiple aspects of a business? My site is based off of user-submitted reviews of businesses. Instead of just an overall rating as provided by fivestar, I want users to rate different aspects & services provided by the business. For example, I'd want them to rate "staff" on a scale of "very unhelpful" to "very helpful," and "quality of clothing" on a scale of 1-10. I'd ideally also want a form field where the user could enter, for instance, how much they spent at the store.

What would be the best way to create a review form for users to fill out, and then to subsequently display the average ratings/amounts of each individual aspect on the business node?

Additionally, I'd need to add up all of these average ratings in order to create an overall "grade" of the business (i.e. if there are two aspects to be reviewed, each worth 10 points, and one has an average of 5 while the other has an average 6, then the business would get an overall grade of 11/20). Hopefully this would be possible with whatever system is suggested. Preferably, I'd like to use Display Suite to display the gathered averages and overall grade since I already have a template for my pages created in it.

In Drupal 7, you can create a review as a custom content type.  Staff could be rated as "very unhelpful" to "very helpful" using a field of type list (integer).  Quality of clothing could also be done with a list (integer).  For the time customers spent at the store, the field type to use depends on what you will do with the data later.

You could then create custom displays for this content type using Views.  Views integrates with Display Suite as well so you could use that if you liked, though I'm not sure it's the best solution.

As for the averages, you'll need to know some PHP, but you can use the Computed Field module.  Even if you are not very familiar with PHP, there are many examples on that module's documentation page.

If you're new to Drupal and all of this is very confusing, I highly recommend the book Using Drupal published by O'Reilly.  The second edition just came out recently and covers Drupal 7; it contains an explanation of how to use fields/content types and views (chapter two) as well as how to build a job posting site (chapter three) and product review site (chapter five), two examples that would probably be highly informative for you.

Good luck!


Allow user to pick a location I would like to add a field to my node that allows the user to search for a location like a city and pinpoint that location on the map or pick a location on a map but without having to zoom in from viewing the whole world (like the problem I am having using the geofield).
Cheers

The geolocation field module solved this problem.


"Drush sqlc < myfile.sql" doesn't return the site to previously working state. Are there files to be deleted? I've backed up my drupal 8 database via the CLI using drush sql-dump > myfile.sql.

I make some changes to the site and break it, then I try to restore it via drush sqlc < myfile.sql.

It works for a bit, until I click something and it messes up again as if there was something written to the files causing it and it is not just the database alone that is the culprit. I get this error:

  The website encountered an unexpected error. Please try again later.

A totally vague error as I'm not sure what is causing it.

Are there any files that are written to the Drupal directory that has to be deleted as well when doing a drush sqlc < myfile.sql restore?

The website encountered an unexpected error. Please try again later.

There was an error on PHP that Drupal couldn't handle.

If you have your install set to log errors, check the report.

Another option, on your settings.php add:

$config['system.logging']['error_level'] = 'verbose';

To show the errors.


How to get a form to submit: a possibly stupid question. Why won't this form submit?

$form['foo'] = array(
    '#type' => 'textfield',
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
);

if I add the following

$form['#submit'][] = 'my_form_submit';

and a submit function:

function my_form_submit($form, &$form_state){
  dd('Submit ran');
}

The debug statement is never called. What am I doing wrong?

Actually the submit handler name should be the form function name with _submit.

So in this case: my_form() returns the form, and my_form_submit($form, &$form_state) is automatically the submit handler. This also works for _validate.

See the Examples project for some working code. It has a submodule called form_example.


Where does drupal_mail() get the return-path and sender? I want to send a simple mail using drupal_mail(). I don't understand from where it gets sender and incorrect_mail@gmail.com as return path. From where does it get this email?

function rappel_mail($key, &$message, $params) {
  switch($key) {
    case 'informations':
      $message['subject'] = $params['subject'];
      $message['body']= $params['body'];
      break;
  }
}

function my_module_passwordOublie_envoie_password ($email) {
  $response = array();
  global $language;
  $mail_user = user_load_by_mail($email);
  if (!$mail_user) {
    return func_succes(950, $response); // just to check if mail exists
  }
  else {
    $to = 'my.real.email@gmail.com';
    $from = 'noreplay@noreplay.com';

    $params = array(
      'body' => t("hi, you've just received a drupal mail"),
      'subject' => t("test mailing"),
    );
    $message = drupal_mail('rappel', 'informations', $to, $language->language, $params, $from, TRUE);
   }
 }

This is Postman response (because I'm working with services on a custom resource that send mail using drupal_mail()).

"Return-Path": "????@gmail.com", <=== those emails are valid (mine too but i've delete this email every where it was ! )
"Sender": "????@gmail.com",<=========
"From": "noreplay@noreplay.com" <=== good one

drupal_mail() gets the value for those headers either from the the value of the site_mail persistent variable (set in admin/config/system/site-information), or from the sendmail_from setting found in php.ini.

The first line of drupal_email() show exactly how the default value for the sender is set.

$default_from = variable_get('site_mail', ini_get('sendmail_from'));

This is then the code that sets the email headers.

  if ($default_from) {

    // To prevent e-mail from looking like spam, the addresses in the Sender and
    // Return-Path headers should have a domain authorized to use the originating
    // SMTP server.
    $headers['From'] = $headers['Sender'] = $headers['Return-Path'] = $default_from;
  }
  if ($from) {
    $headers['From'] = $from;
  }
  $message['headers'] = $headers;


How would you implement an automatic way of the images loading in a pop-up (lightbox/colorbox) window by a click? What I mean is, can we achieve the blogspot.com/Blogger experience where we can add photos to the content (node in Drupal speak) and without any ado (adding class="colorbox", or enclosing the <img> element into an <a> ), clicking the photo in the post will make it enlarged in a pop-up window, similar to how colorbox functions.

I have visited this question Configuring Lightbox2 to Pop-Up Images embedded in nodes and it seems ambiguous to me.

I have a current Drupal 7 site and it's quite annoying that I have to manually enclose the images in a

<a class="colorbox colorbox-insert-image" href="..." title=..."> ... </a>

every effing time.

You can. As always, there are several ways.

You can implement a Drupal behavior (jQuery script) that finds all images within the content and adds according classes / click callbacks.

Another way would be writing a little custom module implementing a content filter that does the same on your server.

I'm not at a PC right now. But I think you have two viable ideas now to search for. Let me know, if you need further help.


Module submission guideline - configuration storage I am trying to finish and submit my first module project. It's a QA/tab launcher thing that is meant for multisites. Basically, I am using a few different methods to retrieve a list of sites that are part of the same multisite as the site that the module is enabled on. The piece I have a question about is a configuration page that saves a list, from that list, of "enabled" sites.

Here is my problem: I want a multisite-wide configuration, but I am concerned about how i'm doing it. I understand that the Domain Access module would provide more than enough functionality for cross-site database access and would probably be more up to the Drupal guidelines, but it's extremely overkill! Domain Access will scare off people that don't want to configure each settings.php file, etc.

All I need, literally, is to save 2 non-associative arrays in a way that each multisite has access. My current setup saves them in the public files directory as 2 .csv files, and works as well as I know how to code it; as far as saving .csv's and retrieving the rows go, I think i'm doing it right. It doesn't really have performance issues tied to it because it truly is a lightweight piece; the only reason i'm doing it this way is for global access.

My question is: is this going to get flagged as non-conformant to the Drupal way because i'm not saving it in a table? I don't see anything in the guides specifically guiding me away from doing it that way... but it's just a guess that they won't like it.

My advice to you is to submit your sandbox to Drupal.org Project Applications, and see what people say.  Its fairly rare to get an outright rejection.  People will inspect your code, offer suggestions for improvement, etc.  Better to get started ASAP.

As for your specific issue:  I think the way you are going about it is not in accordance with The Drupal Way ™.  Your best bet would probably be to generate a PHP file, only allowing your module to access this sort of administrative control from the site in Default.


Feeds Importer running multiple times My feeds importer is acting very strange and running the same import multiple times..

This is what my importer looks like:

class FeedsASUNewCareer extends FeedsCSVParser {
  /**
   * Implements FeedsParser::parse().
   */
  public function parse(FeedsSource $source, FeedsFetcherResult $fetcher_result) {
    global $user;
    $source_config = $source->getConfigFor($this);
    $state = $source->state(FEEDS_PARSE);

    // Load and configure parser.
    feeds_include_library('ParserCSV.inc', 'ParserCSV');
    $parser = new ParserCSV();
    $delimiter = $source_config['delimiter'] == 'TAB' ? "\t" : $source_config['delimiter'];
    $parser->setDelimiter($delimiter);

    $iterator = new ParserCSVIterator($fetcher_result->getFilePath());
    if (empty($source_config['no_headers'])) {
      // Get first line and use it for column names, convert them to lower case.
      $header = $this->parseHeader($parser, $iterator);
      if (!$header) {
        watchdog('CAREER IMPORT ERROR', "Could not parse header");
        return;
      }
      $parser->setColumnNames($header);
    }

    // Determine section to parse, parse.
    $start = $state->pointer ? $state->pointer : $parser->lastLinePos();
    $limit = $source->importer->getLimit();
    $rows = $this->parseItems($parser, $iterator, $start, $limit);

    // Report progress.
    $state->total = filesize($fetcher_result->getFilePath());
    $state->pointer = $parser->lastLinePos();
    $progress = $parser->lastLinePos() ? $parser->lastLinePos() : $state->total;
    $state->progress($state->total, $progress);

    $careers = array();

    watchdog('careers', '
' . print_r($rows, TRUE) . '
');
    foreach($rows as $career) {
        // create career.
        $node = entity_create('node', array('type' => 'careers'));
        $entity = entity_metadata_wrapper('node',$node);
        // Set Entity properties
        $entity->title->set($career['alternate_title']);
        $entity->language = 'en';
        $entity->author = $user->uid;
        $entity->status = $career['status'];
        $entity->body->set(array('value' => $career['body']));
        $entity->field_alternate_title->set($career['alternate_title']);
        $entity->field_career_category_image->set($career['car_category_img']);
        $entity->field_careercategory->set($setCategoryId);

        // Save Career
        $entity->save(); //Save new Entity wrapper
        $node->tnid = $node->nid;
        $entity->save();
      }
    }

    // return empty set.
    $ret = new FeedsParserResult();
    return $ret;
  }
}

When I go to Content > Import and select this Feed Importer to use, it just gets hung up on the processing page and in my logs I can see my watchdog watchdog('careers', '
' . print_r($rows, TRUE) . '
'); executes over and over until I stop it. Keep in mind that watchdog is not in a loop, so the feeds importer is just running endlessly until I stop it.

What could cause the importer to act with such behavior?

It could be that there's a bug in the parser's reporting progress. As long as the parser doesn't tell Feeds parsing is done, Feeds will keep calling the parser over and over again.

Workflow of Feeds

Fetch data.
Parse 50 first items of data.
Process 50 items.
Feeds checks if the parser's progress is complete. If not, the next 50 items of data are parsed.
Process 50 items.

When there's nothing more to parse, Feeds checks if there's more to fetch. If so, above steps are repeated. If not, import finishes.


How to add multiple forums for a single site in Drupal I am working on a client portal and client needs multiple forums for the site based on the user priviledges.

e.g.

  www.example.com/forum1

  www.example.com/forum2

  www.example.com/forum3

Is it possible to create multiple forums in Drupal? If yes, any reference or steps please.

The Drupal forum module allows creation of multiple forums.  The module allows you to create 'forum containers' (groups of forums) and forums.

If combined with 'Advanced Forum' and 'Forum Access' modules it should be able to provide you with the facility to create multiple forums and control access by role to specific forums or containers.

The forum containers are actually taxonomy terms so you can customize the URLs for each container by editing the taxonomy term, eg /forum1 /forum2 etc.

To make the URL structure consistent between containers and forum topics, you may also require 'PathAuto' module, and to look at the URL alias patterns.

For default pattern for forum topics - I use is:

forum/[node:taxonomy-forums:parents:join:/]/[node:taxonomy-forums:name]/[node:nid]

You might find this works better for you if you wish to customize the taxonomy term URLs.

[node:taxonomy-forums:url:path]/[node:nid]

Pattern for forums and forum containers:

forum/[term:parents:join-path]/[term:name]

or perhaps for consistency with custom URLs

[term:parent:url:path]/[term:name]


Using Ultimate cron to set a specific time to run a function of module, but it is not working as expected I have set ultimate cron job time once a day but it works at every hour because another default site cron is running every hour.

This code is working on production but not according to crontab time i.e once in a day. It is working every hour, i checked cron job list on acquia server there is one cron job set named "site cron" which is running every hour.

Code:

/**
 * Implements hook_cronapi().
 */
function demo_cronapi($op, $job = NULL) {

  $items['monitor_run'] = [
    'description' => 'Post Solution',
    'scheduler' => [
      'name' => 'simple',
      'simple' => [
        'rules' => ['0' => '0 7 * * *'],
      ],
    ],
  ];

  return $items;
}

/**
 * Trigger event to generate report.
 */
function monitor_run($job) {
  // logic code.
}

Set your crontab to wget/curl cron.php once per minute (* * * * *).


Drupal core language module, language switcher block Can a preprocess hook convert the default ul of hyperlinks into a drop-down select list? Something like this hook.

function THEME_preprocess_links__language_block(&$variables)

You can copy the core/modules/system/templates/links.html.twig into your theme's templates directory, call it links--language-block.html.twig  and in this file adjust the output from the default ul/li structure into a different html structure.

NOTE: there is already 3 maybe more modules that convert the language switcher to dropdown lang_dropdown, dropdown_language and bootstrap_languages.


How can I change an image field programatically? I'm trying to change the image field 'Badge' when an article is situated at the top of a view 'Top 3' after it has been updated. This is my custom module:

function top_node_update($node) {
    $top = views_get_view_result('top_3');
    $first = $top[0]->nid;

    if ($first == $node->nid) {
        $node->field_badge[0]['value'] = '/default/files/images/gouden_rozet.png';
        field_attach_update('node', $node);
    }
}

Unfortunately, nothing happens when I edit and save an article.

What's going wrong and how can I solve this?

Edit: Everything seemed perfectly fine after @undersounds answer, because the image fields were correctly changed by my custom module. I used the same piece of code to also edit the images of the second and third node in the view:

<?php

function top_node_update($node) {
  $top = views_get_view_result('top_3');
  $first = $top[0]->nid;
  $second = $top[1]->nid;
  $third = $top[2]->nid;

  if ($first == $node->nid) {
    $image = file_get_contents('public://images/gouden rozet.png');
    $file  = file_save_data($image, 'public://images/gouden rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($second == $node->nid) {
    $image = file_get_contents('public://images/zilveren rozet.png');
    $file  = file_save_data($image, 'public://images/zilveren rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($third == $node->nid) {
    $image = file_get_contents('public://images/bronzen rozet.png');
    $file  = file_save_data($image, 'public://images/bronzen rozet.png', FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }
}

I started playing around a bit to see whether everything worked and discovered this: when a certain node has for example the 'bronzen rozet' image and moves to the first row in the view, the image is changed to 'gouden rozet' - as it should be - but the bronzen rozet.png file is also deleted in my images file!

How can I prevent this?

function top_node_update($node) {
      $top = views_get_view_result('top_3');
      $first = $top[0]->nid;
      $second = $top[1]->nid;
      $third = $top[2]->nid;

  if ($first == $node->nid) {
    $image = file_get_contents('public://images/badges/gouden rozet.png');
    $file  = file_save_data($image, 'public://images/gouden rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($second == $node->nid) {
    $image = file_get_contents('public://images/badges/zilveren rozet.png');
    $file  = file_save_data($image, 'public://images/zilveren rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($third == $node->nid) {
    $image = file_get_contents('public://images/badges/bronzen rozet.png');
    $file  = file_save_data($image, 'public://images/bronzen rozet.png', FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }
}

You should also try to prevent using functionality twice. So instead of the code above you can also write something like:

function top_node_update($node) {

  $top = views_get_view_result('top_3');
  $first = $top[0]->nid;
  $second = $top[1]->nid;
  $third = $top[2]->nid;

  if ($first == $node->nid) {
    $img_name = 'gouden rozet.png';
  }

  if ($second == $node->nid) {
    $img_name = 'zilveren rozet.png';
  }

  if ($third == $node->nid) {
    $img_name = 'bronzen rozet.png';
  }

  $image = file_get_contents('public://images/badges/' . $img_name);
  $file  = file_save_data($image, 'public://images/' . $img_name, FILE_EXISTS_REPLACE);
  $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
  field_attach_update('node', $node);

}


Fatal error: Call to undefined function cache_get() I am getting the following error on the server

Fatal error: Call to undefined function cache_get() in includes/module.inc on line 665
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Call to undefined function cache_get() in includes/module.inc, line 665

How to fix this?

For me, the cause was different: some errors are not caught by Drupal's error handler.

I used a new DateTime() in my settings.php (probably very rare)
It generated an error because the date.timezone setting in my CLI php.ini wasn't set.

To find the real error (this is the interesting part of the answer for all of you, I think) :

Edit your module.inc, line 723.

Add these lines before the cache_get call.

if (!function_exists('cache_get')){
    debug_print_backtrace();
}
$implementations = cache_get('module_implements', 'cache_bootstrap');

It might give you lots of information about the real source of the issue!


Notice: Undefined index: #value in element_validate_integer_positive() I'm getting the error Notice: Undefined index: #value in element_validate_integer_positive() (line 4190 of includes\form.inc) after clicking the Upload or Remove of a managed_file even though the file is actually being stored in the correct directory.

Here's the relevant snippet:

$form['some_image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
    '#default_value' => variable_get('some_image', ''),
    '#upload_location' => 'public://some_images/',
  );

I'm running the instance on XAMPP with PHP 5.3.6. Downgrading to PHP 5.2.9 didn't fix the problem as indicated in the other forums.

When I use Chrome to checkout the ajax request URL, I see the message that is also seen from looking at file/ajax/image/file/form-wRaEJ-JRPqC7q6BSbp6Ccxi_9X1cpiaBzhwlIs9NFd0 that I found from /admin/reports/dblog

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

Note that I'm only uploading a 100kb file.

Line 4190 of includes/form.inc is as follows:

function element_validate_integer_positive($element, &$form_state) {
  $value = $element['#value'];
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
    form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
  }
}

Update: It turns out the problem is not just for the managed_file, but also for the form itself. Clicking the submit button shows the very same error.

Currently, my hook_form_validate is as follows:

function mymodule_form_validate($form, &$form_state) {
}

Removing it gives me a Drupal error that says it should be there. I think I'm missing an implementation some other hook, but I have no idea which.

What am I missing here?

It sounds that apache user doesn't have the permissions to write in the temp directory which is set in the Drupal's file system settings.

I'd suggest you to check first the status reports on admin/reports/status. If you have any problems with your installation, it would be listed there.


How to print the Addthis block code into a template I've installed the AddThis module and am trying to print the buttons on my template, however I can't get it to work. Here's the I'm using:

$addblock = module_invoke('addthis','block_view','addthis_block');
print render($addblock['content']);

For the record, If I switch to Bootstrap theme, the links are displayed on the page, if I switch to my own theme (Bootstrap child-theme) it doesn't. I've copied the code verbatim from modules/node/node.tpl.php and it still doesn't work.

Any suggestions?

did you enable the Display Setting in your addthis block configuration because code is good go it working for me, so go and configure the display setting surely it will work.. its under admin/structure/block/manage/addthis/addthis_block/configure enable it as you need by "Basic button or Basic Toolbar"...


Getting the user ID of the user who created a taxonomy term I need to get the user information of the user who created a taxonomy term. How can I get it?

try to do this:

Add a field called 'Author' like a entity reference
alter the form to prepopulate this field

function customodule_form_alter(&$form, &$form_state, $form_id){
print_r($form_id);
if( $form_id == 'taxonomy-form-term' && isset($form['field_author']) ){

  print_r($form['field_author']['nid']['nid']['#value']);
  global $user;
  $form['field_author']['nid']['nid']['#value'] == $user->uid;

  }
}

I put some print_r so you can debug this code fast.


Show terms in view filtered from another view I have two views, first one is block, second one is page. I have vocabulary, let's call it "food".
In the food vocabulary we have that hierarchy:

Fruit

Apple
Banana

Meat

Chicken
Pork

Both views goal is to show taxonomy terms, but first one shows ONLY parent terms, then we click on parent Fruit, we get second view, which shows ONLY terms from Fruit, so Apple and Banana. If we clicked on Meat term, we get terms Chicken and Pork. My question is how to do it?

You don't need two Views Display for that, you can do that one with one Page Display.

Create Views of type Taxonomy term and add Page Display
Add Filter for Food Vocabulary
Add the Parent Relationship. It is called Taxonomy term but look at the Description The parent term of the term. This can produce ....

If you Require it the results will only show terms that have Parent items, so you'll probably want that.
Add Contextual filter Name from the Taxonomy term Category and configure it:
Relationship: Parent
When the filter value is NOT available
Display a summary
Format List
Base path (you must enter the Page path if this isn't the first Page Display in your Views)
Display record count with link
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term name
[Food]
Transform dashes in URL to spaces in term name filter values
More
Transform spaces to dashes in URL

You will see a list of your parent items in the results (as a Summary), then when you click on one you will see Views results terms that are its children.


How to let view display selected field content according to nid I have a content type "banner" with Field Collection Fieldset, each fieldset is having a image upload field and a text field to enter node ID.

Eg output:

Image A, nid=1
Image B, nid=2
Image C, nid=3

I would like to have a view block, appearing in every page, and shows Image A when the page nid is 1, shows Image B when nid is 2.

I know this should be something related to filter or contextual filter, but I can't get the correct steps to configure. Is there any way to do it?

I think this is what you're looking for

Add a contextual filter of

  content: nid

then do as the picture below.


change node field value without node->save or without causing hook_entity_presave infinite loop Have CONTENT_TYPE_NAME with field_counter that the user can set when editing a node.  If a user edits and updates that field I want all other nodes that have this field set (to an equal or higher value) to increment their values by 1.  I am overriding hook_entity_presave for this purpose.
As you can see in the following code I am getting all nodes of the same content type using entityQuery exluding the node that was about to be saved.  For all the nodes found I am getting the entity and incrementing the field value by 1 and setting the field value and saving the node.
    function MY_MODULE_entity_presave(EntityInterface $entity){
      if ($entity->getEntityType()->id() == 'node') {
        $changed_field = array(
            "field_counter",
        );
        $nid = $entity->id();
        foreach($changed_field as $field ){
          $value = $entity->{$field}->value;
          if(isset($value) && $value !=""){
            MY_MODULE_change_field_value($field,$value,$nid);
            //...
          }
        }
      }
    }

    function MY_MODULE_change_field_value($field,$value,$xeid){
      $query = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', 'CONTENT_TYPE_NAME')
        ->condition('nid', $xeid,"<>")
        ->condition($field,$value,">=");

      $nids = $query->execute();

      foreach ($nids as $nid) {
        $node = \Drupal\node\Entity\Node::load($nid);
        //or
        //$node = \Drupal::entityTypeManager()->getStorage("node")->load($nid);

        $old_value = $node->{$field}->value;
        $old_value++;
        $node->{$field}->value = $old_value;

        $node->save();
      }
    }

This code works with but has a problem. All nodes updated programmatically will call entity_presave again and cause an infinite loop.
I did not find a way to update field value without calling node->save() if there is a way please let me know (I know there was a way in drupal 7 field_attach_update which is deprecated as of 8.0.x I think)
Is there a way to call node->save() which does not call hook_entity_presave ?
or alternativelly what checks can I do in the hook_entity_presave to know if the field was just updated programmatically and not from user edit ?

I think I have found a simple solution

add revision message with UNIQUE string before saving the node

    //...
    $node->setNewRevision(TRUE);
    $node->revision_log->value = "AUTOMATED-UPDATE ". $field." incremented to ".$old_value ;
    $node->save();

check on the hook_entity_presave that the revision was not AUTOMATED by checking in the log for our UNIQUE string

    if ($entity->getEntityType()->id() == 'node') {
        $log = $entity->revision_log->value;
        if( substr( $log, 0, 16 ) === "AUTOMATED-UPDATE" )
            return;
        ...


Block within another block In drupal 7, I want to render block into another block, for example block-1 into block-2.
I guess I should put some PHP code into block-2, but I don't know what the code could be?

Based on Ashlars's comment.

A minipanel, provided by Panels, is for anyone not used to Panels, essentially a block, that supports internal layouts. You can use a mini-panel to wrap several different blocks (and many other things, views, nodes, etc) into a single "block".

Unfortunately, I must admit that documentation is scarce on this topic. I will refer you to this other question: looking for a good mini panels tutorial.


Redirect Fisrt time login with LDAP The first time that the user login to the page, have to be redirected to the user edit profile to fill a field (Id) that is mandatory at the first login, I tryed using drupal_goto at hook_user_insert and hook_user_presave and don't worked. How can I do that? In which hook I can do that?

EDIT: I am using LDAP Authentication, user don't have to fill a form registration.

Thanks for your answers, I could do it, no with Rules module. I did it using hook_user_login(), and $_GET['destination'].

    function webform_sub_user_login(&$edit, $account) {
    $currentuser = $edit['uid'];
    $_GET['destination']= "/user/".$currentuser."/edit";
    }

If it can cause problems, let me know. But for now it seems to work well.


How to determine create access for a given enitty and bundle This one feels like it should be obvious, but after some searching I'm having trouble finding a code example for checking whether a user has create access for an arbitrary entity.

In this case, I'm looking to pass an arbitrary entity type and bundle, in order to check whether a user has create access. This can be any entity type, including custom entities.

I have a sense that the end of the expression will be ->createAccess() , based on what I've read for the entity access interface classes, but where I'm stuck is finding the right class to call first, in order to get the entity information.

OK, I have figured it out. Here's what I am using to get access for the current user (in the createAccess() step the second parameter can be an account, if you need to pass an account):

// Before this, you need to get the entity type and bundle,
// shown here as $entity_type and $bundle .
$entity_manager = \Drupal::entityTypeManager();
$access_handler = $entity_manager->getAccessControlHandler($entity_type);
$access = FALSE;
if ($bundle) {
  $access = $access_handler->createAccess($bundle);
}
else {
  $access = $access_handler->createAccess();
}


How to move custom code into template.php In my node.tpl.php file I have this custom code:
<?php if($node->field_division['und'][0]['value'] = 1):
    $cta = $GLOBALS['base_url'].'/node/6';
elseif($node->field_division['und'][0]['value'] = 2):
    $cta = $GLOBALS['base_url'].'/node/7';
endif;
?>

I want to move it to my template.php file, so I can access it both from node.tpl.php and page.tpl.php.
How can I do this?
I tried following the examples in this thread and this article but I can't get it to work. Any help would be greatly appreciated.

First off, don't use 'und'. You should use field_get_items(). This is a change from D6, which is likely why you can't use those articles as a reference.

Secondly, you are using = and not ==, so you're assigning the value instead of comparing it.

So, you can probably just do the following:

function THEMENAME_preprocess_node(&$variables) {
  THEMENAME_field_division_helper($variables);
}

function THEMENAME_preprocess_page(&$variables) {
  THEMENAME_field_division_helper($variables);
}

function THEMENAME_field_division_helper(&$variables) {
  if ($node = $variables['node']) {
    $field_division = field_get_items('node', $node, 'field_division');
    if ($field_division[0]['tid'] == 1) {
      $variables['cta'] = $GLOBALS['base_url'].'/node/6';
    }
    else if ($field_division[0]['tid'] == 2) {
      $variables['cta'] = $GLOBALS['base_url'].'/node/6';
    }
  }
}

And then in your node.tpl.php and page.tpl.php file,

<?php if (isset($cta)): ?>
  <div class="some-wrapper">
    <?php print $cta; ?>
  </div>
<?php endif; ?>


Importing Joomla 1.5.23 to Drupal 7 by using Feeds I'm trying to migrate Joomla 1.5 to Drupal 7 by using Feeds Module. I have tried the "Joomla to Drupal" with no luck. And the "Migrate" module requires some PHP coding, which I'm not an expert on this.

Question 1 - So, my question is which phpMyAdmin database for "Node Import" when I import CSV to Drupal? I know "jos_users" is for the "User import". What about the rest of them?

Question 2 - How to import Joomla user password by using Feeds? The password format seems different.

Question 3 - How and where can I import the url formatting?

For details, please see below of my Joomla phpMyAdmin database list.

Thanks!

jos_banner
jos_bannerclient
jos_bannertrack
jos_categories
jos_components
jos_com_file_index
jos_com_file_index_errors
jos_contact_details
jos_content
jos_content_frontpage
jos_content_rating
jos_core_acl_aro
jos_core_acl_aro_backup
jos_core_acl_aro_groups
jos_core_acl_aro_map
jos_core_acl_aro_sections
jos_core_acl_aro_wtf
jos_core_acl_groups_aro_map
jos_core_acl_groups_aro_map_wtf
jos_core_log_items
jos_core_log_searches
jos_funrecaptcha
jos_groups
jos_jce_groups
jos_jce_plugins
jos_jcomments
jos_jcomments_custom_bbcodes
jos_jcomments_reports
jos_jcomments_settings
jos_jcomments_subscriptions
jos_jcomments_version
jos_jcomments_votes
jos_jobline_jobs
jos_jobline_jobs_types
jos_jobline_types
jos_jxcomments_comments
jos_jxcomments_ratings
jos_jxcomments_ratings_members
jos_jxcomments_threads
jos_jxtended
jos_menu
jos_menu_types
jos_messages
jos_messages_cfg
jos_migration_backlinks
jos_modules
jos_modules_menu
jos_newsfeeds
jos_plugins
jos_polls
jos_poll_data
jos_poll_date
jos_poll_menu
jos_redirects
jos_sbxss_categories
jos_sbxss_slides
jos_sections
jos_session
jos_stats_agents
jos_taxonomy
jos_taxonomy_config
jos_taxonomy_elements
jos_taxonomy_filters
jos_taxonomy_map
jos_templates_menu
jos_users
jos_weblinks
jos_xmap
jos_xmap_ext
jos_xmap_sitemap

I've never considered how you would use Feeds to import from a database, but it works great for migrating content when that content is in a "feed".

If you have to use the DB, then there is Feeds SQL and Feeds DB, but I think both require you to write a query. That said, if you are using phpMyAdmin then when you "open" any of those tables phpMyAdmin will show the query it's running.

If you are able to expose your content as an xml/rss feed, a JSON feed, , or etc. then thing become very straight forward.

Using the Feeds Preview module may help you get your mapping correct.

You should be able to import the node alias (path) along with the content.


How to associate a product cost to a product in Drupal Commerce? I have to purchase each of my products from my manufacturer.  I want to store the cost for each product, so I can run reports and get my gross profit.  I have not found any site that demonstrates how to do this.  It seems like this should be basic for Drupal Commerce.  Am I using/searching for the wrong terminology?

Just add a new price field to your product type, call it cost, and populate it at will. That's what I do to track my cost on realmilkcheese.com.


Access Denied for password reset page I am trying to redirect user to edit profile page after accessing the password reset link, code looks like

function mymodule_reset_menu_alter(&$items) {
  // Drupal's default behavior is to show the user a log-in form before
  // their user profile.  We replace this item to skip the uneccesary step.
  $items['user/reset/%/%/%'] = array(
    'title' => 'Account settings',
    'access callback' => 'simple_pass_reset_pass_reset_access',
    'access arguments' => array(2, 3, 4),
    'page callback' => 'test',
    'page arguments' => array(2, 3, 4),
    'type' => MENU_CALLBACK,
  );

}

function test($uid, $timestamp, $hashed_pass, $option = NULL) {
  global $user;
  // Show the user edit form instead of silly one-time login form.
  $account = user_load($uid);
  $user = $account;
  $token = drupal_random_key();
  $_SESSION['pass_reset_' . $user->uid] = $token;
  drupal_goto('user/' . $user->uid . '/edit', array('query' => array('pass-reset-token' => $token)));
 }

while test() is callback for menu 'user/reset/%/%/%'.

The issue is when the user access the link for first time user gets "Access Denied" for second time user successfully redirects to edit profile page with password reset option. I think issue must be in the way the token is generated as it is the only thing which changes, but have no clue on how to fix this.

Drupal has an option to just login using the user reset link. When you add /login after the reset link the user is logged in directly and redirected to their their profile page.


The Views UI supports this.

Once you have your View configured, click on the "Settings" link in the Format section. You will then see a table that allow you to choose which column each field should appear in. See screenshot below. In this example, if you wanted the Author uid and Nid fields to appear in the same column, you would just select Author uid from the select list next to Nid (or vice versa).


Can I disable input filters in a view? I have created an admin-only view on a certain content type where we want to review the body content all in one place. The problem is that the input format for these nodes does some additional glossary markup etc. and we want to see the raw body content.

Is there a way to disable or change the input format for this view without changing it for each node?

I hope i understand the question correctly:

In views you can check the option "Strip html tags" in options.


How to hide install new module link on http://localhost/admin/modules page? I want to hide install new module link on http://localhost/admin/modules page?

I have created a new user role he/she have all admin rights(Editor Role), but I don't want to show install new module link to that user so that user should not be able to install any module in the website.

Why not just remove the Administer modules permission under System for that role?


Create a hidden character field? How can I create a hidden character field in D7 for a text field that hides the user input like the password field does? For example a field called "social security number" should not display the users input in plain text, but instead hide the input. Is there a module that can do this? Or how would that be realized?

You can with '#type' => 'password' in  your form.

Ex:

$form['social_sec'] = array(
  '#type' => 'password',
  '#title' => t('Social Security'),
  '#description' => t('Please enter your social security number'),
  '#size' => 9,
  '#maxlength' => 9,
  '#required' => TRUE,
);

If you want this as a field in a node's form, then you will have to use hook_form_BASE_FORM_ID_alter and alter an already existing field.


How do I add jQuery to specific node form? I'm using an Omega sub-theme and I want to do this the correct (best practice) way.

Basically I'd like to add some script so that selects a value in a select box based on a previously selected value in another select box. I have the code, just need to plug it in to my theme now.

However, I only want it to load on node creation forms of node type "X".

Any help greatly appreciated, thank you!

Install the JS injector module. Then go to admin/config/development/js-injector. Add a new rule. Fill the JS code field with your script.
In the Pages fieldset select the Pages on which this PHP code returns TRUE (experts only) option and enter the following code:
<?php
if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'content_type') {
 return true;
}
return false;
?>

Replace content_type with your content type name.
This is a theme independent solution. Another way is adding your script in hook_preprocess_page in template.php file of your theme.


How to edit a web form value so that the column name can be as required in a table in UI I have a submissions form where I am displaying all the form submissions in a table with custom columns, which I build from my form elements I created. But also I am using an built-in drupal column called 'completed', which will display the date and time of the submissions. I need to edit this column name to 'submitted at'.

I tried theme_table and module_table methods to edit the value but I am not able to hit those methods. When I tried hook_form_alter I am not able to see the table values when I did var_dump($form) to edit them in form[] array. I kept knit(_context) in the twig file of the table and I am able to see the values of the table and the value is coming from _context->few layers  Drupal\Core\Template\AttributeString.

How do I use this info in form_alter or any other hook to edit that string value?

Like I don't know how to use _context array in form_alter method. when I tried form['_context'] its giving me null.

I was able to edit it using theme_preprocess_table method below is the method which I used.

   function theme_preprocess_table(&$variables)
   {
       $variables['header']['completed']['content'] = 'your requirement';
   }