Remove Block Directly From Database - Drupal 7 I created a block and put in some invalid PHP code resulted in entire site not accessible at all.

I'm fairly new to Drupal and I'm not a back-end programmer either. Much appreciated if you can provide a clear step-by-step guide on how to delete that particular block directly from the Database (PhpMyAdmin).

To delete a block programmatically using the Database API, try this:

$module = 'block';
$delta = 1;

// Get the block id (bid) required to delete the correct block from table 'block_custom'
$result = db_select('block', 'b')
         ->fields('b', array('bid'))
         ->condition('module', $module)
         ->condition('delta', $delta)
         ->execute();
$bid = $result->fetchField();

db_delete('block_custom')
  ->condition('bid', $bid)
  ->execute();

db_delete('block')
  ->condition('module', $module)
  ->condition('delta', $delta)
  ->execute();

db_delete('block_role')
  ->condition('module', $module)
  ->condition('delta', $delta)
  ->execute();

When creating custom blocks through the Drupal Block UI, the module name is block and the delta value is an integer. Be sure to use the correct delta value to delete the desired block.


How to override thumbnail generation of file type media? In admin/content/media I need to show file type related icons instead of generic file icon.

From this:

To this:

I tried to edit the related thumbnail field in "media" view but no option is present.

Thanks

In the media source plugin for this media type you can find the code generating the thumbnail. See the source code of the "File" media type provider.

To summarize the code, you have to put your thumbnails files for each supported MIME type in the folder configured in the "icon_base_uri" configuration (which is stored in the "media.settings.yml" configuration file).

For example, using the default "public://media-icons/generic" folder and inserting a PDF media, you have to store your thumbnail image under the name "public://media-icons/generic/application--pdf.png" for it to be detected and used.


Allowing a user to control and/or view their own revisions Is there a way to allow a user to view and/or edit only their own revisions?  I don't want another user to be able to view other people's revisions.  Is there a module for this?

The revisioning module gives you this ability:

  Revisioning is a module for the configuration of workflows to create,
  moderate and publish content revisions.


Different front page for anonymous users I am looking to create a custom front page for users that are visiting the site. This is a landing page in a way, which will encourage users to register and has different CSS. Once a user is logged in or registered then they can see the normal website. Trying to do this without any modules.

What I have done so far is change the .htaccess file so it loads the index.html first.

Like so:

DirectoryIndex index.html index.php index.htm

The problem with this method is that users who login in still see the index.html page if they click on any link that points to the Home page. Instead I would like them to see the index.php or the normal Drupal site.

If it possible to do this with preprocess page hook? What code should be used?

I am only trying to present a different front page to the visitor when they hit domain.com. All the other pages such as domain.com/about-us and others should display properly regardless of the user role. In other words, I am NOT trying to hide the whole site for visitors.

If the pages are not too different, you could edit the page--front.html.twig and make it something like:

{% if not logged_in  %}
  // add your markup for non-registered users here
{% else %}
  {{ page.content }}
{% endif %}


How to use URL query parameter on a View Exposed Filter? We have a View which has the following settings. How can we setup the view to use a query parameter from the URL to filter the results?

Article Content Type (fields):

Title
Body
Category (field_category) --> taxonomy
Type (field_type) --> taxonomy

View Exposed Filters (values)

Category (All, Security, IoT, Wifi, Network)
Type (All, Blog, Press Release, Breaking News)

Desired output:

When the URL is www.mysite.com/news?type=Blog, then set filters Type=Blog and Category=All to return results of all Article pages where type=Blog and Category can be any (not null)
When the URL is www.mysite.com/news?type=Blog&Category=Security then filter results to return all Article pages where type=Blog and Category=Security

We tried adding a contextual filter with the following settings only but it did not work.

Views Exposed filters already work this way, no need for any Contextual filters.

In the settings for each Exposed filter there is an option to type in Filter identifier. That is the text that will be used for that field in the query.

In your case set the Filter identifier of the Category to Category and of Type field to type.

If you configure the Exposed filter Selection type settings for those two filters to Dropdown then you'll have to use term IDs in the link to make the filter work (I'm assuming your Security term has ID 6):

www.mysite.com/news?Category=6

Use Autocomplete to get term names in query

But if you set the Exposed filter Selection type settings to Autocomplete you will be able to use term names, which is what you want.

www.mysite.com/news?Category=Security

or

www.mysite.com/news?Category=Security+(6)

Drupal 8 adds the term ID next to the term name when choosing from the autocomplete suggestion list, but that part isn't necessary. You can construct the link with Category name only and it will work. If the Category name has spaces in it, replace them with + in query.

If you have more than one Exposed filter they get combined, for all types:

www.mysite.com/news?Category=Chemistry

or

www.mysite.com/news?Category=Chemistry&type=

and for some specific type in addition to Category:

www.mysite.com/news?Category=Chemistry&type=Blog

or change order:

www.mysite.com/news?type=Blog&Category=Chemistry


Rewrite title to download file? I have a content type with a file field. In a view I am trying to make the title link to the document. So that when someone clicks the title it downloads the file.

In Views for the title field I selected 'output this field as a link' and in 'link-path' I entered [field_file] which is valid.

When I click the title I get a page not found error.
The requested page "/%20the%20file%20name.xlsx" could not be found.

So it seems it is treating the link as a url link. How can I change this so that it downloads the file?

When you added field_file in views as a field you should set the Formatter to URL to file instead of Generic file.


views_embed_view fails with contextual filters? I have a view with 2 contextual filters, each is set to display all results if not present. This is tested on the Views edit screen using the Preview Contextual Filters. Both contextual filters filter taxonomy term Ids.

With none set it gives loads of results; with '152' it returns three results; with '152/366' it returns one result. These are the expected results.

However in my Drupal 7 code I have tried the following, but none of the ones with filters work:

print views_embed_view('my_view','default'); // ✔ all shown

print views_embed_view('my_view','default',152); // ✘ nothing
print views_embed_view('my_view','default','152'); // ✘ nothing
print views_embed_view('my_view','default',array(152)); // ✘ nothing
print views_embed_view('my_view','default',array('152')); // ✘ nothing
print views_embed_view('my_view','default',152,366); // ✘ nothing
print views_embed_view('my_view','default','152','366'); // ✘ nothing
print views_embed_view('my_view','default',array(152,366)); // ✘ nothing
print views_embed_view('my_view','default',array('152','366')); // ✘ nothing
print views_embed_view('my_view','default','152/366'); // ✘ nothing

Also, all the ones that use array for the contextual filter argument generate an error: "html_entity_decode() expects parameter 1 to be string, array given"

I feel like I'm missing something obvious here...

If you have devel installed , try checking with this syntax , if you do not see any result then try passing the arguments as 4/1(w.r.t given example) in the preview of views to cross check you have results with those combination of exposed filters.
Debugging at devel/php will save lots of your time.

dpm(views_embed_view("view_name", "view_display_type", 4, 1));


Adding a file to a node programatically I am working on a module that is transferring files from my old site (hosted on the same server) to a new drupal based site.  The files will be associated with a single content type (the content type has multipel file fields associated with it). I've written code to read a directory and then loop through the files, associating the files with the appropriate file file.  So far the files are getting transferred correctly, but they aren't being associated with the new node.  What am I missing

$result = new stdClass;
$result->type = "results";
node_object_prepare($result);

//add values to text fields here
...

//open the source directory
$d = dir($seasonDir);
while(false !== ($entry = $d->read())) {
      if($entry != "." && $entry != "..") {
        //set the file location
        $fileLocation = $seasonDir . "/" . $entry;
        //get the file contents
        $fileContents = file_get_contents($fileLocation);
        //save the file
        $file = file_save_data($fileContents,'public://results/'.$entry,FILE_EXISTS_RENAME);
        //store the file for copying to a subdirectory later
        $result_files[] = $file;
        //create an array to assign to the various file fields
        $file_details = array(LANGUAGE_NONE => array('0' => (array)$file));
        switch($entry) {
          case "results.inc.html":
            $result->field_results_html = $file_details;
            break;
          case"clubs.inc.html":
            $result->field_clubs_html = $file_details;
            break;
          case "events.inc.html":
            $result->field_events_html = $file_details;
            break;
          case "index.xml":
            $result->field_results_index = $file_details;
            break;
          case "events.xml":
            $result->field_results_events = $file_details;
            break;
          case "clubs.xml":
            $result->field_results_clubs = $file_details;
            break;
          case "results.xml":
            $result->field_results = $file_details;
            break;
          default:
            //because the resuls_files field allows multiple files, this
            //field has to use a different method of assigning the file
            $result->results_files[LANGUAGE_NONE][] = (array)$file;
            break;
        }
       }
    }
    $d->close();

    node_save($result);
    //now move the files to the folder using the node ID as the subfolder
    $newdir = 'public://results/' . $result->nid;
    if(file_prepare_directory($newdir, FILE_CREATE_DIRECTORY)) {
      //move the files into this directory
      foreach($result_files as $file) {
        file_move($file, $newdir . '/' . $file->filename, FILE_EXISTS_REPLACE);
      }
    }
    else {
      drupal_set_message("could not create $newdir");
    }

At the end, all the nodes have been created, the files have been moved to the correct sub directory, but the node doesn't show any attached files.  What am I missing?

I think from what I understand; you are trying to add each file(s) to its node folder public://results/[nid]/filename.ext

As solution to your issue, first you need to save the node before you attach the file(s) to it. Then move/save file(s) to its desired location. Then attach the moved file(s) to the selected node again.

Change your code to look like the following:

$result = new stdClass;
$result->type = "results";
node_object_prepare($result);

//add values to text fields here

// save node
node_save($result);

//open the source directory

$d = dir($seasonDir);

while(false !== ($entry = $d->read())) {
  if($entry != "." && $entry != "..") {

    $dir = 'public://results/' . $result->nid;
    // create folder str
    if(file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {

      //set the file location
      $fileLocation = $seasonDir . "/" . $entry;

      //get the file contents
      $fileContents = file_get_contents($fileLocation);

      //save the file - added nid as sub folder
      $file = file_save_data($fileContents, $dir . '/' . $entry, FILE_EXISTS_RENAME);

      // important if you are importing none image files
      $file->display = 1;

      // you don't need to copy files to an array anymore

      // create entity object to store file(s) to the node

      $entity = new stdClass();
      $entity->nid = $result->nid;
      $entity->vid = $result->vid;
      $entity->type  = $result->type;

      //create an array to assign to the various file fields
      $file_details = array(LANGUAGE_NONE => array('0' => (array)$file));

      switch($entry) {
        case "results.inc.html":
          $entity->field_results_html = $file_details;
          break;
        case"clubs.inc.html":
          $entity->field_clubs_html = $file_details;
          break;
        case "events.inc.html":
          $entity->field_events_html = $file_details;
          break;
        case "index.xml":
          $entity->field_results_index = $file_details;
          break;
        case "events.xml":
          $entity->field_results_events = $file_details;
          break;
        case "clubs.xml":
          $entity->field_results_clubs = $file_details;
          break;
        case "results.xml":
          $entity->field_results = $file_details;
          break;
        default:
          //because the resuls_files field allows multiple files, this
          //field has to use a different method of assigning the file
          $entity->results_files[LANGUAGE_NONE][] = (array)$file;
          break;
      }

      // save entity
      field_attach_presave('node', $entity);
      field_attach_update('node', $entity);
    }
  }
}
$d->close();


Character escaping rules for $form_state['redirect'] I'm writing a redirect for the form submit function, the redirect part looks like this

$form_state['redirect'] = array(
// $path
'catalog/search',
// $options
array('query' => array("circle_op=<&a%5Bvalue%5D=28&a%5Bl%5D" => $location, 'p' => $keyword,)),
// $http_response_code
    302,
  );

The problem is that the "circle_op=<&a%5Bvalue%5D=28&a%5Bl%5D" part on redirect transforms into "%253Ccircle_op%3D<%26a%255Bvalue%255D%3D28%26a%255Bl%255D%3D" inside URL.

Please explain, how to pass this key value correctly?

Thanks

The rule for query strings is pretty simple; you need a key, and a value. The format for this key/value pair is:

key=value

Both the key and the value will be URL encoded, so any special characters are escaped.

Take the = sign for example. Your sample code above uses:

circle_op=<&a%5Bvalue%5D=28&a%5Bl%50

as a key, and a value from the variable $location as a value. So without being escaped, your query string looks like this:

?circle_op=<&a%5Bvalue%5D=28&a%5Bl%5D=VALUE_OF_LOCATION_VAR

Obviously if a browser was to encounter that URL it wouldn't know what to do; there are two equal signs, so it doesn't know what is supposed to be the key, and what is supposed to be the value. It can make a guess but that's not the point.

The URL that you are redirecting to is absolutely the correct one for the input you've given for your redirect URL.


Add content from one content type into another content type What is my current site setup:

I am working on an academic website using Drupal 7 and I'm working on adding content from one content type into another content type.

I have a Books content type and also a People content type.

Book has the following fields:

Image (image upload field)
Title (textfield)
Description  (rich text)
Publisher URL (text field)
Publish Year (text field)
People name (entity reference to the title on the People content type (multi
select))

People has the following fields:

Title (the person's full name) (textfield)
Description (rich text)
Email (text field)
Phone number (text field)
Office location (text field)
Biography (rich text)
Research (rich text)

My specific question:
How do I relate the book content type to the people content type so that the list of books written by the respective person appear on the public version of the person's people content type page?

You can achieve this using reference module

Install this module, enable the references and node reference checkbox in the Module menu.

Create the people and book content type with the respective field

In Book content type, Add the People name field, and choose the node reference , then it will the show all the content types.

Select the People content type, set the widget types as select list.

Then create a content in Book, People Name field will show the people title as options in select list..

DO this thing, Please ask me if you have any queries.

Before that: Create some contents in People content type.


How do I import a view? Recently, I migrated Drupal 7 to Drupal 8 using the Migrate upgrade module, but the views aren't migrated.

Is there any method to import views from Drupal 7 to Drupal 8?

Unfortunately there is no upgrade path for views from D6/D7 to D8 and plans for this in core are postponed.

See the latest comment for this issue https://www.drupal.org/node/2500547#comment-11402389. There is a contrib project mentioned, but this is at very early stage.


how do i alter comments and comment form I am trying to change the way comments are displayed in drupal 7 for a specific content type. I am using garland theme. Ideally I would like to modify comment display in my module as opposed to doing it in the theme.

I have successfully implemented hook_form_comment_form_alter to hide the author name this way:

function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id) {
  //  krumo($form_id);
  switch($form_id) {
    case 'comment_node_mycontenttype_form':
      hide($form['author']);
      break;
  }
}

Now I would like to alter the comments to:

Hide the comment title link
Hide the "reply delete edit" links

I tried to implement hook_comment_view_alter() and hook_node_alter() but these seem not to get called. When I use the following code, nothing happens (no krumo outputs and no modifications).

function mymodule_comment_view_alter(&$build) {
  krumo($build);
}

function mymodule_node_alter(&$build) {
  krumo($build);
  hide($build['links']['comment']['#links']['comment-reply']);
}

The only way I found was to modify garland_preprocess_comment() in template.php in garland theme. But this applies to all content type and also I would like to have all my code in my module.

Is there a proper way to do this?

How come hook_comment_view_alter() and hook_node_alter() don't seem to get called?

Note I am using panels to add my content. So I have added the comments and the comment form using panels module. Therefore there is no field to toggle "allow comment title" as there is in structure->content type->comment settings. Even though the "allow comment title" field is unchecked, titles are still displayed. it seems like panels overrides this setting somehow.

To put this in my module I actually just did put the following code in my module:

function mymodule_preprocess_comment(&$vars) {
$vars['submitted'] = $vars['created'] . ' — ' . $vars['author'];
switch( $vars['node']->type )
 {
 case 'myContentType':
 $vars['title'] =FALSE;
 $vars['content']['links']['comment']['#links']['comment-reply'] = FALSE;
 $vars['content']['links']['comment']['#links']['comment-edit'] = FALSE;
 $vars['content']['links']['comment']['#links']['comment-delete'] = FALSE;
 break;
 }
}


How to check in Rules if a text field has changed? Not sure why this condition is ALWAYS evaluating to true. Trying to check to see if the value in a long text field has been changed.

The first field in the condition node-unchanged:field-security-audit (field type is Long Text) is always evaluating as true. The second field node-unchanged:field-security-audit-status-pubf (field type is term reference)is evaluating  properly.

Any help would be greatly appreciated.

Here is the rule export:

{ "rules_security_audit_status_updated" : {
"LABEL" : "Security Audit Status Updated",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "security" ],
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--api_publishing_form" : { "bundle" : "api_publishing_form" } },
"IF" : [
  { "OR" : [
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-security-audit" ],
          "value" : "node:field-sucurity-audit"
        }
      },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-security-audit-status-pubf" ],
          "value" : [ "node:field-security-audit-status-pubf" ]
        }
      }
    ]
  }
],
"DO" : [
  { "data_set" : {
      "data" : [ "node:field-security-audit-timestamp" ],
      "value" : [ "site:current-date" ]
    }
  },
  { "mail" : { //send mail
    }
  }
 ]
}
}

First things first: your node:field-sucurity-audit token might contain a typo ... It could well be that you intended to use node:field-security-audit instead (see the difference?). If that is not the solution (yet), just keep reading ...

Also make sure to always (repeat: always) add an Entity has field condition BEFORE any other Rules Conditions in which you might want to refer to some field. So in your case you should add 2 such extra Rules Conditions (since you're checking the value of 2 different fields). That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says:

  The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

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


What would be the Drupal way to have a preloader overlay divs untill they were finished loading? I am trying to get a theme to have a pre-loader image run over each section of the theme until the corresponding div section is finished loading.

I am trying to refrain from a $(window).load(function()); if i can.

What would be the best approach?  Thanks in advance.


Error: "module does not exist" after I removed a module from the file system without disabling and uninstalling it I removed a module from the file system without disabling and uninstalling it. And now I have error:
Drupal\Core\Extension\Exception\UnknownExtensionException: The module drupalweather does not exist. in Drupal\Core\Extension\ExtensionList->getPathname() (line 522 of core\lib\Drupal\Core\Extension\ExtensionList.php).
How to solve this error?
I use windows operating system and local server open server.

@Leigh comment:

It's fairly straight forward - put the files back and then uninstall
it before deleting again

Solved the error


Any module which even comes close to frontpage slider module I saw this front page slider module, and I was impressed by it, but I see there is no Drupal 7 module and it is payed property now.

Is there any module which comes close to this one?

Views Slideshow is incredibly configable and I am sure it will cater for that type of display. However is it not an off the shelf product like the wordpress example so dont expect to install it and it just work.

Instead like much of Drupal it is more like a construction box, complex but hugely powerful.


Multisite cannot find module in sites/default I haven recently set up a multisite setup with Live, staging and tag as the domina/subdomains used by the code

in the sites directory I have the modules set up like so:

sites/all/modules/<modules shared by ALL sites>
sites/default/modules/<modules ONLY used by default>
sites/tag.example.com/modules/<modules ONLY used by tag>
sites/staging.example.com/modules/<modules ONLY used by staging>

in the default, staging and tag modules directory are independent copies of modules that I am developing.

However when I add new urls to hook_menu() in any module in staging it is not picked up at all, only when the function is populated to sites/all

further to this, the modules disappear from the admin/modules page

on top of this there is this next issue.

If I place My_Module into the default and staging folder there are times that it either says that a function name cannot be found (when it is blatantly using the module) OR even worse is when it says I cannot re-declare a given function name

So can anyone point out if I am doing something wrong?

Am I putting the modules in the correct places because when I have EXACT duplicates of a module in separate site folders (staging and default but not all)  I am able to edit the content and see that the content has been edited but not add new urls/functions that get picked up.

And YES I am flushing all caches when uploading new hook_menu() items and function changes etc

Any Help is appreciated.

Thanks, Jim.

So this was the issue,

When I created the sub-domain i used cpanel, even though I specified

/home/<username>/<subdomain-name>

as the home directory path,

it would override it in the vhost entry to:

/home/<username>/public_html/<subdomain-name>

so,  even though I created the symlink at the right place, it never hit it,
so when I went to the subdomain url is was picked up by the drupal htaccess as a url to the live site

lots of confusion and lots of annoying behaviours

As soon as I edited the vhost entry to the corect path, everything worked correctly

thanks for all the reads though

Jim


Submitting a form, when using the same form with different ID are on a page Here is what happens:
I've create a content type poll, which admin can create polling questions and answers. Then this polling node will be rendering in a new Page node with node reference (using paragraph).

I manage to create a paragraph preprocess on .theme which will pass the NID to the buildForm.

Here is how it looks like on preprocess:

function THEME_preprocess_paragraph__poll_and_sidebar(&$variables) {
  $paragraph = $variables['paragraph'];
  $poll_form = '';
  if (!$paragraph->field_poll_content->isEmpty()) {
    $node_id = $paragraph->field_poll_content->getValue();
    $nid = $node_id[0]['target_id'];
    $poll_form = \Drupal::formBuilder()->getForm('Drupal\mypoll\Form\PollForm', $nid);
  }
  $variables['poll_form'] = $poll_form;
}

The myPoll buildForm module:

 public function buildForm(array $form, FormStateInterface $form_state, $nid= null) {

if (!$nid == null) {

  // check if user have voted
    $get_count_voter = $this->queryVoter($_COOKIE['cusid'],$nid);

  // Function on node load
    $poll_form_result = $this->getPollDetail($nid);

    $each_answer = [];

    foreach ($poll_form_result['answers'] as $answer_value) {
      $each_answer_id = $answer_value->id();
      $each_answer['answer'][$each_answer_id] = $answer_value->get('field_polling_answers')->value;
      $each_answer['calc'][$each_answer_id] = $answer_value->get('field_answers_calculation')->value;
    }

    $answer_type = 'checkboxes';

    if ($poll_form_result['poll_type'] == 'linear' || $poll_form_result['poll_type'] == 'multiple_2') {
      $answer_type = 'radios';
    }

    $form['poll_'.$nid] = [
      '#markup' => '',
    ];

    $form['poll_'.$nid]['headline'] = [
      '#markup' => '
' . $poll_form_result['headline'] . '
'
    ];

    $form['poll_'.$nid]['question'] = [
      '#markup' => '
' . $poll_form_result['question'] . '
'
    ];

    $form['poll_'.$nid]['sub_question'] = [
      '#markup' => '
' . $poll_form_result['sub_question'] . '
'
    ];

  if ($get_count_voter == true) {

    $form['poll_'.$nid]['answers'] = array(
      '#type' => $answer_type,
      '#options' => $each_answer['answer'],
    );

    $form['poll_'.$nid]['poll_type'] = [
      '#type' => 'hidden',
      '#value' => $poll_form_result['poll_type'],
    ];

    $form['poll_'.$nid]['poll_user_cookie'] = [
      '#type' => 'hidden',
      '#value' => $_COOKIE['cusid'],
    ];

    $form['poll_'.$nid]['poll_nid'] = [
      '#type' => 'hidden',
      '#value' => $nid,
    ];

     $form['poll_'.$nid]['actions']['#type'] = 'actions';
      $form['poll_'.$nid]['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#button_type' => 'primary',
      '#name' => 'submit-'.$nid,
      '#attributes' => array(
        'class' => array(
          'button--darkblue'
       ),
        'id' => array(
          'submit-'.$nid
        ),
      ),
   );

  } else {

    $form['poll_'.$nid]['result'] = [
    '#markup' => $this->t('RESULT'),
  ];

  }
    return $form;
}
}

On 1 page there will be more than 1 polls, for this example, I will have 2 sets of polling and it was successfully display 2 sets of forms but when I click submit button on the 2nd form , and trying to dump $form_state, it always pickup the 1st form value.

Is there a way I can define the Form ID by NID or any suggestion on fix?

Thanks,
Queenie

You need to call your form like this:

$form = new Drupal\mypoll\Form\PollForm($nid);
$poll_form = \Drupal::formBuilder()->getForm($form);

Then add this methods to your form class:

protected $nid;

public function __construct($nid)
{
  $this->nid = $nid;
}

public function getFormId()
{
  return 'my_form-' . $this->nid;
}

And you need to make sure that $nid is different each time the form is on the page.


Why does this query raise an exception? I am using the following code to query an ECK entity.

$query = \Drupal::database()->select('object__field_amount', 'f');
$query->fields('f', array('object__field_amount_value'));
$query->addExpression('MAX(object__field_amount_value)', 'maxvalue');
$query->execute()->fetchAssoc();

It raises the following exception.

  Drupal\Core\Entity\EntityStorageException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'maxvalue FROM object__field_amount f'

I've tried multiple other options, without result.

How do I avoid the code raises an exception?

MAXVALUE is a reserved word in MySQL (Maria). Change maxvalue to topvalue or something else.


How to have search results from a views defined block display on page? I have created a custom search block with Views 3 in Drupal 7. I would like the results of that search be displayed in a page (like the default drupal search block) and not in the block itself (which seems to be the default behaviour for views). How do I accomplish this? I think I am missing a setting somewhere but can't find it.

This is from a project I worked on a while ago. It uses Search Api and has a full search page at product-search/% (a Search Api view). After the redirect in the block's form submit, it places the search term into the search box text field for the search page. It's not a direct answer to your question as you will have to adapt the code if you want to use it.

function MODULE_block_info() {
  $blocks = array();
  $blocks['product_search'] = array(
    'info' => 'Search Products',
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  return $blocks;
}

function MODULE_block_view($delta) {
  $block =  array();
  switch($delta) {
    case 'product_search':
      $block['subject'] = t('Search Products');
      $block['content'] = drupal_get_form('MODULE_search_products_form');
      break;
  }
  return $block;
}

function MODULE_search_products_form($form, &$form_state) {
  $form['search'] = array(
    '#type' => 'textfield',
    '#title' => t('Terms to search for'),
    '#size' => 28,
    '#maxlength' => 128,
    '#required' => TRUE,
  );

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

  return $form;
}

function MODULE_search_products_form_submit($form, &$form_state) {
  drupal_goto('product-search/' . $form_state['values']['search']);
}

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'views_exposed_form':
      if ($form_state['view']->name=='product_search_api_view' && $form_state['view']->current_display=='page') {
        // get the view argument if defined
        if (isset($form_state['view']->args[0])) {
          // Set form filter input value to term tid
          if (!isset($form_state['input']['search_api_views_fulltext']))
            $form_state['input']['search_api_views_fulltext'] = $form_state['view']->args[0];
        }
      }
      break;
  }
}


Statistics on drupal projects I am trying to contribute Drupal modules and placed my first project on drupal.org.

Is it possible to see if a proprietary project on drupal.org has been downloaded and how many times?

Have a look at the "Usage statistics" page of any module on drupal.org, which includes all sorts o relevant information.

As an example, checkout the Rules module, for which you can find those statistics at https://www.drupal.org/project/usage/rules . Apart from a nice chart, it also gives you the statistics by Drupal Release (D6, D7, D8), and this for each Drupal Release for which the module does have some release. If you scroll to the bottom of those statistics, you even get more details (for the last 5 weeks) of every (minor) release of the module.

Attention: don't confuse "using a module" with "number of dowloads of a module"! E.g, for the Rules module, there are currently 296,819 sites reporting that they are using this module, while there have been 2,642,716 downloads so far. Open question: does that mean that only (about) 10% of sites for which this module was downloaded actually still use this module? Answer: I don't think so ...

PS: Replace "rules" in the above URL by any other module's name to find similar statistics.


A view I wrote has bugged handlers so I want to alter the query manually. How do I get the current view display? The view handler for locations is broken when the locations are in field collections.

I need to rewrite the view query, replacing 3 joins with 2 other joins, for the query to work.

I don't want to mess with other displays of the view - how do I get the currently used display with hook_views_query_alter()?

If you already know the machine name of the view then you can wrap your code in an if statement.

function hook_views_query_alter(&$view, &$query){
    if($view->name == 'name_of_view_to_alter'){
        //do stuff to the query
    }
}

hook_views_query_alter takes two arguments &$view and &$query. If you don't already know the machine name, of course install devel and use dsm($view) to find what you need. Also very helpful calling that on the $query variable as well. I just did something very similar.


How to hide administrator under role When an administrator (except user 1) editing a user how to hide "administrator" under role in a user edit page in D7 site? or how to prevent assign a role of administrator while editing a user?

I believe the RoleAssign module can help you with that:

RoleAssign specifically allows site administrators to further delegate the task of managing user's roles while withholding the Administer permissions permission.
RoleAssign introduces a new permission called Assign roles. Users with this permission are able to assign selected roles to still other users. Only users with the Administer permissions permission may select which roles are available for assignment through this module.


Drupal 7 Services -- hook_services_request_postprocess_alter() does not identify the requested resource According to the Services API in Drupal 7, we can use hook_services_request_postprocess_alter() to alter drupal's REST response before returning it to the user. This is useful if you want to alter the structure of an array, or strip out data we don't want returned to the API user. However, I don't see any way to identify what resource is being requested explicitly.

The Hooks passes: ($controller, $args, &$result);

The controller has semi-identifiable information, such as the callback which was fired, or the file where this resource exists. For instance, when firing a node INDEX request, we'd see:

[help] => List all nodes
[file] => Array
    (
        [type] => inc
        [module] => services
        [name] => resources/node_resource
    )

[callback] => _node_resource_index
[args] => Array
    (
        [0] => Array
            (
                [name] => page
                [optional] => 1
                [type] => int
                [description] => The zero-based index of the page to get, defaults to 0.
                [default value] => 0
                [source] => Array
                    (
                        [param] => page
                    )

            )

Etc. However, there is nothing standard here across services which would tell us: "This is a node INDEX request, using the NODE endpoint."

To be clear, we're referring to node in the resource sense, such as my_host/my_endpoint/node.json. Meaning, which of our endpoint's resources is being requested here, and what (if any) method/operation are we performing.

I was hoping there was something standard within this hook to identify this information, as opposed to relying on more external data, such as the GET or POST variables.

Anyone have insight into this?

[edit]:

hook_services_request_preprocess_alter() is passed an $options array, which contains the endpoint resource and method. I need access to this information in the postprocess hook mentioned above, but don't see any clean, Drupal-way to do that. this is what I am looking for.

The array looks as follows:

Array(
  [version] => ,
  [resource] => node,
  [method] => 1.json
);

if you take a look to $args array, you can find your node type, for example I have a content type "video", my $args are like this:

Array
(
    [0] => 2
    [1] => *
    [2] => Array
        (
            [type] => video
            [uid] => 92
        )

    [3] => 2
)

Then $args[2] has the content type (because I set it like a parameter in my resource:
http://site.local/api/v1/node?parameters[type]=video&parameters[uid]=92&pagesize=2&page=2


Trigger a drush @sites cr --yes daily Drupal 8.

Title sums up pretty much my question.

I'm wondering what is the best way to rebuild all my site's cache daily.

A cron job with Truncate table cache ?
Module who rebuild cache on each site ?

Does a plugin exist?

The simplest way is a cron job that calls drush @alias cr set for 24 hours. You can do that at the server level.


Allow editing of user content by account creator I have to create a set of user roles and permissions for sets of teams.

Users with a "coordinator" role would be able to create and manage a set of subordinate accounts.

The 'coordinator' role should also be able to edit content created by one of their own subordinates - but no one others.

If the coordinator were to change, it should be possible to assign their existing permissions and privileges in regards to their subordinates to a new user.

Is this easy to do with Drupal 8?

Your question looks like a perfect fit for the Group module, which can be used to create collections of content (nodes) that can be accessed by sets of users and with variations of access levels, such as none, read only, edit, etc.

Have a look at the answer to "What are the alternatives for the Organic groups module?" for a brief introduction to the Group module.

For this specific question, here is a blueprint of how it could be used/configured:

Group Type: Teams
Group Roles (refer to "What are the various roles supported by the Group module?" for more details):

Coordinator.
Team Member (or whatever fits), used for those who have access to a Team's content.

Groups: 1 such group for each team (simple as that ...).
Optional (not sure if you want this): If a user creates a new group, then automatically assign the "Group Owner"-role to the user who created the group.
Group permissions: grant permission to the user with role "Group Owner" to perform actions like "Add members" or "Invite members to join".

Special case: "If the coordinator were to change" (as in your question), then simply tune the permissions to grant the "Coordinator" role to another appropriate user (how easy can it be ...).

To use the Group module from within a custom module, start from its Development guide and/or have a look at its API for D7 or API for D8.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Other questions tagged with the group tag.

PS: Even though this question is related to D8, this answer applies for either D7 ...


Best way of including a View without extra modules as Panels, CTools, Context, etc I have a View which shows a list of nodes of a certain type.
If I don't want to use additional modules as Panels, CTools, Context, etc... which is the faster and better way of including it in a landing page? I have made a new kind of content for the landing page, with its own URL in PathAuto, and in the template.tpl I embed the Views with views_embed_view. Is it a good idea? Is it the simplest way of doing it? I have managed to get all working but the method seems very cumbersome and strange.

views_embed_view is a common method of doing it with highly degree of flexibility. Make sure that the type of the view's display (of the embedded view) is Embed. This display type can be made accessible in views UI by enabling it inside view's advanced settings.


Need block content for each menu items I need to have a separate block for a each menu items in my menu (Add item section).Is there any drupal module can help me or i should write the custom module.Please suggest the possible ways to do.

There is no module you can use with your situation.
Possible way.

Create separate menu and place them in each block.

Please describe your scenario so that we can discuss more.


Embedded remote video not showing I am new to Drupal and setting up my first site. I am keeping it fairly basic and have not added on much. I am able to embed uploaded videos without any problem, but when I attempt to embed a remote video in an article, the video does not show, instead it shows the word 'media'. I have tried uploading the video through the Content -> Media and also during the creation of the article. I have tried embedding a youtube video and a vimeo video and they both respond the same way. I wonder if the cause of the problem is that the max_width and max_height are both set to 0, if so, I have not seen any place that I can change that.

Media

Here is a link to the page that I pulled the code from, http://www.boundlessmotion.com/online/node/8

Any help is appreciated.

If you check your console in your DevTools, you can see the error message says:

It says that Vimeo allows the content to be displayed only from the Same Domain. The Vimeo videos provide links in the following format which can be embedded in external websites.

https://player.vimeo.com/video/12345.

You can try embedding video in the above format.


How do I add a menu task to /node path? I want to add a custom tab after "Edit" but can't figure out how to do so. I added a mymodule.links.task.yml file

entity.node.import_form:
  route_name: entity.node.import_form
  base_route: entity.node.canonical
  title: Import JSON from file

But I don't understand what to do next. The node form just errors out with:

  Symfony\Component\Routing\Exception\RouteNotFoundException:
  Route "entity.node.import_form" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName()
  (line 128 of /var/www/sites/datacenter.com/docroot/core/lib/Drupal/Core/Routing/RouteProvider.php).

What you have done is to create a menu task on the route entity.node.canonical with the title of Import JSON from file which links to the route entity.node.import_form.

The error you are getting is because the route entity.node.import_form (the link of the task) doesn't exist. You have to either depend/enable the module that provides this route or create the route yourself.


Adding custom vars with a block I want to use the title of the block as a hyperlink (or maybe adding an image) and I do not know how can I do this.

I've been looking to block.tpl.php. I know I can modify the template the way I want.

Maybe the way to do it is defining custom variables, such as $block->mycustom.

If the variable is defined there is a link, if not, nothing. The problem with this approach is that I don't know where this variable should be defined.

Is that correct, or am I totally mistaken?

I am interested in an answer for Drupal 7.

You could add a theme preprocess function for blocks to add some logic pushing variables into your block template. You can then check against those variables to output the title as a link etc.

THEMENAME_preprocess_block(&$vars) {
 //logic here to add variables
}


How do I alter a message in the message queue independent of site language? I want to programatically alter a message in the message queue. The message I want to alter is set in the message queue by function comment_form_submit() in comment.module, i.e.:

if ($comment->status == COMMENT_NOT_PUBLISHED) {
  if (!user_access('administer comments')) {
    drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
  }
}

Instead of this, I want the call to drupal_set_message() to be this:

drupal_set_message(t('Your comment will be published when you validate your e-mail address.'));

How do I do this?

Postscript: Based on the answer below by Topsitemakers, I got this working for any language by using array_search() inside a custom MYMODULE_comment_submit to search the message array, and then compare the translated strings to identify the key of the string to alter.

This is the working code I ended up with:

$mm = drupal_get_messages('status', TRUE);
$key = array_search(t('Your comment has been queued for review by site administrators and will be published after approval.'), $mm['status']);
if (FALSE !== $key) {
  $mm['status'][$key] = t('Your comment will be published when you validate your e-mail address.');
}
foreach ($mm['status'] as $msg) {
  drupal_set_message($msg, 'status');
}

You can compare messages using the t() function, as it will localize both messages and compare them.
Just use the original text in English you want to find and wrap it in t() function. E.g.:

if ($message == t('This is a sample message')) {
  // Alter the message/perform additional processing.
}


Why are two url aliases being generated for some users? I have a site under development, that is a migration from an different cms via the Migrate module. I noticed that the links for a lot of my user profiles are not staff/lastname-firstname as I set in the pathauto settings, but /firstname-lastname.

Looking in the url_alias table I see one alias for staff/lastname-firstname (pid 1644030) and another one (pid 1644031) for firstname-lastname. I point out the pids just because it appears that they are probably being created one after the other. They are both marked as language undefined, most likely due to the neutral path module. I suspect that one of the aliases was originally meant to be for English and the second for Japanese, but there is no setting in pathauto for different language paths for users. I can try disabling the neutral path module and rerunning my migration to confirm that they were each meant for different languages, but how can I fix it? I do not need a /firstname-lastname path in the system. I only want /staff/lastname-firstname to be generated.

Then first go to /admin/config/search/path/delete_bulk and delete the aliases in question.

Disable Pathauto for the migration process.

Once your site has been migrated, then enable pathauto and do a bulk update /admin/config/search/path/update_bulk


Add ctools processing for content loaded via ajax I have a search result page where all the searched results are loaded using ajax call. For each result, there is a button which should open a form in the modal.

The code snippet which is loading a button on the search result is as follows:

$build[$entity->id]['footer']['footer-bottom-section']['view-modal-form'] = array(
        '#type' => 'markup',
        '#markup' => l(' Get Best Price', 'request/add/'.$space_id.'/'.$entity->id, array('html'=>TRUE,'attributes'=> array('class'=>array('btn','btn-orange', 'pull-right', 'ctools-use-modal')))),
    );

The button is loaded properly on each search result, and it has all the classes provided. But it does not have ctools-use-modal-processed class.

I know the reason since the page is already loaded and results are added to the page through ajax after load finishes, ctools is not finding ctools-use-modal class to process.

I would like to know, how can I trigger ctools to process my ajax loaded search results so that it can add modal form for each searched result?

EDIT: Following is the js function which is calls a custom menu callback function, to load results:

function fetchNext(url, $parent) {
    $parent.append('
Loading
');
    $.get( url, function( data ) {
        $parent.append( data );
        $('.load-next').bind('inview', function (event, visible) {
            if (visible && !($(this).hasClass('disabled'))) {
                var url = $(this).attr('href');
                fetchNext(url, $(this).parent());
                $(this).remove();
              }
            });
        $('.load-next').click(function (event) {
            event.preventDefault();
            var url = $(this).attr('href');
            fetchNext(url, $(this).parent());
            $(this).remove();
        });
        processAfterLoad();
    }).fail(function() {
        $('#space-loading').text('Error in loading spaces. Please refresh page');
    });
}

This is line which calls above function:

$('.load-next').bind('inview', function (event, visible) {
            if (visible && !($(this).hasClass('disabled'))) {
                var url = $(this).attr('href');
                fetchNext(url, $(this).parent());
                $(this).remove();
              }
            });

Following is the kind of URL which will be called:

/lazyspaces/<Google places api locality>?<lat, lng, geolocation, sort, page>

for e.g.:

/lazyspaces/Thane-West--Thane--Maharashtra--India?lat=19.2444738&lng=72.9814877&geolocation=Thane%20West%2C%20Thane%2C%20Maharashtra%2C%20India&sort=distance&page=2&plain=1&lastdistance=8.80

Menu callback:

$items['lazyspaces'] = array(
        'title' => 'Find a Space',
        'page callback' => 'discover_lazy_spaces',
        'access callback' => 'entity_access',
        'access arguments' => array('view', 'space', 1),
        'file' => 'includes/search.utils.inc',
);

Here discover_lazy_spaces function, extracts get parameters and send it to a query to fetch results from database and then builds result list.

You need to call Drupal.attachBehaviors() after inserting the new content into the page.

Change this:

$parent.append( data );

To this:

$parent.append( data );
Drupal.attachBehaviors($parent);


Print view in email notification I have created View and that is with edit node from admin side, and I want to send same view by printing in email and I am using code to print view in email like this

$items['user/%user/display']['access callback'] = false;
$viewName = 'example_view_1';
print views_embed_view($viewName);

But there is edit node link also whenever I see from admin side,but whenever I got same view in email then it will not show edit link of node, Let me know if anyone have solution.

Finally I have done this reminder this way.

module_load_include('inc', 'webform', 'includes/webform.submissions');
$submissions = webform_get_submissions(nodeid);

and checked roles while printing node data in loop and get edit link through $base_url; and print into simple tabular format. Let me know if any query in it.

Thanks for the support.


Render image or entity in a custom block! I want to render product content type in a custom block with a custom view mode. I have a field product_teaser in my article content type that reference the product that is I want to render in the custom block using advert view mode

The content type to be rendered: "product"

The view mode to be rendered with: "advert"

The product teaser only contains an image and a buy=now button I can easily place using twig. So placing only the image in the render of the custom block should be enough for this to work But I have been trying to render the image for a while and I could not do it.

This is my first approach to do this, Rendering the whole product advert.

  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $view_mode = 'advert';
      $product_id = $node->get('field_product_teaser')->getValue()[0]['target_id'];
      $product = \Drupal::entityTypeManager()->getStorage('node')->load($product_id);
      $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
      $pre_render = $view_builder->view($product, $view_mode);
      $render_output = render($pre_render);
      return $render_output;
    }
    return [];
  }

Render output is an empty string for some reason. $pre_render has got view mode and node array having all the product fields, everything looks good except that render($pre_render) return an empty spaces string.
This is the error being output from this approach "Argument 1 passed to Drupal\Core\Render\Element::isEmpty() must be of the type array, object given"

My second approach was to get the image URI of the product advert and render it manually

$build= array();
    //Gets current node to check for which product to be displayed.
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $product_id = $node->get('field_product_teaser')->getValue()[0]['target_id'];
      $product = \Drupal::entityTypeManager()->getStorage('node')->load($product_id);
      $product_advert_url = $product->field_teaser->entity->url();
    }

    $build['image'] = [
      '#theme' => 'image_style',
      '#style_name' => 'thumbnail',
      '#uri' => $product_advert_url
    ];

    return $build;

This is the error being output from this approach "Class name must be a valid object or a string in Drupal\image\Entity\ImageStyle->buildUri()"

How to fix these errors ??, I prefer the first method because it will be easier if I needed to add anything to the product teaser later.

You can do this in a View block. Add a contextual filter for the content id and configure it to provide the default value "Content ID from URL":

The view mode Teaser would be in your case a custom view mode (for the content type "article") only containing the product teaser field, configured to render the target entity in a second view mode "advert" (now for the content type "product").

If you want to do this in code, then get the node from a context plugin (see this great answer from @Berdir https://drupal.stackexchange.com/a/188629/47547) and build the render array (if you use the view modes mentioned above you only need one line of code). Very important, never render in Drupal 8, always return unrendered arrays.


How do I use hook_views_pre_render in template.php in Drupal 7? I have some auto generated data from my articles stored in a view(my_amazing_view). I also have a custom field in articles where user can enter similar data. If user has entered the data, i want to show that data. Otherwise I want to show auto generated data.

To do this, I want to implement hook_views_pre_render in my template.php file and target that specific view. I tried naming the function as my_amazing_view_views_pre_render as well as mytheme_views_pre_render and targeting that view but I am unable to do so.

How do I use the pre_render hook in my theme?

The hook is run for every view, therefore you need to inspect the $view object (the parameter passed to the function).

Place the function in your theme's template.php.

Name it YOURTHEMENAME_views_pre_render (ie  replace 'hook' with your theme name). Then use $view object to target specific view name and display_id, as in $view->name and $view->display_id (from memory, I might be wrong, but you get the gist).

function MYTHEME_views_pre_render(&$view){
  if ($view->name == 'VIEWNAME' && $view->display_id == 'DISPLAY_ID') {
    // do what you want
  }
}

If you want to do this for many views, best do it like this to separate the views into their own functions:

function MYTHEME_views_pre_render(&$view){ {
  // will run for all views
  $function = __FUNCTION__ . '_' . $view->name;
  if (function_exists($function)) {
    $function($view);
  }
}

function MYTHEME_views_pre_render_VIEWNAME(&$view){
  // will only run for specific view, but for all of its displays.
}


Entity Reference Roles I've created a Entity Reference from customer to contract and I created a user which can create a customer.

Now is the problem that I can't select any contract with the new user when I try to create a new customer.

The only solution I found is to give the new user the Bypass content access control permissions. But then he also can create a contract. And I don't want that user to do that.

Can anyone explain me what I'm doing wrong?

Probably you must not have given that specific user/role, the permission to "View Published Content". Verify that please.


Save and set an external link image programatically I have a field that will accept an image link coming from the external source. But of course, to set that image I have to save it in Drupal first. I'm wondering how do Drupal save the image from an external link. I use the following code.

$imageUri = 'https://api.statvoo.com/favicon/?url=google.com'; // this is a favicon

$file = File::create([
          'uri' => $imageUri,
          'status' => 1,
        ]);
$file->save();

$user_profile->field_profile_image[] = [
        'target_id' => $file->id(),
        'alt' => 'Alt text',
        'title' => 'Title',
        'width' => 200,
        'height' => 200,
      ];

$user_profile->save();

I notice that the following values and the external image URL were added in the image field, but the image is not displayed on the page. Thanks in advance!

Well, I think it is supported. I found an exact solution I need to be able to save and set an external image source inside Drupal according to Programmatically update node image field (using URI of the image) and get URL in twig.

I use this method system_retrieve_file.


How to track users site use in a webform / contact form? I was wondering if anyone knows a way of adding some data to the end of the emails I receive from a contact / web form, such that I can see what pages users (authenticated and unauthenticated) have visited prior to submitting the form?

Something like:

Here is the main body of the web form.

Before submitting this form the user visited:
/node/1,
/node/12,
/contact-us,
/node/45,
etc etc...

This is more or less the feature of the Google Analytics Contact Form, Webform, Rules Email module.

  This module will instantly append Google Analytics information to the bottom of the Contact Form, WebForm, and Rules emails.

The mail would look something like:


displaying fields of selected taxonomy term I'm trying to create a minimalistic ordering system. No need for a full fledged solution like Commerce or UC in this case.

Orders are represented as nodes (or maybe as custom entities using ECK, have yet to decide). Products are organized into a taxonomy tree. Hierarchy_select module gives the user a super convenient way of selecting the product.

But there is a problem. I need to display some fields of a product term selected by user. Is there a way to tackle it without writing much of custom code?

you need this functions:

taxonomy_term_load
taxonomy_term_view
drupal_render

load term by taxonomy_term_load, pass it to taxonomy_term_view then render it by drupal_render


Get menu link siblings I'm trying to create a menu in Drupal 8 that is just sibling links of the current page. So if the menu is:

Home
Parent 1

Sub-parent 1

Child 1

Sub-parent 2

Child 2
Child 3
Child 4

Parent 2

When I'm on the "Child 3" page, I want a menu block to link to look like this:

Child 2
Child 3
Child 4

I know how to do this in D7, I think, but I'm having a hard time translating that knowledge to D8. Is this even something that is doable in D8? And if it is, can someone point me in the right direction on how to do it?

Thanks!

Clarification: The child level needs to be variable, so that menu items with different depths can display their siblings. So for instance, in addition to wanting a menu for the children, I'd need a menu for the sub-parents and a menu for the parents and so forth. I also have no control over/knowledge of how deep the menu goes and if it goes that deep on all sections.

So, I ended up figuring out some code that would let me do this, by creating a custom block and, in the build method, outputting the menu with transformers added to it. This is the link I used to figure out how to get the menu in the block and add transformers to it: http://alexrayu.com/blog/drupal-8-display-submenu-block. My build() ended up looking like this:

$menu_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

// Load the tree based on this set of parameters.
$tree = $menu_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  // Remove all links outside of siblings and active trail
  array('callable' => 'intranet.menu_transformers:removeInactiveTrail'),
);
$tree = $menu_tree->transform($tree, $manipulators);

// Finally, build a renderable array from the transformed tree.
$menu = $menu_tree->build($tree);

return array(
  '#markup' => \Drupal::service('renderer')->render($menu),
  '#cache' => array(
    'contexts' => array('url.path'),
  ),
);

The transformer is a service, so I added an intranet.services.yml to my intranet module, pointing to the class that I ended up defining. The class had three methods: removeInactiveTrail(), which called getCurrentParent() to get the parent of the page the user was currently on, and stripChildren(), which stripped the menu down to only the children of the current menu item and its siblings (ie: removed all submenus that weren't in the active trail).

This is what that looked like:

/**
 * Removes all link trails that are not siblings to the active trail.
 *
 * For a menu such as:
 * Parent 1
 *  - Child 1
 *  -- Child 2
 *  -- Child 3
 *  -- Child 4
 *  - Child 5
 * Parent 2
 *  - Child 6
 * with current page being Child 3, Parent 2, Child 6, and Child 5 would be
 * removed.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu link tree to manipulate.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   The manipulated menu link tree.
 */
public function removeInactiveTrail(array $tree) {
  // Get the current item's parent ID
  $current_item_parent = IntranetMenuTransformers::getCurrentParent($tree);

  // Tree becomes the current item parent's children if the current item
  // parent is not empty. Otherwise, it's already the "parent's" children
  // since they are all top level links.
  if (!empty($current_item_parent)) {
    $tree = $current_item_parent->subtree;
  }

  // Strip children from everything but the current item, and strip children
  // from the current item's children.
  $tree = IntranetMenuTransformers::stripChildren($tree);

  // Return the tree.
  return $tree;
}

/**
 * Get the parent of the current active menu link, or return NULL if the
 * current active menu link is a top-level link.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The tree to pull the parent link out of.
 * @param \Drupal\Core\Menu\MenuLinkTreeElement|null $prev_parent
 *   The previous parent's parent, or NULL if no previous parent exists.
 * @param \Drupal\Core\Menu\MenuLinkTreeElement|null $parent
 *   The parent of the current active link, or NULL if not parent exists.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement|null
 *   The parent of the current active menu link, or NULL if no parent exists.
 */
private function getCurrentParent($tree, $prev_parent = NULL, $parent = NULL) {
  // Get active item
  foreach ($tree as $leaf) {
    if ($leaf->inActiveTrail) {
      $active_item = $leaf;
      break;
    }
  }

  // If the active item is set and has children
  if (!empty($active_item) && !empty($active_item->subtree)) {
    // run getCurrentParent with the parent ID as the $active_item ID.
    return IntranetMenuTransformers::getCurrentParent($active_item->subtree, $parent, $active_item);
  }

  // If the active item is not set, we know there was no active item on this
  // level therefore the active item parent is the previous level's parent
  if (empty($active_item)) {
    return $prev_parent;
  }

  // Otherwise, the current active item has no children to check, so it is
  // the bottommost and its parent is the correct parent.
  return $parent;
}

/**
 * Remove the children from all MenuLinkTreeElements that aren't active. If
 * it is active, remove its children's children.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu links to strip children from non-active leafs.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   A menu tree with no children of non-active leafs.
 */
private function stripChildren($tree) {
  // For each item in the tree, if the item isn't active, strip its children
  // and return the tree.
  foreach ($tree as &$leaf) {
    // Check if active and if has children
    if ($leaf->inActiveTrail && !empty($leaf->subtree)) {
      // Then recurse on the children.
      $leaf->subtree = IntranetMenuTransformers::stripChildren($leaf->subtree);
    }
    // Otherwise, if not the active menu
    elseif (!$leaf->inActiveTrail) {
      // Otherwise, it's not active, so we don't want to display any children
      // so strip them.
      $leaf->subtree = array();
    }
  }

  return $tree;
}

Is this the best way to do it? Probably not. But it at least provides a starting place for people who need to do something similar.


The file upload in feeds importer is not working I have been reading through all the documentation I can find, but I cant find a simple solution for this problem.

I can upload the first CSV file, and import it to a custom table with error handling and everything; when I try to upload the second CSV file, the importer imports the first file and the new file is not even uploaded to my server.

Does anyone know why this would happen?

So I have still been working on this issue and this is what seems to be happening. I "upload" a local file, this file is not actually uploaded to the server and is not recorded in the database in the "feeds_source," or in the "files" tables. The only available file is the original file that had been uploaded, and this file is being re-imported into the database. This is why I am not getting any errors or warnings or watchdog reports.

Has anyone else experienced this?

I solved the issue by increasing the PHP upload limit, and the memory limit.


How can I create a path auto pattern token based on a menu path without placing node in menu? Here is the scenario:

We have a D7 multisite set up with an installation profile that we created so that all sites are basically managed with the same rules. But we do allow some flexibility... So we have a content type "News Article". Usually news articles won't be in the menu because there can be thousands of news articles on any given site. One site might want to put their news articles under the "News" menu item in the main menu. Some might call it "News Room". Since we're not forcing the parent path, I can't set "news" as a root path for all the nodes in path auto. And even more crazy, some site users might chose to place node A under News while node B is under About. I was thinking of some type of menu "parent" selector as if they were creating a menu item, without creating the actual menu item in order to generate the path. I thought the menu position module might be on the path I needed, but it turns out you have to create rules administratively and not on a per-node basis where the user is making the determination.

With the use of the Menu Reference module and hook_pattern_alter, I was able to get this accomplished. The code piece ended up looking like:

function custom_paths_pathauto_pattern_alter(&$pattern, array &$context) {
  if (isset($context['type']) && $context['type'] == 'news_article' && isset($context['data']['node']) && !$context['data']['node']->menu['enabled'] && $context['data']['node']->field_menu_path['und'][0]['mlid']) {
    $menuitem = menu_link_load($context['data']['node']->field_menu_path['und'][0]['mlid']);
    $menupath = drupal_get_path_alias($menuitem['link_path']);
    $pattern = $menupath . '/[node:title]';
  }
}


Accessibility : Broken Skip Link Error on "Skeleton" Theme I installed the "Skeleton" theme and found it has a "Broken Skip Link" by using "wave.webaim.org". How can I find and fix where is this "Broken Skip Link"?

You can find this Skeleton demo at "http://demo.drupalizing.com/skeleton"

and the "Broken Skip Link" error at "http://wave.webaim.org/report#/http://demo.drupalizing.com/skeleton/"

I use the Skeleton theme. it has:

    Skip to main content

But it has no anchor tag for main-content. You should file an issue for the Project on Drupal.org.

You can fix this by supplying a patch to the theme project that alters html.tpl.php or page.tpl.php to include an  at the top of the content area. You may do this in your own subtheme as well of course simply by modifying the necessary TPL file.

EDIT:
Issue created at Drupal.org https://drupal.org/node/2211661


Combine two content types in one using search api views I am using search api views for site search.

I have 4 content types A, B, C and D.

In the views filter when I expose a content type filter, it display as following on the search page

All
A
B
C
D

I want to combine the C and D content types.

All
A
B
Combined

Where Combined will be a custom text and when click , it should filter the content with Content type C and D.

Is it possible with search api or is there any workaround?

You have to:

1) allow multiselect for the field;
2) implements hook_form_views_exposed_form_alter and edit the filter - replace 2 values on new value and in validate function to replace back.

Example for the simple field:

/**
 * implements hook_form_views_exposed_form_alter
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
    if($form['#id'] == 'views-exposed-form-list-your-views'){

        $form['#validate'][] = 'MYMODULE_form_views_exposed_form_validate';

        $form['field_your_field_value']['#multiple'] = false;
        $form['field_your_field_value']['#size'] = 1;
        $options = $form['field_your_field_value']['#options'];
        unset($options[3]);
        unset($options[4]);
        $options['3+4'] = 'name of combine value';
        array_unshift($options, '- ALL -');
        $form['field_your_field_value']['#options'] = $options;
    }
}

/**
 * our validate for  form views-exposed-form-list-your-views
 */
function MYMODULE_form_views_exposed_form_validate($form, &$form_state) {
    if($form['#id'] == 'views-exposed-form-list-your-views'){
        if(in_array('3+4', $form_state['input']['field_your_field_value'])){
            form_set_value($form['field_your_field_value'], array(3,4), $form_state);
        }
    }

}


print script on specific node id I want to print out a script from facebook on a specific node page in my html.tpl.php file. What is the best way of doing this? looking for nid? I need some kind of a if statement...

thanks

a hacky solution in html.tpl.php could be like this:

$node = node_load(arg(1));
echo $node->nid;

You'll want to check for the existence of $node and such to avoid errors.

You could also create your own node template: node--123.tpl.php

You could also use the HOOK_preprocess_page() function to check for the node ID.


Rearrange filters option missing? How can I rearrange the weight of the exposed filters?
In Drupal 6 I had that option, and in Drupal 7 it has disappeared.

Is there something I'm missing?

Select 'And/Or' next to Filter Criteria, this will show a popup where you can rearrange them.


View for Taxonomy terms? How can I output nodes which linked with taxonomy term through a view?
How can I link taxonomy vocabulary with a view wich will output appropriate nodes for each term of this vocabulary?

In Drupal 7 we have two modules:

Taxonomy Display (is not present in D8).
Taxonomy Views Integrator (is raw in D8).

You don't need additional modules to create different Taxonomy term pages, in D7 nor D8. Taxonomy Display and Taxonomy Views Integrator modules save steps in certain cases, but you can recreate their functionality with configuring different Views for different cases.

You can reuse the existing Taxonomy term Views (this lists nodes based on the taxonomy term in the URL).

If you need different Taxonomy page settings for each Vocabulary you can Duplicate the Taxonomy term Views (that shows Content tagged with a term) as many times as you have different Vocabularies, and add Filters to each to apply only to one Vocabulary.

Then you can also change all the other options related to how you want different Vocabulary terms Content to be displayed, because you'll have a different View for each Vocabulary.


Where do these version numbers come from "module-name-1.0-alpha1+13-dev" with plus? I've started to work in an existing drupal development project and wanted to do some module updates and found modules with versions like this:

Universally Unique IDentifier 7.x-1.0-alpha3+47-dev
Taxonomy CSV import/export 7.x-5.10+17-dev

I've never seen this before. According to drupal version number guidelines this is not wanted.

Now, our head developer says they never modified any contributed modules and only took them from drupal.org ... Where do that version numbers come from?

Did I miss something?

-dev versions, are regularly built from the latest source code.

To differentiate between todays -dev release, and yesterdays, the number you've indicated counts the number of changes between any two dev releases.


Altering body text of a node before the page is rendered I am using the Zen theme. I want to alter the body text before it is rendered as a page. In particular, I want to replace a string with another string. I thought that the general solution for this would be to place the code in the the theme_preprocess_node hook in my sub-theme's template.php. Here is the code that I've got so far:

<?php
function mytheme_preprocess_node(&$variables) {
    if ((isset($variables['body'][0]['value'])) && (preg_match('/suppose/i', $variables['body'][0]['value']))) {
        dpm('string was found in "value"');
        $variables['body'][0]['value'] = preg_replace('/suppose/i', 'new tring', $variables['body'][0]['value']);
    }
    if ((isset($variables['body'][0]['safe_value'])) && (preg_match('/suppose/i', $variables['body'][0]['safe_value']))) {
        dpm('string was found in "safe_value"');
        $variables['body'][0]['safe_value'] = preg_replace('/suppose/i', 'new tring', $variables['body'][0]['safe_value']);
    }
}
?>

However, this has no effect what so ever. I do get a positive match - this I can verify by the debug dpm() display.

Am I simply trying to rewrite the wrong sub-array?

Thanks in advance,
Valera Rozuvan

Try this in mytheme_preprocess_node:

function mytheme_preprocess_node(&$vars) {
  // Collect / create / adjust new body content
  $new_body = 'xyz';
  // Assign to output
  $vars['content']['body'][0]['#markup'] = $new_body
}

After looking through the vars array a bit, I'm a little surprised at the amount of redundant data there.  There are a few different places where the body text is recorded, usually as an array.

Note that the node body will likely have a 'safe value' and a 'value'.  You'll probably want to use safe almost all the time, but it might be good to check on the filter type selected in $vars['body'][0]['format'] to select which of the body values you'll want to output and display.


How to export all users with all custom fields? I want to export users list with all custom fields. I have tried the Users Export module but its export only below fields:

uid
mail
name
created
access
login

Is there any solution to solve this problem?

You can use the Drush Entity module:

  With drush entity you can query the entity system available for Drupal
  8, 7 and (some of) 6.

Getting all users with some fields:

drush entity-read user `drush entity-read user` --fields=uid,mail,name,created,access,login

Getting one user with all the fields:

drush entity-read user 1 --fields=* --format=json

Getting all the users with all the fields:

drush entity-read user `drush entity-read user` --fields=*

Getting some users with some fields:

drush entity-read user 1 2 --fields=uid,mail,name,created,access,login --format=export

Output (for the last command):

 1  mail@gmail.com  admin  1353518169  1470089957  1469713365
 2  other@gmail.com  webadmin  1353518169  1470089957  1469713365

If you want to try with another options you can read this page: http://build2be.com/content/drush-entity-support-patch-needs-review


How to programmatically set the field formatter for a field given certain conditions I have an entity 'house' with an address field. The address field comes with a default field formatter plugin. This is perfect for when i view my entity at its canonical route and where its view_mode is 'full'.
However I want to change how the address field is displayed when the 'house' has view_mode 'teaser'. For example at a page that displays a list of all my houses. To be specific I want my address to appear on one line.
Now, I have gotten all this working. Like this:
house_entity/src/Plugin/Field/FieldFormatter/AddressTeaserFormatter
<?php

namespace Drupal\rrre_entities\Plugin\Field\FieldFormatter;

use Drupal\address\Plugin\Field\FieldFormatter\AddressPlainFormatter;
use Drupal\Core\Field\FieldItemListInterface;

/**
 * Plugin implementation of the 'address_teaser' formatter.
 *
 * @FieldFormatter(
 *   id = "address_teaser",
 *   label = @Translation("Teaser"),
 *   field_types = {
 *     "address",
 *   },
 * )
 */
class AddressTeaserFormatter extends AddressPlainFormatter {

  /**
   * {@inheritdoc}
   */
public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = parent::viewElements($items, $langcode);
  foreach ($elements as &$element) {
    $element['#theme'] = 'address_teaser';
  }
  return $elements;
}

house_entity/house_entity.module
/**
 * Implements hook_theme().
 */
function house_entity_theme($existing, $type, $theme, $path) {
  return [

    'house' => [
      'render element' => 'listing',
    ],

    'address_teaser' => [
      'variables' => [
        'recipient' => '',
        'organization' => '',
        'address_line1' => '',
        'address_line2' => '',
        'postal_code' => '',
        'sorting_code' => '',
        'dependent_locality' => [],
        'locality' => [],
        'administrative_area' => [],
        'country' => [],
      ],
    ],
  ];
}

and in the same house_entity.module file:
/**
 * Implements template_preprocess_HOOK().
 */
function template_preprocess_house(&$variables) {
  $addressDisplayOptions = [
    'type' => 'address_teaser',
  ];
  $house->address->getItemDefinition()->getFieldDefinition()->setDisplayOptions('view', $addressDisplayOptions);
}

Finally I have my template for my new address fieldformatter all set up at house_entity/templates/address-teaser.htm.twig
This all works fine.
Except that the custom field formatter does not apply to the first 'house' in my list of 'houses' (it does apply to all subsequent 'houses') ... and adding a xdebug_break() immediately after the line:
$listing->address->getItemDefinition()->getFieldDefinition()->setDisplayOptions('view', $addressDisplayOptions);
Triggers the following error - basically that the twig template was not found:

Question?:
Do I have my template in the right place?
Is there a more convenient way of setting a field formatter for a particular field on an entity?

Is there a more convenient way of setting a field formatter for a particular field on an entity?

Yes, choose the formatter in the view mode settings (configure in the user interface) rather than using template preprocess.

(I found this old question looking for how to make a field formatter, and ended up copying Drupal\user\Plugin\Field\FieldFormatter and simplifying it by dropping the configuration parts, and then simply selecting that formatter on the view modes and Views tables i wanted to use it on.)

For ensuring this formatter doesn't show up in places it shouldn't, the key part is "isApplicable"; here's what mine looked like for a custom entity 'give_donation' and a field named 'recurring':

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return $field_definition->getTargetEntityTypeId() === 'give_donation' && $field_definition->getName() === 'recurring';
  }


Drupal 8 - Can't link custom CSS files We're trying to create our very first theme in drupal 8 and we're having some problems with it.

When we try to link our custom css and try to load the page it gives us

  The website encountered an unexpected error. Please try again later.

We've tried different solutions, but none of them worked and we're kinda lost.

here's our Fubiz_NJ.info.yml file

name: Fubiz_NJ
description: Website homepage reproduction
type: theme
core: 8.x
libraries:
  - Fubiz_NJ/global-styling
  - Fubiz_NJ/global-scripts
stylesheets-remove:
  - core/assets/vendor/normalize-css/normalize.css
  - core/modules/system/css/system.module.css
  - core/modules/system/css/system.theme.css
  - core/modules/views/css/views.module.css

# Define regions
regions:
  header: 'Header'
  primary_menu: 'Primary Menu'
  secondary_menu: 'Secondary Menu'
  slideshow: Slideshow
  page_top: 'Page Top'
  content: 'Main content'
  footer: 'Footer'

and here's our Fubiz_NJ.Libraries.yml file

global-styling:
    version: 1.0
        css:
            theme:
                css/style.css: {}

global-scripts:
    version: 1.0
        js:
            js/script.js: {}

We're both new to drupal so we don't really know where to look at this point, Hope you guys can help!

The libraries YAML file is not correct. In YAML, indentation matters. Additionally, spaces should be used instead of tabs.

global-styling:
    version: 1.0
    css:
        theme:
            css/style.css: {}

global-scripts:
    version: 1.0
    js:
        js/script.js: {}


Trouble installing drupal-project with Composer I have followed the directions to install drupal-project with drupal-composer.
I keep getting this error and it doesn't make sense to me.

  [InvalidArgumentException]
   Could not find package drupal-composer/drupal-project with version 8.x-dev in a  version installable using your PHP version 5.5.38.

I am using MAMP and the php version is 7.1.22. I even tried the template download for drupal-composer/drupal-project and I still get the same error. Composer is installed, verified with the checking the version in terminal.

I have searched and cannot find anything to assist me in solving. Yes, I am new to composer and trying to get a local environment setup with composer versus just downloading etc. Any help or direction would be appreciated.

Despite not technically being a Drupal question, this gets asked a lot. The answer, for anyone coming across this using various local dev stacks - you need to inform your command line of where PHP ($PATH variable) is that you want to use. Otherwise it will default to what is installed on your machine, likely very out of date.


Matrix view with content as columns and taxonomy terms as rows I need to build a view in a matrix format. I have a content type mycontent and a taxonomy vocabulary myvocabulary. The content type has a term reference field in it, which refers to the vocabulary and can have multiple values.

I want to list all contents in a view as columns, and all terms in the vocabulary as a table header, i.e. columns. I want to put a check mark to the corresponding field in the table according to the terms that the content has.

An illustration of what I want to achieve:

+-----------+--------+--------+--------+--------+-----
|           | Term 1 | Term 2 | Term 3 | Term 4 | ...
+-----------+--------+--------+--------+--------+-----
| Content 1 |   x    |   x    |        |   x    |
+-----------+--------+--------+--------+--------+-----
| Content 2 |        |        |        |   x    |
+-----------+--------+--------+--------+--------+-----
| Content 3 |   x    |        |   x    |        |
+-----------+--------+--------+--------+--------+-----
| Content 4 |   x    |    x   |        |        |
+-----------+--------+--------+--------+--------+-----
|    ...    |        |        |        |        |

So, my challenge is to dynamically create a column for each taxonomy term in the vocabulary. I.e. if I add a new taxonomy term, the view should have this column automatically added to the table.

With the default table display I can list the nodes as rows, but it is not possible to make a column for each term in the vocabulary.

I have found 3 different modules which seem to related to my problem:

Views Crosstab
Pivot Tables for Views
Views Matrix

None of those modules have a stable version for Drupal 7, nor they have a good documentation, if any at all.

I am going to download and install the dev versions of each module and play around. However, before I do that I wanted to ask if anyone has done such a view and if there would be another better approach to achieve such a matrix view.

Other suggestions that doesn't include using Views are also welcome.

It can be achieved with the help of hook_views_pre_view() and the Views field template file.

Create a View

Create a view showing content in table format and add two fields:

Content: Title (Title)

The title will populate each row of the first column.

Content: All taxonomy terms (All taxonomy terms)

select: Exclude this field from display

select: Limit terms by vocabulary and tick the vocabulary you want to use.

Your module file

Create a column for each term and populate all the fields with the value from the field Content: All taxonomy terms (All taxonomy terms) Then we'll be able to check if a comma-separated list of terms contains the term of the current column.

/**
 * Implements HOOK_views_pre_view().
 *
 * Adds a field to the "YOUR VIEW NAME" view.
 */
function YOURMODULE_views_pre_view(&$view) {

  if ($view->name == 'YOUR_VIEW_NAME') {
    // the vocabularies defined in the view.
    $vocabularies = array_filter($view->display['default']->handler->options['fields']['term_node_tid']['vocabularies']);
    $terms = YOURMODULE_terms($vocabularies);
    $count = count($terms);
    for ($i=0;$i<$count;$i++) {
      // define the field id.
      $view->display['default']->handler->options['fields']['tid_' . $i]['id'] = 'tid_' . $i;

      // define the table (it has to be the same table for all fields)
      // if you aren't sure what the table name should be, uncomment the line below and take a look at the first field data.
      // debug($view->display['default']->handler->options['fields'], 'VIEW FIELDS', TRUE);
      $view->display['default']->handler->options['fields']['tid_' . $i]['table'] = 'node';

      // here we need to define our custom field output
      // the field "Content: All taxonomy terms (All taxonomy terms)" has a mashine name 'term_node_tid'
      // this field need to be excluded from display because we do not want to display one column only.
      // Instead we will use the data to populate all our custom fields, then we'll be able to define the output for each of them.
      $view->display['default']->handler->options['fields']['tid_' . $i]['field'] = 'term_node_tid';

      // define the field label
      $view->display['default']->handler->options['fields']['tid_' . $i]['label'] = $terms[$i];

      // we need only term names, not links.
      $view->display['default']->handler->options['fields']['tid_' . $i]['link_to_taxonomy'] = 0;
    }
  }
}

A helper function that returns an array of terms. This function will be used twice. First time in hook_views_pre_view() where the argument is available from the View. Second time in YOURMODULE_has_term() where the argument would be hardly to get. That's why I decided to use a static variable here.

/**
 * Helper function that returns an array of terms.
 *
 * @return array
 *   An array of terms from all vocabularies (defined in the view).
 */
function YOURMODULE_terms($vocabularies = NULL) {
  $terms = &drupal_static(__FUNCTION__);
  if (!isset($terms)) {
    $terms = array();
    foreach ($vocabularies as $key => $vocabulary) {
      $vid = taxonomy_vocabulary_machine_name_load($vocabulary)->vid;
      $taxonomy_tree = taxonomy_get_tree($vid);
      foreach ($taxonomy_tree as $term) {
        $terms[] = $term->name;
      }
    }
  }
  return $terms;
}

A helper function to determine if a field value (comma-separated list of terms) contains the term of current column. This function will be used in a Views field template file.

/**
 * Determines if a comma-seperated list of terms contains the term of the
 * current column.
 *
 * @param $field_alias string
 *   The field alias corresponding to the $field->field_alias value in the view.
 * @param $field_position integer
 *   The column corresponding to the $field->position value in the view.
 * @param $output string
 *   Comma seperated list of terms.
 * @return 'X' if TRUE or bool if FALSE.
 */
function YOURMODULE_has_term($field_alias, $field_position, $output) {

  // because we are using two fields to provide the data
  // we need to skip two positions to get appropriate term keys.
  $field_position = ($field_position > 1) ? $field_position-2 : $field_position;

  // because this is a second call for this function,
  // we don't need to define vocabularies as an argument.
  $terms = testmodule_terms();

  // each column has their own term name.
  $term_name = $terms[$field_position];

  // first column fields.
  if ($field_alias == 'node_title') {
    return $output;
  }

  // the fields in all terms columns.
  else {

    // explode terms and trim whitespaces.
    $term_names = array_map('trim',explode(",",$output));

    // check the term names array contains the term of the current column.
    if (in_array($term_name, $term_names)) {
      return 'X'; // check mark
    }
    return FALSE;
  }
}

Views field template file

Create a View template file views-view-field--[YOUR-VIEW-NAME].tpl.php and place in your templates folder.

<?php
// We're assuming that this view only has two fields (Content: Title)
// and  Content: All taxonomy terms (All taxonomy terms).
// All other fields are generated by the HOOK_views_pre_view() function in the
// `YOURMODULE.module` and those should be passed through the
// `YOURMODULE_has_term` function which determines if the $output
// (comma-seperated terms) contains the column term name.
print YOURMODULE_has_term($field->field_alias, $field->position, $output);
?>

I was able to answer this question thanks to a similar post here and added lots of comments to the code. Hope it helps.


How do I get rid of the "Configure Blocks" link above my menus? I know the answer to this will be obvious (and probably embarrassing), but the link started appearing on my new development site, and I want to turn it off to do some styling.  The link only appears above menus and I cannot find a setting in a relevant module to turn it off. This problem is at the annoying stage for me, but could become an obsession if I..don't....squash.....this......nasty..........bug!

Does anyone know what controls this?  :)

I think those links come from the core "Contextual links" module; you should be able to pop to http://mysite.com/admin/modules, disable the module and see the links disappear :)

A bit of extra info on Contextual Links:

http://drupal7ish.blogspot.com/2011/06/contextual-links.html


Simple drop-down "list" items (inside a html "body") --- content (un)hiding upon click --- Not a navigation bar, no redirect, no menu, no forms I would like to ask if it were possible to have certain content (nothing too special, just regular lines of text with standard formatting) on a html article, like e.g. ordered in a list, which can be unfolded (or hidden again) by a mouse-click?

When searching information on this, I easily come by navigation drop-down menu's; but a navigation side-bar or top-bar is not what I am looking for.
I have found another question asking for something similar, but wanting to be redericted to another page (similar to a navigation menu), that is also not what I want to do: I do not want to navigate to another page.

I would simply like a drop-down "list" inside a html's "body" article. The visitor should be able to open or close these "frames" or "list items", e.g. by clicking on the title or on a list button. I am just looking for a "1-level-depth" list.

It would be nice if the items had a title and a number, ordered vertically, like a regular ordered list:

>click to unfold< List item 1
>click to unfold< List item 2
>click to unfold< ...

If, for example you would click on list item 1, the content of list item 1 would show:

>clicked, click to hide content again< List item 1
<<< Content of list item 1, which is just standard lines of text, perhaps with standart formatting. >>>
>click to (un)fold< List item 2
>click to (un)fold< ...

The text I have put between ">"..."<", is just to clarify; isn't specifically needed. This could just be a triangular list bullet for example, which could just change by pointing downwards when clicked.

Is this possible by using a Drupal module, or perhaps just via html code?

Any help on this would be greatly appreciated,

Vincent Verheyen.

P.S.: I am very new to Drupal and understand the basics such as installing modules.

@Wtower's help above makes this pretty straightforward. Drupal (I am using 7) can use these jQuery codes without any additional install.

One can just put the following right inside a drupal "node", such as a standard article. This solution works for list items; the following is to be implemented [I used ordered lists (ol) in my example]:

List tem 1.

Content of list item 1.

List item 2.

Content of list item 2.

I haven't looked at triangular (changing upon revealing or hiding content) list bullets yet.

If you want other items than list items, look here:

http://renaudjoubert.com/fr/node/56
http://triq.net/articles/hide-and-slide-drupal-content-jquery


Will the PHP filter prevent SQL injection attacks? I had trouble getting the form API to work though I am considering re doing all my forms with it. I have some custom html/php forms however I directly insert into the DB using pg_query. I am looking into replacing that with pg_query_params to escape. I was wondering whether the php filter module, if I set it up, would prevent users from doing harm via sql injection? Iwould guess not but thought I would check.

Just looking for suggestions.

It will not, in any way shape or form protect you from injection. Quite the contrary, using the PHP filter is generally a horrible security problem, because it enables arbitrary code to be executed.

Do not use the PHP module, at all.

Greggles mentions the Paranoia module in his answer, which is awesome, consider using it. However, if you have enough control over your server, you could take it one step further, by disabling the eval function all together.

In your php.ini: disable_functions = eval


How to restrict taxonomy term reference with certain terms? In a node edit/add form, I need to show a field with dropdown/select list options (Cardinality unlimited). I do not want all the taxonomy terms of that vocabulary to appear. I want to show certain terms. The vocabulary has 2 level hierarchy. First dropdown in the form element shows only parent terms. On selecting parent term from the dropdown, certain child elements should show in the second dropdown.

You seem to be asking 2 questions here:

Restricting Terms: You can edit the entity reference field's Reference method to use a new custom view that filters only the criteria you're looking for.
Parent/Child Widget: The Hierarchical Select did have this widget functionality in D7, in D8 there are a few modules out there, like Simple hierarchical select & Client-side hierarchical select, that have similar dual-selection functionality.


How do I hide a field from a Profile2 form without deleting it? I have a field in a Profile2 form. I'm trying to streamline the signup process and not ask for users' phone numbers. However, I don't want to delete the phone numbers of users who have already inputted the field, so I don't want to delete the field.

How do I hide the field from the form, without deleting it, and having the ability to unhide it if I decide to do that later (or ask for the information at a later time, after initial signup)?

You could do it using the Field Permissions Module, and set it to admin only. It can easily be changed later to allow everyone to see the field.

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


How to display an Image based on content author role in view? I want to display an image in a view based on the role of the author of the content.
Lets say role "premium user". If the content author is not having the role just display an image placeholder ? What is the best way to do it ? Views PHP ?

Add relationships:

From node to it's author
From author to his role

Then add role field to display, and in tpl.php substitute it for your desired image.

You can read about relationships on http://example.org/help/views/relationship if you have Drupal installed (substitute example.org with your domain or localhost as needed) and advanced help on.