Allowed strings for the text field I have the form which is created through Webform module and now I need to add one more text field but its value has to be unique and can be only the value from some predefined list of allowed values.

It's not the problem that value of the field be unique (I can enable it in text field settings) but I don't have idea how to limit the value of the field on one from predefined list of values.

Those strings are voucher codes that are sent to the clients by email, also there are a 1500 different codes.

If the user enters the code that was already used or enters the code that doesn't exist in the list he should get the notification that the code is not valid right away (Ajax) or on the form submit.

Can anyone can help me with this or direct me? I'll appreciate any suggestion...

In your custom module implement hook_form_alter, this will let you add your custom validation handler to the form, something like

  my_module_name_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'your_form_id') {
      // Add one more validation.
      $form['#validate'][] = '_my_module_name_custom_form_valition';
    }
  }

  function _my_module_name_custom_form_valition($form, $form_state) {
   // $form_state holds value for submitted fields.
   if(!in_array($allowed_values,$form_state['values']['your_form_field']) {
      form_set_error('your_form_field',t('Entered value is not allowed.'));
   }
  }


How to theme a preprocess function output with a default, without the need of a .tpl file? I created this simple function in order to print out the commerce order author UID and email.

How may I add the output of the function inside the messages area, without creating a special .tpl? I want that information to be in a special place regardless of the theme implementation.

This is the preprocess function (the only way I manage to get to know if I was inside an order)

function MYMODULE_preprocess_page(&$variables) {
    //si estamos dentro de la orden, lo sabemos sólo en función del link en el que estamos!
    $uri = request_uri();
    $find = '/admin/commerce/orders/';
    $pos = strpos($uri, $find);
    if ($pos !== false){
        //usando if (commerce_order_type_get_name($type = 'order')) no andaba
        //obtenemos el número de orden: obtenemos el link con request_uri()
        //y de ahí lo explotamos en un array. Sabemos que el número será siempre
        //la última parte del link (4).
        //usamos commerce_order_load('id de la orden') para obtener el usuario que la completó
        $uri = request_uri();
        $partes = explode('/', $uri);
        $usuario = commerce_order_load($partes[4])->uid;
        $correo = commerce_order_load($partes[4])->mail;
        $estado = commerce_order_load($partes[4])->status;
        echo "
".$correo." (".$estado.")
";

    }

}

As you can see, I've tried with this horrible:

echo "
".$correo." (".$estado.")
";

Even when the classes are the same as the rest of the drupal messages, the output keeps appearing at the very top of the page.

How may I do it the right way? (Maybe it necessarily involves template.tpl file?)

I didn't realize that I could simply use drupal_set_message()!

drupal_set_message(t("".$correo." (".$estado.")"), 'status');


How to use Susy with Zen theme I'm trying to change the grid system in the Zen theme to use susy but can not find any documentation on how to do it with the 7.5.5 version.

I have installed susy through compass and have added require 'susy' to my config.rb file.

But from here I'm not sure what I need to do.

Do I have to delete the _responsive.scss file that comes with Zen and code my own?

If anyone could provide a run down of the steps needed that would be very helpful.

Many thanks,

Terry.

Do I have to delete the _responsive.scss file that comes with Zen and code my own?

Whether you delete specific files or not is incidental, but what you do need to do is replace everything in Zen's default Sass that relates to grids with your Susy-based system.

Because of the nature of Susy there's a good chance you won't need to change any of the markup Zen builds, but of course your mileage may vary depending on exactly how customised your theme is.


Drupal 6 with mongodb, any success? There is a mongodb module which is in develeopment stage. As usually find MySQL as my bottleneck, wondering whether anyone has actually implemented mongodb on D6 with success? And if so what are good resources on how to implement mongodb?

MongoDB is not a full replacement for MySQL, you still need it. You can only move certain pluggable systems to MongoDB, like sessions, watchdog and in Drupal 7 also the field storage.


is it possible to populate subclass of FieldItemList from code? The context first:

I'm migrating a website from D7 to D8 and one of the modules has no update on D8.
I found an alternate module with the same functionality.

For the FieldType of the alternate module, it consists in a subclassOf FieldItemList, lets say MyFieldItemList and a subclass of FieldItemBase, lets say MyFieldItemBase.

I'm quite stuck on this:

I exported the data from D7 using views and a csv generation export
I'm creating a micro Drupal 8 module to upload csv file and populate existing nodes with csv data
I can get the subclass of FieldItemList from my node and saw the "append(...)" method in documentation.
I can't manage to find how to create a new item of type MyFieldItemBase

I can't find any examples in existing modules and over the web, is there a flaw in the import process I wanted to follow?

So I found out what I was trying to do in a complicated way could be done by simply setting the field values on the node, like this:

            $node->set($field_name, $field_values);
            $node->save();


How to fix SalesForce authentication errors on localhost? I am fairly new to developing with Drupal, and new to this forum, so any help would be greatly appreciated.
While trying to authorize SalesForce with a local install I get the following two errors with when going to the oauth_callback.
Note: I have not included the entire path to save space but the reference points are accurate for the doc and line the error references.

Notice: Undefined property: stdClass::$data in Salesforce->requestToken() (line 338 of salesforce.inc)
SalesforceException: Error opening socket ssl://login.salesforce.com:443 in Salesforce->requestToken() (line 342 of salesforce.inc)

Local Environment: Mac OS Mavericks with XAMPP 5.6.3, SSL enabled on port 443 in httpd-vhosts.conf with certs created using OpenSSL.
Extension: php_openssl.dll uncommented in php.ini
Also to note the Drupal install was pulled from a live site that has SF module enabled and working.
I created a new connected app with the proper oauth_callback to the local site which is https://secure.localhost/salesforce/oauth_callback
I have both HTTPS and HTTP enabled, I have noticed that in the Status Report when using HTTPS I do get a HTTP Failure error in the status report.
The request url from salesforce is passing a code EX: https://secure.localhost/salesforce/oauth_callback?code=aPrxMZkm7lCkgfR3...
With a Status code of 500 Service unavailable.
I have looked all over online and on this site, and can't seem to find anything that works. I have tried a few patches to the common.inc file, but none of them seemed to work.
Like I said any help would be greatly appreciated, I am just not sure if it is Drupal, Salesforce, or my local setup.

In general, to make SalesForce authentication to work on localhost, you need to:

Create an app in Salesforce with URL Callback to your local (https://localhost/salesforce/oauth_callback) with appropriate permissions.

  In Salesforce go to Your Name > Setup > Create > Apps then create a new Connected App. (Depending on your Salesforce instance, you may need to go to Your Name > Setup > Develop > Remote Access.)

Your site needs to be SSL enabled to authorize the remote application using OAUTH.
If using the SOAP API, PHP must be compiled with SOAP web services and OpenSSL support.
Use the right auth key and secret to Authorize your app (Configuration » Salesforce).
Make sure you're connecting to the right endpoints (live or sandbox).
For more help, check Help » Salesforce API in Drupal, or SalesForce documentation.
Add $conf['https'] = TRUE; to your setting file.

The error in Salesforce->requestToken() indicates that there is a problem exchanging an authorization code for an access token.

Further more, the error:

  Error opening socket ssl://login.salesforce.com:443 in Salesforce->requestToken()

indicates the problem connecting to Salesforce endpoint it-self (check requestToken() in includes/salesforce.inc for more details).

To diagnose the problem, please check Reports » Status report if you've got HTTP Failure error and that your localhost can connect to Salesforce end point via curl:

$ curl login.salesforce.com:443

If your curl is connecting fine and you've still HTTP Failure error in your Status report, then try to:

Temporary disable Secure Site or Secure Pages modules if present.
Make sure you've firewall (e.g. iptables) and antivirus is switched off (for testing purposes).
Make sure you're not behind the proxy.
Make sure you're not running LAMP in a chroot/jail/VM environment.
Make sure you some network functions aren't disabled PHP functions (e.g. stream_socket_client).
Make sure your PHP is not in Safe mode (safe_mode = On) by:

php -r "var_dump(ini_get('safe_mode'));"

Double check your /etc/hosts or ~/.curlrc doesn't have anything suspicious (you can add insecure to your .curlrc for testing purposes).
Check is there is no any problem with certificates (e.g. your system date is incorrect, you added the certificate and your PHP openssl sees your certificates correctly).

In PHP 5.6 you can specify openssl.cafile and openssl.capath,

e.g. openssl.cafile=/usr/local/etc/openssl/cert.pem

If none of above work, please check below simple PHP script which can check if your PHP can connect to external host:

<?php
fsockopen('ssl://login.salesforce.com',443,$errno,$errstr) ? print("UP") : print("DOWN:".$errstr);
?>

Save it to the file (test.php) and place it inside your web root and open via web browser.

If it fails, it's either problem with your PHP configuration or your network. You can debug it further more by using system call tracer (debugger) as below (install it if required):

$ strace -f -e network php test.php # For Linux
$ truss -f php test.php # For BSD
$ sudo dtruss php test.php # For OSX
# For Windows, you may look for StraceNT.

Then you've to analyse the log for any issues.

Or the following perl script:

use strict;
use warnings;

use LWP::UserAgent;
use Mozilla::CA;
my $ua = LWP::UserAgent->new(
        ssl_opts => {
                verify_hostname => 1,
                SSL_ca_file => Mozilla::CA::SSL_ca_file()
        }) or die;
my $url = $ARGV[0] || 'https://login.salesforce.com/';
my $res = $ua->get($url);
print $res->code . "\n";

exit;

See also:

Using cURL in PHP to access HTTPS (SSL/TLS) protected sites.
SSL Certificate Verification
Using Curl to login to Salesforce API at Salesforce Developers
token failed with status 0! at Salesforce Developers
How to fix Curl Error Ssl Certificate Problem Verify That The Ca Error?


How do I add more pages to views pagination on mobile? I'm using Open Social and I want to add more pages to the paginationon mobile phones.

One of my views has 11 pages of users and on mobile the pagination is as the following example (<< = previous page, >> = next page):

<< 5 >>

Now what I want to achieve is the following:

<< 3 4 5 6 7 >>

Now I have searched through all the settings but I can't seem to find where to change this. I believe it should be in the code but no luck so far either. Can anyone push me in the right direction?

You must do this in the views configuration.

First you need to set the pager to use full pager instead of mini pager.

Then in the settings you can set the amount of pager links visible (in your case 5).

That should show the pager you want with 5 pager links visible.


File management- preventing the deletion of files referenced by nodes I'm not a Drupal user normally but a client wants to move from a 200 page flat file site managed in DreamWeaver to a Drupal site.

Issue is that their secretarial staff who have been managing the site in DW want Drupal 8 to warn them before they delete a media file referenced by Drupal nodes.  This is for them primarily images and PDFs which they intend to add to the server via FTP.

Can anyone direct me to a module that provides either that warning functionality or a list of nodes referencing media and PDF files?

This is for them primarily images and PDFs which they intend to add to the server via FTP.

No... I would advise installing the Media Entity and set of modules designed for handling media.

This will allow you to add media in a way that has better treatment than core. You will be able to:

Use one file in multiple places without uploading it again
Build displays based around media, if you need to
Add a button in CKEditor for referencing or uploading new media

If you only upload files in an FTP, you can't do basic things, like:

Resize an image with an image style
See how many times / where an image or file is being used
Generate different displays for different files
Create Views based around media which may be mixed with access grants later on (spitballing)

Core upload fields, or FTP copying, will not grant you anything - and giving non technical people access to FTP instead of a GUI backend like Drupal is far more error prone.

Also, there is a known core issue where files can be deleted without warning, and it is suggested to set the core file system setting of "Delete orphaned files after.." to "Never". No matter how you choose to approach media management, change this setting ASAP until it is fixed.

One of the major benefits of moving from a static setup to Drupal 8 are for reasons like this.


Translation: File upload error. Could not move uploaded file I would like to import an translation file *.po. When I import it, I become the error:
"For security reasons, your upload has been renamed to bootstrap-all.de_.po." and "Error message File upload error. Could not move uploaded file."

Could anyone help?

Try this:

Go to admin/config/media/file-system page
Set Temporary directory field to sites/default/files/temp
Save changes

ALSO

Check that sites/files is writable.


Content: Has taxonomy term ID depth modifier Answer to my question was found here: Show all child nodes of a taxonomy term D7.

But I'm not able to understand the use case of the second option: "Content: Has taxonomy term ID depth modifier" as in the figure.

The taxonomy term ID depth modifier option allows you to reuse the same view to query nodes according to varying depths in the taxonomy tree. For example let's say this is your taxonomy.

North America (term id:7)
- Canada
- Mexico
- United States
-- California
--- San Francisco
--- Los Angeles
--- etc

With a term id of 7 and a depth modifier of 0 your query would include nodes tagged with "North America". With a depth modifier of 1 your query would include nodes tagged with "North America", "Canada", "Mexico" and "United States", and so on.
The term depth modifier is passed as the second argument (Contextual Filter in Drupal 7) to the view separated by a slash. So if the term id is 7 and the depth modifier is 2 the arguments for the view are '7/2'.


How to make a word/pdf type doc clickable Good day

I have created a view, but am not sure how to make the documents type clickable. At the moment you click on the label it works, but not when you click the type. See attached, second example is the desired results and first one is the current results. I would like to take away the label and leave just the type and make it clickable.

On the other hand, how can I determine the document size and display it on the table as per second example.

I know its not a complete answer, but may help.
Icon:

$icon = theme('file_icon', array('file' => $file));

File size:

format_size($file->filesize);


Use different comment template for replies-to-top-comment I tried to make StackExchange-like comment section with different template for the comment replies. I create two template for both top-level comment and its replies. This is the result of the two comment.tpl.php file rendered and then collated in GIMP.

This is comment.tpl.php used for top comment contained in cyan box.

  <div<?php print $attributes; ?>>

      <?
        print render($avatar) . "
";
        print $commenter_name . "
";
        print $creation_date;
      ?>

    <?php
      hide($content['links']);
      print render($content['comment_body']);
      print render($content['links']);
    ?>

While this is comment.tpl.php used for comment reply contained in yellow box.

  <div<?php print $attributes; ?>>
  <?php
    print render($content['comment_body']);
    print " - " . $commenter_name;
    print render($content['links']);
   ?>

If i use one of these template, it will effect ALL the comments as shown below.

I know I can change the style rudimentarily via theme css as suggested in this question, but going by this route means that I have to create one-size-fit-all template for both case that won't be pretty.

My question is: Is there any template file I missed or any other strategy that I can employ to make separate template that will target only the replies-to-top-comment?

I manage to solve this problem by exploiting the pid (parent ID) value in the $comment variable. First, I check if the corresponding comment is a top-level comment. It is a top level comment if the pid value is 0. The code inside comment.tpl.php so far is:

if ($comment->pid == 0) {
  // Top level comments code here
} else {
  // Replies to comments code here
}

The code above will split the template programatically already, but it will be better if I worked at two separate files for the two cases. To do this, I used drupal_get_path function to point every case inside comment.tpl.php to their corresponding template.

In my case, I create these two templates inside my theme folder:

/templates/comment/comment-top.tpl.php for the top comment
/templates/comment/comment-reply.tpl.php for the replies

The code inside comment.tpl.php then become:

if ($comment->pid == 0) {
  include drupal_get_path('theme', 'mytheme') .
    '/templates/comment/comment-top.tpl.php';
} else {
  include drupal_get_path('theme', 'mytheme') .
    '/templates/comment/comment-reply.tpl.php';
}

Of course change the mytheme in the code to your theme name.

To finish off, I pasted the template I posted above in the question to the corresponding template. It will render the template properly with all the variables you define inside the preprocesses function working.


Render a custom form in a custom template For my site, I have to create a custom form in a custom template. It is not in a custom block, but in a custom tpl-file. I have searched the internet for a solution, but or the form is not shown or the fields are shown, but not in a < form > tag. This way, the submit-button does not work. When I render the fields in a self-written form-tag, the validate function and submit-function don't work.

Can someone help me?

TPL-File

$form = _odisee_forms($form, $dag, $datum, $uur, $campussen);
$form['infodag'] = form_process_checkboxes($form['infodag']);
$formulier = drupal_get_form('infodagen-block-form');
print '<form id="'.$formulier['#id'].'" accept-charset="UTF-8" method="'.$formulier['#method'].'" action="'.$formulier['#action'].'">';
print drupal_render_children($form);
//print render($form);
print render($formulier['form_id']);
print render($formulier['form_build_id']);
print render($formulier['form_token']);
print '</form>';

forms.inc

function _odisee_forms($type, $dag, $datum, $uur, $campussen) {
  $form = array();
  foreach ($campussen as $key => $campus) {
  $infomoment[] = t($dag[$key])." ".$datum[$key]. " @ " .$campus. " om ".$uur[$key];
  }
  $form['#id'] = 'infodagen-block-form';
  $form['infodag'] = array(
    '#type' => 'checkboxes',
    '#options' => $infomoment,
    '#required' => TRUE,
  );
  $form['voornaam'] = array(
    '#type'  => 'textfield',
    '#title' => t(''),
    '#size'  => 15,
    '#attributes' => array(
      'placeholder' => array('Voornaam'),
      'class' => array('breed')
    ),
    '#required' => TRUE,
  );
  $form['naam'] = array(
    '#type'  => 'textfield',
    '#title' => t(''),
    '#size'  => 15,
    '#attributes' => array(
      'placeholder' => array('Naam'),
      'class' => array('breed')
    ),
    '#required' => TRUE,
  );
  $form['emailadres'] = array(
    '#type' => 'textfield',
    '#title' => t(''),
    '#size' => 20,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#attributes' => array(
      'placeholder' => array('E-mailadres'),
      'class' => array('breed')
    ),
  );
  $form['submit'] = array(
    '#type'  => 'submit',
    '#value' => t('Schrijf in!'),
    '#attributes' => array('class' => array('button')),
    '#submit' => array('_odisee_form_submit'),
    '#validate' => array('_odisee_form_validate'),
  );
  return $form;
}

function _odisee_forms_validate($form_id, &$form, &$form_state) {
  dpm($form_state, "state");
  dpm($form);
}

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

You need to render your form in the template. Simply calling drupal_get_form won't suffice. To render the form use following:

drupal_render(drupal_get_form('form_nam'))

You also need to ensure the following:

In your custom form #theme parameter is set to appropriate theme function.

Further the hook_theme implementation is correct.

Refer this link for a working example


Link to View page in TPL file? Is it possible in a TPL to create a link to a View page? Rather than hard code the link I would like it to update if the URL of the view page changes.

If the Page display name of the view is page, then it prints the path

$view = views_get_view($view_name, TRUE);
print $view->display['page']->display_options['path'];


Export blocks added as default content I am using Layout Builder to add blocks into my nodes. I am adding several instances of different custom block types to specific content individually.

I wander if it is it possible to export those blocks added to node through layout builder as a default content using: Default content module?

I have tried standard drush dce and while it exports the node, I could not find block data into exported JSON.

I tried drush dcer to export references as well but no luck with it as well.

I am thinking finding specific block IDs and export those entities manually one by one but before I do that I want to find out if there is a way to do it in more elegant fashion.

Also if this something new, it would be good feature to contribute to Default content module, so if we find out that's the case I would happily try to contribute.

Yes It is possible. Core patch is required to fix this issue. It will fix node JSON structure and attach block_content to json files.
See my comment #63 for details:
https://www.drupal.org/project/drupal/issues/2942975#comment-13315805


Adding custom styles to Specific theme I would like to add some custom stylesheets for specific theme.

for example:
Bartik is default and Seven is the Administration theme.

In this case, I want to add some custom styles for only Bartik front-end theme.

How can I customize the following code for the Bartik theme?

<?php
/**
 * Implements hook_init().
 */
function mymodule_init() {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_css(
        $path . '/custom.css',
        array(
            'group' => CSS_THEME,
            'every_page' => TRUE,
        )
    );
}
?>

Actually, what I would do is I would make my own sub-theme that uses Bartik as a base theme and add the additional css stylesheets to my sub-theme's .info file like this:

stylesheets[all][] = css/MY-CUSTOM-CSS-STYLESHEET.css

Just look at Bartik's own .info file to see how it adds stylesheets and javascript files as an example!

Here is some info on how to create a sub theme: http://drupal.org/node/225125.

The best thing about creating a sub-theme rather than adding these stylesheets using a custom module is that you'll be all set to do things like adding or overriding theme images, modifying template files and tackling a big array of potential customizations you may want to do in the future that you may not even be for-seeing now!  It'll just end up being more flexible in the long run.


How can I trim the display of text and expand with "more" link? On my user profile page I have a "about me" text field that can get pretty long.
I would like to only show about 200 characters of text with a "more" link.
When you click more it would show the rest of the text, ideally on the same page.

Look, up in the sky.  It's a bird.  It's a plane.  It's...... sorry.  This is a job for jQuery. A quick google of "jquery more less toggle" (without the quotes lol) will show lots of examples.


Showing Warning for viewing adult classified content I am developing one publishing website, where authenticated users can write the article. For each article, he sets the age group for which the article is targeted for. Different age group may be "Adult","Pre-teens" and "Everyone". I have used taxonomy to age group.

Now, I want to show warning message to the user, when he goes to any "Adult", classified article page, before loading the content, and get the confirmation from the user that he is 18+ to view this article.

Please suggest how, can I implement this or is there any module that helps me to achieve this.

Thanks for your time.

Do you want to implement the age verification for Anonymous users or for logged in users? If you are doing it only for the logged in users maybe a better option would be to just add a birthday field to the user and just verify the age on that, so you won't have to request the age all the time, or only the first time, and then store it in the birthday field.

If not, for the actual confirmation page, you could just use *hook_node_view* and if the user has not confirmed his age for that node, replace the content with the verification form. For the way you can store whether someone has confirmed his age for a node depends, as I've said above, on how you want things to work, for authenticated users, for anonymous users.


Avoid reattaching javascript when a form is rebuilt by ajax callback I have a form that uses ['#attached']['js'] to attach a simple javascript file. A checkbox element of this same form uses ['#ajax'] to dynamically update some portions of the form. I'm finding that, when the form is rebuilt after the ajax callback, the javascript file is reattached multiple times, causing unintended behaviors.

Is there any way to avoid reattaching a javascript file to a form if that same javascript has been attached previously?

As Clive mentioned, the usual way to solve this is to use once() when attaching behaviors:

Drupal.behaviors.myBehavior = {
  attach: function (context, serverSettings) {
    $('elementSelector', context).once('myId', function () {
      // The code that will be executed only once.
    });
  }
};

Also, check the official docs on Managing JavaScript in Drupal 7.


Set role expiry programmatically in uc_roles_expirations table? I am moving a site to drupal. In that site role expire was manually set by admin.

In my drupal site I want this with the use of ubercart recurring subscription.

So how can I set a role expiration date programmatically which will work as we assign a role in features of any product purchase?

Solved Just by Database entry :

$expiredate = date('U', strtotime($expiry));
    db_insert('uc_roles_expirations')
    ->fields(array(
      'uid' => $uid,
      'rid' => 6,
      'expiration' => $expiredate,
    ))
    ->execute();


How can I get header part from my drupal 7 site? Hotelscombined(hotel information site) asked me "the header part" of my website so they can combine my website's header and their hotel list. My header part will be placed in their site.

Then it looks that my website services hotel information.
My site is developed using Drupal 7. How can I get header part only? It shouldn't be just copying and pasting. It should be something like link.
With that, it will be affected in Hotelscombined, even if I changed header part of my website like main menu.

Please help me.

Usually header part is included in drupal in page.tpl.php.

Still you can do it by creating a function in your template.php

e.g. myheader() and calling it in page.tpl.php.

function myheader(){
$html = "<div class='header'>
 Insert header html
</div>";
return $html;

}

Other way you create a template using hook_theme in your custom module and call it in page.tpl.php.

e.g. it will be called in page.tpl.php by below code

print theme('myheader');

//It will defined in custom module

function mymodule_theme($existing, $type, $theme, $path)
{
  if($type == 'module')
  {
    return array(
      'myheader' => array(
        'variables' => array('var_name'=>NULL),
        'template' => 'myheader'
      ),
    );
  }
  return array(); //will raise fatal error if void
}

and put a template in theme directory with name myheader.tpl.php

Hope it will help!


Taxonomy Term Path to Search Running Drupal 7:

Problem: I have a vocabulary that contains a list of faculty, within each faculty member term page is a list of research interests (a separate vocabulary) that are clickable.  Currently they go to their individual term pages.

Goal: How can I make those "Research Interests" clickable and simply make it go to the search page with that term as the search query?

I see two options to achieves this.

The first one is to alter the page callback for the taxonomy/term/%taxonomy_term path through an implementation of hook_menu_alter. In the custom page callback, when displaying a term from your vocabulary, use drupal_goto() to redirect to the search page. And for terms in other vocabularies, you can re-use taxonomy_term_page() to preserve the original behavior.

The second option is to implement hook_entity_info_alter() to alter the uri callback of the taxonomy term entity type. In the custom URI callback, when getting the URI for a term of your vocabulary, returns the URI of the search page. For terms in other vocabularies, you can re-use taxonomy_term_uri() to preserve the original behavior.


What does Page Content contain in Panels Everywhere when site template is enabled? Panels Everywhere (PE) configuration allows a site template to be used to "wrap" any page in a panels display.

If I edit the content of this panel, for example like this:

does it mean that any (I mean all) other page will be crammed in the Page Content item defined in the template?

In other words:

Are pages always inserted in the template's page content?
Is there anything else than pages ever ending in the template's page content? If yes, what and when?

A page panel will be placed where the main page content is located.  The page panel will be displayed only when the conditions of its Selection rules and Contexts are satisfied.  You can define alternatives by creating multiple variants for the panel and modifying the settings to meet your needs.  Panels will search through the variants and go with the first variant that meets the criteria so the order you place the variants in may matter.  Using Panels Everywhere, you would set the overall layout for your site pages in variants to the default site panel.  The various page panels would then be displayed in the regions as defined for them.

You can also create mini-panels and view content panes which act similar to blocks except that, like page panels, you can define selection rules and contexts for them and place them anywhere else on the default panel variants you desire.  So you can provide content related to your main content based upon the context (users, tax terms, field settings etc.) that apply to the main content display.

I'm not sure if I've fully answered your question.  What do you want to achieve in your site setup?


Splitting up a Drupal database Is it possible to split the Drupal database into multiple databases. For example I have one database having the watchdog table and another database having all the other tables?

I know if I created my own tables I could store them in a separate database and use the following:

How to connect to multiple Databases in Drupal 7?

db_set_active('your_second_db_alias');
$query = db_query("SELECT * FROM your_table");
db_set_active();

I think you'd be better served using Syslog for logging without cluttering your database.


Taxonomy term count per vocabulary I want to count taxonomy terms for one (or per) vocabulary. I know, it can be done via views with aggregation but I wonder if there is another way to do this without using views.

There is a taxonomy vocabulary.
There are terms in this vocabulary.
I want to learn how many terms are there in this vocabulary.

Is there a method to show term counts as node count below?

<?php $counter = db_query("SELECT count(nid) FROM {node} WHERE node.type='page' AND node.status=1")->fetchField(); ?>

For count the number of term in a vocabulary you can use this method : taxonomy_get_tree($vocabulary_id). It will returns all the terms of the vocabulary in an array. After that, you only have to get the size of the array.

Example :

$terms_array = taxonomy_get_tree(9); //9 is the vocabulary ID.
$terms_nb = sizeof($terms_array); // $terms_nb = your number of terms.


Theming the userpage I want to modify the userpages with some changes:

change the page-title
hide some or all of the local taks items (the tabs)
display some user-infos
insert a view

Here is how I want to solve it:

use THEMENAME_preprocess_page() to change the title
use THEMENAME_menu_local_task() to hide the tabs
use the user-profile.tpl.php to display user infos
create a view and use views_embed_view()

Is there a better way of doing that? Should I consider using page--user.tpl.php or a combination?

Edit: concerns Drupal 6

Yes, THEMENAME_preprocess_page() is fine for this, but one could argue that it's better to implement hook_user when $op == 'view'. That way you would make the change available for all themes (who knows you will be adding a mobile theme a couple of months from now?).
I wouldn't use THEMENAME_menu_local_tasks() for this, but instead do $variables['tabs'] = ''; in THEMENAME_preprocess_page(). Of course, only do this for the user page, otherwise you will lose the tabs on all pages.
Yes, use user-profile.tpl.php to print out variables. If you need additional variables, fetch them in THEMENAME_preprocess_page() and add them to the $variables array to make them available in your template. Depending on what you need to do, see also user-profile-category.tpl.php, user-profile-item.tpl.php and their respective preprocess functions.
Yes, that's an option. You can also create a block display of that view and enable the block on the user page.

I recommend not to use multiple page templates (like page-user.tpl.php) if you can. When you do, a simple change to page.tpl.php will often need to be applied to all other page templates as well, which is a bore.


How to debug why some content is not migrated from D7 to D8? I am using migrate_plus to migrate from D7 to D8 and so far it has been a fairly smooth process.

I have a particular content type that has 10 nodes in D7 but will only migrate one of them to D8.

After running the migration, one node is reported to exist and is successfully migrated. There are no messages related to the migration so I don't have any issue to remedy, yet only one of the ten nodes are migrated.

Can anyone suggest a way to dig into why this might be happening and/or how to get the missing nodes to migrate?

This issue was due to not factoring in languages when migrating.
So if you have the same issue you'll probably need to look at your i18n migrations.


How to use Views to make slideshow of the content created using block type To Explain further:

Please I have created a block content type directly from block, say Item_1 using ADD BLOCK then published. I did the same 3twice (item_2,item_3) each carries its contents(body). all published.
Now I want to use views to view this block type via slideshow method. Could this be possible?

All I saw in the filter list of views 3 version are all nodes, content types none points to this.
Please help.

I assume you're trying to create a View from Blocks? It's not possible as far as I know, and it's not really a good idea I think. You could instead create a new Content Type (Structure -> Content Types), and add each of your block's contents into a separate node of the type you made.

Then use Views to create a node view, filtered by the Content Type you created. You can then display this view as a Block, with a "Slideshow" display style using the Views Slideshow module


How do I add a node field widget to a custom form? I added a number of fields to a node content type in Drupal 8. I want to create a custom form and add the field widget form (the one used during node creation) to this form.
How can I achieve this?

Answering my own question, I ended up using the following:
<?php
//Create an empty representative entity
$node = \Drupal::service('entity_type.manager')->getStorage('node')->create(array(
                'type' => 'article'
            )
        );

//Get the EntityFormDisplay (i.e. the default Form Display) of this content type
$entity_form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')
                                        ->load('node.article.default');

$form['#parents'] = []; // Mandatory, otherwise the widget class throws an error

//Get the body field widget and add it to the form
if ($widget = $entity_form_display->getRenderer('body')) { //Returns the widget class
  $items = $node->get('body'); //Returns the FieldItemsList interface
  $items->filterEmptyItems();
  $form['body'] = $widget->form($items, $form, $form_state); //Builds the widget form and attach it to your form
  $form['body']['#access'] = $items->access('edit');
}

see EntityFormDisplay::buildForm


How to permit users to view unpublished nodes which they didn't create? I have created two roles: Editor and Reviewer.

Editor must only create unpublished nodes; instead, Reviewer must publish and view these nodes.

How can I make users with a role see unpublished nodes? If I set the permission "Access the content overview page", the users with that role can modify all contents and I don't want this.

I tried the View unpublished module, but it has an issue, as reported in View unpublished breaks access rules defined by Views.

How to permit users to view unpublished nodes which they didn't create?

Solution 1

I would "set the permissions 'Access the content overview page' ...", and combine that with using the Rules module to prevent "the Reviewer can modify all contents". Read on for more details about how to do so.

Create a rule (using the Rules module), that is a variation of the rule I included (in export format) in my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?".

These are the changes to that rule to make it work for this case also:

Append /edit at the end anywhere there is already something like node/% (I assume when somebody tries to edit a node, they use a node with  /edit at the end, though any variation of that should work in a similar way).
Add a Rules 'Condition' to verify that the current user trying to do such edit does NOT have role "Editor".
You probably also need to add another Rules condition like "content is of type" (i.e. 'article' in your case, something that is not mentioned in your original question, but in an extra comment). That way the rules action does NOT apply for ay other content type.
Change the "Message" (in the Rules 'Action') to something that fits your needs.
Modify the Rules 'Action' to fit your own requirements, e.g. to issue a redirect to some other page.

Note that the Rules Event is "Drupal Is Initializing" ... Otherwise you are, for sure, "too late": you don't want the rule to be triggered after the edit session has been started already, instead it should be triggered before that. I.e when Drupal is getting ready to start an edit session.

Haven't experimented/tried creating this rule (= variation of the rule in the answer I mentioned above). But pretty sure it'll work.

You may also want to look at my answer to "https://drupal.stackexchange.com/questions/182958/how-to-limit-appearance-settings-based-on-roles-permissions/182959#182959" for another example of a rule, which uses some techniques similar to what you'd need here.

Solution 2

Solution 1 should work, but its weakness is that it's based on "Bypass Content Access Control". Personally I do not like that either. So I agree with your comment about that (a comment which has been removed via moderation). But hey, it's "a" solution to answer "your" (original) question.

If it was up to me to implement a "real" solution for the challenge you're trying to solve, I'd go for a plan b, as further detailed below.

Have a look at my answers to either of these questions:

How to implement a multi step approval with webforms/entityforms based on form components?
How can I allow anonymous visitors to submit content?

These answers explain how you can implement a workflow that is pretty (though not exactly) similar to what you are looking for.

To do so, it "only" requires you to use these modules (and regular content types):

Rules.
Node Convert.
Flag.
Content Access (already suggested in the previous answer also).

And by using such approach, it does not require modules like "Webform" or "Workbench" (modules that are typically involved for these kinds of workfows).

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module.

Note: This "Solution 2" is also how I implemented a variation of your question on 1 of our own sites: it starts from an Issue (= problem or feature request), evolves to a Recipe (= instructions about how to get something to work) and ends with a Software solution (= a plugin or so, whereas the Recipe becomes part of the documentation). Node Convert and Content Access do most of the work for this, and even works in D6 ...


insert webform component values into a custom table i am having trouble storing webform component values into a custom database table,
i have created a custom module to insert the data into the table but its not working and i can't figure out where my problem is can someone please help
here's my code  thanks

<?php
function customform_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'webform_client_form_24') {
        $form['#submit'][] = 'customform_additional_insert';
        if ($node = menu_get_object()) {
            $form['submitted']['node_id']['#value'] =$node->nid;
            $form['submitted']['amount']['#value'] = @$node->field_needed_amount['und'][0]['value'];
            $form['submitted']['full_name']['#value'] = @$node->title;
            $form['submitted']['image']['#value'] = @$node->field_student_photo['und'][0]['fid'];
        }
    }
}

function customform_additional_insert($form, &$form_state) {
    $data = $form['submitted'];

    // Insert a record into a 3rd-party module table when a submission is added.
    db_insert('sponsorship')
        ->fields(array(
            'n_id' => $form['submitted']['node_id']['#value'],
            'user_id' => 1,
        ))
        ->execute();
}
?>

I would suggest taking the data straight out of the webforms DB tables.

To understand how to do that we need to look at how data is stored in the DB.

Each time a new webform is created a row for it is created in the webform table. Each webform has a unique identifier called nid.

Each component added to the webform is stored in the webform_component table and has a unique identifier of cid (cid is only unique per webform, nid is also required to make the primary key).

Now when a user fills in the webform a row is created in the webform_submission table (with a unique id of sid) and each fields value is stored in webform_submitted_data. Each row in the webform_submitted_data table has a nid (the webform ID), sid (submission ID) and cid (the component ID).

So, if you wanted to get all of the data from a particular submission with the name of the field (or component), uid and the data submitted you can use the following query:

SELECT c.`name`, sd.`data`, s.uid
FROM webform_submitted_data sd
INNER JOIN webform_component c ON c.cid = sd.cid AND c.nid = sd.nid
INNER JOIN webform_submissions s ON s.sid = sd.sid
WHERE sd.sid = {YOUR SUBMISSION ID}

Or to show all of the values submitted for a particular field with uid and date then you could use:

SELECT sd.`data`, s.uid, s.submitted
FROM webform_submitted_data sd
INNER JOIN webform_component c ON c.cid = sd.cid AND c.nid = sd.nid
INNER JOIN webform_submissions s ON s.sid = sd.sid
WHERE sd.cid = {YOUR COMPONENT ID}


Popular tags view active class I have a view which is a HTML list of the most popular tags in a specific vocabulary it is displayed as a block on a page of most recent news items. It is also displayed on each individual news item.

When it is displayed on the individual news item page I would like any tag that the news item has been tagged with and that also appears in the popular tags block to be highlighted by adding a css class called active.

How would I achieve this?

Well, the only method I can think of is to do it the template, but have a feeling there must be a better solution than this... But to do it this way:

Edit your view and under Advanced click on Theme: Information. This shows a list of template file names that would apply to your view. If you had a view called tags then creating a template file called views-view-fields--tags.tpl.php would be appropriate. After adding your template file (in your themes directory) click the Rescan template files button.

The standard template file looks like this:

<?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; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

But if you changed it to this:

<?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
$current = false;
if(arg(0)=='node' && is_numeric(arg(1))) { // check if we are on a node page
    $node = node_load(arg(1)); // load the node
    $tag = strip_tags($field->content);
    foreach($node->field_tags[LANGUAGE_NONE] as $term) { // loop over the tags attached to the node
        if($term['taxonomy_term']->name == $tag) { // there is a match
            $current = true;
            break;
        }
    }
}
if($current) {
    print ''.$field->content.''; // add a span with current class
} else {
    print $field->content;
}
?>
<?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

The disadvantage of this method it that code needs to run for each tag in the list, but it would achieve the desired result.


Form Submission Problem I've a form...

function modulename_myform($form, &$form_state)
{
        $form['my_ta'] = array(
            '#type' => 'textarea',
            '#resizable' => FALSE,
        );
        $form['my_submit'] = array(
            '#type' => 'submit',
            '#input' => TRUE,
            '#value' => 'Submit',
            '#name' => 'sub_1',
            '#button_type' => 'submit',
        );
        return $form;
}

My form couldn't submit any data... So I tried doing two variants...

/* Form Submit */
function modulename_myform_submit($form, &$form_state)
{
    drupal_set_message('Submitted Value @name',array('@name'=>$form_state['values']['my_ta']));
}

Output : Doesn't print anything and says value is null at that location...

/* Form Submit */
function modulename_myform_submit($form, &$form_state)
{
    drupal_set_message(t('Submitting values: @values', array('@values' => var_export($form_state['values']['my_ta'], TRUE))));
}

Output : Prints the Dump with proper values...

Why is that? It should be giving me the text entered in my_ta right? Please help me...

the first attempt doesn't contain t() function in set message function... hence it's failing...


EntityQuery with a condition on an array I try to list all fields where a paragraph type is referenced (to find all contents which have paragraphs of a specific type).

My problem: I do a EntityQuery on field_config entity type to find the fields. But, the condition on which paragraph_type are targeted doesn't work correctly and return all fields which can content a paragraph disregarding the type.

Here my code:

// Recover my paragraph_type selected in my form.
$paragraph_type = $form_state->getValue('paragraph_type');

// List all field_config which referred this paragraph_type.
$query = \Drupal::entityQuery('field_config')
  ->condition('field_type', 'entity_reference_revisions')
  ->condition('settings.handler', 'default:paragraph')
  ->condition('settings.handler_settings.target_bundles', $paragraph_type, 'IN');

$field_config = $query->execute();

For exemple, I have a paragraph type "press_release_about" which can be add only in press release in a specific field. But for this paragraph (and all others), it's all fields which can contains a paragraph in the system which are returned.

When I inspect a field_config which referred paragraph, I can see that settings.handler_settings.target_bundles is an array of the paragraph types which can be add with this field. The format is:

[settings:protected] => Array
    (
        [handler] => 'default:paragraph'
        [handler_settings] => Array
            (
                [target_bundles] => Array
                    (
                        [1col_text] => 1col_text
                        [1col_image] => 1col_image
                        [1col_quote] => 1col_quote
                        [1_col_graphique] => 1_col_graphique
                        [2_cols_texte_media] => 2_cols_texte_media
                        [2_cols_texte_graphique] => 2_cols_texte_graphique
                        [2_cols_text] => 2_cols_text
                    )
              )
         )

If I remove the condition ->condition('settings.handler_settings.target_bundles', $paragraph_type, 'IN'), this change nothing. And if I change the INby NOT IN, I have no result.

I don't know if I don't write my condition correctly or if my error is elsewhere.

try to use an array instead of the value of $paragraph_type.

that would be like this :

->condition('settings.handler_settings.target_bundles', [$paragraph_type], 'IN')


Authenticate against a Drupal Instance Is it possible for an application (e.g. a Java Web app) to authenticate against the Drupal users table?  I know they use an SHA512 encryption, but I am wondering if there is any way to expose this service outside of Drupal

Perhaps use hook_auth within Drupal, but expose that hook externally somehow?

hook_auth() has been gone since Drupal 5.

But it sounds like you're looking to implement something with user_authenticate().

General outline of how to accomplish this (note that this will send passwords as plaintext - use SSL if that's a problem):

Create an API page using hook_menu() for your app to hit.
In that pages callback function, accept the username and password as POST requests (or however you want to build your app) and run them through user_authenticate().
Return the results of user_authenticate() (either FALSE: fail or numeric: pass) as a json string (or whatever you want) and act accordingly within your external app.


How can I show 4 latest articles in ascending order? Lets say I have 10 articles, tenth being the last one created.
I want my view block to show 4 latest articles, but in ASCENDING order.

7,8,9,10 - something like this.

Can I somehow filter out the exact number of latest articles?

Just output the rows you need and reverse them with CSS.

.view-content {
  display: flex;
  flex-direction: column-reverse;
}


Listing the terms of a Taxonomy Vocabulary in a Tree structure using Views I am on drupal7. I am trying to list all the terms of a vocabulary in a view. However the Taxonomy vocabulary has multilevel categories and subcategories.

  Is there any module to Show the list in a view so that Initially
  Parents will be displayed, then when hovered or clicked on parent all its child terms are displayed, if hovered or
  clicked on child its sub-child are shown.

I want to display the list in the sidebar first or in the header part of the front page .

Example:

Similar to the style how categories in Flipkart are displayed.

Any help!

Taxonomy menu module you are looking for and also you can integrate with views,
See the demo here

  Custom Menu per vocabulary
  Uses the default taxonomy term path or custom paths
  Integrate with Views
  Integrate with Pathauto: use URL/path aliases
  Does not interfere with other menu modules


Prevent / stop user_save Our current setup involves a multisite for different parts of our company. We need all sites to share a single user pool for various reason, but each site has slightly different user profile regulations that we need to adhere to. We have different permissions for profile fields on each site, so I need to prevent user profiles being saved if a user isn't on their home site.

I have a field in every profile called "Domain". I intend on pairing this to the current site url to determine if the user is on their home site or not. If not, I need to stop all user_saves from completing. What would be the best way of going about this?

I've found in D6 hook_validate('user') would have done the trick, but there doesn't seem to be anything in D7 that I can use. Would hook_presave work, if I throw an exception?

You could also try to alter the "user_register_form" and "user_profile_form" and add a custom validation.
So in that validation you'll be able to check the domain and set an error if it's wrong.


Exclude current node from entity reference view (for related news) In Drupal 7 I have a news content type with a simple related news selection list. This works like a charm, I use an entity reference view to fill the list and new news-items are created just like they should be. But once the news-item is published it will of course be shown in the list. If you select it, the standard behaviour will be to render its full content view, resulting in a recursive content error.

How can I create an entity reference view that excludes the current node? I have found a lot of related issues, but nobody seems to answer the question of using parameters at all in this special kind of view. I tried to add an argument to the filter using the token syntax which says "AND Nid not equals [node:id]" but that turns out to be ignored. I also found that when you include the view it is possible to send parameters to it, but I was unable to find documentation for how to use them.

Does anybody have more information/documentation about this?

there is a patch fixing that issue and helping you to use [node:nid] as an arg here.

Otherwise, did you try Entity Reference View Widget ?

  The module has a way of hiding selected items from the View. Simply
  add a base field contextual argument (Product ID for products, Node ID
  for nodes, etc) and in the "More" fieldset enable "Allow multiple
  values" and "Exclude". Then edit the Entity Reference field, and in
  the widget settings enable "Pass selected entity ids to View ".


Deleting content types programmatically I'm trying to delete some content types which are no longer used but are still active.

I'm going to deploy the update using hook_update_N and have this so far (Code taken from node_type_delete_confirm_submit:

function hook_update_N(&$sandbox) {
  node_type_delete('mynodetype');
  variable_del('node_preview_mynodetype');
  node_types_rebuild();
  menu_rebuild();
}

The problem I'm having is that the node type is deleted, but the nodes of that type are still there in the database. Running cron hasn't deleted those nodes (I'm not even sure if that's the default behavior when deleting content types through the admin UI)

My question is:

Are the nodes deleted automatically after a certain time through Cron or some other method? If not then doing it manually, would it be best to do it before deleting the content type or after?

$ournewtype = 'voucher';
$sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
$result = db_query($sql, array(':type' => $ournewtype));
$nodeids = array();
foreach ($result as $row) {
  $nodeids[] = $row->nid;
}
node_delete_multiple($nodeids);
node_type_delete($ournewtype);


Drush get all non-required modules In Drupal, the Module Filter module adds four search filters to /admin/modules:

Enabled
Disabled
Required
Unavailable

If "Required" is unchecked, the admin page will only show modules that are not dependencies of any other module. I know that drush pm-list --status=Enabled will show only the enabled modules, but it doesn't filter out modules that are required by other modules.

Is there a way to do the same thing using drush?

Drush does not support such a feature, but it sounds like it would be an interesting enhancement.


Hide webform components after submission I'm trying to autohide all my webform components after submission. I've tried to add an extra submit handler to the form, but no luck there.
The webform is posted by using AJAX (but nothing is shown in my Console).

Is there some module or hook I'm overlooking?

I managed to do so with a hook_form_FORM_ID_alter:

function mymodule_form_myformid_alter(&$form, &$form_state, $form_id) {
    if(!empty($form_state['input'])) {
      $items = array('name', 'firstname', 'zip', 'phone', 'email');

      foreach ($items as $value) {
        $form['submitted'][$value]['#type']     = 'hidden';
        $form['submitted'][$value]['#title']    = '';
        $form['submitted'][$value]['#required'] = 0;
      }
      $form['actions']['#type'] = 'hidden';
    }
  }

It's not the most clean way to do so, but it does the trick :)


Views table aggregation with counts per value of a field A person can log multiple cases: Case 1, Case 2, Case 3

a case can have multiple states: New, Active, Resolved

Using a views table I want to generate a view where each person has one row, and I can see how many new, Active and Resolved cases each has:

Person   | States
Person 1 | New(1), Active(3), Resolved (13)
Person 2 | New(5), Active(3), Resolved (1)

Or something like this:

Person   | New | Active | Resolved
Person 1 | 1   | 3      | 13
Person 2 | 5   | 3      | 1

With normal aggregation all I can achieve is:

Person   | Cases
Person 1 | 17
Person 2 | 9

Surely I am missing something?

Views_merge_rows module will save your day! Assuming that the States field is a list field.

1) In your aggregation enabled views with table display add a User:Name (Group results together), a States field (COUNT, Excluded from display) and again a States field (Group results together, Rewrite Results > Rewrite the output of this field: [field_states]  ([field_states_1])).

So you will get a list of users with states but with one row per node. Here is a screenshot:

2) Then, enable the views_merge_rows module. In you Merge rows settings do this:

So you get what you want!


Theme for specific requesting computer Similarly to changing the theme based on the requesting browser or logged in user, I want to change the theme based on where the request is coming from.

If a request comes from a specific address, domain or computer, how can I force a specific theme? I can't seem to find a module that accomplishes this.

Possible with

ThemeKey
ThemeKey Properties


How do I get an OG Group Menu block to appear in View? Running Drupal 7 with OG 7.x-2.3 and OG Menu 7.x-3.0-rc4.  I have added a view to a Group Menu that lists all content in the group.  All I want is for the group menu block to display when the view is executed.

I have added code in hook_views_pre_view to maintain the group context when view is executed.

I also attempt to utilize OG URL Group Context Detection by creating this URL path for the view:

group/%/content

I also added code in the view header/footer to detect if there is a group context when view executes.  There is.

Despite all this, I can not get the Group menu block to display when the view is executed.  Does anyone know of a way to accomplish this?

Resolved my issue, more or less, here: https://www.drupal.org/node/2195889#comment-8493709

First, setting all group views to use this url format: group/%/(title)
Always set group context in hook_views_pre_view() when arg(0) == 'group' and arg(1) is numeric.
3 .Use hook_block_info() to create my own block.
Use hook_block_view() to make my block content equal that generated by og_menu_block_view().
Go into block settings, and set the block to only appear on views = group/%/(title).
Set the block to appear at the same weight (just above or below) as the OG Menu block.

And, voila!  When I click on view from  OG Menu, the OG group menu itself persists.


Create multiple users roles and views at the same time I'm using D7, I need to create views and user roles, when I'm using the interface mode, it takes me too much time, how can I do that using code? or could you please suggest to me a module to install, that can create, for example 10 roles at the same time, or cloning a view 5 times at the same time.

If you set up Drush, which is is a command line shell and Unix scripting interface for Drupal, then you can create a role with the command:

drush role-create

This command accepts and requires 2 arguments, the first one defines the machine name of the role and the second one the human readable name. For example:

drush role-create 'my_new_role' 'My New Role'

Would create the role 'My New Role' with a machine name 'my_new_role'

Drush can also be used to quickly create views. Due to the variety of possible setups depending on your use case, it is probably best to start by looking at the documentation on https://drushcommands.com


Site logo on user registration email I am using drupal 7. I want to add the site logo on the user registration email, when new user added with my site. How can i include the logo path on the user registration settings. It doesn't support the html  tag format. I have also searched with tokens, but there is no token for including logo. How can i add the logo. Please help me.

Thanks,
Sathish

Drupal doesn't support HTML e-mails out of the box.  To do this, you can download either:

Mime Mail

or

HTML Mail

You will also need the Mail System module.  On my own site, I use the Mime Mail module with a PHP template that I designed (following the instructions in the Mime Mail documentation) to attach my logo to outgoing e-mail messages.


add a block of related products to any search result item What I want is , when a user searches for a special product , for each single search result a block of similar products show up (containing products image and product title as images alt).

I do have a taxonomy vocabulary called usability with terms gaming , light weight and ... ,

so if a search result is of kind product , the block of related products should be seen under it

So my questions are :

how to alter search result view so I can place my block
how can I fetch data of an result item to pass it to view filter

you should be able to do with a combination of these:

Views Field View Module

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

and

Views Related Content Module

  Views Related Content is an extension to the Views module. It helps
  show the related contents, related nodes on the content detail page.
  This module makes it easy for you to work with contents, nodes by
  adding the filter criteria by Author, Content Type, Taxonomy Terms in
  the Views configuration.

Adding the related content view as a field in the primary view should show the results for each row. Exactly how to integrate them depends on your set up.


How do I keep the trail for the breadcrumbs till the specific nodes? When I create a new node and I assign a tag to it, I can view it from the corresponding taxonomy page. The breadcrumbs seem to follow the trail normally

Home>>category>>subcategory

until the very leaf node, at which point it indicates only

Home>>node

Why so? How do I keep the breadcrumb trail from collapsing?

Breadcrumbs can sometimes be a bit confusing. In my experience the breadcrumb never behaves 100% as you would want it to behave, if you use it as it comes 'out of the box'.

Luckily also other people got annoyed be the standard breadcrumb (mis-)behaviour so over the years a sea of breadcrumb related modules found its way to drupals module collection. Here is an overview / comparison with some 10-15 modules listed. Maybe Breadcrumbs by Path could suit your needs…


Get the t function to work in a custom php file I am having a custom hand coded PHP page within a Drupal module that loads in a fancybox.
I want the Drupal t() function to work in it. What should I include in the file to make it function?

Include these lines in your php file

define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


set a entity reference field programmatically I have a node form, with an entity reference field.

I'm trying to hide the reference field from the node form and automatically reference an entity created by the node author.

Im using code like the following to fetch the entity to be referenced.

  $query = new EntityFieldQuery();
  global $user;
  $query->entityCondition('entity_type', 'node_ref');
  $query->fieldCondition('cmp_ref', 'target_id', $user->uid);
  $result = $query->execute();
  $storeids = array();
  foreach ($result as $ref) {
   foreach ($ref as $ref_id){
    $refids[] = $ref_id->id;
   }
  }
  $entity = entity_load('node_ref',$refids);
  foreach ($entity as $ref) {
    $ref_id = $ref->id;
  }
  return $ref_id;

I think its a long way of doing it but I just modified some code I found in a module.

Now upon save of the node I would like the entity reference field to reference $ref_id

So something like

  $node->entity_reference_field[$node->language][]['target_id'] = $ref_id;

How do I call this on node submit? If I unset the field on the node form will the value still be set?

Thanks for any help

In case entityreference prepopulate is not a viable option, I always use an EntityMetadataWrapper to set field values.

function mymodule_node_ref_presave($node_ref) {
    global $user;
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node_ref');
    $query->fieldCondition('cmp_ref', 'target_id', $user->uid);
    $result = $query->execute();
    // A more efficient way to grab entity ids from a EFQ
    if($result['node_ref']){
      $ref_ids = array_keys($result['node_ref']);
    }
    if ($ref_ids){
      // Load the entity w/ metadata wrapper to set field more transparently
      $node_ref_wrapper = entity_metadata_wrapper('node', $node_ref);
      $node_ref_wrapper->entity_reference_field->set($ref_ids);
      // Because this operation is going to execute a save anyways,
      // we don't need to do $wrapper->save()
    }
}


What is the feasibility of using Entity Reference instead of Taxonomy? I read an opinion that argues for using Entity Reference to content types as a complete replacement for Taxonomy, on the basis of UX and performance. The UX issue appeals to me - happy content managers (who don't have to go dig around in Taxonomy ever) is important!

In considering this strategy for a new site that will be essentially built around one content type that can be tagged lots of different ways, I have a couple questions:

Is there really a performance difference? Can it be quantified?
I need hierarchy support. Is there a good option? Searching around, the land of Entity Reference hierarchy options exists but seems like a wild west at this point.
Are there better solutions if my only complaint is site admin UX?
Taxonomy is the best-practice, as it is in core, for the general use case. I'm wondering what else I haven't considered in going off the beaten path here.

(Note a very similar question has been asked before, but it is talking about using Entity Reference to taxonomy terms, rather than replacing the Taxonomy module. I also understand the purpose of Taxonomy, but am wondering what would make alternatives worth considering.)

Is there really a performance difference?

For sure! Totally different and independent pieces of code was used for it, so there must be.

  Can it be quantified?

You can measure it, but because taxonomy is pretty well defined, and references are open to configuration, your mileage will vary. Overall, taxonomy is older, and optimized for speed - a lot of terms on one node is common. Also, it's easier to optimize something that works only one way.

  I need hierarchy support. Is there a good option? Searching around, the land of Entity Reference hierarchy options exists but seems like a wild west at this point.

Exactly! Everyone consider different things good, so implementations vary. I don't know what your "good" means, so I can't tell if it happened to be similar to one of already implemented "good".

  Are there better solutions if my only complaint is site admin UX?

Again - it depends on what exactly you consider better. There are things like Taxonomy Manager, but it addresses things it's creator considered that need to be addressed, in a way that's better - for him.

  Taxonomy is the best-practice, as it is in core, for the general use case.

Not really... But that was a claim, not a question anyway.

  I'm wondering what else I haven't considered in going off the beaten path here.

And this is simply too broad for Q&A


Retrieve value from an array I have an array, that I want to retrieve the values from.
When I test the array with a print_r, it says that it has the right values. But when I want to show them  in their right places, it says that it has no values.

function employees_items($nodeid, $language)
{
  $query  = db_query(//SOME QUERY);
  $rows   = array();

   foreach ($query as $row) {
    $rows[] = array(
        $row->nid,
        $row->title,
        $row->field_service_nummer_value,
        $row->field_support_email_value,
        $row->uri,
    );
}

    return $rows;

}

Here I want to retrieve the values...I want the value in $row->uri. The errormessage: Trying to get property of non-object i employees_block_view()

  function employees_block_view($delta = '')
 {
 if (array_key_exists($brandpage_id_page, $medarbejder_brandpages))
    {
     switch ($delta)
    {

        case 'employees':

        $employees = employees_items($brandpage_id_page, $lang_name);

        foreach ($employees as $row)
            {

              $block['content'] .= '
';
              $block['content'] .= 'uri). '" alt="Vores support medarbejder" />';
   }
  return $block;
 }

Try $row['uri'] instead.  As 'uri'  is merely the key and not another object.

In this line of code:

$block['content'] .= '<img style="width: auto; height: 100px;" src="'.file_create_url($row->uri). '" alt="Vores support medarbejder" />';

you refer to another object, the uri ($row->uri). Within the $row array, that you printed with print_r, there is the key 'uri'. To get the value of that key you should use $row['uri'].


How to implement a user profile attribute to indicate "Where did you hear about us"? I want to add a "Where did you hear about us?" checkbox list to user profiles. There will be 6 radio buttons and an "Other" textfield.

There's no need for a taxonomy vocabulary, which was my first thought. I also thought about using Webform, but that feels like overkill and I think I'd have to do more work to link the form to the user.

Really, I just want to view the user profile and say "Oh look, they found out about us from twitter ...". So what are good techniques/approaches to implement this?

This question does not say if it is about D6 or D7, but how about just a pull-down selection list (could be a checkbox as well if you prefer)? Similar to what you can see on this registration page, around the middle of the page (still a D6 site, D7 should be similar).

If it makes sense, I'd be happy to further enhance my answer to include the details of how I implemented that (piece of cake).

Note: please do not submit a real registration request if you checkout the link I added here ... unless you really want to sign up there (which requires prior approval ... ).


Disable "Operating in maintenance mode. Go online." The solution for Drupal 7 is using the following code, as per answer of How can I disable the message “Operating in maintenance mode. Go online.” in maintenance mode?

function mytheme_preprocess_page(&$vars) {
  if (variable_get('maintenance_mode', 0)) {
    $message_count = count($_SESSION['messages']['status']);
    if($message_count > 1) {
      array_shift($_SESSION['messages']['status']);
    }
    else {
      unset($_SESSION['messages']['status']);
    }
  }
}

What is the solution for Drupal 8?

I cannot figure out how to do it with https://www.drupal.org/project/disable_messages.

Hide/disable the message for everyone including the user #1.

Drupal 8 version:

function mytheme_preprocess_status_messages(&$variables) {
  if (\Drupal::state()->get('system.maintenance_mode')) {
    $message_count = count($variables['message_list']['status']);
    if ($message_count > 1) {
      array_shift($variables['message_list']['status']);
    }
    else {
      unset($variables['message_list']['status']);
    }
  }
}


Use of relationships (joins) in Views I use Drupal 7. I have read dozens of questions that revolve around the need to incorporate relationships among tables in Views (even many where the person asking the question phrased it differently, and the person answering the question said "just use Relations in Views").  I have also read various books that nearly always use single tables in example of pulling data from databases. I rarely see any understandable explanation of the use of "relations" in views. What's the point of using a relational database if it is so difficult to use joins? Can anyone shed any light on this? I've read the explanation in Pro Drupal 7 Development, which is arcane at best.

Bruce

Views is an awesome query builder and formatter - all through the UI. In my past coding days I did that all manually and recently I started to appreciate the power of views.

Just go into views settings / basic and turn on "Show the SQL query". Then create a basic view of nodes. Now add fields and filters to see how the SQL changes. Add a relationship and you'll see how views adds the "SQL Joins" automatically.

When you add some "fields" it will automatically add some joins without you having to add relationships. For example add "last comment author" field to a node and views will automatically add:

INNER JOIN {node_comment_statistics} ...
LEFT JOIN {users} ....

When you want to add some fields that you don't see in the selection, for example "author of the node", you add the relationship "Content: Author - Relate content to the user who created it."
Views adds the SQL:

INNER JOIN {users} ....

Now you'll have the user related fields available, for example "(author) User: Picture (Picture)".

So in summary: most views will pull data from multiple tables but most of that detail is hidden from the developers because views does it all for you. If you understand tables and SQL turn on the SQL output and see what views does. Sometimes all those "joins" are not optimal from an optimization standpoint ;-)


path template page--path.tpl.php I am using one shared template - page.tpl.php for basic pages such as about us, contact us,etc. However, there are rental properties that share a different template, so i have created Content type - property page, and i would like to share a separate template for all pages of content type - property page. How to do it?

I tried to add path 'rentals/property1-3' and use page--rentals.tpl.php but it doesn't work

Any help appreciated.

Thanks

You need to use this format for drupal to recognize the template for that content type.

page--machine_name.tpl.php

The machine name should be displayed on your YOUR_SITE_NAME.com/admin/structure/types page.


How to capture URL from a webform without using token value? I have a Webform as a block. Set to show on a certain content type with a hidden field returning the token value %get[q] to let the admins know from which page the form was submitted from.

Unfortunately it has intermittent errors that I've not been able to duplicate. Is there a better way to capture the URL?


Hide 'configure block' for Omega theme? How can I hide the 'configure block' mouseover from appearing? Im using the Omega theme.

Its breaking parts of my site but I cant stop it from appearing with permissions as certain users need the permission to edit blocks.

If you are using Omega theme version 7.x-3.1, you can go to the templates folder and edit region--content.tpl.php. In line 12 you will find the following:

   <?php if ($action_links): ?>
<?php print render($action_links); ?>
<?php endif; ?>

You can comment this line out, or delete it.


How to make "php if" for views block? I'm generate views content with this:

<?php echo views_get_view('xtr')->preview('block_1', array(1)); ?>

But I need to add slidewrap class only if the content available.

Below is what I've tried which not working:

<?php if (views_get_view('xtr')->preview('block_1', array(1))): ?>

<?php echo views_get_view('xtr')->preview('block_1', array(1)); ?>

<?php endif; ?>

1.If you want to just add a class to the content of view container you can add it from the view itself

if you have a template file for views you can add the class there. or you can set it as in views header and footer


How do you disable modules in bulk via Drush matching a specific pattern? Currently I have to disable all of the ubercart modules in bulk, but there are too many of them to do it one at a time via the modules page. And doing it via drush doesn't disable every module related to ubercart sometimes. Is there a quick way to disable these modules via Drush in bulk matching a specific pattern?

Here's the drush recipe combined with a few other commands to disable modules in bulk:

drush pm-list | ack uc_ | ack Enabled | grep "\((.*)\)" | awk -F'(' '{print $2}' | awk -F')' '{print $1}' | xargs -i drush dis '{}' -y

Broken down:

drush pm-list lists out all of your modules
ack uc_ returns only the lines matching "uc_"
ack Enabled returns only the enabled modules
grep "\((.*)\)" matches the words in parentheses
awk -F'(' '{print $2}' breaks up the line starting with the ( character
awk -F')' '{print $1}' breaks up the line starting with the ) character
xargs -i drush dis '{}' -y runs the returned result into drush disable command with the -y parameter for yes to all.

Thanks to greg_1_anderson, I updated it to be a bit shorter.

drush pm-list --status=enabled --pipe | grep 'uc_' | xargs -i drush pm-disable '{}' -y


Views show content where field used in user and node entity matches I have an entity reference field called 'field_client' (client) used on both the user entity and on a node content type called 'ticket'.

I'd like to build a view that only shows nodes where this entity reference field value matches the logged in user's client entity reference field value.

I'm struggling to determine how to build the contextual filter and if a relationship is required.

Option 1

Add a contextual filter of your entity reference field.

Then programatically get the logedin in user's entity reference field value. (I'll let you figure this part out)

Once you have this value, you can programmtically print the view like this:

print views_embed_view('view_name', 'view_machine_name', $value);

This is the machine_name

ex: print views_embed_view('hello_kitty', 'block_1', $value);

Option 2

For a non-programatic answer, View Fields View module.

1) Create a User view with a Contextual filter of User ID. Select logged in user's ID. Now add the entity reference field as field.

2) Create a Content view with a Contextual filter of Entity Reference.

3) Go back to your User View, hide the entity reference field and add View as field. Select the View in #2 and for contextual filter, use the replacement pattern of the entity reference field.


Reuse fields programmatically Conceptually and for performance purposes it is advisable to reuse existing fields in Drupal. This is very easy to do manually, but my question is, how can I do this programmatically?
I have the following code:
$all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('taxonomy_term', $vid);

if (!isset($all_bundle_fields['field_image'])) {
  FieldStorageConfig::create(array(
    'field_name' => 'field_image',
    'entity_type' => 'taxonomy_term',
    'type' => 'entity_reference',
    'settings' => [
      'target_type' => 'media',
    ],
    'cardinality' => 1
  ))->save();

  FieldConfig::create(array(
    'field_name' => 'field_image',
    'entity_type' => 'taxonomy_term',
    'bundle' => $vid,
    'label' => 'Logo',
    'description' => 'Logo to represent the term.',
    'required' => FALSE,
  ))->save();
}

In this example, I extract all the fields from the vocabulary and only create the field if and only if it does not exist previously in this vocabulary. The above code works.
What does not work here is if that field has already been created for another entity or vocabulary. This is what I would like to find out in order to make a complete reuse of the fields.
Thanks in advance.

Until someone tells me how an existing field can be reused I have got a remedy. As my "need" was to reuse fields that I have been creating in various vocabularies, what I have done is the following:

Create a function that goes through all the existing vocabularies and checks if a certain field, passed by parameter, exists.
If so, it returns me the name of the vocabulary where it already exists. This saves me from creating the corresponding database table.
Then I check if the vocabulary where the field exists is my own vocabulary. In case it is not, I link it.

This would be the final result. First, the function:
function existsField($field) {
  $vocabularies = taxonomy_vocabulary_get_names();

  foreach($vocabularies as $vocabulary) {
     $all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('taxonomy_term', $vocabulary);
     if (isset($all_bundle_fields[$field])) {
        return $vocabulary;
     }
  }
}

Next, the final code:
$vocabulary = existsField('field_image');

if (empty($vocabulary)) {
  FieldStorageConfig::create(array(
     'field_name' => 'field_image',
     'entity_type' => 'taxonomy_term',
     'type' => 'entity_reference',
     'settings' => [
        'target_type' => 'media',
     ],
     'cardinality' => 1
  ))->save();
}

if (empty($vocabulary) || $vocabulary != $vid) {
  FieldConfig::create(array(
     'field_name' => 'field_image',
     'entity_type' => 'taxonomy_term',
     'bundle' => $vid,
     'label' => 'Logo',
     'description' => 'Logo to represent the term.',
     'required' => FALSE,
  ))->save();
}


How to create multiple node at a same time programatically? I am creating a node via code

   function mymodule_form_alter(&$form, &$form_state, $form_id) {

        if($form_id=='article_node_form'){
            $form['#submit'][] = 'newApp';
        }
}

functin newApp($form,$form_state){
        $node = new stdClass();
        $node->type = 'application';
        node_object_prepare($node);
        $node->title = $prductData->title;
        $node->language = LANGUAGE_NONE;
        node_save($node);
        }

It's creating the application node. I also alter content type node form for article. When I click save button of article content type it's creating my application type node, but it's not creating the article type node. I need the site to create one node create of article type and second application when I save a new article.

I guess it is because you overriding node variable.

In my opinion the more Drupal way is to use Rules module. There you can create   application node after article is created.


View: Only display parent term? I'm trying to create a view that will display a number of nodes sorted by their parent terms.

For instance, if my terms have the following hierarchy:

- Fruit
--Apple
--Banana
--Orange
-Vegetable
--Broccoli
--Carrot
--Beet

I would ideally like to get two 'headings', one for Fruit, one for Vegetables and then list nodes with any sub-term in those sections.

I have tried using view relationships and contextual filters but I just feel lost. What should I do?

Thank you!

Go to your view settings. Add term relationship - your term field. Add Filter critera - Parent term. Operator 'equal' value - leave empty


EntityFieldQuery with "NOT IN" FieldCondition and "=" FieldCondition on the same multi-value field is only processing one FieldCondition The EFQ is:

$query->entityCondition('entity_type', 'node')
    ->fieldCondition('field_terms_wb_access', 'tid', array_keys($children), 'NOT IN')
    ->fieldCondition('field_terms_wb_access', 'tid', $tid, '=')
    ->propertyOrderBy('title');

and the query being generated is

SELECT DISTINCT
  field_data_field_terms_wb_access0.entity_type AS entity_type,
  field_data_field_terms_wb_access0.entity_id AS entity_id,
  field_data_field_terms_wb_access0.revision_id AS revision_id,
  field_data_field_terms_wb_access0.bundle AS bundle
FROM {field_data_field_terms_wb_access}
  field_data_field_terms_wb_access0
INNER JOIN {field_data_field_terms_wb_access}
  field_data_field_terms_wb_access1
  ON field_data_field_terms_wb_access1.entity_type = field_data_field_terms_wb_access0.entity_type
  AND field_data_field_terms_wb_access1.entity_id = field_data_field_terms_wb_access0.entity_id
INNER JOIN {node} node
  ON node.nid = field_data_field_terms_wb_access0.entity_id
  WHERE  (
    field_data_field_terms_wb_access0.field_terms_wb_access_tid
    NOT IN  (
      :db_condition_placeholder_0,
      :db_condition_placeholder_1,
      :db_condition_placeholder_2,
      [...]
      :db_condition_placeholder_22
    )
  )
  AND (
    field_data_field_terms_wb_access1.field_terms_wb_access_tid = :db_condition_placeholder_23
  )
  AND (
    field_data_field_terms_wb_access0.deleted = :db_condition_placeholder_24
  )
  AND (
    field_data_field_terms_wb_access0.entity_type = :db_condition_placeholder_25
  )
  ORDER BY node.title ASC

However, why I include both fieldCondition('field_terms_wb_access', 'tid', $tid, '=') AND fieldCondition('field_terms_wb_access', 'tid', array_keys($children), 'NOT IN') clauses, it seems to only honor the first one and ignore the second. If I comment out the first one, however, then the second one is honored. I get no errors in the php error log or on the screen.

This happens because EntityFieldQuery::addFieldCondition() is written like so:

protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  // The '!=' operator is deprecated in favour of the '<>' operator since the
  // latter is ANSI SQL compatible.
  if ($operator == '!=') {
    $operator = '<>';
  }
  if (is_scalar($field)) {
    $field_definition = field_info_field($field);
    if (empty($field_definition)) {
      throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
    }
    $field = $field_definition;
  }
  // Ensure the same index is used for field conditions as for fields.
  $index = count($this->fields);
  $this->fields[$index] = $field;
  if (isset($column)) {
    $conditions[$index] = array(
      'field' => $field,
      'column' => $column,
      'value' => $value,
      'operator' => $operator,
      'delta_group' => $delta_group,
      'language_group' => $language_group,
    );
  }
  return $this;
}

Note that a field condition is stored as an array in the $conditions variable, indexed by a a value that represents the field. When you add a new fieldCondition on the same field, it just overwrites the array.

I don't know if this was intentionally designed this way, or if it's a bug... but the behaviour you are seeing is exactly what the code says it should do!


WYSIWYG error when using managed_file and AJAX I have a form that has both a managed_file element and a text_format element. Both are encapsulated in a wrapper div (using #prefix and #suffix). On submit, an AJAX callback is executed and both elements are populated with data.

However, when the form is rebuilt, the WYSIWYG editor disappears. The following error is displayed in the javascript console of my browser: Uncaught [CKEDITOR.editor] The instance "edit-text-value" already exists.

When I remove the managed_file element, the form works as it is supposed to. It probably has something to do with the Drupal behaviours not being executed properly (managed_file widget?), not removing the editor instance.

go around ckeditor.utils.js, the thing is that at various events ckeditorOff() function is called which causes ckeditor to go off, i just commented out a destroy call in the ckeditorOff() method and the RTE disappearance issue got solved


Change contact setting flood limit I want to change the contact setting flood limit, but I don't find the correct place. How I change the flood limit for sent messages?

There isn't an interface to change this, but you can do it by importing a config file. You need to get a hold of contact.settings.yml file. Default looks something like this:

default_form: feedback
flood:
  limit: 5
  interval: 3600
user_default_enabled: true

You can see the flood limit and interval which you can change and then import the file using the config management system.


What is the correct way to implement a custom block with twig template? I know there are tons of posts for this but I think I have a problem with understanding how a custom block with a custom template is meant to work in Drupal 8.
Problem
My aim:
To place a custom block to display social icons. The block needs some logic (generate a url for example).
My main problem:
Everything seems to work so far but I do not get the variables passed through the twig-template (url and urlencode). They always contain the default value from the module-file (null).
What I have so far:
Files under /modules/custom/wzm_social_icons:

wzm_social_icons.info.yml
wzm_social_icons.module
src/Plugin/Block/WzmSocialIconsBlock.php
templates/block--wzmsocialicons.html.twig

I installed the module and also placed a custom block with id "socialicons". The block itself is just a placeholder with no special fields.
Files
wzm_social_icons.module
function wzm_social_icons_theme($existing, $type, $theme, $path) {
  return array('block__wzm_social_icons' =>
    array(
      'variables' => array(
        'url' => null,
        'urlencoded' => null
      ),
      'template' => 'block--wzmsocialicons'
    )
  );
}

WzmSocialIconsBlock.php
class WzmSocialIconsBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $oUrl = Url::fromRoute('<current>');
    $sUrl = $oUrl->toString();
    $sUrl = \Drupal::request()->getSchemeAndHttpHost() . $sUrl;
    $sUrlEncoded = urlencode($sUrl);

    return array(
      '#url' => $sUrl,
      '#urlencoded' => $sUrlEncoded
    );
  }
}

Nothing special in the twig-template - just the output for {{ url }} and {{ urlencode }}.
I think my main problem is to understand what needs to be declared with which key in the module-file and if the custom-block-id is used somewhere. No clue so far.
Thanks for any help!
Cheers

You're almost there. In your WzmSocialIconsBlock.php return the following:

return array(
  '#theme' => 'block_wzm_social_icons',
  '#url' => $sUrl,
  '#urlencoded' => $sUrlEncoded,
);

You might also want to simplify your hook_theme by letting it autodetect your template by name:

return array('block_wzm_social_icons' =>
  array(
    'variables' => array(
      'url' => null,
      'urlencoded' => null
    ),
);

And name your template templates/block-wzm-social-icons.html.twig.


Export Paragraph bundles I know drupal config:export:content:type is for exporting a content type. Is there a way to do this for a Paragraph bundle?
drupal config:export:paragraph:type doesn't work.

Turns out it can be done with the config:export:entity command.
drupal config:export:entity paragraphs_type [PARAGRAPH_TYPE] --module="[YOUR_MODULE]" --optional-config --remove-uuid --remove-config-hash --include-module-dependencies


How to print/render nested Paragraph values to twig template? I'm trying to figure out how I can render values from nested Paragraphs. Basically I have field/values from a Paragraph within a Paragraph I have tried experimenting and searching for answers but I can't seem display the values from the nested Paragraphs to the twig template.

Here is the sample of the code below that I have been working on

First Paragraph
{% for paragraph in node.field_sidebar_area %}

{{ paragraph.entity.field_label.value }}

        {% for block_query in paragraph.entity.field_block_query  %}

            {{ block_query.entity.body.value | raw }}

        {% endfor %}

         {% for link in paragraph.entity.field_link_item %}

{{ link.url }}

{{ link.title }}

         {% endfor %}

    Second Paragraph
    {% for object in paragraph.node.field_sidebar_content %}

        {{ object.entity.field_label.value }}

    {% endfor }

{% endfor %}

I am also curious about the best way to do this. While I'm still trying to figure out what that is, here is what I've done:

I've enabled the Twig Tweak module, and inside the first paragraph template, I pull in the second paragraph with a selected view mode.

{{ drupal_entity('paragraph', content.field_sidebar_area[0]['#paragraph'].id(), 'MY_CUSTOM_VIEW_MODE') }}

And then in the template for the second paragraph, I can adjust the Twig as I please. Note that the naming convention would be:

paragraph--PARAGRAPH-TYPE--MY-CUSTOM-VIEW-MODE.html.twig.

Best of luck!


Unable to display Drush cache-clear theme registry I was using drush to do some of the most frequently used Drupal tasks, mainly to cache clear. It was working great, but recently I'm getting only the following option:

Enter a number to choose which cache to clear.
 [0]  :  Cancel
 [1]  :  drush
 [2]  :  registry

It was supposed to be:

 [0]   :  Cancel
 [1]   :  all
 [2]   :  drush
 [3]   :  theme-registry
 [4]   :  menu
 [5]   :  css-js
 [6]   :  block
 [7]   :  module-list
 [8]   :  theme-list
 [9]   :  nodeaccess
 [10]  :  registry
 [11]  :  token
 [12]  :  views

There is no way to clear css/js or theme registry. Whats the problem? Is it with Drush or Machine settings. Any advise highly appretiated.

The Drush code looks like this:

  $types = drush_cache_clear_types(drush_has_boostrapped(DRUSH_BOOTSTRAP_DRUPAL_FULL));

If the parameter to drush_cache_clear_types is TRUE, then the missing cache types shown above are included in your selection list.  Your Drupal site is not bootstrapping all the way up to the 'FULL' level, which means there's probably something wrong with the Drupal site.  Try running drush status --debug, and see if you can determine from the log messages why the bootstrap is stopping.

Update: See MPD's comment below. I thought the exact same thing as I was driving in to work this morning: this situation can also arise if you have told Drush where your Drupal root is, but have not specified your sites folder.  The Drupal root is specified via --root, or by using cd to switch to a directory anywhere in your Drupal installation.  The specific site is selected via --uri, or by using cd to switch to the same directory that contains settings.php.  If you cd to the folder that contains settings.php and run drush cc all, that might fix your problem.


Selecting field from all comments on a particular node I have essentially hacked comments into reviews of a node, having a comment field of 'rating' with a fivestar widget. I was hoping it would be a trivial call to the voting API to fetch the rating of each 'review' so I could work out a nodes average rating.

However I notice that for some reason all the votes are getting saved in a database table of field_revision_field_product_rating, and this contains no direct foreign key to the node it is from, is there a 'Drupal' way of fetching the comments in manual SQL with some monster joins?

Just to confirm, review is actually a comment, and the fivestar 'rating' is a field on the comment.

Bonus points: Why, even though I'm using fivestar, are the votes not getting put into the votingAPI storage?

On the field settings screen, it is important to set the “Voting
target” to “Parent node,” so that these votes will add ratings to the node; then,
click the “Save field settings” button


how to update a module-defined view? In D6, I have a custom module that I've developed. It has a view.

I've made some changes to the view in the module code, and I wanted those changes to go live on the site. I've clear the cache, but I don't see my changes.  What should I do,  disable, revert, delete?

1 -  if its a default view,  you should not be able to delete it.  You should only have the option to Enable or Disable it.  If the enabled view is alter then you only have the option to Revert.

2 - An unaltered default views are not stored in the views_view table of the database (however they are stored in the cache_views table).   If you alter the view,  they are now stored in the views_view table.

So,  if you have a unaltered default view and you make changes to it in the code, then the changes will be visible once you clear the cache.   If you have an alter default view, you must revert it for it to match the code in your module.