How to use hook_form_BASE_FORM_ID_alter() to save variable? I am attempting to use hook_form_BASE_FORM_ID_alter() to 1) add a field to the node edit form, which then is 2) turned into a token, and 3) used in Rules. This question is only about the first part of this process.

The following code is in place. It creates a field, but nothing is getting saved to the variable in question, additional_email, after the node edit form is submitted. I know I'm doing something very wrong here, but I don't know what.

How can I save the variable entered by the user to be accessed by a different function in my module?

Edit Form Code

function MYMODULE_form_node_form_alter(&$form, $form_state) {
   $email_default = 'john@example.com';
   $form['additional_email'] = array(
      '#title' => t('Additional E-mail'),
      '#type' => 'textfield',
      '#default' => variable_get('additional_email', $email_default),
      '#description' => t('If you would like to notify an additional person, please supply the e-mail address.'),
   );

   $form['options']['additional_email'] = $form['additional_email'];
   $form['options']['additional_email']['#title'] = t('Additional Notification');

   $form['#submit'][] = 'MYMODULE_submit';
}

function MYMODULE_submit($form, $form_state) {
   if (isset($form_state['values']['additional_email'])) {
      variable_set('myvariable', $form_state['values']['additional_email']);
   }
 }

Token Creation Code

 function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
    ...
    $notify_email = variable_get('additional_email', '0');
    $concat_array = implode(' ',$notify_email);
    $section_users['add_email'] = $concat_array;
    ...
  }

Update: I added a submit handler, shown above (and clarified the variable I accidentally omitted when copying the code). Unfortunately, I'm still getting the old garbled array that was somehow saved in there previously.

The code which assigns the variable's value to the token is above, in case that's the problem.

return system_settings_form($form); will do nothing in this context. An alter function like this has no return.

What you should do if you want to save the value is add a submit handler into the form instead:

function MYMODULE_form_node_form_alter(&$form, $form_state) {
   $form['additional_email'] = array(
      '#title' => t('Additional E-mail'),
      '#type' => 'textfield',
      '#default' => variable_get('additional_email', $email_default),
      '#description' => t('If you would like to notify an additional person, please supply the e-mail address.'),
   );

   $form['options']['additional_email'] = $form['additional_email'];
   $form['options']['additional_email']['#title'] = t('Additional Notification');

   $form['submit'][] = 'mymodule_submit';
}

function mymodule_submit($form, $form_state) {
  if (isset($form_state['values']['additional_email'])) {
    variable_set('additional_email', $form_state['values']['additional_email']);
  }
}

This adds a new submit handler to the form, which will trigger upon submit. If a value was supplied, it will set the variable.

What is $email_default? That is never defined.

However I would suggest a different approach, because:

Variable can only hold one value, and this form item exists on every node. Every submission with a value will override the previous.
Rules can read fields, why not add an email field on the node, and use that in the Rule
You should do extra validation on the entered value to make sure it is a legit email value and not just any string with valid_email_address
You can default the email field to be the $email_default you are checking for
You could add cardinality for the email field and adjust the Rule if multiple people need to be notified

If you didn't use a custom form field, and instead added a real field on the node, you could ensure that any node can have any email address without relying on variable_set which as stated, will only ever allow one value to exist.

Rules is able to inspect your node and fetch a field value from it in order to use as a data variable in a later action, in this case, to send an email. If you do that, you don't really need any code at all.


How to display URL in status message? I want to customize the status message after creating a content to include the current URL.

From

  @type %title has been updated.

to

  @type %title has been updated. Your permalink is (URL)

I'm running Drupal 7 using the String Overrides module.

You will need to create the message yourself, since the url is not available as a parameter in the string, like the type and title is via @type and %title.

To do this, you can add a custom submit function with hook_form_alter and delete the message created by the node module. This would look like this:

module_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'node_form') !== FALSE) {
    $form['#submit'][] 'my_custom_submit_handler';
  }
}

function my_custom_submit_handler(&$form, &$form_state) {
  // Unset previous set messages.
  drupal_get_messages('status');
  drupal_set_message(t('Your custom string', array('@with' => 'params')));
}


How to add weight to the total weight of the order witn Commerce Shipping with rules? I want to add a constant weight to the total weight of the orders in my shopping cart to account for packing materials in the weight calculation.

I'm also using Commerce Shipping Postal Code Code Weight. The Postal code weights work brilliantly.Shipping Postal Code Weights

What I want to do is add a 6oz to the total weight of my order.

You should implement this hook in a custom module:

/**
 * Allows modules to alter the weight that has been determined for an order.
 *
 * @param &$weight
 *   The weight field value array representing the weight of the order or NULL
 *   if no weight has yet been determined.
 * @param $order
 *   The order object whose weight is being determined.
 * @param $unit
 *   The unit of measurement to use for the returned weight of the order.
 *
 * @see commerce_physical_order_weight()
 */
function hook_commerce_physical_order_weight_alter(&$weight, $order, $unit) {
  // No example.
}


I deleted my .htaccess. easy way to fix this? I'm clueless enough that I managed to delete my .htaccess file from my drupal site (after some mistaked advice from my webhost tech support).
Now, I can go to the home page, but links to all internal pages result in 404 not found.
I'm using drupal 5 and my web host is dreamhost.
I don't have a recent backup of my site. I did find a very old htaccess file, and uploaded it, but then it threw a login pass popup.

Is there an easy way to fix this? Must I have the htaccess file?
How can I generate a new one that will work with my site?

any help much appreciated.

Here you go the . htaccess for drupal 5.x

http://drupalcode.org/project/drupal.git/blob/refs/heads/5.x:/.htaccess


Self-hosted development and deployment control panel - does this exist? My company requires a dev/staging/production environment for a new Drupal project. Plus some kind of control panel for managing development workflow and testing, upgrades and backups of code and content.

An obvious choice would be a platform like Acquia Cloud or Pantheon; their control panels do exactly this. But we are unable to use a hosted service; industry regulation means we must host on our own LAMP environment.

I'm familiar with Drush, Features and GIT, but wondered whether there is any distribution, project or commercial package that provides a management backend that pulls these elements together? I guess one of the reasons why Acquia exist is because the answer is no.

Any tips would be appreciated.

Aegir in and of itself is definitely the route I would recommend.

If you want a complete server + Aegir solution (and are willing to consider a LEMP stack), Barracuda-Octopus-Aegir (BOA) is fantastic (and highly maintained).


The Field module shows an error when I call drupal_get_form() I have a menu local task callback in hook_menu():

$items['leg/add'] = array(
    'title' => t('Create a new leg'),
    'page callback' => 'mymodule_leg_node_form',
    'access arguments' => array('create leg content'),
    'file' => 'node.pages.inc',
    'file path'=> drupal_get_path('module', 'node'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
);

This is the page callback function:

function mymodule_leg_node_form(){
    $form = drupal_get_form('leg_node_form');
    return $form;
}

When I visit that page, I get the following error:

  Fatal error: Cannot access empty property in path\to\site\modules\field\field.attach.inc on line 197

I have a "Leg" content type, and I just want to show the form to create nodes of that type in a tab.

My content type has two fields: "field_from" and "field_to."
drupal_get_form() calls _field_invoke(), and the error is generated from that function.

I tried to change the menu definition as below, but I get the same error.

$items['leg/add'] = array(
    'title' => t('Create a new leg'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('leg_node_from'),
    'access arguments' => array('create leg content'),
    'file' => 'node.pages.inc',
    'file path'=> drupal_get_path('module', 'node'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
);

I'm implementing something similar to what reported in http://drupal.org/node/251526#comment-827860; it might work in Drupal 6 with the CCK module, but it doesn't seem to work on Drupal 7.

I found the same problem reported in Drupal bug issues, but I could not find any qualified answer.

http://drupal.org/node/1015580#comment-4914818
http://drupal.org/node/1028230#comment-4799746

Solved this issue when I upgraded to drupal 7.10, but I had to create a node object in the page callback function.

function mymodule_leg_node_form(){
    global $user;
    global $language;

    $node = new stdClass();
    $node->uid = $user->uid;
    $node->type = 'leg';
    $node->language = $language->language;

    $form = drupal_get_form('leg_node_form', $node);
    return $form;
}


Monthly change images directory Drupal 8 I am working on a news portal site.
We have a lot of posts and also a lot of pictures are saved daily.

At the moment, the size of /sites/default/files directory is around 6GB and contains almost 23k files. And that is a problem.

What I want is to have directory for every month, for example:

/sites/default/files/3-17
/sites/default/files/4-17
...

Does anybody know how to do this?
Also, is there a way to keep live posts working?

I solved this problem using this module: https://www.drupal.org/project/filefield_paths
You can change path for every field type and use tokens like /[date:custom:Y]/[date:custom:m] to achive what I wanted...


PayPal Payflow Pro not allowing user to buy product when I enable (and try to use) PayPal Payments Advanced and Payflow Link sub-module of Paypal module and submit the product form I get this error:

messageEntityMetadataWrapperException: Unknown data property
commerce_customer_address. in EntityStructureWrapper-
>getPropertyInfo() (line 335 of
/site/sites/all/modules/entity/includes/entity.wrapper.inc).

When I remove Payflow Link module I do not get this error.

The problem occurs when I remove the default 'address' field from the Customer Profiles > Billing Information and instead just use my own fields...but I don't want to use that default address field because it contains items I don't want.

Anyone know how I can fix this so i can use Payflow?

It appears to be a problem in the Entity module but only gives me an error when trying to use Payflow Pro to purchase a product.

This is what that line of the entity module file has:

  public function getPropertyInfo($name = NULL) {
    $this->spotInfo();
    if (!isset($name)) {
      return $this->propertyInfo['properties'];
    }
    if (!isset($this->propertyInfo['properties'][$name])) {
      throw new EntityMetadataWrapperException('Unknown data property

' . check_plain($name) . '.');
        }
        return $this->propertyInfo['properties'][$name] + $this-

  info['property defaults'] + $this->propertyInfoDefaults;
        }

No one but me seems to have encountered this problem. But in the oft-chance someone ever does encounter it, here's why.

This error is occurring because I had removed the default address field from the customer profile > billing information in my drupal commerce store in favor of custom fields. But you apparently HAVE to use the default dynamic address field, or at least I don't know a way around it.

Since most of those fields are valuable anyway, and I just wanted them really in a different order, I found it valuable to KEEP that field, add some custom fields as well, and then just re-order them using hook_form_alter() and the '#weight' property of each form element. Additionally using this function you may also hide any of the fields in the default address field (it contains multiple fields) that you don't want.


Module(s) doesn't enable properly with Drush I have installed Acquia's DevDesktop 2 to create local sites and while testing D8.3.6 I have found an interesting issue. When I enable various modules with drush (drush en paragraphs (example)) drush reports the module installed correctly however when I try to use the module the site errors. The way to fix this is to uninstall with drush then use the Drupal UI to enable the module and all is fine.

The version of drush shipped with the latest version of DevDesktop is 8.1.10

Anyone else seen this?

This is a bug in either Drush, Drupal or the Entity Reference Revisions module (which the Paragraphs module depends on). The solution is to enable the Entity Reference Revisions or the Paragraphs module from Drupal itself, not with Drush. You can safely download the modules with Drush.

See my Drush issue at https://github.com/drush-ops/drush/issues/2873 for more information.

No, I can't reproduce this issue with other modules. (I'm using the same setup as you.)


What to enter into browser-sync command to run it on Aquia Dev Desktop? I'm trying to set up Broswers-Sync for my Aquia Dev Desktop Drupal 7 installation on localhost

In the page tutorial it says to set up local host like this command:

browser-sync start --proxy "myproject.dev" --files "css/*.css"

But I'm not sure what to put in there for my actual project.

The file I want to target is:

C:\patch\sites\all\themes\bootstrap_subtheme_local\css\style.css

And site URL on my machine is:

http://patch.dd:8083/

I want to know what to put in the command line to make this work.

You need to specify the hostname and port (patch.dd:8083) and the path to the CSS files you want to watch. Using the values in your example, you should therefore run:

browser-sync start --proxy "patch.dd:8083" --files "C:\patch\sites\all\themes\bootstrap_subtheme_local\css\style.css"


ubercart: finding order id when admin is editing order I have a custom shipping quote module which adds freight costs to the orders admin comments:

$order_id = intval($_SESSION['cart_order']);
uc_order_comment_save($order_id, 0, t($shippingquote_text), 'admin');

This works correctly when the user goes through the checkout process.

Problem:
How do i find the order id when the admin is manually editing a users order?

For example: admin is on admin/store/orders/3845/edit and clicks get shipping quote button - which fires freight quote module

Want:
comment is saved to order 3845 w shipping quote details.

My answer below is valid for Ubercart 7.36 as the page doesn't use Ajax.
UberCart 7.38 Uses Ajax, and the same variable isn't available. Still looking for an answer

I found the answer after posting the question:  (Valid for Ubercart 7.36)

if (in_array('administrator', $user->roles)) {
dpm (" do fancy stuff");
dpm($_SESSION['ucga_order_id']);

$order_id = $_SESSION['ucga_order_id'];
 uc_order_comment_save($order_id, 0, t($admin_text), 'admin');

dpm ("end admin fancy");

}


How to create a view that display on the same row a field and its translation Let say I have a content type with 2 fields that can be translated in a 2 languages site (EN-FR): the title and field_tobe_translated

I would like to list (in a view) all nodes of this content type with only one row by node and each row should have this format:

Title_FR -- Title_EN -- translatable_field_FR -- translatable_field_EN

The "--" before means a column separator in a table type view.

Added question:

Is it possible to filter this view to show only the row where "Title_FR != Title_EN" [I assusme that the process would be the same for the other translatable field]

I haven't found a way to show translations in the same row as the source, without additional modules that is. Although that would be nice to have.

These modules aren't currently covered by Drupal’s security advisory policy so they might not be a wise choice:

Translation Views
Views entity translation shortcuts
Translate Side by Side

A compromise might be to show your information spread accross two rows instead of one:

Create Views showing Title and Field for the two languages
Sort by ID (this will list translations close to their sources so you'll end up with pairs of English and French nodes that are translations of the same content)
Add another Sort criteria by Language (this way you're sorting inside each pair, so you always get French first, English second, if that's how you prefer it)

So in the end you'd have:

+----+------------+-------------------------+
| ID | Title      | Field                   |
+----+------------+-------------------------+
| 1  | Title_FR_1 | translatable_field_FR_1 |
+----+------------+-------------------------+
| 1  | Title_EN_1 | translatable_field_EN_1 |
+----+------------+-------------------------+
| 2  | Title_FR_2 | translatable_field_FR_2 |
+----+------------+-------------------------+
| 2  | Title_EN_2 | translatable_field_EN_2 |
+----+------------+-------------------------+
| 3  | Title_FR_3 | translatable_field_FR_3 |
+----+------------+-------------------------+
| 3  | Title_EN_3 | translatable_field_EN_3 |
+----+------------+-------------------------+


Inserting a form into a block in Drupal doesn't work I am creating block module in Drupal 7.

In the body of block I want to put the form which will restripe the data of table in forms.

I have created block as shown below but it doesn't showing the form.

<?php
/**
 * @file
 *  This is module file which display the links on the welcome page.
 *  This module will create a block of the link which is to be displayed on the welcome page.
 */

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function welcomepage_links_block_info() {
  $blocks['user-filter-ajax'] = array(
        'info' => t('User Filter'),
        'cache' => DRUPAL_CACHE_PER_ROLE, // default
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function welcomepage_links_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'user-filter-ajax':
        $block['subject'] = t('User Filter');
        $block['content'] = drupal_get_form('restripe_command_example_fieldset');
        break;
   }
  return $block;
}

function welcomepage_links_form() {
    $form = array();
    $form['restripe_command_example_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t("Demonstrates the Ajax 'restripe' command.")
);
    $form['restripe_command_example_fieldset']['restripe_num_rows'] = array(
            '#type' => 'select',
            '#default_value' => !empty($form_state['values']['restripe_num_rows']) ? $form_state['values']['restripe_num_rows'] : 1,
            '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
            '#ajax' => array(
                    'callback' => 'user_filter_ajax_restripe_num_rows',
                    'method' => 'replace',
                    'wrapper' => 'restripe_table',
            ),
    );
    $form['restripe_command_example_fieldset']['restripe_restripe'] = array(
            '#type' => 'submit',
            '#value' => t("Restripe the table"),
            '#ajax' => array(
                    'callback' => 'ajax_example_advanced_commands_restripe_callback',
            ),
            '#suffix' => "

first row

'Restripe' Command Status: Unknown
",
    );
    return $form;
}

Got it.

There was error in my programming. This is how i fixed it.

<?php
/**
 * @file
 *  This is module file which display the links on the welcome page.
 *  This module will create a block of the link which is to be displayed on the welcome page.
 */

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function welcomepage_links_block_info() {
  $blocks['user-filter-ajax'] = array(
        'info' => t('User Filter'),
        'cache' => DRUPAL_CACHE_PER_ROLE, // default
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function welcomepage_links_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'user-filter-ajax':
        $block['subject'] = t('User Filter');
        $block['content'] = drupal_get_form('welcomepage_links_form'); /**Problem was here**/
        break;
   }
  return $block;
}

function welcomepage_links_form() {
    $form = array();
    $form['restripe_command_example_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t("Demonstrates the Ajax 'restripe' command.")
);
    $form['restripe_command_example_fieldset']['restripe_num_rows'] = array(
            '#type' => 'select',
            '#default_value' => !empty($form_state['values']['restripe_num_rows']) ? $form_state['values']['restripe_num_rows'] : 1,
            '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
            '#ajax' => array(
                    'callback' => 'user_filter_ajax_restripe_num_rows',
                    'method' => 'replace',
                    'wrapper' => 'restripe_table',
            ),
    );
    $form['restripe_command_example_fieldset']['restripe_restripe'] = array(
            '#type' => 'submit',
            '#value' => t("Restripe the table"),
            '#ajax' => array(
                    'callback' => 'ajax_example_advanced_commands_restripe_callback',
            ),
            '#suffix' => "

first row

'Restripe' Command Status: Unknown
",
    );
    return $form;
}


Easy date selector for Views Exposed Date Filter I'm looking for a solution to put "Easy date selector" on the Views Date Exposed Filter, something like a drop-down or links with predefined date range:

Posts for today
Posts for yesterday
Posts for last week
Posts for last month
Custom range

any ideas?

A filters set as "Grouped filters" (as opposed to "Single filter", under "Filter type to expose"), lets you provide a predefined list of options.

With Grouped filters, you can setup your fixed list with date filters that are "offset from the current time". For example:

I'm not sure how you'd accomplish the Custom Range. Perhaps something like the Select (or other) module, or a second filter date filter?


How can I arbitrarily execute a rule from the UI to test a login togobban workflow using selenium? I am trying to create tests for my Drupal site using Selenium UI.  I am attempting to test Login Toboggan's "verify user" behavior, but since the account verification link is different each time, it cannot be easily included in a test.

I have several rules that should be triggered upon successful validation; since I cannot trigger validation in the normal manner, I would like to activate these rules manually.  Is there a way to do this from within the UI (so that it can be added as part of selenium)?

I ended up solving this with rules by making a new rule.

Event- "User has logged in"

Conditions- "User has roles" -> The role of the "unverified user" (set on the
logintoboggan configuration screen)

Actions- "Show a message on the site"

Message text:

validate your account

This will present a message to unverified users when they log in allowing them to verify their accounts.  Of course this has to be disabled for production, but it allows one to test validation workflows in Selenium.


Layout detail node + ckeditor layout When I create a node of content type Proposal like this:

I can add images, paragraphs, ... . But it looks like this on the detail page of the node:

No image, no paragraphs, ... . What could be the problem of this?

I'm using the Filtered html text format. When I check the html of the paragraph there is no image, nothing. Just text ... .

These are my settings of context filter filtered html:

Have a look at Limit allowed HTML tags in the setting for your text filter. Make sure img is among the allowed HTML tags.

The settings are found under admin/config/content/formats.


View of organic groups name list with no activity I'm running a Drupal 7 site, and I want to create a list view of group names with no activity within last 60 days. For example if user have not created any content with in those groups.

Currently groups (OG) hold different content-types/nodes i.e news, galleries, wikis, and discussions.

Can someone please help me achieve this?

I suggest you to create a custom table with group id and access timestamp. Whenever you are adding a new content to OG, update the table with group id and current timestamp. Then list inactive groups (by calculating current time from your timestamp saved in table), using theme_table function.


clone of drupal project failing: operation timed out I am trying to clone the drupal project locally  but getting this error

k10593:htdocs welcha$ git clone git://drupalcode.org/project/drupal.git fooproject
Cloning into 'fooproject'...
fatal: unable to connect to drupalcode.org:
drupalcode.org[0: 140.211.10.6]: errno=Operation timed out

I am following this tutorial: http://drupal.org/node/803746

Any idea what the problem might be?

Try disconnecting your wifi and then connecting again. Used to resolve the issue before, when i got "some broken pipe error". This generally happen iF your wifi network keep switching to different connection to balance the load. Just a suggestion.


Different roles create different amounts of a specific content type I'm building a job directory where users are allowed to register (selecting a membership type) and create Companies and Jobs.

A membership can be Simple, Business or Premium. The membership type is treated in the similar way as a user role. See the list of roles:

My goal is:

if the user selects Simple membership (Authenticated user), he / she is going to be able
to create only 1 Company and 1 Job;
if the user selects Business membership (Business user), he / she is going to be able
to create 2 Companies and 3 Jobs.

How can I do this?

Through the Permissions section I was only able to define if the user can add, edit, delete content and that's not enough.

Sounds like you should have a look at the Group module, which gives you all the features you are looking for, using the "roles" of the Group module (as explained in "What are the various roles supported by the Group module?"), combined with granting the relevant permissions for each of the groups you'd configure. Refer to some of these questions to get you going with the Group module.

BTW, even though this question is about D8, same is true for D7 ...


How to define profile types per group type in the Group module? I am working on a site where I am just starting to work with the Drupal 7 version of the Group module. The groups and roles stuff is fine but can I define a profile type per group type?

eg. Group Type "School" might have profiles Principal, Teacher, Student, Volunteer and Group Type "Church" might have profiles Pastor, Youth Worker, Member etc

So when someone signs up I want them to find their group (eg St John's Baptist) and then enter their profile type (eg Pastor).

Then I want to show specific content depending on their profile type. eg All Pastor's will have access to certain nodes.

Group profile types seems to be global so looking for a way to do this neatly.

... can I define a profile type per group type?

Sure (yes?) you can, it's what in the Group module is called "Group Specific Roles".

  Group profile types seems to be global ...

Here you're talking about what in the Group module is called "Special Global Role" or "Configured Global Roles".

For more details on this, refer to the answer to "What are the various roles supported by the Group module?".

Be aware: this answer applies to D7, as in the question (for D8 it would be different ...).


Taxonomy terms with conditional field 50 terms and each term needs to have radiobuttons or "other".

Food - o in price - o extra price

Drinks - o in price - o extra price

WiFi - o in price - o extra price

So "in price" and "extra price" are radiobuttons. User clicks "extra price" and he gets conditional text field (integer) where he can write the extra price. Result after choosing "extra price" should look like this:

Food - o in price - o extra price - _________ €.

There are 2 things that come to my mind. Making separate vocabulary out of each term, each containing terms "in price" and "extra price", make separate integer field in content type and use conditional field module.

But that would mean i would have to create 50 vocabularies and 50 integer fields for 1 content type and its possible that there will be more terms in the future.

2nd option would be creating 50 fields instead of using taxonomy and use Select or other module but that also seems to be overdoing it to have 1 content type with over 50 fields just becouse of this option

With a module, creating a form and using the drupal ajax function to switch the input field on/off might be a solution.

check out this example from deckfifty: form api using ajax example

partial code:

function deckfifty_example_form($form, &$form_state) {
  $form['fox_color'] = array(
    '#title' => t('Specify the color of the fox:'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('', 'brown', 'black', 'white')),
    '#ajax' => array(
     'callback' => 'deckfifty_fox_ajax_callback',
     'wrapper' => 'deckfifty_fox_ajax_wrapper',
   ),
 );
 $form['fox_wrapper'] = array(
    '#type' => 'markup',
     '#prefix' => '
',
    '#suffix' => '
',
 );

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

 return $form;
}


Trying to save an image field on a user using services, but for some reason it isn't saving in base64 So my server (running Drupal 7) is getting this information:

[field_picture] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [file] => iVBORw0KGgoAAAANSUhEUgAAAIwAAACMCAYAAA..... (the rest of a huge base64 string)
                        [filename] => test.png
                        [filemime] => image/png
                        [target_uri] => test.png
                        [filepath] => public://
                        [mimeType] => image/png
                    )

            )

    )

This is to a user endpoint, and this is the only field that doesn't update.

The rest of what is sent to the server looks like this:

[field_description] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] =>
                            [format] =>
                            [safe_value] =>
                        )

                )

        )

[uid] => 22
[roles] => Array
    (
        [2] => authenticated user
    )

And my AJAX to put this up:

    $.ajax({
        url: SITE_URL + "/" + ENDPOINT + "/user/" + localStorage.uid,
        type: 'PUT',
        crossDomain: true,
        headers: {
            'X-CSRF-Token': token
        },
        contentType: 'application/json',
        data: JSON.stringify(json),

...etc

The request doesn't fail (or at least it doesn't go to my error callback) - what is going on here and why isn't it saving?

You need to make two requests, the first you will POST the base64 encoded string of the file which in turn will return to you the file id, at which point you can make the second call to save the user entity with the file id on the field in question. I have a blog post about this here: http://tylerfrankenstein.com/code/drupal-services-file-create-example-json-and-jquery

Here's the gist of it (assuming your endpoint path is api):

// Get the file id...
$.ajax({
  type: "post",
  data: {
    "file":{
      "file": my_base_64_encoded_image_string,
      "filename": "my_image.jpg",
      "filepath": "public://my_image.jpg",
    }
  },
  url: 'https://www.example.com/api/file.json',
  dataType: 'json',
  success: function(result) {

    // Now that we have the file id, save it on the user entity.
    var userAccount = {
      field_picture: { und: [ { fid: result.fid } ] }
    };

    $.ajax({
      url: "https://www.example.com/api/user/" + localStorage.uid,
      type: 'PUT',
      crossDomain: true,
      headers: {
          'X-CSRF-Token': token
      },
      contentType: 'application/json',
      data: JSON.stringify(userAccount)
    });

  }
});


Serial number for each item I am making a book rental cum selling site. I have planned to use Drupal Commerce for it. But tracking the item is simply not possible & so that I am trying to find the solution for assigning serial number for each number of items(attributes) for drupal commerce product.

Like I am having a BOOK & it has 10 copy, so I want to keep one unique serial number for each copy.

If somebody have any idea about this then please help.

I would implement this by first creating a Book Product (Non-Fiction) and issuing a specific sku number for each separate Book Title that I would introduce as a specific product. Combining this with the http://drupal.org/project/commerce_stock module might be useful in allowing unique skus per book but than also having quantity of books in stock for multiple copies.

Ender's Game (10 copies according to commerce_stock) SKU #00000001
Dune(30 copies according to commerce_stock) SKU #00000002


Dynamic block titles I have added a custom block to my users' profile page that shows a list of all that user's submissions.  I would like the title to be the user's name then projects so for the user Mike I would like to see "Mike's Projects" as the block title.  Is there a way to do this?

If you're familiar with Drupal's hook system, you can do this via hook_block_view_alter


How to create media image entities like an image field? I have been using a content type Article with an Image field to allow users to upload images.  I have decided that I want to use media image entities instead because the images will be re-used on multiple nodes, so it would be better to use a module like Entity Browser to allow admins to pick the images they want to use.

Following this tutorial, I set up Media Entity, Media Entity Image, Embed, and Embed Entity on my site.  I can now add entities from the /media/add/image page.

But, with using this set of modules, the workflow has changed.

Image field on content type workflow

User uploads images in the field when creating a node.

Media entity image + content type/embed workflow

User uploads images.
User creates a node.
User embeds the images on the node.

So actually this new workflow has more steps than the old one.  Is there a way to "embed" creation of media entities as if it was just an image field attached to the content type?

Sounds like exactly the use case Inline Entity Form was built for:

  Provides a widget for inline management (creation, modification, removal) of referenced entities.


How to create dynamic drupal 7 taxonomy views I have to create 1 view using taxonomy.

Let's take the example i have 8 categories: cricket, football, tennis, swimming.

I have to show this each category with their 5 latest articles.

Thew views should display database like

Cricket

List item
List item

Football

List item
List item

Like this all 8 categories with grid layout and 4 categories in row.

Right now what i am doing is creating 8 different views and showing on 1 page.

But this create issue when i am adding new category.

So it's dynamic view can help or i have to write code for this.

This is fairly simple in Drupal 7 with the help of EVA: Entity Views Attachment. You are able to then create only two(2) views.

The first view will render all your categories you have in taxonomy as well as calling in the second view into a field of this view.

Your second view will then display the entities associated with the taxonomy term,
You will have to create a Term reference in your content types in order to have a field in your entity view to check against.

I have previously done this where there are categories or terms displayed with a list of entities below them, all displayed in a grid view. See Example below.


Is it possible to change the path of modules/themes installed using an installation profile? I have a site which has a profile which downloads a number of modules using drush make. It adds the modules in the path /profiles/profile_name/modules.

Is it possible in the make file of the profile to change the path to where the modules and themes are put, so that they are then installed in sites/all/modules and sites/all/themes?

If you have already installed the profile — no, you can't move modules by modifying make file. Profile's .make file is used only during installation process.

If you want to replace modules from profiles/%PROFILE_NAME%/modules/ to sites/all/modules on already installed copy of Drupal, you can just replace files (with mv or something) and then run system_rebuild_module_data() function to ask Drupal to update modules destination. With Drush:

drush eval "system_rebuild_module_data();"

For profile installation process — I really don't know why and don't know how to modify .make file. Maybe you can specify 'contrib_destination' property for every project?


Node preview with different theme than editing I'm using an admin theme for nodes editing, also for users that are not admin (with permission "View admin theme").

The problem is that in this way also the preview of a noded is displayed with admin theme, but I need to display the preview with the "default" theme.

Is there a way?

Page Preview module could be the solution.

Simply add an iframe on the node edit form with the preview of the node in the "default" theme. It's in "dev" version but works.


Add background to a div based on a Node's Image Field I had a request approach me and am blanking on a smooth way to implement this. We have on content type that on occasion will have a background image in a a div. The image will be a washed out background image behind content. The content authors want to add this page by page using an Image Field.

How would you implement this?

I'm assuming I can do this through our custom theme -- perhaps a theme_preprocess_page() or theme_process_page()?

You could try BackgroundField:

  BackgroundField started as an extension of the CCK ImageField that
  allows a CSS selector and background attributes to be set for a
  content-type. This is particularly helpful for allowing your node
  authors to add images to a node that are integrated into the theme of
  the site. With the inclusion of the Image field in Drupal 7,
  BackgroundField was rewritten to extend that core functionality.


How do I get the block title from the plugin implementing it? I'm attempting to print the value of the title of the block in a block plugin.

public function build() {
    $build ='
        <div class="header-text">
            <'.$this->configuration['header-size-submit'].'>'.$this->title.'</'.$this->configuration['header-size-submit'].'>
        </div>
            ';
    return array(
        '#type' => 'text',
        '#markup' => $build,
        );
}

I attempted to get the value of the title by using

$this->title

But that did not work.

If your block plugin derives from the BlockBase class, BlockBase::label() returns the default title for the block, but the block title is set in BlockBase::buildConfigurationForm().

  $form['label'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Title'),
    '#maxlength' => 255,
    '#default_value' => $this->label(),
    '#required' => TRUE,
  );
  $form['label_display'] = array(
    '#type' => 'checkbox',
    '#title' => $this->t('Display title'),
    '#default_value' => ($this->configuration['label_display'] === BlockInterface::BLOCK_LABEL_VISIBLE),
    '#return_value' => BlockInterface::BLOCK_LABEL_VISIBLE,
  );

So, your block class should check if $this->configuration['label_display'] is set to BlockInterface::BLOCK_LABEL_VISIBLE; if it is, then use $this->configuration['label'] for the title.

That said, I feel like the code you want to implement is actually not necessary, since the BlockBase class already takes care of showing the block title.


How to see changes inside Paragraphs or Field Collections with Diff I have read and checked that Paragraphs and Field Collections revisions are tracked. But when I make a change to the node and then look at the Revisions tab, no changes done with fields inside Paragraphs or FC are displayed. Does Diff support display of those changes? If yes, how can I see them?

Things I checked:

Enable the Revisions page for this content type is checked.
Standard comparison preview is Full Content and it has paragraphs field displayed.
Diff module is installed and enabled.
On page admin/config/content/diff/fields in Global settings for Paragraphs Markdown callback is set to "Drupal HTML to text", as well as for those field types that are inside paragraph.

I can see field changes for my content type, but the comparison page does not show changes for fields that are inside paragraph.
What is missing?

You have to install and enable the Diff module.

  This module adds a tab for sufficiently permissioned users. The tab
  shows all revisions like standard Drupal but it also allows pretty
  viewing of all added/changed/deleted words between revisions.

Nothing else is needed.

Given a simple paragraph with a boolean field and a text field, if oyu change the textfield uou will get someting like this:


How to add a field to Browsing Widgets partial form? I have a content type Task which has a field that references to other content type Project, so when I create a new Task, I can reference it to a project. I would like to add this to the Commons Browsing Widgets partial form.

How can I add a dropdown list to this form that shows the projects where user can link the task? I was trying to add it by adding it to code in .module file, in the form_commons_bw_partial_node_form_alter() part but I didnt manage to get it working..

It seems that you can just do this by going to your content type, edit the field you want to show and check the "Display in the browsing widget mini-form". After all the trouble it seems quite simple..


Show two copies of same menu Let's say I have Main Menu and I want to show it in header and in footer, to achieve that I can use Menu Block module, but using it lets say I disable one link in Main Menu, it also disables it in the clone menu in the footer. How do I have multiple copies of same menu, but with different disable options for each, and when adding new links it would update both, but at the same time be able to disable links separately on each menu?

Let's say both menus have Home and Events links. I want to show Home and Events in just header menu and disable Events in footer? And if I decide to add new link, it will add up in both menus at the same time and then again I will be able to disable it in only one of them if needed.

Makes sense?

How do I have multiple copies of same menu, but with different disable options for each

Drupal doesn't support anything like that, and I must admit it doesn't make sense to me that it would.

As soon as you have two menus that need to show different things, you need two menus. Setting arbitrary rules on how that second menu should partially sync itself with another, arbitrary, menu, is a conceptual nightmare. I can't even imagine what the UI would look like for that.


Database field of timestamp type cannot be added to the database using hook_schema() I have created a custom module in drupal 8. But in the .install file there is a field for created_date which has a type of timestamp. When I try to enable that module it gives the below error.

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'created_date'' in

.install file

<?php
function golf_reservation_schema()
{
  $schema['golf_reservation'] = array(
   'fields' => array(
       'id' => array(
           'type'     => 'serial',
           'not null' => TRUE,
       ),
       'property_tid' => array(
           'type' => 'int',
           'not null' => TRUE,
       ),
       'property_name' => array(
           'type'     => 'varchar',
           'length'   => 100,
           'not null' => TRUE,
       ),
       'title' => array(
           'type'     => 'varchar',
           'length'   => 20,
           'not null' => FALSE,
       ),
       'full_name' => array(
           'type'     => 'varchar',
           'length'   => 255,
           'not null' => TRUE,
       ),
       'tee_date' => array(
           'type'     => 'varchar',
           'length'   => 255,
           'not null' => TRUE,
       ),
       'tee_time' => array(
           'type'     => 'varchar',
           'length'   => 255,
           'not null' => TRUE,
       ),
       'golfers' => array(
           'type'     => 'int',
           'not null' => TRUE,
       ),
       'no_of_carts' => array(
           'type'     => 'int',
           'not null' => TRUE,
       ),
       'special_request' => array(
           'type'     => 'text',
           'not null' => FALSE,
       ),
       'created_date' => array(
           'mysql_type' => 'timestamp',
           'not null' => true,
       ),
     ),
     'primary key' => array('id'),
   );

   return $schema;
}

But when I execute this query in database it does not give an error

CREATE TABLE eme_golf_reservation (
  `id` INT NOT NULL auto_increment,
  `property_tid` INT NOT NULL,
  `property_name` VARCHAR(100) NOT NULL,
  `title` VARCHAR(20) NULL DEFAULT NULL,
  `full_name` VARCHAR(255) NOT NULL,
  `tee_date` VARCHAR(255) NOT NULL,
  `tee_time` VARCHAR(255) NOT NULL,
  `golfers` INT NOT NULL,
  `no_of_carts` INT NOT NULL,
  `special_request` TEXT NULL DEFAULT NULL,
  `created_date` TIMESTAMP NOT NULL,
  PRIMARY KEY (`id`)
)

I am running the latest Drupal version with MySQL 5.6.30.

I believe you need to explicitly define the default value for those in the schema:

'created_date' => [
  'mysql_type' => 'timestamp',
  'not null' => FALSE,
  'default' => NULL,
],

For maximum portability, you can also define the types for other databases:

'created_date' => [
  'mysql_type' => 'timestamp',
  'pgsql_type' => 'timestamp',
  'sqlite_type' => 'datetime',
  'not null' => FALSE,
  'default' => NULL,
],

Look at \Drupal\KernelTests\Core\Database\SchemaTest for an example.  FWIW, code doesn't use that for timestamp/created/updated.  Those are field types and handled by the Field API.


How to only allow a user to edit his/her own users? For instance, my site contains two roles:

employer.
company.

Every company has to be able to add, edit and delete there own employees.

As you may understand, companies should not be able to edit or delete users created by other companies.

How can I achieve this?

The Organic groups module (as already suggested in another answer) is indeed a possible answer to your question. But you should also have a look at the (fairly new) alternative for it, which is the Group module (with it roots close to where Dries started Drupal ...). Some more details about it (from its project page):

Organic Groups allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).
Groups instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" Organic groups module.
The Group module also integrate nicely with the Rules module, as explained in comment #2 of issue 2603136, which states the following:

... you can already use Rules to:

Add a new Group
Create a new GroupMembership and save it (the equivalent of $group->addMember())
Add or remove a GroupRole from a GroupType
React on new GroupMembership or Group entities
…

What hasn't been done yet is custom Rules actions or conditions. Seeing as 90%+ of Group is pure Entity API CRUD-operations, there has been no custom Rules code yet given how much you can already accomplish out-of-the-box.
Useful Rules we may add could be:

E-mail all members of a Group, optionally filtered by GroupRole
Easier-to-understand labels for the above list: "Member joined group" sounds easier than "GroupMembership entity is created"

...

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.
PS: Refer to How to implement an option for users to limit access to nodes/comments to users with the same role while posting it? for an interesting illustration of how this module can be used.


Display the node edit form on a node view page Can we show the node edit form in a custom block and show that on a node view page?

You could use Form Block module and place the block above your view block. Some details about it (from its project page):

  Enables the presentation of user registration, site wide contact, or node creation forms in blocks.

OR go with Clive's answer to this Q: Why doesn't loading a form in the view header work? and load the form in your View's header.


How to display rss from external site into a view and sort them? I want to import RSS from an external website and then display them in a view content pane. I also have to sort them by date. The External RSS contains Title, Body and Date but the Date is hidden by default in RSS, I guess. I checked the Aggregator and feeds module but I don't think it serves the purpose because i also have to link the title to the Nodes on the External site.
Thank you.

If feeds are read by drupal core aggregator module then you can do this with the help of views module itself.

Rough Example: Settings as per the screenshots

Create new view
Add fields to your view.

This will show feeds in view and you can easily do whatever you want to do with it.
Hopes this will help.


How to show tooltips using a bootstrap sub-theme in a views filter? I am using the bootstrap Tweme theme and would like to show tooltips when hovering over exposed filters (e.g. haslanguagecertificate) in a view. When hovering over profile edit fields the help text is shown properly.

I have also added the snippet in html.tpl.php before the closing < / body>.

(function($) {
   $(document).ready(function() {
   $('[data-toggle=tooltip]').tooltip();
   });
})(jQuery);

This has How to show tooltips on form labels based on view filter descriptions in a Bootstrap sub-theme? that helped, but the tooltips are not showing up. Devel does not show ['title']['#attributes'] - what do i have to write here?

/**
 * Implements hook_form_FORM_ID_alter().
*/

function customisations_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
dpm($form);
// $field_name = 'filter-title';
$field_name = 'filter-field_haslanguagecertificate_value';
$form['title']['#attributes'] = array(
  'data-toggle' => 'tooltip',
  'data-original-title' => $form['#info'][$field_name]['description']
  );
 $form['#info'][$field_name]['description'] = '';
}

form['title'] needed to be replaced with the fieldname without "filter-".

function customisations_form_views_exposed_form_alter(&$form) {
  //drupal_set_message("setting exposed filter tooltips", 'status');
  //dpm($form);
  $allFilter = array();
  $filtersList = array_keys($form['#info']);

for ($i =0; $i<count($filtersList); $i++) {
    //drupal_set_message("filter " . $filtersList[$i], 'status');
    array_push($allFilter,$filtersList[$i]);
  }

  foreach ($allFilter as $field_name) {
    $fieldTitle = substr($field_name,7); //removes the filter-
    $form[$fieldTitle]['#attributes'] = array(
    'data-toggle' => 'tooltip',
    'data-original-title' => $form['#info'][$field_name]['description']
  );
  $form['#info'][$field_name]['description'] = '';
}
}


field_view_value returns null for boolean field I have a custom field field_sold which contains a single boolean value. I'm trying to use the following function to retrieve the content of the field, but it always seems to return null:

function <theme>_render_field($node, $field_name, $delta = 0, $display = array()) {
   $field = field_get_items('node', $node, $field_name);
   $field = field_view_value('node', $node, $field_name, $field[$delta], $display);
   return render($field);
}

When trying to dumping the $field variable between the calls to field_get_items() and field_view_value() I recieve the following output:

// after field_get_items()
Array ( [0] =>
   Array ( [value] => 1 ) )
// after field_view_value()
Array ( [#markup] => [#access] => 1 )

When I'm using the above function for other fields it works as expected, for instance when rendering a image field like this:

print <theme>_render_field($node, 'field_image', 0,
                     array('type' => 'image',
                           'settings' => array(
                           'image_style' => 'object_200x300',
                           'image_link' => 'content')
                           ));

Set

$display['type'] = 'list_key';

in your theme function to get not null key of field. Or create own formatter, for ex.

function mymodule_field_formatter_info() {
  return array(
      'my_formatter' => array(
          'label' => t('My formatter'),
          'field types' => array('list_boolean'),
      ),
  );
}

function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
    case 'my_formatter':
      foreach($items as $delta => $item) {
        $value = $item['value'] == 1 ? 'ON TEXT' : 'OFF TEXT';
        $element[$delta] = array(
            '#markup' => $value,
        );
      }
      break;
  }

  return $element;
}

and after that set

$display['type'] = 'my_formatter';

in Your theme function


How to use the same URL alias for all translations of a node? I want to use the same URL alias for all nodes regardless of language.

On my site, the primary language is English.  Translation is enabled for nodes of type basic page.

At /admin/config/regional/content-language, content translation is enabled for the Title and Body fields.

With this configuration, on the node edit page, it shows "URL alias (all languages").  I set a URL alias manually for each English node.

However, when I add a translation in another language, even though I see my alias on the translation edit page, this alias is not applied for that language.  In other words, if the alias is myfolder/mypage in English, if I go to the Japanese translation at /ja/myfolder/mypage, I get a "page not found" error. Instead, the page is available at /node/5 or whatever the NID is.  But, on the "edit node" page for the Japanese translation, it does show the English alias with the text "all languages."

Workaround

I can go to /admin/config/regional/content-language and enable translation of URL alias and then manually set each additional language alias to the English alias, but this seems like a lot of extra work to keep the same alias.

As pointed out by @Rockabelly, this is a bug with Drupal core.  For now, there is a patch to fix the issue.


Why has not Pressflow been upgraded to 6.24? Two weeks ago, Drupal released 6.23 to fix a security vulnerabilities, which was followed from Drupal 6.24. However, Pressflow is still in 6.22 (although, there are some files have been changed at the last week).

I am wondering whether Pressflow 6.22 has not been affected by the vulnerabilities in Drupal 6.22, or it does but it takes time for the team to upgrade it. If so, how insecure is Pressflow 6.22?

I'm a developer at Four Kitchens.

Drupal 6.24 introduced changes to the bootstrap process, and those created a merge conflict with Pressflow. See David Strauss' comments here on Github.

The forks of Pressflow on Github may have the latest 6.24 but these changes have not been reviewed by Pressflow maintainers and no pull requests have been sent.

The forks also include patches from the Drupal issue queue to fix some serious issues that appeared in 6.24, and they are not the most recent patches in the actual issue nodes:

drupal.org/node/1425868
drupal.org/node/1425260

So beware: Using a fork means you're using Pressflow upgraded to 6.x-dev essentially, except it's not even -dev as these issues are not yet adequately resolved; at least, not sufficiently enough to be accepted into Drupal 6.x-dev.

We're working on getting a full 6.24 stable version of Pressflow out. In the meantime, Pressflow 6.23 contains the security fix and was available when Drupal 6.23 was released.

You can also follow Pressflow at https://twitter.com/#!/pressflow.


Upgrading from 5.3 to current Is there a reasonable upgrade path from drupal 5.3 to the current version or should I just rebuild the site from scratch? It's a pretty small site, but it does have a few custom content types, and use tac_lite for role-based security.

These are the modules I have installed:

tac_lite
filebrowser
private_upload
role_weights
site_user_list
user_import
cck
views
imagefield
imagecache
token
pathauto
path_access
marksmarty
devel
admin_menu

Nope, there is none. No matter if by "current" you mean 7.x or 8.x, skipping 6 is too much gap, and even upgrades from 6 to 7 are known not to be painless and safe.

You may try to rebuild site's structure from scratch, and then use Drupal-to-Drupal data migration module to import your data:

  migrate_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed. As of 7.x-2.1-beta1, it requires Migrate 7.x-2.6-beta1 or later.


OK to replace images on server? So my client has been populating the site with content, but their images aren't optimised for the web.

Can I just download all the images, and then upload new versions to overwrite them ? Or are images linked more carefully to the DB?

I've never had any problems just replacing images.

If there are any images that have image styles applied then don't forget to clear the image styles caches/files so they get regenerated as well.  You can do them all at once with Image style flush

tl;dr:

Should be fine so long as the filenames match.


Newly created field not being added to entity I have created a form that adds a subset of field types to an entity (does not support bundles).  (the reason for the custom form is that end users find the Drupal standard 'Manage fields' workflow too difficult)  The class extends FormBase.  When the 'submitForm' function is executed, the field is saved but not added to the entity.
This is the code to save a date field (with text values filled in for explanation purposes):
$field_storage_values = [
  'field_name' => 'field_test_date',
  'entity_type' => 'my_entity_id',
  'type' => 'datetime',
  'translatable' => TRUE,
];

$field_values = [
  'field_name' => 'field_test_date',
  'entity_type' => 'my_entity_id',
  'bundle' => 'my_entity_id',
  'label' => 'Test Date',
  'translatable' => FALSE,
];

$this->entityTypeManager->getStorage('field_storage_config')->create($field_storage_values)->save();
$field = $this->entityTypeManager->getStorage('field_config')->create($field_values);
$field->save();

When the form is submitted, the field is created correctly but not added to the entity.
When I export the field configuration to YML, the following appears under dependencies:
dependencies:
  config:
    - field.storage.my_entity_id.field_test_date

Creating an identical Node field results in the following field configuration YML dependencies:
dependencies:
  config:
    - field.storage.node.field_test_date
    - node.type.basic_page

I suspect the field created with my custom form should also add the second configuration dependency like:
my_entity_id.type.my_entity_id

I tried adding the following before the field is saved but the 'addDependency' function is protected.
$field->addDependency('config', 'my_entity_id.type.my_entity_id');

You can't add this dependency, it's bundle configuration which you don't have and don't need in a bundleless entity. For testing better add a user instead of a node field or check the already pre-installed field.field.user.user.user_picture.yml
To create the field config you only need to specifiy the field storage and the bundle (for a bundleless entity this is the entity id). The other values are then extracted from the storage config:
$storage = $this->entityTypeManager->getStorage('field_storage_config')->create($field_storage_values);
$storage->save();

$field = $this->entityTypeManager->getStorage('field_config')->create([
  'field_storage' => $storage,
  'bundle' => 'my_entity_id',
]);
$field->save();

BTW part of the field UI is also the configuration of display modes. You need to add the new field as component at least to the default view and form mode, so that the new field is visible. See How to change the entity view display configuration programmatically?


How to show a random image from unlimited image field using Views? There is an content type called "imagenode". This content type contains title, body and one image field (unlimited images can be uploaded/attached).

Now exactly one node from imagenode is created: 20 Images are attached/uploaded.

Question:
How can I create a views block that displays one random image out of these images attached to this one node from type imagenode?

I can create a view with fields and show one image and I can set an offset in order to display onother image. But there seems to be no way to display one random from all attached images.

How can this be solved in Drupal 8?

1) Click on your image field

Under Multiple Fields Settings, uncheck display all values in the same row.

2) Add Global: Random as your sort and remove the default sort (content post date).


Why are the Recent log messages not shown within admin/reports? The usual log reporting option "Recent log messages" is not showing up under 'admin/reports' (in the admin menu).

Any idea what might be causing that? Is there a module that provides this functionality?

The "Recent log messages" is one of the submenu options located within admin/reports/dblog.

It becomes available after the core module dblog (Database Logging) is enabled.

If that core module is enabled, and it still isn't showing up, then it is probably because permission "View site reports" (within "System") has not been granted to the user trying to access that report.


How to delete Duplicate Nodes based on title? Is there any easy way to remove duplicate nodes based on Node title?

You can achieve that by Remove Duplicates module

This module helps the administrator to easily remove duplicate nodes according to one of the node fields.
Features
The duplicate nodes found are permanently removed. It can be very useful with Drupal Feeds module (Feeds).


page visible to unathenticated users Possible Duplicate:
  enable viewing access to anonymous user

I can't remember how to make certain pages visible to the public, only blocks.  My site is private but I would like for 3-4 pages to visible to ALL users.  How would I go about implementing this?  Thanks!

Here's a screenshot of clean install with Content access module and Rubik admin theme:


How to display body content in custom text? How to display body content in this line?

I had tried "content_body" and "field_body" but doesn't work.

The script below is inserted in "Configure field: Global: Custom text"

            [field_image]

[title]

[field_categories]

[content_body]

Under the custom text box, if you click on "Replacement Patterns" it will show you all the patterns you can use.

Should be [body]

Also, make sure all the other fields are arranged above the Global: Custom text or else the pattern will not work.


Views contextual filter - related nodes as an offset from a node's creation date I have a related content view which displays similar nodes based on shared taxonomy terms. I want it to display related nodes that were published in a date range relative to the current node's creation/published date. E.g: for a node published in March, I want to filter similar nodes that were published between February and April.

Currently I am only able to create a contextual filter "Node: Published at year + month" which displays similar nodes that were published in the same year+month, but I am looking for something similar to the post date filter criteria with operator (image attached), but instead of offset from current time, have an offset from current node's creation date. Is that feasible with views contextual filter?

I think in this case you can use panels for that
In views create a content pane

Then add contextual filter based on Created Date
and in "PANE SETTINGS" click on "Argument input" and use this Settings :

this will export the node's created date from it and pass it through arguments to views.

this will give you an Panel's pane , to add it to your view you can use Page manager module .


How to create a view of nodes of which a user is a member? How do I create a view of Nodes that a logged in user is a member of? Is this enforced in Relationships or Contextual Filters? That is, can you explain how group membership is enforced via relationships and contextual filters?

Organic Groups provises a default view for this called "OG User Groups". You can use that as a base and adapt it accordingly.


How to attach a single node multiple times to an entity (e.g. badges)? For an experimental Drupal 7 site, I would like attach a single node to another entity (this might be users, other nodes or even organic groups). The reasoning is fairly simple, say I have several users active and they can gain badges for activity just like in any stackexchange platform. Each badge is represented by a single node. Now, how could a user get the same badge multiple times?

Using entityreference, I can attach the same reference multiple times, but I am struggling with the output, it will show the same badge multiple times instead of only badge name and a counter. Is there already a module for that I haven't found yet? Can you think of a better way to do it?

Badges might not be the best example as you normally wouldn't lose any. Think of a trading card game might be better, as you can have the same card multiple times and trade it with another user. So, in the end I would need a way to add and remove the references. But this will be custom code, I guess.

EDIT (in answer to Webdrips' comment):
As said in the very beginning, it's just an experiment so far, we are trying to use Drupal in unconventional ways in order to explore the full capacity of Drupal as a framework.

So, I came up with a better example to illustrate what I would like to achieve: let's say I am building a browser game. Game users will be normal Drupal user entities. An user may have several normal fields like health (number), name (text) and gender (list). Additionally, this user can collect items where each individual item type can be found multiple times.

Several players can be in a clan (organic group). This group has a central storage. So, each individual player of that group can place an item in the central storage.

Technically, I need a relation between user and item (for each item type) which also holds the number of items (e.g. Player1 has 5 nails). If he places 2 nails in the central storage, I need to change the relation between user and item (e.g. Player1 now has 3 nails) as well as the relation between organic group and item (e.g. Group1 has 2 nails).

So I am actually looking for a way to connect an item node (e.g. nails) to other entities (users, organic groups, ...) along with an additional value (item count).

I hope this renders my problem/question in an easier-to-understand way.

I've come across the User Points module and for keeping track of game points in my example this might be the right way to go, but imho it's not suited for the item thing.

Somehow it kept slipping my attention, I was probably focussed too much on specific ideas, but as it turns out, there is already a module for that, it's simply called Relation.

It's not that straight forward to use (imho), but it essentially creates relations between entities. The created relations are also entities and thus fieldable. By creating a relation type (A [owns] B / B [is owned by] A), I can add a custom field "amount" which holds the information how many Bs are owned by A.

The result (one custom view block added plus a single line of CSS) looks like this.


Is it possible to call a custom module function in the theme template file? I created a custom module and there is a simple hello_world() function. Is it possible to call this function in the page template file?

Module file looks like this.

function choco_custom_newui_total_students(){
return 500;
}

function choco_custom_newui_preprocess_page(&$variables) {
    $variables['total_students'] = total_students();
}

page--front.tpl.php

<? echo $total_students?>

You can do it, but it's not recommended, because in the Model-View-Controller pattern, your logic is in the Controller (in this case your module) and in the View (your .tpl file) you should only have code to show the values that comes from the Controller.
The idea is that all variables are prepared in template preprocess functions (in modules or in your template.php).
You can implement the hook_preprocess_page():
function YOUR_MODULE_preprocess_page(&$variables) {
    $variables['my_var'] = hello_world();
}

and in your page.tpl.php file you can now use $my_var to output the value set in your preprocess function:
echo $my_var;


hook_menu() to display node view mode How to create hook_menu to display node view mode?

node/% - full view mode (default)

node/%/subpage - custom created view mode of this node, for example "subpage"

I've tried this: How to render custom view mode in d7 but it doesn't work. Maybe something is wrong with the code?

There is a module exists that does just that: View Mode Page.

Check it out and inspect the source to see how it works.


how to open a link field in new window in view In views,for image  field, I have selected "output this field as link" and in link path, I wrote "node/[nid]". Link works and open in same window. How to open the link in a new window? I dont see any option in view.

Thanks

1) Click your image field at your views
2) Click Rewrite results. Check Output this field as a link. Key in your URL in the Link Path

) 3) At Target text field, key in this "_blank"


checkbox type in form how i can knowing if the checkbox is checked or not on the form

function darksite_config_page() {
  $form['darksite_status'] = array(
    '#title' => t('Enable pop up screen'),
    '#description' => t('When enabled, a pop up screen will be displayed on the home page.'),
    '#type' => 'checkbox',
    '#default_value' => variable_get('darksite_status', 0)
  );

  return system_settings_form($form);
}

Like so:

if (variable_get('darksite_status', 0)) {
  // Yes.
}
else {
  // No.
}


How do we use drupal_add_library(), drupal_add_css() and drupal_add_js()? How do I use drupal_add_library(), drupal_add_css() and drupal_add_js() in Drupal 8?

I am porting a module that uses those functions. I am following what reported in this post, which says these functions have been removed in favor of #attached, but I am not able to attach these files to my configuration page.

The error I am getting is the following:

  Uncaught PHP Exception LogicException: "You are not allowed to use js in #attached"

How do I attach CSS and JavaScript to a page?

Drupal_add_js() and Drupal_add_css() are quite simple to write in Drupal 8.

We basically create a module_name.libraries.ymlfile having list of all the jss and css that we wish to use.

An example of which is

name_of_the_key: // This would basically work as a key for you.
  version: 1.x
  js:
    js/name_of_your_js_file.js: {}  // Name of your js file
  dependencies:  // Adding dependencies if you have any.
    - core/jquery
    - core/drupalSettings
  css:
    theme:
    css/name_of_the_css_file.css: {} // Name of your css file.

This would basically add all the files but would not attach these files to your page/form.

So in order to attach the js and css to your page/form, you simply replace

drupal_add_js()
drupal_add_css()

with

$form['#attached']['library'][] = 'name_of your_module/name_of_the_key'; // Name of the key would be the key that you have defined in module_name.libraries.yml file.

So if your module uses different js and css file at different points in a forms/pages you could define n number of keys in your libraries.yml file and use it accordingly.

Source: https://www.drupal.org/node/2274843 and guidance form AjitS.


Simple click alternative to Draggable views? I'm trying to find an alternative solution to the Draggable views module. But instead of dragging the rows, you just click some simple up and down arrows once, and you click any of them to reorder them.

Any suggestions?

The standard ordering for lists of nodes or entities in Drupal is first by the "sticky" attribute and then by the created date. Many content modules have some facility to change this ordering, but only for their content type. The modules described in the Community documentation about Comparison of node ordering modules attempt to provide a more controllable ordering in a variety of ways.

Here is the list of modules mentioned in that documentation (quotes are from their project pages):

Outline Designer:

  ... is a user experience module that makes book management more intuitive. Essentially it overlays on the admin book outline page so that you can use AJAX to build and edit site outlines much faster then Drupal traditionally allows.

Weight:

  ... adds a weight option to enabled node types. Nodes with lower weight will float to the top of lists, while heavier items will sink.

Nodeorder:

  ... gives users an easy way to order nodes within their taxonomy terms.

  By default, the taxonomy module orders listings of nodes by stickiness and then by node creation date -- most recently posted nodes come first.

  The nodeorder module gives the user the ability to manually put nodes in any order they wish within each category that the node lives.

Nodequeue:

  ... allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:

  A block listing teasers for the five top news stories on a site
  A user’s favorite music albums
  A group of favorite from which one is randomly displayed

DraggableViews:

  Have you ever rearranged Blocks?, sorted Taxonomy terms? or reordered Menu items at the Drupal administration pages? All these pages use the tabledrag.js javascript that enables Drag'n Drop on HTML-tables.

  With DraggableViews you can apply this tabledrag.js to any Views-generated table.

Flag Weights:

  ... very simple module that adds a 'weight' field to the tables already used by the excellent Flag module.

  This weight can then be used to provide ordering of flagged items. This module also provides a Views field which can be used to sort flagged items. One interesting use of this ability is to integrate with Draggable Views to create a user-sortable list of flagged items.

Sortable Grid Views Plugin:

  ... provides a Views plugin for the user to be able to show a grid composed of draggable elements and save the displayed order of these element.

  The user may then create other displays to show the elements in the order defined above.

  This project is very similar in its goals to Draggable Views, yet a lot simpler as there is no hierarchy management. It doesn't depend on Draggable Views though.

  The added value resides in the presentation, a grid rather than a table list, and the therefore possible uses which Draggable Views doesn't permit.

JQGRID - View integration:

  ... provides views integration for the jqGRid jQuery plugin, which
  provides advanced interaction controls to HTML tables such as dynamic
  pagination, on-the-fly filtering, and column sorting.

  For full documentation and examples, visit the jqGRid jQuery plugin page

Nodeflow:

  ... gives a drag and drop interface for publishing nodes and positioning them in your desired order. This is useful for large publishing sites where editors can get a bird's eye view of all nodes currently on the frontpage and all nodes waiting to be published. A drag and drop interface helps to publish nodes quickly into desired positions.

Queues:

  Adds new Queues entity
  Revisionable
  Support multiple Bundles
  Support reference to any Entity/Bundle
  Full State Machine Support (Queues Workbench)
  Supports Revision Scheduler Module (Queues Workbench)
  Revision Revert Operation
  Revision Delete Operation
  Revision Publish Operation (Queues Workbenc integration)
  Revision Unpublish Operation (Queues Workbenc integration)


Why do OG Vocabulary terms not list content? Drupal 7.41, OG 2.7, og_vocab 1.2.

I've created a group, and a group content type. I added a og vocab to the group and enabled it for the content type. The og_vocab field shows on the node edit page, and the terms in the og_vocab are displayed on the node view. But when I click a term to view all content that has been tagged with that term, the term page does not list any content.

It looks something like:

# Term
Primary tabs
View(active tab)    Edit

There is currently no content classified with this term.

If I do the same thing with a normal vocabulary, the term page does list the content.

I've tried just the taxonomy/term/<term id> path, as well as the alias pathauto generated <og vocab name>/<term name>. Both show the same thing.

As far as I can tell, the only modules that could be overriding the path are views and page manager. I made sure neither was doing so.

So, how do I get the term page for og_vocab terms to list the associated content?

I waited a few days on this to see if anyone posted a solution but no luck..

I've never had any luck with og_vocab and instead use a content type as a group type and use that just like taxonomy. This is possible by using entity reference fields that use entity reference views for values instead of a taxonomy field. But the "taxonomy term" ie. Field value must be set before hand as far as I can tell.

If this solution, and I actually like it a lot, sounds like it could work, I can write up a more detailed guide.


How to make users default in searches? When a user tries to search for another user, the search returns no result, however, when it searches for a node e.g article, questions etc it returns a matching value immediately with search autocomplete. What is wrong?

Permissions are ok and user is set as default in settings. I want users to be able to search users, nodes, location or whatever available and matches their query.

In order to allow non-admin users to search for other users on your site, you'll need to give the appropriate user role (typically "authenticated users") permissions to "view user profiles" and "use advanced search". To access User search, you can utilize the "Advanced search" link in the Search block, or use the URL /search/user

Note, these permissions will also allow users to see other users' profile pages, so make sure this is acceptable for your use case.

If you need to search both nodes and users from the same text box, you'll need more than Drupal's Core search functionality to do so. See How to search both Users and Nodes simultaneously in drupal 7 for some suggestions.


View with nodes but pull only one field from collection I have a node type of photo-gallery. Each node has a field collection which contains multiple photo fields and caption fields. I want to  create a view showing the 5 most recent photo-gallery nodes but I only want to display one photo field from each without the caption field. How would I do this? I can't seem to figure out how to get only one field from the field collection in the view.

There is another solution mentioned in the issue that you reference in your answer that I would say is a good solution.

Add a new view mode. You could use the entity view modes module if you didn't want to code it yourself.
Configure that view mode for your field collection so that it only shows the photo and not the caption.
Don't add a relationship to the field collection because it will cause rows per field collection item.
Configure your view to display the field collection as one of the fields. Select the view mode you created. In the "Multiple field settings" part of the field definition configure it to Display 1 value(s) starting from 0 to just show the first one.


How do I enable recording option in the BigBlueButton module? I am using the BigBlueButton module for conference in Drupal 6. I also installed the server.

The demo code (http://demo.bigbluebutton.org/demo/demo10.jsp) is properly executed. I passed record=true in my API.

How do I enable recording option in the BigBlueButton module?

My problem is resolved. I have pass record=true in setting array of bbb.module file. Please see below code

function bbb_init_meeting($node = NULL, $params = array()) {
  $welcome     = variable_get('bbb_content_type_welcome_'     . $node->type, '');
  $dialNumber  = variable_get('bbb_content_type_dialNumber_'  . $node->type, '');
  $moderatorPW = variable_get('bbb_content_type_moderatorPW_' . $node->type, '');
  $attendeePW  = variable_get('bbb_content_type_attendeePW_'  . $node->type, '');
  $logoutURL   = variable_get('bbb_content_type_logoutURL_'   . $node->type, '');
  $settings = array(
    'nid'          => $node->nid,
    'name'         => $node->title,
    'meetingID'    => bbb_create_meeting_id($node->nid),
    'attendeePW'   => !empty($attendeePW) ? $attendeePW : user_password(),
    'moderatorPW'  => !empty($moderatorPW) ? $moderatorPW : user_password(),
    'welcome'      => !empty($welcome) ? $welcome : t('Welcome to @title', array('@title' => $node->title)),
    'dialNumber'   => $dialNumber  ? $dialNumber  : NULL,
    // TODO: This is limited to 90000 voice bridges and may
    // collide sooner, as rand() may return x twice in a row
    'voiceBridge'  => rand(10000, 99999),
    'logoutURL'    => $logoutURL, //TODO: make absolute, as soon as supported
    'initialized'  => 0,
    'created'      => time(),
    'record' => 'true',
    'duration' => '10',
  );
  $params = array_merge($params, $settings);
  return $params;
}


Advance Poll block keeps caching results We have begun testing the Advanced Poll module. We are having an issue where the results from the very first vote are cached, and then all page views from that point are only the results of that single vote.

I need a way to make sure the blocks for the Advanced Poll are not cached.

We use Memcached, and everything I read on it is vague.

You can try to use Lazy Pane or Block Lazyloader modules to output your poll block. Your block will be loaded from the client side, on demand, via AJAX.


Location City synonym support? I would like to allow users to search node location using location city with synonyms.

For example:

New York
NY
NYC
New York City

etc.

should bring the same search results.

How to do this ?

I have created the related feature request here.

  If this feature is not yet available in the location module, I could
  maybe use Views, create the indexed synonyms as taxonomy terms
  vocabulary and term reference field Content: Location Synonyms,
  modify the view's Global: combine filters filter setting Choose
  fields to combine for filtering as Location: City and Content:
  Location Synonyms? This would require tagging each node location
  synonyms manually or would require setting up a Rule (using Rules
  contrib module) that would add these synonyms automatically depending
  on the Location: City selected. The standard Drupal search would
  index these tags.

  It would be better to have it either inside the Location module or as
  an additional contributed helper module.

There is also a contributed module Location Taxonomize that might help in achieving this.


Event registration for events with multiple dates/places I'm making a event content type (representing academic conferences) for a Drupal 7 site, and I'm thinking of give visitors the posibility of registering in these events.  But in some cases, these conferences can occur several times, in different dates and places. When registering, the registrant must choose in which date/place he wants to go.

For now, the date/place pairs are being stored in the event via a Field Collection. I've also checked two common modules for registrations in D7: Node Registration and Entity Registration.

Right now I'm thinking in 2 alternatives to implement this:

Several registrations forms per event, one for each date/place:

Pros:

I could (in theory) manage each presentation separately, with different capacity/end of registration date.

Cons:

As now, I don't find a module that permits multiple registrations in a node. (custom code?)

One registration form per event, with a list field that permits to choose the date/place

Pros:

Implementable right now through Node Registration module + private fields per node

Cons:

I can't manage capacity/end of registration date separately, and when the end date of one presentation comes, I must update the list field manually (custom code?)
The list options are defined per field (not by field instance) so I have to create a new field on each event that has multiple dates/places (each one with different machine name. Consider this is going to be done not by site admins, but event organizators with its own user role)

Is there another way to implement this feature? An module I haven't found? A hidden feature or creative use of Node/Event Registrations? Custom code/module?

I would suggest that you create two different content types. Event Display and Event Entity

Event Display : Will be just used as a placeholder or display item. It will contain all jazzy text fields and images. It will also contain Node References to the Actual Event Eneities.
Event Entity : This will just contain Location, Date and Capacity.

Now Enable Entity Registration for the content type Event Entity.

Suggestion : Use Inline Entity Form so that you can edit the Event Entities directly from the Event Display Content.


Remove language prefix from base URL I've installed the Internationalization module in order to make a multilingual site, I've set italian as default language, but there's a problem, the front page is always in english. I've checked the base URL and I've noticed that there's a language prefix, is it possible remove?

Sometimes I think people do not know how to use search in our time.
You can find the answer on stackoverflow, similar question has already been asked. Have a nice day.


How to add large self hosted videos to Drual 7? The Video module for Drupal 6 has an option to use videos uploaded through FTP. The Drupal 7 version does not have that option. How can I embed large self hosted Video files?

To answer your question: Use the contributed Drupal 7 Video module.

You will likely need to configure your server to allow for large file/video uploads.

I currently allowing video uploads that are up to 1GB using only the Video module, FFMPEG and a few helper modules to manage the 'video processing' workflow.

Most likely you will need to modify your PHP.INI file to allow large uploads.  Specifically max post size and max upload size.

As for a widget that allows you to select a file uploaded via FTP, I see several issues in the Video modules issue queue that look relevant, but no solutions seem to be offered.

This question was also un-answered months ago.  If FTP is a requirement you may need to write a custom module or contact the Video modules maintainers for a status update.


Removing prefix for default language breaks all the link Since I built the site I always used language prefix "en" for my site. English is my default language.

The thing is our SEO Expert said that this is content duplication for Google and we might get Panda penlty. Thus I removed "en" for English and now all my links are broken.

Thus, is there any way to do following:

*http://www.xyz.com/en/*business-opportunities/zimbabwean-supplier-beverage-flavourings-calls-financiers

automatically redirect it to "*http://www.xyz.com/*business-opportunities/zimbabwean-supplier-beverage-flavourings-calls-financiers". So that I can save

Google into htaccess rules if you have the apache module mod_rewrite on the apache server (if it's an apache server you're using), you can make redirections based on REGEX patterns, so there's a little work for you there....


How To Override Webform's Submission Template in Drupal 8 The template provided by the Webform module for theming a submission is rather plain. Basically, it looks like a print_r of the data variable. If you try to add HTML to validation function before it gets submitted, the HTML just gets rendered as plain text.

So I was trying to find a way to override the template from a module as opposed to a theme. I'm not able to find much documentation for this right now.

How do I override webform's default submission HTML template from a module?

Create a custom module and in the custom.module file add this code:

/**
 * Implements hook_theme_registry_alter
 */
function custom_theme_registry_alter(&$theme_registry) {
  $theme_registry['webform_submission_html']['path'] = drupal_get_path('module', 'custom') . '/templates';
  $theme_registry['webform_submission_html']['template'] = 'custom-submission-html';
}

You should have in the custom module your template at the location custom/templates/custom-submission-html.html.twig

The contents of that Twig file look like this.

{{ data }}
{{ data.r }}
{{ data.n }}

You can add HTML that suits your specific case.


Drush sql-dump with stored procedures According to the current documentation I don't think this is possible, or is it?
(drush sql-dump --routines doesn't work or anything like that)

Aaaannndd... let's say it's not possible, and I want to add this feature to drush sql-dump command, how can I do that? Where should I start?

I got it working for MySQL with the extra option:

$> drush sql-dump --extra="--routines"

References:

Drush command: https://drushcommands.com/drush-8x/sql/sql-dump/
MySQL dump options: https://dev.mysql.com/doc/refman/5.5/en/mysqldump-stored-programs.html


Custom made blocks not getting displayed in Blocks page I am new to Drupal. I tried to write custom module(Sample).. After completion of Module, Enabled at Module. But it is not showing at Block Page.

Please check the below code and correct me..

first.info

;$Id$

name = First
description = A first module.
package = Drupal 7 Development
core = 7.x
files[] = first.module

;dependencies[] = autoload
;php = 5.2

first.module

function first_block($op = 'list', $delta = 0, $edit = array()){
    switch ($op) {
       case 'list':
        $block = array();
        //List out all blocks you want to create here
        $block[0]["info"] = t('Display info');
        return $block;
       case 'view':
        switch ($delta) {
          case 0:
            $block['subject'] = "ADMIN Header of the block";
            global $user;
            if(in_array('Site admin', array_values($user->roles) || $user->uid == 1)) {
              $block['content'] = "input form";
              $block['subject'] = "Header of the block";
            }
            return $block;
        }
    }
}

Did you try to (steps in order):

use a minimal hook_block_info() definition for your block (such as
the one below or even without 'cache' option!) the very first time?
manually remove your block's entries in block table, if any?
then clean all caches?

Longer version of why these steps may help:

Using a minimal block definition such:

function sso_block_info() {
  $blocks['applinks'] = array(
    'info'   => t('Single Sign On'),
    'cache'  => DRUPAL_NO_CACHE, // this can also be left out!
  );
  return $blocks;
}

Would not list my block in the "Disabled" pseudo-region of admin/structure/block!

Troubleshooting revealed that block had been inserted in block table, but its value for the region column was blank and not the usual '-1' that every other currently disabled block contained!

Tip: updating this value to -1 directly within DB made block 'Single Sign On' show up in block admin's Disabled zone instantly!

Then I manually removed my block's entries from DB and cleaned caches to effect Drupal calling again hook_block_info. This time my block showed up correctly in block admin UI the first time!

My hunch is that existing config entries in DB for blocks will sometimes interfere with what is indeed correct block registration code! Cache clearing will not affect entries in block table! I guess that certain perhaps invalid combinations of options in hook_block_info() will cause D7 to register a block with a blank value for the region (a block appears in) instead of -1 (a disabled block).


How to build a dynamic user-page from LDAP (Active Directory) and show this page after logged in? I have Open Atrium 2 with Drupal 7. User are able to login over the active directory using the Lightweight Directory Access Protocol (LDAP) module, which works pretty well.

After login the user should come to its own personal page. In which the user can see his/her personal data and so on. But how to create a dynamic page like a template for this personal page?

I couldn't find any similar on the net. Any help I would appreciate.

Edit:

My first step is: After Login over LDAP (active directory) getting all personal data and lead every person to his own page with all this personal data in it.

Can I do this with some appropriate modules or do I have to script this in php or a mix of both (scripting and modules)? And which modules or plugins for Drupal with Open Atrium 2 can help me to get this?

After login the user should come to it's own personal page.

Whatever page you want to send the user too (different from the default user profile page) can be achieved by using the Login Destination module:

  The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.

Then you said:

  In which he can see his personal data and so on. But how to create a
  dynamic page like a template for this personal page??

You didn't mention if this page should be the user's profile or a different page simply showing all the account details from LDAP (and possibly other pieces of content). You can embed the user profile on any path you want, see similar question(s) and example solutions at:

How to show custom user profile fields in a view?

Or, you can create a View that uses an LDAP Query and simply show information from LDAP on a custom view page, which the ldap module supports. See the LDAP Query documentation.


How to update a record with drupal_write_record? I do not understand how to update a record with drupal_write_record.

I want to update column "vid," in table "node," with the value $value, where "nid" equals $key.

This is what I have, and it doesn't look right, nor does it work. I can't find any examples.

$table = 'node';
$record = new stdClass();
$record->vid = $value;
drupal_write_record($table, $record, array('nid' => $key));

To be clear: I want to insert $value into column "vid" where the value $key exists in column "nid"; this is all happening in table node.

drupal_write_record updates an entire record, not a single column. With drupal_write_record you could do this.

$node = node_load($nid);
$node->vid = $vid;
drupal_write_record('node', $node, 'nid');

But dealing with nodes, you can use node_save instead, which also handles saving fields and other data. Using node_save is recommended way of saving alterations to a node, since it also deals with revisions issues along with fields, hook notification ect. It's simple to use:

$node = node_load($nid);
$node->vid = $vid;
node_save($node);

If you want to update a single value in a datebase, you can use SQL (db_query) or the db_update function which is two ways of running SQL on your database. The db_update utilizes the Drupal query builder, and will work on any database backend the Drupal supports (now and in the furture):

db_query("UPDATE {node} SET vid = :vid WHERE nid = :nid;",
  array(':nid' => $nid, ':vid' => $vid)
);

$num_updated = db_update('node')
  ->fields(array(
    'vid' => $vid,
  ))
  ->condition('nid $nid)
  ->execute();

drupal_write_record will itself use db_update, a snippet of the code looks like this:

$query = db_update($table)->fields($fields);
  foreach ($primary_keys as $key) {
    $query->condition($key, $object->$key);
  }

Which basicly creates an update query, updating all of the fields, and using all of the values set in primary key as the condition.