Errors displayed during core upgrade When I am updating Drupal core, and uploading files via FTP, how can I prevent mydomain.com/install.php trying to load and displaying WSOD errors like "Fatal error: require_once() [function.require]: Failed opening required..."?

I'd like to display a static page with a BRB message instead.

Just move your entire Drupal root somewhere else, and put something else in its place (with a "Be Right Back"-message) while the upgrade goes on.

For instance, if your Drupal root is /var/www/html, prepare a directory named /var/www/brb and put a static index.html-file in it with your BRB message.

Then execute the following pair of commands:

mv /var/www/html /var/www/pending_upgrade
mv /var/www/brb /var/www/html

Now, make sure that your ftp job puts the files in below /var/www/pending_upgrade.

When done, restore your site with the following pair of commands:

mv /var/www/html /var/www/brb
mv /var/www/pending_upgrade /var/www/html

The above assumes that you have CLI access.  If you don't, most ftp tools have built-in commands to move directories around.


Trouble adding conditional to page-title.html.twig I am building my first D8 theme and I am new to Twig. I am trying to add a class to the h1 title tag on the home by editing page-title.html.twig, but I can't get it to take. Here is my code

{% set body_class = '' %}
{% if title == 'Welcome to My Website' %}
    {% set body_class = 'home-page-title' %}
{% endif %}

{{ title_prefix }}
    <h1{{ title_attributes.addClass(body_class) }}>{{ title }}</h1>
{{ title_suffix }}

You're doing it wrong. The method you are using is not consistent if you change the page title to something else, or use another page as your landing page.

There are two ways to solve this:

The long way, using hook_preprocess_html()

Instead of this, I recommend targeting the <h1> tag through a body selector, and add there a special class for front page through hook_preprocess_html(). This is a cleaner solution, and you can target other elements as well.

This code would go to your YOUR_THEME.theme file:

function YOUR_THEME_preprocess_html(&$variables) {
  // Add a custom class determining if we're on the front page.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $variables['attributes']['class'][] = 'front';
  }
  else {
    $variables['attributes']['class'][] = 'not-front';
  }
}

In your html.html.twig file you need to have:

<body{{ attributes }}>

Then in your CSS file, you would use:

body.front h1.page-title {
  /* Your styles. */
}

The short way, using only twig - by 4k4

The root_path variable provided to you by template_preprocess_html() will be set to FALSE when you are on the front page. This means that you can use it as condition argument, and give different class to the body element.

Here's an example:

<body{{ attributes.addClass(root_path ? 'not-front' : 'front') }}>

Hope this helps.


Secure Drupal User Profile Information I need to secure the user profile information, which contains predefined & custom fields such as username, profile picture & phone number.

I do need to encrypt & store it in DB. And then decrypt to display output.

Do anyone know, does encryption for fields is possible?

Yes it's possible only if you do it programatically for this. You can use hook_entity_presave() and update encrypted values while saving user. And while retrieving data/fields you can decrypt with the key that you used for encryption and show in profile view page. Example:

/**
 *
 * @param array $edit
 * @param type $account
 * @param type $category
 */
function example_user_presave(&$edit, $account, $category) {
  $name = $edit['name']; // Get value of field.
  $edit['name'] = encrypt($name); // Encrypt and save.
}

/**
 * Returns encrypted string
 */
function encrypt($pure_string) {
  $encryption_key = 'SECRET';
  $encrypted_string = openssl_encrypt($pure_string, "AES-128-ECB", $encryption_key);
  return $encrypted_string;
}

/**
 * Returns decrypted original string
 */
function decrypt($encrypted_string) {
  $encryption_key = 'SECRET';
  $decrypted_string = openssl_decrypt($encrypted_string, "AES-128-ECB", $encryption_key);
  return $decrypted_string;
}


Dynamic data forms and reports from non-Drupal databases I have the task of displaying non-Drupal data which is stored in SQL Server within Drupal. I need to display search pages (ad-hoc style) and results based on page and field definitions stored in a SQL Server database. I will also need to display them based on permissions defined in the SQL Server database. This information will be a copy of the users and organic groups from the Drupal system, but will be stored in SQL Server so that they are available to other systems leveraging the same data, so in essence it can be considered a completely separate system.

I need to read the list of permissions (which will be managed down to the field level) and dynamically manage the display of fields, in both search criteria and result sets. For example, if Form1 has 10 fields and 2 of them require you to be an admin to see, there will be the following tables (structure hasn't been decided so there are just samples):

tbl_forms: form_id, form_name
tbl_fields: field_id, form_id, field_name
tbl_users: uid, username, etc
tbl_role_permissions:
 - roleperms_id
 - element_id (id of form or field)
 - element_type (form or field)
 - roles_show (an array of roles that have access to see this form or field)
 - roles_edit (an array of roles that have access to edit this form or field)

With this information, I believe it's possible to create an ad-hoc reporting system with roles level control of who can see individual fields for editing or in the data results of searches. I may need to also add a roles_search field, but I can't think of anything else.

Is there an existing approach to displaying external data dynamically within Drupal? If not, does this type of structure appear granular enough for effective creation of this type of external data management and reporting system?

Consider the Forena module, not many people know about it, which is why I wanted to mention it here.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

Note: I'm a co-maintainer of Forena.


Is there a possible/safe way to do a sub-request In Drupal 8 the Symfony HttpKernel Component offers a nice way to make an internal sub-request (forward a request to another page without changing the URL). I'm wondering if there is an ad hoc way to mimic some parts of this idea with existing Drupal 7 APIs.

I have a use case where I need to provide a central path that delivers XML, but for various reasons that XML must be fetched from embedded content on a separate path, that I don't control, but that's also delivered via the Drupal menu system. The specifics of the use case are probably beyond the scope of this specific question, so I won't elaborate too much there. Anyway, I've had some success creating a menu callback that simply calls menu_execute_active_handler() internally, and then renders the output. It gets the path to use for the sub-request via a query string. Something like:

// The XML we are looking for will be inside a sub-requested page at path
// xml-source-path and inside a <script id="xml-source-id"> block.
$query = drupal_get_query_parameters();
if (isset($query['xml-source-path']) && isset($query['xml-source-id'])) {
  $source = drupal_render_page(menu_execute_active_handler($query['xml-source-path'], FALSE));
  // Search for the XML within the raw sub-request markup.
  $matches = array();
  preg_match('/<script[^>]*id=\"' . $query['xml-source-id'] . '\"[^>]*>(.*)<\/script>/simU', $source, $matches);
  if (!empty($matches[1]) && strpos($matches[1], '<?xml') === 0) {
    $xml = $matches[1];
    // ----- Misc other processing to fetched $xml -----
    // Set headers and directly print result.
    drupal_add_http_header('Content-type', 'application/xml; charset=utf-8');
    print($xml);
  }
}

Though this works great for most of my own tests, I'm really not sure if I'm breaking any best practices here, or worse, introducing any security concerns. Since the callback itself is triggered from within a call to menu_execute_active_handler() (in index.php itself) is a recursive call like this potentially problematic? Also, would the fact that I'm accepting the path for sub-request via a query string provide any way for this menu callback to be used for malicious purposes? I really don't think so, but I'd feel much better if I could confirm, or identify a better way.

I do this as following:

// We mimic menu_execute_active_handler().
$router_item = menu_get_item($href);
if ($router_item['access']) {
  if ($router_item['include_file']) {
    require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
  }
  $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
}
else {
  // Access denied.
  $page_callback_result = MENU_ACCESS_DENIED;
}

if (is_array($page_callback_result)) {
  // Render array.
  $output .= drupal_render($page_callback_result);
}
elseif (is_string($page_callback_result)) {
  // Render string.
  $output .= $page_callback_result;
}


Print a image field without styles I do print render a image field in node. I´d like to have to original image size without any styles. But when i take a look on the image path, i see that the image was uploaded to folder "large" and gets a width of 480px. In Node display settings i have set the format to "Original". What else can i do to get the original size rendered? Thanks!

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

Output Browser:

src="http://fake.org/sites/default/files/styles/large/public/field/image/test-image.jpg?itok=FuFLPjDI"

This is not the original image, it is a derivative generated by image styles. Fortunately it is a quick change to tell the field what to use.

Simply go into the display settings for the node or entity outputting the image, and change the field formatter from the image style setting to just "Original Image". The same option exists in Views if you are outputting the field.


How to return boolean with math expression comparison in Views I want to output a boolean value like this:

if some field value (e.g. [comment_count]) > x (my constant, e.g. 5) = 1, else 0

without installing Views PHP (or other modules) or having to create a field.

I tried with the Views field "Global: math expression" but that won't support comparisons.

Is there a math expression or another simple way to do this within my view?

PS: I thought I could use floor(logX([comment_count]) but logX() seems not supported: it always returns 0. Custom base logarithm is among PHP math functions but not present in Views? :(

Easiest method is to either use hook views view pre render out a preprocess function.


How can I get a Rule to trigger a rule I need to make a set of eight rules.  Each rule will have about ten actions, nine of which will be the same for each rule (basically, these rules will duplicate a node and change one field).  I would like to create a rule (sub-rule?) that contains the nine similar actions, and then make eight other rules which call the sub rule.  Is there a way to make a rule trigger another rule?  If possible, I would like to do this directly instead of performing an action (such as saving a node) which can trigger an event.

Try creating a Rule Set Component and call it from a reaction Rule.
(https://drupal.org/node/1300024)


Does hook menu accept a wildcard as argument 0? In a custom module I have implemented hook_menu() using the following code.

function MYMODULE_menu() {
  $items = [];

  $items['%/review'] = [
    'page callback' => 'review',
    'page arguments' => [0],
    'access arguments' => ['access content'],
    'type' => MENU_CALLBACK,
  ];

  return $items;
}

Wildcard should be existing node. I am trying to access mydomain.com/product1/reviews (where product1 is node/1) and then print some related product data on reviews page.

I'm getting a 404 error. If I change $items['%/review'] to  $items['abc/%'] everything works. What can be the problem?

Note: I don't want to change node route. I want to access this path mydomain.com/product1/reviews where product1 is an existing node.

Wildcards may not be used as the first component of a route path in hook_menu. https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x

what can you do if you want this feature, the solution is kind of tricky solution like

function MYMODULE_menu() {
  $items = [];
 $myItems =  // load what do you have
foreach($myItems as $myItem){
  $items[$myItem.'/review'] = [
    'page callback' => 'review',
    'page arguments' => [0],
    'access arguments' => ['access content'],
    'type' => MENU_CALLBACK,
  ];
}

  return $items;
}


Limit/nullify entity reference query/loading of select options, if using hook form alter to populate with ajax I have added an entity reference field to a profile2 profile entity. The entity type referenced by this field will contain thousands of results (university courses). I have used hook_form_alter to add an ajax callback to the university field which is selected before the course field. Selecting the university first, then populates the course field (which is disabled initially) with the courses available only at the selected university. Since I do not want my courses entity reference field loading thousands of courses on load, I need to nullify the query or hook into the function that populates this field. I have seen entity reference limit module but don't intend to use it.
How can I achieve this? Thanks

I have managed to achieve this using hook_entity_query_alter. I am not sure if this is the best approach.
You can set the limit using the $query->range($start, $length).
Return 1 row.. $query->range(0,1);
See https://api.drupal.org/api/drupal/includes%21entity.inc/function/EntityF...

<?php
/**
 * We don't want to load thousands of courses into the student course entityreference field as
 * we populate it with ajax, so add LIMIT 0 and database should return empty result set
 */
function mymodule_entity_query_alter(&$query) {
  // check if we got our field
  if(property_exists($query, 'metaData') && $query->metaData['field']['field_name'] == 'field_student_course') {
    $query->range(0,0);
  }
}
?>


One content type two different node--MYCONTENTTYPE.tpl.php for content style I've got one content type, in the teaser I've limited the chars lenght for title and body through a script in the file .tpl.php

<?php $limited_title = (substr($title,0,60));
    print $limited_title."..."; ?></h2>

For the same content type I've got two views, both in "content" mode with a different filter criteria.
What I wanna do is to have one view showing 60 chars of the title and the other view showing 100 chars of the title. Is it possible to create two different node.tpl.php like we do with the view giving the name of the page? like node--mycontentType--page-1.tpl.php.

if it's not, what the best way to get the result I want?

No javascript please.

Thanks in advance.

I think the best way is to change this by clicking the title field in the views page and using the "Trim this field to a maximum length" option under "Rewrite results". You can set it to 60 for the first view and 100 for the other.


How to set field permission with time limit I want to set up a customer´s private recording system, where the customer can record his private issues. This record cannot be changed after one hour. The record includes time,episode and my comments. I used "field collection" module to set up the record first, then use "edit limit" module to limit the edit time-everything works fine but I found after one hour, though the customer cannot use the "edit" tab for the whole node, he can still click a "edit" link below each field (time, episode, etc.). Is there anyway to disable the "edit" link for each field after one hour as well?

You can hide at all links to separately edit/delete field collections values, go to Structure » Content types » YOUR_CONTENT_TYPE » Manage display, click to field collection settings cogwheel and clear fields.

Also you have to forbid an access to edit/delete by direct link, place in your custom module:

/**
 * Implements hook_menu_alter().
 */
function yourmodule_menu_alter(&$items) {
  $path = 'field-collection/' . strtr('your_field_name', array('_' => '-'));
  $items[$path . '/%/edit']['access callback'] = FALSE;
  $items[$path . '/%/delete']['access callback'] = FALSE;
  $items[$path . '/add/*/*']['access callback'] = FALSE;
}

Don't forget to clear cache.


How to add Structured data to a site? I am trying to find a lot on Google how to add Structured data to site and from all the tutorials I got an impression that there is RDF module in core which was supposed to do that work like providing structured data to search engines (Google).

That module is in core and already installed on site, still Google Search Console saying,

  We do not detect any structured data on your site.

Am I missing something? If RDF does not provide structured data to search engines, what is the right method to add structured data to a site? Please, correct me if I am wrong about RDF.

If you enable the RDF module, Drupal will automatically output some RDFa for your content. You can use a RDFa parser to extract it, e.g., http://linter.structured-data.org/. If it doesn’t find any data (under "Raw structured data extracted from the page"), you are likely using a theme that doesn’t support it. Use a default/core theme for testing, you should see it then.

If you want to provide additional structured data for your content types and field content, you need to map the content types to suitable RDF types, and the fields to suitable RDF properties. If you care about SEO, you’ll likely want to use the types and properties from Schema.org, as the big search engines sponsor this vocabulary, and use it for things like rich search results.

One way to add these mappings is using the RDF UI module (which comes integrated with Schema.org).


Permissions for seeing translated custom menu link items I have a problem with custom menu link translations.

Only users with permissions to 'Translate custom menu link' (translate menu_link_content) are able to see the translated strings.

For example if I log in as admin, I can see the link texts changing when switching languages.
But when I switch languages as an anonymous user the link texts fall back to the default language. Translated routes are working correctly.

As a workaround I could just give all users the 'translate menu_link_content' -permission but that seems like a possible security flaw.

Is this a bug or am I doing something wrong here?

Make sure your menu link translations are actually published, there's a checkbox in the edit form. I think there are some bugs there that this isn't set properly when doing it from a node edit form.


Is it possible to make path to /%? My question: Is it possible to make path to /% ?

I have path that goes categories/% and that works when I type categories/hats it returns me category hat with all product it's taged with.

I would like to be able to type url/hats and to have above explained functionality.

Is this possible and what do i change in view it is not possible to make path just /% ?

You can do that quite easily with the Views module and contextual filters.

The one thing that I don't suggest doing is using Taxonomy.  I don't like using taxonomy because besides it being a non-indexed list of vocabulary, it allows for too much variance.  For instance in taxonomy:

"hat" != "Hat" != "hAt"

So, if you tagged one page as "hat" and the other "Hat", you would have to search for both term to get the content to display.

It much better to use the existing functionality of Content Types to create your "taxonomy."  Coupled with Views, Entity Reference, and Path Auto, you can do exactly what you are looking to do with a minimum of additional modules and "no taxonomy."

I would definitely suggest taking a look at the Relativity Data Model put out by Jay Epstien.

The Florida Drupal Camp website was redesigned with this model.  The most important thing to notice is the speed at which things load.

I have also been using it quite extensively and can tell you that excluding content, my site is less than 5K in size; that's about the size of an iPhone app.  This is accomplished mostly due to the fact I am running less than 20 modules total.


How can I compare data comparison with values submitted in a webform? I am trying to use webforms with the Rules module.

How can I compare data with the values submitted in a webform ?

For example, if the webform has a yes/no radio button, how can check the submitted value is yes?

When adding a new condition, I choose:

Data Comparison
Data selector *
Data (the submitted webform value)

I'm not sure how to access a particular form_key to check its value. I feel like Data should have more options to choose from.

At a minimum, make sure you have the Webform Rules module enabled. Some details about it (from its project page):

  This module adds rules integration on webforms.

  Did you ever want to react on webform submission using rules but couldn't find the proper event?

  Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

You may also want to have a look at feature request "Expose submission data to rules". Here is a summary of it:

  Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

Issue status is "Needs work" ... not an "easy" issue.

Time for a work around ...

The very same issue contains a comment with a workaround (it's genious I think, because it's so simple), here is a relevant quote from it:

  You can initialize a rules string variable with the tokens. If you need integers or booleans you can subsequently convert it to whatever and then use it to load nodes or whatever.

A picture is worth more then 1000 words, checkout the screenprint included in that comment.

... and a demo

Consider this rule (in Rules export format):

{ "rules_validate_a_component_of_a_submitted_webform" : {
    "LABEL" : "Validate a component of a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled \u0022[data:contact_us_subject-title]\u0022 which has value \u0022[data:contact_us_subject-value]\u0022 and another field \u0022[data:contact_us_message-title]\u0022 which has value \u0022[data:contact_us_message-value-raw]\u0022." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:contact_us_message-value-raw]" },
          "PROVIDE" : { "variable_added" : { "submitted_form_component_value" : "Submitted form component value" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "text_matches" : { "text" : [ "submitted-form-component-value" ], "match" : "mail.ru" } },
            "DO" : [
              { "drupal_message" : {
                  "message" : "Stop and listen! ... One of the form components of the form you just submitted (= \u0022[submitted-form-component-value:value]\u0022), contains some value that is not allowed around here ...",
                  "type" : "error"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

Some details about the above rule:

Rules Event: After a webform has been submitted
Rules Conditions: User does NOT have role "authenticated" (i.e: an anonymous user submitted the form).
Rules Actions:

Show an informal message on the site (this is just for QA-purposes, omit this action after you're convinced it works).
Add a variable (this is the clue of it all ...), named submitted_form_component_value and with label "Submitted form component value", and with value [data:contact_us_message-value-raw] (the form component we want to validate in subsequent Rules Actions).
Use the Conditional Rules module to perform some text comparison. In this case it checks if it contains mail.ru. If so, then perform another Rules Action like "Show an error message on the site". Obviously, at this point you could make any Rules magic happen ("block IP address" seems appropriate).

Be aware: as per the Rules Event we used here, the Webform has been submitted (and so far I've not found a more appropriate event like "Before submitting a Webform").

Showtime

With the above rule enabled, I submitted a webform. This is the message I got (as per the first Rules Action):

  The webform component submitted by Pierre (= First name:) Vriens (= Last name:) contains a field labeled "Subject:" which has value " This is a demo of a validation of a webform component using Rules ... " and another field "Message:" which has value "Bonjour! Guess what happens AFTER I submit a webform with a form component containing a string like mail.ru ? The bets are open ...".

And sure enough, this is the error message that follows it right away (as per the last Rules Action):

  Stop and listen! ... One of the form components of the form you just submitted (= "Bonjour! Guess what happens AFTER I submit a webform with a form component containing a string like mail.ru ? The bets are open ..."), contains some value that is not allowed around here ...

PS: In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".


Creating a View with Distinct Results I've created a view called 'Browse'. I've set the 'Query Settings' to show only DISTINCT (but it doesn't work).

Background:
I have a 'Resource' content type with a field list field called 'type'. Types may include 'blog', 'book', 'web article', etc. (there are only 8 types). I have about 80 resources in this content type, each with a 'type'.

When I create my view with DISTINCT set and content type=resource and 'type' as the only field it displays about 15 instances of each type, so it ends up looking something like this:

Blog
Blog
Blog
...
Book
Book
Book
Book
...
Web Article
Web Article
etc.

I only want each 'type' to display once and link to the views I've already setup that show all the resource content types with that particular type set (ie. if a user clicks 'blog', which should only appear once, it takes them to a page view listing all the blogs in the db.

Does anyone know how to ensure my View shows only distinct values for items in this field_list?

It does not work because the rows are all unique to start of with. Switch on SQL preview in views settings, and you will see that it adds the node's nid to the result in the SQL. Now add nid to the fields, and you will see something like

Book, nid:5
Book, nid:7

Book, nid:5 is not equal to Book, nid:7. For distinct to work, whole rows need to be equal.

What you need is aggregation.

To do that, switch on aggregation for the view in the advanced pane. Then set aggregation to COUNT on the nid.

Now your result will look something like this:

Blog, nid:6 // ie 6 rows with field value blog
Book, nid:2 // ie 2 rows with field value book

Then, finally, to get the output you want, just hide the nid from the views display.

In essence, what you have done is to group by the field 'type', and to count how many nids (rows) there are in each group. And then hide the count as you don't need to display it.


How to use relations in Views to get Content type fileds when I use Taxonomy Good day. I have Content type with Taxonomy field. Right now I try to build Views by this Taxonomy vocabulary. And I want to use (how?) relations to get access to Content type fields. So, idea is to have View by Taxonomy, but use fields of content type, which has this taxonomy as field.

Is this similar to what you want to do?
https://www.drupalgardens.com/documentation/taxonomy/views


Placing header element inside list element I am using the Group: Combine fields filter (grouped) in Views and I want to separate my first few list items from the last two with a header before the last two. Is it possible without theme functions, like with some field in Views I do not know about?

Found these similar, but they use theme functions.

Add additional element to exposed view form?
https://www.drupal.org/node/893392

Not that I know of without a theme function or a view display template.  However one option without any code would be to create two separate blocks views.

The first view, limit the displayed items to whatever your want, three for example. Clone the first view, but set the offset to three, and also limit it.  Add the header to this view. Then plunk them down as you normally would with view blocks.

EDIT:  What it would like like to add a new template file.

As an example, if you are using the unformatted list output, you would need to find the theme suggestion for that particular view.  Example below.

Then as you can see it is currently using views-view-unformatted.tpl.php

So use that file as a base, it is located in:sites/<all|default|siteurl>/modules/views/theme/views-view-unformatted.tpl.php

It currently contains this code below

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

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

<?php endforeach; ?>

So you need to copy this file into your theme templates folder, rename it, and edit it.

You're going to want to create a count variable, and then when the count reaches the right number, print the title you want like so

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

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

  <?php $count++; ?>
<?php endforeach; ?>

That will print a H1 header after the third row.


Hit count/ number of page visits in D7 How to implement a hit counter for all 'Article' type nodes? I want to display number of times (could be unique) a node was visited - perhaps within the teaser and at the bottom of the node.

In Drupal, you already have that module. You just need to activate Statistic module and set the rights permissions to anonymous users. And maybe you might modify your node.tpl.php to show count information.

Also, this module provides you blocks that show the most viewed nodes in the day, all the time or right now.


Change menu item class attribute How can one change drupal's default CSS classes? They are set in drupal's core and I don't find if there is any hook to change the #attribute entry of a menu item.

CSS classes are already set before the theme_menu_link hook call, the classes of defined in menu.inc. Is there a hook to alter these values ?

If it's just menu links you're after you can give Menu Attributes a whirl.


I want to change language in a select list and whole site changes to selected language(All content) I want to have four languages Catalan, Spanish , French and English. English language will be default.If i change language to be spanish,i want the whole site to change to spanish or if i change to french the whole site should changed to french.

Example site. I want to know how this would have been done ?

Any help really appreciated :)

I don't believe you need Internationalization module, core's Locale module will already do the job. It makes content translatable, so yes you need to translate it manually. When you enable Locale and edit a node, the option to enter a translation will appear.


How to write test(s) with specific config to test custom access checks? I have built a custom module that alters some of the User routes (view, edit, delete) to do 3 things:

Forbid account editing, except a user who has 'administer users' permission
Forbid account deleting, except a user who has 'administer users' permission
Forbid account page viewing (/user/{user}) unless that account being viewed has a specific role AND has a boolean field value of TRUE

The accounts are synced from a remote source and logins provisioned by SSO, so, there is no point for anyone to access edit/delete except an admin/dev checking if accounts look correct.

The first two seem straightforward enough as it requires nothing but setting up some test users with different role permissions and checking the response from an edit or delete route.

For the third, what is the best way to provide simple configuration to get the field added to the User entity under test? Do I install my entire project config (seems heavy)? Is there a way I can selectively install some config for test only? I think I would just need one or two of the 800 config files to be installed. I checked some of the core tests, but couldn't quite locate one close to what I am asking.

Wound up figuring this out I suppose, although I have no idea if this is the proper way.

Under the custom module I wanted to test, I created a 'tests' directory with a test module and within that new module placed 3 configuration files from my project config ("Show Profile" field storage, "Show Profile" field instance, user form display configuration).

In a functional test, I required that module:

<?php

namespace Drupal\Tests\mymodule\Functional;

use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\Role;

/**
 * Class ProfileAccessTest
 * @package Drupal\Tests\mymodule\Functional
 */
class ProfileAccessTest extends BrowserTestBase {

  /**
   * A set of test users.
   */
  protected $user1, $user2, $user3, $user4;

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['node', 'user', 'mymodule', 'system', 'mymodule_test'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $anon_role = Role::load(Role::ANONYMOUS_ID);
    $this->grantPermissions($anon_role, ['access user profiles']);

    $this->user1 = $this->drupalCreateUser(['access content', 'access user profiles'], 'regular_user');
    $this->user2 = $this->drupalCreateUser(['administer users'], 'john', TRUE);
    $this->user3 = $this->drupalCreateUser([], 'zzz', FALSE);
    $this->user4 = $this->drupalCreateUser([], 'yyy', FALSE);
  }

  public function testProfileAccess() {
    // The average user should not be able to do anything to their own account.
    $this->drupalLogin($this->user1);
    $this->drupalGet('/user/' . $this->user1->id());
    $this->assertResponse(403);
    $this->drupalGet('/user/' . $this->user1->id() . '/edit');
    $this->assertResponse(403);
    $this->drupalGet('/user/' . $this->user1->id() . '/cancel');
    $this->assertResponse(403);

    $this->drupalLogin($this->user2);
    $this->drupalGet('user/' . $this->user3->id() . '/edit');
    $edit['edit-field-show-profile-value'] = 1;
    $this->drupalPostForm("user/" . $this->user3->id() . "/edit", $edit, t('Save'));

    $this->drupalGet('user/' . $this->user4->id() . '/edit');
    $edit['edit-field-show-profile-value'] = 0;
    $this->drupalPostForm("user/" . $this->user4->id() . "/edit", $edit, t('Save'));

    // Any user should be able to view an account with SHOW PROFILE true.
    $this->drupalLogin($this->user1);
    $this->drupalGet('/user/' . $this->user3->id());
    $this->assertResponse(200);

    // But not if SHOW PROFILE is false.
    $this->drupalGet('/user/' . $this->user4->id());
    $this->assertResponse(403);
  }
}

The tests all pass, which is good.


Taxonomy page view template override I have two custom page views, one showing content, and a second one showing taxonomy term. The first one's template override suggestion as expected is    views-view--{viewname}.html.twig, I do not get the same override functionality for the second view though. Am I missing something here or is it just the way it is?

I have also noticed that the template suggestions for views is sometimes gone, but as drupal.org writes you can just name your templates like this.

For example, if you have a view called foobar, then you shall call your template views-view--foobar.html.twig.

For more information, see Views template files.


different sort criteria depending on term ID I'm using views for my taxonomy term page. I want to sort the nodes in some categories by title, while nodes in other categories by weight. I've been poking around the views UI but I can't figure it out. I was thinking that I probably should implement some hook or create a custom query but I don't know where to start. How do I achieve this?

I accomplished what I wanted to do by using hook_views_pre_build() and hook_views_query_alter()

 /* Remove sorting by weight if viewing a category that should be alphabetized.*/
 function commerce_customizations_views_pre_build(&$view) {
   $alphabetize = array('3','58');

   if($view->name == 'taxonomy_term' && $view->current_display == 'page'
   && in_array($view->args[0], $alphabetize)) {
    unset($view->sort['weight']);
   }
 }

 /* Sort by title if viewing a category that should be alphabetized.*/
 function commerce_customizations_views_query_alter(&$view, &$query) {
   $alphabetize = array('3','58');

   if($view->name == 'taxonomy_term' && $view->current_display == 'page'
      && in_array($view->args[0], $alphabetize)) {
        $query->add_orderby('node','title','ASC');
   }
 }


How to create a view that list all child nodes of current page? I have a content type "A" that has an entity reference field to content type "B".

I need to create a view that will be embed on "A" node page for listing all "B" nodes referenced to it.

I know I have to use contextual filters for getting the current node id and a relationship, but not sure exactly the recipe.

Create a view of content type B. (View Type Block)
Create a relationship in that view to the content that contains the reference field by clicking on add a relationship, and search for the name of your reference field)
Create a contextual filter to filter by ID using that reference field. Choose "Provide default value" then "Content ID from URL".
Display your block on the appropriate pages.


Create update table of features vs plans I am looking for a way to achieve this with minimum custom module work.

Imagine a table with features listed down the left, and the plan names are going across the top as headings. Where these columns and rows meet is an icon to say whether this plan has that specific feature.

The ability to add new features needs to be possible easily through Drupal.

I was thinking of creating a plan content type and then the feature could be a field collection with a boolean, and some other data (a booleon on its own is not sufficient).

The issue with this is that you can't reuse field collections, so that would mean creating a field collection for each feature, not very user friendly and too much work for the end-user when they have to add a booleon, and a couple of other fields, also the template file would need to be modified to allow for this new field.

My next thought was to set the field collection as unlimited and then have the features as taxonomy terms, to then use hook_form_alter to first pull in the taxonomy terms and then pre-populate a term reference field for each instance of the field collection.

However this gets a little complicated when you think about a scenario in which someone adds a new feature as a taxonomy term. The custom module would need to look at the fields on the node in the field collections and check to see if the term exists already.

Maybe this would work, but is there a better way?

You might want to give a try to Editable Views module. So you would create a view page with columns and rows as you desire, making all the fields editable. Then you could change any field value (boolean if checkbox is used) just in place.


How to add the Organic Group list in the user profile Is there a way to add the Organic Group list in the user profile

The OG List appear in the Registration Form but not in the user profile

Not appear in this path
/user/[uid]

This question is slightly vague, however, I am going to answer in the two methods that I take away from it.

You want a list of all OG groups on a user page: Create a View for all of the different content you have related to groups (i.e. you have a content type called "Groups" that is an Organic Group).
You want a list of all OG groups that a user is a member of: Create a View (with a contextual link and/or relationship) between the UID in the current URL and get their appropriate group memberships.

You can create either of these Views as a block and place that on the /user page.


Create different user profiles with drupal 7 There are two user profiles, landlord and tenant. Both require different user role as well as different registration data.

Now tenant can search through landord's profiles and comment / rate on them as well.

How can I achieve this in drupal 7

I don't know if you are still interested or not. I've got the same problem and I solved in this way:

In the User account you can put an option "Tenant" - "Landlord".
Then use the Rules module to create a rule that gives automatically the role dependent on the option chosen.

Or you can also redirect straight to the edit profile after the registration.


Override name of file field link in Drupal field.tpl template I have a file download field in a node. The field displays as a simple link with the name of the file that will be downloaded, eg:

picture.png

What I want to do is rename the name on the link, i.e. I want it to stay the same but say:

Download the picture,

instead.

I have created a field--resource.tpl template, I don't know how to get started to get the name that is displayed overridden.

Here is what is in my field--field-source--resources.tpl file:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>

Thanks!

There is an easier way to approach this without having to go through the template file:

On the 'edit' page for your content type, you can set it to 'enable description field'

which will add a new field to your content form that will let you override the label for the file, ex:

This should be easier than trying to parse the template approach and will work seamlessly with other modules that interact with the file field.


Override user registration form I'm looking for a OOP way to have a simplified User registration form in Drupal 8.

As of today, the default User registration form is declared directly as an annotation in the User class. From the administration pages, it is possible to add a Register form display for the user form. However, when removing all possible fields save for the password/login, there is still a bunch of fields showing up that I want removed:

Username
Password confirmation
Locales settings
Contact settings
etc.

What I want is an extremely simple registration form, with just two fields: e-mail address and password. All other fields will be editable later. I want this form to use OOP if possible, so extending the class Drupal\user\RegisterForm seems to me a good way to achieve this...

I extended the form but can't use it. It requires an entity to be passed to it apparently, but I don't know how to do that.

The ideal way to do it would be:

$entity = \Drupal::entityTypeManager()
  ->getStorage('user')
  ->create([])
;
$formObject = \Drupal::entityTypeManager()
  ->getFormObject('user', 'register')
  ->setEntity($entity)
;
$registerForm = \Drupal::formBuilder()->getForm($formObject);

However this will insist on fetching the original, non-inherited RegisterForm class, not my custom one. How can I tell Drupal to instanciate my own form instead?

BTW how can I make username optional?

I've seen a few solutions out there for redefining the user registration form, however most of them are Drupal 7 solutions and none of them are OOP.

If you want to use the extended register form class, you need to put it in the place of the original form class in the user entity type:

mymodule.module

  /**
   * Implements hook_entity_type_alter().
   */
  function mymodule_entity_type_alter(array &$entity_types) {
    $entity_types['user']->setFormClass('register', 'Drupal\mymodule\MyRegisterForm');
  }


Remove case sensitivity from username when logging in When I try to login, my usernames are treated as case sensitive. As in if username is john and I try entering John, it is not accepted.

Is it possible if I could make all the characters lower case before they could be submitted?

Thanks

Using hook_user_insert, you can convert every letter of username to lower case once a user is being created. Then when a user is submitting the login form, you can convert its username field to lower case. So from now on all of the usernames will be in lower case it is no longer case sensitive


How to determine the modules enabled on a third party website? When I don't have the admin access to a site, how can I find out the modules that are enabled on the site.

For example : How can I identify various modules enabled on www.drupal.org

There are various you can find this out. But none of them are foolproof and they are just dirty tricks at best.

You can check source(view source) of the website and do the following.

Check the css includes in the head tag and figure out the modules from path.
Check the javascript includes in the head tag and figure out the modules from the path.
Check the classes of html tags from the body tag.
Do the above for multiple standard pages and you should be able to make a list of at-least 50% of the websites based on your knowledge of the modules.

But the easiest of them all is using the http://www.drupalxray.com/ website. Looks like they have automated many rules like the above and search enough paths to prepare a pretty exhaustive list of modules used on a website.


How do I install modules using a module? I wanted to install few modules when my module is installed. How can this be achieved?

I am creating a module which requires few other modules to be installed. I want to install them when my main module is installed.

I have placed all those module folders inside one main folder, and I want to create an install file to install those modules when this main install file is executed.

If there are modules from which your module depends, your module should declare them as dependencies, in its .info file. Supposing that your module is my_secret_module.module, and it depends from first_module, and second_module, my_secret_module.info should contain the following lines.

// Drupal 5
dependencies = first_module second_module

// Drupal 6, Drupal 7, and next releases
dependencies[] = first_module
dependencies[] = second_module

In this way, your module cannot be enabled of the other modules are not enabled too.


Add HTML to Page Title for Entity (Profile2) I have a Profile2 page where I want to add some HTML into the page title (I want to insert a fontawesome icon). I am using Display Suite to layout the Profile2 page with a custom view mode.

I have succeeded in over-writing the title using the function hook_profile2_view_alter() and drupal_set_title(), but drupal_set_title() uses check_plain, which strips out all the extra html. I tried using hook_preprocess_page, but there is no title variable available. I think this is because Display Suite takes over the title variable, and renames it as label. I also tried the html_title module without any luck, as I'm pretty sure this is because it only works on nodes and not on entities. I also tried hook_preprocesss_profile2 (having first used mymodule_preprocess_entity(&$variables, $hook) to create the function suggestion), but this function doesn't seem to be running on the page. I'm not sure if this is because I'm using display suite or a custom view mode.

Any help much appreciated, as I seem to be running out of options.

I solved this by adding the HTML to a custom page template based on the user role and profile. I used the following code to create the template suggestion in the template.php file:

function MYTHEME_preprocess_page(&$variables) {
  global $user;
    if(arg(0) == 'profile-carer' && in_array('my custom role', $user->roles)) :
      $variables['theme_hook_suggestion'] = 'page__profile_carer_my_custom_role';
    endif;
}

I was then able to use the custom template page--profile-carer-my-custom-role.tpl.php based on the page.tpl.php


How to prevent the addition of HTML in "Full HTML" text format? Sometimes, Drupal has the annoying habit to automatically add HTML to the content's source, generally <br/> and <p>, even when the text format is set to "Full HTML".

This is really annoying and I can't find any way to prevent that.  Any idea ?

Ok, I think I've found the answer:

This is a "feature" of the Full HTML mode.

  Full HTML:

  Web page addresses and e-mail addresses turn into links automatically.
  Lines and paragraphs are automatically recognized. The  line break,  paragraph and  close paragraph tags are inserted
  automatically. If paragraphs are not recognized simply add a couple
  blank lines.

You can disable it in You are here Administration » Configuration » Content authoring » Text formats by unchecking Convert line breaks into HTML (i.e. <br> and <p>).

Source: http://drupal.org/node/503754


How to tell if a view gets cached? I assume that as soon as you add a contextual filter, that is not a fixed value, the View becomes uncachable since it becomes dynamic, right?

Is there a clear cut way to tell if the View gets cached or not?

I assume that as soon as you add a contextual filter, that is not a fixed value, the View becomes uncachable since it becomes dynamic, right?

No.

That just means that the view's output varies based on the URL. Specifically, a query argument.

This is why we in Drupal 8 have the concept of cache contexts: https://www.drupal.org/developing/api/8/cache/contexts.

For the Views module to efficiently determine whether a view can have a cached version or not, we need to know ahead of time which contexts a particular view display varies by. So, upon saving a modified view, the Views module iterates over all plugins that a particular view display uses and gathers its cacheability metadata. It then stores it in the view config entity.

Concrete example: the "Taxonomy Term" view that ships with Drupal 8 core. It has a path of /taxonomy/term/%, with that % being a particular taxonomy term ID. Open core/modules/taxonomy/config/optional/views.view.taxonomy_term.yml and scroll all the way to the bottom. You'll see this:

page_1:
    id: page_1
    display_title: Page
    display_plugin: page
    position: 1
    display_options:
      query:
        type: views_query
        options: {  }
      path: taxonomy/term/%
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_interface'
        - url
        - 'user.node_grants:view'
        - user.permissions
      max-age: -1
      tags: {  }

Note the presence of the url cache context. That describes that this view varies by URL, in particular by the value for the % wildcard in the /taxonomy/term/% URL.


Datepicker not appearing when an url alias is added I've implemented a datepicker in a textfield on a basic page from Drupal. It works fine and the url shown is "http://....../drupal7/node/28".

If I add an url alias to the url, the datepicker doesn't appear. It only reappears if I remove the url alias.

Anyone know how to show the datepicker with an url alias?

The files used are:

jquery-1.10.2

jquery-ui.js

jquery-ui.css

I have date_popup module under date enabled and any form field with date_popup type displays date picker for me:

$form['my_date'] = array(
      '#type' => 'date_popup',
      '#date_format' => 'Y-m-d',
      '#title' => t( 'My Date' ),
  );

It seems to work for me regardless of which url it is used on.


How can I programmatically set date field Month, Day, Year dropdowns in Paragraphs? I'm setting a basic date field (and several other text fields) programmatically when creating a paragraph. The database is showing that it is getting my date, which is being stored inY-m-d\TH:i:s format. All the other data is being saved as well. No errors.

However, when I edit the node my paragraph is attached to, all the data is there except for the date field. It's not set despite the data being in the database.

The date field is set to show MDY in dropdowns like so:

I've tried this: $date = new DateTime('2015-06-01 23:45:52', new \DateTimeZone('UTC')); This does get the date saved into the database, however, the dropdowns are not set.

So then I tried converting it to MDY: $date->format('M-D-Y') but no such luck. This doesn't work at all.

I have also seen that you have to reference the actual stored format using $date->format(DATETIME_DATETIME_STORAGE_FORMAT) but there doesn't seem to be other parameters for that to get it into the format that I need.

Is there some way I need to individually set the actual dropdown options in code?

Full paragraph code below. Almost all of these examples save data in the DB correctly, the date dropdowns do not reference it though.

use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\file\Entity\File;
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;
use Drupal\datetime\Plugin\Field\FieldFormatter\DateTimeCustomFormatter;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Drupal\datetime_range\DateTimeRangeTrait;

  $date = new DateTime('2015-06-01 23:45:52', new \DateTimeZone('UTC'));
  //$date = $date->format('Y-m-d\TH:i:s');
  // if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
  //   $currentDate->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
  //   $db_friendly_value = $currentDate->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
  // }

  //$date->setTimezone(new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
  //$date = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
  // $date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));

      $program_1 = Paragraph::create([
        'type' => 'programs',
        'field_program_name' => 'Program Name',
        'field_program_description' => 'Description',
        'field_program_year' => [
          'value' => $date,
        ],
      ]);
      $program_1->save();

Am I missing something somewhere? I've been hunting for the correct way to do this for a few days and have tried a number of different ways. I could probably get around this by just changing the field to be a text (date/time) date field instead of dropdowns.

I tried the suggestion here, but this doesn't seem to work either: Adding content to Paragraph Date Field Drupal 8

Any ideas here?

After trying just about every solution for the date I could find, I finally figured this out.

It seems that it doesn't even matter what the DB is wanting to save the date as. Looking in the DB, the date is being stored as Y-m-d without the trailing H:i:s. Most examples are saying that you need the full date in Y-m-d\TH:i:s format.

This particular dropdown widget for the date field wants only Y-m-d and I only found that out after trying to pass it all kinds of different date strings and it gave me an error message back about the format without the trailing H:i:s.

So all of that garbage that I tried to pass it earlier and formatting was way off. All I needed to do was this, and the paragraph saved properly and the form fields are reflecting the proper date now.

'field_program_year' => date('Y-m-d', strtotime('2011-11-12')),
'field_eligibility_range' => [
  'value'=> date('Y-m-d', strtotime('2011-11-12')),
  'end_value' => date('Y-m-d', strtotime('2011-11-12'))
],


What's wrong with my GET request? (Commerce Services, REST) I'm developing a mobile app to connect with my Drupal Commerce (Kickstart) store, using a REST server.

When I do GET: endpoint/rest/product it retrieves the products list

<result is_array="true">
    <item>
        <revision_id>1</revision_id>
        <sku>TOT1-GRN-OS</sku>
        <title>Tote Bag 1</title>
        <revision_uid>1</revision_uid>
        <status>1</status>
        <log />
        <revision_timestamp>1423972403</revision_timestamp>
        <data />
        <product_id>1</product_id>
        <type>bags_cases</type>
        <language>und</language>
        <uid>1</uid>
        <created>1423972403</created>
        <changed>1423972403</changed>
        <title_field>Tote Bag 1</title_field>
        <commerce_price>
            <amount>1600</amount>
            <currency_code>EUR</currency_code>
            <data>                <components />
                </data>
        </commerce_price>
        ...
    </item>
    <item>
     ...
    </item>

Everything looks fine. I can even GET endpoint/rest/product?status=1 and it does filter well.

I'm trying to filter by commerce_price.amount:

GET endpoint/rest/product?commerce_price.amount=1600

but it's not working. I have no problems filtering by a first level key, but can't access second level ones and so on. What am I doing wrong?

From what I understand, querying only works on entity properties. That is why status works, commerce_price is a field and won't work. Checkout Services Entity API, it may do what you're looking for.

You may still be out of luck though. You alternatives will be to use services_views or write your own Services Resource.


How can I move a module block's title to display within the block's template? When I give my module block a title it displays above my module block.
How can I move this to display within my blocks template and not display above the template?

You can do this by overriding the block template:

create a template called block--block-name.tpl.php OR override all block templates by using block.tpl.php and move the code the prints the title into the content div:

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print render($title_prefix); ?>
      <?php if ($block->subject): ?>
       <h2<?php print $title_attributes; ?>><?php print $block->subject ?>

      <?php endif;?>
    <?php print render($title_suffix); ?>
    <?php print $content ?>


CKEditor 4 library is not detected by Wysiwyg module The Wysiwyg installation instructions tell me to

  Extract the archive and copy its contents into a new folder in the following location:
  sites/all/libraries/ckeditor

  So the actual library can be found at:
  sites/all/libraries/ckeditor/ckeditor.js

These 2 conditions are met, however in the overview of editors, the CKEditor is now red. So it sees something is there, it's just not right.
What can be wrong? where should i be looking to troubleshoot?

The WYSIWYG module is not compatible with CKEditor 4, because CKEditor 4 uses double quotes " around it's version string, where CKEditor 3 used single quotes '. This breaks the version detection regex in the WYSIWYG module.

You could use CKEditor 3, like Bruno suggests, or you could patch the WYSIWYG module like described here https://drupal.org/comment/6790812#comment-6790812.

In editors/ckeditor.inc, replace line 81:

if (preg_match('@version:\'(?:CKEditor )?([\d\.]+)(?:.+revision:\'([\d]+))?@', $line, $version)) {

with:

if (preg_match('@version:[\"|\'](?:CKEditor )?([\d\.]+)(?:.+revision:[\"|\']([\d]+))?@', $line, $version)) {

If you're not bound to using the WYSIWYG module, you could also use the CKEditor module.


find Menu Settings of node, given URL alias (or node ID) In the Drupal 8 screen for editing a node, we have these two sections:

URL Path Settings > URL alias
Menu Settings (Menu link title, Description, Parent item, Weight)

How, given the URL alias of a node, can we get those Menu Settings, particularly the Menu link title?
This may break down into two separate problems:

finding the node ID from the URL alias
finding the Menu Settings from the node ID

and in fact I would be thrilled at a solution to either one, even as a high-level explanation.
I would go into detail about how I've attempted to answer this question already, and the services & classes that appear to be relevant, but I don't want to post a complicated-looking question.  If data is that easy to put into those basic fields in the UI, it should at least be possible for some module code to get it back out.

Comments in my question getting URL from Route: breaks in localhost subdirectory have clarified that the solution of @4k4 is absolutely the right way to get the alias from the current path.  But the alias is not as useful as I thought in applying suggestion (@Ivan Jaros) to use entityQuery to take it the rest of the way, since the current path is able to match the link.uri field of menu_link_content, except for a leading slash in the pathname and the entity: protocol:

$current_path = \Drupal::service('path.current')->getPath();
$system_uri = 'entity:' . trim($current_path, '/');

$query = \Drupal::entityQuery('menu_link_content')
  ->condition('link.uri', $system_uri)
  ->condition('menu_name', 'main');

$result = $query->execute();
$menu_link_id = (!empty($result)) ? reset($result) : FALSE;

if ($menu_link_id) {
  $menu_link = MenuLinkContent::load($menu_link_id);
  $menu_link_title = $menu_link->getTitle();
} else {
  drupal_set_message(t('no Menu Link Content for ID that we found...'), 'error');
}


Entity reference to user doesn't work without 'administer users' permission EDIT: I have most probably found out the reason thy it works (or doesn't work actually) this way. The problem is that I don't have legitimate access to the user node that is being edited. I only 'hacked' the menu system so it let me through but don't really have the real access. Unfortunately I have no idea how to resolve this problem...

I have reworked the system that handles permission to user edit pages so that it allowed editing certain users even without the 'administer users' permission.

The system itself works well, the only problems are entity reference fields on the user. To be more specific, there are two entity reference fields attached to user bundle -> one that references another user 'supervisor' and another that references certain content type.

The problem with these two fields is that the autocomplete feature (I use autocomplete widgets) in the widgets not only doesn't work but even throws a 'access denied' error (in AJAX response).

It works well when current user has the 'administer users' permission but I can't give every user this permission.

BTW: To make it perfectly clear, not even the field that references a normal content type (node) works so the problem can't be in access to user entities as the answer below suggests.

I have tried to look into the entity reference code but have not found anything that would explain this strange behaviour (there's literally zero calling of user_access that might lead to this kind of behaviour).

You could try creating an entityreference display in views which, with the 'access' options defined in views, handle user access however you please.

Here is an example view display to get you started:
https://gist.github.com/acao/7297342

Just configure the field settings to use this view instead of the default handler, and see if that gets you around your problem!


Rules module doesn't send emails to user roles once conditions are met I'm working in drupal 7 and I've configured the rules module to send emails you specific user roles when content is created. For some reason I'm getting inconsistent results, sometimes not receiving any emails. Any insight to why rules isn't generating emails would be helpful.

Here's my Rule:

{ "rules_announcements" : {
    "LABEL" : "Announcements",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "10",
    "OWNER" : "rules",
    "TAGS" : [ "announcements" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--announcements" : { "bundle" : "announcements" } },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "announcements" : "announcements" } }
        }
      }
    ],
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "5" : "5", "4" : "4" } },
          "subject" : "Announcements: [node:title]",
          "message" : "\u003Cp\u003E[node:title]\u003C\/p\u003E\r\n\u003Cp\u003E[node:field_announcement]\u003C\/p\u003E\r\n\u003Cp\u003E[node:body]\u003C\/p\u003E\r\n\u003Cp\u003E[node:url]\u003C\/p\u003E",
          "from" : "[site:mail]"
        }
      }
    ]
  }
}

Attempt to answer this part of your question:

  Any insight to why rules isn't generating emails would be helpful.

I doubt that Rules is the culprit ... and that it is rather something in actually sending the eMails. To verify this, just add a Rules Action to "Show a message" (as the very first Rules Action), and with actual content something similar to the subject / message body as what you have already in the Rules Action to send an eMail. Pretty sure that each time you'll get such extra message shown on your site. If it does indeed, you found a confirmation that there is nothing wrong with your rule itself.

However, just looking at the subject / message body of the eMail you want Rules to send: make sure to also verify that all those tokens (such as node:field_announcement) are available (not blank).

PS: a completely different explanation might be related to your event "after saving content", whereas the saving actually happens ... "before saving content". To verify if that's what your issue is about, replace your Rules Action by an appropriate Rules Component (which does the same thing), and actually "schedule" that Rules Component (using the rules Scheduler) to run after just a few seconds or minutes (at that time, for sure the save will have been completed).


How do I programmatically insert the entity ID? I have added extra fields on the drupal 7 user registration form and created a module with a hook_form_alter function so that i can alter one field in the registration form.
in the same file i also added the hook_form_submit function to handle the submission of that input box.

function user_registration_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'user_register_form'){

    $form['field_first_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First Name'),
        '#description' => t('Enter your first name.'),
        '#maxlength' => 255,
        '#required' => TRUE,
        );

}

if (isset($form['actions']['submit'])) {
        $form['actions']['submit']['#submit'][] = 'user_registration_form_submit';
       }
}

function user_registration_form_submit(&$form, &$form_state)
    {
        $fe_id = db_insert('field_revision_field_first_name')
        ->fields(array(
            'field_first_name_value' => $form_state['values']['field_first_name'],
            ))->execute();
        drupal_set_message(t('your form entry has been added'));
    }

When i click on the submit button i get the following error message

  PDOException: SQLSTATE[HY000]: General error: 1364 Field 'entity_id' doesn't have a default value: INSERT INTO {field_revision_field_first_name} (field_first_name_value) VALUES (:db_insert_placeholder_0); Array ( [:db_insert_placeholder_0] => john ) in user_registration_form_submit() (line 38 of /var/www/html/lite/sites/all/modules/user_regestration/user_registration.module)

I noticed the error is generated because the"entity_id doesn't have a default value" when the insert query is executed.
My question is how do i include the entity_id default value.

Why don't you use a module providing this functionality, like profile2 ?

The user is not created in your submithandler, so either you save it:

function foo_user_register_form_submit($form, &$form_state){
    $edit = array(
          'name' => $form_state['values']['name'],
          'pass' => user_password(),
          'mail' => $form_state['values']['mail'],
          'init' => $form_state['values']['mail'],
          'status' => 1,
          'access' => REQUEST_TIME,
          'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_first_name']))),
    );
    user_save(drupal_anonymous_user(), $edit);
}

For more details see the docs.

Or you could try to add a custom submit handler, which would be fired after the user is created, in form_alter:

$form['#submit'][] = 'your_custom_submit_handler_function';

In there the user should already be created. so:

function your_custom_submit_handler_function(&$form, &$form_state)
    {
        $fe_id = db_insert('field_revision_field_first_name')
        ->fields(array(
            'field_first_name_value' => $form_state['values']['field_first_name'],
            ))->execute();
        drupal_set_message(t('your form entry has been added'));
    }

  But keep in mind, that this custom inserting maybe needs some more
  code, here you only add the revision entry ..


How do I append a view to the node body in custom module? In Drupal 7, we could do the following within a hook_node_view:

$node->content['nodehierarchy_children'] = array(
  '#theme' => 'nodehierarchy_children_embed',
  '#nodehierarchy_view' => $node->nh_children_view,
  '#nodehierarchy_view_display' => @$node->nh_children_view_display,
  '#nodehierarchy_view_args' => $arguments,
);

Then in the hook_theme:

function nodehierarchy_views_theme() {
  return array(
    'nodehierarchy_children_embed' => array(
      'render element' => 'element',
    ),
  );
}

Finally we have the theme function:

function theme_nodehierarchy_children_embed($variables) {
  $element = $variables['element'];
  $display = $element['#nodehierarchy_view_display'];
  $arguments = $element['#nodehierarchy_view_args'];
  return $view->execute_display($display, $arguments);
}

How do I accomplish the above in Drupal 8? I'd like the implementation to be Drupal 9 compatible, so ideally I don't want to use depreciated functions etc.

I mean should I attempt to somehow override node.html.twig and provide it with a render array using something similar to:

$view = views::getView($node->nh_children_view)
$build['nodehierarchy_children_embed'] = $view->buildRenderable($display,$arguments);

I think if someone could provide the functions and general methodology, I could fill in the coding portion.

So it turns out that the hook_node_view was all that was needed, but I don't know why it didn't work the first time:

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode){
  // Get the arguments to send to the view.
  $arguments = ...;
  if ($view = Views::getView('my_view')) {
    $display = ...
    $build['some_name'] = $view->buildRenderable($display,$arguments);
    $body = $node->get('body')->value;
    $node->set('body')->value = $body.render($build['some_name']);
  }
}


Plugins before event subscribers Not sure if there's a way out of this problem but...

I have a custom log module which listens for events that could come from multiple sources. All it does is listen for an event, and if it occurs logs an entry in the DB.

But there could be different recorded data coming from different modules and I want to separate concerns so there's no complex web of dependencies.

If Module L is the listener it might get EventA from module A and EventB from module B. The events have a common base but each module stores slightly different data in the log which needs to be set-up in each case.

Option 1) Module L could be set up to listen for "module_a.event" and "module_b.event" and process them separately but that is a "bad thing" because the listener is dependent on each of the other modules. The Listener shouldn't need to know how the data is stored, it doesn't care.

Option 2) Or Module L could have a specialised event "listener.event" that Module A and Module B calls having set up the data in the event correctly. But that means those modules have a dependency on the listener.

I don't like either option because of the dependency requirements in one direction or the other.

Bright idea: Create a plugin in Module L that builds the log structure for a particular module. So Module A has a plugin that handles its requirements, and Module B has another plugin that handles its needs.

There's no dependency in either direction because if Module L is not running then A and B don't care (the plugins will never be scanned or loaded). And if either or both of A and B are missing, Module L doesn't care.

And if I then need a Module C I just give it its own plugin.

But Module L still needs to listen for events from A, B and C (module_a.event, module_b.event and module_c.event). How does it know what events it should listen for?

Easy: Set a value in the annotation of each plugin giving the name of the event to listen for. We can load all the plugin definitions in the EventSubscriber and set it up. Fantastic. Problem solved. No dependency but every event type can be listened for and handled.

Except it doesn't work because: apparently event subscribers are initialised before plugin services.

My "module_l.services.yml" looks like this:

services:
  notifications_log.notifier:
    class: Drupal\notifications_log\EventSubscriber\NotifierSubscriber
    arguments: ['@plugin.manager.notifier', '@entity_type.manager',
                '@current_user', '@logger.factory']
    tags:
      - { name: event_subscriber }

  plugin.manager.notifier:
    class: Drupal\notifications_log\Plugin\NotifierManager
    parent: default_plugin_manager

Which seems fine (doesn't matter which way round they go BTW - I've tried) but we get a fail here, in the EventSubscriber:

  static function getSubscribedEvents() {
    /** @var NotifierManager $notifierManager */
    $notifierManager = \Drupal::service('plugin.manager.notifier');

    $events = [];
    foreach ($notifierManager->getNotifierEventNames() as $eventName => $plugin_id) {
      $events[$eventName] = ['onNotification', 0];
    }

    return $events;
  }

This is a static function so we have to fetch the plugin manager directly, and it can't find it.

Is there any way around this? I could find write some code to find all the plugins myself but that's a lot of faffing about.

What I really need is a way of dynamically adding to the Event subscribers, but I haven't found a way to do that.

If I could carry the plugin_id across as well, that would be useful but it's not a big problem to find the right plugin in the "on Notification" method.)

The solution to the the problem is to dynamically add event subscribers later in the page load process, so for example:

  /**
   * {@inheritdoc}
   *
   * We can't return the plugin-based events here, but we set up
   * a response to do that at a later stage
   *
   */
  static function getSubscribedEvents() {
    // Subscribe to kernel request very early.
    $events[KernelEvents::REQUEST][] = ['onRequest', 900];

    return $events;
  }

  /**
   * Add the plugin events at this stage - early in the process.
   *
   * @param GetResponseEvent $event
   */
  public function onRequest(GetResponseEvent $event) {
    // Find every event mentioned in a plugin...
    foreach ($this->notifierManager->getNotifierEventNames() as $eventName => $plugin_id) {
      // Add the event to the dispatcher as a listener, to call that routine...
      $this->dispatcher->addListener($eventName, [$this, 'onNotification']);
    }
  }

The list of event names is cached in getNotifierEventnames().


Programatically set the language I'm trying to automate the setup of Drupal multi-site installations as much as possible, we're using each multi-site for a separate country so would like the languages localised for each.

Is there a way to programmatically set the default language? It normally defaults to English. For a Spanish multi-site I would like to set it to Spanish.

The default language seems to be set in SelectLanguageForm.php .Since this happens so early on in the installation process, I can't use hook_form_alter() because no modules, profiles, or themes would be loaded at that point.

The default language will be defined basing on the subdomain where Drupal is going to be installed.

You should consider using Drush (or Bash running Drush) for that. With drush site:install you can set the default language via --locale.

The following command will (re)install Drupal using the expert install profile and set default language to Ukrainian.

drush si expert --locale=uk

Source: https://drushcommands.com/drush-9x/site/site:install/


What is the recommended way for handling a multilingual service? I'm using the Services module together with a multilingual backend (field translation). My endpoint is v1. What I would like to have is <domain>/v1/fr/....

Is this possible without having a redirect?
What is the recommended way for handling multilingual services?

If you are using the language code as a URL prefix, then you should be able to access your endpoint as usual with the language code prefixed to it:

?q=fr/v1/...

For example, to get a node in French you could make a GET call on:

?q=fr/v1/node/123.json


Solr multi-select facets occurs bad request error I faced with a weird problem using apache solr faceting search. While selecting two facet constraints, solr respond with 400 error:

  "400" Status: null: null HTTP ERROR 400

  Problem accessing /solr/project/select. Reason:

  null

Basically I have one index configured and number of fields indexed inside. I'm using facet for "content type" field. There is no problem at all when only one facet constraint is selected.

  http://localhost:8983/solr/project/select?fl=item_id,score&fq={!tag=facet:type}ss_type:"system"&start=0&rows=10&sort=ds_created
  desc&facet=true&facet.sort=count&facet.limit=10&facet.mincount=1&facet.missing=false&facet.field={!ex=facet:type}ss_type&f.ss_type.facet.limit=50&wt=json&json.nl=map&q.alt=(ss_search_api_language:"sv")
  (index_id:"project_nodes_index") (hash:gf1tmd)

Problem starts where two constraints are selected:

  http://localhost:8983/solr/project/select?fl=item_id,score&start=0&rows=10&sort=ds_created
  desc&facet=true&facet.sort=count&facet.limit=10&facet.mincount=1&facet.missing=false&facet.field={!ex=facet:type}ss_type&f.ss_type.facet.limit=50&wt=json&json.nl=map&q.alt=(ss_search_api_language:"sv")
  ((({!tag=facet:type}ss_type:"system") OR
  ({!tag=facet:type}ss_type:"product")))
  (index_id:"project_nodes_index") (hash:gf1tmd)

Standart modules are used:
* search_api_solr
* search_api
* facetapi

Solr version 3.6.2

I think you can update to the latest dev version.

For more info you could check this issue:

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


Is it possible to install new module without ftp in drupal 6? I don't have the cpanel password of my hosting, I want to install new module through website. It's easy in D7, how can I do it in D6.

Note: if you suggest any module, I can't install that too through ftp and I don't know drush too.

If all directories are writable, you should be able to enable PHP module, create a node with PHP filter, and in that node use:

file_put_contents ( 'path_to_modules/mymodule/mymodule.info', 'name = example
description = Demonstrates how to write info file.
core = 6.x');

The same for module file.

Preferably do that with rudimentary module that will allow you to upload and extract zip / tar.gz module files as provided by Drupal.org, and then remove PHP filtered node and disable PHP module.


Views and node_access I have a D7 installation with about 2k "project" nodes, which have a multi-entry field "team members" used to control view and edit access.

So far, I have my (pretty complex) logic inside node_access, and it works fine. But views (e.g. a "new projects" feed) don't respect node_access. The mymod_node_access hook is called (I see it with dpm()), but the nodes still appear in the view result.

Obviously I could simply hide the elements using a view field template, but that breaks the paging system (e.g. user selects "10 projects per page", but sees only four).

How can I make the Views module respect node_access as a filter?

If you are willing to give it a try to "replace node_access AND drupal filters with one solution" (as per one of your comments), then have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site).
What are the features of the Group module versus Organic Group module?

Resources

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


How to properly attach Google Maps Api to Drupal behaviors in Drupal 7? So, I've posted on this elsewhere and I seem to either get half answers but they've gotten me closer to a solution but not over the finish line.

I'm trying to implement a custom Google Maps application that pulls data in from GeoJson views that I've made of an OpenLayers application that I've abandoned. The problem that I'm having is that if I follow the Drupal docs and wrap my code in a jQuery closure, then my Google Maps call back which is loaded in the global context is out of scope for the function.

I've written a simple module that loads a block of html with a map div, and then loads my google maps script externally in the footer. My map callback works when I load plain JS via my module, but not when wrapped in a closure and attached to a behavior. This poses two problems for me: 1) I can't use jQuery functions to get my data; 2) it's bad practice (as above). So, I guess my question comes down to how do I pull a callback on an externally loaded script into the scope of my Drupal behavior?

So loaded as plain JS this works:

 var map, alumLayer, chapterLayer, assocLayer, userLayer;
  function initMap() {
    map = new google.maps.Map(document.getElementById('json-map'), {
      zoom: 4,
      center: {lat: 38.43, lng: -90}
    });
 //ajax code to get map data here
}

But this closure attempt doesn't:

    (function ($) {
Drupal.behaviors.gmap_json = {
attach : function (context, settings){
  var map, alumLayer, chapterLayer, assocLayer, userLayer;
  function initMap() {
    map = new google.maps.Map(document.getElementById('json-map'), {
      zoom: 4,
      center: {lat: 38.43, lng: -90}
    });
}
}
};
  alert('it works');
}(jQuery));

So, I know that my problem here is scope, but I haven't yet found how to do this.Do I need to modify my callback trying to reference the behavior object somehow? Is there a way of mix and matching scoped jquery? Or best practices be damned, whatever gets it working?

As you've figured out, your problem is one of closures. In the code that is not working, you have initMap() enclosed in the anonymous function (function($){}(jQuery)). This means it's not part of the global scope, and therefore cannot be called from the global scope.

The solution to this is to set your function to be available globally. But of course, you don't want namespace collisions, which is the whole point of wrapping code in an anonymous function in the first place.

There is a happy medium here. You create a global variable, and add your callback to that from within your anonymous function:

// Initialize your global object. Set the value to itself (if it exists)
// or an empty object otherwise.
var GoogleMaps = GoogleMaps || {};

// Start your anonymous function.
(function($, Drupal, GoogleMaps) {
  Drupal.behaviors.someKey = {
    attach:function () {
      GoogleMaps.initMap = function () {
        // Initialize your map here
      };
    }
  };
})(jQuery, Drupal, GoogleMaps);

Use &callback=GoogleMaps.initMap in google maps api script embed.

You can also initialize your map from any other scripts using GoogleMaps.initMap()


Redirect page to existing field value I am redirecting most of the pages of my old website to a new subdomain of the same domain, from http://www.domain.com/www-page_url to http://new.domain.com/new-page_url/with-different-slug. This new URL value exist in (almost) every page of the old website.

How would I proceed to create a general rule that permits the redirection from the page itself to new.domain.com/page_url existing field value?

You should be able to get this to work using the Rules module, using the "Drupal is initializing" event. That will ensure that the rule gets triggered BEFORE the actual content is shown. I'm not sure (actually I really doubt ...) if using Rules event " Content is viewed " (not " Node is viewed " ...) will work (typically that's 'too late'). Refer to "How to specify a Rules event like "Content is 'going to be' viewed"?" for more details on that.

If you can think of something to use a (new) URL like http://new.domain.com/new-page_url?newslug=with-different-slug (instead of http://new.domain.com/new-page_url/with-different-slug), then you can make the value of the URL argument (= the value of the newslug argument in this example) available as new variable to Rules, simply by using the Rules URL Argument module. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

  add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
  add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

  You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.

PS: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.


Add commas between allowed file extensions I need to restrict the user to upload only the file extensions that i mentioned in the Allowed file extensions filed. It works properly. But in front-end, i need to add a comma separator for this format.

Actual - Allowed file types: ai aif avi bmp csv doc docx eps fla flv gif img.

Expected - Allowed file types: ai, aif, avi, bmp, csv, doc, docx, eps, fla, flv, gif, img

You are definitely allowed to separate file types by comma in the admin are

For user area, find the ID of the form (you can find this in the firebug) then

function YourTheme_form_alter(&$form, &$form_state, $form_id){
      if($form_id == "TheFormID"){
            kpr($form);
      }
}

In this way you can find the form elements. get the Key of image field in the form array, if it is image then write

function YourTheme_form_alter(&$form, &$form_state, $form_id){
      if($form_id == "TheFormID"){
            $form['image']['#description'] = t('File types are comma separated')
      }
}

This is the general idea but a few modification might be needed


video module, MIME problem I have installed the video module of the Drupal 7 distribution. I have added the "video" field to my content type. When I upload the mp4 format of the video, I get the following message:

  No video with support format and MIME type found.

What should I do?

Changing the player set to play files of that type might help. If not, installing one of the transcoders like ffmpeg or Zencoder will fix it. If that's not practical, you can use other modules besides Video, and create your own video field, for example the jPlayer module (which takes any m4v videos, a variation on mp4)


Change the author of a node We have a website which will host lots of species information. A resource is entering the data on behalf of another person. I would like to change the author information of the nodes once the data entry is completed.

Is it possible to replace all instances of the author ID of 'Person A' with 'Person B'? I assume we need to write some database query and run it in the phpMyAdmin. What query it would be? Also, is there any other efficient way?

Thanks

The easiest way I think is this:

Install the views, views_bulk_operations, and admin_views modules.
Go to the content listing (admin/content).
Filter the results to get the nodes you are interested in.
Check the checkboxes next to the node (there is also an option to select all).
Select "Change author" from the operations dropdown and click the "Execute" button.
Select the user you want to change the author to and click the "Next" button.

Admin views uses views bulk operations to override the default drupal administration views with something a lot more useful.


Dependant dropdown list I have 2 fields, state and city. I would like to change the city field when I select the state field.
I tried to use "hs_nodereference", but this module shows the state and city fields as follows.

statename: statelist
cityname: statelist  citylist

I want them to be shown as follows.

statename: statelist
cityname:  citylist

Does anyone know a solution for this?

Make a vocabulary with states at zero level and cities at deepest level for each state. Then install hierarchical_select module.

Enjoy :)


Drupal & Wordpress User Integration I know I might be asking a really dumb and likely complex matter, but it's the only remotely easy option I have at the moment.

Due to what is set up on two systems by my predecessor, wordpress and drupal both appear as CMS's that I have to manage, the one problem area apparently always having been the ability to keep users accounts in order so that if a user created an account on one site, the admin would have to go through and manually connect that account to the other site.

So my question is, after looking through everything and apparently finding very little to resolve this issue, I am coming to ask whether or not there is an option for me to connect the two (for the time being, I don't expect it to take more than a few months) in just how pull, from a table, a username and password? And just as a heads up, I am converting the wordpress to drupal so this problem will be solved in the near future, I just need this as a temporary solution...

I'd greatly appreciate any help.

This is a rough sketch based on some other projects I've been involved in but the WP part is a bit uncertain. FWIW here it is:

1) install services, rest server and an auth module (like oauth or api_key) the on drupal and create an endpoint with resources for the user functions you need. Find a great tutorial by here. Essentially you should be able to push a php call with the json to your endpoint (Chrome's postman is a great tool to test this with) and get a 200 response if user was logged in or 401 unauthorized if not.

2) pause WP from processing user tasks on its side

3) export legacy WP users to csv and import users into Drupal using the user import module

4) Now you should be able to set ping your drupal from WP, get a reply back, set a session var if logged in and serve content on WP as if they logged in.

Granted, this is not an ideal setup but hopefully will carry you through the few months until you convert WP to Drupal.


How to show the count of members that belong to a group? I have a view showing a list of nodes of type group. How do I set it up to show the count of members that belong to each group?

I finally figured it out:

(enlarge image)

The steps are:

create a view for "content" type "group". Use "fields" and show "content:title", that's the name of your group
add relationship "Group: Node group" (required), then "(group) Organic groups group: OG membership" (required).
add filter "(OG membership) OG membership: Entity_type " and set to "is equal" to "user"
"use aggregation"
add field "(OG membership) OG membership: Entity id" and use "count distinct" option. That's your count of members.

If you want the count of nodes that are "linked" to a group you would just change the filter from "user" to "node".


Alternate node/add page I would like to create an alternate node/add page, which can be accessed by a url path, so that I can have an alternate add node page for users while admins can see a different add node page.

This are my current selection rules:

This panel will be selected if Current path is "test", and NOT (Logged in user has role "anonymous user").

I get a 404 error when I access "test". I've tried adding the Node being edited is type "Test". selection rule but it doesn't work either.

Due to talking from comments, there answer that help:

You cann't alternate node/add/nodetype via Test.
You can create alias Test for node/add/nodetype or you can write custom function, that call node/add/nodetype form via drupal_get_form with some node preparements function.
After this you can apply Panels and so on

First answer was incorrect:
Enable Page manager module (part of CTools), then goto admin/structure/pages and add 'Add custom page', set path to test, save it. Now you can use your Panels that fire for Test page.


Existing module for logged in user image upload I'm looking to build an image upload website. The only feature needed is the ability for logged in users to upload images.

Is there an existing module for this?

I could just build a custom module for a form; but i wanted to find a decent module to build this before investing time into it.

Required:

Image upload restricted by user role
Each Image upload becomes either node

Some wants:

Image cropping

You can make that in different ways, you can use the media module to create image galleries, remember if you use that module installing Styles


Blank page when trying to add new content I've to cope with something very odd: I can't add any type of content anymore. For example: when I go to Content > Add content > Article, I navigate correctly to the 'add acticle' page, but I simply get a white screen. I didn't have this before and I can't remember installing new modules. I already tried to flush all caches, but that didn't solve anything. Even when I add

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
?>

to my index.php or settings.php file, no erros are displayed. Please help!

Edit 1: going to the Configuration screen doesn't result in a WSOD. There's only a white screen when I try to add content.

Edit 2: I discovered that I also get a WSOD when I try to edit already existing content. Please help me! I really can't do anything anymore!

There was something wrong with my database. I had to delete it and reinstall my backup.


Align embedded Media Images When I embed an image into CKEditor text I can choose alignment options. When I embed a Media Image I cannot choose alignment, but a Media View. A media View allows me to specify image size (via image style) but not alignment

Embedding an Image does not add the image to the Media Library and it would be nice to only use Media Image embedding so as to manage the site's media library of images.

What is the preferred way of specifying the alignment of embedded Media?

Background

I am switching over to simply using core Media modules in Drupal 8.8. I have ditched what I was previously using:
*  Embed
*  Entity Embed
*  DropzoneJS entity browser widget
*  Entity Browser
*  Entity Browser IEF

The easiest to resolve (and most likely) issue is:

You are limiting the allowed HTML tags for the text format you're using and you haven't allowed the align (and also caption, if you want captions) attributes for the drupal-entity HTML element. (I'm assuming you do have the Align images and Caption images filters enabled because you said those features were working for non-media embeds. If they're not enabled, enable them.)

Solution:

In the "Limit allowed HTML tags and correct faulty HTML" section (/admin/config/content/formats/manage/MY_FORMAT#edit-filters-filter-html-settings), make sure the drupal-entity has at least the data-align (and data-caption for captions) attributes. E.g. <drupal-entity data-align data-caption data-etc...>.