Why bootstrap navigation button does not expand? I am trying to created a simple responsive theme using bootstrap but got stock at navigation bar in Drupal 6 and basic theme. Here is the navbar that I've put in page.tpl.php:

  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

  </button>
  MySite

Home

About

Tutorials

I have removed all the native css and js files. Instead I have placed bootstrap.css, bootstrap.min.js and jquery-1.10.2.min.js into the theme and defined them for info and template.php. In the rendered page source I can see that all the 3 are loaded.

When I shrink the window, the navigation links collpase to button but then the button does not respond to on click to expected and show links.
I also tried the very bootstrap example navbar but the button and drop-down menus does not work either.

What could be wrong here?

Can see in the source of the page that all the three are loaded.

The problem is in JavaScript: you should not include jQuery (and generally other libraries) through your theme.

Bootstrap requires newer versions of jQuery (I think v1.8+) and you should use jQuery Update module to upgrade it on your site.


Fatal error: Class name must be a valid object or a string in /home/dsmedia/blog/public_html/includes/common.inc on line 7749 I installed a module in drupal called Views Media Browser, that is when I first noticed the issue.

I properly uninstalled the module (unchecked it, uninstalled it, then removed the folder from my sites/all/modules folder).  Now when I go to any article content I've created I am welcomed to the above mentioned error.

I checked the file and the location of it mentioned in the error

/**
 * Get the entity controller class for an entity type.
 */
function entity_get_controller($entity_type) {
  $controllers = &drupal_static(__FUNCTION__, array());
  if (!isset($controllers[$entity_type])) {
    $type_info = entity_get_info($entity_type);
    $class = $type_info['controller class'];
    $controllers[$entity_type] = new $class($entity_type);
  }
  return $controllers[$entity_type];
}

I even compared it to a vanilla version of Drupal and the files are the same.

I noticed that it does not occur with basic pages or any other content type I have. I would prefer not to have to restart the site, so if there is a way to correct this fatal error I would appreciate it.

I had a similar issue today (same error message) and I just solved it. It concerns my personal case, but if the description can help anyone :
the problem was the fact that I had created a few items with a content type that I deleted since. So these non published items had an invalid class, because the content type was not existing anymore.
I found these 3 items in the list of content with a blank space instead of the content type name.
Deleting these 3 items, and then extracting/importing the database again to the customer made it work.

The stange thing is that my version of the site was still working since I deleted the content type, so I couldn't understand why suddenly this problem when migrating the site.


How to make 2 or 3 xml sitemaps in drupal for example for different taxonomies? I need to generate 4 sitemaps which differ in content included in them according to certain taxonomies! XML sitemap can generate one sitemap. When I try to generate other it displays error: A sitemap with the same context already exists.

I suggest installing the Views Data Export module. It will allow you to create XML pages from your taxonomy and as many as you want.

I would create one view and 4 page displays with the varying filters to generate your pages.  Then change the output to XML.

I looked over the XML Sitemap, and the error you are experiencing seems to be something they are trying to troubleshoot. You can follow along there, or try some of their methods.


How to combine values of same field in a single column of a chart created with Charts? My question is about merging values for both the title field (= the company name) and various fields. I'm currently using the Charts module.

In the picture below, it shows a column chart that displays a content type with a field of title, integer field (labeled 2017), and another integer field (labeled 2018). In this view, I have a chart (showing title and 2017) and a chart add-on (title and 2018).

The graph looks like this:

Here is how the table about these data looks like:

  Company   ! 2017 ! 2018
  ----------+------+-----
  Company A ! 5    ! 6
  Company B ! 2    ! 3

What I want to do is SUM all the values of the 2017 field into one column and values of 2018 into one column.

I tried using the Views Merge Rows module and configured the option to SUM all the values of 2017 and 2018 into one column, but it's not working for me. The chart (showing title and 2017) works since it combines all values, but the chart add-on splits apart and I don't know why.

This is what I get:

Is there a way to combine all values of 2017 and 2018 into one column for each year? "Combine" means that I want to sum all values from a field into one column, so  for (e.g.) 2017, it should be 7 (=5+2).

Note: I'd prefer to not Use the Charts API, but I will if I have to.

Edit: The module now shows individual values for each company and takes the company's latest published version's vales. So, if I made another entry for Company A and it's published, the chart will only show the latest version's values. I've also edited the body and included a picture of the final result.

It looks like building a custom module answered my own question. I had to code a module with the charts API and create a custom block to show the data (it was a huge pain writing the functions and retrieving the data).

Instead of adding all the values into one column, what I've done is take a company's values for each year, place it on the chart, and other company values stacked on the previous company values as shown here:

To anyone else now or in the future with the same problem as me, here's a code snippet that I used:

$chart = array(
 '#type' => 'chart',
 '#chart_type' => 'column',
 '#stacking' => TRUE,
);

Include the code ^above in your function that displays the block/module.

You will need to make your own functions and may be you'll need to implement some of the functions as shown in WD Tutorials for Drupal.

Also, for getting the field data, I made a function that shows all the years (in sequential order). I made several variables: holding a result of an array to store the years, counters (for an array counter, year counter, etc.), an offset for the current year, and a variable for a hard limit (having an arbitrary hard limit is bad). I made use of two while loops that checked to see if the data field (e.g. field_data_field_(insert name of field)) to check if it exists and to see that year contained any rows (indicating that having any values in the table shows that it exists).

As for the other functions, I made separate functions such as filtering duplicates, retrieving all node IDs that are Company content type, and getting each of the node's ID values.

For anyone that's stuck on Drupal's PHP syntax, I would suggest looking at PHP first and then comparing it to Drupal's PHP documentation (confused me at first).

Thanks to all that offered me help during the process. It got me thinking better.


Why would the body field's language not save as the same language as the node? I am having a problem where the user is creating new nodes and entering body text, but setting the nodes to "language neutral" for the language. Yet when it saves the node the body field's language gets set to English. Why would this be happening? What would cause this?

On this site we have both English and French enabled and configured. This site is D7 running i18n.

This is similar to Empty body in node edit page except that I want to know how the field would get a different language than the node in the first place.

By default, drupal sets 'und' as the field language, that is LANGUAGE_NONE. So, when you print_r($node), you will see a field with something like $node->field_name['und'][0]['value']

Now, when you enable translation on this field, the 'und' will get replaced by the language code and somehow the $node structure would look like $node->field_name['en'][0]['value'] where 'en' is the language code. Your body field will now have 'en' as the language and won't be empty anymore when rendered

For your question above :

  I am having a problem where the user is creating new nodes and entering body text, but setting the nodes to "language neutral" for the language. Yet when it saves the node the body field's language gets set to English. Why would this be happening? What would cause this?

Check default language of your site, if its set to English, then probably Language Neutral will take your site's default language.


preprocess view fields I have a view with some fields wich I theme inside views-view-fields--MYVIEW.tpl.php. I use a phptemplate_preprocess_views_view_unformatted__MYVIEW() to preprocess some $vars before the template to have the template as clean as possible. But I don't know the right way of preprocessing the fields.

I can access the fieldcontent in the template via $fields['MYFIELD']->content. Inside the preprocess function I can't find this explicit content value. All I see is something called last_render but i'm not sure it's ok (the right way) to use/change this value.

Try to use debug() to see the content of $vars. As far as I know, in views/themes/theme.inc there are many examples of preprocessing functions.


Avoid random number cached in preprocess hook I have a random set of images that appear on the homepage which needs to show each time the page is refreshed. My holding page was doing this comfortably in PHP, but since building the whole site and migrating the PHP into Twig I ran into issues with the cache. I tried moving the code into a preprocess hook for the content type however that too is subject to the caching.

Is there anyway around this problem by disabling caching for anonymous users in the preprocess hook, or updating the random number variable in the cache on each reload etc.?

Ideally I'd like to avoid doing this in JS as per the recommendation here Ignore cache in preprocess function

Here is my preprocess function PHP code which feeds a loop.

function freadman_white_preprocess_node__3(&$variables) {

$imageset = (rand(1,8));
$time = array(
    '01:14',
    '10:37',
    '11:16',
    '09:38',
    '04:51',
    '03:24',
    '10:39',
    '10:58'
);
$date = array(
    'pm Saturday 18.08.18',
    'am Sunday 05.08.18',
    'am Sunday 05.08.18',
    'am Wednesday 15.08.18',
    'pm Tuesday 21.08.18',
    'pm Tuesday 21.08.18',
    'am Wednesday 25.07.18',
    'am Saturday 25.08.18'
);

$variables['imageCount'] = 33;
$variables['imageSet'] = $imageset;
$variables['imageTime'] = $time[$imageset-1];
$variables['imageDate'] = $date[$imageset-1];

}

First, try to pass a render element with a '#cache' value set, maybe like so:

$variables['imageSet'] = [
  '#type' => 'value',
  '#value' => $imageset,
  '#cache' => [
    'max-age' => 0,
  ],
];

Next, you could try to completely disable the cache for this node (though that's probably not the best idea).

$variables['#cache']['max-age'] = 0;

And last – but quite advanced – you can provide a custom controller, that returns an uncached JSON response with your calculations and then use a little JS script that fetches the JSON via Ajax and inserts it into some placeholder selector in your markup (for the placeholder you could even provide a pseudo field to be placed at a desired position via the admin UI).

I used exactly the concept described above to build User Online Status. You can simply grab a copy and check its code to get an idea how that works.


How can I move taxonomy terms to a different vocabulary and update term reference fields? I need to split a taxonomy vocabulary into two different vocabularies in Drupal 7.

I can use the Taxonomy Manager module to move terms from one vocabulary to another; I have tested this and it works.

However, the big problem is that I have a large number of nodes with a taxonomy term reference field that include references to the terms.

This is what it looks like now:
Nodes of Content Type X have a Taxonomy term reference (multiple values permitted) to Vocabulary A.

This is what I want to do.

Split Vocabulary A into Vocabulary B and Vocabulary A (which contains about half the terms).  [This step can be done with Taxonomy Manager.]
Create a new term reference field to Vocabulary B.  [This can be done from the Field UI.]
Move the term references to terms that are now in Vocabulary B in the Term reference to Vocabulary A to the new term reference for Vocabulary B.  [No idea how to do this except a lot of manual work.]

Any ideas about how to go about step 3?

This tutorial suggests doing it via directly performing SQL queries to change the associated vocabularies for the terms in question.

The term reference fields should be by term ID. The term ID should not be changing, only the vocabulary value associated with the term entity.


Views: creating a hierarchy of content - am I doing it right? This is a little complicated, but here goes:

I have a taxonomy vocabulary in a tree-structure.
I have a content type with a field of the vocabulary.
I am using the Views Tree module to display a tree of the vocabulary, and want the content to display within the tree. (Please see the illustration below).
In my view I use a relationship to add the links to the content type to the view.
animal

mammal

DOG
CAT

vegetable

flowering plant

ROSE

This would seem to me to be a fairly common thing to do. Am I doing it right? (i.e. is creating a taxonomy vocabulary and using Views Tree the best way to do this?)

A taxonomy tree is often the first that comes to mind thinking of a hierarchical directory of content items – but similar structures can also be built in many different ways. Here's just two examples that I personally find often easier to handle, than a taxonomy tree:

Entity reference – rather than having 'lists' of content items 'attached' to taxonomy terms, to me this approach has a more 'real' feel concerning the item-to-item relations. You actually have nodes (items) that can either be partens, children or siblings of nodes (or content types) with all the advatages that come with nodes like commenting etc. And the free tagging reference field let's you even generate new elements 'remotely'.
Book module – probably one of the most underrated core modules – let's you genrate complex tree structures out of the box. While I consider it ideal for a quick start, it might become a bit low-fi in the long run.

For me reading this article "RIP Taxonomy Module in Drupal 7" was appeared to be quite helpful when I (again) had to decide how to build a tree of related nodes.


Requesting REST-GET gives me 403 but works fine in DHC I am stuck for hours now with a JSON REST problem:

I have a simple REST endpoint in my Drupal 8 App. If I call it with the DHC Chromium REST Extension like GET http://proreos/api/v1/checklawyer/1?_format=json, I get

127.0.0.1 - - [07/Jul/2016:15:03:54 +0200] "GET /api/v1/checklawyer/1?_format=json HTTP/1.1" 200 477 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/51.0.2704.79 Chrome/51.0.2704.79 Safari/537.36"

That's wonderful. Also Drupal does all the requested processing.
But if I call it from curl like

curl 'http://proreos/api/v1/checklawyer/1?_format=json'

I get the bad 403 response:

127.0.0.1 - - [07/Jul/2016:15:10:27 +0200] "GET /api/v1/checklawyer/1?_format=json HTTP/1.1" 403 409 "-" "curl/7.35.0"

Well actually, I want to call it from a JS plugin like:

function checkLawyer() {
  var server = drupalSettings.bootasde.proreos_server;
  var id = drupalSettings.bootasde.asdeid;
  var jUrl = server+'api/v1/checklawyer/'+id+'?_format=json';
  console.log('Q: '+jUrl);
  jQuery.getJSON(jUrl);
}

It works fine, but unfortunately, it also gives me a 403 without any further Drupal backend processing:

127.0.0.1 - - [07/Jul/2016:15:06:03 +0200] "GET /api/v1/checklawyer/1?_format=json HTTP/1.1" 403 464 "http://proreos/asde/anwalt/1" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"

Console says:

15:17:22.973 "Q: http://proreos/api/v1/checklawyer/1?_format=json"
XHR HTTP/1.1 403 Forbidden

Any idea would be great! Thanks.

Doomed, I am so stupid. Chrome had the admin cookie, FF had a simple user cookie. I forgot to permit the GET on the new endpoint in the user permissions!!!

So stupid. @Clive: Thanks a lot for your help and sorry for that waste of time.


How to link Views Bulk Operations and Bibliography modules in a home-made search engine? I am using Bilbiography module to manage scientific publications on a website.
The default search engine is nice but I would like to add a Views Bulk Operations function so users can choose specific nodes (tick the boxes on each line) and then export them to End Note or Bibtex, etc., like Bibliography does (export links at the top right).
Has anyone built a thing like this before in a View?
I would appreciate to have a few tips on this.
Thanks in advance.

See this sandbox module that add export functionality for all results in a view as a footer / header: https://www.drupal.org/sandbox/szeidler/2394975


Executing a view programmatically with input filters I've created a View to search for suitable jobs. Along with View I want to give a "Subscribe" button for those who want matching jobs(if any) be delivered in their inbox daily. I want to save the input entered in the exposed filters and run the View at night in a batch for all those who have subscribed for jobs.

I will add a "Subscribe" button along with "Apply" in the Views form. So if any logged-in user selects the "Subscribe" button I want to: 1) Save the input of exposed filters; 2) Run this view every night and see if any new matches are found; 3) Email the user with new jobs found.

Is there any easy way to do it? Is there any module to help me?

I can use Views Saved Searches module to save current user selection of exposed filters.  This input could be fed when calling view programmatically.

Also two more useful links: Using Views Programmatically Drupalcamp & get the result view creates.

EDIT:
I need someone to provide me practical in-use implementation that can save my time.

I don't think that you need to execute the view programmatically. Because it's meaningless. Views just fetches data from the tables which you show and display it, it's all it does.
I think you need to alter Exposed Filter form and add your additional submit callback which on submission writes the searched strings into your custom table. And then you can query those table (from which table views fetch data.) with saved string as condition..
All of this logic must be run on cron job..

EDIT:
I don't know this can help you or not, but here is a very poor example. Not very performance friendly :). OPTIMIZE IT.

function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
   if ($form['#id'] == 'MY_EX_FORM_ID') {
      if(user_is_logged_in()) {
         $form['actions'] = array(
            '#type' => 'actions',
         );

         $form['actions']['submit'] = $form['submit'];
         $form['actions']['subscribe'] = array(
            '#type' => 'submit',
            '#value' => 'Subscribe',
            '#submit' => array('my_ex_form_subscribe_submit'),
         );
         unset($form['submit']);
      }
   }
}

function my_ex_form_subscribe_submit($form, &$form_state) {
   global $user;
   $account = clone $user;

   $input_val = $form_state['values']['field_adv_price_first']['min']; //Find your input field value and change this..

   db_insert('MY_SUBSCRIBE_TABLE')
      ->fields(array(
         'uid' => $account->uid,
         'email' => $account->init,
         'input_val' => $input_val,
      ))
      ->execute();
}

function MY_MODULE_cron() {
   $subscribed_query = db_select('MY_SUBSCRIBE_TABLE', 'mst');
   $subscribed_query
      ->fields('mst', array('uid', 'email', 'input_val'))
      ->execute()
      ->fetchAllAssoc('id'/* id - is the primary key of MY_SUBSCRIBE_TABLE */);

   // Supposing that your view is querying for the node table to fetch jobs, by title field
   if(!empty($subscribed_query)) {
      foreach($subscribed_query as $key => $val) {
         $nids = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('title', '%' . db_like($subscribed_query[$key]['input_val']) . '%', 'LIKE')
            ->execute()
            ->fetchCol();

         if(!empty($nids)) {
            foreach($nids as $nid) {
               $node_url = url('node/' . $nid, array('absolute' => TRUE));
               $template = 'New job is found in our site and blablabla... BLABLABLA';

               // Suppose that you are using SwiftMail library.. You can use drupal's mail system as well. It's up to you
               $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
                  ->setUsername('MYGMAILUSERNAME')
                  ->setPassword('MYGMAILPASS');

               $mailer = Swift_Mailer::newInstance($transport);

               $message = Swift_Message::newInstance()
                  ->setFrom(array('no-reply@'.$_SERVER['SERVER_NAME'] => 'MY-SITE.com'))
                  ->setTo(array($subscribed_query[$key]['email']))
                  ->setBody($template, 'text/html');
               $mailer->send($message);
            }
         }
      }
   }
}


How to change taxonomy term ID to term name? I'm trying to change path of my site which is based on taxonomy tags. Default path of my site in this context is /taxonomy/term/120 (or other number - TID).

In Drupal 7 option to change TID to term:name was easy using Contextual filter and Filter value type set to Term name coverted to Term ID (shown eg here: Views contextual filters taxonomy name).

The big problem I'm struggling with is that there is no Filter value type field (dropdown menu) in Drupal 8. This is picture of my screen:

So I cannot change TID to term name.

Have anyone idea how I can exchange them. Is there another way to change them in Drupal 8?

You first have to create a relation with the taxonomy terms by adding the relationship with the taxonomy list or Taxonomy terms on node. Once you have added the relation, you can now add a contextual filter called name with the category Taxonomy term. This way you can pass the taxonomy term by name to the filter.


Allowing file-transfer to use sftp or ssh? I have my own dev-server that I installed with Ubuntu 11.04. When I set it up, I was fairly new to the whole "server thing", so I'm not sure that I set up everything 100% up to industry standards.

The problem I am having, is that trying to automatically update things almost never works when using drupal's UI.

I usually got around this, by just ssh-ing into my server, and using drush to update everything.

The problem now, however, is, that instead of updating the site, I am trying to install "apps" (not modules), and I am not sure how to do this with drush. (plus I want to figure out how to fix this FTP problem anyway)

What usually happens, is that I will get an error (not a specific one, just one that is saying Error installing nameofmodule)

Recently though, I tried using a different user account with direct access to the folder (it being the user's home folder), and I am getting the folowing error

Warning: ftp_login(): Login incorrect. in FileTransferFTPExtension->connect() (line 59 of ..../includes/filetransfer/ftp.inc).
Failed to connect to the server. The server reports the following message:
Cannot log in to FTP server. Check username and password

I know the username and password are correct, I checked them more than a dozen times in terminal, however, I realized, that whenever I ftp into the server, I get an error if I use ftp, but I instead have to use sftp.

Is that what my problem is? If it is, how can I get Drupal to use sftp or ssh to transfer files instead of just ftp?

PS. If it helps, I am using the OpenEnterprise 7.x-1.x-dev distribution of Drupal

I would still like to be able to use sftp, but for now, I was able to set up ssh here's how I did it:

user$ sudo apt-get install libssh2-php
user$ sudo /etc/init.d/apache2 restart

And now I can use the update manger with ssh, which works, for now......


Testing the path module Taxonomy terms on my site are saved with the proper path alias assigned to them but attempting to go to the corresponding page results in a "page not found" error.

The core path module includes a test file (path.test.) Does anyone know how to use it?
Thanks. :)

I welcome any suggestion on how to fix that problem. :)

Running tests is fairly straight forward:

Enable the Testing module at /admin/modules
Visit /admin/config/development/testing and choose tests to run (you'll find Path, Path API and Pathauto)
Run them and wait for the results

If you have stable versions of core and the contrib modules it's a pretty safe bet that they'll pass.


Submission of dynamically generated input fields I have created data entry form using Drupal 8 Webform (Yaml forms),
Part of the form is table field which hosts dynamically generted textfields using jquery shown below:

 $(document).ready(function(){
    var input="";
    var column="";
    $(".add-row").click(function(){
    var new_row =jQuery('<tr>');
    input= jQuery('<input>').attr({type: 'text',name:'names[]'});
    column=jQuery('<td>').append(input);
    input= jQuery('<input>').attr({type: 'text',email:'emails[]'});
    column=jQuery('<td>').append(input);
    new_row.append(column);
        $("table tbody").append(new_row);
    });
});

However, to my surprise when I hit submit button of the form all other fields are submitted except the fields
which have been generated dynamically on the table field.It seems Drupal 8 can not recognize the dynamically generated input
fields

So my question how can I make Drupal 8 recognize my dynamically generated input fields. I want to see the data in these fields in
the database. Please help. Your assistance will be greatly appreciated

The WebformSubmissionStorage service uses the list of elements associated with the webform to properly store the data.  You are going to have to create an Element and WebformElement plugin definition that defines the element type (ie multiple, composite, etc...) and then attach your JS as a library.


How to pass a literal string into drush config-set I'm currently attempting to configure the ClamAV module via drush config-set. When using the executable mode, the module allows us to specify command-line options to run when the ClamAV executable is triggered.

My attempt to do so is:
[root@localhost html]# drush config-set clamav.settings mode_executable.executable_parameters '--max-filesize=4095M --max-scansize=4095M --max-embeddedpe=4095M --max-htmlnormalize=4095M --max-htmlnotags=4095M --max-scriptnormalize=4095M --max-ziptypercg=4095M --pcre-max-filesize
=4095M' --y

Unfortunately, I get the error:
Unknown option: --max-filesize.  Seedrush help config-setfor available options. To suppress this error, add the option --strict=0.

Using sh/bash, how do I write this command as to pass in the executable parameters as the setting (a literal string), not as options to drush config-set, as is currently happening?

Short answer, preface the value with an empty space (inside the quotes).

This appears to be a drush bug. This fails with the unknown option bit:

drush config-set system.site name '--max-filesize=blah'

However, if I preface the value with a space:

drush config-set system.site name ' --max-filesize=blah'

this works as expected.

Edit: It is also worth noting that drush config-edit would bypass this issue altogether, and allow the value to be set via your preferred text editor.


Node id inside views template? How to get the $node->nid inside a views template where i'm printing cck fields? $node variable is availabli only in node.tpl.php.

If using fields as the display type the data will not be readily available in the display or style output, but can easily be gotten in the field tpl's by accessing the $row object which has all of the original raw data from the database.

Click on Theme: Information when in Views (editing the view in question) and you'll see all of the template recommendations to use. You'll probably want to use a tpl file that involves both the view and field name, e.g. view-view-field--[view_name]--field-[field_name].tpl.php.

Once you've created this tpl file you can access the following variables:

$view: The view object
$field: The field handler object that can process the input
$row: The raw SQL result that can be used
$output: The processed output that will normally be used.

You could do something special in <?php ?> and then print it like normal. For example, this would print out a specific field from a node that's referenced in a node_reference field:

Contents of view-view-field--blog--field-blog-parent.tpl.php:

<?php
$a_referenced_node = node_load($row->{$field->field_alias});
if ($a_referenced_node) {
  print $a_referenced_node->field_some_other_field[0]['value'];
}
?>


Is there a way to list permissions for a given module? Using Drush 9, I am trying to automate the creation of a role and I need to assign permissions to it. I see that I can use drush role-add-perm to do the assignment itself, but I can't find a command to actually give me the permissions supplied by the enabled modules.

It looks like this was doable in older versions of Drush, but I'm not sure Drush 9 has equivalent commands.

Thanks!

You could use drush cim and create a yml for your role like for example

langcode: en
status: true
dependencies: {  }
id: myrole
label: 'My super Role'
weight: 1
is_admin: false
permissions:
  - 'whatever 1'
  - 'whatever 2'

And if you don't know what perms your module brings, you could use that simple eval code with drush:

drush php-eval '$p = Drupal::service("user.permissions")->getPermissions(); foreach ($p as $k => $x) print $k." : ".$x["provider"]."\n";'


mkdir permission denied error when running Browser based test I've wrote a browser based test for the contributed module, code can be seen here, when I run test in terminal I get following error

./vendor/bin/phpunit   --configuration /home/sharique/Projects/drupal/d8/d8contrib/core/phpunit.xml --filter "/::testReadOnlyModeEnabled( .*)?$/" Drupal\Tests\readonlymode\Functional\ReadOnlyModeTest /home/sharique/Projects/drupal/d8/d8contrib/modules/porting/readonlymode/tests/src/Functional/ReadonlymodeTest.php -v
PHPUnit 4.8.36 by Sebastian Bergmann and contributors.

Runtime:        PHP 7.1.10 with Xdebug 2.5.5
Configuration:  /home/sharique/Projects/drupal/d8/d8contrib/core/phpunit.xml

Testing Drupal\Tests\readonlymode\Functional\ReadOnlyModeTest
E

Time: 2 minutes, Memory: 6.00MB

There was 1 error:

1) Drupal\Tests\readonlymode\Functional\ReadOnlyModeTest::testReadOnlyModeEnabled
Exception: User warning: mkdir(): Permission Denied
Drupal\Component\PhpStorage\FileStorage->createDirectory()() (Line: 173)

/home/sharique/Projects/drupal/d8/d8contrib/core/lib/Drupal/Core/Test/HttpClientMiddleware/TestHttpClientMiddleware.php:44
/home/sharique/Projects/drupal/d8/d8contrib/vendor/guzzlehttp/promises/src/Promise.php:203
/home/sharique/Projects/drupal/d8/d8contrib/vendor/guzzlehttp/promises/src/Promise.php:156
/home/sharique/Projects/drupal/d8/d8contrib/vendor/guzzlehttp/promises/src/TaskQueue.php:47
/home/sharique/Projects/drupal/d8/d8contrib/vendor/guzzlehttp/promises/src/Promise.php:246
/home/sharique/Projects/drupal/d8/d8contrib/vendor/guzzlehttp/promises/src/Promise.php:223
/home/sharique/Projects/drupal/d8/d8contrib/vendor/guzzlehttp/promises/src/Promise.php:267
/home/sharique/Projects/drupal/d8/d8contrib/vendor/guzzlehttp/promises/src/Promise.php:225
/home/sharique/Projects/drupal/d8/d8contrib/vendor/guzzlehttp/promises/src/Promise.php:62
/home/sharique/Projects/drupal/d8/d8contrib/vendor/guzzlehttp/guzzle/src/Client.php:131
/home/sharique/Projects/drupal/d8/d8contrib/vendor/fabpot/goutte/Goutte/Client.php:155
/home/sharique/Projects/drupal/d8/d8contrib/vendor/symfony/browser-kit/Client.php:315
/home/sharique/Projects/drupal/d8/d8contrib/vendor/behat/mink-browserkit-driver/src/BrowserKitDriver.php:144
/home/sharique/Projects/drupal/d8/d8contrib/vendor/behat/mink/src/Session.php:148
/home/sharique/Projects/drupal/d8/d8contrib/core/tests/Drupal/Tests/BrowserTestBase.php:333
/home/sharique/Projects/drupal/d8/d8contrib/core/tests/Drupal/Tests/BrowserTestBase.php:472

FAILURES!
Tests: 1, Assertions: 1, Errors: 1.

Same error when running from PhpStorm

Maybe the Permission problems section of Running PHPUnit tests can help you:

Note: functional tests have to be invoked with a user in the same group as the web server user. You can either configure Apache (or nginx) to run as your own system user or run tests as a privileged user instead.
To develop locally, a straightforward - but also less secure - approach is to run tests as your own system user. To achieve that, change the default Apache user to run as your system user. Typically, you'd need to modify /etc/apache2/envvars on Linux or /etc/apache2/httpd.conf on Mac.
Example for Linux:

export APACHE_RUN_USER=<your-user>
export APACHE_RUN_GROUP=<your-group>

If the default user is e.g. www-data, the above functional tests will have to be invoked with sudo instead:

export SIMPLETEST_DB='mysql://root@localhost/dev_d8'
export SIMPLETEST_BASE_URL='http://d8.dev'
sudo -u www-data -E ./vendor/bin/phpunit -c core --testsuite functional
sudo -u www-data -E ./vendor/bin/phpunit -c core --testsuite functional-javascript


How to restrict editing some node properties (like title / URL) for some users (roles)? I would like to know how I can restrict editing some property of nodes (like title / Url) for some users (roles).

So if I give -moderator access- to some users, they don't start messing with urls and I have to make 301.

If you want finer control over any field then you can implement hook_field_access($op, $field, $entity_type, $entity, $account) and provide/deny access.

Determine whether the user has access to a given field.
This hook is invoked from field_access() to let modules block access to operations on fields. If no module returns FALSE, the operation is allowed.


Why does Drupal use 403 Forbidden? RFC 2616, the document that defines HTTP/1.1, lays out the definitions of all the HTTP status codes. For 403 Forbidden, it says:

  The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity.  If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

But that's not how Drupal uses it: depending on the case, it either uses it for the default condition in callbacks (e.g. shortcut_link_add_inline())—essentially making 403 Forbidden equivalent to "Drupal doesn't understand the request"—or it uses it to inform the client it doesn't have access to the page (i.e. due to permissions like being an anonymous user).

In the case of the former ("the request isn't understood"), the more appropriate status code is 400 Bad Request:

  The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

And in the case of the latter ("the client does not have access to the page due to permissions"), it should either be 401 Unauthorized (if Drupal wants to give away that it's just a permission problem):

  The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.

or 404 File Not Found (if it doesn't):

  The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

Emphasis mine (see also the final sentence in the definition for 403 Forbidden).

I realize it's been like this for many years, but what was the original rationale for making drupal_access_denied()—and by extension 403 Forbidden—the only response Drupal sends when it gets a request it doesn't like?

As stated in your quote, 401 Unauthorized must be combined with HTTP authentication, which is not what Drupal is using, so this is not an option.

So 403 is IMHO a perfectly valid response because clients must not repeat their request but might eventually fill out a login form wich whill result in a different request.

Special cases like the shortlink function you posted aren't so clear. I guess the reason for using access denied there is that it is checking the token which is kinda an authentication. But it could just as well use 400 or 404. I guess the reason for using 403 instead of 400 is simply because there is no helper function for returning a 400.

There also has been a discussion regarding the Privatemsg module (that I'm maintaing) whether trying a private message as anonymous user should result in a 403 or a 404 (for privacy reasons). It used to be 404 but has been changed to 403 because users often click on direct links in mail notifications and a 403 page can easily be turned into a login form (as there is a module that does this out of the box). So this is related to the last two sentences of the 403 description.


How to load a view with ajax with all js files needed? I am using this function to load three views which are loading comments of a node in three tabs by three different sort types by ajax:

function sort1(){
var nid='<?php echo $node->nid; ?>';
$.ajax({
    url: 'http://www.example.com/views/ajax',
    type: 'post',
    data: {
        view_name: 'comments_views',
        view_display_id: 'block_3',
        view_args: nid,
    },
    dataType: 'json',
    success: function(response){
        $('#cm').html(response[1].data);
    }
});
    return false;
}

And for other two views there exist a similar function.

Now what is the problem?

These comments can be replied and voted. But after switching between tabs nether reply nor vote works by ajax. I am using ajax_comment module in order to make it work by ajax and voteAPI and Rate module for rating comments.

I think views is failing in loading js of views.

what is the solution?

What you did is a HardCode solution ,I suggest you instead of loading JS on block, put your JS in .JS files and add ( or attached) to page you want, with simple if your JavaScript just works for you, and remain only one problem, how pass NID to JS?

Pass it with something like

drupal_add_js(array('YOURMODULE' => array('nid' => $nid)), array('type' => 'setting'));

and get it on your js with

nid = Drupal.settings.YOURMODULE.nid;

1
down vote

There is a lot of documentation about how to include a JS file into a custom module or into your theme in general. Here is the official article: https://www.drupal.org/node/304255

There are plenty of examples and you can inspire yourself with it.


How to query for null in nested db_or conditional I am trying to perform a query as listed below (notice the check for NULL)

$query = db_select('node', 'n');
/* add fields and joins... */
$query->condition(db_or()
      ->condition(db_and()
                  ->condition('join_alias1.field_date_unassigned_value', NULL, 'IS')
                  ->condition('join_alias2.field_date_assigned_value', $end_date, '<='))
      ->condition(db_and()
                  ->condition('join_alias1.field_date_unassigned_value', $start_date, '>=')
                  ->condition('join_alias2.field_date_assigned_or_submitted_value', $end_date, '<=')));

I am aware that Drupal expects Null values to be checked like

$query->isNull('myfield');

But I don't understand how to perform a query like I listed above while using $query->isNull().

Any ideas? Thanks

You can use isNull() in the db_and() condition, it'll work just fine:

$query->condition(db_or()
  ->condition(db_and()
    ->isNull('join_alias1.field_date_unassigned_value')
    ->condition('join_alias2.field_date_assigned_value', $end_date, '<=')
  )
  ->condition(db_and()
    ->condition('join_alias1.field_date_unassigned_value', $start_date, '>=')
    ->condition('join_alias2.field_date_assigned_or_submitted_value', $end_date, '<=')
  )
);


How do I create a custom search and filter? I have created a custom module to render forms on the front end (modules\custom_mod\src\Form\Contact\ContactUserForm.php) and stored the form values to a custom table.

I have also created a listing (admin end) of the stored data from table which I acheived with the help of controller (modules\custom_mod\src\Controller\Contact\ContactController.php).

In that listing, I have the Edit and Delete actions based on the ID from the table.

The file structure is below.

modules/custom_mod/
├── js
├── css
├── custom_mod.routing.yml
├── custom_mod.info.yml
├── custom_mod.module
├── custom_mod.libraries.yml
└── src
    ├── Form
        └── Contact
            └── ContactUserForm.php
            └── ContactUserStorage.php
            └── ContactAdminForm.php
            └── ContactAdminEdit.php
    ├── Controller
        └── Contact
            └── ContactController.php

Now I need a search box, a From date and To date filter, with an Export (CSV) button above the listing, so that the administrator user can filter or search accordingly.

How can I achieve this?

I created a very easy month/year filter select box. For that I created a new form class which extends the FormBase class of Drupal 8.

To add filter and search inputs I added following values to the returning array:

namespace Drupal\my_sandbox\Controllers;

use Drupal\Core\Controller\ControllerBase;

class TestController extends ControllerBase
{

public function test()
{

    $form = [];

    //add you custom code here...

    $form['form'] = [
        '#type'  => 'form',
    ];

    $form['form']['filters'] = [
        '#type'  => 'fieldset',
        '#title' => $this->t('Filter'),
        '#open'  => true,
    ];

    $form['form']['filters']['text'] = [
        '#title'         => 'text',
        '#type'          => 'search'
    ];

    $form['form']['filters']['year'] = [
        '#title'         => 'Year',
        '#type'          => 'select',
        '#empty_value'   => 'none',
        '#empty_option'  => '- None -',
        '#size'          => 0,
        '#options'       => ['value1' => 'label1', 'value2' => 'label2'],
        '#default_value' => 'none'
    ];

    $form['form']['filters']['actions'] = [
        '#type'       => 'actions'
    ];

    $form['form']['filters']['actions']['submit'] = [
        '#type'  => 'submit',
        '#value' => $this->t('Filter')
    ];

    //place the table in the form
    $form['table'] = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#attributes' => array(
        'id' => 'bd-contact-table',
      )
    );

    return $form;

}

}

The array for the key 'filters' is the container in which all the filter will be placed. I choose the type 'fieldset', you can change the type of container to any element you want.

Afterwards I added the search and filter input and at the end the button to submit the filter-form. If you use the a class that extends the FormBase class the form will be send the the submitForm method of your class.

A thing here to notice is that every "#type" key maps to Drupal element. All elements are located in the DRUPALCORE/lib/Drupal/Core/Render/Element folder. Example: The #type search will map to the file Search.php within the Element folder. Every file includes a comment where all options of the element are explained.

I hope I could help you.

Nicolas


Why is my form only redirected sometimes? I want to have a user register, and be redirected to a node create form. Here's how I'm doing it thus far.

The setup

I have a route, my_module.register that is handled by MyController::register(). It returns the user register form, like so:

class MyController extends ControllerBase {
  public function register() {
    return $this->entityFormBuilder->getForm(User::create([]), 'register');
  }
}

I also have this service, my_module.form_alter_service (just pretend all the implied dependency injection is there):

class MyFormAlterService {

  public function registerFormAlter(array &$form, FormStateInterface $form_state) {
    if ($this->currentRouteMatch->getRouteName() == 'my_module.register') {
      $form['actions']['submit']['#submit'][] = [$this, 'redirectToAddNode'];
    }
  }

  public static function redirectToAddNode(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirect(/* imagine a node form route here */);
  }

}

I have also implemented hook_form_FORM_ID_alter():

function my_module_form_user_register_form_alter(array $form, FormStateInterface $form_state) {
  \Drupal::service('my_module.form_alter_service')->registerFormAlter($form, $form_state);
}

The expected behavior

I fill out the user register form at /my_module/register, hit submit, and am taken to the desired node add form.

What happens instead

I fill out the user register form at /my_module/register and end up on my user edit page.

But then, if I delete that user, clear the cache, and repeat the process with the exact same credentials, it works as expected.

What I know

I am getting debugging output from every part of the process, so I know each part is running.
I am using the exact same pattern for the login form; identical code in the form alter, and that works great.
I can also get debug output from Drupal/user/EventSubscriber/AccessDeniedSubscriber::onException() which redirects authenticated users who are visiting the user.register route to their edit page. So I know that's causing the unwanted redirect, when the unwanted redirect happens.
I tried removing the user.roles:authenticated cache context from the form, and adding user, but that didn't seem to change things.

The actual question(s)

Why is the form initially not respecting the redirect I set in the submit handler? Why does a cache clear change that behavior?

The cause for the erratic behavior is probably the condition for the current route name in the form alter method. The form is not necessarily built in the same request as the custom controller, it could be served from cache or built in a POST request.

At the moment you have the condition for the route name because the controller invokes the default register form and the form alter doesn't know where it is called from. So you need to make the form distinguishable, for example by a different form handler, a field value in the new entity before you hand it over to the form builder or put the form alter code in a custom form class extending the core user form.

BTW why are you not redirecting by the destination query string you can set on the user register link, then you don't need code?


How to override theme() part in page.tpl.php file? This question is extension of this question: Current Username title instead Secondary menu title, but it is different.

I would like to how can I override the following part of code  theme('links__system_secondary_menu',............) which is in page.tpl.php

For example, if I want to change text => t('Secondary menu') to text => t('Any new text').

One way to do this, which I think is just change that part in page.tpl.php and it works perfectly.

OR

Is there any other way like hook-way to do this, so we can write function in template.php and that override only that part?

from page.tpl.php

<?php if ($secondary_menu): ?>
      <div id="secondary-menu" class="navigation">
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Secondary menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#secondary-menu -->
    <?php endif; ?>

Thanks,

You can override theme_links__system_secondary_menu() in template.php. You will name it MODULENAME_links__system_secondary_menu(), and the original code can be seen here: https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_links/7.x

Copy that code, and modify it as necessary.


Core blog module only shows two blog entries? I've enabled the core blog module, but it only shows two entries on exampe.com/blog

If I "unpublish" one of them, it brings up the next published blog post, which shows me that it does recognize that there are additional blog posts.

There are about 137 in the database. How do I show them all with pagination? The core blog module doesn't seem to have any config settings.

EDIT: The site was recently migrated from D6 to D7, is there anything that may have caused this issue given this fact?

Can you reproduce this behavior using your module set, but with fresh install and blog posts entered manually / generated with devel generate? If not, it's migration failure and your best bet is to export content from old site (you have backup, don't you) and import it to the new one, without Drupal's built in migration tool.

If this happen with fresh setup too, try changing theme to one of the supplied core themes. If it works, then, it means you have a bug in your templates. If it's not, I need to get more info to further expand my answer.


Profile Fields in D7? How do you add fields to a user in Drupal 7 for say, first and last name? I see that Profile is deprecated, is there an easy way to do this without using Content Profile?

You can directly add fields to users (at admin/config/people/accounts/fields) if that's all you need. You can set for each field if it should show up on the registration form.

What Profile2 allows additionally is to create multiple profiles for each user, similar to the categorization feature of the core profile.module.


Is there a way to load the content types using DrupalWebTestCase? I'm trying to learn how to do testing in Drupal. I'm pretty new with it so maybe i didn't got it right.
well, I'm trying to test some views of content types, but to test those views i need to have that content type created when im testing. actually with drupalWebTestCase it's seems it doesn't load the content types that i would have in my normal drupal(except for the basics).

I tried to use simpletest clone but it doesn't work,don't know why, and I don't need all the database for it, just the content types and views.

So... Is there a way to load that content type WITHOUT having to create everything by code? I've a lot of content types some with some complicated fields and loading one by one sounds too harsh to be done.

Try the SimpleTest Clone module.

SimpleTest performs the test on a clean Drupal installation, so if you have created Content Types they will not be available.

SimpleTest Clone craetes a copy of the database (using a table prefix) and performs the tests over those tables, so all config you have done is present.

Once the tests are donde the extra tables are deleted.

The drawback fo this method is that is a little slower than standard SimpleTest because the table copy operation.

To use SimpleTest Clone just subclass your test class form SimpleTestCloneTestCase class instead of DrupalWebTestCase class.


How to not include page titles in the webform included email values? My webform has pages and sections in a webform. The title of the page is not printed out on screen, but it is printed out in the email. The page name was setup as being the same as the section resulting in the email sent having duplicate headings as follows

The form has pages and sections with the form build looking like

I'm using a twig template to print out the results. I could print out each field/title individually however I'd rather just use the 'included email values' functionality. This would make my webform more maintainable. The headings are not in the list of included email values.

Is there a way to manage the headings using this interface? An alternative would be to use inline css on the email. e.g. .x_webform-section-wrapper > h2 {display:none}. I'm not sure all the downstream applications will cope with this.

This should be as easy as changing the wizard page's display settings, but you found a bug.

Issue #3106037: Allow a multi-step wizard page's display to be customized

Once you apply the patch, in the page element's 'Advanced' you can change how the page is displayed via HTML and text. You can use Twig to just render the child element.


How to alter a view sort order? I have used Views to create a view Display a summary by contextual filter.

O/p

View settings like

Needs

There are only two option for sorting "ASC" or "DESC".

But i need to show like

Pass(4)

Fail(2)

Waiting(1)

Tried for

function hook_views_query_alter(){

}

But did not get how achieve this.

VIEW QUERY

SELECT field_data_field_bid_test.field_bid_test_value AS field_data_field_bid_test_field_bid_test_value, COUNT(crm_core_contact.contact_id) AS num_records
FROM
{crm_core_contact} crm_core_contact
INNER JOIN {users} users_crm_core_contact ON crm_core_contact.uid = users_crm_core_contact.uid
LEFT JOIN {field_data_field_bid_test} field_data_field_bid_test ON crm_core_contact.contact_id = field_data_field_bid_test.entity_id AND (field_data_field_bid_test.entity_type = 'crm_core_contact' AND field_data_field_bid_test.deleted = '0')
GROUP BY field_data_field_bid_test_field_bid_test_value
ORDER BY field_data_field_bid_test_field_bid_test_value ASC

Yes finally i am able to solve this one.

Using

function utility_views_query_alter(&$view, &$query) {

  if ($view->name == 'Viewname') {

    //dpm($view->query->orderby[0]);
 $view->query->orderby[0]['field'] = "CASE  field_data_field_bid_test_field_bid_test_value WHEN 'Pass' THEN 1 WHEN 'Fail' THEN 2 WHEN 'Waiting' THEN 3 ELSE 4 END";
  }
}


Setting the default front page setting to be translatable I've enabled the following multilingual modules:

Configuration Translation
Content Translation
Interface Translation
Language

Configuration translation enables me to translate the site title and slogan, but how can I translate the default front page setting to have a different front page per language?

I can see the setting in system.site.yml:

page:
  403: ''
  404: ''
  front: /node

but overriding it in language/de/system.site.yml doesn't seem to help.

Is there anyway I can activate the setting for translation?

I created a proof of concept Drupal (latest - 8.3.5) instance on simplytest.me earlier today to check if this is actually something you cannot override in language//system.site.yml. I had no problem to differentiate frontpage for default (english) language and additional language.

Just remember that front property is nested under page key.


Drag and drop no longer working on my drupal 7 site after workbench acess install When I enable the workbench access module, all drag and drop reordering is broken. It doesn't work under blocks or under the menus. This doesn't happen on my local computer.

The working bench acess module I have is 7.x-1.2 under drupal 7.28

Try selecting a newer (or older) version of jQuery using "jQuery Update"


Cannot fetch form_state['values'] of text field from dynamically created Ajax fields I have a custom form with dynamically generated fields. I am unable to fetch values from these fields using form_state['values']. Code is attached below. I have been struggling with this since two days, but have not found anything that can fix the issue. Please help!!!

function oulta_seller_create_search_agent_form_second($form, &$form_state) {

$form['#tree'] = TRUE;

$form['names_fieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('People coming to the picnic'),
  '#prefix' => '
',
  '#suffix' => '
',
);

if (empty($form_state['num_names'])) {
  $form_state['num_names'] = 1;
}
for ($i = 0; $i < $form_state['num_names']; $i++) {
  $form['names_fieldset']['name'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
);
if(!empty($form_state['values'][$i]) &&  ($form_state['values'][$i] !='')) {
drupal_set_message($form_state['values'][$i]);//<-- This statement never gets executed. Also cannot fetch the value of $form_state['values'][$i]
}

}
 $form['names_fieldset']['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('ajax_example_add_more_add_one'),
  '#ajax' => array(
  'callback' => 'ajax_example_add_more_callback',
  'wrapper' => 'names-fieldset-wrapper',
),
);
if ($form_state['num_names'] > 1) {
  $form['names_fieldset']['remove_name'] = array(
    '#type' => 'submit',
    '#value' => t('Remove one'),
    '#submit' => array('ajax_example_add_more_remove_one'),
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
  ),
);
}
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
);

return $form;
}

function ajax_example_add_more_add_one($form, &$form_state) {
 $form_state['num_names']++;
 $form_state['rebuild'] = TRUE;
}

function ajax_example_add_more_callback($form, $form_state) {
 return $form['names_fieldset'];
}

function ajax_example_add_more_remove_one($form, &$form_state) {
 if ($form_state['num_names'] > 1) {
   $form_state['num_names']--;
 }
 $form_state['rebuild'] = TRUE;
}

You have used $form_state['num_names'] instead of $form_state['values']['num_names'].

Please try to update and see.


How can I sort a view based on a date value in a multi-value paragraph reference field? I have a custom entity type that uses an entity reference revisions field that accepts multiple values. The referenced paragraphs contain a date field. I would like to sort the entities (descending) by the most recent date in a paragraph referenced from their fields. E.g.:

Entity 1

Paragraph 0

Date: 1/1/2016

Paragraph 1

Date: 1/1/2017

Paragraph 2

Date: 1/1/2018

Entity 2

Paragraph 0

Date: 2/1/2017

Paragraph 1

Date: 2/1/2018

Entity 3

Paragraph 0

Date: 3/1/2016

Paragraph 1

Date: 3/1/2017

...should sort to: Node 2, Node 1, Node 3.

Thanks!

Sounds like you need to do a relationship to the paragraph reference field on your node. Which will then open up the fields on the paragraph into views. Then you might need to turn the field aggregation on in your view and add a sort on your date field selecting the MAX value


Multi-user/role testing, best practices Am loving using Drupal 6 for creating a site with more than one user "type", with different Content Profiles, different Roles with associated Permissions, different access to nodes etc. My current site has 3 different roles - Recruiters, Candidates and a Simple Administrator (as a reduced feature subset administrator, to limit the amount of damage that a non-technical administrator can do to the site, yet still do things like edit the outgoing emails, add/remove users etc).

I was wondering... when I am testing, I am currently using multiple browsers (dev in Firefox, Testing one user type in Chrome, one in ie9) to get around the "current" session issue (you can only be logged in as one user). What techniques do people use to test on multiple roles simultaneously? Is there, for example, a Firefox plugin or something else to isolate different browser based session cookies in different tabs?

You could try the Masquerade module for Drupal.  It allows you to switch users if you have the right permissions, so you could switch mid-session to a user with a different role etc.

Another thing you could try, though non-Drupal, is multiple sessions within Firefox.  Look here, here and here to see if that could help you.


Can view file list in IMCE but can't load files I'm setting up a Drupal 7 multisite. Already have another site running with no problem on same server. I can access IMCE browser (see image below), and can upload but not insert images; clicking on image does nothing. When I hard code link to image into a text field, I get 404 'file not found' error.

Setup is standard:

/www/d7 [drupal core]

/www/multisite1 [symlink to ../d7]

/www/multisite2 [symlink to ../d7]

Within /www/d7, also standard setup:  sites/multisite1/files, etc. Everything else including Clean URLs is working correctly, and I've set all permissions per usual. I'm stumped, have tried various mod_rewrite directives and none have changed anything.  Any possibility there's some path corruption in database? Any other suggestions?

I know your question is 6 months old and you have probably solved it or found a workaround... but I had exactly the same problem and wanted to share what has worked for me, in case it could help others.

At the beginning I had a default single site and IMCE worked perfectly, a few months later I set up another site in multisite configuration, and IMCE didn't work on the second site : no upload, insert, suppress buttons in the top bar, and no possibility to view images or insert them.

In fact it was not a multisite problem, it was due to a jQuery incompatibility.

Both sites use the jQuery Update module :

for the default site, the default version is jQuery 1.7
for the second one, the default is jQuery 1.9 for the front theme (and 1.7
for the admin theme, but IMCE uses the default version).

If I tried to use 1.7 version for the second site, IMCE get to work.

So, in order to still use jQuery 1.9 or newer (needed by the front theme) and have IMCE working, you can use jQuery Migrate Plugin to resolve incompatibilities.

There is a patch for jQuery Update here, I applied it, get to jQuery Update config page, selected "Enable jQuery Migrate Plugin" (with or without the CDN), and it worked perfectly !


Content Type and Fields programmatically I make a module in Drupal 8 who create a new content type programmatically.
Module name : Annonce

In config/install I add this file:

node.type.annonce_type.yml

type: annonce_type
name: 'Ajouter une annonce'
description: 'Formulaire pour ajouter une annonce'
help: ''
new_revision: false
display_submitted: true
preview_mode: 0
status: true
langcode: fr

All is good, my new content type is create in backoffice.
But now I want to add some fields programmatically, and I don't find a core module who are doing that.

I answered pretty much the same once already I think, but I can't find that answer anymore.

You add fields and their widget and formatter configuration in the same way. By adding all the relevant config entities.

You can find almost all of them by exporting configuration into the staging folder and then search for files that contain "announce_type" in the file name. That gives you the fields, the form and view displays configurations.

Then you also need the field storages. These are shared across bundles, so they don't have the node type in them (unless you prefixes your fields with your node type/module, which is a good idea if you want to make them part of your module).

Put all those fields in config/install and you're done.


Unprocessable Entity: The following relationship fields were provided as attributes I'm trying to set the value of a taxonomy term entity reference field with a POST operation in JSON:API.
const data = {
  data: {
    type: 'node--page',
    attributes: {
      field_text: {
        value: `${values.textFieldValue}`,
        format: 'basic_html',
      },
      field_ref_term: {
        type: 'taxonomy-term--my-vocabulary',
        id: '9ca0cdc7-384c-4aa4-8ce9-d6c97fc2f44b',
      },
    },
  },
};

However, that gives me this error:

Unprocessable Entity: The following relationship fields were provided
as attributes: [ field_ref_term ]

What am I supposed to do to fix this?

As the error indicates, the entity reference has to be set in relationships, not attributes.
The documentation gives this example:
{
  "data": {
    "type": "node--article",
    "attributes": {
      "title": "Article by admin",
      "body": {
        "value": "Custom value",
        "format": "plain_text"
      }
    },
    "relationships": {
      "uid": {
        "data": {
          "type": "user--user",
          "id": "{{UUID of user 1}}"
        }
      }
    }
  }
}

In this example, the author of the node is set using the relationship of uid.  However, it wasn't immediately clear to me how to set the entity reference field.
It turns out to be quite easy:
const data = {
  data: {
    type: 'node--page',
    attributes: {
      field_text: {
        value: `${values.textFieldValue}`,
        format: 'basic_html',
      },
    },
    relationships: {
      field_ref_term: {
        data: {
          type: 'taxonomy-term--my-vocabulary',
          id: '9fa0cdc7-384c-4aa4-8ce9-d6c97fc2f44b',
        },
      },
    },
  },
};

The key for the relationship is the machine name of the entity reference field.


How can I process a node form from a custom submit handler? I have a use case where I have a custom submit button on a node edit form that will take the user off to another page to do some other editing.

If the user has made some changes to the node, such as changed the title, I need to save the current node before redirecting them off to the new page (along with some other generated ID's).

For the life of me, I cant seem to see how I can save the changes to the node in my custom submit handler.
I have tried using $formState->prepareCallback('::submitform()) but that doesn't seem to do what I expected of processing the form.

Anyone done this before or got any good ideas?

Typically, I found the answer 10 minutes after posting!

For anyone else, in your custom submit handler get the form object from the form state.

$formObj = $formState->getFormObject();

You can then call submitForm() on the form object and pass the form and form state variables.

$formObj->submitForm($form, $formState);

Then finally just simply trigger the save() function on the object.

$formObj->save($form, $formState);


Insert code from module to .tpl I'm trying to insert a code (a button) from a module to a specific place in a view (between the filters and the array).
Does anyone have an idea of how it can be done ?

Thanks

Copy sites/all/modules/views/theme/views-exposed-form.tpl.php into your theme's template folder.  Rename it to views-exposed-form--YOURVIEWMACHINENAME.tpl.php and clear caches.  You should be able to put your button after the exposed filter content.


Workaround for missing migrate-deregister command in Drush 10.3.1? I'm trying to migrate and upgrade a site from Drupal 7 to Drupal 8 (version 8.9.1). The migration cannot be accomplished with the UI, since I need to make some changes to the content types and taxonomies during the process. I followed the advice at https://www.drupal.org/docs/upgrading-drupal/upgrade-using-drush and generated individual migrations using drush migrate-upgrade --configure-only so that I could use the YAML files it generates as the basis for a custom migration module.
After I built my module, I ran drush migrate-status (alias drush ms). I can see that my migrations are registered, but the ones generated earlier by drush migrate-upgrade are also there. In the past, removing them would be a simple matter of using drush migrate-deregister (alias drush mdreg), but that command, strangely, is no longer available in the current version of Drush (10.3.1).
How do I deregister the migrations that were generated by drush migrate-upgrade --configure-only? I am assuming that if I don't deregister them, my content will be migrated twice, and I don't want that to happen.

Those migrations are stored as configuration.
When you run drush migrate-upgrade --configure-only the command created various migrate_plus.migration.* config data related to your D7 migration.
If you remove the config, you'll remove the migrations. For example:

If you have config captured in a sync directory, do a drush cex, remove all migrate_plus.migration.* yml files, then drush cim. Drush will drop all migration configuration on import.
If you'd rather delete the migration directly, drush cdel will let you specifically delete a migration.

Even if you delete the migration config, some migration metadata is still kept around in the database (see migrate_map_ & migrate_messages_ tables). They'll be re-used if you re-import migration config. If you're finally finished with your migrations, you can delete them.


How owerride entity node delete core function I'm doing a headless drupal cms.

I need to check the entities before they are deleted.
I need to do it globally as the deletion of entities can take place via api (already written) or by using the cms as an administrator.

How can I overwrite the "delete" core operation?
I've tried using hooks (hook_entity_predelete / hook_entity_delete) but they don't block delete operation.
I need something like this:

if ($condition == true)
  core_delete()
else
  disable_core_delete()

Thank you

The only way I can think to do this is to override the entity's storage handler in hook_entity_type_alter() with a storage handler that provides the delete functionality you want.

Something like

// You're going to want to be sure you're extending the entity's original
// storage handler.
class CustomStorageHandler extends EntityStorageBase {

  /*
   * {@inheritdoc}
   */
  public function delete(array $entities) {
    array_filter($entities, function ($entity) {
      // Do your logic to determine if the entity should be deleted here.
      // This example only allows entities with odd ids to be deleted.
      return (bool) $entity_id % 2;
    }
    parent::delete($entities)
  }
}

It is probably a better idea, however, to use the entity's access system to prevent users from deleting entities as it will be confusing to try to delete an entity, then for that to not happen.


Views: Show only "Grouping Field" headings I'm working on customizing a view that is displaying a content type. I need to build an attachment that shows available taxonomy terms on this content type.

In this attachment, I currently have the taxonomy term name displaying as a field for each returned instance of the content type.

Grouping the results by the taxonomy name field produces one instance of each term as an <h3> followed by one instance for each node that was returned:

TAXONOMY TERM 1 (Grouping Title, H3)
    taxonomy term 1 (term on node)
    taxonomy term 1 (term on node)
    taxonomy term 1 (term on node)
TAXONOMY TERM 2 (Grouping Title, H3)
    taxonomy term 2 (term on node)
    taxonomy term 2 (term on node)
    taxonomy term 2 (term on node)

Is there a way to just show the grouping without outputting the additional content? Something like:

TAXONOMY TERM 1 (Grouping Title, H3)
TAXONOMY TERM 2 (Grouping Title, H3)

This would produce exactly what I need but I can't figure out a good way to do this.

I've tried aggregation but this makes exposed filter inheritance for the attachment messy and unreliable.

Thank you!

Since you want to display all the terms  possible, and not only those assigned to nodes, it doesn't make sense to build it through a Node View.

You can create a new View of type Taxonomy terms, create a block displaying Taxonomy terms, then place the Block in the Content region on your Views page (or any other region).

Alternatively you could also use a module to create the block listing Taxonomy terms: Taxonomy menu and again place the Block in a region and restrict it to show only on your node View page.


Emails not being sent from Acquia dev desktop2, win7 I have a Acquia DevDesktop2 set up on my development machine (win7). I'm testing a webform submission and I'm running into an issue where I get messages that the emails are sent, but nothing reaches the inboxes. I have  I'm trying to email them to regular Gmail accounts. The vanilla install on my live site sends the emails without a problem, but I don't want to code on the live codebase.

I've seen that a lot of people have this issue, but there's no good documentation that I've stumbled across on how to set up the xmail server, or how to configure it after the fact. The acquia docs all say it comes cooked in, but I'm not sure why this doesn't work for me. Any references to how to trouble shoot this would be appreciated.

So any advice would be appreciated

Had the same problem and switched from XMail to Papercut recently:

  Papercut is a simplified SMTP server designed to only receive messages (not to send them on) with a GUI on top of it allowing you to see the messages it receives. It doesn't enforce any restrictions on addresses, it just takes the message and allows you see it.

So, turn off the XMail service and start Papercut. When a mail is sent in Drupal, Papercut acts as the (local) SMTP server and allows you to see the message.


Domain Access but isolated user and content perfectly I try domain access module for different domains. But when using user reference in contents every user sees other users. Is it possible to isolate every domain users from other domains users.

Use the References modules and enable user reference submodule.

Add a user reference field to your content. Then, in the "Views - Users that can be referenced" section of your field options select a View that filters users by current domain. You must create this view before add the field to see the view.


Get node ID that field belongs, in field.tpl.php being displayed in a block on any page I have a 'Gallery' content type that has an entity reference field, which I use to reference other nodes of the 'Gallery Item' content type. When creating a 'Gallery' I use the nodeblock module to automatically create a block with this content.

So when I place this block in any page, let's say the homepage, I have it displaying the 'Gallery' title and a body on top, and below that, each 'gallery item' using the 'rendered entity' field formatter.

What I also need, is to somehow display the node id of each 'gallery item'.

I've tried editing the entity reference field template by creating a custom field.tpl.php template for it, but I can't find a way of accessing the node ID of each corresponding item.

Please help!

Found my solution!
I was trying to access the node id from the field.tpl.php template because I wanted to add a CSS ID (using the node id) to the field outer wrapper (a div). Which was in this field template.

What I ended up doing was removing this div wrapper from the field template, and just adding the CSS id to the div wrapper in the node.tpl.php template.

Since I only needed this CSS id in certain a view mode, I created a node template for my specific view mode.


Is there any way to validate taxonomy terms? Is there any way to validate a taxonomy term before it will be saved? I'm using Simple Hierarchical Select with its "add new item" functionality. I would like to enable this option for registered users. They are not completely trusted though. What I would like to do is to create some limit on number of terms that can be added, for example per day. This is a ajax callback of SHS that creates new terms:

function shs_json_term_add($vid, $parent, $term_name) {
  if (!user_access('edit terms in ' . $vid)) {
    // Sorry, but this user may not add a term to this vocabulary.
    return FALSE;
  }

  $term = (object) array(
    'vid' => $vid,
    'parent' => $parent,
    'name' => check_plain(filter_xss($term_name)),
  );
  // Save term.
  $status = taxonomy_term_save($term);

  // Return term object or FALSE (in case of errors).
  return ($status == SAVED_NEW) ? array('tid' => $term->tid, 'name' => $term->name) : FALSE;
}

As you can see, it basically checks permissions and saves term by using taxonomy_term_save($term); . Would there be a way for validating this term without patching SHS module?

there are these lines in shs.module:

$callbacks = array(
    'shs_json_term_get_children' => array(
      'callback' => 'shs_json_term_get_children',
      'arguments' => array(
        'vid' => 'is_numeric',
        'parent' => 'is_array',
        'settings' => 'is_array',
      ),
    ),
    'shs_json_term_add' => array(
      'callback' => 'shs_json_term_add',
      'arguments' => array(
        'vid' => 'is_numeric',
        'parent' => 'is_numeric',
        'name' => 'is_string',
      ),
    ),
  );
// Let other modules add some more callbacks and alter the existing. (!)
drupal_alter('shs_json_callbacks', $callbacks);

I think we can do something like this:

function MY_MODULE_json_callbacks(&$callbacks) {
  $callbacks['shs_json_term_add']['callback'] = 'CUSTOM_CALLBACK';
}

function CUSTOM_CALLBACK($vid, $parent, $term_name) {
  if(!NEW_CONDITIONS) {
    return FALSE;
  }

  return shs_json_term_add($vid, $parent, $term_name);
}


How to have a 'Has Photo' (true or false) views filter I am looking to list a views result set based on whether it does or does not have a photo in the photo field.  I think I remember this being part of d6? d5 maybe? Regardless, I cannot find it for d7 if it exists.

If there is no such option, thoughts on how to limit a result set based on whether the field contains a photo / file or not?

Thanks

You definitely can do that in D7/V3.3. Just add a filter field that reads like: Content: IMAGE_FIELD_NAME:fid (not empty)


Set image as permanent in custom block plugin, temporary URI I'm building a custom block plugin with an image upload which is working fine except for the fact that although the $file->status is set to permanent the URI still comes up as temporary.

This is the code I'm using:

namespace Drupal\eight\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;

class MyBlock extends BlockBase {
  public function defaultConfiguration() {
    return [
      'upload_image' => '',
    ] + parent::defaultConfiguration();
  }

  public function blockForm($form, FormStateInterface $form_state) {
    $form['upload_image'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Upload Image'),
      '#default_value' => $this->configuration['upload_image'],
    ];

    return $form;
  }

  public function saveImage($fid) {
    $file = File::load( $fid );
    if ($file) {
      $file->setPermanent();
      $file->save();
    }
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $fid = $form_state->getValue('upload_image')[0];
    $this->saveImage($fid);

    $this->configuration['upload_image'] = [$fid];
  }

  public function build() {
    $config = $this->getConfiguration();
    $image = '';

    $file = File::load($config['upload_image'][0]);
    if ($file) {
      return [
        'logo' => $file->getFileUri(),
      ];
    } else {
      return [];
    }
  }
}

Inspecting the $file object before and after the saveImage method the status is actually changing from 0 to 1 but the URI I get is still pointing to the temporary file scheme.

URI: temporary://xxxxx.jpg

URL: xxxxx.xxx/system/temporary?file=xxxxx.JPG

What would be the way to correctly store the image as permanent?

To set the correct file scheme is necessary to define the upload location in the form array.

I've amended the form as follows:

public function blockForm($form, FormStateInterface $form_state) {
  $form['upload_image'] = [
    '#type' => 'managed_file',
    '#title' => $this->t('Upload Image'),
    '#default_value' => $this->configuration['upload_image'],
    '#upload_location => 'public://blocks',
    ];

  return $form;
}

The URI and URL are now as expected and the file is permanently saved.


How to get last_comment_timestamp for a node Can someone tell me what table to look for to get the node's last_comment_timestamp?

It's in the node_comment_statistics table.


How do I index custom fields with the search API using elasticsearch? I see all kinds of tutorials to get apache to index content.  Is there any difference in getting elasticsearch to index my new custom field?

On the field page I can see my field but when i expand it there is nothing to add.

Using this Create custom fields using custom Processors in Drupal 8 tutorial, but it doesn't seem to be working and no errors are being thrown so I don't know if my code is broken or this is apache specific.

You seems to have provided link for creating custom fields using processor. Processor works smoothly for me.

Create custom fields using processor.
Make sure your name spaces are done correctly.
Enable your processor from the processor tab of Elasticsearch ui in Backend.
Go to "fields" section. You will see your added field there.
Finally Index item.


drupal_get_form renders blank page I'm building a module for basic e-mail sharing that will present a form on every node. So I hook into nodes and add a new variable called share_form which is supposed to contain the from from email_share_node_form after it has been fetched with drupal_get_form.

I have been checking out loads of examples and as far as I can see I'm doing everything right. But the page turns completely blank, with no errors either in the reports or on the page. The same occurs when I use other form_ids such as user_register_form that is supposed to work.

If I add any normal string to share_form the page renders with no issues at all. So the error is definitely occuring inside drupal_get_form.

Is there obvious error in my code? How can I debug this?

UPDATE: If I put the render(drupal_get_form('email_share_node_form')) in my node.tpl.php it renders just fine. Why not in the module?

/**
 * Hook into node_load to insert an e-mail share form.
 */
function email_share_node_load($nodes, $types) {
  foreach ( $nodes as $nid => $node ) {
    $nodes[$nid]->share_form = drupal_get_form('email_share_node_form');
  }
}

// --------------------------------------------------

/**
 * Create a share-form to display on a node.
 */
function email_share_node_form($form, &$form_state) {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );

  return $form;
}

Thanks

If you have a white page then there is very likely an error somewhere. Check your apache or php error logs. Which could really be any where depend on what platform you are developing on.

Fatal errors won't make it into the database log file within Drupal since fatal errors tend to stop everything dead.


No submit button available when using Display Suite Forms to render a node add form I've created a Display Suite layout and assigned it to my content type.

Everything else is rendered just fine on the form but there's just a "small" problem: no submit button.

Do I need to use some special variables in template file to render submit button?

Current template is(nothign):

1

          <?php print $row_first_col_first; ?>

          <?php print $row_first_col_second; ?>

          <?php print $row_first_col_third; ?>

2

          <?php print $row_second_col_first; ?>

          <?php print $row_second_col_second; ?>

          <?php print $row_second_col_third; ?>

3

          <?php print $row_third_col_first; ?>

            <?php print $row_third_col_second; ?>

              <?php print $row_third_col_third; ?>

Just in time. Went through the ds form source code and found a variable drupal_render_children which holds the so far "unrendered" part of form.

So instead of using regular drupal_render_children as function and passing form etc for it you use it just as an variable.


Draggable view with sections I need a draggable view that includes draggable sections, where both sections and rows are draggable (see image for reference). The sections are not entities on their own. Ideally, the sections would map to a field attached to the entities being output in the view so that they would be available in views, theming, etc. See attached image for reference.

Is there anything in the drupal world that does this today? Looking for ideas or examples on how best to approach this requirement.

Edit Jan 7, 2013 - this is what I have so far, using entity reference, field collection , and field collection table modules, per user user5950's answer below. It's not exactly what I want, and it becomes slow as you add a lot of items (a lot slower to edit a node with 50+ items), but it is functional.

I am using the module Entity reference in conjunction with Field collection to achieve that goal. That means you

add a node with an Entity reference field, where you save the rows
(if they actually are entities in your case),
attach that Entity reference field to a Field collection.
Now you can use the delta value of the Entity reference field to sort the row and the delta value of the Field collection field to sort the sections.

Note! You can use core's node edit form as sorting interface. If you would like to have more than one sort you could do that adding a node for each sort. Draggable view becomes useless that way.

Here is an example:

If you want to have an interface, which does not allow to alter other data than the order you could replace the autocomplete field with text an remove the buttons with hook_form_alter().


View Title does not filter correctly by userid I'm very new to Drupal and trying to learn how to create a view that is filtered by userid, then by whether or not it's been published. I've created a content type of "Lists" and have a link on the home page called "My Lists." When the user clicks the link, it should open a view (and I have it set up as a page) and the title of the "page" should be "My Lists" and show each set of lists the user has. I.e., the user could have a list for their favorite movies, and another for their favorite books. Both lists should be shown UNDER the title of "My Lists" and the user would then click on which list they want to view or update.

What is happening though, is that somehow I got the Title "Booklists for " & "User" name in the title so it shows up as the main title for ALL lists instead of the correct title of "My Lists." I've gone to my Administration menu: Home » Administration » Structure » Views and under Views I have it set up as a Page. The Display name: Page - My Lists. The Title = Title: View My Lists. Now, when I scroll all the way to the bottom of the View My Lists (Content) it has a section for the Title with a little gear wheel icon that you're supposed to click on to change the Title. I've done that and the Page - My Lists: The title of this view dialog box comes up. I've changed the title in that section to "View My Lists" and set it to save for all displays. Then , it goes back to the Title and in the box showing for the title (that I just changed) it STILL shows "Booklist for Ayliea" when it SHOULD say "View My Lists."

It isn't changing the title.

Ok, i guess this is difficult to solve from here. First you should check the following settings in your view.

Display name (how your Page-View is named, for administrative purposes, will not affect the frontend)
Title (this is the name of your view at the frontend, it can be overridden with contextual filters)
Path (this is the URL of your view)
This is the Title of your menu-item.

If this is all in order, you probably have overriden your view-title with a contextual filter.

Check these settings:


What is the best slideshow to CCK image field? I would like to know your suggestions about the best slideshow module to images uploaded from CCK image field. When I mean best, I want to say quality/quantity of features supported according your experience, but if you know another criteria (like support), please feel free to give your suggestion according your criteria.

Well, there is of course this page in the drupal docs: http://drupal.org/node/418616

Unless you have a very specific use case which can be accommodated by a specialized module you really should go with the views slideshow module (http://drupal.org/project/views_slideshow). Very well maintained, fairly well documented (but a lot of tutorials flying around) and a lot of modules integrating with it. With this module you can do almost everything slideshow-wise but it might be a bit complicated (but again: lots of tutorials available).

You can of course check out some of the other modules if they offer something more matching to your specific needs.


Feeds XPath parser - setting the created date of a node I'm importing a date field in the format:

dd/mm/yyyy

I want to set this as the created date for the node I'm creating/updating.

I've tried the Feeds tamper module but the date function seem to convert between a string and a Unix timestamp, which doesn't seem to work anyway.

What's the best way to do this?

You can try to use the hook_feeds_presave in a custom module :

function mymodule_feeds_presave(FeedsSource $source, $entity, $item, $entity_id) {
  $your_import_date = explode('/', $item['your_import_date']);
  $your_import_date_formated = $your_import_date[2] . '-' . $your_import_date[1] . '-' . $your_import_date[0] . ' 00:00:00';
  $item['your_import_date'] = strtotime($your_import_date_formated);
  $entity->created = $item['your_import_date'];
}


Unable to install the Cloudinary Integration module I downloaded the Cloudinary Integration module and installed it.

The module appears in the module list, but I cannot enable it. The modules page shows this message after the description of the module.

  Requires: Cloudinary Stream Wrapper (disabled), Cloudinary SDK (disabled), Libraries (missing)

You haven't installed the dependencies.
They're listed on the module page:

Requirements

Libraries
Cloudinary SDK for PHP
Cloudinary API Account

Download each of those as well, then try again.


How to modify HTML layout inside a View template I am very new to Drupal and this is my first post in this community. What I am trying to achieve I know may be very simple but just don't know how! So I am looking forward for expert help.

First please see the screenshot:

Below is what I want to achieve:

WHITE boxes are laid out as float: left;
I want A, B and C to shift below their respective titles, i.e. at A1, B1 and C1 spots respectively.
I want to make the TITLE + A1 to be under the same container so the container can float left itself. Same with TITLE  + B1 and TITLE + C1

I copied views-view-unformatted.tpl.php file to my custom theme folder. The code snippet is rendering the data fine:

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

<?php endforeach; ?>

But I want each of the field in $row to be printed in a way I want, e.g.:

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

      <?php print $row->title ?>

      <?php print $row->body ?>

<?php endforeach; ?>

I believe there is a way to do it but don't know how. $row->title or $row->body is actually printing (rendering) nothing.

Also, if I modify views-view-unformatted-tpl.php it will affect the entire site. So I want a separate view for this purpose. How to do this?

views-view-fields--[view-name]--machine name.tpl.php

Ex: views-view-fields--hello-world--block-1.tpl.php

  <?php print $fields["field_image"]->content; ?>

     <?php print $fields["title"]->content; ?>

     <?php print $fields["body-summary"]->content; // if you r using a body summary ?>
     <?php // if you are using an actual field then use:  print $fields["field_name"]->content; ?>

CSS

.picture { float: left; }


Drush to get and print single node data in terminal? I want to do a raw dump of a single node's data with Drush, for testing purposes and just to inspect a node fast.  Similar to getting a variable with "drush vget".  Here is a PHP equivalient:

drush php-eval "print print_r(node_load(243271), 1)";

Only, I'd like it to be simplified to be like:

drush nget 243271;

Is there a command like that already?

Install this set of Drush tools to either your $HOME/.drush directory or within your project.

Drush Entity

Brief examples from the project page are:

drush entity-read node 3  |  less

#read in json format
drush entity-read node 3 --format=json

drush entity-type-read user

drush entity-type-read node --fields=label

drush entity-type-read user node --fields=label,bundles/*/label,drush/count

EDIT

For legacy Drupal6 support of viewing what a Node contains consider using Node Export via the command line and drush, possibly using the --pipe command to Linux Less command.


Create block user flag, hide users from view I have created a social site where users can flag other users as "blocked". The primary view for the site lists users along with a bit of profile2 data and a "block" flag link. Users cannot see themselves in the view.

What relationships and filter criteria do I need to add to hide blocked users from the view on a per-user basis?

Example use case: 4 users, User A blocks User C

User A's view:

User B
User C (message about how you blocked them)
User D

User B's view:

User A
User C
User D

User C's view:

User B
User D

User D's view:

User A
User B
User C

I couldn't find a way to do this within Views, despite the seemingly simple task and the various decent explanations found around the internet (nit3ch's comment included). The explanations limited the view results too much or in the wrong way.

I ended up using a Views PHP filter field to perform the filtering task:

global $user;
$flags = flag_get_user_flags('user', NULL, $row->uid);
if( array_key_exists('block', $flags) && array_key_exists($user->uid, $flags['block'])){
    //dsm($row); // optional debug
    return TRUE; // prevents row from being displayed
}


How I show theme selection page with thumbnails to everyone? I want to create a menu link for theme selection to users (also for anonymous users). I have installed the Switchtheme module but it shows only theme names; my requirements are to show the theme name with thumbnails, just like we see in "User account -> edit -> theme configuration" or with normal theme selection in admin/build/themes. So how can I do this?

Go to permissions page sitename.com/admin/user/permissions

search for switch theme and apply for roles.

Switchtheme Also provides some Blocks see Block configuration page

Thats all.


User can add field value Can anyone give me some advice/tips on how to get this working? I have a content type called "reviews", and in that i have two fields, called "pros" and "cons". Both fields have values defined in the Drupal admin interface.

In the front-end of the site, users can add new reviews and select values from the field list, until here no problem, everything work, but now i need to allow users (the registered users) to add new values to the fields (pros & cons).

Beside that, the values submitted by the users that don't exists yet in the database, must be approved by the admin before shows on the front-end.

Any suggestions for resolving this 2 questions?

Thanks in advance for your help.

I will try and provide you a general direction which I think might serve you well:

Create a text field, with label something like this "Please add tags of your choice if you dont find adequate options".(purpose is explanatory from the label)
Create a content type, "Proposed Taxonomy Terms". Let it have only title and body field.
Now on saving a node of the content type in which we had the suggestion field, grab the value of the proposed taxonomy terms from it, create a node of type "Proposed taxonomy term" and clear the value of the field in the first content type.
Now the nodes in the content type "Proposed taxonomy Term" will be your basis which you need to set up such moderation. it will initially remain unpublished. Upon validation, write custom code, to grab the title on its save and create a taxonomy term in the vocabulary(which was used as term referance field in the first content type), and delete the node (or you may choose to keep it).

So next time when user tries to create the node of the first content type, they will have it as an option. this is a complex workflow. The logic parts you can do custom code better, employing drupal hooks or you may choose to use rules module (not sure it will serve the purpose exactly though).

Hope this long answer did not confuse you.


Horizontally sliding gallery with visible neighbors? I'm looking for a way to create a horizontally sliding gallery, where the non-"highlighted" images can be seen to the left and right of the "highlighted" image, instead of a normal slideshow where there is just a transition to the next image in a static box.

Essentially, the functionality shown by Royal Slider, and also demonstrated on the WeArInteractive homepage under "Featured Works."

The only thing that I can find that's close is ImageFlow, but it's not quite the same and has some other odd functionality that I don't prefer.

The popular gallery/slider modules that I have found don't seem to have a built in way to do this, but maybe somebody has figure out a way to do it? I don't mind using views as part of the solution, as I'm assuming that will probably be a necessity.

That technique is most often referred to as a carousel.

I would recommend Owl Carousel module (or as a stand alone library depending on how custom you need it) as it is highly configurable and has support for mobile devices as well.

You can check out their (non-Drupal) demo here.