drupal 7 module for nodes with views I have a problem to find a right module in drupal to do something that should be simple.

I need my web content out into two columns. Entering a node should have title and description in the center column, and then a right column with related documents. It should be the same type of content.

In a previous work had solved with "views", the result:
http://www.imasmallorca.net/ca/unprograma/335

The problem to do with "views" it was not working the bread crumbs, nor the search. Neither the menu worked properly (not marked as an asset corresponding point)

Now, I'm working with "panels" to avoid this problem. It allows me to create columns, and embed a view with eg documents. The problem is that if I use a "panel page" does not appear in the search, and if I create a "panel node" I can pass arguments to the view in the right pane.

The question is: Is this right module? Should look for another module? is there another proper way to do this in Drupal?

Excuse my language, I'm Spanish :)

Thank you very much for your help, in another post I have been very useful.

Panels is the right module to control this kind of layout. You should be using the node/%node panel in Page Manager and be overriding that.
http://example.com/admin/structure/pages/nojs/operation/node_view/handlers/node_view_panel_context/content

The documents should be uploaded to the Node during editing. If you are missing a field for Documents create a Documents field in the node Content Type of Field Type file. Allow it to have infinite values.

Return to Page Manager > Content. Add content into the right hand panel (using the gear icon). Choose Node and locate your Field: Documents. Add that.

Add your other content into the centre panel. Your left hand panel can be a block (for example a Menus block).


how to create next and previous month menu link in calendar in drupal 7 how to create next and previous menu link in calendar in drupal 7

  Next month >>                              << Previous month

             ---- calendar area ----

Use Calendar Module.

From project page..

  This module will display any Views date field in calendar formats, including CCK date fields, node created or updated dates, etc. Switch between year, month, and day views. Back and next navigation is provided for all views. Lots of the Calendar functionality comes from the Date module, so any time you update the Calendar module you should be sure you also update to the latest version of the Date module at the same time.

Hope this will help you.


How to specify default options in a checkbox field using Field API I am trying to add a checkbox field to user entities using the FIELD API (in function MYMODULE_install() )

I can create the field, but I can't pre-load it with the desired default values.

Where my code is wrong ?

$default_notification_field_name = "field_notification_defaults";
if(!field_info_field($default_notification_field_name))   { // check if the field already exists.

    field_create_field(
        array(
            'field_name' => $default_notification_field_name,
            'cardinality' => FIELD_CARDINALITY_UNLIMITED,
            'type' => 'list_text',
            'settings' => array(
                'allowed_values' => array(
                    'group' => t('Groups to which you subscribe'),
                    'content' => t('Authored content'),
                    'comment' => t('Replies to your comments')
                )
            ),
        )
    );

    field_create_instance(
        array(
            'field_name' => $default_notification_field_name,
            'entity_type' => 'user',
            'bundle' => 'user',
            'label' => t('Default settings for notifications'),
            'description' => t('Select the default notification options for the groups to which you subscribe, the contents you send and the replies to (your) comments. These default options can then be modified on a per-group, content or comment bases.'),
            'required' => FALSE,
            'widget' => array(
                'type' => 'options_buttons',
            ),
            'default_value' => array('content','comment')
        )
    );
}

Try this for your instance creation:

field_create_instance(
  array(
    'field_name' => $default_notification_field_name,
    'entity_type' => 'user',
    'bundle' => 'user',
    'label' => t('Default settings for notifications'),
    'description' => t('Select the default notification options for the groups to which you subscribe, the contents you send and the replies to (your) comments. These default options can then be modified on a per-group, content or comment bases.'),
    'required' => FALSE,
    'widget' => array(
      'type' => 'options_buttons',
    ),
    'default_value' => array(
      0 => array(
        'value' => 'comment',
      ),
      1 => array(
        'value' => 'content',
      ),
    ),
  ));

To assist you in knowing the array structure, try this:

Install the devel module
Go to the page /devel/php on your site
Run this code to see all field information on your site:

// Show all fields.
dpm(field_info_fields());
// Show all field instances.
dpm(field_info_instances());


Using taxonomies with Field Collection in Drupal 7 How do you create a taxonomy listing when the field is being used in a field_collection field type?

I'm working on modifying the Article content type for a newspaper website; specifically, I've added two field collections: one is a byline, with two fields ("author" [taxonomy] and "position" [text]; e.g. "Ændrew Rininsland, Production Editor") and another is an image, with three fields plus the image ("caption" [text], "author" [taxonomy], "organization" [text]).
Both of these are set to have unlimited values, such that each story can have multiple bylines and multiple photos, each with its own caption and photo credit.

What I'm wanting to do now is use the "author" taxonomy term to create a listing of each story each author/photographer has contributed to. Simply going to the term's taxonomy page doesn't work; that only lists nodes with attached taxonomy terms, not fields (such as a field_collection). See this issue.

Ultimately, I'd build a view that looks at the taxonomy term and then uses a node reference for other information supplied. The Second post in your issue points to another issue that contains a lot info about views integration and node references. If you can't find a solution there, I'd add your needs into the mix and follow that discussion.


Rendering drupal login form in a modal window I need to display the login form in a modal window when a user clicks a link on my website. I am doing that using jquery ui dialog currently.

However, once the user logs in, i don't want a page refresh instead i just want the modal window to get reloaded with some content.

how do i achieve this?

Modal forms module might help you.

Modal forms make use of the modal feature in the ctools module to open some common forms in a modal window.
Supported forms:

Log in (modal_forms/nojs/login) Request new password
(modal_forms/nojs/password) Create new account
(modal_forms/nojs/register) Contact (modal_forms/nojs/contact)
Comment (modal_forms/%ctools_js/comment/reply/%node) Webform
(modal_forms/%ctools_js/webform/%node)


Programmatically load webform edit page by SID I am trying to load an edit form like (drupal 7) : node/6/submission/72/edit into a custom page where I run the drupal_render_form

but I am not sure is this the same as node load form? can some one provide references on how to load webform submission edit page into a body of page.

thank you!

I managed to solve it by creating a custom module, with a custom page and inside the custom page I use the :

drupal_get_form

and it works perfect!


Converting Term names with special characters to Term ID's in Views I have a view where I want to use multiple termID's as arguments. I want to use a term name from the url and convert it to a termID. I've managed to do this easily enough and it works with simple 1 word terms or even multiple words by checking the 'Transform dashes in URL to spaces in term name arguments'

I have a few terms that have special characters eg: "news & politics".

Is there any way to have nice URL's (news-politics) and get views to recognise the correct term and convert it to the correct termID? Will I have to urlencode the ampersand? Will that even work?

Edit: You can setup path aliases for single taxonomy terms, but is a problem when you want to use the term name as a second argument in a path with multiple arguments eg:

Say I wanted to filter the view results by %1 News term then %2 News & Politics

/news/news-politics

second term would not be recognised.

You can use pathauto to set up automatic aliases for your taxonomy terms. Pathauto will take care of invalid url characters for you when it creates the automatic aliases. Then in your view use term id as the argument. The path of your view can either be taxonomy/term/% or the autoalias you set up/%


Unable to uninstall a module When I try to uninstall the "Commerce license" module, the following error appears :

  drupal module:uninstall commerce_license

[ERROR] SQLSTATE[42S02]: Base table or view not found: 1146 Table
         'www.domaine.com.mg433jdr_commerce_license__license_role' doesn't exist: UPDATE
         {commerce_license__license_role} SET deleted=:db_update_placeholder_0
         WHERE bundle = :db_condition_placeholder_0; Array
         (
             [:db_update_placeholder_0] => 1
             [:db_condition_placeholder_0] => role
         )

I do not know what to do. How to uninstall this module ?

Thank you

The solution for this, is a quite similar response for this question: Manually disable a module take a look. Hope that helps.


How can I set site.com/node/1 into site.com (clean)? I am trying to get my site as site.com and when I type the URL, I get site.com/node/1.

How can I get this done? If you can specify step by step, highly appreciated.

AB

I think @JimmyKo and @Gulok, misunderstood the question OR I myself misunderstood the question(If so comment me I will delete the answer).

As stated in the question,

  I am trying to get my site as site.com and when I type the URL, I get
  site.com/node/1.

The issue is user want site.com as his Front-Page but when he types site.com he is redirected to site.com/node/1.

If this is the case. You need to set your home page. Now to set the home page, you need to go Configuration/Site information for D7 and Configuration/Basic site setting for D8, there you set the front page path as shown in following images.

For D7 case,

For D8 case,

Now Reverse Case, In case I misunderstood the question

If you want to make your front page to some node like node/1, Go the same path as mentioned above and put your path there as shown in follwoign image. NOTE: There is a difference between D7 and D8 path which is '/', you can see in following images.

For D7 case,

For D8 case,

Other case(Less likely): Have downloaded other Font-page creating module or are you using panel which provides the option of making any panel a front-page. If that is the case, those modules are overriding this default setting, Hence you have to modify accordingly.


Limiting number of multiples in a drupal webform in an ajax callback I have a form with a select element to choose the number of guests you want to add to an event.  This select has an ajax callback that updates a container that holds a contact composite element.

I am trying to in my ajax callback update the number of multiple contact elements to the value of the number of guests select box.  Anyone have any thoughts?  If I use a form alter like below on initial load the number of elements updates correctly.

My alter attempting to just set multiple number outside ajax

function lebow_events_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['elements']['guest_info']['guest_contact']['#type'] = 'webform_multiple';
  $form['elements']['guest_info']['guest_contact']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#multiple'] = 10;
  $form['elements']['guest_info']['guest_contact']['#cardinality'] = 10;
  $form['elements']['guest_info']['guest_contact']['#sorting'] = FALSE;
}

My webform source

registration_type:
  '#type': select
  '#title': 'Registration Type'
  '#options': registration_types
guests_container:
  '#type': container
  '#states':
    invisible:
      ':input[name="registration_type"]':
        value: ''
  number_of_guests:
    '#type': select
    '#title': 'Number of guests'
    '#options':
      - '0'
guest_info:
  '#type': container
  '#title': 'Guest Info'
  guest_contact:
    '#type': contact
    '#title': 'Contact Info'
    '#multiple': 2
    '#multiple__add_more': '2'
    '#company__access': false
    '#phone__access': false
    '#address__access': false
    '#address_2__access': false
    '#city__access': false
    '#state_province__access': false
    '#postal_code__access': false
    '#country__access': false

My alter to add ajax callback (and try setting number of multiples)

function lebow_events_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

  $form['elements']['guests_container']['number_of_guests']['#options'] = ['' => '- None -'];
  $form['elements']['registration_type']['#ajax'] =
    array(
      'callback' => 'lebow_events_registration_change',
      'wrapper' => 'edit-guests-container',
    );
  $form['elements']['guests_container']['number_of_guests']['#ajax'] =
    array(
      'callback' => 'lebow_events_guests_change',
      'wrapper' => 'edit-guest-info',
    );

  $form['elements']['guests_container']['number_of_guests']['#validated'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#type'] = 'webform_multiple';
  $form['elements']['guest_info']['guest_contact']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#multiple'] = 10;
  $form['elements']['guest_info']['guest_contact']['#cardinality'] = 10;
  $form['elements']['guest_info']['guest_contact']['#sorting'] = FALSE;
}

My ajax callback

function lebow_events_guests_change(&$form, \Drupal\Core\Form\FormState $form_state) {

  $form['elements']['guest_info']['guest_contact']['#type'] = 'webform_multiple';
  $form['elements']['guest_info']['guest_contact']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#multiple'] = $form_state->getValue('number_of_guests');
  $form['elements']['guest_info']['guest_contact']['#cardinality'] = $form_state->getValue('number_of_guests');
  $form['elements']['guest_info']['guest_contact']['#sorting'] = FALSE;
  $form['elements']['guest_info']['guest_contact']['#element']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#element']['#multiple'] = $form_state->getValue('number_of_guests');

  $message = $form['elements']['guest_info'];

  $response = new \Drupal\Core\Ajax\AjaxResponse();
  $response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('[data-drupal-selector=edit-guest-info]', $message));

  return $response;

}

It is very difficult and sometimes impossible to alter a form via an Ajax callback.  Generally, an Ajax callback just returns the updated form element from the $form render array.

The Examples for Developers module includes several Ajax form examples that you can use as a starting point.


How can I check I run the Drupal Commons profile? Yesterday I installed Drupal Commons on http://campus-24.com/. The version was grabbed from http://commons.acquia.com/home, but I am not very sure I have chosen the Drupal Commons installation profile.
In general the installation ends up with the appearance of exactly the same theme that is shown on http://commons.acquia.com/home.
It is pretty interesting that the above mentioned site does not feel/look, and it does not behave as a Commons. In short: The look and feel, and the behavior of the site is totally neurotic! If I look in the administrative area, I have only the following 6 themes in the system to choose between:

Bluemarine
Chameleon
Marvin
Garland
Minnelli
Pushbutton

So I guess there isn't a clear evidence that I have installed the wrong profile, the Drupal standalone installation profile, and not the Commons profile. Where can I have a closer look at which profile is active?
Update
I finally got it: After several trials, I ported over an installation of the Drupal Commons that was smoothly installed on the local Lampp.

The profile used to install the site is stored in the variable install_profile. There's a few different ways you can see the value:

Pop into the variable table in your database and search for install_profile:

select value from variable where name='install_profile';

Install the Devel module and visit mysite.com/devel/variable
Put this custom code in a template file somewhere:

<?php print variable_get('install_profile', 'No install profile found.'); ?>

Hope that helps


Drupal homepage customization i want to add some feature in drupal home page, like:
1) All new posts will be arranged greed
2) A thumbnail will appear from post photos
3) Text of content will be minimized to 150 words
so, how to do it?
Thanks

What @Kantu already said. Take a look at this tutorial: Panels 3: Creating a new front page with Views and Panels 3.


List all blogs from users in same group I'm new to Drupal, and I'm using Organic Groups to make groups. The site is supposed to be a multi-blog platform where groups can have their own group and the group admin(only) should be able to get a list of all group members (linked to their blogs) in the side menu. How am I able to achieve this? Any help would be appreciated!

I found the following code from here:

<?php
    $query = db_select('node', 'n');
    $query->join('users', 'u', 'n.uid = u.uid');
    $query->join('file_managed', 'f', 'f.fid = u.picture');
    $query->fields('u',array('name'));
    $query->fields('n',array('type'));
    $query->fields('f',array('filename'));
    $query->fields('u',array('uid'));
    $query->condition('u.status', 1);
    $query->condition('n.status', 1);
    $query->condition('n.type', 'blog', '=');
    $query->addExpression('COUNT(n.uid)');
    $query->groupBy('u.uid');
    $query->groupBy('n.type');
    $query->orderBy('COUNT(n.uid)', 'DESC');
    $result = $query->execute();
    $output = array();
    while($record = $result->fetchAssoc()) {
    // print $record ;
     $output = '
';
     $output .= '

';
     $output .= '
'.$record['name']. 's Blog
Posts: ('.$record['expression'].')
';
     $output .= '
';
     $output .= '';
   //  $output .= '
'.l($record['name']. ' ('.$record['expression'].')', 'blog/'.$record['uid']);
    }
    echo $output;
?>

Unfortunately this gives me the following error:
Notice: Array to string conversion in include() on the last line (echo $output).

Any ideas on how I can achieve this with using Views?

Try setting $output = array(); to $output = ''; and see if that fixes the issue. Also, I would recommend using views instead of custom SQL query while dealing with Drupal.

Views


How to print edit link on a node page if the current logged-in user has access to node edit I'm using Display Suite custom fields to have my Edit link rendered somewhere else on the node page, I'd like to see if there's an easy way to check if the current user has the permission to edit the node or not.

So far I tried this:

<?php
global $user;
      if (node_access('update', $nid, $user) == true) {
       echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
      }
?>

unfortunately does not work, Thanks a million.

First of all you need to make sure to get access to your administrators as well as the author, also note that you need to load nid along with the uid

<?php
global $user;
$node = node_load(arg(1));
if(user_access('edit any "" content') || ($user->uid == $node->uid)){
    echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
}
?>


Calling a javascript function from a form item ajax callback? I am working on a project and I think I am stuck on this. I have a form that I want to add points to a map as users edit it.

Here's a rundown on how the form works:

The user chooses a number (1-10) for how many stops they'd like to make from a select list. The select list defaults to 1 and below it there is a select list that lists all of the points of interest they can choose from. If they change the first select to 2 the ajax callback updates the form and adds an additional select box of POIs. That's working great.

What I'd like to be able to do is add the POI to a map on the page whenever they select it (with driving directions between them). I have an ajax callback on the POI select list in order to do this but I am having trouble figuring out where to go from here.

I have the following in my POI callback (for testing) and it works, but I am having trouble figuring out what ajax_command_ function to use to call a js function to add the point to the map.

$commands = array();
$commands[] = ajax_command_alert("Here!");
return array('#type' => 'ajax', '#commands' => $commands);

Basically I just need to pass the latitude and longitude of the POI (which I am gathering in the callback) and send it to a js function to then update the map. My first thought was using drupal_add_js but I couldn't get it working and discovered later that it was not the right way to go.

Any thoughts?

PHP:

$commands[] = ajax_command_alert("Here!");
$commands[] = array(
  "command" => 'your_custom_command',
  "latitude" => "45.23",
  "longitude" => "23.25"
);

Javascript:

Drupal.ajax.prototype.commands.your_custom_command = function(ajax, response, status) {
  if( response.latitude != "" ) {
    // do something
  }
};


$user->uid is always 1 when running automated tests In my automated tests, I create some users.

  debug('moderator_user: '.$this->moderator_user->uid);
  debug('editor_user: '.$this->editor_user->uid);

outputs

'moderator_user: 2'
'editor_user: 4'

So I would think that

global $user;
$this->drupalLogin($this->editor_user);
debug('currently logged in as '.$user->uid);

would output

'currently logged in as: 4'

but instead it shows,

'currently logged in as: 1'

It seems to be correctly logging user 4 because

$this->drupalLogin($this->editor_user);
$edit = array(
  'title' => $this->randomName(),
);
$this->drupalPost("node/add/{$this->content_type}", $edit, t('Save'));
$node = $this->drupalGetNodeByTitle($edit['title']);

debug('Draft was created by user with uid '.$node->workbench_moderation['current']->uid);

yields

'Draft was created by user with uid 4'

So what's going on?

It happens exactly what described in the documentation page for DrupalWebTestCase::drupalLogin().

  Please note that neither the global $user nor the passed-in user object is populated with data of the logged in user. If you need full access to the user object after logging in, it must be updated manually. If you also need access to the plain-text password of the user (set by drupalCreateUser()), e.g. to log in the same user again, then it must be re-assigned manually. For example:

  // Create a user.
  $account = $this->drupalCreateUser(array());
  $this->drupalLogin($account);
  // Load real user object.
  $pass_raw = $account->pass_raw;
  $account = user_load($account->uid);
  $account->pass_raw = $pass_raw;


Workbench moderation repeats "Save and " in the button labels My workbench moderation label is, for example, Save as draft, but the button says Save and Save as Draft.  How can I get rid of that Save and , which is repeated for every button?

Save and has been hardcoded in the Workbench Moderation module.


Trouble after updating to 2.0 I got a notice to update composer to 2.0 today and gave it a try, using "composer self-update --2". Now when I run composer update, I'm seeing this message.

The "grasmash/composerize-drupal" plugin was skipped because it requires a Plugin API version ("^1.0.0") that does not match your Composer installation ("2.0.0"). You may need to run composer update with the "--no-plugins" option.

I then tried installing colorbox and see "drupal/colorbox": "^1.6" in composer.json, but it does not appear when I refresh the extend page; is this related to the above problem?
Next, I tried updating core from 8.9.6 to 8.9.7, following a message I saw, I tried composer update drupal/core-recommended --with-dependencies -W --no-plugins and now I see this message.
  Problem 1
    - Root composer.json requires composer/installers ^1.2 -> satisfiable by composer/installers[v1.7.0].
    - composer/installers v1.7.0 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.0.0] but it does not match the constraint.
  Problem 2
    - composer/installers v1.7.0 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.0.0] but it does not match the constraint.
    - signature_pad/signature_pad 2.3.0 requires composer/installers ~1.0 -> satisfiable by composer/installers[v1.7.0].
    - signature_pad/signature_pad is locked to version 2.3.0 and an update of this package was not requested.

I don't understand all these errors, and I am afraid to do anything else. How do I get out of this without reverting composer to 1.x?

grasmash/composerize-drupal is used to convert a Drupal site that wasn't created with Composer into a Drupal site managed with Composer.
Once the plugin converted the site, it can be removed. After the plugin is removed, modules and themes must be added with composer require, not downloading the archive containing the module/theme files.
If that is the only plugin that isn't compatible with Composer 2.x, you can remove it, as it's not necessary to keep it installed.
Drupal 8.9 is compatible with Composer 2.x; it should not create issues with that Composer version.


Why is "drush make" installing a library in /sites/all/libraries instead of /libraries? I am trying to allow prospective users to demo my module on simplytest.me, however, it requires an external javascript library. I recently created a drush make file for the D7 version of this module, and it is working fine. The D8 version is downloading the library, but placing it in drupalroot/sites/all/libraries instead drupalroot/libraries. Is there a way to change this behavior? Here is my make file.

api=2
core = 8.x
projects[drupal][type] = core
libraries[flot][download][type] = get
libraries[flot][download][url] = https://github.com/flot/flot/archive/master.zip
libraries[flot][destination] = libraries
libraries[flot][directory_name] = flot

I tried using libraries[flot][destination] = /libraries but that did not change the behavior.

Edit: I changed to a make.yml file, but this does not even download the library.

api: 2
core: 8.x
projects:
  - drupal
libraries:
  flot:
    destination: "libraries"
    directory_name: "flot"
    download:
      type: "get"
      url: "https://github.com/flot/flot/archive/master.zip"

drush status tells me that I have version 5.10.0, so that's likely the issue. D8 support was not added until drush 8. Now I need to get upgraded.


Migration query works but migration fails due to sourceid not being found Here is my migration class:

class TaxonomyPrice extends SqlBase {
  /**
   * {@inheritdoc}
   */
  public function query() {
    $table1 = $this->select('venue', 'v')
      ->isNotNull('price')
      ->condition('price', '', '!=')
      ->groupBy('price')
      ->fields('v', ['price']);

    $table2 = $this->select('item', 'i')
      ->fields('i', ['price'])
      ->isNotNull('price')
      ->condition('price', '', '!=')
      ->groupBy('price')
      ->union($table1);

    $table3 = $this->select('nodes_venues', 'nv')
      ->fields('nv', ['price'])
      ->isNotNull('price')
      ->condition('price', '', '!=')
      ->groupBy('price')
      ->union($table2);

    return $this->select('sc_article', 'sca')
      ->fields('sca', ['price'])
      ->isNotNull('price')
      ->condition('price', '', '!=')
      ->groupBy('price')
      ->union($table3);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {

    $fields = [
      'price' => t('Term name'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'price' => [
        'type' => 'string',
      ],
    ];
  }
}

When I run drush ms I can see the correct number of items being counted.

$ drush ms taxonomy_price
 Group: Taxonomy Migrations  Status  Total  Imported  Unprocessed  Last imported
 (taxonomy_migration)
 taxonomy_price                Idle    121    0         121

But when I try to run the migration it gives me an error related to the sourceid.

$ drush mi taxonomy_price
Migration failed with source plugin exception: SQLSTATE[42000]: Syntax error or access violation: 1055     [error]
'drupal_8.map.sourceid1' isn't in GROUP BY: SELECT sca.price AS price,
map.sourceid1 AS migrate_map_sourceid1, map.source_row_status AS migrate_map_source_row_status
FROM
{sc_article} sca
LEFT OUTER JOIN drupal_8.migrate_map_taxonomy_price map ON price = map.sourceid1
WHERE  (price IS NOT NULL ) AND (price != :db_condition_placeholder_0) AND( (map.sourceid1 IS NULL ) OR
(map.source_row_status = :db_condition_placeholder_1) )
GROUP BY price UNION SELECT nv.price AS price
FROM
{nodes_venues} nv
WHERE  (price IS NOT NULL ) AND (price != :db_condition_placeholder_2)
GROUP BY price UNION SELECT i.price AS price
FROM
{item} i
WHERE  (price IS NOT NULL ) AND (price != :db_condition_placeholder_3)
GROUP BY price UNION SELECT v.price AS price
FROM
{venue} v
WHERE  (price IS NOT NULL ) AND (price != :db_condition_placeholder_4)
GROUP BY price; Array
(
    [:db_condition_placeholder_0] =&gt;
    [:db_condition_placeholder_1] =&gt; 1
    [:db_condition_placeholder_2] =&gt;
    [:db_condition_placeholder_3] =&gt;
    [:db_condition_placeholder_4] =&gt;
)

I read through the documentation for getIds(), but I didn't see anything there that would help me figure out what's wrong.

The relevent part of the error message is "'drupal_8.map.sourceid1' isn't in GROUP BY". Let's look at the query as executed:

SELECT sca.price AS price,
map.sourceid1 AS migrate_map_sourceid1, map.source_row_status AS migrate_map_source_row_status
...
GROUP BY price

SQL requires that all columns being selected be part of the GROUP BY. The SqlBase class has determined that your source query can be joined directly to the migration's map table, and thus performs the join as an optimization, adding the map table fields to the columns returned. However, it doesn't add them to the GROUP BY. There's an issue for that: https://www.drupal.org/node/2844595. For now, you can set

ignore_map: true

in your source plugin's configuration to prevent the join and it will work.


How to check if current page is a group entity? Im using drupal 7 and group module

I am trying to run some code only if the current page is a group.

here is my code

<?php
$arg = arg(0);
$arg1 = arg(1);
global $user;
if($arg ='group' && is_numeric($arg1)) {
    $group = group_load($arg1);
    if($group->getMember($user->uid)) {
       print ('user is member');
    };
};
?>

If this is placed on a group page it will print user is member if the current user is a member. If the current user isn't a member it will not show anything. Which is what it is supposed to do.

If I navigate to a none group page I get an error 'Error: Call to a member function getMember()',  but the if statement should prevent this?

How do I check if the current page is a group entity?

Thanks

Edit

I wanted to return true if a group page and user is a member of the group.
Using menu_get_object by Jaypan I used the code below to show. Im checking if page is group if so loading the group then checking if the user is a member of the group.

if (!empty(menu_get_object('group')))
   {
   $group = group_load(arg(1));
   if($group->getMember($user->uid)) {
       return TRUE;
    }
}

You can get the object for the current page in Drupal 7 using menu_get_object().

if ($group == menu_get_object('group')) {
  // do something with $group
}


granularity of views filter on date field I have a content type which has a date field. That date field collects:

Year
Month
Day
Hour
Minute

I've created a view with a filter on that field. The granularity I can filter with only goes down to day. Even if I use operator: is greater than and Relative date: now, the contents of the view only change once a day. That means that hour and minute are not taken into consideration.

Any ideas on how to solve this?

1) Double check your field is collecting the correct date attributes.
2) Make sure "Date Views" is enabled under Modules (Requires: Date API, Views, Chaos tools).

If the above are okay then try creating a new date field making sure you're collecting all date attributes. This should rule out any issues there might be with the field. It could also pay to try create a new date field in a different content type and see how views reacts.

If the new date field doesn't work and views still can't filter down to seconds granularity then try a new test view.

Tested with no problems on Drupal 7.18, Date 7.x-2.6 and Views 7.x-3.5.


Hide create new account tab How to hide Create new account and Request new password tabs in user login form? I use Drupal 7. I use custom theme. Maybe in template.php file some function?

You can see my page - http://broceni.garm.lv/

The Tab Tamer module will do it for you without having to write a single line of code:

  Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.


Move a site hosted on IIS/MS SQL Server across to LAMP stack I have a Drupal 7 site which is currently hosted in a Windows servers environment (e.g. IIS and MS SQL Server). The site needs to be moved over to Platform.sh, which is using the LAMP stack.

I am wondering if there are likely to be any issues with doing this? For example, is it possible to simply export the existing database from MS SQL Server and then import it into MySQL on the new site using drush?

There shouldn't be any issues as such if you properly follow the steps of Migrating a Drupal Site. You can find detailed steps on How to Migrate a Site.

This documentation provides a detailed documentation on Backing up and migrating a site.

Regarding taking a database backup of Site, you can checkout Backup and Migrate Module for quick and easy database backup of site. Here's how you can quickly setup Backup and Migrate module and backup your site databse.


How do you get the display settings of a field on a particular content type/display I'm looking to preprocess a field.

The field type I'm wanting to preprocess is an entity reference field.

I need to know what view mode has been selected on the display settings for this field (see screenshot below).

This information is not made available in the $variables variable passed into preprocess_field.

So how can I get this load this information? I have tried looking for some Drupal-specific functions that would return these settings but haven't found anything that works.

Many thanks.

You're looking for field_info_instance()

  Returns an array of instance data for a specific field and bundle

Example usage:

$info = field_info_instance('node', 'field_foo', 'article');
$display_settings = $info['display'];

$display_settings will be an array of display settings keyed by the view modes that are customisable for that content type and bundle.


Drush not working on Multisite with Shared User Table I have a Drupal 7 Multisite Environment with sub-directories.

(E.g):

mainsite.com
mainsite.com/multisite1
mainsite.com/multisite2
mainsite.com/multisite3
etc.

Each website has its own Database and all are on the same Database Server

I recently configured the multisites to have a Shared User table along with a few shared custom User fields and that aspect works.

However, I am now unable to use Drush within the Multiste directories.

Previously, I would CD into the directory and be able to run Drush commands for that specific multisite like this:

cd /var/www/mainsite.com/sites/multisite1
drush cc all

Now it tells me that "No Drupal site found".

When I comment out the prefix portion of my settings.php file, Drush works again.

How can I make Drush work for these sites?

Below is what my settings.php file looks like:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => '[Multisite DB]',
  'username' => '[Database Username]',
  'password' => '[Database Password]',
  'host' => '[DB Server IP]',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',
  'prefix' => array(
        'default'   => '[Multisite DB].',
        'users'     => '[Main Site DB].',
        'sessions'  => '[Main Site DB].',
        'role'      => '[Main Site DB].',
        'authmap'   => '[Main Site DB].',
        'users_roles'   => '[Main Site DB].',
        'field_data_field_first_name'   => '[Main Site DB].',
        'field_data_field_last_name'   => '[Main Site DB].',
        'field_data_field_title'   => '[Main Site DB].',
  ),
);

The solution ended up being very simple.

I just had to change one line.

I changed this:

        'default'   => '[Multisite DB].',

to:

        'default'   => '',

This is how it looks all together.

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => '[Multisite DB]',
  'username' => '[Database Username]',
  'password' => '[Database Password]',
  'host' => '[DB Server IP]',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',
  'prefix' => array(
        'default'   => '',
        'users'     => '[Main Site DB].',
        'sessions'  => '[Main Site DB].',
        'role'      => '[Main Site DB].',
        'authmap'   => '[Main Site DB].',
        'users_roles'   => '[Main Site DB].',
        'field_data_field_first_name'   => '[Main Site DB].',
        'field_data_field_last_name'   => '[Main Site DB].',
        'field_data_field_title'   => '[Main Site DB].',
  ),
);

I know that a lot of people use Bakery or are already on Drupal 8, but I hope this helps anyone still on Drupal 7 looking to share a User table across multiple websites with different databases.


Provide autocomplete field with user's Display Name Drupal core already supports autocompletion of username fields. However is there a way to provide autocomplete for user's Display Name? Since this is a virtual field, a database query with % like cannot be performed.
One way I could think of accomplish this would be to save display name for each user in the user_data table, and set this storage with an event subscriber that reacts on account creation and account update. Once this field is available, it could then be used with database queries for autocomplete.
Interested to know if there is another way to do this.

I looked at realname module, which autocompletes the real name. Since realname stores the user defined DisplayName equivalent in the database, it can issue % LIKE queries and autocomplete on both username and realname.

I posted this question to see if there were other approaches, the realname module validates the proposed method as asked in the question.


Using Feeds Tamper to convert one list to another? I am using a feeds importer to import a number of FIPS county codes for given locations and I was hoping to use the Feeds Tamper module to convert those county codes to county names, but have thus far been unsuccessful. Any ideas? I realize that there is a "Find replace" plugin for the Feeds Tamper, but seeing as this seems only to convert a single word or phrase at a time, I'd have to do this too many times for it to be worthwhile, though it does seem to reveal that the module is capable of doing the task I desire.

Thanks in advance,

David

For like http://www.census.gov/2010census/xls/fips_codes_website.xls use Feeds or Migrate modules to fill-in a Content Type with the Fields in the Excel file. The are many tutorials online of importing data from a csv or excel sheet to Nodes.


BrowserTest gives wrong connection I am running a test that extends a BrowserTestBase and indicated a custom module as a dependency. The module has a mymodule_module_preinstal() that is supposed to perform a DB query using Drupal::database().

After wasting some time on figuring out why it does not work I realized that the query is run against the main databse of the installation, not that which I had set up in phpunit.xml.

That's really confusing - why is it working like that and why on earth would I want to work with the main database while running a test which is supposed to be run in an isolated database?

And, most importantly, how do I run the query against the test database?

Excerpt from documentation:

  It's terribly important to realize that each test runs in a completely new Drupal instance, which is created from scratch for the test. In other words, none of your configuration and none of your users exists!

Here's code of my test:

class FormTest extends BrowserTestBase
{
    public static $modules = ['mymodule', 'mymodule2'];

    public function testFormPage()
    {
        $response = $this->drupalGet('/mymodule/register');
    }
}

I've also copied phpunit.xml.dist to phpunit.xml and set up this line:

<env name="SIMPLETEST_DB" value="mysql://mydb_tests:password@localhost/mydb_tests"/>

I run my test like this:

cd core
phpunit ../modules/mymodule/tests/src/MyTest.php

I have installed the version of phpunit from core/composer.json globally.

The preinstall hook looks like this:

/**
 * Module preinstall hook
 * @param $module_name
 */
function mymodule_module_preinstall($module_name)
{
    var_dump($module_name);

    print_r(Drupal::database()->query("SHOW TABLES")->fetchAll());
    exit();
}

Show tables doesn't work like that. I doesn't know anything about prefixes, it lists all tables in the database.

The schema API has an API method to list tables, which is DB agnostic and respects the prefix.


user_mail_tokens is undefined I keep getting an error in a site I am trying to work on, which is base don another. The error is in a custom module, and the code line is

if (!function_exists('user_mail_tokens'))
{
    include_once(drupal_get_path('module', 'modulename').'/modulename_e.inc');
 }

As I said this is a copy of another site, which runs. grep shows that the file _e.inc doesn't exist in the other project, so I can only assume that the tokens are defined elsewhere. a Google search implies that the method is sttandard, so I don't want to create a new inf file that redefines it. So where should 'user_mail_tokens' be defined?

Matt -
The user_mail_tokens is a function provided by the user module (Drupal 7 core). Essentially, what your code is saying is:

If the function user_mail_tokens exists (which it should because it's a core function, however these conditional checks are awesome and important), then we are going to include an include file located at /sites/all/modules/modulename/modulename_e.inc.

As to why your code is throwing an error for user_mail_tokens that is an interesting question. I'm looking into it now. Part of me wonders if we should  just say module_exists

What is the need to check the user_mail_tokens?


How to use the stomp module to send and receive a queue? Hello everyone,

I downloaded the stomp module for drupal and I just can't find any tutorial on how to use it.

I'd like to send and receive queues to and from activemq. I've an MQConsumer.php class and an MQProducer.Php class which use the fusesource stomp library and I'd like to integrate it to drupal.

I mean I've installed the module and there's like no feedback from the system. Like no UI.

Can anyone tell me how it works? I'd like to test and extend it's functionality. Thanks

Drupal supports its own Queue interface out the box. See https://api.drupal.org/api/drupal/modules%21system%21system.queue.inc/group/queue/7  The stomp module when configured simply moves the queue infrastructure out of Drupal and into a 3rd party system.

See the readme on this integration settings http://cgit.drupalcode.org/stomp/tree/README.txt


generate or extract a automatic thumbnail for a video file using Video module in drupal 7 I need to show a video thumbnail of a video file which the admin upload using the video module.

I have a content type called MEDIA.I have created field as with following settings.

   LABEL             NAME           FIELD   WIDGET           OPERATIONS

   Upload Videos    field_video Video   Video Upload    edit    delete

Here The following setting I have set for the Upload videos label

         UPLOAD VIDEOS FIELD SETTINGS

These settings apply to the Upload Videos field everywhere it is used.

    Number of values: 1

   Upload destination
   Public files:checked

Enable auto video conversion:checked
 Convert videos automatically using FFmpeg or Zencoder. You can define presets at preset        settings to automatically convert videos to web compatible formats eg. FLV, MP4. Make sure   to configure your transcoder settings to make this work properly.
Video thumbnails
Automatically extract thumbnails from video (with fallback to manual upload):checked

  If you choose Automatically extract thumbnails from video then please make sure to      configure your transcoder settings to make this work properly.

Here I have checked the Automatically extract thumbnails from video  check box and I have saved it.

I have configure the transcoder  setting as follows.(I am working on windows XP)

  Video transcoder
    FFmpeg:checked
  Select a video transcoder will help you convert videos and generate thumbnails.

    Zencoder is unavailable: The Zencoder API module has not been setup properly.
   PATH TO FFMPEG EXECUTABLE
    FFMPEG:C:/xampp/htdocs/newsite/ffmpeg/bin/ffmpeg

   Absolute path to FFmpeg executable.When you install a new FFmpeg version, please clear the caches to let Drupal detect the updated codec support.
   VIDEO THUMBNAILS
    Path to save thumbnails:videos/thumbnails

    Path to save video thumbnails extracted from videos.
    Number of thumbnails:5

    Number of thumbnails to extract from video.
    Save all thumbnails in {file_managed} table
    Save all auto-created thumbnails to the {file_managed} table. Change file status as PERMANENT

Then I created a new media article where i upload the video from my system and But what happens the video thumbnail is not extracting from the video which I upload.

Can anyone help me.Please forgive me for my english

Are there any messages in your Drupal error log related to video transcoding? Also, try to update to the latest version of the Video module.


What is the correct way to set cache contexts on custom blocks? I have run into an issue where a block that should be unique per page isn't for logged-out users.  The issue is a custom block plugin I have on a views search page that contains custom filters (sort of like a custom replacement for exposed filters. the block placed through /admin/structure/block).

Based on what I have learned about Drupal 8, I added the cache contexts to my build array:

  public function build() {

    $search_form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\SearchForm');
    return [
      'search_form' => $search_form,
      '#cache' => ['contexts' => ['url.path', 'url.query_args']]
    ];

  }

But it seems this must be incorrect because when logged-out, the block would get cached on the first view, and when the url changed, it wasn't showing a new version of the block.

I thought it might be the view page that was causing the issue, but even when I turned caching off on the view page, the issue remained.

I was able to fix the issue several ways, for example, by using a preprocess_block hook:

function mymodule_preprocess_block__mycustomsearchblock(&$variables) {
  $variables['#cache']['contexts'][] = 'url.path';
  $variables['#cache']['contexts'][] = 'url.query_args';
}

But it bothered me I couldn't just put the cache contexts into my block's build array.

Since my block extends BlockBase, I decided to try out the getCacheContexts() method, especially since I saw some modules within core are doing it this way.

  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), ['url.path', 'url.query_args']);
  }

This is also fixed the issue, but interestingly, when I output the variables in the preprocess block function, these are not showing in $variables['#cache']['contexts'], but they do show in $variables['elements']['#cache']['contexts']

array:5 [▼
  0 => "languages:language_interface"
  1 => "theme"
  2 => "url.path"
  3 => "url.query_args"
  4 => "user.permissions"
]

I'm trying to figure out how this works, and why it wasn't working from the build function.

Looking at /core/modules/block/src/BlockViewBuilder.php at the viewMultiple() function, it looks like it pulls the cache tags from the entity and the plugin:

'contexts' => Cache::mergeContexts(
  $entity->getCacheContexts(),
  $plugin->getCacheContexts()
),

So that explains why adding a getCacheContexts() method to my block plugin adds the contexts to my block.  Also, looking at the preRender method in the same class, it looks like it doesn't use the cache array in the blocks build function, which confuses me, as it seems the way to add caching in Drupal 8 is to add a #cache element to render elements.

So my question is,

1) Are cache contexts added directly on the array in a block plugin ignored?

2) If so, is there a way around that, do we need to add it to a child element of the build array?

3) If context added directly is ignored, is adding a getCacheContexts() the way to go for block plugins in custom modules?

In most cases, you just set the cache context directly on the render array you return in your build() method.

I have finally found what my issue was, with the help of @Berdir and @4k4.  If you are using a custom template, such as block--myblock.html.twig and you output the variables individually, such as {{ content.foo }} instead of all at the same time like {{ content }}, it ignores your cache contexts passed directly into your block build array, when logged out.  See What is the correct way to set cache contexts on custom blocks?

So, to answer the original question:

1) Cache contexts passed directly into a custom block plugin are sometimes ignored.  You can test this by altering the SyndicateBlock, and then creating a custom template in your theme block--syndicate.html.php in which you output the variables individually like this:

{% block content %}
  {{ content.foo }}
{% endblock %}

As you change the url arguments, you'll see the block doesn't respect the cache context.

Now if you change it output all the content as a piece, it works:

{% block content %}
  {{ content }}
{% endblock %}

Now, it respects the cache context, and the block is unique per page.

2)  For now, to work around this, you can just output what's in your block in it's own template.

 public function build() {

    $search_form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\SearchForm');
    return [
      '#theme' => 'mycustomtemplate',
      '#search_form' => $search_form,
      '#cache' => ['contexts' => ['url.path', 'url.query_args']]
    ];

  }

This circumvents the block module's esoteric caching exceptions and your form is now unique per page when logged out.

3) Should you create your own theme template to fix this, or just add a method for getCacheContexts() in your custom Block plugin?  It's better to create a new theme template, rather than add a getCacheContexts() method that overrides the natural order of bubbling up of cache contexts, and may break metadata deeper in your build array.


how to update the form values after pressing the submit button Below I have written code for update but when I change the value in form and press submit button still those old values goes to the database. My question is how to get current edited value of my form after it is displayed?

function upgrade_menu(){
    $items = array();
    $items['upgrade_page'] = array(
    'title' => t('Upgrade'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(' upgrade_update'),
    'access callback' => TRUE,
    );
    return $items;
}

function upgrade_page($form, &$form_state) {
    if (!isset($form_state['storage']['upgrade_module']['search_criteria'])) {
        return drupal_get_form('upgrade_form');
    }
    $title = $form_state['input']['Name'];
    $query = db_select('form_test', 'n')
    ->condition('name', $title, '=')
    ->fields('n',array('name','Id','age','email','salary'));
    $results = $query->execute();
    $res = $results->fetchAssoc();
    $form['Name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',
        '#value' => $res['name'],
    );
    $form['Id'] = array(
        '#title' => t('Id'),
        '#type' => 'textfield',
        '#value' => $res['Id'],
    );
    $form['Age'] = array(
        '#title' => t('Age'),
        '#type' => 'textfield',
        '#value' => $res['age'],
    );
    $form['Emailid'] = array(
        '#title' => t('Emailid'),
        '#type' => 'textfield',
        '#value' => $res['email'],
    );
    $form['Salary'] = array(
        '#title' => t('salary'),
        '#type' => 'textfield',
        '#value' => $res['salary'],
    );
    $form['submit'] = array(
        '#value' => 'Update',
        '#type' => 'submit',
        '#submit' => array('upgrade_update'),
    );
    return $form;
}

function upgrade_form($form, &$form_state) {
    $form['criteria'] = array(
        '#type' => 'fieldset',
        '#title' => 'Update',
        '#attributes' => array('class' => array('container-inline')),
    );
    $form['criteria']['Name'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
        '#value' => (isset($form_state['input']['Name'])) ? $form_state['input']['Name'] : "",
        '#size' => 10,
        '#maxlength' => 20,
    );
    $form['criteria']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'search',
        '#submit' => array('upgrade_submit'),
    );
    return $form;
}

function upgrade_submit($form, &$form_state) {
    $form_state['storage']['upgrade_module']['search_criteria'] = $form_state['values'];
    $form_state['rebuild'] = TRUE;
}

function upgrade_update($form, &$form_submit) {
    $name =  $form_submit['values']['Name'];
    $Id = $form_submit['values']['Id'];
    $age = $form_submit['values']['Age'];
    $email = $form_submit['values']['Emailid'];
    $salary = $form_submit['values']['Salary'];
    drupal_set_message(t('You provided a  name',array('name' => $name)));
    drupal_set_message(t('You provided a  Id',array('Id' => $Id)));
    drupal_set_message(t('You provided a  age',array('age' => $age)));
    drupal_set_message(t('You provided a  email',array('email' => $email)));
    drupal_set_message(t('You provided a salary',array('salary' => $salary)));

    $entry = array(
        'name' => $form_submit['values']['Name'],
        'id' => $form_submit['values']['Id'],
        'age' => $form_submit['values']['Age'],
        'email' => $form_submit['values']['Emailid'],
        'salary' => $form_submit['values']['Salary'],
    );
    $table = 'form_test';
    $return_value = db_update($table)
    ->fields($entry)
    ->condition('email',$email,'=')
    ->execute();
    print drupal_set_message('Database is successfully Updated..');
    return $return_value;
}

You're mixing up #value and #default_value. If you want to show information in the form but let the user change it, you need to use #default_value. If you want the information to always be the same, and never let the user change it, use #value.


Link field is removing query parameters We have an Article that a link field, field_link. When we create a new page of type Article, we set the link field to have a URL of www.example.com/somepath?someid=123345 and label of View. When the page is rendered, we are seeing the query parameter is being removed (i.e. ?someid=123345). We are not doing any hooks or extra logic in twig templates to remove the query parameters.

How can we prevent the query parameters from being removed when rendering the field_link field?

Current behavior when link is rendered:

View

Expected behavior

View

In review, we had the wrong setting for the link. By setting Both internal and external links, the link was displaying properly with the query parameters.

In Summary

Both internal and external links should be set on the field setting
Ensure to use https:// in the beginning of the url


Drush is not recognizing Acquia extension I am using Acquia and Drush 8.1.8. I am following Acquia's instructions to load Drush extensions and aliases. My ~/.drush directory looks like this:

nickheiner@Nicks-MacBook-Pro.local:~/.drush  λ ls -l ~/.drush/
total 176
-rw-------@ 1 nickheiner  staff  43320 Feb  9 13:25 acapi.drush.php
drwxr-xr-x  6 nickheiner  staff    204 Feb  9 13:26 cache
-rw-------@ 1 nickheiner  staff   6026 Feb  9 13:14 cloudapi.acquia.com.pem
-rw-r--r--  1 nickheiner  staff   7741 Dec 19 16:52 drush.bashrc
-rw-r--r--  1 nickheiner  staff   1937 Dec 19 16:52 drush.complete.sh
-rw-r--r--  1 nickheiner  staff   2811 Dec 19 16:52 drush.prompt.sh
-rw-r--r--  1 nickheiner  staff  13628 Feb  9 13:19 drushrc.php
-rw-------@ 1 nickheiner  staff   1416 Feb  9 13:14 preview1.aliases.drushrc.php

However, Drush is not recognizing the commands:

λ ./drush cache-clear drush
'drush' cache was cleared.                                                [success]

λ ./drush help --filter=acapi
The specified command category acapi does not exist.                      [error]

I am also not seeing the alias:

λ ./drush sa
@none
@self
default

I tried opening up the permissions so they look like the following, but it did not solve the problem:

λ ls -la ~/.drush
total 176
drwxrwxrwx  10 nickheiner  staff    340 Feb 10 10:36 .
drwxr-xr-x+ 57 nickheiner  staff   1938 Feb 10 11:04 ..
-rwxrwxrwx@  1 nickheiner  staff  43320 Feb  9 13:12 acapi.drush.inc
drwxrwxrwx   6 nickheiner  staff    204 Feb  9 13:26 cache
-rwxrwxrwx@  1 nickheiner  staff   6026 Feb  9 13:12 cloudapi.acquia.com.pem
-rwxrwxrwx   1 nickheiner  staff   7741 Dec 19 16:52 drush.bashrc
-rwxrwxrwx   1 nickheiner  staff   1937 Dec 19 16:52 drush.complete.sh
-rwxrwxrwx   1 nickheiner  staff   2811 Dec 19 16:52 drush.prompt.sh
-rwxrwxrwx   1 nickheiner  staff  13628 Feb  9 13:19 drushrc.php
-rwxrwxrwx@  1 nickheiner  staff   1416 Feb  9 13:12 preview1.aliases.drushrc.php

What am I doing wrong?

Can you confirm that you can see your acquia site aliases?

drush sa

I haven't done anything beyond the suggested tar -C $HOME -xf $HOME/Downloads/acquiacloud.tar.gz and drush help --filter=acapi shows all the commands.


Attaching css to blocks Why do we use $block['content'] while attaching css or js files to block ?

$block['content']['#attached']['css'][] = drupal_get_path('module',
                                          'mymodule' . '/mymodule.css');

What does that 'content' mean ?

A block array has a 'subject' and 'content' key, it's just a convention. See hook_block_view() for details:

  Return value

  Either an empty array so the block will not be shown or an array containing the following elements:

  subject: The default localized title of the block. If the block does not have a default title, this should be set to NULL.
  content: The content of the block's body. This may be a renderable array (preferable) or a string containing rendered HTML content. If the content is empty the block will not be shown.


How to detect when $form_state data have expired (and gotten deleted)? Problem: a user opens a multi-page form and fills out several sections – submitting each time – before returning hours later to finish the remaining parts, leaving their browser open (perhaps needing to look for additional documents or consult with a colleague). When they come back, they are still logged in, but the hard-coded 6-hour limit on storage of their $form_state data has elapsed, and the values they submitted in the previous sections of the form will not load on their next navigation-action since they have been deleted.

Background: for multi-page forms, Drupal stores working $form_state information in the cache_form table until the final submission-step is complete, but its "expire" column is set so that deletion occurs 6 hours after creation. Even if this value is changed, sites featuring multi-page forms may still encounter the above situation, wherein an in-progress form is submitted after $form_state information has been discarded.

How can one detect when this circumstance arises (so the user can be informed of this or so that recovery-actions can be silently taken)?

Note: Though you're welcome to post a Javascript answer if you have one, I won't assume Javascript is always available, and therefore do not consider answers which rely on Javascript to be robust.

Although this arrangement is probably more complicated than it needs to be, here's how I was able to achieve it. I'd be happy to accept another answer if someone has a more elegant solution.

/**
 * Implements hook_form().
 */
function my_module_form($form, $form_state) {

    if (isset($form_state['storage']['elements_to_append'])) {
    // If other functions want us to add elements to the form:
        $elements = $form_state['storage']['elements_to_append'];
        foreach( $elements as $key => $element ) {
            $form[$key] = $element;
        }
    }

    $form['submit'] = array(
        '#type' => 'submit',
        '#submit' => array(
            'my_module_submit',
            'my_module_submit_safety',
            // ^ Depending on your requirements, you may wish to switch the
            // run-order of these two functions. Having my_module_submit_safety()
            // put first prevents subsequent actions in the case that $form_state
            // was lost since last navigation, but your users may lose more pages
            // of work before this check becomes effective; it's a tradeoff
            // either way unless you want to run the safety-check twice.
        ),
    );

    return $form;

} // my_module_form() OUT

/**
 * Implements hook_submit().
 */
function my_module_submit($form, &$form_state) {

    $form_state['rebuild'] = true;

    $form_state['storage']['elements_to_append']['navigated'] = array(
        '#type' => 'hidden',
        '#value' => 1,
    );

} // my_module_submit() OUT

/**
 * Implements hook_submit().
 */
function my_module_submit_safety($form, &$form_state) {

    $form_state_cid = '';
    if (isset($form_state['input']['form_build_id'])) {
        $form_state_cid = 'form_state_' . $form_state['input']['form_build_id'];
        // ^ This is effectively the same way the CID is built in @see
        // form_set_cache()
    }

    $statement = db_select('cache_form','cf');
    $statement->fields( 'cf', array('expire') );
    $statement->condition('cid', $form_state_cid);

    $navigated = isset($form_state['input']['navigated']);

    if ( $statement->execute()->fetchAssoc() === FALSE && $navigated ) {
        throw new Exception("The state-information for this form has expired.");
        // ^ I just place an exception here because recovery-actions for this
        // case are going to be system-dependent. If you know what those are for
        // your situation, they'd go here instead of this `throw` statement.
    }

} // my_module_submit_safety() OUT

Above, we use $form_state['input'] rather than $form_state['values'] since the latter will not include the results of the hidden field sent from the client's stale page in the case that $form_state information has been deleted. The strange dance of appending elements from a '#submit' step is done so that we don't run aground of the fact that my_module_form() is actually invoked twice (once immediately before '#submit' functions are called, and once after, each time with different values).

To test whether it works:

Load the form.
Navigate once.
Do: mysql -u <userName> -D <databaseName> [-p<password>] -e\
"DELETE FROM <prefix>_cache_form";.
Navigate again. You should see the message appear after this step.

Note: for security purposes, one might actually want to encrypt the hidden field's value (salting, timestamping, and including it no matter what), then reject the form outright if the value is found to be missing or adulterated in some way.


How to add custom field to the user profile according to its role in Drupal 7? i need to add some custom fields to the user. These fields are not the same for every user, but they vary according to their roles. How can i do that?

I saw that you can add some custom fields in the configuration menu but those cannot be differentiated according to the role.

User role field module allows you to specify role-specific fields.
When creating a new field, you specify what roles this field is enabled for.

Fields are only visible and editable if a user has a specific role.

This role does not determine access controls for visible fields.
You could use the Field Permissions module for setting access controls.

More then 120 sites currently use this module.


How to add wysiwyg (like CKeditor) to Disqus module textarea? As shown in the following image the input textarea of the Disqus is just plain. Is there a way so we can add wysiwyg (like CKeditor) to it? And that input textbox always located at the top of comments, Is there a way so we can shift it to the bottom of the comments (like core comment module of drupal 7)?

Unfortunately, this is impossible. The Disqus comment form is in an iframe originating from disqus.com. It is basically a separate web page embedded within the content of your website.

If your page were to access the Disqus form, it would violate the Same-origin policy. This policy is to keep your information safe. Imagine if another page could read or modify data when you log in to your bank. Bad news.


Login Destination behaving differently on two instances of Drupal I'm seeing some inconsistent behaviour from the Login Destination module on my "UAT" site as compared to my "Dev" site. Both sites (AFAIK) have the same module configuration:

Neither of the global settings is enabled
There is only one Rule, as follows:

Redirect to Page foo-bar
Redirect upon Triggers Login, registration, one-time link
Redirect from listed pages : Only the listed pages - <front>

The problem is with the one-time link sent out on account activation.

The one-time link references a URL of user/reset/[snipped].
At this location there is a "Log in" button.

Clicking this button on my Dev site, users are redirected to user/NNN/edit?pass-reset-token=[snipped], from where they can edit their account details.

BUT clicking this button on my UAT site, users don't redirect to the edit profile page, but are logged in and redirected to /foo-bar, which is useless, because they can never set their passwords.

The only difference I can see between the Dev and UAT sites is that the UAT site is HTTPS while my Dev site is HTTP. Is it possible that could be a cause of this issue? If not, how can I go about debugging this?

Best regards,

MB

UPDATE

Problem resolved - I'm just recording the outcome in case someone Googles this page in future.

It was of course nothing to do with HTTPS.

Someone had previously enabled the Trigger module on my UAT site, and there was a Trigger defined on user login to redirect to foo-bar. This was causing the one-time link to be redirected.

Due to the large number of modules on our UAT site, I didn't find this for a while. Disabling the Trigger module restored the desired behaviour.

See UPDATE above in main question for the solution.

FYI the problem was diagnosed by attempting to step-by-step trace through the Login Destination module, and then discovering that at one point I found myself in the trigger module code. PHPStorm for the win every time!


Programmatically place blocks? I'm using Drupal 7.  Right now, I have a main-menu navigation and Language switcher that exists in my website header.  I placed them there by going to the CMS>Structure>Blocks and hten dragging the blocks into the header region.

How do I programmatically situate these block in the header?

To alter the region where blocks defined by other modules are placed, you can implement hook_block_info_alter(), which receives the following arguments:

$blocks (passed by reference): the array containing the block definitions, keyed by module, and delta
$theme: the theme for which the blocks are being defined
$code_blocks: the blocks as defined from the hook_block_info() implementations, before their values are overridden by the values obtained from the database


save the value of a custom form in the database Why isn't the code saving values in the database?

module_load_include('inc', 'firstform', 'firstform_node_form_alter');

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

$items['submit_driven_ajax'] = array(
    'title' => 'send your email',
    'page callback' => 'drupal_get_form',
    'access callback' => TRUE,
    'weight' => 3,
);
return $items;

}

function firstform_intro() {
$markup = t('The AJAX example module provides many examples of AJAX including forms, links, and AJAX commands.');
return $markup;}

function firstform_form($form, &$form_state) {
$form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
);
$form['email'] = array(
    '#type' => 'textfield',
    '#required' => TRUE
    , '#description' => "Please enter your email name.",
    '#ajax' => array(
        'callback' => 'firstform_text_driven_callback',
        'wrapper' => 'box',
        'name' => 'email1',
    ),
);
$form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
        'callback' => 'firstform_submit_driven_callback',
        'wrapper' => 'box',
        'name' => 'submit1',
    ),
    '#value' => t('Submit'),
);

return $form;}

function firstform_submit_driven_callback($form, $form_state) {
$element = $form['box'];
$element['#markup'] = "your email ({$form_state['values']['email']}): " . date('c');
return $element;}

function firstform_text_driven_callback($form, $form_state) {
$element = $form['box'];
$element['#markup'] = "your email ({$form_state['values']['email']}): " .date('c');
return $element;}

 function firstform_block_info() {
$blocks = array();
$blocks['firstform'] = array(
    'info' => t('Form mail'),
    'weight' => 0,
);
return $blocks;}

function firstform_block_view($delta = '') {
module_load_include('inc', 'node', 'node.pages');
switch ($delta) {
    case 'firstform':
        $block['subject'] = t('');
        $form = drupal_render(node_add('firstform'));
        $block['content'] = $form;

        break;
}
return $block;}

  function firstform_node_insert($node){
  db_insert('firstform_node_form_alter')
->fields(array(
  'nid' => $node->nid,
  'email' => $node->firstform['email'],
  'date' => $node->firstform['date'],
))
->execute();}

function firstform_node_update($node) {

 if (db_select('firstform_node_form_alter', 'a')->fields('a')->condition('nid', $node->nid, '=')->execute()->fetchAssoc()) {
db_update('firstform_node_form_alter')
  ->fields(array(
    'email' => $node->firstform['email'],
    'date' => $node->firstform['date'],
  ))
  ->condition('nid', $node->nid)
  ->execute();
  }  else {
firstform_node_insert($node);}}

    function firstform_node_delete($node) {  db_delete('firstform_node_form_alter')
->condition('nid', $node->nid)
->execute();}

When I add firstform.install, the firstform_node_form_alter table is not created.

function firstform_schema() {
 $schema['firstform_node_form_alter'] = array(
'description' => 'Stores email settings for nodes.',
'fields' => array(
  'nid' => array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0,
    'description' => 'The {node}.nid to store settings.',
  ),'email' => array(
    'type' => 'varchar',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Node Form Example 1 textfield',
  ),
  'date' => array(
    'type' => 'int',
    'length' => 256,
    'not null' => FALSE,
    'default' => '',
    'description' => 'Node Form date textfield',
  ),
),
'primary key' => array('nid'),
'foreign keys' => array(
  'dnv_node' => array(
    'table' => 'node',
    'columns' => array('nid' => 'nid'),
  ),
),
 );
return $schema;
}

hook_schema is called at install and unistall, so make sure your actually installing the module and not just turning it on.

If you've already had your module running on your site, switched it off at /admin/modules and then switched it back on, drupal doesn't recognize this as an uninstall/install event. Rather, you need to fully remove it from the DB by going to admin/modules/uninstall after switching the module off.


How to have a node creation form on a separate node creation form? I'm on d7 and creating a "how to" site where users create a topic and add individual steps to it. I have a topic content type and a step content type and I connect them together by having an entity reference field on the steps so they reference the topic. I'm looking for a way to have an "add step" form on the topic creation page that will add a step and automatically reference the topic that I am creating. The field collections module gives me some of this functionality, but it makes it all in the one node being created. I need it to be separate content type because I want other users to be able to add steps to the topic after its been created, as well as commenting on specific steps and flagging. Any suggestions? Thanks.

Check out References dialog also. The module extends entity reference field by adding links to add, edit and search (which links are available can be configured) for references through a dialog.


How to reuse existing images in field type "Image" I have custom ContentType with one field of type Image.
Currently, when I edit a node I can only upload new images from local to server.
I want to have the option to select images already existing on the server.

I think that the way to go is to use the EntityBrowser and/or FileBrowser modules
but I don't know how to make this work.
I can create the EntityBrowser instance but how do I tell the ContentType field Image to use it?

I'm on Drupal 8.

Your help is appreciated.
--Josef

Projects are built from the start to use the Media module and reference entities instead of files directly. That is how Entity Browser can help.

Here is how it's usually done:
https://www.drupal.org/docs/8/modules/entity-browser/how-to-configure-an-image-widget-to-re-use-existing-files.

More useful resouces:
https://www.drupal.org/docs/8/core/modules/media/faq-transition-from-media-entity-to-media-in-core
Is there any way to reuse the same file or image?

There's a way to convert your files into entities, there is the Migrate File Entities to Media Entities module, and some useful info about it:
Migrate File Entities to Media Entities in Drupal 8,
How do I migrate file entities into media entities?


Will painless upgrading from Drupal 8 alpha 3.x to beta be possible? I'd like to create a website with Drupal 8 Alpha 3. But I'd like to know for sure if it's possible to do a harmless upgrade to Drupal 8 Beta once that it's released.

I heard something about the Drupal 8 API being frozen, but after reading this article (http://buytaert.net/drupal-8-apis-are-freezing-but-not-frozen) i'm not so sure anymore.

Can anyone help out?

PS: The website i'm going to build is fairly simple (few content-types, views, blocks etc)

No.

Upgrading from a previous 8.x version will be supported starting with the first beta.

Upgrading from 8.x-alpha will break, I know of at least one issue that will make major changes to the entity/node storage.


This page was last modified on 1 January 1970 Including the following code:
<?php print 'This page was last modified on ' . date('j F Y', $node->changed);?>

in node.tpl.php displays the correct information on the site. However, I would like to display it in the footer instead at the end of the content so have moved it to page.tpl.php.
The problem with this is that on the homepage the following is being displayed:

This page was last modified on 1 January 1970

Which is clearly incorrect.
In addition, These error messages are displayed on every page:

Notice: Undefined variable: node in include() (line 201 of /home/mysite/public_html/sites/all/themes/mysite/templates/page.tpl.php).
Notice: Trying to get property of non-object in include() (line 201 of /home/mysite/public_html/sites/all/themes/mysite/templates/page.tpl.php).

How do I include the Page last updated text in the footer of every page?

You are trying to access the property of a loaded Node's object in the page template. This variable, $node, will only be available to the page template, typically page.tpl.php, only if the current path is loading a node.

In other words, if you are loading a path like node/NODE_ID, then you are guaranteed the variable will be available. Otherwise it won't be.

The error you are seeing is because of this reason. Try to navigate to a valid node URL and the error will be gone, the variable will be defined, and you can access it normally.

Provide a conditional check in your page template to make sure the variable exists before you access it.

Good Luck!


Ajax Function jquery Fails to send data Drupal 7 I am in the process of converting Drupal 6 module to Drupal 7.
i have a problem of Passing php data to Ajax.
The function should display if a speaker on or off by interchanging icons, when clicked by using (toggle function).
whats i have discovered is that this part $.ajax() doesnt work, while in Drupal 6 it works.
 below is the code.

longa.module file:

  //hook menu
  function longa_menu(){
  $items=array();
  $items['longa/set_speaker_state'] = array(
   'page callback' => 'longa_set_speaker_state',
   'access arguments' => array('longa talk'),
   'type' => MENU_CALLBACK,
  );
  return $items;
}
 //the callback
 function longa_set_speaker_state($speaker_state) {
  global $user;
  $_SESSION['longa_speaker_state'] = $speaker_state;
  user_save($user, array('longa_speaker_state' => $speaker_state));
 }

longa.js file:

(function($){
 $(document).ready(function(){
  if (Drupal.settings.longa_module.has_audio ==1){
  im_flash_player_listener.onInit = function(){
    this.position = 0;
  };
  if ($('#im-console-speaker-icon-on').css('display') == 'none') {
    is_muted = 1;
  }
  else {
    is_muted = 0;
  }
  $('#im-console-speaker-icon-on').click(function() {
    set_speaker_state(1);
    is_muted = 1;
    //alert('You clicked the speaker');
    $('#im-console-speaker-icon-on').toggle();
    $('#im-console-speaker-icon-off').toggle();
    });
  $('#im-console-speaker-icon-off').click(function() {
    set_speaker_state(1);
    is_muted = 0;
    $('#im-console-speaker-icon-on').toggle();
    $('#im-console-speaker-icon-off').toggle();
    });
  }

 });
})(jQuery);

 function set_speaker_state($speaker_state) {
  if (Drupal.settings.longa_module.has_perms ==0) {
   return;
  }
 var sendurl= url_prefix + 'longa/set_speaker_state/' + $speaker_state;
  //alert(sendurl);
   $.ajax({
   type: 'GET',
   url: sendurl ,
   dataType: 'json',
   data: 'js=1'
   /**success: function(xhr) {
    alert('sent successfully');
    },
    error:function(xhr) {
   alert('error occured');
   }*/
 });
}

I will appreciate for any help.

In function set_speaker_state() , the $ symbol doesn't recognized, you must put set_speaker_state() function into:

(function($, window, undefined){
 // here!
})(jQuery, window);


How can I create Folder like Structure with n Key Value Pairs? I'm new to Drupal.

I'm trying to build the following structure

--Root
  --Cars
    --Luxury Car Campaigns (my "Folder")
      -Bentley CampaignInformation (1-n Key Value Pairs of different Types)
      -Lamgorgini CampaignInformation (1-n Key Value Pairs of different Types)
    --Japanese Car Campaigns (my "Folder")
      -Toyota Yaris CampaignInformation (1-n Key Value Pairs of different Types)
      -Corolla Verso CampaignInformation (1-n Key Value Pairs of different Types)

Note: A "Folder" is marked with a double-"--" and a key-value-list is marked with a single "-" (we call it internaly "Project"; but it is basically a named collection of key-value attributes/fields).

Every field can be of any type (Double, Data, Text and so on).

Every folder may contain unlimited subfolders or "Projects". (Must not be enforced by "Constraint")

Now the tricky Part (or not?):
Users can create Folders at any time. Users can create "Projects" in any Folder. Users can add any type of key-value pair to any Project.

Please give me a hint. Can this be done with Drupal? Do i have to dive into writing custom Modules?

I know a lot of Questions. Thanks in advance.

If its just hierarchial text/numbers/whatever content you want under "folders" you could try the built-in Book module. And then re-theme its display to have "parent" pages appear as folders and child-pages be your value fields (or pages). The nice thing you get here is some pre-built templates for "folder" indexes at every depth of the folder-tree.

Also the built-in book module supports HTML export and is pluggable so you can write your own custom book_export_xml() function, see:
book.pages.inc book_export($type, $nid)

Be aware drupal (book) pages nest at most 8 levels deep I believe by default -- I think there are work-arounds for this in the DB to go deeper (perhaps unlimited).

Or, you allow each user to have their own Taxonomy in drupal and try to use like Field Collection to allow users to create many values under a single term in the vocabulary.

Taxonomy sounds like it might meet your needs -- but you would likely have to make custom code something to allow users to create X number of taxonomies only they can see and manipulate.

Just fyi -- there is always a "maximum" in any dataset you have hardware constraints (RAM and harddisk) and can only store so much and still be responsive for the enduser. So be realistic and set yourself a max value, say 999 values per Key ....

Drupal can probably do what you want but it will take a fair amount of research.


How to check if the problem is of clean url when migrating the database from one server to another? After uploading the my local db on server my site was not working and what I was getting was white screen of death. After few hours of struggling I found that as the server was not configured for clean url and the in the database the clean url settings was ON that was causing the problem.

Is there any way we can come to know if the problem is of the clean url in such scenario.

Also I can't use the backup and migrate module as the database size was too large.

It is advised to turn off the CLEAN URLs before migrating the database from one server to server.

Reason behind you were not able to see errors on white screen of death may be error reporting being turned off, if that is the case than you may try adding the following lines in setting.php to turn on error reporting:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

  Also check the entry's of "watchdog" table if you are getting white screen of death upon migration.


Customizing/theming a created view I searched a lot on net, but did not find proper answer for the customizing / theming  a view that is created. I have created a view like one in screenshot . I wanted to change the way the pagination appears and some cosmetic changes for it. So whats the best way to do it.

Use the unformatted style, instead of the table style. Then use CSS in your theme and you can style it any way you want. Should you want to change the html (I hardly ever need it), try rearranging the view or using the suggested templates.


How to hide the comment form label (not title)? I have tried a number of different modules that claim to do this but none have worked, I have also tried changing the comment.tpl file, and I even tried using CSS "Display:none"; however nothing has worked. So how can I hide the "Comment" label on a comment form box? I am not talking about the comment title here, as this can be easily disabled in the content type settings. This is what I am talking about:

I originally thought that this could be done in the manage display settings, by setting the comment label to hidden. So I did this but it didn't change the label of the comment box:

So how can this be done? I simply want to hide the word "Comment" and the "*" after it of course.

You can easily do this with CSS. Looking at dev tools, I see that the label is called edit-comment-body-und-0-value (yours might be different). So what we need to do is, simply edit the CSS file and put in the line label[for*="edit-comment-body-und-"] { display:none; } and clear the cache at /admin/config/development/performance.

That's all there is to it.

K.


Ask users what menu they want while drupal is being installed I am working on installation profile. I wanted to give user choice to choose what menu items he wants like home, about us and another. Is this possible ?

Yes it's possible, using hook_install_tasks().

You can use this hook to create a form that is displayed to your users during the installation process; it can be a standard Drupal form and you can add as many items of content/menu links as you want in the submission function.

Bear in mind the hook and forms your implement will need to go in the .profile file, not the .install file, or they won't work.


Ubercart payment option without gateway? I'm new to this forum, and I'm maintaining a Drupal 6.x webshop using Ubercart 2.4 for a client. The client wants to add a new payment option for business to business customers. These customers wouldn't need to pay at all, but would be invoiced manually from the client.

The client would have to check weather the customer is actually a valid customer for this "payment method", and decide if they can take the order or not, but this would be a separate issue.

How can I add a new payment method that just stores the order with shipping and billing address to my database, no more?

Could I refactor the "Other" option from Payment Pack?

I ended up copying the "Other" option from payment pack. Then I changed all references to "busniess_invoice". Works like a charm!


how to get all the fields that have been modified on entity save (form submit)? I am trying to figure out an efficient way to get the fields names/values that have been updated. It's kind of similar to what the diff module does to calculate changed on a node but not as detailed. I just want to see what fields have been updated when a user saves an entity. For example a user may not change the title but could change the body. I would like to build an api function returns that. something like this pseudo code:

// possibly on presave or form submit.
function my_module_entity_presave() {
    // Return only the fields values that are not similar to the original node:
    $modified = $entity->getModifiedFields();
}

and the method could be something like this psudo code:

public function getModifiedFields() {
  $original = $this->originalFieldsValues();
  $new = $this->newFieldValues();
  // compare original with new
  // finally return only modified fields name values.
  $modified = ['title' => 'new value', 'body' => 'new value' ...];
  return $modified
}

When you are in the presave hook, the updated $node object will have $node->original, which is the node before things were changed.

Nodes also have a $node->toArray(), method that will flatten the object into a multidimensional associative array.

So, this

array_keys(DiffArray::diffAssocRecursive($node->toArray(), $node->original->toArray())

should

Take the $node and $node->original and convert them into arrays.
Run the two arrays through one of the Drupal helper classes that will generate differences in multidimensional associative arrays.
Return the top level keys.  Because of the ways nodes are built, this will be all of the changed property and field names.


Dropdown navigation for calendar view It's not a "new" issue, but I'd like to implement a year + month dropdown selector to navigate a standard calendar view's display, as this particular calendar shows historical entries spanning many years, all of which need to be directly accessible.

I understand it's possible to specify an argument via URL to control the calendar view's current display through its contextual filter. However, I don't know how to supply this argument via a dropdown, either in the block itself or another (similar to an exposed filter), in a way that would function properly in all cases.

Working without a solution, I created my own views style plugin, added an exposed filter, and am now going to look for a way to display the easily filtered-by-month results in a custom calendar implementation through my code.

Hopefully there's a way to make use of the existing calendar module via "inspired" filtering, instead of my custom plugin route?

Any guidance would be appreciated.

I had the same requirement a few time ago.You are right the key is date pager in url to navigate through date/month/year

here is a workaround I did,might be helpfull in your case too.

As in brief I created custom form with field as month and year.Submission of the form navigates passing the selected month and year in url using drupal_goto() and we are calling this form in views header.


What URIs are accessed by drush? What URIs are accessed by drush up? Is it drupal.org? Are there any other URIs?
I have tried using drush up --debug, but I can't seem to find a list of URIs. I have also googled it using the key words drush access URL and drush access URI, among others.

If you are referring to drush dl, then by default Drush downloads from drupal.org, if you don't tell Drush to use another URL.
For example, if you use drush dl views --source="updates.modules.org/history", Drush would probably download the Views module from modules.org, instead of drupal.org. From where the module would be downloaded depends from what updates.modules.org/history/views/7.x (for Drupal 7) or updates.modules.org/history/views/8.x (for Drupal 8) returns.

If you look at what https://updates.drupal.org/release-history/views/7.x retuns, you will notice a line like <download_link>https://ftp.drupal.org/files/projects/views-7.x-3.14.tar.gz</download_link>, which is telling to Drush to download the Views module version 7.x-3.14 from https://ftp.drupal.org/files/projects/views-7.x-3.14.tar.gz.


How to create a single page with a jump select menu? I need to create a page with a single jump select menu. Once the user makes a selection he/she will be redirected to a view page where the selection will be used as contextual filter

Can I do it with the webform module? What other option do I have?

I've found this one: http://drupal.org/project/jump but just a dev version for d7.

Views provides a "jump menu" display, you could just use that.


$form_state['values'] partial empty, while $form_state['input'] is filled I would like extend an existing (altered) form. For this case, I created a new form with the Form API:

function my_new_form($form, &$form_state) {
  ...
}

In the next step, I get the existing form, which one I would like to extend:

function my_new_form($form, &$form_state) {
  $form = drupal_get_form('my_form');
}

Now, I extended the form with fields like this :

function my_new_form($form, &$form_state) {
  $form = drupal_get_form('my_form');

  $form['foo'] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('foo bar'),
  );

  // and so on..

  return $form;
}

In my Template, I display the form:

print drupal_render(drupal_get_form('my_new_form'));

This works correctly, but after submitting the form, the values from the form from which I extend in the $form_state['values'] are empty. But in $form_state['input'] they are existing.

Do you have any idea what I'm doing wrong?

The reason drupal_get_form() doesn't work in your code is that it contains the following code.

  $form_state = array();

  $args = func_get_args();
  // Remove $form_id from the arguments.
  array_shift($args);
  $form_state['build_info']['args'] = $args;

  return drupal_build_form($form_id, $form_state);

What the function passes to the form builder is a newly created $form_state array, not the one being passed to your form builder.

Using drupal_build_form() is not working because the function is retrieving the form from the cache. (See the comments before the code.)

  // If the incoming input contains a form_build_id, we'll check the cache for a
  // copy of the form in question. If it's there, we don't have to rebuild the
  // form to proceed. In addition, if there is stored form_state data from a
  // previous step, we'll retrieve it so it can be passed on to the form
  // processing code.
  $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
  if ($check_cache) {
    $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
  }

You can implement hook_form_alter(), hook_form_FORM_ID_alter(), or hook_form_BASE_FORM_ID_alter() for a form that has been already altered.

About calling drupal_get_form() from a template file, see Be careful with drupal_get_form() in theme layer. As reported in that blog article, you would have problems with the validation error messages which will not appear.


Permanent Deleting of files still doesn't work for me (make_unused_managed_files_temporary = true) make_unused_managed_files_temporary didn't work for me.
I am using Drupal backend for the REST API frontend application.
Thats how the File input looks (because I am not sure if that setting is for that File elements, but guess so).

I read some informations about permanent files deleting, because I would like to delete files permanent from the file system and also database.
I was set the make_unused_managed_files_temporary to true and debuging, this is really true in the code.
I also found the configuration in Backend / File system - Delete temporary files after (6 hours), so this is on.
I am checking also the database file_managed before and after (and after 6 hours) file deletion for the flags like status that indicates isTemporary() method. But after uploading file, saving... then editing, and removing file, the file is still in the database as a status 1.
I am also checking DB table file_usage where there is still the item with count=1 too, that should be not true (because of deletion).
And files maybe should move to /tmp folder, but that doesnt.
I am working on Drupal 8.5.6 and 8.7.2 on production, but the behaviour is the same.
I am doing something wrong? Is there some cron to be configured? Or another futher settings?
Edit 1: I think it is not a Media, but simply file widget - /core/module/file
Edit 2: The main problem is that, when I delete file, it stay in the database as a permanent flag (status=1), and also it has a count of usage 1 (file_usage=1). When I manually update database to set status=0 and count=0, the cron works OK. Why the file usage and count stay on?

I just made a solution that works for me even the Drupal or config doesn't works properly. In my plugin I hooked up the hook_cron() for logging these unused files to proceed them next.

SQL SELECT; query to fetch all file_managed fid's. You can select only status=1, as permanent files, but I got all,
PHP loop all id's and making a Drupal\file\FileInterface entity reference $file = File::load($item->fid) to check all the file references $references = file_get_file_references($file). When the $references is empty() this file is unused. Save all that fid id's into array $fids,
SQL UPDATE; build update query to null these rows: UPDATE file_managed SET status=0 WHERE fid IN($fids) and UPDATE file_usage SET count=0 WHERE fid IN ($fids).

Finaly after next cron run the default function file_cron() {... will properly delete these files.


Node reference to show only author of node I have create two content types as Game and Video. For the Video content type, I have created a node reference field that will be referring to the Game type.

Suppose I have 2 users (e.g. user1, and user2) on my site. User1 has created the following nodes:

Game1 (content type: Game)
Game2
Game3

User 2 has created the following nodes:

Game4
Game5

Suppose User1 is going to create one Video node. On the node reference selected list, I just want to see Game1, Game2, and Game3, but it is displaying all Games.

How can I solve it?

Use views integration option in Node Reference Field Settings... You can connect the node reference results with the view results.. When you edit node reference field settings you can see the setting to select view with which Reference Field pulls results...

You need to build a view first that will display all games created by logged in user... Then select this view in node reference field settings....


Twig Template print field - if not node number I can print an image field in my node template like this:
{{ content.field_big_image }}

But can I say "print this field but not if the node number is node/45" ?

Yes. Sometimes themes will drop documentation when they override a template, but you can always check the original template file for the available variables and other info relevant for working with the template. If you check the node.html.twig template provided by the node module in core, you'll see the following documentation at the top of the file.
/**
 * @file
 * Default theme implementation to display a node.
 *
 * Available variables:
 * - node: The node entity with limited access to object properties and methods.
 *   Only method names starting with "get", "has", or "is" and a few common
 *   methods such as "id", "label", and "bundle" are available. For example:
 *   - node.getCreatedTime() will return the node creation timestamp.
 *   - node.hasField('field_example') returns TRUE if the node bundle includes
 *     field_example. (This does not indicate the presence of a value in this
 *     field.)
 *   - node.isPublished() will return whether the node is published or not.
 *
 * ... continued ...
 *
 */

Note the relevant info here:

The node entity [is available] with limited access to object properties and methods. Only method names starting with "get", "has", or "is" and a few common methods such as "id", "label", and "bundle" are available.

This means you can access the node id with node.id.
So, you can print your field on nodes other than your specific node by wrapping your field in a conditional like:
{% if node.id != 45 %}
  {{ content.field_big_image }}
{% endif %}

or
{% if not node.id == 45 %}
  {{ content.field_big_image }}
{% endif %}

Either choice should produce the same result.