How to properly recognize a session id generated by drupal?

Drupal will let you override the default session handler using the session_inc variable. This is what Drupal actually uses to bootstrap the session:

require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');

So to replace that with your own, set the variable to your own path:

variable_set('session_inc', 'sites/all/modules/MYMODULE/session.inc');

And re-implement the functions from the core session.inc in your custom file, making changes where necessary.


Difficulty getting Rules Scheduler in D7 to publish a node in the future

It turns out the concern about cron running under Anonymous user was a red herring. Thanks @Patrick Kenny for encouraging more persistent logging.

Diagnosis: the reaction rule that was scheduling the component was triggered by a 'Before saving content' event. In my testing - because of my faulty theory about the cause of the problem - I was repeatedly using an already created node. As such, the node nid was successfully passed to the component and so in logging (and in inspecting the list of scheduled rules) everything looked OK. And the alert email was even correctly generated. It turns out, however, that when the component is scheduled from a reaction rule triggered by a 'Before saving content' event, then changes to the node are not saved when the component executes.  So some things works with the parameter passed from a 'Before saving content' triggered reaction rule, but not others. And for the things that don't work no error or issue is flagged in logging. Glad to know that now.

For anyone coming here just wanting some Rules to import to get delayed publishing up and running, here is the exported component and two exported rules that do the job.

Component to publish a node

In my use case, I also had a check for a specific node type. If you need to add that, add an extra condition after importing the component. (Import the component at: admin/config/workflow/rules/components)

{ "rules_publish_content" : {
    "LABEL" : "Delayed publish action",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "delayed_node" : { "label" : "Delayed node", "type" : "node" } },
    "RULES" : [
      { "RULE" : {
          "IF" : [ { "NOT node_is_published" : { "node" : [ "delayed-node" ] } } ],
          "DO" : [
            { "node_publish" : { "node" : [ "delayed-node" ] } },
            { "mail" : {
                "to" : [ "delayed-node:author:mail" ],
                "subject" : "Your item, \u0022[delayed-node:title]\u0022, has been published.",
                "message" : "Your item, \u0022[delayed-node:title]\u0022, has been published.\r\n\r\n[delayed-node:url]\r\n",
                "language" : [ "" ]
              }
            }
          ],
          "LABEL" : "Delayed publishing: publish and alert"
        }
      }
    ]
  }
}

Rule to trigger delayed publication when authored on date is in the future

In my use case, I also had a check for a specific node type. If you need to add that, add an extra condition after importing the rule. (Import the component at: /admin/config/workflow/rules). In addition, in my use case, I looked at a specific date field on the content type rather than the node:created, i.e. 'Authored on', value. If you want to do that then, after doing the import, add a new condition that checks your added date field and remove the condition that checks the standard Drupal created date field.

{ "rules_publish_node_future" : {
    "LABEL" : "Publish node (in the future)",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : [ "node_insert", "node_update" ],
    "IF" : [
      { "data_is" : { "data" : [ "node:created" ], "op" : "\u003E", "value" : "now" } }
    ],
    "DO" : [
      { "node_unpublish" : { "node" : [ "node" ] } },
      { "schedule" : {
          "component" : "rules_publish_content",
          "date" : [ "node:created" ],
          "identifier" : "Delay publication of node: [node:nid]",
          "param_delayed_node" : [ "node" ]
        }
      },
      { "drupal_message" : {
          "message" : "\u003Cstrong\u003EPublishing will be delayed until (up to 3 hours) after: [node:created:long].\u003C\/strong\u003E This is because the \u0027Authored on\u0027 date you entered for your item is in the future. If you need to publish now then edit the item, change \u0027Authored on\u0027 date to now or earlier, set the item to be \u0027Published\u0027, and save.",
          "type" : "warning"
        }
      },
      { "mail" : {
          "to" : [ "node:author:mail" ],
          "subject" : "\u0022[node:title]\u0022 publication will be delayed until [node:field-date]",
          "message" : "\u0022[node:title]\u0022 publication will be delayed until (up to 3 hours) after: [node:created:long].\r\n\r\n[node:url]\r\n\r\nYou have received this message because the \u0027Authored on\u0027 date you entered for your item is in the future. If you need to publish now then edit the item, change \u0027Authored on\u0027 date to now or earlier, set the item to be \u0027Published\u0027, and save.",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Rule to cancel delayed publication if node is saved with a date in the past

This rule cancels any scheduled publication of the node. It does not set the node to be published. Depending on your setup, you might want to add an action to this rule to publish the node.

{ "rules_publish_node_future_cancel" : {
    "LABEL" : "Publish node (in the future cancellation)",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "NOT data_is" : { "data" : [ "node:created" ], "op" : "\u003E", "value" : "now" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_publish_content",
          "task" : "Delay publication of node: [node:nid]"
        }
      }
    ]
  }
}


The reason your current code isn't working is because your submit handler doesn't follow the correct naming convention (i.e. FORM_FUNCTION_NAME_submit) and you don't explicitly attach the submit handler to the form anywhere so it's not being run.

You can solve this by simply changing the nameof your submit handler:

function example_form_form1_submit($form, $form_state){

Or you could look at system_settings_form() which automates much of this process for you.


404 Not Shown For Custom Module - Drupal 7

It's the expected behavior, and it's described in the documentation for hook_menu(), even it  could not be clear, at a quick read.

  Callback Functions

  The definition for each path may include a page callback function,
  which is invoked when the registered path is requested. If there is no
  other registered path that fits the requested path better, any further
  path components are passed to the callback function. For example, your
  module could register path 'abc/def':

function mymodule_menu() {
  $items['abc/def'] = array(
    'page callback' => 'mymodule_abc_view',
  );
  return $items;
}

function mymodule_abc_view($ghi = 0, $jkl = '') {
  // ...
}

  When path 'abc/def' is requested, no further path components are in
  the request, and no additional arguments are passed to the callback
  function (so $ghi and $jkl would take the default values as
  defined in the function signature). When 'abc/def/123/foo' is
  requested, $ghi will be '123' and $jkl will be 'foo'. Note that
  this automatic passing of optional path arguments applies only to page
  and theme callback functions.

This means that, for example with login/asdfdsa, Drupal will first check if there are modules that handle that path. If there aren't modules handling that path, Drupal will check if there are modules handling every path matching login/*; if there aren't modules for those paths, Drupal will check if there are modules that handle login. In your case, that is your module. (I left out how Drupal handles the path aliases, as in this case isn't relevant.)

That happens also for other paths, for example node/1. If you have a node whose ID is 1, /node/1 shows it. If you try to access a path like, for example, /node/1/sdfgrgjpqwd432az, you will still see that node. (sdfgrgjpqwd432az is just a random string, to be sure I am not using a path for which a module defines a page callback.)


This is not you, it is a bug in the module. I'm sorry to say that the fact that the bug goes back to September does not bode well for a fix.  Neither does the fact that there is only one active maintainer who has not made any changes since the releases in August.  If you are a coder, you might try fixing the code.  If not, you may want to look for other options.


How to link to live chat TawkTo module pop up window with Drupal 7?

You can easily achieve this by using Void Menu module.

Download & Install Void Menu module.
Go to http://www.yoursite.com/admin/config/user-interface/void_menu
Set javascript:void(Tawk_API.toggle()) as value for HTML value for <void2>
Then go to main menu configuration and set menu Path as <void2>


How can I fix the "Could not delete temporary file"?

Change to another tmp folder destination? Configuration -> file system

I not sure will this help you.


Menu items disable and weight resets on save

I think I have discovered this issue with Drupal 8 too.

I have the default Menu navigation from the Bootstrap theme, which I am trying to add a menu item for an "About me" page.  When I edit the menu item link and save with correct weight and Enabled set, the menu item is ticked. However, when I click the Save button on the main Menu page, the About Me item is disabled. Two items remain ticked - the Home menu and a View.

There seems to be a bug in the global Save button for the Menu. I guess the workaround is to modify menu items by clicking Edit, rather than directly on the menu page.


I figured out how to actually do this. We need to go to the class from which the object was instantiated and figured out any public getter and setter methods. This should be obvious for someone well versed with OOPs. Here is I managed to modify the response.

public function login(Request $request) {
  $response_data = parent::login($request);

  // We need to get data in the original response and there is actually a
  // a public method provided by the parent class getContent which we are using
  // below.
  $mydata = $response_data->getContent();

  // Original data is serialized so we need to decode it.
  $decoded_data = $this->serializer->decode($mydata, 'json');
  $uid = $decoded_data['current_user']['uid'];
  $user = $this->userStorage->load($uid);

  // custom function to process the user
  $mynewdata = $this->customfunction($user);

  // Adding to the original decoded response array and
  // then encoding again.
  $decoded_data += $mynewdata;
  $combined data = $this->serializer->encode($decoded_data, 'json');

  // Setting the content to the origina response object. Important!!!
  $response_data->setContent($encoded_sponsor_data);
  return $response_data;
}


Allow subusers to access parent's content

I think you already solved this yourself but searching the same issue I ended up on this post. Since I found a solution I will post it here for all other people running in to this problem.

The solution is in combining the modules subuser and user relationships and rules.

Subuser gives other users the right to add new users. These users are related to each other with the relationship module but there is
no link between their nodes.
To get the link between content of the users I used the user relationship module. This module let's you set up relationships as
friend, coworker or co-editor or whatever name you want to give it. These relationships can give one way or two way permissions to
update, view or delete each others nodes.
Normally you would have to go to a users page and request the relationship with the user but with rules it's possible to set a
relationship when a new user is created.

So what steps to take. First enable all modules. For the user relationship you have to enable the main module but also the User Relationship UI and the User Relationship Rules module. Now go to the relationship module admin/config/people/relationships and create a relationship with the name "friends" (or whatever name you want). At the share content tab make sure that the content type you want to share is selected.

Now go to roles admin/people/permissions/roles and create a new role with the name "friends" (so the same as your relationship, just because it's the most clear).

Now go to permissions admin/people/permissions and set the User Relationship permissions as you want. Make sure that Grant view permission to related users and Grant update permission to related users is set in the right way to the roles you use. So if you want the subuser(friend) to be able to see and edit the parents content make sure the permissions are on for him. Also make sure he has the right to get the friends relationship. Also make sure the parent has all these rights as well.

Now go to the parents user page and go to the share content part, set it up so that the friend is able to update and view content.

When all this is done it's time to go to Rules in rules it's possible to create a rule that says:
 - If User Created
 - And Role is Friend
 - Request Relationship (Friend) - Auto Approve Relationship

Now when the parent creates a subuser the subuser will be able to edit and view its parents nodes. For the parent it is still possible to give his Friends a per node based access to it's nodes. So on default all nodes are shared but the parent can edit this per node.

I hope this is clear enough I did my best, but please let me know if there are any unclear parts.


Preventing a menu item from being pressed twice

For long tasks you should use Drupal's Batch API. It takes a bit to learn, but has these benefits.

The user will be taken to a separate page with a progress bar.
You can display a custom message explaining what you are doing.
If you can break your task into discrete chunks that can be performed in separate requests that will ensure that you won't run into any php timeout issues and the users will see their progress.

For example, during Drupal setup you see the following batch process:


How do I change taxonomy page callback for a specific vocabulary only?

Since the callback is getting the taxonomy term object as argument, you can check the value in $term->vocabulary_machine_name to get the machine name of the vocabulary, and see if it is the one you are interested in.

function MYMODULE_taxonomy_page_callback($term) {
  if ($term->vocabulary_machine_name == 'MYVOCABULARY') {
     drupal_goto('somewhere');
  }
  else {
    return taxonomy_term_page($term);
  }
}


The following should work for you.

      hide($content['field_themes_images']);

        <?php
          foreach ($content['field_themes_images']['#items'] as $key => $img)
          {
            print "
";
            print render($content['field_themes_images'][$key]);
            print "
";
          }
        ?>


Domain Access + Domain i18n = Site names not translating in other languages?

I'm assuming you're using the "Domain Access" module. And even though you didn't explicitely mention it, you also use the i18n module. If my assumptions are correct, then be aware of what's mentioned on the project page of the "Domain Access" module:

  If you use the contributed i18n module suite, you should use the Domain Variable module instead of the provided Domain Configuration and Domain Settings modules.

Therefor I think you should try the Domain Variable module, to check if it fixes you issue.


Add panelizer display when create a node programmatically

Here is some example code for creating a node and setting the panelizer variant/display automatically.
Note: The EntityMetadataWrapper module is used for setting the title.

  $entity_type = 'node';
  $bundle = 'page';
  $variant = 'YOUR_VARIANT_NAME';
  $variant_name = $entity_type . ":" . $bundle . ":" . $variant;

  $values = array(
    'type' => $bundle,
    'uid' => 0,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
  );

  $entity = entity_create($entity_type, $values);

  ctools_include('export');

  $panelizer = ctools_export_load_object('panelizer_defaults', 'names', array($variant_name));
  $entity->panelizer['page_manager'] = $panelizer[$variant_name];

  $wrapper = entity_metadata_wrapper('node', $entity);
  $wrapper->title->set('Your Title');

  $wrapper->save();


Here is one way to do it... not sure if there are others (admin based):

/**
 * Implements hook_ckeditor_css_alter().
 *
 * Injects our CSS sheets anytime CKEditor has loaded.
 *
 * @param array $css
 * @param Drupal\editor\Entity\Editor $editor
 */
function mymodule_ckeditor_css_alter(array &$css, Editor $editor) {
  if (!$editor->hasAssociatedFilterFormat()) {
    return;
  }

  $known_formats = [
    'basic_html',
    'full_html'
  ];

  if (in_array($editor->getFilterFormat()->id(), $known_formats)) {
    $css[] = drupal_get_path('theme', 'mytheme') . '/build/css/style.css';
  }
}


Pathauto alias produces inconsistent aliases

Check settings in  Administration » Configuration » Search and metadata » URL aliases there is a Strings to Remove like this:

  a, an, as, at, before, but, by, for, from, is, in, into, like, of,
  off, on, onto, per, since, than, the, this, that, to, up, via, with

thats why your A is removed i think.


How so I execute $query->orderBy('FIELD(node.nid, 5,12,3,6)', 'ASC')?

I did a workaround by implementing a CASE statement then sorting by the value.

$query->addExpression("
    CASE node.nid
        WHEN 5 THEN 1
        WHEN 12 THEN 2
        WHEN 3 THEN 3
        WHEN 6 THEN 4
        ELSE 5
    END
", 'order_field');

$query->orderBy("order_field", 'ASC');

Hopefully they'll add another function to handle these special statements in the future.


Temporary disable ordering in Drupal Commerce

The simplest thing to do would be to disable "Access checkout" permission for these non-privileged users. That may result in some usability issues where links appear that would be inaccessible, so you'll want to confirm that and adjust those interfaces appropriately.


How to create a redirection programmatically?

If you want to store redirects in database use the module Redirect. This module provides a user interface to add redirects. The redirects are stored in a content entity, which you can also create programmatically:
use Drupal\redirect\Entity\Redirect;

  Redirect::create([
    'redirect_source' => 'redirects/redirect1',
    'redirect_redirect' => 'internal:/node/1',
    'language' => 'und',
    'status_code' => '301',
  ])->save();

You can do this at the time you create nodes from imported data or in entity hooks when inserting, updating or deleting nodes.


You can use hook_node_presave, it is called right after creation and edits.


As it's an Email field, you need to query the array for email not value:

$node = node_load(14);
print $node->field_contact_email[$node->language][0]['email'];

// Outputs:
youremail@example.com

If you're intending on rendering the email address on a page, you should look into using field_view_value, which will give you a string of HTML markup for a field value. The benefit of this, is that it will use the rendering function for what ever field type you supply it with.

$node = node_load(14);
$email = field_get_items('node', $node, 'field_contact_email');
$output = field_view_value('node', $node, 'field_contact_email', $email[0]);
print $output['#markup'];

// Outputs:
youremail@example.com


How can I limit the number of upload files programmatically?

I assume you use filefield module for attachment, if so, use this:

/**
 * Implementation of hook_form_alter().
 */
function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'content_field_edit_form') {
    $form['field']['multiple']['#options'] = array(1 => t('Unlimited'), 0 => 1) + drupal_map_assoc(range(2, 14));
  }
}


Conditional price in readonly text field

Looking at your requirements I would suggest going with the data module

You could create a table with all the possible combinations. Once that is done in your content type you would be displaying the required fields such as Apartment Type, Plan Type etc. When the content is chosen you can look up in the table and get the correct pricing.

There are some assumptions made here. The prices are fixed and known in advance and changes in price would be minimal. We only need to get the correct price defined byt the table.

As for the down payment and EMI I presume you would have a set rules for the same which can be calculated on the go.


display newly added field value of account settings

You should use field_get_items:

global $user;

$user_contaning_field = user_load($user->uid);

// Check if we're dealing with an authenticated user
if ($user->uid) {

  // Get field value from $user
  $field_first_name = field_get_items('user', $user_contaning_field, 'field_first_name');

  foreach ($field_first_name as $key => $value) {
    print field_view_value('user', $user_containing_field, 'field_first_name', $field_first_name[$key]);
  }
}


I fixed it. The problem was that the path contained "20%" instead of a space.


How do I see the value of one field of a multi-item field in views formatter

You don't need to search for another method, Field::getValue() returns the array you are looking for:

if ($view->field[$field_name]->multiple) {
  $field_array = $view->field[$field_name]->getValue($row);
}

I don't know if there is a documentation, but you can see this in code:

https://api.drupal.org/api/drupal/core!modules!views!src!Plugin!views!field!Field.php/function/Field%3A%3AgetValue/8.2.x

Difference between field values from view result and entity

If you have a standard multivalue field like text or number in a view and don't change any options, getValue($row) returns a one-dimensional array with the values from the main property of the field. If not you have somehow configured the view so that it shows a different result.

You can although get the original entity field data, which is independent from the configuration of the view. For this the field needs to be in the row entity:

$field_array = $row->_entity->{$field_name}->getValue();

This is then a two-dimensional array with multiple values and multiple properties.


Unable to Search or Sort through Webform Submitted Data

Check your FORMAT -> Format: Table | Settings for a checkbox that says Override normal sorting if click sorting is used and turn it on if it is not already.


Add counter to view with rendered entity output

Result number is a views field node has no clue about. You need to use "fields" output to add fields that are not in the node itself - that's the very reason of this output's existence.


How do I pass multiple block configurations to a behavior?

So as Leigh suggested I send this data values into a twig file

  public function build() {

    $build = [
      '#theme' => 'curatorio_io',
      '#id' => uniqid(),
      '#feed_id' => $this->configuration['feed_id'],
      '#widget_type' => $this->configuration['widget_type'],
      '#attached' => [
        'library' => [
          'curatorio/curatorio_assets',
        ],
      ],
    ];

    return $build;
  }

Now in my twig file, I put those values into data attributes

<div class ="curator-feed"  id = "{{ id }}" data-feed-id = "{{ feed_id }}"  data-widget-type = "{{ widget_type }}" >

</div>

and in js I attached my JS logic to get attribute value and attach Plugin into it.


CCK doesn't find the Image module on Drupal 7

Actually, the Image module is part of Drupal core. Enable it, and the error should vanish.

If you don't find the module listed between the modules, then you need to copy the Drupal files again on your server.

If the Image file is already present in your web server, it is enabled, and CCK keeps saying it cannot find the module, then open an issue report for CCK.


node--<content-type>.tpl.php

Check out the discussion for how to active template suggestions at the theme level: Drupal 7 page template suggestions.


I'd also recommend Views Bulk Operations. You could create a view with a filter of that content type and add enable comments as an action. Then it offers you to select all.

Quite the useful admin tool.


How do you add table column sort functionality to an EntityFieldQuery?

I know this thread is a little old but adding 'field' to the array fixes the issue.

e.g.

$header = array(
  'title' => array(
    'data' => t('Date'),
    'type' => 'field',
    'specifier' => array(
      'field' => 'field_articledate',
      'column' => 'value',
    ),
    'field' => '', //There is an Isset call that prevents links from showing without this.
  ),
);
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1);

$query = $query->tableSort($header);
$query = $query->pager(100);

$results = $query->execute();

See: https://www.drupal.org/node/885014#comment-3464666 for a comment on the issue.


How to programmatically assign user roles

Drupal core user.module provides a simple function to add/remove roles to/from a user. See user_multiple_role_edit().

$uid = 12345; // The user ID of the account you want to change.
$role_id = 4; // The numeric role ID you want to add.
$role_id_rm = 3; // The numeric role ID you want to remove.

user_multiple_role_edit(array($uid), 'add_role', $role_id);
user_multiple_role_edit(array($uid), 'remove_role', $role_id_rm);


The date formatter service automatically converts it to whatever time zone you selected when you installed the Drupal site, admin/config/regional/settings.

Also, if you allow users to set their own timezone in user/1/edit, it would use that time.

So either you need to change the timezone in admin/config/regional/settings and/or in user/1/edit


From the screenshot you show, it's clear that you installed and enabled the Administration Views module. In fact, for a fresh Drupal 7 installation, the admin/content page would appear as in the following screenshot.

I installed it on my test, and it works fine for me.

Once you install and enable the module, that administrative page is replaced from a view. If you changed the view, it could be it is filtering out the nodes to show in that page.
Go to admin/structure/views/view/admin_views_node/edit and check the filter criteria aren't too much restrictive. By default, that view has only exposed filter criteria; if you find any not-exposed criterium, that is something manually added to the view, and it could be causing the issue you are seeing. A filter for the content type can cause what you see, but so a filter for the creation date, and many other filters.

As reference, this is the setting page for the view as it comes after installing the Administration Views module.

Also, the view has a setting for caching it (as any view); if it has been changing from None to Time-based, then either the query results or the render output could be cached for too long. The default values are 1 hour for both.

The other reason could be that the view is being filtered by the author name. If I put three spaces in the Author field, and then I click Apply, I get the following.

Now the list says No content available. even if I still have those two nodes you saw in the previous screenshot. That is because the author name doesn't contain three spaces.
The same happens if I enter three spaces in the Title field.

To be sure the exposed filter criteria aren't causing any issue, click on the Reset button right to the right of the Apply button. That will reset the values for those filters.


how to select a non-drupal (souce db) database in a migrate module

It would probably be better if you looked at the Feeds module using the Feeds Database fetcher.


What entity should entity_id be joined on?

The customer addresses are linked to the user, see https://drupal.stackexchange.com/a/121356/2322 for more details on this, so you've got an order that references a customer profile and this references a user.

It doesn't show this part, but find a more complete description about the commerce entities in this documentation page: http://www.drupalcommerce.org/user-guide/products

In any case, I'd definitely use Entity Field Query for this, it will save you from digging in the database and it will give you a more consistent way to access your data.


Using an authentication provider to keep a user permanently logged in eventually causes session problems

I presume it's because the session has expired in some way?

First you need to understand how this happens.

Configuring Garbage Collection
When a session opens, PHP will call the gc handler randomly
according to the probability set by session.gc_probability /
session.gc_divisor. For example if these were set to 5/100
respectively, it would mean a probability of 5%. Similarly, 3/4 would
mean a 3 in 4 chance of being called, i.e. 75%.
If the garbage collection handler is invoked, PHP will pass the value
stored in the php.ini directive session.gc_maxlifetime. The
meaning in this context is that any stored session that was saved more
than gc_maxlifetime ago should be deleted. This allows one to expire
records based on idle time.
However, some operating systems (e.g. Debian) do their own session
handling and set the session.gc_probability variable to 0 to stop
PHP doing garbage collection. That's why Symfony now overwrites this
value to 1.
If you wish to use the original value set in your php.ini, add the
following configuration:
# config/packages/framework.yaml
framework:
    session:
        gc_probability: null

Source: Symphony's official docs on Configuring Sessions and Save Handlers

In Drupal 8 & 9 you can see these gc settings in default.services.yml
Possible Solutions on how to stay logged in longer.
In /sites/default/settings.php uncomment
 if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
   include $app_root . '/' . $site_path . '/settings.local.php';
 }

then copy /sites/example.settings.local.php and rename to /sites/default/settings.local.php
Now you can use /sites/development.services.yml to override those settings, for example
(I used these numbers for testing so it logs me out after 2 seconds):
parameters:
  session.storage.options:
    gc_probability: 1
    gc_divisor: 1
    gc_maxlifetime: 2
    cookie_lifetime: 2

I tried setting gc_probability to 0 or null, which should stop it, but the gc() function still fired. Perhaps it's reading the value from php.ini
So alternatively you could set the gc_maxlifetime and cookie_lifetime to not expire decades from now. See set a cookie to never expire.


When adding media to content, how can I search for the media by tag or term?

As Kevin said, you need to install the Entity browser module

Optional module: I personally also use Entity Browser Enhance(d|r) for a much better usability when selecting media.

Go to /admin/structure/views/add and create a view showing Media items. On the next screen add a display type Entity browser to your view. You must add the special Entity browser bulk select form field to this view. Configure the view with additional fields and filters of your own choice. E.g. if you need taxonomy tags, add an exposed filter for your tags field.

Under Configurarion > Content Authoring > Entity browsers, create a new entity browser for your media. Configure as you need, and in the last step add the previously created view as widget plugin.
(Beyond the selection view you could add multiple widgets here like DropZoneJs for in-place uploading or Inline Entity form for in-place creating of new nodes).

Go to Structure > Content Types, and edit the form display of your node. Change the widget of the media field to Entity browser and select your previously created browser.

There are quite a lot of configuration options on the way, but this is a basic outline to get a media browser like this:
(The search part can contain any/multiple exposed filter like a "normal" view)

I recommend this tutorial for additional information
https://www.electriccitizen.com/blog/media-libraries-drupal-8
(but I personally would not use Inline entity forms for media, better stick with Entity browser for selection and DropZoneJS for in-place uploading)


What are the best ways for creating galleries from images stored as entities?

Hey you can use the Galleria module in D7. Here is a quote about it (from the module's project page):

... allows users to create image galleries using the Galleria jQuery plugin, found on http://galleria.aino.se.
There are several different approaches of using this module to create Galleria image galleries. The most typical and easiest way to do so is to use it as a field formatter for image or media fields. All images uploaded to such a configured field will then be displayed in a Galleria gallery.
You can also use it in conjunction with the References module to build a gallery of image nodes, referenced by a 'Node reference' field; or you can use the Views module to gather a list of images to display in a Galleria.


AD MPD noted in the comments, the issue is how Amazon Cloudfront handles the image style URL, specifically the ?itok query string.

So, when creating your distribution in Cloudfront, make sure you set "Forward Query Strings" to "Yes". See screenshot:


Can we return 2 table themed arrays in function

The issue is you're passing elements that a render array would use, such as the "#rows", "#sticky", etc, but Form API will ignore them, because anything prefixed with a "#" will be treated as a property of the form element.

Clive gives here (https://drupal.stackexchange.com/a/27269/28556) a very concise explanation and solution for that, which consists in creating your own theme function to render a particular element.

Additionally, I think you could, as well, use the existing theme('table', ...) function to render the table from that same function, but returning the results as direct markup instead.


Cannot alter clientside validation error messages for fields added with the field UI module

I was able to set the rule by referencing the nested #name and #value keys:

_clientside_validation_set_required(
      $element['field_first_name']['und']['0']['value']['#name'],
      $element['field_first_name']['und']['0']['value']['#title'],
      isset($element['field_first_name']['und']['0']['value']['#required']) ? $element['field_first_name']['und']['0']['value']['#required'] : FALSE,
      $js_rules,
      t('Please enter your @field_name.', array('@field_name' => strtolower($element['field_first_name']['und']['0']['value']['#title'])))
    );


Set Home link in breadcrumb for items in a particular menu

In my opinion, if you want to customize the breadcrumb, the Path Breadcrumbs is the best module for this kind of purpose.

  This module is a solution for all problems with the breadcrumbs on
  your site!

  Path Breadcrumbs module helps you to create breadcrumbs for any page
  with any selection rules and load any entity from the URL!

You can follow this tutorial for the help.


theme_hook process: calling a theme function not working(example from DGD7)

First of all, your theme_xray_appearance_summary should be theme_appearance_summary, and should take $variables by reference: &$variables.

Second of all, hook_help() expects you to return a string, but your implementation returns the data from xray_appearance_summary(), which returns an array, thus the error you're getting.


I don't think there is a D7 of the feature server but you can host your D7 specific features on a D6 feature server.


Tags for content type and search by this tags

You can try to use the Term Search module


How can I show list of users that bookmarked article?

If you really want to do this with Views you will need the following:

A Content View for articles
with a Nid as a Contextual Filter, in order to limits the results to the article node you are interested in
one relationship that will restrict your results to content that has been flagged with the bookmark flag (by any user)
one relationship that will return all users that flagged content using the flag from the relationship in (3).

Here is a Screenshot of the View:

and one of the end-result, in a sample node:

Hope this helps!


How to access the administration panel if you cannot login again?

You change your default theme in setting.php.Uncomment this line in your setting.php file

 $conf['theme_default'] = 'garland';


Is there a way to programmatically add new links to the primary links?

You can either specifiy the menu name in hook_menu() (look for 'menu_name') if they are defined with that hook or you can use menu_link_save().

Yet another option would be to use http://drupal.org/project/features and export your menu structure as a feature.


Restrict creation of content type by user reference

I would create a custom module that uses Entity Field Queries to do the following:

First, use EFQ to select nodes of type "location" where "user" matches the "user" specified in the selected "event" AND also the "location" value matches the "location" specified in your event. This has essentially the same effect as the Views solution you've worked out, I believe.
The advantage over Views here is that now you can node_load() the nodes you find or you can execute more complex logic if there are no matches (i.e. if the user should not have permissions).
Use hook_node_grans() or hook_permission as needed.


All modules listed there are dependencies of the Dawn theme, and when we look at the Changelog there are entries like: - Added jQuery Update, Honeypot modules.

There is no way for a theme to define module dependencies (you'd need an installation profile for that), so my best guess would be the theme creators packaged the modules within the theme.
Normally I would have checked that for you, but it is a little harder with commercial themes. You should browse through your Dawn theme folders and see if the modules are nested in a sub-folder somehow. (Perhaps there is even a README explaining you should move them?)

The reason they are listed as themes is because modules and themes both provide a *.info file containing the details, and only the folder they are in is used to distinguish between module or theme. Since the module / theme detection in Drupal can scan multiple folders deep (eg. Views UI module is a subfolder of the Views module), it probably detects these modules's .info files and assumes they are themes since they are in the sites/all/themes folder.


Custom date format (instead of %date) for WebForm e-mail title?

Place this code in a custom module:

     /* first add a custom date field (mydate), you have to set it's value with rules */
  /* change all capital letters with proper names (in lower case) */
  function YOURMODULE_preprocess_node(&$vars) {
$vars['MYDATE'] =
t('!datetime',
  array('!datetime' => format_date($vars['node']->MYDATE,
    'custom', 'M/d/Y, h:i a')));
}
  /* hide custom field to all users but admin */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $uuid = $user->uid;
  /*  check that user is NOT admin (No1) */
    if ($uuid !='1') {
        /* if is user profile form use: if ($form_id == 'user_profile_form')*/
      if ($form_id == 'YOUR_FORM_ID') {
      //dsm($form);
        hide($form['field_MYDATE']);
       }
 }

for a diferent format look at: http://php.net/manual/es/function.date.php

having date format correct, go agian and do:

new message %mydate


Start with a sanity check - make sure your rules "make sense" and that you set them up correctly. Try to apply the same context rules on a clean install.

If it works there and not in your existing site (with content, other modules and customized configuration), clone that site and try disabling modules one by one to see where the conflict is. It's hardly possible to say where the problem is without knowing any details about your existing installation.


D7 : Upload to a folder outside of "files" folder?

It is impossible by design, for security reasons. Imagine your users being able to overwrite your /etc/password or apache.conf - horror.

If you need outside storage, you need to use operating system methods, like:

hard links
symbolic links
mount -o bind
junctions
and probably many other


How to dynamically pass contextual filter to a block view without changing view settings

You have a task:

  " I want site admins to be able to change the featured artist ( node id ) but I don't want them to have access to the views interface )"

and it seems you already decided to use specific solution:

  pass the the node id via the blocks interface

Don't do that. That's pretty weird and unneeded. Easier options are:

Draggable Views and show only first one
Use "sticky" or some other field to mark promoted artists (random order, limit 1 in case more than one is selected)


Change the FORMAT to Show: Fields and then add only your image field and configure its formatter to show what you need – original image or image style or URL to image ...


If you use Varnish - you must consider that for anonymous users PHP code will not execute at all - they will retrieve only static HTML.

In you case solution can be as following:

On welcome page set cookie by JavaScript not PHP.
Using Varnish vcl script check if user loads homepage and has cookie. If not - then redirect it to welcome page.

Now item #2 is made in PHP code but you need rewrite it using Varnish.
You can also write item #2 using JavaScript but it will work much slower and user will see browser redirection.


How to detect if field support multi values?

I believe the 'cardinality' is stored at the field (base) and not the field instance.  You should be able to use field_info_field to retrieve that information.


How to fill form fields based on other fields values using AJAX

I had the same issue and this workaround did the trick.
Basically you clear up $form_state['input'] value and rebuild the form.

Form builder:

<?php
$form['test'] = array(
  '#type' => 'textfield',
  '#title' => t('Test'),
  '#ajax' => array(
    'callback' => 'my_test_callback_func',
    'wrapper' => 'edit-test2',
    'progress' => array(
      'message' => '',
      'type' => 'throbber',
    ),
  ),
);

$form['test2'] = array(
  '#type' => 'textfield',
  '#prefix' => '
',
  '#suffix' => '
',
  '#title' => t('Test2'),
);
?>

Ajax callback function:
This is the trickier part.

<?php
function my_test_callback_func($form, &$form_state) {
  unset($form_state['input']['test2'], $form_state['values']['test2']);
  $form['test2']['#default_value'] = 'Auto Filled!';
  $form_state['input']['test2'] = 'Auto Filled!';
  return form_builder($form['#id'], $form['test2'], $form_state);
}
?>

We unset the user input (or check if it's empty), set a default value and then rebuild the form.


How do I render multiple form fields select boxes in a single row

In this, there is nothing to do with the coding part.
When we add a field it adds lot of wrapper div tags around it. And div tags has the by default property to take the next line in the page.

Just write some css for these divs.

<style>
    div.class1(display:inline-block;width:150px;float:left)
    div.class2(display:inline-block;width:150px;float:left)
    div.class3(display:inline-block;width:150px;float:left)
</style>

Hope it will work for you.


Is it possible to change the location and size of the blocks/tabs in Drupal?

I assume, you are referring to "regions" as  "block/tabs". If that is the case, you can add/change the regions in your theme_name.info file and page.tpl.php file.

You may find this Link useful.


Hide results of drupal view when filter value is empty after search

Edit your view and then set the "Exposed form style" to basic.

Hope that helps!


Overriding the output for the primary navigation links

That syntax (two underscores) means that it first looks for a theme_links__system_main_menu()theme function and then falls back to theme_links() if that doesn't exist.

So to override only the main menu, create the following theme function for your theme: yourtheme_links__system_main_menu().


The method I used to solve this was that in my Drupal site I had entity references at each level that connected me all the way down to my root. It was a simple process of using the functions such as node_load() to return information about the entity and its title, which I was then able to concatenate into a string of text like is in the example above: container_name]/[folder_name]/[presentation_name]
After that I was able to simply use this code to build the folder after each node was submitted:

//$path contained the remaining file path to be built
$dirpath=variable_get('file_public_path', conf_path() . '/files');
drupal_mkdir("$dirpath/$path");


what should I use as placeholder for a html img element?

It would probably be better to use the theme_image() function for that:

$image_html = theme('image', array(
  'path' => $img_src,
  'alt' => 'Some alt',
  // etc
));

If you're hell bent on using t() then you need to use it with the ! prefix, so the value is passed through without any checks/sanitisation:

$markup = t("<img src='!src' />", array('!src' => $img_src));

The docs for format_string() explains the different kinds of placeholders you can use, and which prefix you should use for each.


How to link 'no result behaviour' to node?

An easy way would be to set up a default image for the field. This setting is on the field settings page for the field on the node.

OR

You could to use tokens in the view. Add the path field to the view (set it to not visible), make sure it is higher than the image field. Then you should be able to add an anchor tag around your image tag and use the token value. eg.

OR

You could to use tokens in the view like this. Add the path field to the view (set it to not visible), make sure it is higher than the image field. Under the 'rewrite results' section, check 'Output this field as a link' and add the link path token there.


Textarea not populating with previous value

After disabling WYSIWYG the text area started populating again. More digging revealed the reason it wasn't populating as a rich text box was because when an editor is used it submits the value as an array with two items; value and format. Consequently, this meant that the text editor was being given an array to display rather than a string.

Altering the #default_value to $sidebar_content[$key]['value'] resolved this issue.


How to get all values from a new node being created in hook_ENTITY_TYPE_presave()

There are probably a few different ways to get that info, but if the returned format suits your needs then EntityInterface::toArray(), which Gets an array of all property values, is probably the most succinct:

$field_data = $entity->toArray();


You need to add an expression with SelectInterface::addExpression:

$query = $db->select('node_field_data', 'nfd')
  ->fields('nfd', ['title'])
  ->extend(\Drupal\Core\Database\Query\TableSortExtender::class)
  ->extend(\Drupal\Core\Database\Query\PagerSelectExtender::class);

$expr_alias = $query->addExpression('SUBSTRING(title, 13, 4)', 'num');

$query->orderBy($expr_alias, 'ASC')->limit('50');


Automatically generate a short description of a page when a user posts a link

Look at the source for that page, you'll see this

<meta name='description' content='In honor of Wolfenstein 3D&#039;s 20th anniversary, the game will be released for free to play in browser today.'/>

Should be fairly straightforward to grab that!


content.field_name does not render anything

content.<field_name> should work.
try adding {{ dump(content|keys) }} to your template, does it show anything?


How do I schedule a PHP function every 2 month?

You can easly do this without having access to crontab/shell, by using following code in your cron_hook:

// check if current day is 10th and month is an even number
if (date('d')==10 && date('m') % 2 == 0) {
    // get todays-date (format: yyyymmdd)
    $today = date('Ymd');
    // get info about last run
    $last_run = variable_get('my_last_run', 0);
    // check last run was not today
    if ($last_run!=$today) {
        // set last run to today
        variable_set('my_last_run', $today);

        /* Place your code here */

    }
}

For more info on the modulo-operator (the % ) check:
http://www.php.net/manual/en/internals2.opcodes.mod.php


Should separate Drupal installations have separate temporary directories?

They can all share the same folder if you want them to, but if you want to give each domain it's own tmp folder that's fine too...it really depends on how you want to set your server up.

Aside from being able to identify which tmp files have come from which site (which personally I've found no need to do up to this point in my life) I can't think of an argument either way to be honest.

Edit: Thinking about it a bit more, if you're running a shared host of any description it might make sense to provide a tmp folder for each domain so it's sandboxed from other sites, and from the main system tmp folder (and subsequently other parts of the system that don't relate to web).


How to validate 3 or more fields when creating content in D7

Create a module to add a validation handler to the form by implementing hook_form_alter():

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MY_FORM_ID') {
    $form['#validate'][] = '_MODULE_validate';
  }
}

Then define the handler function that checks the field values:

function _MODULE_validate($form, &$form_state) {
  // Check that the sum of the fields equals a predefined total
}

If you're not familiar with creating your own modules, but are comfortable with PHP, you could probably use the Field Validation module to add a custom PHP validator that does the same thing.


How to orderBy joined table after ordered main in db_select

Not sure I understand but you're not limited to a single orderby() in a SelectQuery so you would just add another one with the correct alias, e.g.

$query -> fields('w', array('entity_id', 'field_cg_w_value'))
  ->condition('w.field_cg_w_value', $options['string'] . '%', 'LIKE')
  ->orderBy('w.field_cg_w_value', 'ASC')
  ->orderBy('g.entity_id', 'DESC');


different form state redirects in a hook_form_alter

I think it should be like:

$form['#redirect'] = $base_url';

you are missing '#' in both of the forms.


You can use Views, which comes with a front page view you can modify to make it show only nodes for a specific language, and a view for taxonomy/term/%. For taxonomy terms, it is not so straight, as Drupal associates a language to nodes, but not taxonomy terms; it still is possible to show only the nodes associated with the selected taxonomy term, and which are written in a specific language.

If you install the development snapshot of Views (7.x-3.x-dev), some settings have been renamed; the one that you should change is "filter criteria."


I think there is a misunderstanding: The Views module is used to create pages, or blocks. In both the cases, the created view shows nodes, users, taxonomy terms, modules, etc matching some criteria set for the view.

A view is not a template for altering the content of other pages. For that there is the Panels module. (Emphasis is mine.)

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


How to write a db_query with condition on a datefield with enddate - value1 and value2

Fields are not stored in the node/entity table to which they relate, it would be quite inefficient to do that.

Drupal 7 introduced the new EntityFieldQuery class to help you build up these kinds of queries. I'd recommend reading the docs, but for your purposes the code would look something like this:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $type)
  ->propertyCondition('uid', $uid)
  ->fieldCondition('field_mytime', 'value', $daystart, '>')
  ->fieldCondition('field_mytime', 'value2', $dayend, '<');

$results = $query->execute();
if (isset($results['node'])) {
  // Load all node objects based on the results of the query
  $nids = array_keys($results['node']);
  $nodes = node_load_multiple($nids);
}


Flag- is there a way to allow users to only flag themselves?

Is there a way to use a node flag instead? Out of the box, there you can restrict it to a node type and also to content only owned by the user (or not).

So if you have the equivalent of a content profile set up in d7, you would be able to set it up so a flag was restricted to that type of content and only to the node owner, which might accomplish what you are after.


How to access services_views the correct way?

On a Drupal.org issue page for this module, someone suggests the following for the 7.x version.

The arguments are passed in the usual url format, for example:
http://example.com/my_endpoint/views/view_name?display_id=default&args=123&offset=0&limit=10&return_type=FALSE

Multiple arguments can be used like this:
http://example.com/my_endpoint/views/view_name?display_id=default&args[0]=abc&args[1]=123&offset=0&limit=10&return_type=FALSE

I've been trying to get this working on 6.x but haven't succeeded yet.


Here is the solution Menu Block. Install and configure it.

It works for me.


Creating a file object from a file already in public:// (drupal 7)

I think the easiest way would be to create a file object manually, populate it with the file details, and save it using file_save():

global $user;
$uri = 'public://path/to/file.txt';
$filename = 'file.txt';

$file = new stdClass;
$file->uid = $user->uid;
$file->filename = $filename;
$file->uri = $uri;
$file->filemime = 'text/plain';
$file->filesize = filesize($uri);
$file->status = 1;

file_save($file);

After you've done that you'll probably also want to use the file_usage_add() function to declare a vested interest in the file, so that it doesn't get deleted by any other system process:

$type = 'some_type'; // A string used by your module to identify this type of file entry
$id = 'some_id'; // An identifier used by your module to identify this particular file

file_usage_add($file, 'MYMODULE', $type, $id);


Error when using hook_form_comment_form_alter()

Turns out the correct way to add the placeholder was:

$form['comment_body'][LANGUAGE_NONE][0]['#attributes']['placeholder'] = t( 'comment' );


What is the proper way to create a custom user field programatically?

Q1: The field should be added in hook_enable() and removed in hook_disable() if you want the field to be removed and then added when you enable/disable the module. However I suggest implementing it in hook_install() and hook_uninstall as that will only remove the field and its data from the user entity when the module is uninstalled as oppose to simply disabled. hook_field_schema is not for these kinds of tasks as it's for defining a database table.

Q2: You'd have to hack your way through the field.module to make these database table name changes. This is really bad practice (VERY VERY) and plus I don't see the point of this, or never even heard anyone attempting this. The database tables are for Drupal and not for human eyes. As such they're in a consistent and systematic naming conventions so the field module as well as other modules that use them can easily extract data.


Drupal commerce get All product variation for list of product

If you could provide more information on version of Drupal and if you are using Commerce modules?

We have done this in the past using Commerce Fancy Attributes module to display colors for products : https://drupal.org/project/commerce_fancy_attributes

From module page:

Example usage:
0) Enable this module.

1) Create a Color vocabulary, add a text field called "Color" that will hold hex values.

Go to the "Manage Display" screen of that vocabulary, click the tab called "Add to Cart form - Attribute", enable only the color field (with the label hidden, and using the "Color" formatter).

2) Create several terms with matching hex colors (Black: #000000, White: #ffffff, etc).

3) Add a Color taxonomy_term_reference field to a product type.

4) When you add the color field on the product type, tick the checkbox "Enable this field to function as an attribute field on Add to Cart forms." and select "rendered term" as option of the "Attribute selection widget".

The Add To Cart form will now show the colors.
Of course, imagefields can be used instead of "textfields holding hex values" rendered as images.


What is correct destination for fid in destination image field?

So the final solution that worked for this is as follows:

field_image:
  plugin: iterator
  source: field_thumbnail
  process:
    target_id:
      plugin: migration
      migration: file
      source: fid
    alt: alt
    title: title
    height: height
    width: width

As explained to me by @mikeryan, the iterator plugin allows you to iterate over multiple values which have subfields, and map the subfields in the internal process pipeline the way fields are at the top level. In this case, I just used the migration plugin to get the target fid from the file migration, and this puts it in the field_image_target_id column in node__field_image table.


It does not work when installed as "subsite"

Look for this code in the .htaccess file in the root of the Drupal site's filesystem:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal

and remove the '#' from the beginning of the RewriteBase line. That should tell Apache/Drupal how to properly rewrite URLs for your case.


Drush command using chef causing error "Command needs a higher bootstrap level to run"

In your drush command you may need to specify the location of your Drupal files. Use --root=<path> argument.

https://github.com/drush-ops/drush#options


The easiest (though probably not the best), is to do something like:

// http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_permission/7

function mymodule_permission ()
{
    return array(
        "view mypage" => array(
            "title" => t("View My Page"),
            "description" => t("View My Page"),
        ),
    );
}

// http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/7

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

    $items["mymodule_mypage"] = array(
        "title" => "My Page",
        "page callback" => "_mymodule_generate",
        "access arguments" => array("view mypage"),
        "type" => MENU_CALLBACK,
    );

    return $items;
}

function _mymodule_generate ()
{
    $path = drupal_get_path('module', 'mymodule');

    drupal_add_css("{$path}/mymodule.css", array(
        "type" => "file",
    ));

    $xsl = new DOMDocument();
    $xsl->load("{$path}/mymodule.xsl");

    $xslt = new XSLTProcessor();
    $xslt->importStyleSheet($xsl);

    $xml = new DOMDocument();
    $xml->load("{$path}/mymodule.xml");

    return (string) $xslt->transformToXML($xml);
}

This is stripped down code I have taken from a custom module I have for displaying a resume maintained in XML format.


How can i add edit profile link dynamically?

You can use the link directly as /user. It goes to the profile page which is similar to the /user/{$GLOBALS['user']->uid}

OR

Use Token module  to create a menu link with this path: user/[current-user:uid]/edit.


How to get field mapping information in custom module?

Looks one potential solution is to use is EntityFieldManager::getFieldMap. See the change log for this change.

Also, FYI:

  When working directly with an $entity, the field definitions (which include base and configurable fields) can be directly requested from the object with $entity->getFieldDefinitions() or $entity->getFieldDefinition($field_name)


Are you using 6 or 7? In 6 you'll need to add an Argument; in 7 a contextual filter. Either way, it works pretty much the same.

Create a block display.
Add the fields you want (usually just the title for a simple list.)
Add either an argument or contextual filter for the author uid.

Then under "Action to take if argument is not present", choose provide default value. For the default value, choose PHP Code, and add this code to the box:

if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $uid = $node->uid;
}
return $uid;

Save your view; then clear all caches.

Note that the use of contextual filters renders the preview unusable; you'll need to actually add your block to a page to see it.


Drupal 8 Forms/Webforms Ajax Callback Elements

You can't add elements in an ajax callback:

  Note, that as part of the Form APIs security system, you cannot
  create new form elements in the callback function, as they will throw
  errors upon submission, and any #ajax on elements created in the
  callback will also not work. If you need to create new elements on
  ajax submit, they must be added in the form definition.

from https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7 (still valid for D8).

It should be possible to find a method in the composite element which is part of the form building process where you can add the form element.


Optional extra products on add to cart form

There is for example Commerce add to cart extras:

  This module provides alternative ways of adding products to cart.

  The initial version provides a views field handler ("Commerce Product:
  Quantity input field") that relies on the Views Form API (a part of
  Views 3 since RC1) to output a quantity textfield that turns the view
  into an add to cart form. The default quantity can be configured, and
  only products with a quantity larger than 0 are added to the cart.

Also, you can find 2 approaches (VBO + Rules, and custom VBO action) at Add multiple products to cart with VBO.


Block a single basic page from authenticated users

If you don't mind hard coding the node ID you could do this fairly easily in a custom module using hook_node_access():

function MYMODULE_node_access($node, $op, $account) {
  if ($node->nid == $node_id && $op == 'view' && $account->uid > 0) {
    return NODE_ACCESS_DENY;
  }
  return NODE_ACCESS_IGNORE;
}


How can I require a custom module hosted elsewhere with its contrib dependencies being downloaded too?

Just for this question I created a dummy module at https://github.com/leymannx/custom_module which has a composer.json similar to yours with drupal/restui in the "require" section and "type": "drupal-custom-module".
And then in a D8 project's composer.json I adjusted the "repositories" section to look like this:
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
        "type": "github",
        "url":  "https://github.com/leymannx/custom_module"
    }
],

In the "installer-paths" section I added:
 "web/modules/custom/{$name}": ["type:drupal-custom-module"]

I then simply ran composer require leymannx/custom_module and it downloaded the module and drupal/restui both to the right places. Of course you now can ignore the custom module with your repo's .gitignore file.
I guess the trick was to have the "repositories" section adjusted like above. And I guess you also can use proper versioning for the custom module when you tagged some releases. Right now it just downloads dev-main.


How to install a specific version of a project with drush

To download a specific version of a project, specify the 'project name', followed by a dash, then the version name. The -y argument answers "yes" to any and all prompts.

The exact 'project name' for a module, is what is included in the URL of the module on D.O., i.e. everything following the last '/' in the URL. So for the Organic Groups module, that would be og, because its URL is https://www.drupal.org/project/og.

As an example, consider something like this:

drush dl og-7.x-1.3

With this command, you download the Organic groups module (replace it with your "module_name"), and more specifically the 7.x-1.3 version of it (replace it with the "version" you want).

You can also specify a development version of a module, as in this exmple (which would download the current 7.x-2.x-dev version of Organic Groups):

drush dl og-7.x-2.x

For many more details, samples, etc, refer to http://www.drushcommands.com/drush-6x/pm/pm-download and/or http://www.drushcommands.com/drush-7x/pm/pm-download.
Or to Installing a specific version of a project with drush.

After you downloaded the specific version, you "enable" the module as per the normal Drupal procedures to do so.

If you want to also enable the module using Drush, then there is no more need to specify the version of the module. To continue the above example, to enable the 7.x-1.3 version of it (after you down;oaded it), use a command like so:

drush en og


This module can do the same: Guidance

For controlling first time, you can use Rules module.


How to create a "pay per node" "pay to publish" type flow in Commerce 2?

You need to create an order and an order item yourself and then add those values, I assume you need to do this from the context of your node anyway and not use a standard "buy this product" form.

A snippet from a project:

$order_item_values = [
  'type' => 'order_item_type',
  'title' => 'label',
  'unit_price' => new Price(...),
  ...
];
$order_item = $this->entityTypeManager()->getStorage('commerce_order_item')->create($order_item_values);
$order_item->save();

$order_type = $this->orderTypeResolver->resolve($order_item);

$stores = $this->entityTypeManager()->getStorage('commerce_store')->loadMultiple();
$store = reset($stores);

// Create the new order.
/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $this->entityTypeManager()->getStorage('commerce_order')->create([
  'type' => $order_type,
  'store_id' => $store->id(),
  'uid' => $this->currentUser()->id(),
  'cart' => FALSE,
]);

$order->addItem($order_item);
$order->save();

$this->cartSession->addCartId($order->id(), CartSessionInterface::COMPLETED);

return $this->redirect('commerce_checkout.form', ['commerce_order' => $order->id()]);

You don't even need to use products, you can define an order item that just has a price and reference to your node. But you can also use products to define e.g. the length/price.


How to dynamically create a view, and then export to PDF

I was able to get the output that I needed by using the Reference module and the Viewfield module.

Created Content type A and content types B, C, and D. B, C, and D are all associated with Content type A via Reference fields.
Created contextual/relationshipped views for B, C, and D, relating it to the title field of Content Type A.
Created a Viewfield on Content Type A for each of the sub-content types (B, C, and D).
Created a View for Content Type A, contextualized with Content:Title, and added the Viewfields to this new View (using reverse relationships with the node referenced field). I then added a PDF Page view using Views PDF, and that did the trick!

I can provide more detail if needed. Just let me know...


Extending the Year range in Popup Calendar

Step 1 :
   Edit the file date_year_range.js located in this path : sites\all\modules\date\date_api\
Step 2 :
   Locate this line : Line 67 start = Math.min(this.getOriginal('int'), -n) n is the number you specified in your Drupal
Step 3 :
   Replace n with the value you want, for example for the field date of birth i want 60 years besfore today
Step 4 :
   Go back to your web site, edit the content type, then manage fields and change more settings and values of your date field.


How do I create content links to a group node without using panels?

Answering my own question.

Seems I needs to use install OG Extras -  https://www.drupal.org/project/og_extras


If you want to select an entity, then there is a way easier way to do that. Drupal 8 has a standard entity_autocomplete field type, just specify your form element like this:

$form['node'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
];

See Custom autocomplete field for more information.

Also, never do database queries against node/entity tables. Use \Drupal::entityQuery() for that.


How to send a message to users who flagged a taxonomy term?

I would create this using a Custom PHP code in Rules and execute the following conditional code on 'After saving new content of type...' event trigger :

if( count(taxonomy_get_term_by_name('[node:field-tags]')) ) return TRUE;
else return FALSE;

Then create an 'action to send an email'.

Requires -PHP Filter,-Rules.
-Here the content type assumes the default 'Article' with default Tags field 'field_tags'

{ "rules_tst" : {
"LABEL" : "Test Rule",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "php" ],
"ON" : { "node_insert--article" : { "bundle" : "article" } },
"IF" : [
  { "php_eval" : { "code" : "if( count(taxonomy_get_term_by_name(\u0027[node:field-tags]\u0027)) ) return TRUE; \r\nelse return FALSE;  " } }
],
"DO" : [
  { "mail" : {
      "to" : "me@mine.com",
      "subject" : "test subject Toys confirmed!",
      "message" : "There are toys to play with!",
      "language" : [ "" ]
    }
  }
]

}
}

I ahve included an importable for you to test.


How to force regions to render in Overlay

I eventually found the code that does this in overlay.module and applied this to a custom module, using the hook:

function mymodule_system_info_alter(&$info, $file, $type) {
  if ($type == 'theme') {
    $info['overlay_regions'][] = 'header';
    $info['overlay_regions'][] = 'footer';
  }
}

However getting this to take effect required visiting the modules page, I don't believe simply clearing the cache worked.


Drupal 7 trim user input and other checks to prevent security issues

I recommend reading this article :
https://www.drupal.org/writing-secure-code
Really a lot of good tips


Which ever role you want to allow to login give the role the permission.

Drupal 6

Please change the permission to an appropriate one. This is just for test purpose.

function modulename_perm() {
  return array('allow modulename login');
}

function modulename_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'login') {
    if (user_access('allow modulename login') == FALSE) {
      drupal_set_message('Member logins have been temporarily disabled. Please try again later.', 'warning');
      user_logout();
      exit;
    }
  }
}

DRUPAL 7

function modulename_permission() {
  return array(
    'allow modulename login' => array(
      'title' => t('allow modulename login'),
      'description' => t('allow modulename login.'),
    ),
  );
}
function modulename_user_login(&$edit, $account) {
 if (user_access('allow modulename login') == FALSE) {
      drupal_set_message('Member logins have been temporarily disabled. Please try again later.', 'warning');
      user_logout();
      exit;
 }
}


How to display node add answer form on a question page using the Answers module?

The most recent version of the Answers module (= 7.x-4.0-rc2) already comes, out-of-the-box, with a "answer node add form on the question page" (as in your question). So you don't need any other modules, such as Advanced form block (it all happens automagically).

To experience it yourself, try out a demo of it. Here are the steps to do so:

Head over to the demo site.
Just accept the defaults to create a sandbox demo site (hit the create sandbox button, and wait for the process to complete).
Login to the site (using the suggested defaults).
Create at least 1 question using either the "Add content" menu link and then selecting "Question", or just enter relative path /node/add/question. And complete the title and body of the question.
After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
Use the Questions tab (or enter relative path /questions, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

Note: you may also want to enable the Answers Theme (sub-module of Answers, new as of 7.x-4.x). After you do, return to the question you created before, and see how the look-and-feel of both the question and related answer(s) below it changed ... Here is a sample screenprint of it:


Membership contribution with profile required 'on behalf of' prefilled

The behaviour that you are expecting to see will work - at least it does for me - when the relationship between the individual and the organisation is "Employee of". Other relationship types appear not to work. Perhaps you are using a different relationship type?


Menu Block disappear when changed the access control permission

Drupal will show / remove pages from the menu depending on whether or not a specific role has access to it. If you want to show the page in the menu but not the content to a specific role such as anonymous there are a couple of different routes you can go.

There is a module called field permissions which would allow you to set the page itself to be visible by everyone but you could hide specific fields from visitors. From drupal.org

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

You could also achieve something similar if you were to use the panels module. You could set visibility based on role, thus hiding sections of content but still having your menu items visible.


Checking for changed fields - Identifying an empty array & Field Type

Thanks, I've got it!

// Check the number of values for each field, or if they are populated at all.
$old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
$new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

If (empty($new_field[LANGUAGE_NONE][0]['value'] && ($field_info[type] == 'text' || $field_info[type] == 'text_long')) {
    $new_field_count = 0;
}

if ($old_field_count != $new_field_count) {
  // The two versions have a different number of values. Something has changed.
  $fields_changed[] = $field_name;
}


What is the machine name for the Date Posted?

If you are talking about the 'ID' of the Content: Post date in Views, it is: created

You can find this under the Theme: Information link under the 'Advanced' settings block (in D7/Views 3) or the 'Basic settings' block (in D6/Views 2).  After clicking that link, find the name of the field and find the ID in parenthesis next to the field name.

Example: In this case you should find Field Content: Post date (ID: created)


Rules: Do action on the field of referenced node

If your rule is set to React on event: Before saving content or After saving new content of type Article, then do this:

Add condition: Entity has field

ENTITY: node:field-your_reference_field

FIELD: field_email

This makes the referenced node's email field available in to Actions. So then you can

Add action: Send email

To: node:field-your_reference_field:field_email

This should get you where you need to be.


How to access an element's value in field validation function

Get a value using $form_state like as follow

$form_state['values']['field_myfield'];


What steps are necessary to build secure database queries from user input?

It depends what you mean by "secure." If your goal is just to block sql injection then yes, that's it :) For Drupal 6, be sure you are using the right placeholder based on db_query docs:

  Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose in
  '') and %%.

And be sure that you enclose the %s placeholder in ''. Failure to match these properly can lead to sql injection.

Drupal 7 takes care of that for you. Even if you use the Drupal 7 db_query you use placeholders like :name and it will figure out the data type and take care of proper filtering/substitution/quoting for you.

The other security related topic for queries is the node access system. In Drupal 6 you should use db_rewrite_sql. In Drupal 7 be sure to use $query->addTag('node_access'); if you are querying for nodes.

This system of preventing SQL Injection as part of the API is, in my opinion, one of the great features of Drupal. Similar functions that perform both functional and security features are the t() and l() function which will prevent XSS when they are used properly.


clearing cache might help:

truncate table cache;


In drush status you should have the following lines right after Database credentials:

Database                        :  Connected
Drupal bootstrap                :  Successful

When you don't have it, this suggest your Drupal instance is not properly configured and drush has problem bootstrapping it. For example, you may check if you can connect to the database, try: drush @mysite sqlc.

When executing dd on a remote machine, Drupal needs to be able to bootstrap on the configuration level, so it can read the variables. When you don't have the proper access, you'll have the error like:

  Target 'root' not found.

See also: drush_core_drupal_directory().

Other suggestions:

Make sure that on your local and remote you have got the same version of drush.
Other problems could include issues with specific PHP version (see: #779).
If you've still problems, run drush with verbose (-v) or debug options (-d).


Override Views Contextual Filter in View Exposed Form Validation

Contextual filters work with arguments from the url so for example {drupal site}/search-nid/% where search-nid is the url of your page  and % is the value you wish to submit to the contextual filter.

An exposed filter tends to take it's values from the query string E.G.
{drupal site}/search-nid?field_nid=% (Again search-nid is the page url and % is the value of the nid)

If you are trying to do what I think you are, (Filter results to a specific nid using a URL to "autofill" the filter) I did this in a hook_form_submit function and not a hook_form_validate function.  The function below assumes your module is mymodule and your form id is advancedsearch_form.  The function looked as follows:

<?php
/**
 * Implements hook_form_submit()
 * Takes values from submitted form and appends them to query string
 * uses @see drupal_goto for info one $form_state['#redirect']
 */
function mymodule_advancedsearch_form_submit($form, &$form_state) {
  $qsa = array(); //for QSA arguments

  $field_nid = $form_state['values']['field_nid'];
  $qsa['field-nid'] = $field_nid;

  $form_state['redirect'] = array(
    'search-nid',
    array(
      'query' => $qsa,
    ),
    302,
  );
}

This may not be best practise (In fact I'm sure it isn't as it was a quick hack I implemented in about 5 mins!) but I hope it does answer your question.


Search api & solr search => no results found

There is a 'solr-devel' module to help http://drupal.org/project/solr_devel.

Make sure that the query works directly in the solr native search page. Isolate the drupal side this way.

Make sure that you have updated schema.xml and solrconfig.xml with the ones that come with the module as per the module README.txt. Reindex.

  Move apache-solr-1.4.1/example/solr/conf/schema.xml and rename it to
  something like schema.bak. Then move the solr-conf/solr-1.4/schema.xml
  that comes with this Drupal module to take its place.

  Similarly, move apache-solr-1.4.1/example/solr/conf/solrconfig.xml and
  rename it like solrconfig.bak. Then move the
  solr-conf/solr-1.4/solrconfig.xml that comes with this module to take
  its place.


Trying to create a view of a node that contains the titles of nodes that reference it

Have you tried the Entity Views Attachment module? Sounds like this is a perfect example for this module...


You may try next code snippet

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
*/
end($rows);
$last = key($rows);
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id == $last): ?>
    <?php $classes_array[$id] .= ' last-element'; ?>
<?php endif; ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>


Content type with buttons such as "I'm going here" and "I have been here"

I would take a look at the Flag module for this.  We have used this module for similar purposes with good results.

You should be able to set up “I'm going here” and “I have been here” as different "flags", and then enable these flags on the content types you need.  This particular module integrates nicely with Views, Actions, and other Drupal mechanisms.


Render first element of a multivalued field

Then it's

{{ content.field_name[0] }}

  Note: If you need to print the label use {{ content.field_name['#title'] }} as {{ content.field_name[0] }} does
  not print the label.


The PHP version is not correctly detected

Drush doesn't use just php directly as a command, but need the full path. With the last version of Drush, you can add the following line in your .bash_profile to set which PHP you want to use.

export DRUSH_PHP=/Applications/MAMP/bin/php/php5.3.14/bin/php

Here is just an example of MAMP, but you can change it as well with your own path.


I'll suggest the most easy thing to do: Create a menu item and in that menu item you'll create the membership by your self. Don't know why this happening to you but the solution i suggest might be quicker.


Using devels dpm function i managed to find the correct name of the setting, so the following now works...

$vocab = '[vocabulary:machine-name]';

$field = array(
  'field_name' => 'field_termref_' . $vocab,
  'type' => 'taxonomy_term_reference',
  'cardinality' => -1,
  'settings' => array(
    'allowed_values' => array(
      array(
        'vocabulary' => $vocab,
        'parent' => 0
      ),
    ),
  ),
);
field_create_field($field);

$instance = array(
    'field_name' => 'field_termref_' . $vocab,
    'entity_type' => 'node',
    'label' => '[vocabulary:name]',
    'bundle' => 'product',
    'required' => false,
    'widget' => array(
        'type' => 'options_select',
        'settings' => array(
           'apply_chosen' => 1
        )
    ),
    'display' => array(
        'default' => array('type' => 'hidden'),
        'teaser' => array('type' => 'hidden')
    )
);


Even though I uninstalled the module, I kept being banned. To remove the ban for a particular IP, I followed the following steps:

Connected to the database
Changed the access table; either  changing the status to 1 or deleting the row with  mask equal to '127.0.0.1' and type equal to 'host' works

I found the solution on Sorry, 127.0.0.1 has been banned.


Programmatically render menu on search view

I worked it out, turns out the problem is different to what I thought.

Because the search view isn't in the menu structure I need to add different values to the $config array. Firstly I needed to add "parent_mid" so it knew what menu item to use as the root for the menu tree & I needed to change the level to 1 to output the links I wanted. Although 2 was still outputting links, just the wrong ones for what I needed.

If you need to work out what the parent_mid is go to Admin > Structure > Menus > Your Menu & hover over the edit link for the menu item you want to be the root of the menu tree, the ID is in the URL. You can also get it programatically, like I did, using menu_node_get_links().


How to create a menu from content type fields found on a node?

You could build this with the Field Group (https://drupal.org/project/field_group) module, which will allow you to group your content fields into horizontal tabs, vertical tabs, accordions and more. By default, groups with only empty fields will be hidden, i.e., they will not display in the "menu".

While this would not create separate pages, your use of the word in quotes makes me think this would be an acceptable answer.

There is a decent tutorial at https://www.youtube.com/watch?v=5GU_tb4K-f4.


you need to "rel" tag in link.

My Account

If you want show a specific region then use this.

 *" rel="lightmodal[|width:700px;height:300px;]">Click to see only the content inside #content-inner

Detailed tutorial can be found here


Understanding the 'node' string in a Views SQL Query

The 'node' string is a placeholder of sorts.

Internally, it indicates to Views that we are not going to attempt to fetch the requested field value in this SQL query itself. Instead, during the Views render process, the full node object is going to be loaded, and the output for that Views field is going to come from partially rendering the node object.

This allows Views to take full advantage of Drupal's field formatting system, which would be impossible on raw SQL values.


Possible to group views by date field larger than current date?

I used this module to accomplish this http://drupal.org/project/views_customfield. It allows you to define a new views field using custom php code


I was surprised that I couldn't find a contrib module that does this out of the box so I created a simple one.

Here it is on Github too:
https://github.com/balsama/bookoblock (bookoblock = "Book Outline Block")

Info file (bookoblock.info):

name = Book Outline Block
description = "Provides a block containing an outline of the current book."
package = Other
core = 7.x
dependencies[] = book

Module File (bookoblock.module):

<?php
/**
 * Define the Book Outline Block/
 * Implementation of hook_block_info()
 */
function bookoblock_block_info() {
  $block['book_outline'] = array (
    'info' => 'Book Outline',
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  return $block;
}

/**
 * Define the contents and title of the block/
 * Implementation of hook_block_view()
 *
 * Returns a renderable block array containing the current book's outline if
 * the node is part of a book.
 *
 * Returns NULL if the current menu item is not part of a book heirarchy.
 */
function bookoblock_block_view() {
  if ($book = bookoblock_is_book_node()) {
    $tree = menu_tree_all_data(book_menu_name($book['bid']));

    // If we pass 1 as the second param, we just get the top level node in the
    // book. Since the key will be the top level mlid, we'll have to use
    // ['p1'] in the $book array (which contains the top mlid) when we use it
    // for the block title.
    $book_name = (book_toc($book['bid'], 1));

    // Build the block title and contents
    $block['subject'] = $book_name[$book['p1']];
    $block['content'] = menu_tree_output($tree);

    // Return the block
    return $block;
  }
  // If the current node isn't part of a book, just return nothing.
  return NULL;
}

/**
 * Checks to see if current node is part of a book.
 * Returns book array if it is part of a book, FALSE is not.
 */
function bookoblock_is_book_node() {
  if ((arg(0) == 'node') && (is_numeric(arg(1)))) {
    $node = menu_get_object();
    if (isset($node->book)) {
      return $node->book;
    }
  }
  return FALSE;
}

Just drop those two files into a folder named bookoblock inside your modules directory and enable the module. You'll now see a new block in the block admin page named Book Outline. That block will only appear on node pages where the node is part of a book. It contains a heierarchical menu of the entire book and it's title is the root node's title.


Specifying a confirmation page after you signup using the Signup Module

If this is a form then use hook_form_alter to add a submit handler with it and then define $form['redirect']. For illustration see the post


Drush make: simplexml_load_file(): I/O warning : failed to load external entity "" Project.php:74

This workaround fixed my issue:

In drush.inc

if ($use_wget) {
  drush_shell_exec("wget --no-check-certificate -q --timeout=30 -O %s %s", $destination_tmp, $url);
} else {
  drush_shell_exec("curl --insecure --tlsv1 --fail -s -L --connect-timeout 30 -o %s %s", $destination_tmp, $url);
}

so weird anyway...


How do I retain user input in a form after submission?

Try adding $form_state->setRebuild(TRUE); to your submitForm().  Quoting from here:

  Normally, after the entire form processing is completed and submit handlers have run, a form is considered to be done and \Drupal\Core\Form\FormSubmitterInterface::redirectForm() will redirect the user to a new page using a GET request (so a browser refresh does not re-submit the form). However, if 'rebuild' has been set to TRUE, then a new copy of the form is immediately built and sent to the browser, instead of a redirect.

I think that as you have stubbed a submit handler, but not implemented anything (and so are presumably not calling parent::submitForm either), it is not considered "done", so it is not redirecting; but it is not rebuilding based on the new $form_state either, because you haven't told it to.  So you end up just seeing the original form.

As well as setting rebuild to true you may also need to $form_state->disableRedirect(TRUE) to get the desired behaviour of staying on the form, but with inputted values showing.


Relation adding not working in Drupal 7.9

There is a known incompatibility with CTools rc1; use the development snapshot, and it will work.


You should look at the workflow module. This one is used to create additional work flows and status in your content authoring.


What is wrong with this code returning error

PHP can define a string with ' or ". Whichever one you choose, you can't have those characters in the string without escaping them: echo "need to escape any \" in this string"

You can use this instead to avoid PHP strings altogether:

<?php if ($is_front): ?>
<META NAME="KEYWORDS" CONTENT="Geek community,stuffs for geeks,geek contents,tech updates,electronics stuffs,tech geeks">
<META NAME="DESCRIPTION" CONTENT="Get articles related to Drupal,wordpress,design tips,Electronics,Web designing,Linux and Programming.Join our Tech community where you can share and get answers for your queries.">
<?php endif; ?>


How do I hide an area in a template or layout if multiple regions have no content?

Your solution will work, but I think the best practice will be to make this check by preprocess 'theme_preprocess_page' and pass the result ( e.g. 'isRegionsEmpty') to the template. Then, in the template you only check one variable.


Change input value on click when there is more than one paragraph

I need to loop through the paragraphs with an .each() like so:

/**
 * @file
 * Javascript behaviors.
 */

(function ($, Drupal) {

  "use strict";

  /**
   * Handle paragraph fields on the node edit form.
   */
  Drupal.behaviors.myBehavior = {

    attach: function (context) {
      $("input[name$='[subform][field_my_number_integer_field][0][value]']").each(function (i) {

        $('input[name="field_my_content_paragraph_field[' + i + '][subform][field_my_number_integer_field][0][value]"]', context).on('click', function () {

          var myNumberFieldValue = $('input[name="field_my_content_paragraph_field[' + i + '][subform][field_my_number_integer_field][0][value]"]').val();
          var myInputTextFieldValue = $('input[name="field_my_content_paragraph_field[' + i + '][subform][field_my_input_text_field][0][value]"]');

          switch (myNumberFieldValue) {
            case '1':
              myInputTextFieldValue.val('A');
              break;
            case '2':
              myInputTextFieldValue.val('B');
              break;
            case '3':
              myInputTextFieldValue.val('C');
              break;
          }
        });
      });
    }
  };

})(jQuery, Drupal);

Which solves the problem.


Is it possible to bypass form validation, but still save form data?

The solution dawned on me this morning; to get this functionality in place I need to work backwards: rather than having Drupal validate the required fields and conditionally disabling the validation, we should remove the validation requirements from the form, and conditionally add them (doing custom validation, if need be).

So, the #required parameter is set to FALSE for all fields, and a custom validation handler conditionally checks the 'required functionality.'


You can try importing the translation file again; it is possible that the connection timed out and that some of the translations were not inserted.

However, if you check the .po file and you can't find the translations of those strings - it means that whoever was translating the terms did not finish them all.

You can translate missing terms yourself within Drupal at admin/config/regional/translate/translate or download Poedit and contribute translations back here.


select paged nodes by using selectNode of drupal 7 service module?

(post)

The url link should be

http://domainABC.com/my_services/taxonomy_term/selectNodes?page=1

parameter:

tid=1

problem fixed.


Custom theming: How to list multiple content types in the same page and use regions too

In block layout the visibility for content types works only, if the content type is a route match. That means, you have requested a node with that specific content type through the url.

It does not work for nodes that are displayed as result of a view.

To configure the visibility for a view you can define in the tab "Pages" the url of the view or a pattern of urls, that matches multiple views.


How to add cancel button while clicking the Edit link in View?

You can make use of the Content type extras module

label on manage field forms Add a 'Cancel' button to node edit forms
Ability to set node title visibility when viewing node Ability to
hide title of front page (takes precedence over content type setting)
Ability to add form submission buttons to top of 'Manage fields'

Or you could use the more buttons module

  MB provides a additional Create new action.

  This action can used as tab in addition to the node View or node Edit
  tab. This action can used as action link on the node edit forms.

MB allows to use own values for:

  Cancel button,
  Save and continue button, Save and create new button
  Create new tab


When I try to browse to a site I get the localhost default page (WampServer)

Do you have properly configured /sites/defaults/settings.php? Looks like somthing in your connection is wrong, it can be database name, username or/and password.


page not found after migrating drupal 7 to dev version same server using drush archive-restore

A couple of questions:

Are you creating that dev site as a root subfolder of the production site?
If yes, do you get a page not found on the production site OR on the server?

This might be an issue with .htaccess; if you just added dev site to the root of your production website, you might need to add a rule to exclude "/dev".

I think adding this before rewrite conditions for the production site would work:

RewriteRule ^(dev).* - [NC,L]


For sure this is related to permission:

A few pointers to help you debug:

Please check the permission of the components components you are trying to display through views. For example, a field is related to displaying an uploaded video. Anonymous users might ot be having permission to view it, though have the permission to view, but still they will not be able to access the stuff. So try to figure out what modules are responsible for the field you display through view, and then check the permissions coming from that module.

Actually this will be the only one that looks most probable to me. hope this helps.


Field Collection Value field is not deleting correctly(using programmatically)

You need to unset the field from node first!

unset($node->field_accommodation['und'][$j]);


Change 'Log in', 'Log out', 'My account' menu text

I needed to do the same but for a lot of items so working with the menu--account.html.twig was more confortable for me.

You can pick up string variable by using getUntranslatedString() method :

{% if item.title.getUntranslatedString() == 'Log in' %}
  <li{{ item.attributes.addClass(item_classes) }}>
  {{ link("new login text", item.url) }}

And if you want to do it for multiple strings :

{% if item.title.getUntranslatedString() == 'Log in' %}
 <li{{ item.attributes.addClass(item_classes) }}>
 {{ link('New login text', item.url) }}
{% elseif item.title.getUntranslatedString() == 'My account' %}
 <li{{ item.attributes.addClass(item_classes) }}>
 {{ link('new my account' text, item.url) }}
{% elseif item.title.getUntranslatedString() == 'Log out' %}
 <li{{ item.attributes.addClass(item_classes) }}>
 {{ link('new log out' text, item.url) }}
{% else %} {# when there is no match with the previous conditions #}
  <li{{ item.attributes.addClass(item_classes) }}>
  {{ link(item.title, item.url) }}
{% endif %}

Be sure to put your conditions before the trailing </li>


So Zen uses zen grids for its grid (in some cases) and that has a requirement for compass/css2/images. if you aren't using zen grids, you can disable that dependency.

Another option could be that you can try to delete/rename the config.rb file entirely, as CodeKit may see that and automatically assume you want to use compass to compile your Sass.

A third possibility could be that in the bottom of _init.scss (STARTERKIT/sass/) it pulls in zen, along with alot of other compass extensions. try disabling zen along with the others you already disabled.


Display image fields of a node as slideshow

Views Slideshow should be more than enough for what you need.

EDIT

I meant View field, not Views Field View - sorry.

  Viewfield provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.


As mentioned in the comments, this is not supported yet but it might at some point: https://www.drupal.org/project/drupal/issues/1671190

What you can do is return false in the onclick event. For example:

$form[button] = array(
  '#type' => 'button',
  '#name' => 'button',
  '#value' => "Do some JS",
  "#attributes" => array(
    "onclick" => "doJs(); return false;",
  ),
);