Problems w/ themes and multi-site installation so i'm currently migrating a single install drupal site into a multi-site drupal install, and for some reason it doesn't seem to be picking up my templates... which is a bit odd considerign that when in the drupal admin interface on the actual client facing CMS I can see that i'm in the correct "theme" which is a custom theme called "press".

however, drupal isn't using my page.tpl.php file. So what I did was hit the main drupal install and opened up bootstrap.inc and found that it is finding the correct directory for the conf and everything... not sure what else to do.

something that's interesting is that if I ping my site on localhost it looks as though it's pulling in 1 block (which should be displayed on the homepage), no wrapper, no menus, etc (which is why i think it's not using the correct templates, also the html is formatted differently than when it uses the correct template).

this is what i did to migrate

moved moved settings.php/modules/themes/files into the drupal/sites/mysite
reconfig'd my httpd.conf to point to the right site (it is).
reset my file path from sites/default/files to drupal/sites/mysite/files

using - drupal 7

curious if anyone has any advice or knows how I can investigate this further.

I have also experienced this issue as well. It seems that drupal doesn't want to recognise themes and modules on a multisite subdomain basis (i.e. sites/yoursite.com/themes is ignored!!!). I don't know if this is intended behaviour but the only solution I have found thus far is to put all modules and themes into the sites/all folder and then to check they are enabled in the admin interface.
Drupal will correctly respond to the subdomain request (and rewrite paths where appropriate) so long as you have the sites/yoursite.com folder.


Download DB in Admin panel How to download my drupal site DB in my Drupal 7? I want to know is there any options are there in download db in admin panel.

You can install Backup and Migrate

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.


How can I add a field in Entityform / hook_form_alter I'm trying to add a field to the form in hook_form_alter. What's the proper way of adding fields in this hook in case of entityform?

I tried to add it this way:

$form['leadname'] = array(
    '#type' => 'hidden',
    '#value' => 'abc'
);

but I have the impression that this is not the way it should be done...

That is the way it should be done.

For example using

MODULE_form_ENTITYFORM_MACHINE_NAME_entityform_edit_form_alter(&$form, &$form_state) {}


Add content type to a taxonomy - Drupal 7 Hello everyone I have content type named contact where I have many fields like name, email, phone, country... and a taxonomy named organization with fields name, acronym and contact. What I try to do is when I create a new term of this taxonomy I have the possibility to add contact. Many thanks in advance

if I understand it right, you're trying to reference a "contact"-node...

You can use the module "entity reference" (https://www.drupal.org/project/entityreference) for that.


Selecting taxonomy term in article and showing all articles titles associated with this term I have a content type article and when editing an article there should be a field where you can select a taxonomy term of a specific vocabulary.

When viewing the article it should show a list of titles of all articles associated with the selected taxonomy term. I know how to make a select field and also a view to show the titles. But how do I send the selected term to the view and how do I display the view in the article?

1) Create a View block, when you create it use Show: Content.

2) Under Advanced Contextual Filters add Has taxonomy term ID

3) Select provide default value Type: Taxonomy term ID from URL (this will automatically grabs the term from your node) If you want, you can limit the terms by vocab.

Even if your tax term reference field is limited to 1, maybe you should set it up as if it was unlimited, in case your client later wants to allow more than 1 value.

Change the multiple-value handling option to the 2nd one, share any term.

Scroll down to MORE and check mark allow multiple values.

Click Apply, to save the settings.

Now you want to exclude the current Article (node) from the list. No point in showing the Article the visitor is already viewing/reading.

4) Add another contextual filter of ID

5) Provide default value Type: Content ID from url (automatically grabs the ID from your node).

6) Scroll all the way down, and click on MORE, and check mark Exclude.

So your Advanced section should look like this:

To place the block in your article, there are several ways.

Go to admin/structure/block and click on Place Block, search for your View Block and click on Place Block.

In the configuration, under Visibility settings, select Content Types and check mark your content type.

Site Note: There are other ways to insert/place your view:

Through a template file.
Using Panels and or Display Suite (Note: I am not 100% sure on this as I have not played much with these modules in D8, in D7 I know you can).


Store value in file entity field using a form Apologies in advance, this question probably has an obvious answer.

I am using a custom form with a 'managed_file' widget named 'image' to upload image files to the public file directory:

$image = file_load($form_state['values']['image']);
$image->status = FILE_STATUS_PERMANENT;
file_save($image);

I am using File Entity Module to attach to image file entities a caption text field (the machine readable name is 'field_caption'). On the custom file upload form there is a 'textfield' widget named 'caption' whose submitted value I want to store as the value of the image file entity's 'field_caption'.

Certainly, Drupal needs to first realize that the uploaded file is in fact an image file, as other file entites might not have attached a caption text field. That's why in the code above I first save the file before the code is followed by

if (isset($form_state['values']['caption'])) {
$caption = $form_state['values']['caption'];
$image->field_caption[0]['value'] = $caption;
}
file_save($image);

However, after submission the caption text field is always left empty.

Did I choose the wrong commands to store a value in field_caption?

I posted this on drupal.org (https://drupal.org/node/1820706) and got an answer that works. I have to replace
$image->field_caption[0]['value'] = $caption; with $image->field_caption[LANGUAGE_NONE][0]['value'] = $caption;


Services add several nodes at once I am using Drupal 7 with Services module (version 3.x). I want to add several nodes at once. When i try one it is okay.

{"type":"article","title":"Test article 1","body":{"und":[{"value":"test body!"}]},"language" :"und"}

But when I try something like this i can't

{"type":"article","title":"Test article 1","body":{"und":[{"value":"test body!"}]},"language" :"und"},{"type":"article","title":"Test article 2","body":{"und":[{"value":"test body!"}

Is there a way to make this happend?

Services default functionality for node creation is one by one. If you want to create multiple node at once then you should write your custom service using hook_services_resources(). You can find some example about how to write custom service Click Here


How to use a block as a field in Drupal 7 I'm working with this module which is providing me a block for uploading the file as mentioned in the doc https://drupal.org/project/jquery_file_upload

Is there a way, where I can use this block as a field while adding the content, for instance at node/add/[my_custom_content]

No, fields are totally independent concept than blocks. Of course there is a way to have a region inside field, and you could then drop that block to region, but there would be no connection between block's uploading capabilities and created node.

If you have a fancy file uploading requirements, it would be better to write them down and ask what module can do it for your file or image field.


Default file on a cck field I want to have a .pdf application form attached by default as a cck field on a custom content type called vacancies, so that every new vacancy created has the pdf file attached without the user having to upload it manually. Is there any way to do this? Thanks in advance!

Probably you need to show a default PDF file attachment with custom type nodes. And need to upload some specific to replace the default one via CCK file field.

CCK file field cannot be associated with some default file easily.

The best approach can be...

Place the default document in file system
Edit content-type.tpl.php and check CCK field (e.g. $node->field_name) for file upload
Print the link of uploaded file if exists Else print the link to default file


query condition comparing two fields i am having this query :

   $db = \Drupal::database();

  $exist_query= $db->select('user__roles', 'ur');
  $exist_query->fields('ur', ['entity_id']);
  $exist_query->condition('ur.entity_id','u.uid', '=');
  $exist_query->condition('ur.roles_target_id', $included_user_roles, 'IN');

  $not_exist_query= $db->select('user__roles', 'ur');
  $not_exist_query->fields('ur', ['entity_id']);
  $not_exist_query->condition('ur.entity_id','u.uid', '=');
  $not_exist_query->condition('ur.roles_target_id', $excluded_user_roles, 'IN');

  $query = $db->select('users_field_data', 'u');
  $query->fields('u', ['uid']);
  $query->condition('u.uid', 1, '>');
  if (!empty($param['login_value'])) {
    $query->condition('u.login', $logindate, '<');
    $query->condition('u.login', 0, '!=');
  }
  $query->exists($exist_query);
  $query->notExists($not_exist_query);
  dpq($query);

the problem i am having is here

  $exist_query->condition('ur.entity_id','u.uid', '=');

it generates :

WHERE (ur.entity_id = 'u.uid')

when it should

WHERE (ur.entity_id = u.uid)

How can i solve this ?

The working request i am trying to achieve

SELECT u.uid AS uid
FROM
users_field_data u
WHERE (u.uid > '1') AND (u.login < '1586705658') AND (u.login != '0') AND (EXISTS (SELECT ur.entity_id AS entity_id
FROM
user__roles ur
WHERE (ur.entity_id = u.uid) AND (ur.roles_target_id IN ('admin_site')))) AND (NOT EXISTS (SELECT ur.entity_id AS entity_id
FROM
user__roles ur
WHERE (ur.entity_id = u.uid) AND (ur.roles_target_id IN ('membre_du_site'))))

You can add such a clause manually:

$not_exist_query->where('ur.entity_id = u.uid');


Loading a script before another one I have created a dependency like the following, but it seems that acquia_lift is still not running before gtmscripts. How can I achieve this?

 GTMscripts:
 version: 1
 header : true
 js:
   assets/js/GTMscripts.js: {}
 dependencies:
    - acquia_lift/acquia_lift

As long as Replace custom weights with dependencies in library declarations is not fixed, you have to use weights to control the priorities of JavaScript files.

 js:
   assets/js/GTMscripts.js: { weight: 10 }


How do you build up a LIKE condition in a db_select() query? How do you build up a LIKE condition in a db_select() query?

I know how to do this with a db_query() API call, but is there a special syntax / method for doing this with db_select()?

After digging through Drupal Documentation found a solution in db_like API documentation page and SelectQuery:condition handler doc page..

For example

$result = db_select('field_data_field_name', 'f')->fields('f', array(
    'entity_id',
    'field_name_value'
))
->condition('entity_type', 'user')
->condition('bundle', 'user')
->condition('deleted', 0)
->condition('field_name_value', '%' . db_like($last_item) . '%', 'LIKE')
->distinct()
->range(0, 10)
->execute();

Condition to use for like query is

->condition('field_name_value', '%' . db_like($last_item) . '%', 'LIKE')


View No Results Behavior not working I have a view with horses for sale. I have another view with a filter of field_sold = yes.

Currently there are no horses for sale. I want to add a No Results Behavior "Currently we have no horses for sale."

I tried in Structure > View > Sold > Custom text (field) > NO RESULTS BEHAVIOR but I don't see the message?

If I understood correctly, your view is not returning any results because of it's filter (field_sold = yes), if so, then no field are going to be shown in the view, so if you rewrite a field 'No results behavior' it won't show, simply because your view is not returning any row.

What you are looking for is the 'No results behavior' that's in the advanced tabs in the view. That's what is going to show when your view returns no results at all.

Just add Custom text field and put whatever you want there.


Hook into Panels content form submit I'm writing a routine to track inline image usage in panel panes every time the panels content form is submitted. The hook_panels_pane_update hook works, but only after the second time the form is saved. Is there a hook that will trigger the first time the form is saved?

Correct, according to the panels.api.php file, hook_panels_pane_update() is for changed panes.  There's one just above it for new panes called hook_panels_pane_insert().

If you want the same function to happen every time regardless of whether the pane is new or not, combine them like this:

function mymodule_panels_pane_insert($pane){
  mymodule_act_on_panels($pane);
}

function mymodule_panels_pane_update($pane){
  mymodule_act_on_panels($pane);
}

function mymodule_act_on_panels($pane){
  //Do the things here
}


Invoking AJAX on a form messes up my form_alter function I am altering the "Add node" form for one of my types so that I can set the title and disable the text box. The (shortened) code looks like this:

function mytheme_form_node_form_alter(&$form)
{
    $form['title']['#default_value'] = 'Some value';
    $form['title']['#disabled'] = true;
}

On the node form, I have a field with "Unlimited values" where a user can click "Add another item" to add another row to the items grid on the form.

The problem: When I click this button and the AJAX request happens, it adds the row to the table as usual. But when I save the form, Drupal thinks the Title is empty, and throws a validation error back. The title is still set and greyed out after the AJAX request happens (like it should be), but it seems to "unset" itself somehow behind the scenes when the AJAX request happens, because when the form gets saved, the title gets cleared and the validation error occurs.

I hope I made that clear... so does anyone know why the AJAX related to unlimited fields might interfere with theme_form_X_form_alter?

function mytheme_form_node_form_alter(&$form){
    $form['title']['#default_value'] = 'Some value';
    $form['title']['#value'] = $form['title']['#default_value'];
    $form['title']['#disabled'] = true;
}

This should solve the problem.
In HTML, disabled form elements' value will not be sent back to the server so server gets nothing back, which result in a form error if the value is required. Storing value in #value overrides any browser input which is a must (for security purposes) when you disable a form element and expect its value back.


Check if theme is enabled programmatically How can I check to see if a theme is enabled on a drupal installation? I'm looking for something like module_exists() but for themes. I couldn't find anything on the documentation.

Use list_themes

Parameters

$refresh:
Whether to reload the list of themes from the database. Defaults to FALSE.

Return value

An associative array of the currently available themes. The keys are the
themes' machine names and the values are objects having the following
properties:

filename: The filepath and name of the .info file.
name: The machine name of the theme.
status: 1 for enabled, 0 for disabled themes.
info: The contents of the .info file.
stylesheets: A two dimensional array, using the first key for the
media attribute (e.g. 'all'), the second for the name of the file
(e.g. style.css). The value is a complete filepath (e.g.
themes/bartik/style.css). Not set if no stylesheets are defined in the
.info file.
scripts: An associative array of JavaScripts, using the filename as key
and the complete filepath as value. Not set if no scripts are defined in
the .info file.
prefix: The base theme engine prefix.
engine: The machine name of the theme engine.
base_theme: If this is a sub-theme, the machine name of the base theme
defined in the .info file. Otherwise, the element is not set.
base_themes: If this is a sub-theme, an associative array of the
base-theme ancestors of this theme, starting with this theme's base
theme, then the base theme's own base theme, etc. Each entry has an
array key equal to the theme's machine name, and a value equal to the
human-readable theme name; if a theme with matching machine name does
not exist in the system, the value will instead be NULL (and since the
system would not know whether that theme itself has a base theme, that
will end the array of base themes). This is not set if the theme is not
a sub-theme.
sub_themes: An associative array of themes on the system that are
either direct sub-themes (that is, they declare this theme to be
their base theme), direct sub-themes of sub-themes, etc. The keys are
the themes' machine names, and the values are the themes' human-readable
names. This element is not set if there are no themes on the system that
declare this theme as their base theme.

Use path_to_theme to get active theme..

  It can point to the active theme or the module handling a themed
  implementation. For example, when invoked within the scope of a
  theming call it will depend on where the theming function is handled.
  If implemented from a module, it will point to the module. If
  implemented from the active theme, it will point to the active theme.
  When called outside the scope of a theming call, it will always point
  to the active theme.


How to check if field value has changed on a node? I have a node type that holds a field of users, when this node is saved I am emailing all the users in this field.

This node might be updated from time to time and I don't want to re-email these users, but I want to check for any new users added to this field.

What would be a good way to check this? Could I simply check $form_state against $form for that field when it is submitted, or is there a better way to achieve this?

You could use the Rules module for this. Similar to what is shown in my answer to "How to check with Rules if a new element has been added to a list in a node?".

By using the rule included in that answer, you can discover scenarios such as these:

Value user3@example.com was removed from the multi value field.
Value user2@example.com was added to the multi value field.

Here is a simplified version of the rule that should be pretty close to your case (to only show the inserted values):

{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

If you just replace the machine name "field-email-addresses" by the machine name of your field that contains the eMail id of the user (prior to import), you should be able to experiment with this rule in your own site to see it at work (for nodes of content type "Article", adapt this type to fit your needs).

All that's left to do is to transform the message that is displayed by sending an appropriate eMail (which is like a Rules-getting-started exercise).


How to set up Drupal Commerce to sell users the ability to create/post custom nodes (ex. classified ads)? I am currently working on a classifieds D7 site, and I would like to sell users the ability to create/post a classified ad. With D6 + Ubercart this can be done using the UC Node Checkout module (http://drupal.org/project/uc_node_checkout), and following the instructions provided on the Drupal Easy website (http://drupaleasy.com/blogs/ultimike/2009/03/event-registration-ubercart).

Is there any way implement the same functionality with D7 + Drupal Commerce?

Thank you so much

You can do this with Rules pretty easily.

Create a role with the desired permission.
Create a product to sell.
Create a rule for the checkout complete event.

Condition is that the product you created is in the order. (I would probably create my own condition as I'm better with code than with the Rules interface, but you should be able to set this up in the Rules interface.)
Action is to give user that owns the order the selected role.
There is no step 4, you're done.


How to prevent a PDO exception when using Rules to Set a data value after saving new content? I need to write a rule that edits some elements of the node, as soon as it is created. Unfortunately Drupal doesn’t like that and crashes whenever you try to save the node within a rule that was triggered by "After saving new content".

Event: After saving new content

Conditions: ...

Actions: Set a data value, with
Parameter: Data: [node:field-workflow...], Value: 1

The above results in:

  PDOException: SQLSTATE[23000]: Integrity constraint violation:

So far I managed to walk-around that with hook_forms, changing the workflow in my portal (so I never have to edit the node just after it is created)

Things get really interesting when I try to use "Execute custom PHP code" action which will change the node value I want:

node_save will result in drupal crushing
db_update - seems to work most of the time...
db_insert - sometimes works (works for superuser only)

Unfortunately all my hacks don't work for all my problems. How else I can address this situation?

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rules Action (related to Set a data value) in a Rules Component, so that your Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Save new content" for sure completed, and your new content will have been created as expected.

PS: I'm assuming this question is about D7.


Commerce Order email with an "Unknown" payment method (Drupal 7) I placed the order programatically.  Everything seems to work fine, even the "payment method" on the order page is show up correctly.  However the order email I received, the payment method is unknown.  It suppose to show "Add to account"

I don't know why, I thought that could be the email rules is executed before the token is available with the payment method name to use. On Drupal commerce email configuration, it's set to use the token [commerce-order:payment-method-short-title]

$payment_method = commerce_payment_method_instance_load('bank_transfer|commerce_payment_bank_transfer');

 $charge = $order->commerce_order_total['und'][0];

$transaction = commerce_payment_transaction_new('bank_transfer', $order->order_id);
$transaction->instance_id = $payment_method['instance_id'];
$transaction->amount = $charge['amount'];
$transaction->currency_code = $charge['currency_code'];
$transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
$transaction->message = 'Name: @name';
$transaction->message_variables = array('@name' => 'Add to Account');

commerce_payment_transaction_save($transaction);
commerce_payment_commerce_payment_transaction_insert($transaction);
commerce_checkout_complete($order);
commerce_order_save($order);

I now found the solution, I need to add the payment method to the order object, so the token system can pick it up and use in the order email.

Before save the order, we need to add the payment method.

$order->data['payment_method'] = 'bank_transfer|commerce_payment_bank_transfer';
commerce_order_save($order);

It can be placed before the transaction section.


Biblio import "choose file" disabled I exported a .enw file from Biblio in drupal 6 and am attempting to import it into my drupal 7 site. However on the "data import" tab, "choose file" is grayed out and disabled. What needs to be done to import the drupal 6 biblio nodes?

I had to enable the Advanced Import module from Biblio in order to get the file to import.

https://www.drupal.org/project/biblio_advanced_import


Cannot get AJAX callback values to save I am using Drupal 7, and I have a content type called Case Record that has the following fields:

Title  (title, Node module element)
Case Number (field_cr_case_number, Text)
Case Title (field_cr_case_title, Text)

When the user creates a new node of this type and enters in a Case Number, an AJAX call is supposed to fetch the Case Title and populate it on the Case Title textbox. Here is my module code:

<?php
/**
 * @file
 * Module for Case Records.
 *
 * @category Examples
 *
 * @package Example Modules
 */

/**
 * Implements hook_form_alter().
 */
function case_records_database_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'case_record_node_form':

      $form['field_cr_case_number'] = array(
        '#type' => 'textfield',
        '#title' => 'Case Number',
        '#prefix' => '
',
        '#suffix' => '
',
        '#ajax' => array(
          'callback' => 'case_records_database_ajax_callback',
          'event' => 'change',
          'method' => 'replace',
          'wrapper' => 'div-case-name-element-wrapper',
        ),
      );

      $cs_short_title = "";
      if (isset($form_state['values']['field_cr_case_number'])) {

        // Code omitted. Use db_select to query the database and
        // get the real case title, but for now we'll just call it
        // "Some Case Title".
        $cs_short_title = "Some Case Title";
      }

      $form['field_cr_case_title'] = array(
        '#type' => 'textfield',
        '#title' => t('Case Title'),
        '#value' => $cs_short_title,
        '#prefix' => '
',
        '#suffix' => '
',
      );

      break;
  }
}

/**
 * AJAX callback.
 */
function case_records_database_ajax_callback($form, &$form_state) {
  return $form['field_cr_case_title'];
}

The AJAX call does indeed populate the Case Title text field with the dummy "Some Case Title" text. However, when I save the new node neither the Case Number field nor the Case Title field are saved with any values. They are both blank. What is wrong with my code?

That code is overriding the fields structure. That fields have a specific structure and that code is changing it completely, so in submit the values are not recognized.

I recommend you use devel module and use dpm function to inspect the structure of that fields:

  dpm($form['field_cr_case_number']);
  dpm($form['field_cr_case_title']);

To make your form changes you must only add the #ajax property to your field:

$form['field_cr_case_number'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
  'callback' => 'case_records_database_ajax_callback',
  'event' => 'change',
  'method' => 'replace',
  'wrapper' => 'div-case-name-element-wrapper',
);

And to add the wrapper and #value to your second field do something like this:

$form['field_cr_case_title'][LANGUAGE_NONE][0]['value']['#prefix'] = '
';
$form['field_cr_case_title'][LANGUAGE_NONE][0]['value']['#suffix'] = '
';
$form['field_cr_case_title'][LANGUAGE_NONE][0]['value']['#value'] = $cs_short_title;

In this question is also explained how to make the ajax callback.


How do I make rows of views blocks on a basic page reacting collectively to an exposed filter? I have to make a page, containing 3 rows with 3 blocks with content teasers.
Preferably the page layout should be made through a basic page content type item, through the Layout Builder, so it is easy to add other stuff.

At the top of the page should come a view's exposed filter for the teasers. So, the teasers that are shown must be filtered for some selected content types plus for some taxonomy terms. I've been able to make that filter on a normal view page. Also I accomplished to get the filter in a separate block. But, because of the fact that both a basic page and a view page need a url, I couldn't accomplish this idea.

Is it possible to make a basic page with separate rows of view blocks via the Layout Builder, reacting collectively to an exposed views filter?

Views Attachments Displays have the option to inherit the exposed and contextual filters from the Views displays they're attached to. So you can try to create one Views Page Display with some of your results, then create as many Attachment Displays (not Block Displays) as you need and attach them to the Page Display.

I haven't tried the Layout Builder with different Views displays like that, but I think it may work to rearrange them a bit.

I think you could also have Views Blocks (that are on the same Views) share the same Exposed filter settings (don't override them), and use the Exposed filter in a block option where you place the exposed filter part of Views as a block in a theme region instead of always appearing it automatically above the Views results.

You may also want to check out the Views Global Filter module that affects all Views exposed filters once a user chooses one option.


How can I send an email to Administrator when Users change their name? We are using LoginToboggan. How can I send an email to Administrator when Users change their name?

I looked at Rules, but the only Rule action which seems close is

"After updating an existing user account"

Is there a (simple) way to program a custom action which sees that the Name field has been changed?

TIA

{ "rules_notify_sales_on_username_change" : {
    "LABEL" : "Notify Sales/Administrator On Username Change",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "email" ],
    "REQUIRES" : [ "rules", "mimemail" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "account" ],
          "roles" : { "value" : { "11" : "11", "7" : "7", "2" : "2" } },
          "operation" : "OR"
        }
      }
    ],
    "DO" : [
      { "mimemail_to_users_of_role" : {
          "key" : "userupdate-sales",
          "roles" : { "value" : { "6" : "6", "3" : "3", "20" : "20" } },
          "active" : 1,
          "from_name" : "User Update",
          "subject" : "User updated their account information",
          "body" : "An existing user has updated their account. \r\n[account:name] \r\n[account:mail] ",
          "plaintext" : "An existing user has updated their account. ",
          "language_user" : 0,
          "language" : [ "account:language" ]
        }
      }
    ]
  }
}

yes in Rules you can achieve it

Step 1 : In Events Event add "After updating an existing user account"

Step 2  : Conditions Elements "Execute custom PHP code "

return [account-unchanged:name] != [account:name]

or add data comparison and add

Data to compare Selected data: account-unchanged:name

Operator : equals

Data value : account:name

Step 3: In action send mail

refer this for same kind of problem with role. but you have is name

How do I create a Rule "When role is removed, send email to the user"?


Insert Block Inbetween Paragraphs of the Content Body Field I have a block I am trying to insert into the body field, catch is I want it to appear after the first two paragraphs. I tried using something similar to this in my node.tpl.php:

<?php
$array = explode ("
", $content['body']);
$array[2] = $myBlock . $array[2];
$content['body'] = implode("
", $array);
?>

//Important: This code snippet needs to be inserted before

<?php
print $content['body'];
?>

This code does insert my block in the body field, but also overwrites all the content in the field.

I'm using Drupal 7.10, any help is appreciated.

I think you want to be doing this on $body[0]['value']; And then in your output put echo render($content['body']); see the answer to this post on rendering fields.


How to create user programatically if not exist? I am using this code to create user.

  if(user_validate_name('czxc') != ""){
        $user = User::create([
                'name' =>'czxc',
                'mail' => 'user@gmail.comgczxcdfa',
                'pass' => 'password',
                'status' => 1
             ]);
            $user->save();
            drupal_set_message($user->id());

    }else{
        drupal_set_message('Already exist user');
    }
   This code works only one time for me.

The user_validate_name function from Drupal only verifies the syntax of the given name.

It does not validate whether the username exists or not.

You could replace the function call, like so:

$uids = \Drupal::entityQuery('user')
  ->condition('name', 'czxc')
  ->execute();
if (count($uids) > 0) {
  $user = User::create([
    'name' =>'czxc',
    'mail' => 'user@gmail.comgczxcdfa',
    'pass' => 'password',
    'status' => 1
  ]);
  $user->save();
  drupal_set_message($user->id());

} else {
  drupal_set_message('Already exist user');
}


Does drupal have another module that have the same feature as media watermark? I am looking a watermark module that have a selection watermark just like in the image.

Unfortunately the media watermark module is support drupal 7.

Does drupal have another module that have the same feature as media watermark?

PS: I am using drupal 6.

Try ImageCache Actions Module. I think this will help you...


group same fields in views using custom template drupal 6 user here. I am sure that this is basic views question but I can not figure answer to it. I have a simple view with 2 fields - node title (field_title) and node author (field_author). I want to print all data separate so that node titles would be printed inside ONE single separate div and node authors would be printed in another div. This can not be achieved using rewrite option as far as I know. Can anybody help me with this? Thank you.

Go to your view: admin/build/views
Edit your view: admin/build/views/edit/view_name
Look at your fields node title (field_title) and node author (field_author) and click on Node:Title for instance
Once editing the view output of the Node:Title field, check "Rewrite the output of this field"
You should see replacement patterns: [title] == Node: Title

In the Rewrite this field section called "Text:" enter

[title]

Repeat 3,4 and 5 for the Node:Author field.

[author]

You can put anything else in the rewrite field here.

(note: D7 has more options that using the rewrite method)


Programmatically set value of Boolean radio button field in form I am using a custom field in the profile2 module for when a user registers. The field is a Boolean field using the radio button widget.

I want to programmatically set the value for the field using hook_form_alter().

I have managed to successfully set the #default_value using:

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  $form['profile_company']['field_employees']['und'][0]['value']['#default_value'] = 0;
}

But this code does not actually check the No button, so it looks like nothing has been selected and when the form is submitted it throws an error saying that that field is required and nothing has been selected.

How can I get the code to actually check one of the buttons as well as setting the default value, based on values that I want to pre-fill the form with?

The code above would work fine with a text field, It just doesn't work with a Boolean field using radio buttons.

I have spent a while on this and can't seem to find an answer. I thought maybe I need to use the field #after_build property or possibly JavaScript?

I'm attaching a screen grab of my field settings.

First, check you are setting the #default_value property at a correct level in the $form array. It seems quite weird to get multiple values in $form['profile_company']['field_employees']['und'], so I'm not sure about assigning defaults nested under [0]['value'] (but I could be wrong).

A good rule is to ensure you set #default_value at the same level as the #options array. For example, if you would have these options under the lang code like :

print_r($form['profile_company']['field_employees']['und']);

# Output :
Array
(
    ['#options'] => Array (
        # ... => ...
    ),
    # ... => ...
);

... you would set the #default_value at the same level :

$form['profile_company']['field_employees']['und']['#default_value'] = $default_value;

Secondly, ensure the #default_value is mapped to an existing key in the form #options array :

# Let's say your options are defined as :
$form['profile_company']['field_employees']['und']['#options'] = array(
  0 => t('N/A'),
  1 => t('No'),
  2 => t('Yes')
);

# This would set 'N/A' as default :
$form['profile_company']['field_employees']['und']['#default_value'] = 0;


How to avoid Drupal redirecting my multilingual Views pages? I've got a Views page in a multilingual website where I need a different url for each language, ie:

es: mysite/apartamentos.
en: mysite/appartments.
fr: mysite/appartements.
ru: mysite/arendu.

I created an url alias for each language (which is mysite/appartments although the default language of my site is spanish) so the spanish alias for appartments is apartamentos and so on. I created these aliases using configuration >> Search and Metadata >> URL aliases >> add alias.

I have to pass query parameters to the view to filter the results so my url is something like mysite/en/appartments/p/location_field/2 and I've got a form where I manually put the action like :

echo "/".$language."/".$translated_page

where translated page may be apartamentos, appartments, appartements or arendu, making the action url :

/es/apartamentos , /fr/appartements , /en/appartments and /ru/arendu

My problem is that when this form is sent Drupal sends me to

  mysite/es/appartments/p/location_field/2

instead of

  mysite/es/apartamentos/p/location_field/2

and the same occurs for all the languages. The rest of the thing seem fine and even the breadcrumb (which is generated using the url) looks correct (
Inicio >> Apartamentos Costa Dorada, in Spanish).

When I use the language switch it redirects me to the correct translated page but without the query parameters (from mysite/es/appartments/p/location_field/2 it sends me to mysite/es/apartamentos).

I don't know what can be causing this issue, maybe the query parameters interfering with the alias interpretation?

Note: I have a lot of translation modules enabled. For the i18n modules there are: block, field, menu, node, path, string, taxonomy, translation (translation sets), variable and views.

i18n_path submodule

I assume you're also using the i18n module. So make sure you also enabled the i18n_path submodule (= Path translation). More details about it, from the community documentation (bold markup added here):

  ... allows you to map together existing pages that are translations of each other. This will allow users to use the language switcher to navigate between the associated pages.

  The module is meant to be used as a last resort to translate paths that can't otherwise be mapped together as translations. For example, paths to translated nodes can already be linked with the Content translation module and paths to translated taxonomy terms can be linked with the Taxonomy translation module. Path translations should be used to link generic paths, such as those provided by Views or Panels.

  To set up translations of a particular path, you need to create a path translation set by going to Configuration > Regional and language > Translation sets > Paths and clicking Add path translation.

i18n page views

You may also want to check if you can get it to work using the i18n page views module. Some details from its project page:

  ... provides a new display of views, where you can select different paths for each language enabled on your site, so a view has a localized route for each language.

Note 1: "if you cannot find any option in the view to translate the path" (as in your comment below), then you may want to have a look at what's mentioned in Comment #1 of issue 2389535, which states:

  ... May be you have chosen a page display rather than a i18n page display when you created your view. Please be sure that you selected the correct views display. I attach some screenshots for helping:

Screenprint 1:

Screenprint 2:

Note 2: To answer the question about "Will I have to create the whole view page again to make it as an i18n_page?" (as in one of your (now deleted) comments below this answer), I would give it a try using either of the approaches described in the answers to the question at
How to duplicate a Views display (which is not the master) as a different display type? ... If that doesn't work / apply, then recreation of the whole view page seems like the only option left.


Where is the code that filter web and email addresses into links? Under full html, drupal states: "Web page addresses and e-mail addresses turn into links automatically."

I'm curious to know where this behaviour is coded and how I would hook into it if I need to modify it slightly

This answer is for Drupal 7

You can see where the default filters are defined in /modules/filter/filter.module line 1147. There we see that _filter_url() (line 1358) is the function used to transform text into links.

You shouldn't modify this code directly. Instead you can implement hook_filter_info_alter() to change the process callback for url filter to your own function (you can copy _filter_url() and make the few changes you need)

function YOURMODULE_filter_info_alter(&$info) {
  $info['filter_url']['process callback'] = 'YOURMODULE_filter_url';
}

Keep in mind that these changes will be reflected everywhere the URL Filter is used. If you need something not so "all inclusive", you can implement a new filter that you can apply to a seperate input format.


How should I share sessions transparently across domains? I work on a Drupal site which has multiple domains (not sub-domains) using Domain Access to set different themes, display different content, etc. on each of them.  These multiple domains are used for canonical HTTP URLs. Each domain also has a corresponding sub-domain of a common domain which is used with Secure Pages for HTTPS (there's a wildcard certificate). This all works fine.

My next step is to manage to unify the session between HTTP (on the canonical domain) and HTTPS (on the sub-domain of the shared domain). Many other sites accomplish this by redirecting back to their main domain to assign or discover the session cookie and redirect back to a "set cookie" script on the the current domain to set it there too.

A semi-serious search of D.O and with Google didn't turn up anything useful so I'll ask here: has anyone done this before in Drupal before? Is there a module or (more likely) a patch I can use and am I on my own here?

Thanks for any suggestions.

There are some related answers and solutions at "Enterprise" authentication, single sign-on and user provisioning for multiple sites.

While you have a more specific question, the goal is similar to what many SSO solutions in Drupal try to achieve.


Download folder through drupal How can I allow users to download the whole folder from Drupal? Is there any easy way? As far as understand, right before they click download link I need to execute php script on a server that will zip the folder and return link to user. This is just too complicated for me. Is there any module that can work? The best I've found is: http://drupal.org/project/download_file but it seems it only works with single file. I have a shared hosting.

Depending on what level of access your users have the ElFinder module is capable compressing and making a directory available for download.

What directory are you allowing your users to download?  Be extra careful that they cannot download critical files like /sites/default/settings.php!


How to change taxonomy url in node view page? How to change  taxonomy url in node view page in Drupal 8?

In node view page I am getting taxonomy term url pattern as term/{%term_id}. I want to change taxonomy term url to custom url in Drupal 8.

Any help?

the code below replaces term/{%term_id} by node/39?technologie={%term_id} with THEME_preprocess_field :

use Drupal\Core\Url;

function MYTHEME_preprocess_field__FIELD_TAXO_MACHINE_NAME(&$variables, $hook){

    foreach ($variables['items'] as $index => $item) {

      $route_name = 'entity.node.canonical';
      $params     = 39;
      $tid = $item['content']['#options']['entity']->id();

      $options = [
        'query' => ['technologie' => $tid],
      ];

     $url = Url::fromRoute($route_name, array('node' => $params), $options);
     $variables['items'][$index]['content']['#url'] = $url;
  }
}


Why is it sometimes $node->field_name[0], and sometimes $node->field_name['und'][0]? Sorry for the code in the title, I couldn't think of a clearer way to ask it.

I have several nodes of the location content type, and a view outputting teasers of those nodes. I want to do some custom stuff in node--location.tpl.php to affect the teasers everywhere they're displayed. When I do a simple dpm($node) to get at the variables, some field values are not always in the same place.

For instance, I have field_phone that just has identically formatted phone numbers. For the first node in this view, that field is structured as $node->field_phone['und'][0]['safe_value']. But for the second node, it's simply $node->field_phone[0]['safe_value'].

I know that und has to do with translations, and perhaps means "undefined". I'm not doing anything with translations or localization or languages on the site, so it's not like this node is any different from other nodes that way.

What causes this, and is there a function or something that can help me test for and get at the value easily, or do I have to roll my own?

EDIT: Chris Rockwell below points out field_get_items(). This seemed to solve my problem on the site I was working on the other day. But now, on a different site, it's failing for exactly the reason I bring up here.

I have a view that outputs three nodes. For some reason, when I dpm($node) in the node--node-type.tpl.php file, I get six variable dumps. The first one has $node->field_link_image['und'][0], while all five others — INCLUDING the duplicate of this same node — just has $node->field_link_image[0]. And now, field_get_items() is silently failing and returning false on those last five nodes.

So I go back to my original question: What causes this difference between some node variables and others, and what can I do about it?

The lack of the 'und', or LANGUAGE_NONE level data seems to indicate that the field has lost the ability to be translated. I've never encountered such a field.

field_get_items() as already pointed out is the canonical way to safely retrieve field data. Any fields that don't work with field_get_items should be considered broken.

I would hazard a guess that you either

Have a broken contrib module that re-arranges field data and doesn't know better than to sometimes remove the language level.
Your field settings have just broken somewhere along the way. Potentially because of a reason similar to above.

Does the problem keep happening on newly created fields?

Can you reproduce on a clean install?


How do I upload a PDF for users to download? I am very new to Drupal. I simply want to provide a link in an article for users to download a pdf document. How do I upload the document on the admin side and then link to it in an article?

It's easy, in admin/structure/types/manage/article/fields make file field like so:

All other stuff is logical:

Don't forget to put PDF as an allowed extensions:


Show an "updated" timestamp on nodes Is there a way to show a "Last Updated" timestamp for nodes? Maybe even in views as well?

EDIT: Via a module or core configuration

IN views, just include a NODE/node last updated date field in your row.  For nodes, take the advice of MPD and those commenting in Showing the date of the latest edit, instead of node's posting date about creating the very simple preprocess() and/or view() hooks.


In views, what is the difference between Normal menu entry, Menu tab and Default menu tab When adding a menu item in views I see three selections that are ambiguius

Normal menu entry

Menu tab

Default menu tab

What is the difference and when would I use each?

They correspond to the type parameter of items returned from hook_menu()

Normal menu entry = MENU_NORMAL_ITEM

  Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.

  Normal menu items show up in the menu tree and can be moved/hidden by the administrator. Use this for most menu items. It is the default value if no menu item type is specified.

Menu tab = MENU_LOCAL_TASK

  Menu type -- A task specific to the parent item, usually rendered as a tab.
  Local tasks are menu items that describe actions to be performed on their parent item. An example is the path "node/52/edit", which performs the "edit" task on "node/52".
  Default menu tab = MENU_DEFAULT_LOCAL_TASK

  Menu type -- The "default" local task, which is initially active.

  Every set of local tasks should provide one "default" task, that links to the same path as its parent when clicked.

The best example I can think of are node pages. When you visit a node page, the 'View' tab is provided by a menu item of type MENU_DEFAULT_LOCAL_TASK (see $items['node/%node/view'] in node_menu()).

It doesn't have a path as such (it inherits from the parent menu item), it's only purpose it to allow the node page to have a tab amongst the groups of 'real' tabs, which are defined with MENU_LOCAL_TASK.


How to attach js in services? Here is my code:

services file

  services:
  my_module.event_subscriber:
    class: Drupal\my_module\EventSubscriber\My_moduleSubscriber
    arguments:
      - '@authentication'
      - '@current_user'
    tags:
      - {name: event_subscriber}

My_moduleSubscriber.php

 <?php

  public function xyz) {
  // I want to attach js here
  $attachement['#attachement'][js] = .....
//    drupal_add_js(libraries_get_path('audio-player').'/audio-player.js');

  }

  static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('xyz');
    return $events;
  }

Since there is no argument passed like $attachement, $page, in which variable should i attach js file in Drupal?

A response event is possibly too late, I think at that point, you already have a built response object, and the page is just a string that will be replaced.

You're better of using a hook for this, namely hook_page_attachments(), which exists just for the purpose of adding additional libraries to the page.


How to manage contrib modules composer dependencies on drupal 8 Let's say I have a module exposing a composer.json file, composer manager let me merge it with others modules composer.json.

In Drupal 8 composer.json are used from the core, so is it possible to avoid dependencies duplication with contrib modules ? Is composer-manager still used for that ?

At the moment this is not possible, and it does not look like this will make it into Drupal 8, as Drupal is in code freeze.

Instead, try to manage your dependencies using your module's *.info.yml file (this is for depending on other modules) or using http://drupal.org/project/libraries, which is for third party libraries.

To elaborate on why using Composer for Drupal 8 contributed modules is not a good idea right now:

You cannot expect site builders to know composer and do a "composer install" after having downloaded Drupal to their computer, as Drupal is not just for people who are familiar with the command line.
Because of that, you would have to do the composer install yourself and commit all code to your repository. While this is legally possible for any third party code that complies with the GPLv2, this makes maintenance harder, and if someone downloads two modules that both use the same library through Composer, they'll end up with duplicate code. This in turn makes class loading and debugging a whole lot less fun.


How can I gracefully interrupt an AJAX callback? I have a form element that triggers an AJAX callback call when it looses focus.  This callback can take a few seconds, which generally is not an issue.

If a user submits the form before the AJAX callback completes, the following error is displayed:

Here is the exact error message displayed to the end user:

  An AJAX HTTP request terminated abnormally.Debugging information
  follows.Path: /system/ajaxStatusText: ResponseText: ReadyState: 4

How can I gracefully terminate an AJAX callback from completing when passing control to a submit handler?

This is the relevant code from the module.

function a_custom_form($form, &$form_state) {
  $form['email'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'textfield',
    '#title' => t('Customer Email Address'),
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_user_email_ajax',
      'wrapper' => 'cust-email',
      'effect' => 'fade',
    ),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit Request'),
  );

  return $form;
}

function _user_email_ajax($form, &$form_state) {
  $commands = array();
  // Doing time intensive stuff here...
  drupal_set_message(t('Some Message'), 'error');
  $commands[] = ajax_command_replace('#email-warning-message', '
'. theme('status_messages') . '
');

  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );

}

I have tried the solution given for Prevent "AJAX HTTP request terminated" error on early form submit, but this seems to prevent the submit button from functioning, rather than interrupting the AJAX callback.

That's not directly possible. There is no API in the browser to manually cancel a sent request. All you can do is to register a callback to know when the HTTP response is received, or at least when the browser changes the state on the xmlHttpRequest object. Drupal's AJAX code already handles that for you. The error message you're seeing is shown because another request was sent which did interrupt the background request, but that still looked as if it was completed (readyState == 4). Drupal considers completely empty responses to be an error and the message is shown.

The most common and user friendly approach I've seen is indeed to disable the submit button(s) while a request is in progress. That in combination with a "spinner" animation or progressbar is a good indication that the user should keep waiting and that they will benefit from it. When the request completes (failed or successful), the buttons are unlocked again.

An input field can become unfocused at any time and for different reasons (maybe the user just wants to copy/paste something into it really quick). Triggering a long running background request whenever that happens could quickly become annoying. As you've already noticed, it interferes with the normal form submit flow as well. Maybe you can work around that and trigger the requests by some other means which more clearly indicate to the user that they need to wait for it to complete? Perhaps giving them the choice to initiate the request when they're sure to be done with manual input into the field and are more inclined to wait for automated processing of their input. Or perhaps trigger the request after a short timer which gets stopped when the field is refocused or the form is submitted.

If not, you could try overriding Drupal's AJAX response interpreting code so it won't show that message if the submit button interrupts the background request, first setting some flag to indicate AJAX errors are to be ignored. Whether this works also depends on how important it is that the AJAX operation on your field completed. If it performs some kind of correction on the [email address?] the user entered, they get it wrong, but the correcting routine didn't get a chance to update the field with valid input, this probably means your serverside validation fails and the user needs to submit it again - which could have been avoided if they had waited for the request to complete.


Send mail to author of content I use Drupal 9.1.4., core Contact module, Contact email module and Contact storage module.
How to use the author as a referenced entity to send email to author of content (in this case autor of article) when submiting simple Contact module form?
Thanks,
Tom.

Users already have a personal contact form if you enable the contact form for users.
This way, you can place the link to the user's personal contact form, and then the email will automatically be sent to the author.


Dont want to redirect after registration, possible? I have a lightbox pop up when a link is clicked to sign up for the site but, after signing up i don't want them to redirect to their user profile page, I need them to stay on the same exact page. Is this possible?

I tried login destination but that feature only works for the login not registration.


Set node view count manually This might be not the smartest way to do, but is it possible to set the node view count per node manually?

I'm manually exporting my nodes to another Drupal without using modules; basically, I'm copy-pasting everything since there are things that are changed. The only thing that bothers me is that the number of times a node has been  viewed will be lost.

Is there a way to manually change the number of times a node has been viewed?

The best way to change this would be by editing each record in your database using a tool such as PHPmyAdmin. Once you have migrated to the new website, and enabled the Statistics module you will see the column added in your database table.

Hope it all goes well.

Chandeep


Customize access denied page I have many basic pages where I need the user to be logged-in in order to view them. How do I customize the site access denied page?

A custom access denied page can be defined under /admin/config/system/site-information. For example, one common 404 error page is provided by the Search404 module.

All you have to do is define your own page, perhaps with a teaser from the requested page and informing the user that access to the full content requires that they be logged in.

This will probably require tha you put some php code into the page body, or you might use the Search404 module as the basis for developing your own module to handle this.

Edit: The more I think about this the more interesting the question becomes. I think a case might be made for a 'View Teaser' permission in addition to 'View published content'. In other words, the page could be available for all users, but the teaser would display instead of the full content, and a message could be displayed indicating that the user had to be logged in to view the full content, much like is done for comments now. Perhaps an idea for a contributed model (could not find one on D.O.).


What is the best way to theme the first row in the view differently? I have a view with the first row of it being designed differently from the rest. What is the best way to theme the first row. Should I attach one view (First Row view) with a second view ? If so, how? Or should I theme using the template files and if so How can I know the row I am currently in?

The attached image may better explain what I am talking about:

In this specific situation, the issue can be easily solved by simply using CSS to target .views-row-1 differently than the other rows, as Jimajamma mentioned.

However, if you had a situation where the content in that first row was much more different than in the other rows, there is a solution natively in Views to create this sort of layout.

Create two displays in your View using the same filter criteria.  Display A would be a block that shows only one node (the top, larger item in your mockup) and has a larger image format and different order for the fields to be displayed.  Display B would be the display that you use as the page that your users see.  You would attach Display A to the header of Display B and set Display B to be offset by 1 result, so that it does not duplicate the first node.

Here is a screenshot of the Views 3 UI, showing where to find these settings.  Earlier versions of Views support the same type of set-up, but the naming and placement of the settings in the UI is different: https://skitch.com/sheenad/gqdmm/archive-content-shop.


How to get MEDIAN of value in a view field I have 5 integer fields and I want to show the MEDIAN result for those fields in my content view.
How to get the result?

You can use Computed Field  module to achieve this.
About Computed Field

Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!


User permissions on a costum content type I've created a custom content type with fields (it's like a form), I've already added permission to logged users to use my form(content type) but I want to hide some checkboxes on this form only when user is not admin. so how to hide (remove) a part of fields of a content type ?

You can use Field Permissions for this

Features

Enable field permissions on any entity, not just nodes.
Role-based field permissions allowing different viewing patterned based on what access the user has.
Author-level permissions allow viewing and editing of fields based on who the entity owner is.
Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
Field permissions overview


How to get a referencedEntity field value in current node language I am trying to get some node's content inside a block.

I managed to get the fields i wanted, but they are always returned in my site default language instead of the current translations (ex. /node/1 and /fr/node/1 returns the same english content instead of the translation)

It works fine for simple fields, but can't get it to work for referencedEntities :

I am inside a Block build() function :

$node = \Drupal::routeMatch()->getParameter('node');

// Simple text field : Correct value depending on language
$correctValue = $node->field_test_text->getValue();

// Paragraphs/referencedEntities
$paras = $node->get('field_paragraphes')->referencedEntities();
foreach ($paras as $para) {
   // Not translated, always in default language ?
   $badValue = $para->get('field_test_in_para')->getValue();
}

Thanks a lot.

The code for your problem (You need to use getTranslation to get a translation and hasTranslation to check is is it actually has a translation or not):

$lang_code = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
$node = \Drupal::routeMatch()->getParameter('node');

// Paragraphs/referencedEntities
$paras = $node->get('field_paragraphes')->referencedEntities();
foreach ($paras as $para) {
  // Remember to check if translation exists
  if ($para->hasTranslation($lang_code)) {
    $para = $para->getTranslation($lang_code);
  }
   $goodValue = $para->get('field_test_in_para')->getValue();
}

Eventhough this code will work and fix your problem, you might consider if you are doing things right. Most of the time, when doing things the proper way, you wont need to handle translations. A lot of modules/systems does this automatically when rendering stuff or using modules like views. Most of the time, when you need to handle translations yourself, there would be a simpler way to do this.


Adding a second search for a specific content type I am currently trying to build out a Video-oriented component on a longform article based site, and one of the requirements call for a Video segment/block that can be placed on any page, and it has a search bar that loads any videos with similar titles.

I know that Drupal includes search, and it can be granulated to a specific content type. But I was wondering if there was any way I could implement a separate search function that inherits the existing search logic, and search for content of this specific content type. Is it as simple as altering the logic inside the search form with hook_form_alter, or are there more intricacies involved?

Maybe if I was in your case I will think about views and if the website is that heavy I will create apachesolr  view so I keep it simple flexible.


Send a context from a panel page to a view integrated in it? I'm struggling trying to figure out how to do the following :

I have 3 different views displaying content filtered by different features (content-type, custom boolean field, etc.).
I want to create 3 panel-pages in which I'll integrate those 3 views. Each of those panel-page will only be displaying the content authored by one different member beetween three specific (named AGS, MM, admin).
Thus I wanted to set up a contextual filter in my view which would be the content author ID. Author wasn't available so I chose User : Authmap ID (?). Then, in my panel-page, at Variants > Panel > Contexts I've tried to send a User context by selecting "AGS". I also checked "Send Arguments" in the view settings at Variants > Panel > Content.

... But it's not working !   :(
I'd also love to send other context to my views (boolean, etc). But let's first try to make this thing working out...

Anyone's enlightenment will be greatly appreciated !
Thks.

[CONFIG : Drupal 7.4 - and most recent Views and Panels]

First thing to do is fix your view. In order to have author ID as a filter you need to add the "Content: Author" relationship. After adding that you will see a lot more options for User in the fields and filters. You can now chose "User: UID" for your contextual filter.

Next thing to do is to edit your panel. Add a user context to your panel and chose "Select a user" for the context type. Type in the username of the user and check "Reset identifier to username."

Now go to your panels content and edit the view settings. You should see the "User: UID" context at the top. Choose the "User ID" from the drop down.

You should now only see content from the user you chose in the context when viewing that panel page.


Create view with path relative to taxonomy term I have multiple content types and would like to create a couple of views to show various content types as sub directory to the term page.

The challenge is that I need to the path to be taxonomy/term/%/content-type1
taxonomy/term/%/content-type2

Tired using tokens in the views path. It didn't work.

Any other suggestions?

The way to influence filtering Views through URL arguments is to use Contextual filters. For each URL sensitive Contextual filter you get one argument in your URL (separated by /).

In your case you need to add a new Contextual Filter of type Content: Content type and configure it:
    When the filter value is NOT in the URL
    Provide default value
    Raw value from URL
    Path component: 4
    When the filter value IS in the URL or a default is provided
    Specify validation criteria
    Content type
    Single ID
    Case in path: Lowercase
    More
    Transform spaces to dashes in URL

Change the Path of your Page from taxonomy/term/% to taxonomy/term/%/%.

Now when you visit taxonomy/term/1/article it will list all articles tagged with the term 1 (I'm assuming you have cloned the default Taxonomy term Views).

Show term names instead of TID in URL

It is possible to pass term names to Views from URL, instead of using term ID numbers. So the URL might look something like: taxonomy/term/tag1/article

To achieve that we have to introduce the term name into Views. In this example we cloned the default  Taxonomy term Views, and they only have term ID available.

To introduce more information about the taxonomy term we add a new Relationship. In this case we add Taxonomy term referenced from field_myvocabulary (use your Entity reference field referencing the term from the relavant vocabulary).

There are no consequences of this step visible from the outside, but from the inside we have more choices to choose from when adding new Contextual Filters. One of those new choices is Name from Taxonomy term Category. Add that as a new Contextual Filter and configure it:
    Relationship: field_myvocabulary: Taxonomy term
    Provide default value
    Raw value from URL
    Path component: 2
    When the filter value IS in the URL or a default is provided
    Specify validation criteria
    Taxonomy term name
    Vocabulary: My Vocabulary
    Transform dashes in URL to spaces in term name filter values
    More
    Transform spaces to dashes in URL

Rearrange the Contextual filters to have that Name filter first, then the Content type second and you can ignore or remove the original "Has taxonomy term ID" in third place.

Now you can enter tag1/article into the Preview and you'll see the results, all with using human-friendly URL bits. or visit /hub/tag1/article on your site.

Relationships can introduce duplicate results. If this happens make sure your filters have turned on "Reduce duplicates" option, although you'll probably have to edit your Views Query settings and set them Distinct.

Be careful about the Case settings and converting spaces to dashes and vice versa. Your term name might be "Best term", and depending on your Contextual filters settings you might need to enter "best term" or "Best-term" etc.

The default Taxonomy term Views renders Taxonomy term in Views Header area. I haven't been able to make it work with the Taxonomy name though. It does work if you keep the ID as the third filter and use path tag1/article/1.

But you can solve it (if you need this feature of rendered Taxonomy term in Views Header) with the help of an additional module: Views taxonomy term name into ID and the patch mentioned there.

You can also use this module to get term name in URL, instead of using a Relationship like explained above ;)


Change some charachter in All field before saving node I want done a action (change some charachter) on every field in saving node.
I know for specified field can use hook_node_presave ,but I want do this on all field in all content type (proximity 300 field  and 40 content types) with out specify one by one .
Have drupal api for hook_filed_presave or something like it?

This is work for specified field

function custom_changes_node_presave($node){

    if ($node->type ==='designer_background_images'){

        $filename =$node->original->field_db_image['und']['0']['filename'];
        $uri       =$node->original->field_db_image['und']['0']['uri'];

        $filename    = str_replace (" ", "_", $filename);
        $uri        = str_replace (" ", "_", $uri);

        $node->original->field_db_image['und']['0']['filename']= $filename;
        $node->original->field_db_image['und']['0']['uri']       = $uri;

        //field_attach_presave('node', $node);

            // And the actual field change for the given node (e.g. entity).

        //field_attach_update('node', $node);

        // echo "<pre>";
            // print_r($node);
        // exit;
        // print $node->original->field_db_image['und']['0']['filename'];
        // print $node->original->field_db_image['und']['0']['uri'];
    }
}

You're probably looking for hook_entity_presave():

  Act on an entity before it is about to be created or updated.

It's equivalent to hook_node_presave(), but as the name suggests is run for all entity types.

From there you can use the Field Info API functions to get a list of fields that should be attached to that entity, then loop through them and do the character replacement.


Use Composer to manage sub-theme Bootstrap LESS dependencies when using LESS starterkit In Drupal 8 let's say I want to use a Bootstrap subtheme and the LESS starterkit described here:
http://drupal-bootstrap.org/api/bootstrap/starterkits!less!README.md/group/subtheme_less/8

The Instruction there is to:

  Download and extract the latest 3.x.x version of Bootstrap Framework Source Files into your new sub-theme. After it has been extracted, the folder should read ./subtheme/bootstrap.

Unfortunately this puts the Bootstrap source outside the ambit of my composer.json where I am managing my site dependecies and upgrade etc... more on why I want to do this here:
https://bojanz.wordpress.com/2015/09/18/d8-composer-definitive-intro/

So how can I include the bootstrap source required by my subtheme in the composer.json?

composer require twbs/bootstrap ^3.3.6 --prefer-dist -vvv

Drupal Bootstrap requires 3.x.x the caret will stop us tripping into v4.

We don't want to include any git files so we do --prefer-dist.

This downloads the latest bootstrap source to vendor/twbs.

I can expose this dir to my subtheme by editing:

/themes/custom/MYSUBTHEME/less/bootstrap.less

Now when I run composer update I will get the latest bootstrap less in my subtheme.


Contextual Filters On Block of News Items Well I inherited a site, I have to make updates too. I have a list of news items, each news item has field I added called section, which lets people know what the section the news article blogs to. The url structure is http://example.com/tv or http://example.com/sports

On those pages, I have a list of news items (right now it's a global list) in a block. I need to adjust that list from a global list to reduce down to a list based on the section you are currently in. So the news list item should only show articles which belong to TV or Sports.

I have been working with the block, adding filters. I have attached an image of what I currently have. The field I have used in the view (sections) is called field_channel_section. In the auto preview I can put in TV and it will show me a list of the articles on that section, but on the actual page it shows nothing at all.

What am I doing wrong?

Whenever you need to pass a parameter into a View, one should immediately think "Contextual Filter" - in this case, one should exist for field_channel_section. Note that blocks don't pass their parameters along the URL by default (as with pages), so you will need to set a default value for the filter criterion based on the URL yourself. Thankfully, this can be done by supplying the default value using PHP in the Contextual Filter settings. The particulars depend on what type of field field_channel_section is. If you could clarify, I'd be happy to do the same.


Dymanimcally add links in main menu (e.g. last 4 nodes) I have main navigation menu with root menu items. A request is that one of those have links to latest 4 nodes of a certain content type. So for example if I have a structure similar to this:

-Parent item:

child item 4
child item 3
child item 2
child item 1

(All child items are all of the same content type, for example Article)

When a user adds a new node of the content type Article, the structure should be the following:

-Parent item:

child item 5
child item 4
child item 3
child item 2

All I can think of is to use Views to make a list of linked titles in a block and then to attach the block to the menu (i'm using TB Mega Menu which allows this).
The solely problem with this approach is that I then don't have trail of active menu items in menu.

Any ideas?

Thanks.

Make the URLs static; have the content of those URLs change

You were on the right track with views. But don't use it to create a block with the links, use it to create a page that displays the full rendered entity of the last node of your content type. You can give it a URL like /latest-article.

You could get fancy and use contextual arguments to display the 2nd, 3rd, ... offsets (e.g. /latest-article/%) or you could just add four more displays to the view, each with the offset bumped up by one.


Search with Views not Saving Selected Filters when user tries to go BACK I've created a search page using Views with exposed filters and the basic search module. The search only returns results for a specific node content type 'resource'. A typical use case would be the following:

User goes to search page, types some text into the exposed search terms block, and also selects some options from the exposed filters that are drop-down menus. They click 'search' and their results are returned on the same page. Pretty standard stuff and I have that all working fine.

A user then clicks a link to a resource node of interest to them and goes to that node's profile page. All fine and dandy.

The problem is when they want to go BACK. I went ahead and added a back button with the following code to my node--resource.tpl.php, which works as you'd expect (it bypasses the browser back button and takes user to main search page again):

<input type="button" value="Go Back" onclick="window.history.back()" />

What happens is it displays the search page again, but no longer with the search term they entered OR the exposed filters they selected. I'd like to change that so when they click the 'back' button the search page still shows their search results from before so they don't have to re-select all their options again.

This seems like pretty basic stuff, but I can't figure out how to do it in Drupal. I imagine it involves session cookies somehow...but how to combine this with Views I do not know.

Thanks for your help!

Ok, I solved my own question. To get Views search results to 'stick' you just have to select an option for each filter you want to save and the role that this works for.

In Views > Filters > check the box next to 'remember the last selection' and select which roles this applies to.

Easy. Now when a user clicks the 'back' button I've added to the tpl file it takes them back to their selections.


How do I create a view that displays the author information of the current node being viewed? I need to show a view in the sidebar that shows information about the current node's author (Username, picture, email). How do I go about doing this?

Create a view with selecting a type as user.
Add "User:Content authored" relationship.
IN Contextual filters add nid and select the option of "provide
default value" and select content Id from URL.

.

That's it :)


Easy way to create author account on node creation? Is there an easy way to add a field that will automatically create an account for the author with the specified email address if that address doesn't exist? I have to enter information for new and old users on occasion and it would help if I could just type the e-mail address each time, instead of creating an account manually first.

You can do this easily using Rules Module. Just trigger a rule that whenever you create a node of the particular type, the Rule checks the entered email-id in the field and creates a new account using that email-id if it doesn't already exist.


Using taxonomy term value as title for the view I created a taxonomy, called Galleries for images on the web site:

Our Rooms
Our Food and wines
Our Services

Then I created a gallery for each of the terms, using views. I wanted to override the title of gallery to the term value, as it is shown in this subform for Contextual filters:

But the id of term is used in the url:

http://hotelcentralpark.ro/gallery/1

http://hotelcentralpark.ro/gallery/2

etc

So, instead of words: "Our Rooms", "Our Food and wines" I get "1" and "2", if I check the box "Override title".

How can I show the value of the term instead of it's id? But keep id in the url.

Try to use the hook_views_pre_render on your view to override the page title

function custom_views_pre_render($view) {
  if ($view->name == 'your_view_name') {
    // get the $tid from the view's args
    $term = taxonomy_get_term( $view->args[0] );
    if( $term ){
      drupal_set_title( $term->name );
    }
  }
}


Unable to access private file? I had this issue before, and last time the problem was that node was unpublished. The private file became accessible when the node was published.

This time, however, I'm not using a node. I'm just using Drupals file manage system to store my own files for my own custom module. SO I generated a url for an image file like so:

$imageFile = file_load($userInput['fid']);
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$url = $style->buildUrl($imageFile->getFileUri());

If I print out the URL, I get:

http://localhost/system/files/styles/thumbnail/private/cfiles/test.png?itok=Le14o4Zs

But when I access that, i get "access denied".

What am I missing?

In Drupal 8, private file permissions by default are given according to the entity to which they are attached. If the user has permission to view the entity, they will have permission to view the file.

If you are not attaching the file to an entity, then you will need to implement hook_file_download(), where you will determine whether or not the user has permission to access the file, and return a value accordingly. Currently, because you have no implemented this, access is denied by default.

Note that this hook can be implemented even when the file is attached to an entity to provide additional access checks and/or additional headers.


drupal 7 webform custom views query I have a custom hook_views which queries db for a webform submission. the query looks like this

$query = db_select('webform_submitted_data','n');
    $query->leftJoin('webform_component', 'wc', 'wc.cid = n.cid');
    $query->fields('n', array('sid','data','cid'));
    $query->fields('wc', array('form_key','cid'))
    ->condition('n.nid',25)

Which translates to mysql:

select n.sid,n.cid,n.data,wc.form_key,wc.cid from webform_submitted_data n left join webform_component wc on wc.cid = n.cid where n.nid = 25

Now i have made a new field called status whose value can be 1 or 0, i want to show only those form submission whose status values are 1,
 I tried the following query in phpmyadmin but it gives out only 1 row output where the form_key value = status and data =1, where as the earlier query gave all the form_key, and data values for form id 25.

select n.sid,n.cid,n.data,wc.form_key,wc.cid from webform_submitted_data n left join webform_component wc on wc.cid = n.cid where n.nid = 25 and wc.form_key="status" and n.data =1

Is their any way by which i can add a views filter like condition here to show only data where status = 1

Webform's schema makes it fairly painful, but this should fetch all of the submitted data for any submission where the field with key status has a value of 1:

$nid = 25;
$form_key = 'status';
$data = '1';

$query = db_select('webform_submitted_data','n');
$query->leftJoin('webform_component', 'wc', 'wc.cid = n.cid AND wc.nid=n.nid');
$query->innerJoin('webform_component', 'wc_filter', "wc_filter.nid=n.nid AND wc_filter.form_key=:form_key", array(':form_key' => $form_key));
$query->innerJoin('webform_submitted_data', 'n_filter', 'wc_filter.cid = n_filter.cid AND n.sid=n_filter.sid AND n_filter.data=:data', array(':data' => $data));

$query->fields('n', array('sid','data','cid'));
$query->fields('wc', array('form_key','cid'))
  ->condition('n.nid', $nid);

There may be performance implications doing this if you have more than a few records...

You could simplify a bit by looking up ahead of time the cid of the data component, or just hardcoding it.


How to link a field to node title in view I created a content type. I have three fields: title, body, city.

I added two contents.

I can see nodes at:

http://www.example.com/?q=content/we-buy-houses-nj

http://www.example.com/?q=content/we-buy-houses-va

I created a view as following:
I added title field first (excluded from display).
I selected city field. For rewrite results, change the path to "content/[title]"

Result:

I can see the city field is hyperlinked. When I click each link, I get URL as following and page can not be found:

http://www.example.com/?q=content/We%20Buy%20Houses

http://www.example.com/?q=content/We%20Buy%20Houses

How do I remove the %20 so page can be found in my case?

You get %20 because the browser replaces/fixes/auto-corrects the empty space between your title with %20 as empty spaces are not allowed in URLs.

EX: If you try to go to drupal.org/Hello World, browser url changes/corrects it to drupal.org/Hello%20World.

Here is another possible option:

Add Path as a field, and checkmark exclude from display.

Make sure Content: Path is above Content: Cities, if not please re-arrange it.

Then in cities, for link path put [path]


Need to redirect the non-existence URL's to 404 page instead of parent url This is in connection to drupal.org issue #432384.

That's when I happen to request for page "node/1/aaa/bbbb", I'm served the response for "node/1" (it's parent page).

I can understand, this is the way Drupal menu system has been designed and works for some obvious reasons.

But I'm in a need to change this. Reason we have some aliased urls across the site, links from third party sites are taking (visitors and crawlers) to not existing page for which ideally http 404 response code and page not found to be returned. Instead Drupal showing it's parent page (with http res. code 200). This is leading to duplicate page in Google webmasters and misleading our genuine users.

I have found a patch to this issue. However it is working fine only for 80% of cases, some valid urls (admin/*, sites/default/files/ * , system/ajax/*, etc.,) leads to 404 page.

Would like to hear how others are dealing with this duplicate content issue concerning SEO and possible fix!

Considering the comments of the previous answer:

Only act on 'node' pages (aliased and not).
Avoid 'page not found' repeating 2 times.

Furthermore removed the unused variable $path.

The code below also avoids a 404 for the path 'node/add'. In case you use the Entity connect module that path might be followed by a dynamic token. The URL could then look like 'node/add/page/entityconnect-form-hmcOTIsupNLNBI-cZ-sSvjsbFISJeOfzT0VBpg0Sbpc'. Obviously that is a path not "known" by Drupal that would otherwise incorrectly result in a 404.

/**
 * Implements hook_init().
 */
function YOURMODULE_init() {
  // Only act on 'node' pages (aliased and not) but not on 'node/add'.
  if (arg(0) === 'node' && arg(1) !== 'add') {
    // Extract different variables that Drupal utilizes for routing.
    $menu_item = menu_get_item();
    $href = $menu_item['href'];     // node/1
    $current_path = current_path(); // node/1/broken

    // Check if the actual path ($current_path) is different than the Drupal assumption ($href).
    if ($href != $current_path) {
      // Redirect user to 404 page which will handle the HTTP response as well.
      drupal_not_found();
      // Avoid 'page not found' repeating 2 times.
      drupal_exit();
    }
  }
}

UPDATE:
There is now a Drupal 7 module Force 404 that solves just this.


Autopopulate "Postal Code" from taxonomy in Location module In Location module input I want to disable "Postal Code" field but the node will have a mandatory vocabulary selection (vocabulary name: Postal Code).

What I want is that when I create a node with the postal code term selection it should automatically populate the "Postal Code" field of location module input from this term.

What is the right way to do it?

I think the only way to do this is with a custom module.

You would implement hook_form_alter to disable (or hide altogether) the location postal code on the node form.

You would then implement presave op of hook_nodeapi (drupal 6) or hook_node_presave (drupal 7) to fill in the location data.

If you don't know PHP, you could also add some custom javascript that changes the location postal code when the taxonomy drop down is changed.


Content profile vs profile I am confused as whether there is even a need for me to enable content profile, I mean you can use profile of drupal that has the ability to enable extra fields and all.Whileas content profile only has one field, Name, Bio ....

With the core user profile you can have just one profile.

Profile2 gives you the permission to create different profile type and with the permission you can relate it to the role.
Every profile can have different fields.
Quick example:

Let's say you have a football website, so you have different profiles for different role player like goalkeeper wing, midfilder etc...

You create one profile per each role with different fields with Profile2
goalkeeper: height, gloves size etc...

Wing: first foot, side, speed etc...

You go to people->permission->role and you create a role per each role player and then you give the permission to a role for the related Profile so user with wing role can use the wing profile.

In the core user account you can create a field "Role player" (a radio button in this case is better)

Goal Keeper | Wing etc...

Then you will use "Rules" to create the rule

React on event = After saving a new user account

Condition = data comparision (you should look for you field "role player" in core user account)

Action = Add user role (you can select the relative role)

Automatically the role is assigned.


How can I limit Webform submissions by date I want to have a select list on the webform node with options to decide how many times each user may submit the form. for example once a day, once a week, once a month... How can I do it?
Thanks!

Download Webform 7.x-4.0-beta3

On the Webform > Form Settings, half way down the page you can set the total submissions limit, and set time frames for limitations.


jQuery ui embedded calendar on a drupal 7 form I have a drupal 7 custom form written in PHP where the user can add periods of time to define his/her availability. Created periods of time are showed in a tableselect list with a button to delete them one by one. Now I want to delete this table and show the periods on a jQuery ui embedded calendar instead. How can I do that?

Given the fact drupal 7 form api has no calendar type I guess one solution would be to write a custom block in PHP where I could print the calendar. Then I could show/hide this new block when needed with Context module new rule. Do you think this solutions is good or there is a better approach?

Any suggestions would be appreaciated! Thanks!

I have already implemented my approach on a custom module and it's working fine! Here's my code:

function calendar_block_info() {
    $blocks['embedded_calendar'] = array(
    'info' => t('Calendar block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

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

  switch ($delta) {
    case 'embedded_calendar':

      //JS code based on: http://stackoverflow.com/questions/5578259/jquery-ui-datepicker-how-to-add-clickable-events-on-particular-dates

      drupal_add_css(drupal_get_path('module', 'calendar') .'/calendar.css');
      drupal_add_library('system','ui.datepicker');
      drupal_add_js('jQuery(document).ready(function() {

                      var events = [
                        { Title: "Five K for charity", Date: new Date("02/01/2013"), class: "red" },
                        { Title: "Dinner", Date: new Date("02/02/2013"), class: "green" },
                        { Title: "Meeting with manager", Date: new Date("03/01/2013"), class: "blue" }
                      ];

                      jQuery( "#embedded_calendar" ).datepicker({
                                                   numberOfMonths: 2,
                                                   regional: "es",
                                                   beforeShowDay: function(date) {
                                                      var result = [true, "", null];
                                                      var matching = jQuery.grep(events, function(event) {
                                                          return event.Date.valueOf() === date.valueOf();
                                                      });

                                                      if (matching.length) {
                                                          result = [true, matching[0].class, null];
                                                      }
                                                      return result;
                                                   },
                                                   });
                    });', 'inline');

      $block = array(
        'subject' => t('&nbsp;'),
        'content' => '

',
      );

      break;
  }
  return $block;
}


Can't find the cause of this error I am working through a Drupal 8 module building exercise from YouTube and I am not able to figure out what is causing an error. The relevant page loads and displays the form but I get the following error message:

Notice: Trying to get property of non-object in Drupal\rsvplist\Form\RSVPForm->buildForm() (line 29 of modules/custom/rsvplist/src/Form/RSVPForm.php).

Drupal\rsvplist\Form\RSVPForm->buildForm(Array, Object)
call_user_func_array(Array, Array) (Line: 518)
Drupal\Core\Form\FormBuilder->retrieveForm('rsvplist_email_form', Object) (Line: 275)
Drupal\Core\Form\FormBuilder->buildForm('rsvplist_email_form', Object) (Line: 93)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 38)
Drupal\webprofiler\StackMiddleware\WebprofilerMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

The code for the form is here:

<?php
/**
  *@file
  *Contains \Drupal\rsvplist\Form\RSVPForm
  */
namespace Drupal\rsvplist\Form;

use Drupal\Core\Database\Database;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 *Provides an RSVP email form
 */

class RSVPForm extends FormBase {
  /**
   * (@inheritdoc)
   */
  public function getFormId() {
      return 'rsvplist_email_form';
  }

  /**
   * (@inheritdoc)
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
      $node = \Drupal::routeMatch()->getParameter('node');
      $nid = $node->nid->value;
      $form['email'] = array(
          '#title' => t('email address'),
          '#type' => 'textfield',
          '#size' => 25,
          '#description' => t("We will send updates to the email address you provide"),
          '#required' => TRUE,
      );
      $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('RSVP'),
      );
      $form['nid'] = array(
          '#type' => 'hidden',
          '#value' => $nid,
      );
      return $form;
  }
  public function submitForm(array &$form, FormStateInterface $form_state) {
      drupal_set_message(t('The form is working'));
  }
}

The Drupal version is 8.6.15. PHP Version is 7.0.15 Can anyone spot an error I am missing?

Line line 29:

$nid = $node->nid->value;

Try this solution:

$node->id();

Very useful thing "Drupal 8 Entity API cheat sheet": https://www.metaltoad.com/blog/drupal-8-entity-api-cheat-sheet