How to enable / disable a module in settings.local.php I'm using a settings.local.php for my local development environment. This is a Drupal 7 site.

I've seen a few references to this via google search, but none of the examples are working for me. I don't want to install a module to make this work if it is possible to accomplish the same result by adding a couple lines to the settings.local.php file.

I use this file all the time for a number of sites so I know it is being read properly. I've also used it to set variables (file_temporary_path, for example) and that works too. It is just enabling / disabling modules I'm having trouble with.

Any thoughts / suggestions?

I don't know if it is possible to enable / disable modules in settings.local.php but for downloading and enabling modules you can use drush, like so:

drush dl views
drush en views -y

For disabling the modules use:

drush dis views -y

Another method is to implement hook_update() in a custom module's module file to disable / enable modules.

/**
* Uninstall views module.
*/
function MODULENAME_update_7000(&$sandbox) {
   module_disable(array('views'));
   drupal_uninstall_modules(array('views'), FALSE);
}

Of cource you can also use module_enable in the hook_update()

/**
* Install views module.
*/
function MODULENAME_update_7001(&$sandbox) {
   module_enable(array('views'));
}

If you use hook_update then remember to do:

drush updb

and

drush cr

Hope this can help you.


How to Retrieve FID from UUID on Feature Enable I would like to use features to import/export some content. The content type conains custom field of file, so I am using hook_uuid_node_features_export_render_alter(&$export, $node, $module){..} to add UUID of the file to the export.

function MODULE-NAME_uuid_node_features_export_render_alter(&$export, $node, $module){
        if($module == 'MODULE-NAME'){
        $field_instance = field_get_items('node', $node, 'field_elastic_slide');
        foreach($field_instance as $key => $instance){
            $file = file_load($instance['image']);
            $export->field_elastic_slide['und'][$key]['image'] = (array)$file;
            $file = file_load($instance['thumb_image']);
            $export->field_elastic_slide['und'][$key]['thumb_image'] = (array)$file;
        }
    }
}

This works well and the UUID along the other file info is written into the file ending .features.uuid_node.inc part of the export module. So far, so good.

When importing, i would like to use the UUID to look up the FID of file on the Drupal instance import taking place, so i am using:

function MODULE-NAME_uuid_node_features_rebuild_alter(&$node, $module){
    if($module == 'MODULE-NAME'){
        $field_instance = field_get_items('node', $node, 'field_elastic_slide');
        foreach($field_instance as $key => $instance){
            $uuid = $instance['image']['uuid'];
            // We have a uuid - we'll try to retrieve fid.
            $file = entity_uuid_load('file',$uuid);//attempt 1
            $slider_img = current($file);

            $fid = uuid_get_serial_id('file', 'fid', $uuid); //attempt 2

            // There is no local image.
            if (empty($fid)) {
                watchdog(WATCHDOG_NOTICE, 'Slider image with uuid: ' . $uuid.' was not found', WATCHDOG_ERROR);
            }
            $node->field_elastic_slide['und'][$key]['image'] = $fid;
...

This is not working. Where is the UUID<->FID Map stored for features? How to retrieve the FID at the time of importing(enabling the feature)? Any help is much appriciated

I guess i didn't know exactly how the export/import works...perhaps, i still do not, but here is my theory so far. When importing custom fields containing file, we have to save the file in the table file_managed by ourselves. The feature module will only do the work of importing files for the default field types(file, text,etc) and not for custom fields which is our case.

Here is quick write up
http://margotskapacs.com/2014/03/make-custom-field-with-file-exportable-in-drupal-features/


Can't seem to load CSS in a custom theme I'm working on trying to add CSS to a custom theme, and it seems my logic is failing somewhere.

I'm adding simple css files in the .libraries.yml on the root of the theme (only thing in them right now is forcing a background color on the body) and not one of the css files is loading.

Where does my logic fail here?

This is in Drupal 8

Ensure you have a call to your library in your .info.yml

libraries:
 - pixelcircus/global


dependent dropdowns in ajax Searching for cascading ajax dropdown in this forum only gives me two discussions here and the other here

I have an almost similar issue only that the form select element I'm about to create cascades down in the 'taxonomy tree'. So each dropdown that was ajaxed will again be used to trigger another dropdown--in ajax...

Here is my sample module (trimmed down to relevant parts only):

function mainswitchboard($form,&$form_state){
    $form = array('#prefix'=>'', '#suffix'=>'');
    $form['maincategory'] = array(
        '#title'=>'Firs Select',
        '#type'=>'select',
        '#options'=>_populate_dropdowns(),
        '#ajax'=>array(
            'callback'=>'maincategory_callback',
            'wrapper'=>'wrapper-div',
            'method'=>'replaceWith'
        )
    );
    return $form;
}

function maincategory_callback($form,$form_state){

   $from_element_name = $form_state['triggering_element']['#name'];

    $triggerer = $from_element_name;
    $value = $form_state['values'][$triggerer];

    drupal_set_message(time(). ' ' .$triggerer);

    $commands = array(); $arguments = array();
    if(count(_populate_dropdowns($value))) {
        $form['subcat_for_'.$value] = array(
            '#title'=>'Subcat for '.$value,
            '#type'=>'select',
            '#options'=>_populate_dropdowns($value),
            '#attributes'=>array('id'=>'subcat_for_'.$value,'name'=>'subcat_for_'.$value),

        );

         $arguments['ajax'] = array(
            'subcat_for_'.$value=>array(
                    'event'=>'change',
                    'callback'=>'maincategory_callback',
                    'wrapper'=>'wrapper-div',
                    'method'=>'replaceWith',
                    'url'=>'/drupal7/system/ajax',

            )
        );

        $commands[] = ajax_command_settings($arguments,TRUE);

    }

    $commands[] = ajax_command_insert(NULL, drupal_render($form));
    $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
    return array('#type'=>'ajax','#commands'=>$commands);

}

The above code seems to work the only problem is you the second dropdown no longer produce results (although a throbber is showing when you click the second dropdown..) The second dropdown does not seem to honor the arguments variable, hence, it does not seem to call the function in its callback...

I'm stuck new drupaler...

Thanks!

You cannot change your $form in your ajax callback. Instead try to add a validate function with hook_form_alter on your form (or if in custom form just there) where your add a variable to your $form_state and don't forget $form_state['rebuild'] = TRUE. This will cause your form to rebuild (so form build function is called anew) In your form build function you can check this variable in $form_state and malipulate the form. In your ajax callback you need to replace the form element (ajax_command_replace)

So workflow will be: form build function - ajax trigger - form build function - form validation (set variable & rebuild) - form build function - ajax callback


Print the node author's full name on a custom node template I have a content type "Blog entry" which I have overridden the template. (node--blog_entry.tpl.php)

The target is to display the node author's full name (as a link) which will take the user to a page (produced by a view) which shows all the other articles they have written.

In my template file, I have the following code:

 function bootstrap_mysite_preprocess_node(&$vars) {
   $vars['author_name'] = $vars['name'];
   $vars['submitted_dt'] = format_date($vars['node']->created, 'custom', 'jS F Y');
 }

The view that I have created which shows the author's other articles takes the UserID as an argument, so what I need is to display a link which which shows the author's full name, but passes their UserID.

the code I have in my custom content template is:

    WRITTEN BY <a href="/user-posts/<?php print $uid; ?>"> <?php print $author_name; ?>

But author name is not only the author's username (not their full name) but it is output as a link which is no good for me.  I simply want to output the author's full name as plain text.

So, to summarise -
What can I use instead of $vars['name']; (which producesa username that links to a profile)
that will instead produce some plain text of the user's full name ?

Your question doesn't indicate whether you are storing the user's full name anywhere. You can add fields to the user profile (at /admin/config/people/accounts/fields). Suppose you add a firstname field (field_user_fname) and lastname field (field_user_lname), you could then write a custom function in your template file, like this:

function _get_author_name($uid) {
  $wrapper = entity_metadata_wrapper('user', $uid);
  $fname = $wrapper->field_user_fname->value();
  $lname = $wrapper->field_user_lname->value();
  return "$fname $lname";
}

And then, since you already know the UID, you could call the function from your content template:

    WRITTEN BY <a href="/user-posts/<?php print $uid; ?>">
    <?php print _get_author_name($uid); ?>

You could also investigate the Realname module.


How do I change the temporary directory without using any administrative pages provided by Drupal? I've moved my live Drupal website to Windows localhost (XAMPP), but I'm getting lots of "The file could not be created" errors. If I log in to the site as an administrator, it fails to return any more pages at all. I can view it with errors if I don't log in.

Is there a way to change the temporary file location without logging in through the interface, or using any administrative page?

In Drupal 7 the temporary path is stored in the variable file_temporary_path, so you can either update the entry in the variables table with a SQL-query. Or you can use Drush:

drush vset file_temporary_path [some_new_path].


How to set the "Read More" link (in Rewrite Rules for Body field) to point to the node url instead of the title? I have created the blog as a view in Drupal 7.14 site. On my main blog page, I want to show 5 trimmed versions of the posts. I have added the following fields for the main blog page view - Title, Author, Post date, Body. In the Body field, I select the following options in "Rewrite Rules" section - Trim field, add read more text. Btw, I have selected the default format for the body. I add the "More link path" as [title] after referring to the Replacement Patterns.

When I apply the changes, I see that the "Read More" links to the actual title and not the url that is linked to the title. Example, it will create a link "www.mysite.com/My post title" instead of "www.mysite.com/blog/my-post-title".

In the Title field, I have selected the option to link the field to original piece of content.

The same setup worked on my localhost and it is not working on my Joyent server. Am I missing something? I have spent several hours looking at concepts like Pathauto, replacement tokens, etc, but no help.

Just change the More link path to the node/[nid]

Add field nid to the views field and exclude from display. Make sure nid is above body field. Re-arrange the fields by clicking on select list next to field label and drag nid field to top of body field. It works !

Drupal l function while generating links will convert automatically to path alias blog/blog-title !


Restricting Menu Item visibility for certain nodes Is there a way of customising what pages a Menu item will be displayed on? For example, I would only like one particular menu item in the sidebar menu to be displayed for one node, but the rest of the menu item links I would like to be the same throughout the site. Is this possible?

I don't know about any module that does what you need. But you could clone you menu (with Menu Clone), remove the particular items and set the visibility to the seperate menus.


Drupal not connecting to Solr Server I have setup Apache Solr version 5.5 and it runs fine when I test through my browser at http://localhost:8983/solr/ but when I try to connect Drupal to this it throws the error:

I am getting some 404's in my logs also:

I don't know what is going wrong here, My Solr set up is fine so I just can't figure out why it doesn't connect to the Apache Solr Server.

There can be two things which I can think of.

Most SOLR installation guides advise you to edit IPAccessHandler in server/etc/jetty.xml to whitelist certain IP addresses. Often this is 127.0.0.1, but that would prevent access from localhost via IPv6. So you maybe should also white label the IPv6 localhost address ::1, or connect explicitly via IPv4 127.0.0.1.
Since SOLR 4.x you should also include your core name in the url. Search API Solr clearly states this. It might apply to Apache Solr module as well. This would mean your should enter a URL like: http://localhost:8983/solr/<core name>.


want to create custom rule for like post or comment? I want to write a code for custom rule.I want to that when some one post a comment then one can able to like his/her post or comment i.e a single click on the Like will 'like' pieces of content and a message is send to that user who posted that comment . Is it possible with rules ??

You can use flag module.

  Def: Flag is a flexible flagging system that is completely
  customizable by the administrator. Using this module, the site
  administrator can provide any number of flags for nodes, comments,
  users, and any other type of entity.

Once you install the module, its very simple. Goto structure->flag->add new flag. Give title for the flag and use the count option to display the like-count.

In my example, 'Node Like' is the title of the flag, the flag count can be achieved in token

[node:flag-node-like-count]

To answer your question, its possible but complex to achieve just using rules.


How to make a form required with states? I have a drop down list that displays various fields based on what is chosen and I know that I can toogle the visibility with states but when I try to use required the * span is display but it isn't actually required. What I mean is that even though it's "required" I can hit submit and not get an error message from drupal. Am I doing something wrong or is this currently broken in Drupal 7.8?

        $form['host_info'] = array(
        '#type' => 'select',
        '#title' => t("Host Connection"),
        '#options' => array(
          'SSH2' => t('SSH2'),
          'Web Service' => t('Web Service'),
        ),
        '#default_value' => t(variable_get('host_info', 'SSH2')),
        '#description' => t("Specify the connection information to the host"),
        '#required' => TRUE,
    );

    $form['ssh_host'] = array(
        '#type' => 'textfield',
        '#title' => t("Host Address"),
        '#description' => t("Host address of the SSH2 server"),
        '#default_value' => t(variable_get('ssh_host')),
        '#states' => array(
            'visible' => array(
                ':input[name=host_info]' => array('value' => t('SSH2')),
            ),
            'required' => array(
                ':input[name=host_info]' => array('value' => t('SSH2')),
            ),
        ),
    );

    $form['ssh_port'] = array(
        '#type' => 'textfield',
        '#title' => t("Port"),
        '#description' => t("Port number of the SSH2 server"),
        '#default_value' => t(variable_get('ssh_port')),
        '#states' => array(
            'visible' => array(
                ':input[name=host_info]' => array('value' => t('SSH2')),
            ),
            'required' => array(
                ':input[name=host_info]' => array('value' => t('Web Service')),
            ),
        ),
    );

You will need to validate this yourself in a custom validate function.

Everything configured by #states happens 100% in the browser, everything that it does is not visible for Drupal when the form is submitted (for example, all invisible form field are submitted and validated in the same way if there were no #states).


Check if it's the front page in the template Im trying to show content when I'm on the front page of my Drupal 8 test website, but the content shows on every page:

{% if front_page %}

    {% if logo %}

    {% endif %}

TESTTESTTESTESTAET

test</h1

    {{ page.header }}

{% endif %}

Why doesn't this work and how can I make this work?

The variable you're looking for is called is_front:

{% if is_front %}

The available variables for a template are documented at the top of the .html.twig file, however there is also a set of default variables available to all templates (which are not documented in every single template). You can find them in _template_preprocess_default_variables().


Unable to save contents once a  tag is added I try to add new contents and added a content with an image tag in it. It could be as simple as:

<img>
Hello

When I try to save, the page merely reloads and nothing is saved, no error messages and I am still at the same page.

Adding new contents without the  tag saves with no problem. Adding new contents with just the  tag also saves with no problem.

Only contents with an  tag AND some other contents not save.

This problem came up suddenly. I have not updated Drupal nor any of my modules. And I have confirmed that I have allowed  as a tag in my text format.

Would anyone know what problem this may be?

Solved the problem. It has absolutely nothing to do with images. The web hosting company configured modsecurity and it broke the way Drupal does POST in some instances.


How to set/get base_path in D8? How do I get the base_path in Drupal 8? When I use the base_path() function it always returns just the /. I know in Drupal 7 you could set the base_url in the settings.php file, but how do I set it in Drupal 8?

I'm trying to create an absolute url for social media sharing.

You're looking for $base_url global:

global $base_url;

If you want to have this in a preprocess function, you'd have to call it within that function; for example:

function YOUR_THEME_preprocess_whatever(&$variables) {
  global $base_url;
  // Now you can use it.
  $variables['base_url'] = $base_url;
}


How do I add inline JavaScript to the footer? I want to add third-party JavaScript code at bottom of the every page. I build an module and I am able to add the JavaScript on the head tag, instead of footer.

I am using the following code.

function ur_optin_monster_preprocess_html(&$variables) {
  $config = \Drupal::config('ur_form.admin_settings');
  $variables['#attached']['html_head'][] = [
    [
      '#tag' => 'script',
      '#value' => $config->get('my_js'),
      '#weight' => 400,
    ],
    'ur_form_js',
  ];
}

I also tried changing 'html_head' to 'html_scripts', but it doesn't help. I tried with the batrik.theme file, but it gives the following error.

  Error: Call to undefined function drupal_add_js() in bartik_preprocess_html() (line 95 of core/themes/bartik/bartik.theme).

function bartik_preprocess_html(&$variables) {
  $config = \Drupal::config('ur_form.admin_settings');
  if ($config->get('my_js')) {
    drupal_add_js($config->get('my_js'), array('scope'=>'footer'));
  }
}

Can you suggest me the correct way to add JavaScript code at the footer of every page?

Until Add support for inline JS/CSS with #attached is resolved, you should add a JavaScript file normally as a library defined in a MYMODULE.libraries.yml and then pass your module's config as Drupal settings from PHP to this JavaScript file.

foobar:
  version: VERSION
  js:
    js/myscript.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

Then in MYMODULE.module add the JS file and pass the config over to JS.

/**
 * Implements hook_page_attachments().
 */
function MYMODULE_page_attachments(array &$attachments) {

  $attachments['#attached']['library'][] = 'MYMODULE/foobar';

  // Pass values from PHP to JS.
  $attachments['#attached']['drupalSettings']['MYMODULE']['lorem'] = \Drupal::config('MYMODULE.settings')->get('lorem');
  $attachments['#attached']['drupalSettings']['MYMODULE']['ipsum'] = \Drupal::config('MYMODULE.settings')->get('ipsum');
}

Then in the JS file access them like following.

(function($, Drupal) {
  'use strict';
  Drupal.behaviors.MyBehavior = {
    attach: function(context, settings) {

      $('html').once('MyBehavior').each(function() {

        var lorem = settings.MYMODULE.lorem;
        var ipsum = settings.MYMODULE.ipsum;

        // Do whatever you need to do.
        // ...

      });
    }
  };
})(jQuery, Drupal);

I just found Inline JavaScript that is in an integration module in the docs. But it also says

  Using any inline JavaScript is highly discouraged. If you can use one of the examples above, please consider those before attempting to
  do this.


How to export the log messages in .csv file? How can I export the log messages (Site Reports-->Recent Log Messages) in a .csv file?

You can use phpMyAdmin to export the watchdog table (or select entries) in csv format which excel can read.

If you do not have access of database, you can use Views, Views Watchdog and Views data export modules to accomplish this.


Bulk change radio button setting in admin/content using database I am using a paywall module called TinyPass where I have to check a radio button in order to activate the paywall for a specific node. I now have a situation where I want to uncheck (or deactivate) this button for a lot of nodes that I have.

Instead of doing this for every individual node I would like to do this for a large selection of nodes (or even all of them).

Is it possible at all to change the value of these radio buttons setting in a node using the database or some other solution? This would save me a ton of time.

Have you tried bulk operations? You can select a bunch of nodes from the content overview page, and use bulk operations to change values on all of them. https://www.drupal.org/project/views_bulk_operations


Reusing existing content types for very similar content Let's say I have n categories of "means of transport" I need to display on my site (aircrafts, cars, bikes...). They share a lot of attributes like "name", "weight", "manufacturer" etc. But each of them also has a small number of distinct attributes that they do not share with others (e.g. only an aircraft has an attribute "wingspan").

I've addressed this myself and seen this issue in related questions here, here and here (and many more) and I do understand that opinions vary as there is (probably) no definite right or wrong answer.

However, I'm still wondering if there exist Drupal-based pros and cons (in terms of performance, maintainability) instead of pure personal preferences for planning your content model one or the other way.

Approach 1: My first thoughts were similar to the following approach, which does not appear to be the optimal use case for the paragraphs module:

1 content type "means_of_transport" with a set of basic fields (name, manufacturer, weight...) that are shared by all.
1 field that references a taxonomy X with terms "bike", "car", "aircraft"... to tag each piece of content.
n fields that each reference a different paragraphs type, containing all the fields that are specific to a certain piece of content (e.g. the "wingspan" & "call_sign" compound field for aircrafts)

This results in 1 content type with n paragraphs types. As Hudri and Kevin already pointed out there does not seem to be much benefit in just shifting the complexity from content types to paragraphs types.

Approach 2:

n content types "bike", "aircraft"... with all the attributes
(fields) that are shared between them being reused, so that you don't
need to create a new field for "name", "weight" etc. each time, but
also each content type having a few unique fields that are specific
to it.

Let's say I'll go with approach 2 and n=50 content types and each means of transport only has 1 unique attribute, all the other ones are shared and their fields could be reused. To me that seems very inefficient and often you read one should try to reduce the number of content types when planning your site. But maybe that's the Drupal way to do it and by reusing most of the fields you do not create too much overhead anyway.

Is there any other possible solution to "reuse existing content types with different fields" as also indicated in this answer by Jaypan?

Again, I'm interested in facts that support one or the other approach (and I'm aware they might not exist at all and it comes down to personal taste).

Nodes are a generic entity, with each bundle (content type) being it's own type (ie - a means of transport). This is too generalized. As such, I would say that this is a case for a custom entity, rather than nodes. Your custom entity would be means of transport. You would then create base fields on the entity type for the fields common to each means of transport. You would then create bundles (which for nodes, are known as 'content types') for each separate means of transport (car, plane, bicycle etc) and add means-specific fields to the bundle.


Hide form fields unless 'add node image (etc) link is clicked I have content type with many fields. I'd like to simplify the form as best I can and hide un-needed text boxes/checkboxes/options whenever possible. Is there a module you know of which will replace an entire field with an 'add this field' hyperlink. When clicked that field would obviously become visible.

Try the Conditional Fields module. It's still in -dev state for D7 but maybe it works for your case.


Access denied on image styles files on Drupal 7.34 As you can see in the screenshot below, images that are processed through image styles aren't showing up and when trying to display them through their urls, we get a 403 access denied.

It's a fresh drupal install on a Debian 7 with no additional modules

Any ideas are welcome to overcome this problem

Thanks

It's common to have incorrect permissions on that folder. You'll need to fix the permissions for /site/default/files directory. For a complete answer, see the recommended directory permissions or just run the following from the website root (per @David's comment below).

find sites/default/files -type d -exec chmod 755 {} +
find sites/default/files -type f -exec chmod 644 {} +
chown -R www-data:www-data sites/default/files

For additional issues, check Status Reports on yourWebsiteName.com/admin/reports/status.

Update:

I think I found the issue.

There was a similar question asked on Drupal.

It seems that the issue is that certain hosts, such as BlueHost, HostMonster and Virtualmin forbid +FollowSymLinks. You will need to change +FollowSymLinks into +SymLinksIfOwnerMatch in your .htaccess file. See an entire discussion on Drupal.


Remember View results on a browser back button click I have a view with some exposed filters that show some links. When I select a filter option, an ajax search is done and it shows the results. I click in one link and then I click in the browswer back button to go back to the view page.

Now, all results are shown and not the filter option ones.

How can I get that the view remembers the ajax search?

The answer to this question should include a "non-Drupal" part since what happens when you click the "Back" button is browser-related.

What happens on the browser

I'm not an expert on the subject, but basically all browsers add the last request that you did in a "history cache" and pressing the "Back" and "Forward" buttons moves you backward or forward in this "cache".

In general, AJAX requests are not included in this cache but this is browser specific (I think that I have read somewhere that Safari in some cases does store AJAX requests). You can find various resources on how this works for different browsers if you look it up on google (keywords could be: "back button ajax calls", along with the name of the browser that you are looking for).

Views' "Remember last selection" setting

For your specific question there are 2 things that you should notice:

Views do allow you to store the last selection by the user in the Exposed Filters' settings. The setting's name is: "Remember the last selection". This setting also allows you to limit the roles for which the last selection will be remembered.
The browser does not really care what Views do and, at least in the case of Chrome (probably other browsers do the same too), returns its cached version of the page (aka minus ajax calls).

You can test the above-mentioned assertion by setting the last selection option, hitting the back button (you will see the browser-cached version of the page) and then hitting the refresh button (browser will request the page again and views will kick-in and enforce the application of the last used filters).

Solution

The google search "back button ajax calls" could give you a lot of relevant results but if you want to test the famous Drupal notion: "There is a module for that", there actually is and its name is "Views AJAX History". It depends on the history.js javascript library and the Libraries API module.

Proof of concept

I have quickly created a dev site that I can use for my answers here and added 50 nodes with devel generate. You can see a sample view here that has AJAX enabled. After you have filtered the view using the "Body contains" exposed filter with a sample string like "oppeto" you will instantly see what Views AJAX History does: the call is being made through AJAX but the URL on your browser changes to include the exposed filters' values and is stored in your browser's history cache.

Now, when you click on a node link and then hit the "Back" browser button, you get returned to the correct, filtered version of the view (tested it on Chrome but you can test it on any browser that you want to make sure that it works as expected).

Important Warnings

I have used this module on a couple of sites that I have built and the thing that bothered me the most is the fact that it has a known, unsolved conflict with the core Overlay module. It was not a very big deal for me since I could afford to disable Overlay at these specific cases but you should definitely consider this if you rely heavily on Overlay. For example, if you rely on Overlay Paths to show colorbox-like popups, you will find yourself in a world of hurt.

I am considering using Views AJAX History on one of my core projects but in order to do this, I will have to take a stab at the issue that I mentioned before. In any case, you can monitor the progress of the specific issue or even try to create a patch yourself.


How to place images in footer region through page.tpl.php I would like to know how to place images in footer region through page.tpl.php. I know a block can be created and done so but i want to do so using page.tpl.php. Where should i write the code?

If your not going to use blocks how about going a level deeper into the actual footer region template...

region--footer.tpl.php


One rule for multiple webforms I've created several webforms. 5 of them contain a field with same machine-name where 2 different rules check the value of the mentioned field. Depending on that value an e-mail is sent. My problem is that both rules run on all webforms, not just on the 5 I only want them to. As the field it tries to check is not present in the other webforms, I get an error message on all other webforms. How can I limit the rule to run on only these 5 of my webforms?

PS: In my rules under "Condition" I execute an PHP code to check the value.

I guess it could be solved with AND or OR but couldn't figure it out.

Typical approach

The previous answer quite often resolves various situations where some variables appear to not be available in Rules Actions, etc. For example, before using a Rules Action like "Set a data value" for your a field, you have to make sure to add a Rules condition Entity has field (related to the  field for which you want to set a value). And make sure to add that Entity has field condition BEFORE other Rules Conditions in which you might want to refer to this field.

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

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

Webform requires another approach

However, for this specific question, which is about using Rules in combination with Webform, things are a very little bit more complicated, as further explained below.

Let's assume I have a webform created with some of its fields with machine names like so:

contact_us_first_name.
contact_us_last_name.
contact_us_subject.

After you add these fields (with identical machine names) to any of your own forms, you should be able to import the prototype-rule below (using the Rules UI) in your own environment (without running into an integrity constraint):

{ "rules_create_a_node_from_a_submitted_webform" : {
    "LABEL" : "Create a node from a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "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." } }
    ]
  }
}

In the above rule I included an extra Rules Condition to prevent the Rules Action from being executed for anonymous users (feel free to adapt the role id of it, or just remove that Rules Condition). And the rule is triggered via Rules Event "After a webform has been submitted".

The Rules Action only displays an (informational) message on the site (my recommended way of writing and debugging Rules ...) after a webform gets submitted. Here is what I specified (in the Rules UI) as the message to be shown:

  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 "[data:contact_us_subject-title]" which has value "[data:contact_us_subject-value]".

Here is a sample of the message shown in my own setup:

  The webform component submitted by Dries (= First name:) Buytaert (= Last name:) contains a field labeled "Subject:" which has value " Rumour goes that the Rules module for D8 is making progress! ".

What the above prototype-rule shows is that the "clue" to answer your question is that you have access to all labels and all values of any field of a webform available, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

All that's left to fully answer your question now is to correct your Rule using similar tokens.


Installing Drupal with existing Pantheon site? First, I am completely new to, well, all of this... So I'm sorry if I sound like an idiot. I have been fighting with this thing all day, and I think I'm more confused then when I started. I work for a non-profit, and I'm supposed to be helping our web designer with the new website. He uses Drupal and Pantheon. His instructions were something to the effect of "Download the repositories from Pantheon, install Drupal, and point Drupal to the repositories" Yeah... I downloaded the stuff from pantheon using Git, so I think I at least did that part right, but I have no idea how to install Drupal. I have read half a dozen different manuals, all of which tell me to do different things, most of which I don't understand. And our web designer can't help me because he doesn't know how to do any of this on a Windows box. (He's a Linux guy). Help??

I'm using Windows 7 Ultimate.

To install Drupal on an existing Pantheon site you don't need to install or copy anything to your local computer; you can just work on the Pantheon development environment in the cloud using the dashboard workflow. Pantheon hosts three distinct environments for each site: development, testing, and the live production site. You can install Drupal plus modules and themes on your development site. Once you're satisfied with the results, you can push your site code to the test environment for user testing and then to the live environment to serve the site from your domain, once you've launched with a paid site. The workflow tools let you push code from dev->test->live, and also clone your database and files between environments. Typically you'll install Drupal and configure the modules on the development environment before launching the site, then clone that database up to live to retain all the content changes. However, post-launch you would only want to copy the live database and files down to development and testing environments, as the live production environment is the canonical source of site content. You'll want to review Pantheon docs for how to use the workflow, both pre-launch and post-launch:

https://pantheon.io/docs/articles/getting-started/


How to add a new responsive Layout for large viewports to Omega Theme I would like to add another Layout to the Omega-Theme Settings, because i need a certain media-query for an extra-large viewport. I tried adding a new setting to the .info-file but without success.
Maybe this will be possible only by adding a new media-query directly to the css-file?

You need to copy the grids variable from the default alpha.info file, and add your new layout in your theme's .info file like so:

grids[alpha_default][name] = Default (960px)
grids[alpha_default][layouts][fluid] = Fluid
grids[alpha_default][layouts][narrow] = Narrow
grids[alpha_default][layouts][normal] = Normal
grids[alpha_default][layouts][wide] = Wide
grids[alpha_default][layouts][wider] = Wider  <- Your custom layout
grids[alpha_default][columns][12] = 12 Columns
grids[alpha_default][columns][16] = 16 Columns
grids[alpha_default][columns][24] = 24 Columns

# Default settings for the new layout
settings[alpha_layouts_alpha_default_wider_responsive] = '1'
settings[alpha_layouts_alpha_default_wider_media] = 'media query here'
settings[alpha_layouts_alpha_default_wider_weight] = '4'

You'll also need a new CSS file (called THEMENAME-alpha-default-wider.css) to manage CSS for that layout, but Alpha/Omega should handle the rest for you.


How to properly add JavaScript to drupal I'm trying to create a module that will make use of Google Maps to display the current places indicated in the search results via markers. The problem that I'm having is that I'm getting the following error when I add the Google maps script:

Uncaught ReferenceError: jQuery is not defined

The map wouldn't work if I don't include my own version of jQuery, but the error stays there whether or not I include jQuery.

function gmapsnrew_block_view($delta = ''){
    $block['subject'] = 'Google Map Test';
    $block['content'] = '

';
    return $block;
}

drupal_add_css(drupal_get_path('module', 'gmapsnrew') . '/css/gmapsnrew.css');

drupal_add_js('http://maps.googleapis.com/maps/api/js?key=google_key&sensor=false&libraries=places');

drupal_add_js(drupal_get_path('module', 'gmapsnrew') . '/js/load-map.js');

And the load-map.js looks something like this:

(function ($) {
  Drupal.behaviors.gmapsnrew = {

    attach: function(context, settings){

      console.log(context);
      var base_lat = 51.322377;
      var base_lng = -0.1358427;

      var latlng = new google.maps.LatLng(base_lat, base_lng);
      var options = {
          zoom: 10,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          mapTypeControl: false
      };
      var map = new google.maps.Map(document.getElementById("map-canvas"), options);
    }
  }

})(jQuery);

Any ideas what I'm doing wrong here? Thanks in advance.

If your code sample is accurate, and you are calling drupal_add_js() from outside a function in a module file, then that will be the problem.

You would want to add your js from within your hook_block_view().
This way it loads after drupal has done all it needs to do with its js and jQuery will exist.

Also, you might not want to put your map initialisation in a behavior, because you would usually only ever want your map to load once, on page load.
I don't know all the details of your setup though so I can't know exactly what is best in your case.


Finding variables available in preprocess node or node.tpl.php from cck fields Would really appreciate help resolving this. I am using D7 and the devel module is not an option, for some reason it causes some problems with my site. I have looked into the contemplate module but see it isn't supported in D7, otherwise it would be great. Is there any quick way for me to see all my variables so I can utilize them in a preprocess function?

Yes, you can do something like this in a custom module:

function YOURMODULE_preprocess_node(&$vars) {
  drupal_set_message('
' . print_r($vars, true) . '
');
}

or this in your theme's template.php file:

function YOURTHEME_preprocess_node(&$vars) {
  drupal_set_message('
' . print_r($vars, true) . '
');
}

If that's too much information, you can get just the variable names with:

 foreach ($vars as $name => $value) {
   drupal_set_message($name);
 }

instead of print_r()ing the entire array.


Why does my drupal 7 redirect me to the home page from any link? I have just enabled clean URLs via admin panel, but now...

it doesn't matter what I click, all my urls redirect me to my home page.

you can try for yourselves by clicking any of the links: http://www.gelpalhano.org/drupal/

and none of the admin links work either, so I can't even disable clean URLs to make sure that is the problem. logout also does not work.

any light you can shed on this will be much appreciated.

It looks like you redirected the default user login page to somwhere else.

When I go to http://www.gelpalhano.org/?q=user, I get a HTTP 302 moved temp, followed by a 301 moved perm, followed by a 200 OK to http://www.gelpalhano.org/site/ (what appears to be your homepage).

Generally clean-urls would fail because your .htaccess if not configured properly, or because your web server is not configured properly. I saw your web host's headers say that the server is of type Microsoft, so I would not be able to suggest a fix for your particular setup (I only use the LAMP stack).

I can suggest however that to regain back access to your site, you substitute www.gelpalhano.org/?q=user for www.gelpalhano.org/?q=[the relative path to your user login page], and then once you've logged in, you can go to www.gelpalhano.org/?q=[the path where you turn on/off clean urls] and turn them off while you trouble shoot the issue. IMHO, this is a server setup issue, and I think you have more chances of having your issue resolved by researching and posting the same question at serverfault.com. Good luck and hope that my answer helps.


Filter by field user role permission I have created View permission field in the events content type. Its field type is Role, so I can select which roles can see the node.

This works fine, but when I add events content type in the view this will displays all the data. I want to filter the data by the View permission field for the currently logged-in user.

I want to show data to the roles which I selected in the node View permission field. I have tried with contextual filter with user:uid, but I don't get what I am expecting. Actually, I don't know how to do that.

How can I achieve this?

Note: I want to integrate with my content type field View permission. I will select a role in View permission field. That roles only can see the view result.

It sounds like the only requirement here is a per-node, role-based, permission setting on content. If that's the case, I'd drop your role reference field in lieu of Content Access. The module enables such a requirement and it hooks deeper into the Drupal permission system so you don't have to build a bespoke permission checking for every situation (e.g. views access, node page access, etc.).


Passing arguments to a node with an alias url There is a similar issue in here:
Passing an argument to a node causes 404

But there is no real viable solution.
I tried using the sub-pathauto module but the restiction of 8 arguments is too little, since the urls will look something like this:

www.site.com/alias/key/value-1/key/value-2/key/value-3/key/value-4

and it can go on for a while.
It works when instead of alias i have node/nid.

Is it possible to have it work with any amount of dynamic arguments?

Iv'e not tested with more than 8 args, but I enabled path_alias_xt when passing args to a node Alias with /mynode/term-name/tid and the 404s magically went away.

https://www.drupal.org/project/path_alias_xt

Further more using
print_r(arg(2));
in the node template prints "term-name"


Lost CSS when authentifification I made a custom theme based on bartik.

In this custom theme I add just one CSS file and a very simple specific view template file.

When I am connected with a user with 'Administrator' Role all is OK. It means that my customed class are loaded an applyed

But when i am connected with a user without 'Administrator' Role all is KO. It's like my customed class are not in the theme.

Any Idea ?

Finaly I found the problem.
The real problem was not because the user had this or this role.

But the view that i wanted to show had specifc class for some objects for user with Administrator Role.

Example :
an 'article' can have 'contextual' class when the user connected had Administrator Role.
the same 'article' does't have it  when the user connected didn't have Administrator Role.

I am new in drupal 8, so...


How to hide empty fields on user accounts display? Let's say a profile2 has 3 fields.

Weight:
Height:
Length:

The user only inputs 45 kg and 160 cm, BUT for length he inputs nothing.

Now the display is like this:

Weight:45kg
Height:160cm
Length:Select

How can I hide the field that had no input like this:

Weight:45kg
Height:160cm

Since the user didn't select any value for length, and it's not a required field. I don't want it displayed on the user profile.

I know this can be done with Views and no results behavior, but I need this for user profile display.

Here is a live example:

http://vuxi.com/users/nitap

One way to look at this use node.tpl for this node type and add a php check like the following:

 <?php if(!empty($content['your_field_name'])): ?>

<?php echo t('Your Label'); ?>

    <?php print render($content['Your field Name']); ?>
 <?php endif; ?>


How to award User Points after checkout using Rules? I'm trying to award some User Points to users who select a certain plan during his checkout process.

Here is the explanation of my website functionality.

When a user register with a role, the user will get access to the website with certain functionality.
Some users will be having permission to create new nodes.
During the node creation, the user needs to select a plan (I'm using Commerce Node Checkout module to add product as plan).
Based on the user's selection, the user will be redirected to the checkout page.
After completion of the checkout process, the user will receive some User Points. For this I have created a rule, but it is not working as expected.

Here is the export of my rule:

{ "rules_per_day" : {
    "LABEL" : "Per day",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "per day" ],
    "REQUIRES" : [ "commerce_order", "userpoints_rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "commerce_order_contains_product" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "product_id" : "day_4dxivfX2oFRAqQH-Ij6VBFnBheZBRIo744cF46KKPSI",
          "operator" : "=",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "50",
          "tid" : "0",
          "entity" : [ "commerce-order" ],
          "description" : "You have received  the points for selected plan.",
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "approved"
        }
      }
    ]
  }
}

The Rules Condition checks whether the order contains a specific product withe the product id n.

I don't understand what I did wrong or what I have missed in this rule. Any suggestions to make this rule work?

In order for your Rules Condition to be satisfied, ALL these criteria must be true:

Order contains the product whereas the SKU of that product must be "day_4dxivfX2oFRAqQH-Ij6VBFnBheZBRIo744cF46KKPSI".
The quantity of the specified product on the order must be "= 1".

Since the user does not seem to receive the userpoints, it must be because of either of these reasons:

Reason 1: your Rules Condition is not satisfied. Assuming that there is no typo in the SKU value, it could be because the quantity is NOT "= 1".

As a quick check to find out if this is what is causing your issue, simply do a test in which you (temporary) change this rules condition to the opposite, by using the "negate" checkbox for that Rules Condition. If in that scenario the userpoints are granted, you can be sure that the quantity is indeed NOT "= 1" (even though you may think/expect that to be the case ...).
Reason 2: your Rules Condition is OK, but your Rules Action for some unknown reason does not actually grant the points to the user.

As a quick check to find out if this is what is causing your issue, just add another Rules Action (before the one you have already) to simply "Display a message" (which you find within "System"). All the message should be is something like "Rules Action triggered". If in that scenario such message is actually shown, you can be sure that the cause of your problem is something related to your Rules Action (to grant points) that is not working as you think/expect it to work.

If none of the above helps, then it's time for Rules debugging, as detailed in "How to debug a rule that doesn't want to fire?".


multi page content drupal 7 So i want to create a website which presents information about topics over multiple pages, i.e. say the content was films, one page would be an overview of the film and there would be a button at the bottom which would pull up the films cast etc (think like a multi step signup form).

My current thinking is I could create this as a series of views so have like one view that links to %film/overview, %film/cast etc. As I am still pretty new to drupal I thought I would ask here whether this was the best way to present this type of content, or if there are better options?

Thanks.

The Best way is to do it with core Book module

  A book is a set of pages tied together in a hierarchical sequence,
  perhaps with chapters, sections, subsections, and so on. You can use
  books for manuals, site resource guides, Frequently Asked Questions
  (FAQs), or whatever you'd like.


Is Drupal forum module suitable for a massive forum If I use the Drupal forum module (not the advanced forum module) to create a forum website (30 replies per page) and if the forum grew to a massive forum, will this module decrease the performance?

Drupal is caching the comments separately, will that going to be a problem?

It depends on how 'massive' is your forum, what level of control you expect to have on the forum and how powerful and well configured is your server. There are Drupal forums with couple of hundred thousand users that work kind of fine, but if your main goal is to have a large and capable forum, you get much better performance and features out of specialized forum software like VB.

While Drupal forum provides rudimentary functionality, you will have hard times attaining many common specialized forum features like assigning different moderators to each forum, post thanks (which exists in D6 but not in D7), merging threads, banning users for certain amount of time, limiting posts/threads per day, and the list goes on and on.

The only pros that I can think of is integration to Drupal core, which makes sense only if you already have a Drupal site.


[function.unserialize]: Error at offset I initially came across this error while I migrated my site from local server to live server.

Notice: unserialize() [function.unserialize]: Error at offset 83 of 108 bytes in variable_initialize() (line 935 of /home/ebemorgi/kog.church/includes/bootstrap.inc).

I followed #9 from this drupal post , then I found out that
the variable causing the issue was authorize_filetransfer_connection_settings_ftp.

I deleted the above variable but that hung up my whole website.

Then I deleted the content in the variable table and re-populated it.
Initially the error didn't popup but when I tried installing a new module at the live server the error
popped up with an new offset value. Again the villain is authorize_filetransfer_connection_settings_ftp.
The error which I am now receiving is :

Notice: unserialize() [function.unserialize]: Error at offset 32 of 121 bytes in variable_initialize() (line 935 of /home/ebemorgi/kog.church/includes/bootstrap.inc).

I have made sure that I have updated the ftp details in my mysql dump file before importing it to live DB.

I'm not sure if this issue is related to Core, but I don't honestly know under which product to list it.

Any help is appreciated.

It looks as though you have invalid serialized data for that authorize_filetransfer_connection_settings_ftp variable.

If saving to the db manually, make sure you have serialized the data prior to db storage.

Some ways to set the variable include

variable_set('authorize_filetransfer_connection_settings_ftp', $value);

and

drush vset authorize_filetransfer_connection_settings_ftp 'value'

The former is a bit easier if setting an array value, otherwise you can do something like this with Drush:

drush php-eval 'variable_set("authorize_filetransfer_connection_settings_ftp",array("key1" => "value1", "key2" => "value2"));'


Entity difference between fields defined in the entity itself and the external fields When defining an entity (using e.g. Drupal console) some fields are created in the entity, these fields are stored in the entity-table. Afterwards you can add fields to an entity, these fields are stored in separate tables.
I see that in the entity-source you can add fields later on.

What is the difference between 'internal' fields and 'external' fields??

The 'internal' fields are base fields, defined in the entity type definition. The 'external' fields are bundle fields, defined in configuration, which can be exported and imported to yaml, and is configurable in UI.

Content entities that have no bundles can have bundle fields, for example the user entity. In this case the id of the bundle is that of the entity.

More information https://www.drupal.org/docs/8/api/entity-api/introduction-to-entity-api-in-drupal-8, especially this chapter https://www.drupal.org/docs/8/api/entity-api/defining-and-using-content-entity-field-definitions.


How can I invoke Drush command inside hook_cron? I have module that provides drush integration.

Now I want to create modules with hook_cron where I want to launch drush command.

How can I run Drush command programmatically?

You should not call drush from inside a Drupal module.  Instead, factor out the functionality of your Drush commands into separate functions that can be called from module code and drush commandfiles alike.  Your module code should do all user access / permissions checks before calling the API functions (usually via the access checks provided by Drupal's menu system); the Drush commands should call the API functions directly, without access checks.


Undefined index $base_path in include(), line 7 of page--front.tpl.php I receive this error message in my pages; strange enough, it doesn't appear in the front page.

  Notice: Undefined index: $base_path in include() (line 7 of /home/kinderen/kinderenenislam.nl/sites/all/themes/kei2/page--front.tpl.php).

Where should I include $base_path?

$base_path is a global variable which should definitely be available in your theme's page template files.

I would guess your theme is doing something to remove that var (perhaps in a preprocess function). You can easily solve the problem using one of the following:

Using a call to the base_path() function instead of $base_path.
Using $GLOBALS['base_path'] in place of$base_path`.
Adding the line <?php global $base_path; ?> to the top of your page template file(s)


How can we associate an image & textfield with a specific Domain in Drupal 7? I am using two subdomains in my drupal project. I would like to associate image and textfields with specefic domain only.

Domain Fields module works for me as it restricts fields to specific content type on specific domains.


What hook runs on all filtered input text of all filter types? This is one of those, "Looked everywhere in the API for a hook, can't find it" questions. There must be a hook like I'm looking for, but none of my searches have found anything.

I'm looking for a simple hook in D7 that lets me edit text filtered content, after it's gone through a text input filter, before it's saved: regardless of which input filter, and regardless of entity type (i.e. not just nodes).

I can't find a suitable hook. The new-style hook_filter() alternative hook_filter_info() isn't suitable because I want this code to run on all input filters, so I don't want to define a new one.

hook_node_save() is too specific. I could maybe hook on hook_entity_presave() then load field info, then look through all fields looking for fields that are longtext fields, then act on those, but I'm hoping there's something more direct. That sounds like a lot of extra work for something simple. I'd prefer not to have every single entity save load all the field info and check every field (unless there's a very low-overheads way to do that).

What's the simplest, cleanest way to get code to run on all text that has gone through an input filter, regardless of the input filter?

Here's my best clunky workaround so far:

  <?php
  function mymodule_entity_presave($entity, $type) {
  $fields = field_info_fields();
  foreach($fields as $field) {
    if ($field['type'] == "text_long" || $field['type'] == "text_with_summary") {
      if( isset($entity->{$field['field_name']}) ){
        foreach ($entity->{$field['field_name']} as $langcode => $items) {
          foreach ($items as $delta => $item) {
            $value =&$entity->{$field['field_name']}[$langcode][$delta]['value'];
            $value = _mymodule_do_stuff( $value );

            if ($field['type'] == "text_with_summary") {
              $summary =&$entity->{$field['field_name']}[$langcode][$delta]['summary'];
              $summary = _mymodule_do_stuff( $summary );

            }
          }
        }
      }
    }
  }
}

Not ideal at all, but I think it beats the only non-core-hacking alternative I can see which is to use hook_field_attach_presave();. The code would be almost identical, and I believe it would be worse since we'd have to call and loop through field_info_fields() once for every field on every saved entity (instead of once for every saved entity).


Drupal doesn’t create clean links – checkbox doesn’t do anything After migrating my Drupal 7.27 site to a new server, I can’t get Drupal to re-enable Clean URLs.

The .htaccess file works and I can access clean URLS, but Drupal doesn’t create clean links. (For example, /admin/config/search/clean-urls works fine, but the link in Drupal points to /?q=admin/config/search/clean-urls.)

The clean URLs configuration page doesn’t say anything about the test, but offers me the option to enable clean URLs:

When I do that, it says the configuration options have been saved, but the checkbox is still unticked:

I also manually changed the settings.php to include $GLOBALS['conf']['clean_url'] = 1; but that doesn’t help either.

Does anyone have any ideas why this is happening and how I could get Clean URLs to work properly?

1)enable rewrite module on apache.

a2enmod rewrite

(to disable type a2dismod rewrite)

2)Set directory permission.
You must find the file that sets permission of each directory for apache. In my case it was /etc/apache2/sites-enabled/000-default
edit the page so that the directory that you will be using to serve webpages has "AllowOverride All". My file contains the following:

Options Indexes FollowSymLinks MultiViews

AllowOverride All

Order allow,deny

allow from all

3)Just restart apache and it should be working:
/etc/init.d/apache2 restart

There are several other checkpoints to fix this issue. All the points are discussed here


Colorbox not working in new content type I have Colorbox and the plugin installed, and enabled.

The module is in the sites/all/modules folder, and the plugin is in the sites/all/libraries folder.

I've created a new content type and called it Image Gallery.

I've created a new field for that content type also called Image Gallery

The display format for my Image Gallery field is set to Colorbox.

I can create an image gallery, but the images are not opening in Colorbox. I'm stuck, the console isn't showing any errors, as far as I know everything is configured right but it's not displaying properly. What am I missing?

This problem might occur because the path to library is incorrectly set. It is typically like so:

libraries\colorbox\jquery.colorbox-min.js

Though via /admin/config/media/colorbox it is possible to set some other path for it (within 'advanced settings').

There was a time (some older version in colorbox) that the solution was to correct the path to the Colorbox plugin directory, so that after unpacking it looked like so:

sites/all/libraries/colorbox/colorbox/jquery.colorbox-min.js

Refer to issue #1906156 for more details on this.

If that doesn't help, then check if there are any other modules that use Colorbox that are trying to find it on this path.

Of course, make sure also that the "permissions" to the plugin are set correctly (if no read access is granted, then that is probably what is causing the problem).


Improvements in Drupal Gardens way: How do I place an input filter selector in CKEditor? I would like to know how to achieve two improvements in WYSIWYG in the same way Drupal Gardens does.

The first one is to place Input filters selector as a dropdown selector within the WYSIWYG toolbar, which saves a lot of space and looks cleaner.
The second one is to place two tabs in order to switch from HTML code and WYSIWG Editor.

I created a site and exported the file as to see which modules Drupal Gardens uses, but I didn't find the correct one.

This is the code responsible for those modifications.

(function ($) {

Drupal.gardens_misc = Drupal.gardens_misc || {};

Drupal.behaviors.gardens_misc = {
  attach: function(context, settings) {
    if (typeof CKEDITOR != 'undefined') {
      // Bind events to handle enabling and disabling of the WYSIWYG.
      CKEDITOR.on('instanceReady', Drupal.behaviors.gardens_misc.instanceLoaded);
    }

    $('.wysiwyg', context).closest('.text-format-wrapper').once('wysiwyg-tabs', function() {
      var $tabs = $('

').insertBefore($(this).find('.form-textarea-wrapper'));
      $('
' + Drupal.t('WYSIWYG') + '
')
        .bind('click', this, Drupal.behaviors.gardens_misc.tabToggle)
        .appendTo($tabs);
      $('
' + Drupal.t('HTML') + '
')
        .bind('click', this, Drupal.behaviors.gardens_misc.tabToggle)
        .appendTo($tabs);
    });
  },
  instanceLoaded: function(event) {
    var $wrapper = $(event.editor.container.$).closest('.text-format-wrapper');
    var $original = $wrapper.find('.wysiwyg');
    var $clone = $original.clone().val($original.val());
    $clone.bind('change', function(event) {
      $original.val($clone.val()).change();
    });
    $wrapper.find('.cke_toolbox').removeAttr('onmousedown').prepend($clone);
    $wrapper.find('.wysiwyg-tab.enable').addClass('wysiwyg-active');
    $wrapper.find('.wysiwyg-tab.disable').removeClass('wysiwyg-active');
  },
  tabToggle: function (event) {
    if (!$(this).hasClass('wysiwyg-active')) {
      $(this).closest('.text-format-wrapper').find('.wysiwyg-toggle-wrapper a').click();
    }
  }
};

/**
 * Overides the default attach behavior for text formats without an editor
 */
Drupal.wysiwyg.editor.attach.none = function(context, params, settings) {
  var $field = $('#' + params.field);
  var $original = $('#' + params.trigger);
  var $clone = $original.clone().val($original.val());
  var $container = $('

');
  $container.append($clone).insertBefore($field);
  $clone.bind('change', function(event) {
    $original.val($clone.val()).change();
  });

  // @todo: Need to display the allowed tags here
  var tags = Drupal.settings.wysiwyg_formats[$original.val()];
  $('' + Drupal.t('Allowed tags: ') + '' + tags + '').appendTo($container);

  // Original behavior
  if (params.resizable) {
    var $wrapper = $field.closest('.form-textarea-wrapper');
    $wrapper.addClass('resizable');
    if (Drupal.behaviors.textarea.attach) {
      Drupal.behaviors.textarea.attach();
    }
  }

  $field.closest('.text-format-wrapper').find('.wysiwyg-tab.enable').removeClass('wysiwyg-active');
  $field.closest('.text-format-wrapper').find('.wysiwyg-tab.disable').addClass('wysiwyg-active');
};

/**
 * Overides the default detach behavior for text formats without an editor
 */
Drupal.wysiwyg.editor.detach.none = function(context, params) {
  $('#' + params.field).siblings('.wysiwyg-none-header').remove();

  // Original behavior
  if (typeof params != 'undefined') {
    var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first');
    $wrapper.removeOnce('textarea').removeClass('.resizable-textarea')
      .find('.grippie').remove();
  }
};

})(jQuery);;

Save the above in its own file e.g. drupalgardens_wysiwyg.js, then either add the script to the .info file of your theme/module or add the file on the relevant page(s) using drupal_add_js or via the #attached property of a form/render array.

To get this to work on a non-DrupalGardens site, I had to comment out the two lines below the @todo comment around line 53. You may need to further tweak the code depending on how you have your wysiwyg profiles configured.


What is the protocol for adding a new module dependency to a module that has only had a dev release? I created a module a while ago and it has only had a 7.x-1.x-dev release on Drupal.org for the last month or so. There are a number of reported downloads and installs already for this module so I want to make sure that the handful of users that already are using this module are still considered in the next dev release I need to make. The new release will have a new module dependency that is from another project (i.e. not included as a submodule of mine). While I would normally create a 2.x version if the module had a stable release, it has only been in dev. Do I just go ahead and add the new dependency in the 1.x-dev or create a 2.x-dev?

There's no sanctioned protocol for such a case. All I think of is to minimize the impact.

Consider that even if you create a new branch, users may update and neither realize there's a new dependency, and your module may end up silently disabled because of unmet dependencies. This happened to the update of views from 6.x-2.x to 6.x-3.x where a dependency on ctools was added. In that case, the impact was low because ctools usually is present.

On documentation, in addition to changelog or upgrade doc in the project page, I suggest to add it to the release notes. Since they can be read easily when updating with drush.

Last, if the dependency you're introducing is a popular module, you can alleviate the impact by enabling the new dependency in hook_update_N or raising an error if not available. Here's some untested code:

<?php
function MODULENAME_update_7001() {
  $enabled = module_enable(array('foo', 'bar'));
  if (!$enabled) {
    throw new DrupalUpdateException('foo required.');
  }
}


Invalid Signature in Services Oauth When using the Services API with a PUT request, it returns an error saying that the signature is invalid. When working with POST I was getting access denied because the bundle was specified but this seems to be completely different.

401 Unauthorized : Invalid signature 21
["Invalid signature"]

For testing purposes, "Cache pages for anonymous users" and "Cache blocks" are both unchecked. I cleared the cache once to make sure it wasn't that.

It appears to be that the server generated signature does not match, but I saw the answer below, and the two signatures are completely different, not just missing a plus sign. I was able to log the signatures that the server sees to the devel debug log.

Service request with OAuth (Invalid signature error)

One thing I noticed which I wasn't sure about is that the base string that got logged for the request on the server started with GET, but this is a PUT request. Is that normal or could that be a bug in the implementation? My Oauth client is using PUT as the method.

Update: In looking into it, that does indeed seem to be the problem or at least part of it.

if($_SERVER['REQUEST_URI'] == '/api/rest/resource/18.json'){
    die('hi put' . $_SERVER['REQUEST_METHOD']);
}

The above code inserted at the beginning of index.php gives me hi putGET. However POST works perfectly fine.

My access log has this line

"PUT /api/rest/resource/21.json HTTP/1.1" 401 21 "empty referrer" "My User Agent String"

Once I figured out that the access log was different than the $_SERVER variable, I called my hosting provider and discovered that their servers are only configured to allow GET and POST (haven't checked HEAD).

So I invented this hack to use the header, since it seems that Apache just transparently changes unrecognized methods to GET.

if( isset($_SERVER['HTTP_X_REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
    $_SERVER['REQUEST_METHOD'] = $_SERVER['HTTP_X_REQUEST_METHOD'];
}


how to pass multiple view fields to an action via vbo in D7? I have a view relating different types of information together.
I have a node type and 2 relation types. The base node is related to other nodes using the 2 relations.

Lets say there are 3 fields in the view listing: the base node and 2 other nodes related to the base node:

nid of the "base node"
nid of a related node (using relation1)
nid of another related node (using relation2)

I like to do some action with the base node using views bulk operations.
In this custom action I like to use the nids of the other 2 nodes.

My problem is, you can only use one of the three nodes in the action, depending on what you selected in the bulk operations field.

Is there a way to pass ALL three nids?

I know I can use views php to create a hidden field, containing the other two nids and then use the hook_form_submit to hook into the submitted form.

But is there a more elegant way, only to use the custom action, without hooking the submitted views form?

You sort of can already.
Create the component with three arguments. It will pass the selected node to the first argument. On the second page of VBO you'll have two more fields to fill in. You can enter tokens here e.g. [yourrelationfield1] for fields of your view.


Disable email user notifications It's possible in Drupal 8 disable all users notifications? New account, forgot password, etc

I'm using one external tool to send these emails and I don't need these notifications.

Thanks

One of the easiest ways to make sure no emails are going out is to add

Mailcontrol (https://www.drupal.org/project/mailcontrol) which lets you specify what emails go out.

or

Maillog (https://www.drupal.org/project/maillog) which logs all emails and has an option to not send any emails to users. This will prevent all emails from leaving the system and log them if needed. It was designed to test sites but works well in this use case also.

Your other option is to go through and handle them one by one via code. There is no easy button inside of Drupal that will just turn off the service that I know of.

Sorry to just recommend a module, but given your needs this seems like a pretty obvious choice.


How to mark a Message as 'viewed' when a user sees it in a View? I'm displaying a user's Messages (created with the Message module) in a View. I'd like to flag them once they're viewed and thought that a Rule could do this easily. I've set the Rules Event to "A message is viewed" and the Rules Action to "Flag a message", but for some reason the viewing event is not triggered. I tried hovering the Message, visiting the referenced node's page and visiting Content > Messages, but nothing runs the Rule.

Did anyone experience the same problem before? Maybe this is a bug in the Message module (I've reported it at https://www.drupal.org/node/2291695), but I'd like to know whether you've already found a solution for this.

Ultimately, I'd like the Rule to be activated when a user hovers the Message or clicks it (I've already made sure that he/she will then be redirected to the referenced node/comment).

I will go about this differently. Create a non-global flag on the message (ie for each user) and only give flag action (not unflag). Do not auto display this flag.

Then in your view you add the flag action as a field on the row and test whether it works by clicking on it (to test you could give temporary unflag permission). When it works to you satisfaction hide the flag link via css, and add some javascript to click the flag if the row is hovered (or whatever) over. And set the Javascript up so that it can only activate the link once as one can sometimes fire off multiple events when on the border of an element.

And then just add you rule to fire when the message is actually viewed to cover that angle as well as the user may go to that path from somewhere else but your view.

EDIT: jQuery example code:

This code is for a flag called 'test', and a view called 'all', jQuery version 1.7+

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
        attach: function(context, settings) {
            $('.view-all .views-row').once().on('mouseover', function(){
               // unbind this event handler so it only fires once
                $(this).off('mouseover');
                // get the flag and click it.
                $(this).find('.flag-test a.flag').trigger('click');
            });

            window.alert = function(text) {
            // Prevent unwanted ajax errors when navigation away
            return true;
        };
        }
    };

})(jQuery, Drupal, this, this.document);

One other little issue is that views does not seem to respect the flag unflag permissions per role. I circumvented that by adding a field 'Flags: Flagged (A boolean field to show whether the flag is set or not.) and setting its output to 0/1. I then hid this new field as well as the flag link, and added a Global PHP field with this Output Code, and it worked like a charm:

<?php
if (!$row->flagged) print $row->ops;
?>

There is a possible patch for this behaviour at Flags: Flag link views field should respect permissions, but I have not tested it.


Creating and Linking anchors using CKEditor I am using CKEditor in my drupal 7 website. I am designed a new content type, in which I am writing about project activities in the following manner.

(1) Project A [anchor]
     This project describes about the design and analysis of Binary Search Tree
(2) Project B [anchor]
     This project describes about the design and analysis of Red Back Tree

Now, from a different page, I want to provide a link to anchors in following way-

The Binary Search Tree [as described here] also called an ordered or sorted binary tree.

I wanted to know using CKEditor-

How to create links (anchors) inside a page?
How to add these links to text on a new page?

How to create links (anchors) inside a page?

There is an icon with a flag. You click on it and you create the anchor.

If the icon is missing, go to /admin/config/content/ckeditor , edit the respecive profile and customize the icons under section 'Editor appearance'.

  How to add these links to text on a new page?

You add a link as you would:


Fetch customer profile in a component rule I'm working on a multi-lingual webshop and I'm trying to create a system for commerce where an admin can accept or reject orders. I've done this by creating a view that lists all pending orders and then I'm using bulk operations with 'accept' and 'reject' buttons to send a list of selected orders too a component rule that changes the order status. This works fine, except that I also want to send an e-mail to the person who made the order when the order is rejected. Again, sending the e-mail is not a problem, since it is stored within the order, what I'm having trouble with is sending the e-mail in the customer's language.

The site allows for anonymous orders, so referring too the order's owner for the language is not an option. I can't store extra information in an order either, so I added a hidden field too the customer profile that stores the language. However, all I have to work with is the list of orders. When I try to fetch the customer profile I don't get access too the field values, only the profile's ID and User ID.

Is there any way to fetch the complete profile, or possibly even better, is there a way to send the language string as parameter too the component rule with from the view?

Which module you using for customer profile. Are you using user profile like profile_load_profile($account);


Commerce one-off products in admin interface Is there a way I can create the capability for an admin to add a one-off product when creating an order through the admin interface? (For example, it could have a SKU of "CUSTOM" but we'd need the ability to enter a custom description that would show up in the line item in the receipt).

These are for customizations that are not available to the general public/only available if an admin enters them and would only be useful one time, so creating a full-fledged product for each one is not feasible.

I have done some testing with Commerce Customizable Products but it seems to allow customizable fields on the front end, but not in the admin "Add Order" screen where I need it.

The line item title in 1.x is derived from the line item type's title callback. Your simplest option is going to be to define a new line item type, as you've surmised, and have its title callback pull the value from a field you add to the line item type and expose to administrators to edit. Alternately you could edit the various Views to render this field directly ... but then you'd still need some way to allow creating ad hoc line items on the back end.

Sorry, I wish it were easier.


Drupal 7/Zen - How do you move the header (field_image) image above the title on a page? How do you move the header (field_image) image above the title on a page?

Drupal 7/Zen Theme

This seems like it would be a simple thing to do. I've been messing around with trying to accomplish this by doing a few things suggested on other websites but cannot seem to get it to work.

I've tried editing the page.tpl.php file but that messes up my homepage.

I'm trying to do this without using panels or any other module.

Thanks!

If you want to change the page.tpl.php template file, but avoid it gets used for the front page, just:

Create the page--front.tpl.php file from the current page.tpl.php file
Edit the page.tpl.php file to move the image above the title

In this way, page--front.tpl.php will be used with the front page, and page.tpl.php will be used with the other pages.


Correct way to extended Field Settings I'm doing something that works fine but I get the feeling there is a better way.

I have managed to extend the field settings in the field's manage page to add two new checkboxes. The checkboxes in this case, allow the input form field to be rendered with a Bootstap Add-ON for things like £ signs via my themes template.php

Adding the checkboxes using hook_field_widget_form_alter seems ok (although checking for args is a bit rubbish).

It's the 'wangle' I have to do in hook_widget_validate to get the settings to be incorporated in to the other field settings and saved to the database that is a bit nasty.

There must be a nicer way to do it than that so the question is ..

What is the standard (or better than this) way to extend a field's settings without creating a new widget ?

For reference, here is my code, firstly the added checkboxes  :

<?php
/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  if (arg(5) == 'fields' || arg(4) == 'fields') {
    if (isset($element['value'])) {
      $name = $context['field']['field_name'];
      // PREPEND.
      $val = 0;
      if (isset($form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['pre_on'])) {
        $val = $form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['pre_on'];
      }
      $element['#element_validate'][] = 'village_widget_validate';
      $element['pre_on']              = array(
        '#title'         => t('Render Prefix as Prepend'),
        '#type'          => 'checkbox',
        '#default_value' => $val,
      );
      // APPEND.
      $val = 0;
      if (isset($form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['app_on'])) {
        $val = $form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['app_on'];
      }
      $element['#element_validate'][] = 'village_widget_validate';
      $element['app_on']              = array(
        '#title'         => t('Render Suffix as Append'),
        '#type'          => 'checkbox',
        '#default_value' => $val,
      );
    }
  }
}
?>

The silly 'wangle' in the form validation to get the custom added fields to save as proper field instance settings that can be reteived.

<?
/**
 * Form validation handler for village_field_widget_form_alter().
 */
function mymodule_widget_validate($element, &$form_state) {
  if (isset($element['pre_on']['#value'])) {
    $form_state['values']['instance']['settings']['pre_on'] = $element['pre_on']['#value'];
  }
  if (isset($element['app_on']['#value'])) {
    $form_state['values']['instance']['settings']['app_on'] = $element['app_on']['#value'];
  }
}
?>

And for completeness here is the counterpart in my template.php that checks for the settings and adds some markup.

<?php
/**
 * Implements hook_form_element().
 */
function mytheme_form_element(&$variables) {
  // Default suffix.
  $suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';
  // Check for field settings.
  if(isset($element['#field_name'])){
      if (isset($element['#bundle'])) {
      $field_instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
      if(isset($field_instance['settings']['app_on'])){
        // Our Bootstrapped suffix.
        $addoncls .= 'input-prepend ';
        $suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';
      }
    }
  }
  // Complied element.
  $output .= '
' . $prefix . $element['#children'] . $suffix . "
";
  return $output;
}
?>

The only bit of interest is the recalling via.

$field_instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
$field_instance['settings']['app_on'];

You can add extra field instance settings as part of you custom module using hook_form_FORM_ID_alter, e.g.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function FOO_form_field_ui_field_edit_form_alter(&$form, $form_state, $form_id) {
  $field = $form['#field'];

  // @todo: Consider adding extra condition.

  // Inject setting form element to an instance settings form.
  $form['instance']['settings']['pre_on'] = array(
    '#type' => 'checkbox',
    '#title' => t('Render Prefix as Prepend'),
    '#description' => t('Some description'),
    '#default_value' => isset($form['#instance']['settings']['pre_on']) ? $form['#instance']['settings']['pre_on'] : NULL,
  );
}

If you don't want to create new module for a single checkbox, consider adding this hook into your template.php file as part of your theme.


How to alter the URL path alias generated by content type programmatically? Our current url pattern is [node:menu-link:parents:join-path]/[node:title]. What we need is a way to not to include the parent menu link items and only include the child menu link items.

For example:

The expected output is the following:

When Any menu link is placed at the same level as "Fourth level 1" (under Top level), it should be ".com/Second-level1/Third-level-1/Fourth-level-3"
Current issue is that the URL is generated as ".com/Top-Level/Second-level1/Third-level-1/Fourth-level-3"
We want to remove Top level, Top level 2, top level 3, etc removed from URL path alias.
Depending upon the placement of the menu link item, it should always contain the menu links 1 level above (if applicable)
The expected url pattern for third level 2 (under Top level/Second level 1) is ".com/second-level-1/third-level-2"

Updated:

I ended up write a custom module to call the hook_alter using the pathauto that just removes the first part of the URL before the node save event.

You can use this module https://www.drupal.org/project/pathauto with this you define the custom path use token


Installing TinyMCE plugins on Drupal 7 with the WYSIWYG module I using Drupal 7 and the WYSIWYG module and the TinyMCE (3.4.2) plugin.
I want to install a plugin for TinyMCE.

I placed the plugin folder in the right directory.

sites/all/libraries/tinymce/jscripts/tiny_mce/plugins

However, the plugin doesn't show up in my configuration checkboxes for the WYSIWYG configuration.  What else do I need to do to enable a contributed plugin?

You need to inform the WYSIWYG module that you've installed a plugin, it won't know it's there otherwise. It will involve writing a small custom module.

Have a look in the wysiwyg.api.php and wysiwyg.api.js files included in the root of the  WYSIWYG module folder; there are examples and very good documentation explaining exactly what you need to do.

The most important (perhaps only) hook you'll need to implement is hook_wysiwyg_plugin()


Removing all validation on submit I have a multistep form with two submit handlers (save/submit), when "Save" is clicked I want to remove any validation applied to the node and have it's contents saved.

In my custom validation hook I am checking both the triggering_element and clicked_button for the correct button, I'm then removing  limit_validation_errors however this doesn't work. According to the api documentation it should though.

function test_workflow_form_validate($form, &$form_state) {
  if ($form['#form_id'] != 'test_application_assessment_form') {
    if ($form_state['triggering_element']['#value'] == 'Save') {
      $form_state['triggering_element']['#limit_validation_errors'] = array();
      $form_state['clicked_button']['#limit_validation_errors'] = array();

      $form_state['buttons'][1]['#limit_validation_errors'] = array();
      // Remove validation.
    }
    else {
      // Add in default validation.
      //$node = (object) $form_state['values'];
      //node_validate($node, $form, $form_state);
      //entity_form_field_validate('node', $form, $form_state);
    }
  }
}

I've removed the default node validation so my custom one is the only one present. Is there something else I'm missing?

Your '#limit_validation_errors' may be set when the form gets built, not when it's processed.

Hence in your custom *_form() function or a hook_form_alter(); not in *_validation() or *_submit().


How to hide title of any content type without using a module? I want to hide the title field of a particular content type (such as Article), but without using any modules.

How can I do this?

You could do it in template.php in your theme dir, technically not a module.

e.g:

/**
 * Implements hook_preprocess_node
 */
function MYTHEME_preprocess_node(&$variables){
  if ($variables['node']->type == 'article') {
    $variables['title'] = FALSE;
  }
}

Replace "MYTHEME" with your theme name and clear all caches at Admin > Config > Performance to apply.


Invalid URL Aliases in Drupal Nested Sites/Subsites - Main 404 I'm sure my title made no sense! But I'm really struggling with something and could use some assistance.

I inherited a Drupal-based website a few months ago, and it was my first exposure to Drupal.

The way this website is set up is that it actually has three separate Drupal installs. Clean URLs is enabled with aliases set up. I'm sure this was the complete wrong way to set up multi-site, but unfortunately it is this way for now and I'm not confident I could correct it without breaking many things.

www.website.com (1st Drupal Install)

www.website.com/success (2nd Drupal Install)

www.website.com/spa (3rd Drupal Install)

For awhile, everything was working fine. But at some point the URL www.website.com/success/thank_you, started to display a 404 error - but NOT /Success's 404 page - it would be the 404 display page of the base Drupal install! But still show www.website.com/success/thank_you in the URL

Other Aliases on /Success continued to work, etc www.website.com/success/online, www.website.com/success/privacy.

If I typed in a garbage URL, say, www.website.com/success/abcdefg, i would get the 404 page of /Success install like it should, not the base Drupal.

I managed to "fix" this issue by changing the URL Alias of /success/thank_you to /thankyou.

Now last week, it started happening with the other Aliases.

If I go to /success/thankyou it still works properly. If I do /success/online, or /success/privacy, I get the main Drupal's 404 page.

If I remove the Alias, I can do /success/node/20 and see the page. If I change the Alias to say, /success/online2 I can see the page. But if I change it back to /success/online, it does not work.

So, my current thinking has been that this is an issue with the base Drupal install, not the /success Drupal. That the base Drupal is grabbing that URL I am entering for some reason and seeing it's not an alias in that Drupal and failing. But why is it only happening to specific aliases? And why doesn't the base Drupal grab the URL if I type in a garbage one? (/success/abcdefg for example).

Any pointers in the right direction would be greatly appreciated.

Option 1 - base_url
Maybe you want to do some experiments to see if setting the $base_url in your settings.php somehow helps.
Option 2 - RewriteRule
It might be worth trying to further enhance your .htaccess file, by adding a line after the line containing RewriteBase, which looks like so:
RewriteRule . index.php [L]

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.


Extract the CSS class depending on the user type Is it possible to extract the PHP string for user type, when the user is not an administrator user?

I need to discern between staff or non-staff users. I am aware of $is_admin, but in this case I would need something like $is_staff.
I need this so I can apply CSS styles to hide/show some fields that I want to be visible only to staff users.

Is anyone aware if there's anything that might help me?

If $user is the user object, then $user->roles is an array containing all the roles the user has. Drupal doesn't have the concept of user type, and the user roles are the closest it has.

If you want to check if the user has the "editor" role, for example, you can use code similar to the following one:

$global $user;

if (in_array(array_values($user->roles), "editor")) {
  // The user has the "editor" role.
}

Depending on what you are trying to achieve, you could also be interested in checking if the user has a specific permission, which is what is normally done in Drupal, where instead of checking the role assigned to a user, it is checked which permission the user has (using user_access()).

As for hiding a form field, this can be done implementing hook_form_alter(), or hook_form_FORM_ID_alter() and altering the property "#access" of the form field.

Supposing that "example_form" is the form ID for the form you want to modify, and "file" is the ID for the form field to change, then you can use code similar to the following one ("mymodule" is the name of the module; change it to match the name of the module that contains the hook):

function mymodule_form_example_form_alter(&$form, &$form_state) {
  $form['file']['#access'] = user_access('administer file');
}

"Administer file" is the permission that the user needs to have.
Alternatively, if you want to only check if the user has the "editor" role, you can use code similar to the following one:

function mymodule_form_example_form_alter(&$form, &$form_state) {
  global $user;

  $form['file']['#access'] = in_array(array_values($user->roles), "editor");
}

The global variable contains the user object for the currently logged in user.


How to do field validation during migration? I've a user migration class as shown here.

However for some reason users are created with empty required fields (such as e-mail).

How do I implement custom validation of the field during migration?

So I can fail the validation for specific row and continue the migration? So the specific rows won't be migrated and they will appear in the list of the one which has error in it.

Is there any method for that?

You can accomplish this using the ::prepareRow() method on your migration class. You'll have access to the source field values in the $row variable. This method is called once for each record being imported, and returning FALSE will skip the row in question.

Example:

function prepareRow($row) {
  if (!validate_my_field($row->my_custom_field)) {
    return FALSE;
  }
}

More info https://www.drupal.org/node/1132582

For Drupal 8 you could accomplish the same by either implementing a custom source plugin with a prepareRow() method. Or by implementing hook_migrate_prepare_row() and performing your validation there.


How to make view mode available only to selected bundle? I have three taxonomy vocabularies which means that I have three bundles of the vocabulary entity type. I have a few view modes for them and one of them has to be available only to one of those vocabularies.

The method responsible for getting available view modes is \Drupal\Core\Entity\EntityManager::getAllDisplayModesByEntityType() but it does not distinct between bundles, only entity types.

Is there a way I can make that view mode restricted for that one particular vocabulary or this is just not possible?

No, there is not. A view mode is not bundle-specific.

That hardly matters, because a view mode doesn't do anything unless you actually enable it and configure field formatters for it, resulting in a view display. If you don't then it just falls back to the default view display.


Iterate over items in FieldItemList? In other words: How do I get the URI for each of the files in a file field that's on a custom content entity called 'listing'.
Right now I have:
$images = $variables['elements']['photos']['#items'];

Where $images is a FieldItemList
How do I iterate over my FieldItemList to grab the URI for each of the files referenced therein?
Ok figured first part out with:
 $images = $variables['elements']['photos']['#items'];
   $photos = $images->getIterator();
   foreach ($photos as $photo) {
     xdebug_break();
   }

Now the question is:
How to get the URI for each of $photo, and assign it as a variable...?

Update
After Berdir's Comment and my own investigation this is what I went with.
  if (isset($variables['elements']['photos']['0'])) {
    $number_of_photos = count($variables['elements']['photos']['#items']);
    $listing_pics = [];
    for ($i = 0; $i < $number_of_photos; $i++) {
      $pic = file_create_url($variables['elements']['photos'][$i]['#file']->getFileUri());
      $listing_pics[] = $pic;
    }
  $variables['elements']['listing_photos'] = $listing_pics;
  }

This is in a Hook_template_preprocess_HOOK(), and now all of the urls from my multi-value file field are available to the template like this {{ elements.listing_photos }}

PHP calls getIterator() for you, you don't have to do that. Also use $variables['node'], much easier to access.

File/Image references an extension of entity references, which means they inherit the computed ->entity property, which automatically loads the referenced entity. Make sure you check if the file can be loaded, or inconsistent data (if, for some reason, the file gets deleted. Less likely for files but could happen for node or other references) would result in a fatal error.

foreach ($variables['node']->photos as $item) {
  if ($item->entity) {
    $uri = $item->entity->getFileUri();
  }
}

$uri is something like 'public://your_file.jpg'. You can create a public url with file_create_url() or you can also pass it to an image style entity's buildUrl() method to get the URL for a given image style.

See http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for common ways to access field values, what properties exist for each field type and much more.


Create 3 Views blocks that display 1st, 2nd, and 3rd most recently created nodes How can you create three View blocks such that (based on a particular field value or taxonomy category or just content type) the first block displays the most recently CREATED (not updated) node, the second displays the second most recently created node, and the third displays the third most recently created node?

Create the 3 views blocks with your filters and order by created. Then change the Pager to Display a specified number of items.

For 1st block update the settings (it should say displaying X items) then update the Items to display to 1 and the offset to 0.

For the 2nd block do the same but change the offset to 1 and then for the third block set the offset to 2.

Untested but on a quick check of the options, this should give you what you are after.

Paul