Webform2pdf - Message body empty I'm trying to use webform2pdf to generate a pdf containing form inputs. The form works fine if I don't check "Generate PDF Document", and I receive a confirmation email.

If I do enable the PDF, I don't receive a confirmation email and I get the following error:

  Unable to send e-mail. Contact the site administrator if the problem persists.

In the smtp log I see:

phpmailerException: Message body empty in PHPMailer->Send() (line 577 of /var/www/clients/client1/web1/web/sites/all/modules/smtp/smtp.phpmailer.inc).

Is there additional configuration I need to make? Drupal is new to me.

Drupal - 7.54
Webform - 7.x-4.15
Webform 2 PDF - 7.x-4.0
SMTP Authentication Support - 7.x-1.6
MIME Mail - 7.x-1.0
TCPDF - 6.2.13

** Edit **

Turning off SMTP Authentication Support and using DefaultMailSystem solved this particular issue and allows PDF attachements, although DefaultMailSystem only allows plain text emails.

Webform2PDF has dependencies, did you install them?

  Third-party tools:

  TCPDF

  4.5.000 or later required from webform2pdf 2.x or 3.x
  6.0.000 or later required from webform2pdf 4.x


unable to set CONTEXTUAL FILTERS according to Raw Value from Url In my project having two type of Content Type 1) Artist and 2) Work

I have added the content for the Artist and now also i have added  the content for the Work according to Artist Name having field name (Artist field_artist    Entity reference)

On view Page i want to show the result according to the artist

http://localhost/drupal8/artists-works/robert

According to name robert i have set the CONTEXTUAL FILTERS and Relationship.but its not showing any result
when removed the filter its showing all the work content type type
How can I set CONTEXTUAL FILTERS and Relationship according to this

You need to add a relationship to the content, and use the title (or whatever field contains "robert") as the contextual filter instead.

Currently the query that's getting built is trying to find content with an ID of "robert", which won't work as nid is numeric.


How can I include php file in my module without using composer? I want include PHP file in drupal 8 module.
What is the best way for it ?

Outside of autoloading, the only option Drupal provides itself is module_load_include(), which literally

Loads a module include file.
Examples:

// Load node.admin.inc from the node module.
module_load_include('inc', 'node', 'node.admin');
// Load content_types.inc from the node module.
module_load_include('inc', 'node', 'content_types');

The final part of the description is worth taking in separately as it's important:

Do not use this function to load an install file, use module_load_install() instead. Do not use this function in a global context since it requires Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file' instead.

It's also worth noting this function won't be around forever, the plan is to move it completely into the module handler service.


How to limit access for some special user to a single (Views) page? I'm using Drupal 7.43 and I have to create a special user, with access to a single page (a Views page) and nothing else.

What would be the best approach for this situation?

Note: The view is already made (I show a custom content type made in a custom module). The website is private (the only thing an anonymous user can see is the login page).

Not sure if it is the "best" approach, but for sure a "possible" approach for this would be to use the Rules module for this. All you'd have to do is to create a (rather basic) rule like so:

Rules Event: Drupal is initializing.
Rules Conditions (both must be true):

Check if the user's Id (uid) or user's name matches your "special user".
If the URL being accessed (= "site:current-page:url") does NOT match with the URL of your  "single (Views) page"

Rules Action: Perform a redirect to your "single (Views) page".

Done ...

Happy Rules-ing!

Note: Obviously, this rule only takes care of what that special user is allowed to use as URLs (while logged in). If that user does not login (yet) or logs out again, then anything an anonymous user is allowed to navigate to will also be available to this not-yet-logged-in-user. For whatever that is not allowed as an anonymous user, you must ensure that the permissions for anonymous users are set to deny such access.


How to render Views anchors with `title` attribute? By default the Views module doesn't put title attributes on anchors as it only puts them on anything that has an alt attribute.

Seeing as you're not likely to have an alt attribute on a standard anchor. Could someone please advise what you need to do in order to render Views anchors with title attribute?

You can do this:

In your Content: Title expand Rewrite Results and check Rewrite the output of this field

In the Text field enter: [title]
This will create your anchor jump point.

Next you can add a block and repeat the same process replacing Text field with [title]


Using tokens with entities? I'd like to be able to use tokens with entities, similar to how they work for node right out of the box with core.  However, for whatever reason, entity tokens are not available to me even though I have Entity API and Entity Token enabled.

Is there something that needs configuration?  I see no way to configure Entity Token.

The problem was that theme_token_tree($variables) was being passed only a subset of available tokens.  Just a gotcha to look out for if you haven't done work with the token tree before.

$variables = array('token_types' => array('nodes','comments'), 'global_types' => FALSE);
theme_token_tree($variables);

I needed to add additional token types to the token types array, like so:

$variables = array('token_types' => array('nodes','comments','bean'), 'global_types' => FALSE);
theme_token_tree($variables);

You can also go to /admin/help/token to get a list of all available tokens.  Be warned though, unless you have enough memory allocated to MySQL it could consume all of it and give you a "MySQL gone away" error.  I received that error and I upped mine to 500MB locally and it was fine after that.


How to get exact value of a field from database? I want to get value of a field, but I need the value that is saved in database, not the value that may be changed by hook_node_load. Is there a way to do this?

If there is no function for this purpose, which query should I use to get the field value?

I'm not sure there's an API function to get this directly; the field functions (like  field_get_items()) seem to rely on a loaded entity object, which in the case of a node would have gone through the whole loading process.

If you want to get the value directly you'll find the data in the field_data_field_* tables. A query like the following would get the data for a node of type 'article', assuming a text field called 'field_my_field' with a column name of 'value'. It also assumes the field is not multiple; if it is you'll need to remove the last line of the query and loop through $val instead:

$val = db_select('field_data_field_my_field', 'f')
  ->fields('f', array('field_my_field_value'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'article')
  ->condition('entity_id', $node->nid)
  ->execute()
  ->fetchField();

If you've got node revisions turned on for the content type in question you'll probably need to alter this to query the field_revision_field_my_field table instead, and use the node revision id (vid) instead.


Is it possible to set Cookie Session ID from a REST Service? I have overridden Drupal's login process by calling a REST API which returns a 'true' or a 'false' depending on whether the login was successful or not. Once successful, I'm logging the user in by using a particular Drupal user account.

Would it be possible to change Drupal's Session ID to the one specified by the REST API call? Currently the REST API Call is giving me a JSESSIONID cookie and I was wondering if its possible to map this cookie to the one Drupal generates when the user logs in. Reason I need this is because I need keep track of this JSESSIONID to call other API methods related to the logged in user.

You cant save off the JSESSIONID into the user attributes, eg data column, in D6 or D7. You simply do this in your code with:

$_SESSION['JSESSIONID'] = /* some value here */;

or wherever you call user_save() in your custom login you can pass $edit['data'] = array('jsessionid' => 12341234); from the user_save documentation:

  $edit: An array of fields and values to save. For example array('name'
  => 'My name'). Key / value pairs added to the $edit['data'] will be serialized and saved in the {users.data} column.

it then becomes accessible from a fully loaded $user object as simply a field of the user ... $jsessionid = $user->jsessionid; and you can use it as needed.


Insert html in views every nth element I want to insert

 every nth element. How can I insert this into the twig template of a view?

Same Question for D7: Insert *whatever* every nth row in Views

In twig you can use |batch().

For example to group the view in groups of 5 and add a div container around each group:

views-view-unformatted.html.twig

{% for group in rows|batch(5) %}
  <div class="group">
  {% for row in group %}
    <div{{ row.attributes }}>
      {{ row.content }}
    </div>
  {% endfor %}
  </div>
{% endfor %}


Is there a way to programmatically add new links to the primary links? Is there a way to add links to the primary links using PHP in Drupal 6? The reason I ask is that I want to add more links in the footer of the web page, which I don't want to put in the top navigation level.

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

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


How to use profile2 profile type in custom form? I'm building a multi step sign up form for my drupal 7 website, so I want to use one of profile type from profile2 in first step.
For such purpose I'm using this code:

function personal_info_form($form, $form_state) {
    $form_state['profiles']['main'] = profile2_get_types('main');
    profile2_attach_form($form, $form_state);
    $form['#validate'][] = 'profile2_form_validate_handler';
    $form['#submit'][] = array('profile2_form_submit_build_profile', 'profile2_form_submit_handler');
    return $form;
}

But still getting error, you can visit this page to see the exact error
http://dev.BlindHelp.net/user/register . Any help?

i Suggest to use hook_form_alter or hook_FORM_ID_form_alter to perform specific task of existing form of profile2.

function mymodule_form_alter(&$form, $form_state, $form_id)  {
    switch ($form_id)  {
        case 'comment_form_id':
            $form['your_comment_form_name'] = array (
              '#type' => 'checkbox',
              '#title' => t ('Subscribe to replies to this comment'),
            );
            break;
        case 'user_register_form' :
           $form['actions']['submit']['#value'] = t('Submit');
           break;
     }
  }


Insert region into html.html.twig Is there any way to add a region into html.html.twig? I want to have one inside  tag to be able to render different js counters through Block Layout

So, the solution is to add a new region into your theme.info.yml (say before_body)
Then the code you'd place into theme_name.theme be:

function theme_name_preprocess_html(&$vars) {
  /**
   * moves region before_body into before_body var inside basic html
   */
  if (isset($vars['page']['before_body'])) {
    $vars['before_body'] = $vars['page']['before_body'];
}
function theme_name_preprocess_region(&$vars){
  /**
   * Cleans before_body from standard html markup
   */
  if ($vars['region'] === 'before_body') {
    $vars['content'] = theme_name_clean_special_content($vars['content']);
  }
}
/**
 * Cleans content from basic markup
 * @param $content
 * @return \Drupal\Component\Render\MarkupInterface|string
 */
function theme_name_clean_special_content($content) {
  /** @var \Drupal\Core\Render\Markup $content */
  $content = preg_replace('~<\/?section.*?>|<h\d?.*?>.*<\/h\d?>|<\/?div.*?>~', '', $content);
  $content = preg_replace('/(?=<!-- (THEME DEBUG|BEGIN OUTPUT|THEME HOOK|FILE NAME SUGGESTIONS|END OUTPUT))([\s\S]*?)-->/i', '', $content);
  $content = preg_replace('/((\r\n|\n|\r)$)|(^(\r\n|\n|\r))$/m', '', $content);
  return \Drupal\Core\Render\Markup::create(trim($content));
}

Just don't forget to add before_body variable into your basic html template.


Programmatically set updated time on node I'm creating duplicates of nodes by doing

$node->createDuplicate();

It duplicates all the values of all the fields but but it duplicates the created and updated time as well. I want both of those set to now. I know how to set the created time.

$clone->setCreatedTime(time());

However there doesn't seem to be a function or a property for setting the updated time. I read up on the source code of the Node class but couldn't find any mention of it.

Is there any kind of method where you can set the updated time of a node?

I think you can change the value by accessing the variable and saving it then

$clone->changed->value = time();
$clone->save();


Clear Cache without logging in I added an if statement around the content render php in my page.tpl.php file. Only problem is I made a mistake and accidentally prevented it from rendering content on any page. I cleared the cache and logged out to test it, and realising my mistake I corrected the template file. But now I can't log back in to clear the cache again as my site won't render content and thus won't render the login box.

Can someone give me a way in Drupal 7 to either log in without the login in box (like a way to render the login box separately to the content) or a way to clear the cache?

i. If you have drush installed (http://drupal.org/project/drush) — if you don't have it, think about that next time :), open up the console (WIN+R) in Windows or Ctrl+Alt+T in Linux point to your site folder (e.g. cd /www/mydrupalsite/ and type:

 $ drush cc all

from the command line.

ii. Another method is to log into your phpmyadmin select your cache_ tables and flush/empty  them.


Symfony's getQueryString method doesn't return modified query parameters Symfony's getQueryString method doesn't return modified query parameters.  So how should someone go about getting a modified query parameter string?

Example code:

   $request = \Drupal::request();
   $parameter_bag = $request->query;
   $parameter_bag->remove('destination');

   $query = \Drupal::request()->getQueryString();
   $query_array_modified = $parameter_bag->all();

$query in this instance will return the destination query parameter even though it was removed from the ParameterBag.  $query_array_modified in this instance will not return the destination query parameter ... as expected.

PS - Feel free to replace \Drupal::request(); with Symfony's request object in example code below if you are using Symfony.

Symfony's Request object has a query property that is of type
ParameterBag, this maintains an iterable list of parameters.  The ParameterBag however is not directly translatable to a query string.  This causes issues when trying to use the getQueryString() method after modifying the ParameterBag parameters.

Solution 1 - Create a new query string:

   $request = \Drupal::request();
   $parameter_bag = $request->query;
   $parameter_bag->remove('destination');

   // This has to be http_build_query() because
   // \Drupal::request()->getQueryString() returns the original query string
   // but here we need the modified query string (without destination).
   $query = http_build_query($parameter_bag->all());

Solution 2 - Update all global variables:

    \Drupal::request()->query->remove('destination');
    \Drupal::request()->overrideGlobals();
    $query = \Drupal::request()->getQueryString();

Reference to overrideGlobals()

The main issue is that getQueryString() returns the global server variable query string which doesn't reflect changes to the parameter bag.  So editing the parameters is not as straight forward as it used to be.  We either have to build a new query string or override ALL global variables.  In my particular use case I thought that overwritting all globals was too wide reaching and it would overwrite any changes that other modules implemented that our specific code has no control over so I went with solution 1 above as it is generally a safer piece of code to implement.

My two options for solving this the right way is that:

1) ParameterBag either needs a method to build a query string

2) The request object needs to be able to return modified query parameters.  Probably by deprecating / defaulting the existing function to returning the output of a new function called getQueryStringOriginal() and creating another new function called getQueryStringModified().


How to register a theme function from the theme I want to introduce a custom theme function in my theme.  Typically, I would register a theme in hook_theme() in a module, but I want to define this function from my theme (Omega 4).  In whatever module I'm in, I'd like to just build my render array and let it be themed by the theme-side theme function.

Example:

$ra = array(
    '#theme' => 'my_theme_fx',
    '#somevar' => 'foo',
    '#anothervar' => 'bar'
);

The description of hook_theme() is:

  Register a module (or theme's) theme implementations.

So you can implement this hook in your theme.


Searchable exposed filters on views I have an exposed filter of a taxonomy vocabulary (localities) and I want the user to be able to search on it in order to find the desired values more easily.

I am using BEF at the moment. I found the jquery ui multiselect widget but it does not seem to work with views filters.

Thanks

Check this answer.

I also faced same kind of issue and I followed the below url  and its worked for me

http://codekarate.com/daily-dose-of-drupal/drupal-7-views-autocomplete-filter


how to add "create node form" in a block? I just wanted to know how to add "create node form" in a block

when i  copy the source code and make a block out of that code, only public could post from that.
when i am posting as a user it says timeout and tells us to refresh the page.
plz someone give me solution.

SO i tried to add the following code in page.tpl.php

$form = node_add('nodetype');
print drupal_render($form);

there are two modules which can give option to create node from block
Formblock module ,
Advanced Form Block


Hide the  item in the main menu I want to remove the link to the homepage from the main menu.

I can delete it with:

menu_link_delete(NULL, "<front>");

But I am worried about needing to undo that at some point in the future, or causing problems when some module expects that link to exist.

It looks like menu_link_save allows marking a menu item as "hidden", but I can't figure out how to get the mlid so that it knows I want to edit an existing menu item.

I have tried calling menu_main_menu, but the result doesn't appear to have a main_menu['<front>'] element.

Any suggestions?

Using the Features module let me export the menu, at which point it was easy to set 'hidden' => '1' on the 'main-menu:' link.


How to get query result in devel? In Admin we have

http://domain.com/devel/php

I added query

$result = db_query("SELECT name FROM `users_field_data`");

print ($result);

It's not showing result. How to show that?

Enable the Kint module (comes with devel) then do

kint($result->__toString()); or kint($result->arguments());


Responsive grid in view layout I think it's an easy question but I just can't solve it.

I use responsive grid type in view to show a content type named "clinic information",and it is.

I want a row only have two clinics and the five-stars are beside the information(picture,phone number...), not below, how can I make it?

(picture, name, address, phone number, five-stars are clinic information in one content in a grid)

The important thing to make this work is the theme that your using; the Views Responsive Grid doesn't do much by itself with regards to styling but it allows you setup you view to apply the appropriate CSS class from your theme to make your display responsive.

You are using the Corporate Clean theme but it's not a truly responsive theme from what I can see from its layout CSS. You can still have that layout that you want for one screen type so that will be what I will show you here.

Change your view's format to Responsive Grid

Next change the settings for the Responsive Grid format to have  2 column in horizontal alignment and the class grid_6 to every column. You can also use grid_4 if you have a sidebar on your page.

Then change the Format's Show options to fields.

Now in the fields section add all the fields that you want to display. For example, I have the fields title, body and post date.

The next step requires you to add some custom html/css; normally advanced view display formats such as Views Bootstrap would have different options to display your fields. For example, had you been using a Bootstrap based theme the Media Object format would have served you well.

However, since you are using something different, I would recommend you override the out of the fields as follows.

Hide all but the last one of your fields by clicking on each field and checking the "Exclude from display option".

For the last field override its display by clicking on it and going to the Rewrite Results section. In the text box provided add in your custom HTML markup with along your fields using tokens provided by views.

In you theme make sure to add proper CSS classes, i.e, in the example HMTL I'm showing you should have the classes clinic, clinic-thumb and clinic-details. These should have the styling in such a ways that the clinic class clear floats, the clinic-thumb and clinic-details classes should have floats and respective widths.
Example CSS:

/**

.clinic has a clearfix taken from this page
*/

.clinic:before,
.clinic:after {
    content: " "; /* 1 /
    display: table; / 2 */
}
.clinic:after {
    clear: both;
}
/**

For IE 6/7 only
*/
.clinic {
*zoom: 1;
}

.clinic-thumb{
 width: 35%;
 padding-right: 5%;
 float: left;
}
.clinic-details{
 float: left;
 width: 60%;
}

If you followed my example you should get something like this:

Hope this helps!


"Drupal\Component\Plugin\Exception\PluginNotFoundException: The 'integer' plugin does not exist." When I try to update from drupal 8.27 to 8.35, I get the following error. How can I resolve this issue?

  Failed: Drupal\Component\Plugin\Exception\PluginNotFoundException: The "integer" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of C:\Users\ven_arajendra\Sites\devdesktop\offshore2-dev\docroot\core\lib\Drupal\Component\Plugin\Discovery\DiscoveryTrait.php).

As an option just try to add this code in the enabled custom module in your project.

/**
 * Implements hook_entity_base_field_info_alter().
 */
function custom_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
  if ($entity_type->id() === 'menu_link_content' && isset($fields['weight'])) {
    $options = $fields["weight"]->getDisplayOptions('view');
    // Lets check if field definition is buggy.
    if ($options['type'] === 'integer') {
      $options['type'] = 'number_integer';
      // @TODO: This should be fixed in the menu_link_content core module.
      // @see https://www.drupal.org/node/2903161
      $fields['weight']->setDisplayOptions('view', $options);
    }
  }
}

Or try to use this patch from this issue


Multiple instances of item in View row I am getting five instances items in my View row when I wrap image field inside my link field. This is what I have in the template file:

    <?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php //print $field->content; ?>

            <a href="<?php print $fields['field_news_link']->content; ?>" target="_blank"><?php print $fields['field_news_image']->content; ?>
            <?php //print $fields['field_news_image']->content; ?>

        <a href="<?php print $fields['field_news_link']->content; ?>"><?php print $fields['field_news_source']->content; ?>

  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

If I uncomment <?php //print $field->content; ?> and remove the linked image and the rest of my mark up, I don't get multiple instances of the item.

The field template prints all the fields as a row. If you want to output the row of fields manually you need to remove the foreach iteration of the fields.

See views-view-fields.tpl.php for more info.


How to hide a form field in hook_node_view() function hook_node_view($node, $view_mode, $langcode) {
// How can I hide a field in the hook_node_view() using $node
// In my case the field is an image file field
}

You can't. hook_node_view() exists only to

  Act on a node that is being assembled before rendering.

It can't be used to alter the node's edit form.

You need to use hook_form_alter() or hook_form_FORM_ID_alter(), to alter form elements e.g.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form' && $some_other_condition) {
    $form['some_element']['#access'] = FALSE;
  }
}


List of referenced entities appended to a node I have two content types: "project" and "task"
Using flag and with support of entity reference + flagging form, users can append very rapidly new "task" nodes to the current "project" node they are viewing.
The structure then is the following:

Node type 1 >> project
Node type 2 >> task
Flag >> task appended to project; actually is a "container" of an Entity
Reference(with multiple value) field linked to task

My target is create with views, a list of appended "task" nodes and show that list in a block to the related "project" node.
I believe that I should use relationship + contextual filter, but I have no idea on how to achieve my needs.

Could you help me? Thank you all in advance!

Update on 13-01-2017 16:45:
Attached step by step after suggestion from pierostz. These steps were done before the configuration window uploaded at 15:00.

Update on 13-01-2017 15:00:
Attached contextual filter Nid after a first aattempt after suggestion from pierostz.

Create a new view showing tasks nodes. In your view use these settings.

Add a relationship "Entity Reference: Referencing entity".
Add a contextual filter of "Content:nid" with the relationship you previously created as the selected option on the relationship select box. Also provide the default value from "Content ID from URL".

Create another contextual filter with "Content: References".
Choose what fields to show as you normally do in a view.

I think this should do the trick.


Need to add HTML characters to Select list I have a form using the FAPI that has a select list of currency values as one of its inputs.
I need to be able to add HTML characters such as &euro; $pound; &yen;

The problem is that Drupal is filtering the input and not displaying the desired symbols, but displaying the actual html codes as displayed above.

Is there any way of having Drupal not filter my list?

You can and should put the UTF-8 characters for the symbols in your list. HTML entities are a relic from the past when it was possible that some symbols did not have a representation in the active code page. Thus simply use €, £, and ¥ in your lists.

Drupal is UTF-8 from back to front: use it.


How to make an entity reference field required using states I need to make an entity reference field in my form be required based on the state, the code below is working with other fields, but not my entity reference field.

$form['schedule_publish_date'] ['#states'] =  array(
 'required' => array(
  ':input[name="moderation_state[0]"]' => array('value' =>"published"),
 ),
);

this is the source code of the entity reference field. Am I putting in the wrong name for the form item?

<fieldset data-drupal-selector="edit-schedule-publish-date" id="edit-schedule-publish-date" class="js-form-item form-item js-form-wrapper form-wrapper">
  <legend>
Schedule Publish Date

the moderation state is not what I am having trouble reaching. It's the schedule publish date, which is an entity reference and doesnt become "required" when it should.

There isn't a specific form element with the moderation state, since they are added as action submit buttons, but you could add one like this:

  if (!empty($form['moderation_state']['widget'])) {
    $form['moderation_state_hidden'] = [
      '#type' => 'hidden',
      '#title' => 'moderation_state_hidden',
      '#value' => $form['moderation']['widget'][0]['#default_value'],
    ];
  }

Then you could refer to it in your states array like this:

$form['schedule_publish_date'] ['#states'] =  array(
 'required' => array(
  ':input[name="moderation_state_hidden"]' => array('value' =>"published"),
 ),
);

But using states doesn't really make sense because you can't change the moderation status of a hidden field or a non-ajax submit button.

So in that case, you could just update the form element to be required

  if (!empty($form['moderation_state']['widget']) && $form['moderation_state']['widget'][0]['#default_value'] == 'published') {
    $form['schedule_publish_date']['widget'][0]['target_id']['#required'] = TRUE;
  }


What is the proper way to uninstall a module that adds a content type I heard that when uninstalling a module that is a content type, you should not use node_type_delete('my_module') in hook_uninstall(). Instead, you should let it be handled by Drupal that just disables the content type in the database. Is this right?
Apparently Drupal handles it in hook_node_info().

Wouldn't it be better to delete this node type in the database, or does Drupal handle uninstallation process in an other way?

I am using Drupal 7.

You should not delete content types in hook_disable(). Instead, you should make sure callbacks are left sane, and all data you will need on hook_enable() is properly archived and secured from modification by other modules. Good idea is to use drupal_set_message() to warn about content type that should no longer be used or displayed, but that's site admin's responsibility.

On hook_uninstall() you are supposed to left the database as if your module was never there. Thus, feel free to delete content types that was created using node_type_save(), if there are any. The ones created with hook_node_info() will be deleted automatically. Again, setting message about orphanted content is good idea, but it's site admin's responsibility not to uninstall module he is still using, after all.

If your hook_node_info() defined content type is not deleted, just disabled, you can decide to explicitly delete it, but you are responsible for cleaning all the mess it may cause, like orphaned content. You risk serious site failure if you don't.

Edited to incorporate information from Clive's comments under other answer


Use another token value if the first one is empty I am using the [message:user:profile-fname] token to get the first name of the user, but some users are without first name; the value shown for that token is a blank string.

How can I use another token (e.g. [message:user]) if the first token is an empty string?

Seems like there was Token Logic module, once upon a time, and it got abandoned: https://drupal.org/node/354039

You can try and wrote your own token to fill that niche, or contact original's authors.


How to add a confirmation form upon submission of user profile form I have previously added a confirmation dialog to my own forms using a technique like http://blog.purdy.info/2014/04/how-to-work-with-confirmform-in-drupal-7.html.  However this assumes that you have control of the form builder and submit functions.  I now want to add a confirmation to the user profile form which is of course defined in the user module.

Any suggestions ?

Thx

You can add your own submit handler in front the of the predefined submit handler using hook_form_alter().

The #submit property is an array of submit handlers and it allows multiple values. Use array_unshift() to put your handler in front of the predefined handler.

Your code will look something like this:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id){
  if ($form_id = 'target_form') { // make sure it's the right form
    // add my handler
    array_unshift($form['#submit'], 'my_submit');
  }
}

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

When the form is submitted, it will run my_submit() before the predefined submit handler.


Show audio file but require registration - suggestions for approach? I am converting my guitar lessons site to drupal. On my previous site, I displayed an audio link, and upon clicking it, one could play the audio if they were registered. If not registered they were taken to a page asking them to register, then redirected to the lesson. The audio was in a protected folder. I am trying to do similarly in drupal. Any tips on how to get started? I am new to drupal...

Here is what I think would be ideal:

For the lesson page, use selection rule (via panels, views, or whatever) to display the embedded audio for the registered user
For guest user, display the embedded audio player but via guest class use javascript so when they press play they are redirected to register page, then have them register with captcha then redirect to lesson page. Or simpler, for guest user, just display a "play" icon that takes them to register page.

Ideas?

Regards

You could create a views block for the anonymous user.

1) add a content path field

2) Under Rewrite results, rewrite the content path field and use it's token.

Ex:

Note: (the ?destination= tag, will send them to that page after registration).

3) Change the view access from permission to role and select anonymous user.

4) Add a contextual filter of nid(node ID), select provide default value, select content ID from url.

Then you could use panels, a block, or a view block, then just give it a role of authenticated and put your player there.


How do I get the user avatar picture? I am working on a custom Drupal 8 theme and I am trying to get the user avatar picture on a variable and output somewhere in the HTML.

I have created this function to get the name & email of the current user logged in like so:

#Function to get the user name value & output in the HTML DOM
function tropical_preprocess_page(&$variables){
  # gets current user name
  $user_logged_in_name = $variables['user']->getDisplayName();

  # creates value to ouput in the DOM & capitalize first letter
  $variables['user_logged_in_name'] = ucfirst($user_logged_in_name);

  # gets user email
  $user_email = $variables['user']->getEmail();
  $variables['user_email'] = $user_email;
}

That worked perfectly! Now I am trying to get the user profile picture, but I am not able to do it. Any help will be appreciate it.

you can get Url it by   get('user_picture')->entity->url()( you can get URI too with get('user_picture')->entity->getFileUri()), So

function tropical_preprocess_page(&$variables){
  // gets current user name
  $user_logged_in_name = $variables['user']->getDisplayName();

  // creates value to ouput in the DOM & capitalize first letter
  $variables['user_logged_in_name'] = ucfirst($user_logged_in_name);

  // gets user email
  $user_email = $variables['user']->getEmail();
  $variables['user_email'] = $user_email;

  // get user picture
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())
  $variables['user_picture'] = $user->get('user_picture')->entity->url();

}

Additionally,  If you want to get the default image when the user account doesn't have an image associated, use the following code.

$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$picture = file_create_url($file->getFileUri());


Do Drupal websites have bad performance or are heavy? I'm facing a lot of problems with my shared hosting company regarding the performance of my website.

My website is not complicated at all, just text pages, and also some pages using the Views module, I'm not using Panels, and I aggregate my css and js, and also I have 7 image styles (thumbnail,large etc...).

But even so my hosting company told me that I exceeded the memory limit and I have to optimize the website.

I have also another site in a different hosting company .... another problem appears in the database and this is the error message:

  PDOException: SQLSTATE[00000] [1129] Host '...' is blocked because of many connection errors;

I don't know if the problem is because of Drupal or something else.

What's your hosts memory limit?

For MySQL Run this MySQL command

SHOW VARIABLES LIKE 'innodb_buffer_pool_size'

If it's at the default I would see if you can increase it to at least the same size as your database. If you can not, I would look at converting some of your tables to MyISAM.
http://www.mysqlperformanceblog.com/2007/11/03/choosing-innodb_buffer_pool_size/


How to hook contact form of drupal 7 for custom styling? how can I alter my contact form for adding custom classes
I am using contact form of Drupal 7 core module.

Or you can use hook_form_FORM_ID_alter() to get the specific contact form. hook_form_alter() will run for every form on the page.

function MYMODULE_form_contact_site_form_alter(&$form, &$form_state, $form_id) {
  $form['name']['#attributes']['class'] = array('class1', 'class2');

  $form['mail']['#attributes']['class'] = array('class1', 'class2');

  $form['subject']['#attributes']['class'] = array('class1', 'class2');

  $form['message']['#attributes']['class'] = array('class1', 'class2');

  // add class to the overall form
  $form['#attributes']['class'] = array('class1');
}

If you don't know how to use custom modules, you'd have to research that first. Dropping this function in and replacing MYMODULE with your module name will make this work.


Contextual filters exclude option missing I've downloaded the drupalcommerce kickstart but when adding a contextual filter to my view, the "exclude" option is missing.

when I expand the "more" at the bottom the only options are: Allow multiple values and administrative title

do I have to enable the option somewhere before I can access it?

I'm trying to make a list of nodes of the same type, excluding the current node...

The exclude option is a part of the views_handler_argument_numeric handler that comes with views.  If it's not there, it likely means your filter is operating on something other than a numeric argument.  What you have is "Indexed Node: Node ID".  If you create a filter on "Content: Nid" instead then you should see the option.

Also see https://www.drupal.org/node/733686 .


Send a mail automatically with content/attachment using webform using rules In Drupal 7 a want people to fill in a webform with their email/tel/etc..and finally can choose some options.
When the submit the form, I want them to get automaticcaly more information about the chosen options, by sending automaticly a pdf by mail or permission to some content. Rather not with subscribing, also anonymous users.
Is this possible with rules and webform (I also installed webform rules).
When you need more information just let me know.

Thanks very much in advance!!!

Pieter-Jan Derks
Holland

Pieter - I think this answer can be helpful. You would use MIME mail to add attachments and send rich emails.


How to identify and copy a pane? I have a site that is developed with panes. There are "Contact Us" forms at the bottom with bad links. Some pages share the same pane, some have different panes.

My task is to standardize all the pages so that they use the same pane, so that fixing a link in one will fix the link in all of them.

What I see as the title is Contact Us (id: 1740). That's the title of the pane that is shared among certain pages. On other pages, it's Contact Us (id: 1738), with different ids for different pages.

What I would like to do is copy the pane entitled Contact Us (id:1740) to all the pages that have the Contact Us section. However, I am not sure how to copy it from one page to another.

When I click on the gear icon of the page and choose Edit, I can edit the values, but I don't see what type it is. I've looked at node of nid 1740-- it's not that node. Also, I don't see that title in the list of re-useable panel panes.

How can I copy this panel pane to other pages where it doesn't already exist?

It turns out my pane was a fieldable panel pane. As far as I can tell, these panes serve as templates, and when placed in panels, they are copied into one-off panes.

So my solution was to add another copy of the fieldable panel pane, this time making sure to check the 'reusable' box. Then, I replaced all the one-off panes throughout the site with the reuseable pane.


Print the error message returned from the SQL query I created a custom module where I am querying the database, for example with code similar to the following one.

$query = db_select('node', 'n');
$query->fields('n', array('nid'));
$nid = $query->execute()->fetchField();

I want to print the warning, error, and success messages after the execution of the query. How can I achieve this?

Try to follow below code..

   try {
        $query = db_select('node', 'n');
        $query->fields('n', array('nid'));
        $nid = $query->execute()->fetchField();
        drupal_set_message(t('Print your sucess message here'));
      }
    catch(Exception $e){
        drupal_set_message(t('Print your error message here'),'error');
    }


Custom layouts for responsive site page We're converting a site to be responsive and have decided to use Adaptive Theme. But the client insists on a unique layout for the Front page that does not fit into Adaptive's method of stacking sidebars. In principle I need a layout program like Panels or Display Suite that lets you create two layouts, and then decides which one to use depending on the device. I'm a coder and can do this myself with a page callback, or I suppose in the front page template, but was hoping for another solution. Is there a better way?

I think the theme key module might be just what you need. From the module's page:

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules. In combination with Drupal's
  theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen a
date/time-selected Christmas
theme mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes indicating your
environment (production, staging, testing, sandbox, … ) testing your
redesign safely on a live server

And many more. https://www.drupal.org/project/themekey


How to alter drupal views filter by start date query I need to display only future events with start and end date greater than or equal to today's date. I am using drupal with oracle. When i am trying in views UI, its giving me an SQL error.

Try this module Views between dates filter  I suppose this may help you


menu items saved with menu_link_save() don't have the delete button, and I can't edit the menu path When I add menu items manually, they work fine.  When I try this I get no delete link in the admin, and I can't edit the menu items.

$link = array();
$link['link_title'] = "text";
$link['link_path'] = 'node';
$link['menu_name'] = $menu;
$link['expanded'] = 1;
$link['module'] = "dl_migration";
$link['weight'] = $i;
menu_link_save( $link );
menu_cache_clear_all();

The reason the "delete" link is not shown is that the link is only shown when the menu item is created by (or associated to) the Menu module. _menu_overview_tree_form() contains the following code:

  // Only items created by the menu module can be deleted.
  if ($item['module'] == 'menu' || $item['updated'] == 1) {
    $operations['delete'] = l(t('delete'), 'admin/build/menu/item/' . $item['mlid'] . '/delete');
  }

menu_link_save() uses some defaults for the array $item passed as argument; this means that if the module associated with the menu link is not explicitly set, it receives the default value ("menu").

  // Load defaults.
  $item += array(
    'menu_name' => 'navigation',
    'weight' => 0,
    'link_title' => '',
    'hidden' => 0,
    'has_children' => 0,
    'expanded' => 0,
    'options' => array(),
    'module' => 'menu',
    'customized' => 0,
    'updated' => 0,
  );


hook_uninstall not working I have created a custom content-type in my custom module with custom fields.. It works fine.. But when I try to uninstall it, it doesnt call hook_unistall().. Can any one suggest what can be the problem ?

Here is my code :

function homepage_blocks_uninstall() {
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
    $result = db_query($sql, array(':type' => 'homepage_blocks'));

    //echo "hello";
    //exit;

    $nids = array();
    foreach ($result as $row) {
        $nids[] = $row->nid;
    }

    node_delete_multiple($nids);
    foreach (array_keys(_homepage_blocks_installed_fields()) as $field) {
        field_delete_field($field);
        //db_drop_table($field);
    }

    $instances = field_info_instances('node', 'homepage_blocks');
    foreach (_homepage_blocks_installed_instances() as $instance_name => $instance) {
        field_delete_instance($instance);
    }

    node_type_delete('homepage_blocks');
    field_purge_batch(1000);
    //variable_del('comment_homepage_blocks');
    //variable_del('node_submitted_homepage_blocks');
    drupal_flush_all_caches();
    //module_disable('homepage_blocks');
}

And I want to delete all tables, cache, variables node entries related to that module while uninstalling module so that I can re-install it.. What extra code I need ?

_homepage_blocks_installed_fields() and _homepage_blocks_installed_instances() are functions reside in homepage_blocks.functions.inc file and I have included this file to my homepage_blocks.module and homepage_blocks.install

Are the functions you are calling from your implementation of hook_uninstall() defined in your .module file? If that is the case, those functions will not be found, as the module file is not anymore loaded in memory.

  When hook_uninstall() is called, your module will already be disabled, so its .module file will not be automatically included. If you need to call API functions from your .module file in this hook, use drupal_load() to make them available. (Keep this usage to a minimum, though, especially when calling API functions that invoke hooks, or API functions from modules listed as dependencies, since these may not be available or work as expected when the module is disabled.)


Domain Access force node redirect to proper domain Using Domain Access with Drupal 6, I am encountering an issue in the following scenario:

I set up a node published to a sub site, say:

subsite.com/node-x

If I browse to:

mainsite.com/node-x

I would like it to redirect to:

subsite.com/node-x

However, it just renders the content on the main site domain (which the search engines would pick up as duplicate content).

Any idea how I can configure the sites to redirect to the site on which the node is published? I attempted to use Global Redirect to redirect from the main site to the full url  on the sub site but Drupal told me that I was redirecting something to itself. Are web server redirects my only option?

There is a special module for that: https://www.drupal.org/project/domain_path_rewrite.

The idea is to check the request path before the page load and to make a redirect to the proper domain if needed. Something like:

/**
 * Implements hook_init().
 */
function domain_path_rewrite_init() {
  if ($domain_path = _domain_path_rewrite_domain_path(current_path())) {
    global $_domain;

    if (!($_domain['domain_id'] == $domain_path['domain_id'] && request_path() == $domain_path['path'])) {
      drupal_goto($domain_path['url'], array(), 301);
    }
  }
}


Earliest point in page load to issue a redirect? I'd like to redirect all of the paths for my media entities the path of a file on the entity. What hook would allow me to do this as early in the page load process as possible?

You should create an EventSubscriber! This post gives a pretty good code example.

I'm doing exactly this and I had some issues when the media's file changes, the redirect will be cached and still point to the old file. To get around this I use the page_cache_kill_switch service which you can inject into your subscriber or just call like:

\Drupal::service('page_cache_kill_switch')->trigger();

One other note is that you'll want to make sure you only fire the redirect when the route \Drupal::routeMatch()->getRouteName() == 'entity.media.canonical'. This will make sure you only redirect when trying to view the entity vs edit or etc.


Finding unused Image Styles I'm working on a pre-existing Drupal 7 website that has been through several iterations so I'm trying to have a tidy up and remove items which are not required.

I'm currently looking at the Image Styles, of which there are 26 on the site. I'm pretty sure a lot are not used any more, is there any best practise method of making sure they're not used before removing them? My current thinking is either to check every Content Type & View to see if they're used, then do a search in the database & code base to see if they appear in there. Is this the best way? Would it cover all locations they could be being used?

You have a couple of tasks,

Identify all the image styles
Identify where they're used. You can have multiple node displays, views, display suite, panels, etc.
Check if they're defined in code (features/custom modules)
Remove extra ones that aren't being used

They all apply to images. So your first step if find image fields and where they're used. Drupal has a report for that.

admin/reports/fields

For Views, you can use,

admin/reports/fields/views-fields

For each content type, check all displays see which ones are used,

admin/structure/types/manage/<CONTENT_TYPE>/display
admin/structure/types/manage/<CONTENT_TYPE>/display/teaser
admin/structure/types/manage/<CONTENT_TYPE>/display/<OTHER_DISPLAYS>

Then see if you have Panels or Display Suite. And check those modules to see if they reference other image styles.

After that, you can start looking into your code. This could be tricky. Assuming the contrib modules are in a separate folder,

sites/all/modules/contrib

It's easy,

grep -rn 'image_format_machine_name' sites/all/modules | grep -v 'contrib'

But if everything is thrown together into modules/, contributed, custom, feature modules, you'll have to exclude contributed modules manually. Probably Excel would be your best bet here.

I think basically that should cover the places where they're used.

Not sure if anyone would have any other ideas.


How can I load CSS files located outside the web root from within a custom module? I need to store my css files at a location outside Drupal's path (e.g. /srv/assets/css/my_site/general.css). I attempt to achieve this using drupal_add_css but the browser loads them from:

http://www.my-site.com/srv/assets/css/my_site/general.css which results of course in 404 error.

Any idea how to load those external (file system) CSS files from within a module? note: I am using Linux.

drupal_add_css() expects a path relative to the site root. As such, if you're going to use drupal_add_css() you need to add a path within webroot to access the file.

One way to that is to use a symlink. For example

ln -s /srv/assets/css/my_site/general.css sites/all/modules/my_module/css/general.css

As long as the file is readable by your web server, you can use drupal_add_css to reference your symlink path.

drupal_add_css(drupal_get_path('module', 'custom') . '/general/custom.css', array('type' => 'file'));


What is the value of "Drupal user" in Drush status for? What is the value of "Drupal user" in Drush status for? Suddenly, one of my websites lists the Drupal user as "anonymous" instead of blank, like the other environments. I noticed the change after pulling in code from the repo and the data from production, but it may have always been like that.

The value "Drupal user" is the user the Drush command is run as. You can supply a (valid) user name to any Drush command using -u - for example drush status -u admin. Your implicit question, why did the status command suddenly report "anonymous" as the user, I can not answer. You would have examine the code you pulled - maybe something in the settings?


List all nodequeues a node belongs to Given I have a node, how to programmatically find out all the nodequeues it belongs to? Is there any ready functionality in Drupal 6 or do I just have query this from the DB myself?

Given that you have loaded the node in $node you can do:

$queues = nodequeue_load_queues_by_type($node->type, 'links');
$subqueues = nodequeue_get_subqueues_by_node($queues, $node);


Proximity for OpenLayers It has a bug that keeps dumping errors to the logs.  There is a patch, but the patch removes the distance field.  The module isn't maintained.

Does anyone know of other modules that can be used with OpenLayers and views to plot locations within a particular radius?

Use the geofield module 2.x. It contains proximity capabilities


Assigning global var to session variable? I want to assign the user name to a SESSION variable, yet this is not working.

$_SESSION['loveleytest'] = $user;
$_SESSION['thelovelytest2'] = $user->name;

What should I do?

For assigning user_name to a session variable you would directly do something like

global $user;
$_SESSION['thelovelytest2'] = $user->name;

I think the issue with your code may be:

It is not able to retrieve the global $user variable.
You might not have defined the global $user variable.
Because you did $_SESSION['loveleytest'] = $user, thats why the issue is there.

I am also curious to know which was the exact issue.


How to make my user notifications module notify node authors about new comments? I need to send a notification to the article owner when some user comments on the review added to an article.

But in the Rules module, while adding a Rules Action, there is this action: 'Send notification to user when flag is applied' (part of a custom module I inherited from a prior mantainer of this site). With this action, notification is only sent to the reviewer, not the article owner.

Can anyone help to get this to work? Or is there another way to make this work without the custom module I'm struggling with?

Here is my rule:

{ "rules_send_notification_when_commented_on_article_listing" : {
    "LABEL" : "send notification when commented on article\/listing",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "user_notifications", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "entity_is_of_bundle" : {
          "entity" : [ "comment" ],
          "type" : "comment",
          "bundle" : { "value" : {
              "comment_node_article" : "comment_node_article",
              "comment_node_page" : "comment_node_page",
              "comment_node_comment" : "comment_node_comment",
              "comment_node_company" : "comment_node_company",
              "comment_node_review" : "comment_node_review"
            }
          }
        }
      },
      { "NOT data_is" : { "data" : [ "comment:node:author" ], "value" : [ "comment:author" ] } }
    ],
    "DO" : [
      { "user_notifications_action_send_notification_flag" : {
          "flag_as_flag" : "commented",
          "content" : [ "comment:node" ],
          "message" : "commeted on ",
          "heading" : "d"
        }
      }
    ]
  }
}

As per the "Or is there another way to make this work without the custom module I'm struggling with?" in your question, IMO the answer is yes. Read on for more details about how to "send a notification to the article owner when some user comments on the review added to an article." (as in your question).

Have a look at this, rather basic, rule (in Rules export format):

{ "rules_notify_node_author_about_new_comment" : {
    "LABEL" : "Notify node author about new comment",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "NOT data_is" : { "data" : [ "comment:node:author" ], "value" : [ "comment:author" ] } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "comment:node:author:mail" ],
          "subject" : "A new comment was posted to the node you authored",
          "message" : "A new comment was posted, you can find it at [comment:url]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Use the Rule UI to import it in your own environment. Some more details about this rule:

Event: After saving a new comment.
Condition: Check that the user who posted the comment is different from the node author (I'd think it doesn't make sense to notify the node author of comments posted by the node author, right?).
Action: Send an eMail to the node author, with a link to the comment that got posted.

Feel free to add any rules conditions that may fit to further improve the above prototype, to fit your actual requirements.

Note that the above rule doesn't depend on any other module, though you could make it way more sophisticated if you'd also get the Message module involved (eg to create a log file of all such eMails ever being produced, if that's what you'd want to do).

BTW: no need for custom code ...


Is there any way to make Commerce Customer Profile save/store data in a predictable manner? Heres the thing. We have a customer profile of type 'Delivery' which contains a delivery address for an order. It also has other non-addressfield data like driver route, delivery day (M-F, day of week), default product (recurring order kit), and delivery frequency (how often to receive new orders).

The customer can, at any time, change their delivery frequency, default product, and delivery address. Here is the issue... any slight change and/or order reference and the profile is cloned. I get that Drupal Commerce does this to preserve historical order data integrity, however, the new profile ID needs to be assigned to all non-completed orders. We can't store this as a Profile2 object, because changing address or product affects their available delivery day and driver route, which has to go along with the order.

Orders are generated by the system based on this profile data... so it is important to maintain order reference and the 'newest' profile of record that is the basis for new orders and any editing. Profile data cannot be edited at the order level itself.

I am having a lot of difficulty wrapping my head around how to wrangle profiles to either prevent dozens of clones or making it make sense to administrators (Views reports will show tons of user profiles).

What is the most sensible way to manage this? Currently I have set up a Rule that when a customer profile is created or updated, the profile ID is proliferated through orders... but not sure this is the best approach.

I'm not really sure what the best solution is. I'm also not particularly fond of the code I wrote to prevent customer profile changes from harming the data integrity of historical orders. Those two caveats aside, maybe the following options can help:

You could patch commerce_order.module to add specific exemptions for your fields in the function commerce_order_commerce_customer_profile_presave(). You'd basically add a whitelist to the top of the foreach() loop there over field instances and if you see one that shouldn't be taken into consideration for profile copying, use a continue statement. Note that this approach means any changes to these fields would "appear" on previous orders that were placed with alternate values for these fields - if that doesn't matter to you, then this should be safe and fine.
You could look into Commerce Single Address. I'm not sure it's what you want, but it may offer some insight. You may need to add code to it to handle updating those previous references that were giving you an issue.

Ultimately we need to get a reasonable API around this so there are hooks and alternate options for the copy behavior. If you decide to patch commerce_order.module, make sure you maintain that patch in your codebase and have a process in place to re-apply it whenever you update Drupal Commerce.


Show rendered node in jQuery modal through JSON Whenever a link has a specific class I want to show it as a jQuery modal. I have added the neccesarry data attributes to the link in order to be able to use it as a modal.

I have also created a route for nodes that has a custom controller that is run when a node is viewed with ?_format=json. The controller returns the rendered node as JSON which seems to work fine.

To see the route definition look here.

Here's my controller:

public function json(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
  $build = $this->entityTypeManager->getViewBuilder('node')->view($node, $view_mode);
  $output = $this->renderer->renderRoot($build);

  return new JsonResponse($output);
}

And here's the JS that makes the link a modal:

if ($(context).find('.class').length > 0) {
  $(context).find('.class').each(function () {
    $(this).attr('data-dialog-type', 'modal').addClass('use-ajax');
  });
}

The only problem is that when clicking the link it gives an error saying:

  SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data

Why does JSON.parse fail to parse the JSON data that JsonResponse generates?

I can suggest you to check with AjaxResponse, it will return the json response object.

$response = new AjaxResponse();

And use below to open content in modal or as dialog.

$response->addCommand(new OpenModalDialogCommand($title, $content, ['width' => '700'])); // To open a modal window

OR

$response->addCommand(new OpenDialogCommand('#some-element', $title, $content, ['width' => '700'])); // to open a dialog window

$title refers to title of your node and $content refers to content that you want to show in the modal. It is also possible to define some properties like width in it.

And in the end just return it's response like below:

return $response;

Remember to include AjaxResponse in it your controller file.

use Drupal\Core\Ajax\AjaxResponse;

I hope the above will solve your problem.


Creating readable links for nodes in a view I have 2 views setup - one is for a directory listing of nodes and the other displays an individual node from that directory.

The directory view is visible at /directory and can be filtered by letter (e.g. /directory/b will show all nodes whose title starts with b)

Currently, the directory listings link to /directory/show/[nid] but I would like them to be friendlier. For example /directory/show/example-title.

I can get close to this if I check 'Output this field as a link' on the Title field and set the 'Link path' to directory/show/[title]. However, that displays the link as /directory/show/Example Title.

Is it possible for this link to be displayed as /directory/show/example-title somehow?

First way:
For second Views I assume argument handling is used (NID send as argument).

So you should modify this argument,
Add/change this argument validation - select PHP code
There you should check if this $handler->argument is numeric
if not, try find node by title ($handler->argument will title),
if found, assign to $handler->argument found NID.
Return in code TRUE if argument is numeric or node found by title.

Minus of this for nodes with the same titles, so you can use next way.

Another way is using Rules for that:

Add rule for node creation/editing
Add action and use next PHP code for inserting new alias:

     global $language;
     $path = 'node/' . $node->nid;
     $alias = 'directory/show/' . $node->title;
     path_set_alias($path, $alias, NULL, $language->language);

Be sure that $node accessible in your Rules PHP code action, if not, seek patterns like [nid], etc.
Also you should resave all your required nodes for creating new aliases for these nodes, recommend to use for it VBO module.


can I use db_update to update a field ( appending a string to the current string in the database ) Is it posible to do something like:

db_update('my_module_table')->fields( array('myfield' => <myfield> + 'newstring') );

Or do I have to load the field value first by using db_select() ?

Maybe someway with db_query() ?

You can still use db_update() just with an expression() instead of fields(), e.g.

db_update('my_module_table')
  ->expression('myfield', 'myfield + :newstring', array(':newstring' => 'Some string'))
  ->execute();

Although it strikes me that still wouldn't work as you're trying to concatenate strings (the + operator doesn't perform string concatenation as far as I know). This should do it:

db_update('my_module_table')
  ->expression('myfield', 'CONCAT(myfield, :newstring)', array(':newstring' => 'Some string'))
  ->execute();


How can I get my module to see the current language my user is using? When I use Node::load(10)->toArray() I see that my module thinks that the current language is English. I have the language key (fr) in the url and when I place \Drupal::languageManager()->getCurrentLanguage()->getId() in my code it says (fr). How can I get Node::load(10) to see the current language the user is using?

When I translate the content type into another language, all translations of the same page seem to have the same id to place into the load function.

You could try the following:

$lang_code = \Drupal::languageManager()->getCurrentLanguage()->getId();
Node::load(10)->getTranslation($lang_code)->toArray();

Good luck!


Field prints twice, or not at all when added to template file I have set my node field to 'Hidden' in the Manage Display page, and am printing the field in the corresponding tpl.php file, but the field only prints if I set the field format to 'Default' in Manage Display.

How can I hide the node field, and JUST print it in the template?

This is the code I'm using to print the field

<?php print render($content['field_description']); ?>

so basically what's happening... is that if I set the format to 'Hidden' in Manage Display, the field doesn't display at all, and then if I set the format to 'Default', the field shows twice - once where I've printed it using the above code, and again in the content area.

What am I doing wrong?

Cache has also been cleared.

Your template file will only print fields that are not hidden in the Manage Display window, so you definitely need to make it 'default'.

It's probably printing twice because you have the default print render($content); somewhere in your template file.

If you want to print the field separately and not have it print when the main content is printed you need to hide the field in the template file not in Manage Display:

<?php hide($content['field_description']) ?>

Make sure you do this early in the file, before print render($content);.


Setting up a development environment for drupal site I have a production site at example.com (with a subdomain multi-install) and I have been meaning to setup a development environment at beta.example.com (also having all of the multi-sites). I would like these machines to be as identical to each other as possible so the push from the development machine to the production machine goes very smoothly. Is it possible to have the sites folders named the same on the development machine as they are named on the production machine? That is, they do not have beta in the file name. Does this involve hostname rewriting? Can apache even do that?

Yes it is possible to have the same DIR structure as on your live site using sym links.

Suppose subsite.example.com is a folder on live site on production you need a link like beta-subsite.example.com -> subsite.example.com And you can use subsite.example.com in both your environments.

SO folders on Live site will be

default
subsite.example.com

In dev environment one extra link has to be created pointing to subsite.example.com.


How do I display questions in blocks? How can I display questions in a block using the Quiz module?

I do it using the Views module, but when I click on Start quiz, it goes to a page. I want all functionality done inside a block.

Though now 3 years old, the Quiz FAQ addresses this question: drupal.org/node/507090#1

How do I create a quiz block?

Quiz 3.x has the Views module integration. To create a quiz block showing the top scorers or recent quiz you can use the Views module [to expose as a block]


Site Map Menu are not translatable I have created sitemap page using sitemap module to include some menu for displaying on sitemap page. Now I am unable to translate menu titles, while all the links are translated.
Also I added the translation for menu title from Edit-Menu-> Translate.

Be aware of the Main Menu not translated issue, which states:

  When using the default 'Main menu' menu, and outputting that on the sitemap, the title, or menu name, isn't translated ...

I just double checked in a multi language site also where I have the i18n Menu Translation sub-module enabled (one of the Internationalization sub-modules).

I tried editing the Sitemap menu item to be translated, by navigating to admin/structure/menu/manage/navigation. From there I tried to use the "translate" link (for the Sitemap menu item), which one would expect that it can be used to translate that menu item.

However, after doing so, I only get something like "You are not authorized to access this page."

This issue appears to be fixed in the most recent dev version.


Node id in views template Sorry if this question has been answered already but I couldn't find an exact answer. Maybe I'm missing something.

Context of my issue:

I have a view that lists fields of certain content type. One of the fields is the nid. I need to do some validation in the view template before printing anything. So I need to call a function and check something using the nid as parameter. In my views-view-fields.tpl.php I do something like:

<?php foreach ($fields as $id => $field): ?>
    <?php if ($id == "nid"): ?>
        <?php my_function_here($field->content); ?>
    <?php endif; ?>
<?php endforeach; ?>

As you might expect, $field->content is a string and if I do something like this in my function, it just won't work.

function my_function_here($nid) {
    var_dump(node_load($nid));
}

I tried casting the value to integer, but still no luck (casting returns 0):

function my_function_here($nid) {
    $nid = (int)$nid;
    var_dump(node_load($nid));
}

and

function my_function_here($nid) {
    $nid = intval($nid);
    var_dump(node_load($nid));
}

So my question is: how do I get the nid in that view template?

Big thanks in advance!

From a similar issue - you can find details here (or just search for views preprocessor):

A preprocessor will give you access to the data, instead of rendered html which you find in the tpl file.

  There aren't dynamically generated preprocess functions; instead, all
  of the theme functions use the base preprocessor automatically. So
  views-view--my-first-view.tpl.php still uses
  template_preprocess_views_view(&$vars) as its preprocessor function.

  You can add preprocess functions for specific views with the exact
  same naming conventions. Note that that it's named *preprocess not
  preprocessor_.

  Note that currently Drupal's design requires that you have the
  .tpl.php file in order to have the preprocess function (though you
  could drop in a generic preprocess function and do switches based upon
  information contained within the $vars['view'] variable. There's an
  issue for this which is fairly easily found by going to the Drupal
  queue and searching in the 'theme system' queue.


How to use Commerce Feeds to Import Stock for the Commerce Stock module? I have the Commerce Stock module enabled for my products in Drupal Commerce.

But I cannot import data to the stock fields: When I set up the correct product processor, I can't see the Stock field which is present in my product variation type.

Your problem sounds similar to the issue: Not recognizing product variants fields.

The solution is most probably to upgrade the Commerce Feeds module to 7.x-1.x-dev, or if you don't want to use a dev version you could downgrade the Feeds module to 7.x-2.0-alpha9.


Inserting the value from Datetime field form I have a form where the user can input datetime and then I want to store it in the database. Here's my schema :

  'start' => array(
          'type' => 'varchar', 'mysql_type' => 'datetime',
          'not null' => FALSE,
        ),

The form :

  $form['add']['start'] = array(
        '#type' => 'datetime',
  '#default_value' => $date,
      );

When I hit submit button, it shows me :

  db_insert failed. Message = SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:...

What I got out of it was that the DateTime in Drupal is incompatible with MySQL's. Any suggestions or how should I process the value from the form so I can insert it into the db?

Alternatively, any way to convert DrupalDatetime into string?

(For what it's worth I also tried 'timestamp' as the MySQL type but it throws me the same error).

Datetime fields in Drupal 8 are stored as strings, partially because date support between databases isn't consistent and partially to make them easy to manipulate to extract parts where there aren't proper date functions.

The date is stored with the format DATETIME_DATETIME_STORAGE_FORMAT, and the timezone is implicitly DATETIME_STORAGE_TIMEZONE.

You would need to do something like:

Before Drupal 8.5

/** @var \Drupal\Core\Datetime\DrupalDateTime $date */
$date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
$string = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);

In Drupal 8.5 and after, as per https://www.drupal.org/node/2912980

/** @var \Drupal\Core\Datetime\DrupalDateTime $date */
$date->setTimezone(new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE));
$string = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);

There are better ways to handle this, though.  It is best to use the date formatter service to format the dates, rather than the ::format() method (I'm being lazy here).  It is also probably best to use proper entities and add this as a field, and not just stuff it into a database table.


How to iterate through an object returned by fetchAll? Since fetchAssoc was returning only one row, i was forced to use fetchAll.

The problem is fetchAll returns the data as an array of objects. Iterating through them is kind of painful, not impossible but seems like a long way to go for something that should be really simple.

fetchAllAssoc throws an error.

If somebody could show me a neater trick, that would be great.

    $result = db_select('raffles', 'r')
  ->fields('r')
  ->execute()
  ->fetchAll();

  dpm($result);

<?php
// Retrieve all records into an indexed array of stdClass objects.
$info = $result->fetchAll();

// Retrieve all records into an associative array
// keyed by the field in the result specified.
$info = $result->fetchAllAssoc($field)

To iterate just use:

foreach($info as $key => $object) {
  print $object->property . "<br>";
}

References:

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


Drush core files location I don't want to add some commands I don't want to know where drush configuration file is I am simply looking for a file which contains drush command functions.

I am running drush on Ubuntu.

The commands are in a folder called 'commands' in the root of the Drush folder.

If you don't know where that folder is on your machine, running locate drush.php in terminal should help you find it pretty quickly.

In fact, running locate drush/commands should give you a list of all the individual include files related to commands, but it depends if your Drush files live in a folder with that name.


Is it acceptable to modify Drupal's composer.json file? Drupal adheres to the best-practice of never modifying core.

Drupal 8 has a composer.json file built into core, if you need to add a third-party library, should you modify composer.json, or is there a better way to do this?

It is possible to consume Drupal 8 into your own composer.json file:

{
    "name": "davidbarratt/mydrupalproject",
    "require": {
        "drupal/drupal": "8.*"
        "composer/installers": "1.*"
    },
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "drupal/drupal",
                "type": "drupal-core",
                "version": "8.0.0-dev",
                "source": {
                    "url": "http://git.drupal.org/project/drupal.git",
                    "type": "git",
                    "reference": "8.x"
                }
            }
        }
    ],
    "minimum-stability": "dev"
}

There's a pull request to composer/installerswill allow installation of drupal-core project types:
http://github.com/composer/installers/pull/38

Would love your input on the above pull request, as well as this other one in the queue that allows installation of modules/themes/profiles.

Another solution that currently works is the Composer Manager module, which facilitates composer.json use for modules. It's currently available for Drupal 7, and will be available for Drupal 8 once the Drupal 8 alpha releases are close.

Thanks a lot,
Rob


How to create a glossary page in Drupal 7? I tried to create glossary page like this. I've used Glossary module version 7.x-1.x-dev.

But i couldn't make it work. How to create glossary page in Drupal 7?

Option 1: Install https://www.drupal.org/project/views module. Go to Structure > Views, then enable the 'Glossary' view. View module provide 'Glossary' view by default.

Option 2: Also you can achieve your requirements by installing https://www.drupal.org/project/views_glossary module.


Don't let user register without role/profile2 profile? I created a site for a client that lets users register an account of either one out of two roles, which then is linked to one of two profile2 types.

Therefore my client wanta no other being able to register without one of these roles/profiles so i did a 301 direct from $site/user/register to  in .htacces. It works, as I see it, but somehow users/bots seem to be able to get passed this and register accounts without a role anyway.

Any ideas how to secure this in a better way than currently?

Daniel

Best way to close all ways of creating users without that profile is adding a custom validation function for the user_register form.

In that validate handler just make sure that the form values are right and a user with a profile2 node will be created when form is processed (submit handlers are executed).

Use a form alter to add your validate.

This way you enforce the creation of valid user only where all user creation happen, the the user register form (except admins).


Import contacts from different social networking sites and invite to my drupal site I am in the process of building a social networking site.I need to allow my users to be able to invite their friends as well on to the site. Using the Invite module alone will not cater to my need. What i need is this to work with some other module. I want users to be able to import their contacts from Facebook, Twitter, Gmail and then select between the contacts the users to invite. I thought of using the Contact Importer module but it has issues with social networking platforms. Please advice. You may have a look at the following image to understand my use case.
http://i.imgur.com/BAczhzX.jpg?1

You would use the invite along with the Contact Importer

Invite

  Invitations are important to create network effects and exponential
  growth of a community of interest. This module provides an Invite a
  friend feature to allow your users to send and track invitations to
  join your site.

Contact Importer

  Contact Importer provides a form for your users to enter their email
  address and password. The contacts from their address book are then
  retrieved.

  Contact Importer can be used with any Drupal form. No codding
  necessary. It can be used with an invite module, a user import module,
  an emailing module, or anything else that you can think of.

  The current release interfaces with the Octazen or Open Inviter
  retrieval services. But the architecture is modular and can be very
  easily extended to use other retrieval services such as Contact Mines,
  ImproSys, or IpInvite.


If statements in twig I've got the following card in my drupal installation, I've hidden unnecessary items for my question in the picture.

What I want to achieve is the following:
I want the icon to change based on the taxonomy term showed besides the little icon (in this case, test).

This is the code that generates the card:

{% if topic_type %}
  {% embed "node--teaser__field.html.twig" %}
    {%- block field_icon -%} group {%- endblock -%}
    {%- block field_value -%} {{ topic_type }} {%- endblock -%}
  {% endembed %}
{% endif %}

I think it should look something like this but it gives me an error:

{% if topic_type %}
  {% embed "node--teaser__field.html.twig" %}
    {% if topic_type == 'test' %}
      {%- block field_icon -%} icon 1 {%- endblock -%}
    {% else %}
      {%- block field_icon -%} icon 2 {%- endblock -%}
    {% endif%}
    {%- block field_value -%} {{ topic_type }} {%- endblock -%}
  {% endembed %}
{% endif %}

Twig blocks are named control structures, you can't define them multiple times within the same scope. Either try to move the if statement inside one single block

{% if topic_type %}
  {% embed "node--teaser__field.html.twig" %}
    {%- block field_icon -%}
      {% if topic_type == 'test' %}
        icon 1
      {% else %}
        icon 2
      {% endif%}
    {%- endblock -%}
    {%- block field_value -%} {{ topic_type }} {%- endblock -%}
  {% endembed %}
{% endif %}

or don't overwrite the block at all, instead use variables and pass them down in the embed statement

{% set custom_icon = (topic_type == 'test' ? 'icon1' : 'icon2') %}
{% embed "node--teaser__field.html.twig" with {'icon': custom_icon, 'title': topic_type } %}

I'd recommend the first when there are major overwrites in the HTML output, and the 2nd when only strings/variables/placeholders are replaced.


Uninstalling a created custom module in drupal 8 I've created a custom module in drupal 8 and on this module i've created:

Content types
Fields
Entities
Views ...

all this programmatically.

But the problem when i try to uninstall it the database keep all this forms stored !!!

I'm wondering if there is a solution to automatically delete them from database when uninstalling a module

I appreciate any kind of help :)

See How to delete a content type, programmatically?

You can add enforced dependencies on any config entity, if you do so, drupal will automatically remove them.

That's much better then using hook_uninstall(), as the user is informed about what will be removed on the uninstall confirm page.


How to write test cases for custom ajax functionality using simpletest in drupal7 I am trying to write the test case for my custom ajax functionality in Drupal 7. I am firing the event on click in my .js file but the test case gets a fail.

In my .tpl.php template file I have the following code:

Click Here

In the Js file I am getting the event as follows:

$('#myFirstEvent').live('click', function())
$.ajax({
        cache: false,
        url: Drupal.settings.basePath + '?q=mymodule/add',
        data: {page: page, sort: sort, order: order},
        dataType: 'text',
        error: function(request, status, error) {
            alert(status);
        },
        success: function(data, status, request) {
            /**Function definition goes here**/

}

In my custom.test file I have the following:

$edit = array();
$this>drupalGet("myform/add");
$this->drupalPost('myform/add', $edit, 'myFirstEvent');
$this->assertResponse(200, 'Success');

But I am not getting the success screen (Green Color) after I execute my test cases.

You cannot test custom javascript with simpletest because it simply ignores them. Simpletest can simulate the ajax behavior (via xpath) only if you add that to the form with the #ajax property. http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax

To test custom js you might want to have a look at Selenium.


URL aliases and Entity Translation (menu name replacement pattern) I am using entity translation (Field translation) for my nodes, and set the menu name on each 'page'.
The menu itself is arrange to basically have a duplicate tree in the same menu each with a different language, for example:

main-menu
-item 1 english
--sub item 1 english <node/23>
-item 1 german
--sub item 1 german <node/23>

Now when i want to make URL aliases based on the menu it does not translate.

[node:menu-link:parents:join-path]/[node:menu-link]

Keeps the URL as english. i assume this is because of "node".

What replacement patterns could i use to make the URL aliases compatible with my entity translation?

Instead of using [node:menu-link], use [node:title] instead.


How to return drupal error message in php cli I am programmatically saving nodes with corresponding photos into a D7 content type.  It's working well sometimes, and failing on others, and I am sure it has something to do with a form field not having the right data.

Typically this would throw an error when manually uploading via the Drupal content type form, but I am using the PHP CLI.  How can I output that message to the CLI?

I tried 'print $messages' which is what is used for web pages, but, alas, that is not working.

Thanks

Since you are using the command line, have a look at PHP's input/output streams. These let you write data out to where your environment would be expecting to receive output.

Alternatively, you might want a look at Drupal's built-in logging with watchdog(). You can see the messages it generates in Administration >> Reports >> Recent log messages.


Why Static Block id is getting changed? I have sidebar block which has id "block-block-11--2". After including this statement in the node template

";
 $search_block  = module_invoke("views","block_view","-exp-category_wise_search-page");
 print render($search_block['content']);

all css of tat id is messed up, because id of that block has been changed to block-block-11. If I comment that code in node template the previous block id comes properly and all css works fine with that.Those two are entirely different blocks.

NOTE I am not trying to place same blocks at two place.

What is the issue over here? Thanks in advance.

The issue is you're not using things correctly. You should never call blocks directly from templates. Use regions in templates and add blocks to them from GUI, or you can expect IDs to get messed up. Block IDs are based on the order blocks are prepared for display (see implementation of drupal_html_id function), and each time you mess up with the block display mechanism, and go around it, their numbers may change.

If you call block directly because you need to place a block in two places, see answers to Place a block in multiple regions question. Or, if it's a Views block, simply clone block display.

To reliably style a block, you can use Block Class module to assign a class that will not change the way ID does. Alternatively, you can use answers to How to add id to a block to manually override IDs - just be careful to keep them unique if you want JavaScript to continue to work.

Note that not only IDs will get messed up when you call block directly, but also things like permissions and cache settings may get compromised.


What is the appropriate way to store arrays of information with configuration API? In Drupal 7 with custom forms and variables, one could easily store arrays of information in the 'variables' table. I would sometimes construct configuration forms that provided a setting per say user role. Then I could either store the setting for each role in a separate variable, or pack all the settings into one array and store it that way.

I am wondering what the standard best practices way of doing a similar thing in Drupal 8.

in Drupal 7 I would have something like this for a form code:

// build list of roles
  $user_roles = user_roles(TRUE);
  // remove authenticated user role from options
  if (isset($user_roles[2])) {
    unset($user_roles[2]);
  }
$role_settings = variable_get('MYMODULE_role_type_mapping', $role_settings);
foreach ($user_roles as $rid => $role) {
      $form['roles']['other_roles']['MYMODULE_role_' . $rid . '_type_mapping'] = [
        '#title'         => $role,
        '#type'          => 'select',
        '#options'       => $membership_types,
        '#default_value' => !empty($role_settings[$rid]) ? $role_settings[$rid] : '',
      ];
    }

and then something like this in the form submit callback:

    // build list of roles
      $user_roles = user_roles(TRUE);
      // remove authenticated user role from options
      if (isset($user_roles[2])) {
        unset($user_roles[2]);
      }
      foreach ($user_roles as $rid => $role) {
        $role_settings[$rid] = !empty($form_state['values']['MYMODULE_role_' . $rid . '_type_mapping']) ? $form_state['values']['MYMODULE_role_' . $rid . '_type_mapping'] : '';
      }
variable_set('MYMODULE_role_type_mapping', $role_settings);

This type of thing is necessary when you install the custom module on multiple sites, where there could be different number of roles on each site.

So now with Drupal 8 we have this new Configuration API. I can't assume I know the roles in advance.

I was hoping to achieve this with "Simple Configuration" but I realize it may be necessary to create a custom configuration entity, although if it can be done without that that would be nice and "simple".

According to this resource: https://www.drupal.org/node/1905070#types
There are just a few schema types for configuration fields, none of which seem intuitively appropriate to this case.

Reading that page, it is not obvious even how one would store the value of a multi-valued select list in configuration, let alone variable that could be an array of all kinds of different information. In D7 a multi-valued select list would return an array. In D7 variables are stored as serialized variables. Even D7's "simple_settings_form" would handle this no problem.

Surely this type of problem has been solved many times, but it is not "simple" to find any information.

So the problem is two-fold
1) Just storing an array of values into configuration, with unknown number of array elements, number depending on custom site conditions (like user roles on a site)
2) Unpacking this array and setting up form elements for it, which on submit, packs it all up into one variable.

Similar question, simpler question is:
If one is defining configuration schema for a multi-valued select list, what data type does one use? String?

Is the model I used here for D7 even portable to D8, there's probably some better way to go no doubt, but making a configuration entity for each role in the site and all of that doesn't seem simple and definitely not as simple as could be done in D7. I do want to give a thought to config export / import between sites. dev/staging/production versions of the site may all have the same user roles, but definitely not separate websites altogether.

Although I ask several questions in this post, the common theme is how to store arrays of information as configuration appropriately in Drupal 8? Simple case is the value of a multi-valued select list, more complex scenario of the setting per user role like I describe.

Thanks in advance!

You define a schema type sequence:

Example: /core/modules/options/config/schema/options.schema.yml

# Schema for the configuration files of the Options module.

field.storage_settings.list_integer:
  type: mapping
  label: 'List (integer) settings'
  mapping:
    allowed_values:
      type: sequence
      label: 'Allowed values list'
      sequence:
        type: mapping
        label: 'Allowed value with label'
        mapping:
          value:
            type: integer
            label: 'Value'
          label:
            type: label
            label: 'Label'

You'll find the form for this example in /core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php

More info https://www.drupal.org/docs/8/api/configuration-api/configuration-schemametadata


Fatal error after disabling ctools I was getting fatal error to do with ctools along the bottom of each page of my site. To try to fix the issue I logged in as admin, and disabled 3 ctools modules in my website:

Custom Content panes
Page manager
Views content pane

This gave me an error page and my site is totally inaccessible or viewable. I turned them back on manually in the database, but now I get this error message:

  Fatal error: Call to undefined function page_manager_get_task() in /var/www/mywebsite.com/httpdocs/sites/all/modules/ctools/page_manager/plugins/tasks/page.inc on line 266

Does anyone know how to fix this?

Its really hard to figure out a solution for your issue without trying different options; but I hope the following instructions will help you.

Backup your current database
Open phpMyAdmin or any desirable MySQL administration tool.
Delete all ctools modules from system table or run this query

DELETE FROM system WHERE name LIKE '%ctool%'
Drop ctools tables ctools_css_cache, ctools_custom_content, ctools_object_cache or run these queries

DROP TABLE ctools_css_cache

DROP TABLE ctools_custom_content

DROP TABLE ctools_object_cache
truncate all cache tables (cache table and all tables with prefix cache_), example of truncate query

TRUNCATE TABLE cache


In Drupal 8, how to automatically create a term in a specific vocabulary from the field present in node/add page? Steps to reproduce -

Create two new vocabularies at - SITE/admin/structure/taxonomy/add
Add them as fields to the article content type. Set number of values to be unlimited, set form display to Autocomplete (tags style)
The new vocab fields do not work like the Tags field

Could you help me learn how to automatically create a term in a specific vocabulary from the field present in node/add page?

Thanks to a colleague, I found the setting I had to use.

Go to - SITE/admin/structure/types/manage/article/fields/node.article.field_vocab_a_tag
Check - Create referenced entities if they don't already exist


How to add a comment form in VBO to add the same comment to mutiple nodes? I am using "Comments" as a note option. I want to let users add the same comment to multiple nodes with the Views Bulk Operations (VBO) module.

How do I get the "Add Comment Form" in VBO to achieve this?

Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to create an entity, of type "Comment", whereas you specify some relevant parameters for that Rules Component, such as:

The node to which the comment is to be added.
The relevant options for the actual comment (such as the actual text of the comment).

Below is an example of a Rules Action that creates a comment (in Rules export format, use the Rules UI to import it in your own site):

{ "rules_add_a_comment_to_a_node" : {
    "LABEL" : "Add a comment to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "comment_node" : { "label" : "Node to add comment", "type" : "node" },
      "comment_body" : { "label" : "Comment body", "type" : "text_formatted" },
      "comment_subject" : { "label" : "Comment subject", "type" : "text" }
    },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : [ "comment-subject" ],
            "param_node" : [ "comment-node" ],
            "param_author" : [ "site:current-user" ],
            "param_comment_body" : [ "comment-body" ]
          },
          "PROVIDE" : { "entity_created" : { "comment_created" : "Created comment" } }
        }
      }
    ]
  }
}

Step 2

Create a view of the nodes to which some comment is to be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.

PS: this answer is for D7 ...