add variable to process_page($vars) in form function Is there an option to change $vars array in form function? I would like to pass some variables to page template in form creation function .. If not, what are other options to influence page.tpl from form?

EDIT:
I have a function for form creation and i would like to add page class if some params are sent to this function.

function mymodule_test_form($form, &$form_state, $param){
  if ($param == 'special'){
    #add class to page
  }
}

thanks!

It seems to me that you are talking about two different things: altering form fields vs. modifying the $variables array in page.tpl.php.

1) When you say "form creation function", what I hear is that you want to change fields in an existing form. For this, you would want to implement hook_form_alter(). If you want to learn more about how to structure a form, visit the Form Generation page in the Drupal API.

2) If actually you meant that you want to add or change variables in your page.tpl.php file, then you'll want to implement hook_preprocess_page().


Filter images by 'current page' nid I have a view with multiple fields:

Nid
Title
Content
Image

On my page, I use the nid as a selector ( I have a button elsewhere on the page tied to it) to open my content without going to another page. The images are also loaded. Only problem I have is that I need to find a way to ensure that only the images for the view row's [nid] are being output, rather than all of them. The [nid]  filter requires a hard value and I'm looking more for a "current page" ish kind of thing.

Basicaly, I want to load only the images that have the same nid as the content being displayed in each row.

How would I set up a filter for this?

Edit your view
Create Block View
Add Contextual Filter

Add Content:Nid

In settings choose : Content Id from URL

Enable your block in your node pages where you would like to display images


How do I get the default user picture? I am using the following code to get the URL of the image associated to a user.

$user=\Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$picture=$user->get('user_picture')->entity->url();

If the user didn't upload a picture, this code doesn't return anything useful.

How can I get the URL for the default image?

User pictures are no longer guaranteed to exist in Drupal 8. It is added by the standard profile, but not added if you use the minimal profile.

The user picture is simply a image field attached to the user bundle, so normal file field API's can be used. To get the file path of the default image for the user picture field attached to the user bundle:

<?php
$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$file->getFileUri();
?>

I'm not sure what you are trying to achieve. If you are looking for better default avatars, then I encourage you to look at Avatar Kit for Drupal 8. Disclaimer: I am the developer of Avatar Kit.


How do I prevent D7's ajax_deliver() from loading CSS? For some crazy reason, using ajax_deliver() in a menu callback is causing 4 theme CSS files to be loaded into my page, breaking the page styles.

What I'm doing:

Using Seven as my admin theme
Created a basic admin page for a module
Admin page has a link (no form) which should return content via AJAX
Link points to a menu path which uses a custom callback
Custom callback uses the /nojs trick and returns content via ajax_deliver()

What's happening:

AJAX content is loading into the page just fine, working as expected
4 Bartik CSS files are being dynamically added to my admin page (using Seven theme)

Anyone experienced this? Any ideas on how I can prevent this CSS from loading?

Figured out the reason Bartik CSS was loading when the admin page was using Seven.

My admin page was located at /admin/mymodule/settings

My menu callback for the AJAX link was /mymodule/special-form

Because /mymodule is outside the admin area, the theme would be Bartik when actually visiting that page. So Drupal's AJAX system assumes I want the CSS that goes along with that page. Not a bug, but a feature to be aware of.


How do I link an image to a given URL? I'm using Panels to generate my front page. In one of the panes in my panel layout, I want to have an image which is linked to a given URL. The image and URL are going to be managed by my users.

I've been told that the Link module will give me a field type for URLs., and the Link Image Formatter module will let me link images to URLs; but I can't find any documentation on how to actually use the link image formatter. (EDIT: It turns out the Link Image Formatter wasn't about making href links, but just including images from a different domain.. or something, I'm confused.)

I've tried creating a content type with an image field, and a link field, but I can't find any way to connect them, or any way to associate an image with the link field.

EDIT: The URL may be internal to the drupal site or it may be external. These image/link combinations will be created and managed by the user through drupal. There may be 4 of them on the front page, but I may need to use them more later on throughout the site. They aren't unique to each user, I'll only have one admin user who will be posting all of the content on the site.

I want the user to add a piece of content. They'll upload an image and they'll define the URL they want that image to link to. Then in one of my Views/blocks, I can select that content type and show it in a certain region. It'll just show the image, but if a user clicks on the image, it'll take them to the specified URL which may be external to the site.

This seems like a wheel that should already have been invented, but I'm having trouble finding them.

How can I achieve this?

EDIT: I figured out what I was doing wrong... I think the person who suggested the Link Image Formatter module to me may have hastily picked the wrong url when they sent it to me and really meant to send the Link Image FIELD module which does exactly what I expected.

you can load a image from a node.

 $prev_node = node_load($prev->nid);
    $image = field_get_items('node', $prev_node, 'field_image');
     $img = field_view_value('node', $prev_node, 'field_image', $image[0], array(
      'type' => 'image',
      'settings' => array(
      'image_style' => 'thumbnail',
      'image_link' => 'content',
     ),
   ));

then if you get the image, linking image to a certain url can be easily done by

 $options = array(
            'html' => TRUE,
            'attributes' => array(
                'title' => $prev_node->title
            )
 );
 $output = l($img, "your url", $options);
 print render($output);


How can I get pragmatically all certain actions from Rules and Components? On rules settings page (admin/config/workflow/rules) and components page (admin/config/workflow/rules/components) you can specify action (like 'send e-mail') for each of rule or component.

How can I get pragmatically all certain (e.g.: 'send e-mail') actions from Rules and Components?

This function should do the trick:

/**
 * Find all rules with action name matching a string pattern
 *
 * @param $pattern
 *  String pattern to check action names
 *
 * @param $active
 *  Boolean whether to limit the search to active rules only
 *
 * @return
 *  Array with rule names with actions matching the pattern as keys and arrays of rule
 *  action names as values
 */
function search_rules_for_action($pattern, $active_only = TRUE) {
  $active_only = ($active_only) ? array('active' => 1) : array();
  $rules = rules_config_load_multiple(FALSE, $active_only);
  $matching_rules = array();
  foreach ($rules AS $rule_name => $rule) {
    if (method_exists($rule, 'actions') === TRUE) {
      foreach ($rule->actions() as $action) {
        if (method_exists($action, 'getElementName') == TRUE) {
          $action_name = $action->getElementName();
          if (stripos($action_name, $pattern) !== FALSE) {
            $matching_rules[$rule_name][] = $action_name;
          }
        }
      }
    }
  }
  return $matching_rules;
}


how to catch when node is being promoted? I would like to take some action when node is being promoted. I tried using node_validate or node_presave but none of them is working.

What is the quickest way to do this?

thanks

You can do it using hook_node_presave ...

Below is the code which works for me... Trick is here you need to make sure if node is new and promoted take action.. If node already promoted that means you are editing a node... You need to check whether original was unpromoted and after edit it is promoted then take action...

function YOURMODULENAME_node_presave($node) {
  if ($node->is_new && $node->promote == 1) {
    drupal_set_message("NODE PROMOTED");
    // Take Some Action
  }
  else if ($node->promote == 1 && $node->original->promote == 0){
    drupal_set_message("NODE PROMOTED");
    // Take some action
  }
}


Permission for private file to anonymous I have an ad content type, with a file field that is in a private directory when saving the node.

Ads and their files are only accesible for authenticated users.

I wish I could allow anonymous users to see ads and their files that are promoted.

I use content_access module

I want programmaticly, change acces control foreach ads who is promoted and I don't how to achieve that.

It sounds like you might want to check out the Private Files Download Permission module which may provide exactly the functionality you're looking for.


Call a function in JS file from drupal I have included a javascript in the module "myid" I've been developing in drupal by using this code:

function myid_init() {
    drupal_add_js(drupal_get_path("module", "myid") . "js/myid.js");
}

This is my Javascript file "myid.js":

function myid_js_start(){
    alert("hello world");
}

Below is the code that creates a button that invokes an alert function:

$form['add_button'] = array(
    '#type' => 'button',
    '#value' => 'Take a picture',
    '#attributes' => array('onclick' => 'myid_js_start()'),
);

I dont know where did I go wrong. The button shows up but doesn't fire any alert function. Can anyone help me with this?

Try to write JS in drupal way like this:

(function($) {

    Drupal.behaviors.xyzModule = {
        attach: function(context, settings) {

//            $('.test', context).click(function() {
//                $(this).next('ul').toggle('show');
//            });

//myid_js_start();
            function myid_js_start() {
                alert("hello world");
                //console.log(' Hello');
            }

        }
    };

})(jQuery);

For More info visit here


Creating a bootstrap sub-theme with the SASS starter kit I am attempting to create a bootstrap sub-theme using the SASS starter kit in the the bootstrap base theme. I'm using bootstrap version 7-3.16.

I followed the directions here: How to create bootstrap subtheme using sass? as best as I could.

I copied the SASS starter kit into a new directory in the sites/all/themes directory and named it "bootsub". Then I changed the sass.starterkit file to "bootsub.info" and edited the file to reflect the name "bootsub".

Then I copied the bootstrap framework files into a file in the subtheme named "bootstrap". I had previously installed compass and sass.

I then ran the command "compass init" from the command line (in the subtheme root directory). This created the config.rb file. I then ran the command "compass compile" in the subtheme root directory.

I am still not able to see any styling on the site. I have flushed the cache and I have double checked to make sure that the subtheme is enabled and set as default and the bootstrap base theme is enabled.

I am including an images of the directory structure and a copy of the config.rb file

require 'compass/import-once/activate'
# Require any additional compass plugins here.

# Set this to the root of your project when deployed:
http_path = "/sites/all/themes/bootsub"
css_dir = "stylesheets"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "javascripts"

# You can select your preferred output style here (can be overridden
via the command line):
# output_style = :expanded or :nested or :compact or :compressed

# To enable relative paths to assets via compass helper functions.
Uncomment:
# relative_assets = true

# To disable debugging comments that display the original location of
your selectors. Uncomment:
# line_comments = false

# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv
scss sass

Try using Radix Theme. Check how the compiler gulp is setup and try to replicate it to bootstrap sass.


How to correctly add Google AMP .js files to my theme I'm using the Drupal AMP module,theme and library in Drupal 7

I'm using the AMP verification tool here validator.ampproject.org

I have the amp-sidebar working fine except the JavaScript causes an error.
When adding the AMP internal js file I get the below error when validating.

<script async custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js"></script>

I get the following warning

"The tag 'script' is disallowed except in specific forms."

The second error i get is the following.
And as a result of that I get this error
  The tag 'amp-sidebar extension .js script' is missing or incorrect, but required by 'amp-sidebar'. Learn more.

I have included the full HTML file contents below if you want to run it through the validator to see the errors live, Just copy and paste the code.
Pastebin of full Drupal AMP page

Add the AMP component JS in the <head> section of your document, then it will be ok.

<script async custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js"></script>

  Extended components are loaded by including a  tag in the head of the document  https://www.ampproject.org/tr/docs/reference/spec


Fields in Paragraphs twig template I've created a paragraph type called "text_icon_boxes". It has 19 fields. I've added this paragraph type to one of my content types.

What I'd like to do is customise the display of this paragraph type. I've created a twig template paragraph--text-icon-boxes.html.twig, but the fields display "-1", etc. How do I access the paragraph fields in this twig template?

Here's a small snippet:

{{ content.title }}

{{ content.text }}

The twig template is the right one. Twig template suggestions:

The field variables are not right - they need to correlate to the field name.

Example:

{{ content.field_icon_1 }}

{{ content.field_icon_1_title }}

These are the render arrays you are looking for. {{ content.text }} does not exist.

Also, keep in mind that these render arrays are rendering those fields - you may want to place the markup in those field specific templates.


Access denied PDO Exception - other users are getting it but not me I've set up a new Drupal 7 site (which is still in a vanilla post-install state with no custom code, no themes, no content). This particular site runs on a remote DB, with users (my team colleagues) downloading the Drupal code from a VCS to run on their local machines. Everyone is getting the following error while trying to access the site - except me. I can log into the site just fine.

PDOException: SQLSTATE[HY000] [1045] Access denied for user
'root'@'localhost' (using password: YES) in lock_may_be_available()
(line 167 of /private/var/www/drupal_media_7/includes/lock.inc).

What could be different about my local setup, given that we should all be running the same code and accessing the same database with the same credentials? (since the credentials are all in the code).

How might I start debugging this?

Have them check sites/default/settings.php and see if the credentials for your database user (assuming 'root') are correct.

If it is, they should also be checking to see if:

The user 'root' has access to the local database and
Root has that same password as an sql user


Rule to autopopulate node reference field and redirect after content creation I'm trying to make a rule so that when a node of content type X is created, a node of content type Y is also created and is automatically populated with a nodereference field to the nid of content type X that was created. Then the user should be redirected to the edit form of the node of content type Y that they just created.

My rules configuration looks like this right now:

Event: After saving new content

Condition: Content is of type X

Actions:

Create a new entity of content type Y
Set a data value: set the node reference field on new node of content type Y nid of new node of content type X
Page redirect: URL: [entity-created:edit-url]

Everything works as expected except the redirect (which I thought would be the easiest part). Both nodes get created and the node reference field is set correctly. But I get a page not found error with the following messages:

  Notice: Undefined property: stdClass::$nid in node_tokens() (line 112
  of /web/xxxxxx/www/modules/node/node.tokens.inc).

  "content type X" "title of new content of type x" was successfully created

  The requested page "/node//edit" could not be found.

I've also tried node/[entity-created:nid]/edit for the page redirect. Same exact problem. I have no idea why it's not plugging in the nid of the new node of content type Y in between node/*/edit.

Basically you need to create another event right after "create entity" which immediately saves the new entity before you move on to the redirect rule.

See also http://groups.drupal.org/node/204558#comment-688188.


Export menu as feature? How can I export a menu as a feature? I found the menu import module, but it does not work with this feature.

You need some way to assign UUIDs to menu links. Just like how the uuid_features module assigns UUIDs to nodes.

For Drupal 6, there's a patch to the uuid_features module that has worked well for me. (See comment #2 on the issue for instructions.)

Haven't tried for Drupal 7.


adding group by in views sql query I have view of teasers which one has united filed.

Is there a way to add "group by" by this field (join field table and group by the field) into sql query of view?

In Views 3, under "advanced settings", there is a setting for enabling aggregation, which will give you group by options.

Most likely they are hidden by default as the UI is complicated enough as is.

You can also check out chapters 28-30 in the NodeOne Taming the beast learn views with nodeone which are all about aggregation.


manage fields is missing I created new content, but I can't see manage field. I googled the problem, all the solutions say enable Field UI module, I did enable the Field UI, but still I can't see the manage fields, any help please?

Did you flush all caches under Performance settings? You can do it manually too. Go to phpmyadmin and clear all tables with "cache" preposition. If you use admin_menu module, it need to be rebuild from time to time.

Try to access manage_fields manually on path https://www.yourdomain.com/admin/structure/types/manage/page/fields

page is name of your content type

When I'm facing strange problem I always try to reproduce it on new Drupal installation. It tells me a lot when I'm "reverse-engineering" the problem.


Trying to show multiple relationships with Drupal view I have a website with Car manufacturers (c_manufacturer), each Manufacturer has car Models (content type: c_model), and each model has picture (content type: model_pictures).

I'm trying to create a view to display on every Manufacturer's page and show the car pictures of the car models that belong to that Manufacturer.
Using Contextual Filter for the Manufacturer node ID, I added 3 relationships:
Content: c_manufacturer  - reverse
Content: c_model  - reverse (Using Relationship: c_manufacturer)
Content: model_pictures  - reverse (Using Relationship: c_model)

I tried to show the Title field (something that all of the content types have on my site)
and I keep getting no result on the view Preview (when giving a manufacturer ID as an argument), what am I missing ?

I would have used references to start with.

You would create a manufacturer (e.g BMW). Now BMW will have a picture/logo description etc.

Then you would create a CAR (e.g 320i). Now the car will have all the fields you want and most importantly the reference to the manufacturer.

You will then need to create a block view of content type CAR.

Fields will be picture and title(320i).

Filters will be "Content: Type (=Car)".

Contextual filters will be "Content: Nid".

Then in Structure->blocks you move the newly created block view into the Content section under "Main page content".

When visiting the BMW node the view should display the car + title.


Can't use node_page_edit in ajax callback function I have an ajax callback function:

function mymodule_callback($form, &$form_state) {
    $nid = $form_state['build_info']['args'][0]->nid;
    $node = node_load($nid);

    module_load_include('inc', 'node', 'node.pages');
    $form = node_page_edit($node);
    return print_r($form, true);
}

(Please note that I'm returning from print_r as I'm trying to debug the problem).

This callback is being run from a form submit:

function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'save',
        '#ajax' => array(
            'wrapper' => 'my-form-id',
            'method' => 'replace',
            'callback' => 'mymodule_callback',
            'effect' => 'fade'
        ),
        '#submit' => array('node_form_submit'),
    );
}

When I submit the form I get an AJAX error which says 'cannot unset string offsets' in field.default.inc. I know that the node_page_edit function is causing it because when I remove it the error doesn't happen.

Interestingly, if I press the submit button again straight after getting this error, it works - and the full structure of the form is loaded in to my div.

Why doesn't it work the first time and how do I fix it?

My solution:

/* Drupal caches all ids of form elements and when ajax request happen, this
 * results in the new form have id's appended with --2 --3 etc, so css breaks.
 * Unsetting this makes the ids always the same. Maybe hook_init is not the best
 * place for this, but for now it works.
 */
function mymodule_init() {
    if(isset($_POST['ajax_html_ids'])) {
        unset($_POST['ajax_html_ids']);
    }
}

function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    //only do the do if this is and ajax request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Save',
            '#ajax' => array(
                'wrapper' => 'my_form_id',
                'method' => 'replace',
                'callback' => 'mymodule_callback',
                'effect' => 'fade'
            ),
            '#submit' => array('node_form_submit'),
        );

        /* For some reason this _has_ to be in form_alter. Putting it in a submit
         * callback doesn't work. What this is doing is setting the changed time
         * of the form to be in the future, if we don't do this, when the form is
         * reloaded after a submit, it's not possible to submit the reloaded form
         * because Drupal thinks someone else has edited it (I think it checks
         * the last update time of the node VS this value). This adds a 5min window
         * where changes can still happen. It's not the best solution but I think
         * it will work.
         */
        $form['changed']['#default_value'] = time() + 300;
    }
}

function mymodule_callback(&$form, &$form_state) {
    $new_form = drupal_rebuild_form('my_form_id', $form_state, $form);
    $form_html = drupal_render($new_form);

    return $form_html;
}


Add conditional stylesheet CSS for internet explorer only The following methods can be used to add CSS for specific versions of IE:

Paste the code into html.tpl.php:

<!--[if lt IE 9]><link type="text/css" rel="stylesheet" src="/sites/all/themes/mytheme/less/ie.css"><![endif]-->
Make use of the plugin Conditional Styles
Use drupal_add_css() function

I have always used option #1 above, and adding yet another plugin for something so simple seemed crazy. BUT working with LESS and calling in statically means the file does not get processed by the LESS pre-processor, so the question:

How do you include a stylesheet using drupal_add_css() for specific versions of IE?

I Found the solution in the comments on the drupal documentation for drupal_add_css():

drupal_add_css(
  path_to_theme() . '/less/ie.less',
  array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE
    )
  )
);

Using this resulted in the LESS file being compiled by the LESS pre-processor, and the style was included within <!--[if lte IE 9]> comment tags.


Is there a firm or preliminary decision on which modules will leave Core for 8? I seem to recall I've seen a more than one discussion about breaking out certain less than maintained modules from Core. They would presumably be moved to contrib instead. Currently I can't find any information on this topic.

There is an issue report for that ([Meta] Make core maintainable), but nothing has been decided yet. As you can see, there are different opinions about what to remove, and what to keep.
catch, the latest maintainer added to Drupal 8, expressed his opinion on that; the same did Dries, chx, Crell, and eaton (just to cite some of them). There is an agreement about some of the modules to remove, but there isn't a complete agreement.

That issue report is not marked as postponed, and a new issue report has been opened (Establish heuristics for core feature evaluation).


JavaScript errors with 'Add collection', 'Select media' (Media, Field Collection) I drupal 7 site that I did not build but now maintain has developed an odd error.  About a month ago the site lost the ability to add an image to a Media field inside a new addition of field collection.  Looking into it, this is what I find:

The first few warnings are nothing that I can see would harm things.  The media.popup.js error is nonsense:

dialogOptions.buttons[ok] = function () {
  alert('hell yeah');
  return "poo";

  var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia();
  if (!formattedMedia) {

I have yet to see that code be reached, though it looks a little unprofessional to have such things in a contrib module.

When I scroll down the node edit form I see see the next segment.  The Bulletin error has to do with Google Syndication code linked in, and can be ignored for now.

The piece of the screenshot after that is when I try to trigger the field collection's "Add Additional Item" button from the console.  Nothing happens.  I am not sure if I did it right, but I included it in this screenshot in case it helps identify anything.

The final segment shows the messages that appear when I click the Add Additional Item button.  A new field collection instance is actually added to the form, and if the console was not open I would not know that something was wrong yet.  I get from 2 to 5 instances of that "object is undefined" error any time I do this.  The "too much recursion" error occurs about 1 in 15 tries, so I do not know if it is relevant.  I have all cache and compression turned off, and this is a local virtual box copy of the live site so I do not have to worry about killing it in the investigation.

The problem is these "object is undefined" errors block the use of the Media module's Select Media button for a field on the node.  First time this problem was noticed was when a new slide show entry was being added to an Article node.  The Add collection button causes the error, and the Media button then does not respond but throws some "this.hoverable" error.  I went over to another content type that has a field collection that contains only text, but also has a Media field on the node itself.  The field collection generates the same error, I switch vertical tabs to get to the Media field and it behaves the same as the media field inside the collection.  JQuery Update is used to keep the admin screens on jquery v1.5 because it is needed for the Media module.

Modules involved:

Drupal 7.38
Field collection (field_collection)  Module  Enabled      7.x-1.0-beta8
Chaos tools (ctools)  Module  Enabled     7.x-1.7
jQuery Update (jquery_update)   Module  Enabled     7.x-2.4
Media (media)      Module  Enabled    7.x-1.5

OK, this was sort of entertaining.

The trail begins with this silliness in media.popups.js:

dialogOptions.buttons[ok] = function () {
  alert('hell yeah');
  return "poo";

Just as it stuck out for @DeveloperWeeks, it stuck out for me because I'm familiar with the work of Media module's primary maintainer, and I know him (by reputation) to be pretty meticulous. So in checking it out I discovered that it was removed long ago (like, in 2013) in this commit: Removed inappropriate JS code.

(I am sure he would be thrilled, by the way, to know that this bit of code will now live forever after on StackExchange. :-P)

Since the OP lists as part of his installation the latest production release  of Media (7.x-1.5), this didn't mesh. The errors were originating from a two-year-old file.

With this compelling clue in hand, @DeveloperWeeks was able to locate an extra copy of the Media module hidden away in his installation. That's when the sun rose, the flowers bloomed, and things just generally started to make more sense.

As for those pesky errors, well...

  "This is why "duplication of data" is such a horrible thing." -
  @DeveloperWeeks

Hell, yeah. ;-)


Views not found on disabling Page Title module I've  Views 7.x-3.7 and Page Title 7.x-2.7 installed. Since many months I'm using Meta tags and Page Title module but now I want to remove Page Title module as I don't need it since Metatag module provides equivalent functionality.

But on disabling Page Title module I'm getting page not found(404) for the Views Page display URL. Also when I go to edit that display in the View from Structure->Views I get the following screen:

When I go to view the Page url of the View Display I get this :

There is no information in the dblog except for this when I access the View Page url:

What should I check to start debugging this?

The page_titles module sets a lot of variables. I don't know if that would cause an issue like you are seeing, but it's best to remove these variables. Disabling the module will not remove them, but uninstalling it will. With page_title disabled, go to admin/modules/uninstall, select the module, and click uninstall. This will unset all variables that were set by the module.


Is block weight ignored when setting content in hook_block_list_alter()? I am using hook_block_list_alter and hook_block_view_alter to force caching upon a block provided by nice_menus, which has bad performance when used with my HUGE taxonomy menu. Here is an abstract of my code:

/**
 * Performance hack for nice_menus
 * Force the nice menu blocks to be cached globally.
 * Note that the same menu will be displayed for all users on all pages where the block is enabled.
 */
function mymodule_block_view_alter(&$data, $block) {
  $deltas = variable_get('mymodule_nice_menus_performance_hack_deltas',array());

  if ($block->module == 'nice_menus' && in_array($block->delta,$deltas)) {
    // if we are here, then the block has been rendered. set the cache.
    cache_set('mymodule_nice_menu_'.$block->delta.'_data', $data, 'cache_block', CACHE_TEMPORARY);
    cache_set('mymodule_nice_menu_'.$block->delta.'_block', $block, 'cache_block', CACHE_TEMPORARY);
  }
}

function mymodule_block_list_alter(&$blocks) {
  $deltas = variable_get('mymodule_nice_menus_performance_hack_deltas',array());

  foreach($blocks as &$block) {
    if ($block->module == 'nice_menus' && in_array($block->delta,$deltas)) {
      $cached_data = cache_get('mymodule_nice_menu_'.$block->delta.'_data', 'cache_block');
      $cached_block = cache_get('mymodule_nice_menu_'.$block->delta.'_block', 'cache_block');
      if (!empty($cached_data) && !empty($cached_block)) {
        $block = $cached_block->data;
        $block->content = $cached_data->data['content'];
        $block->subject = $cached_data->data['subject'];
      } // else just don't set anything, and nice_menus will recreate it!
    }
  }
  dpm($blocks);
}

Now my problem is, that whenever $block->content is set, the block's weight is ignored, and it is rendered as the first block in the region, even though $block->weight was set to the correct value.

What causes this, and how does one enforce the weight?

Symptoms: When the block is not loaded from cache, but from the database, the ordering works fine. When loading from cache, the weight is ignored.

Diagnosis: The block module uses SQL to order the blocks:

function _block_load_blocks() {
  global $theme_key;

  $query = db_select('block', 'b');
  $result = $query
    ->fields('b')
    ->condition('b.theme', $theme_key)
    ->condition('b.status', 1)
    ->orderBy('b.region')
    ->orderBy('b.weight')
    ->orderBy('b.module')
    ->addTag('block_load')
    ->addTag('translatable')
    ->execute();

// ...

After that, it ignores the weight value, and relies on the order of php array keys (order in which foreach iterates) when rendering:

function _block_get_renderable_array($list = array()) {
  $weight = 0;
  $build = array();
  foreach ($list as $key => $block) {
    $build[$key] = $block->content;
    unset($block->content);

// ...

    $build[$key] += array(
      '#block' => $block,
      '#weight' => ++$weight, // HERE LIES THE MADNESS!
    );
    $build[$key]['#theme_wrappers'][] ='block';
  }
  $build['#sorted'] = TRUE;
  return $build;
}

Strategy: Either hack the blocks module (DON'T) or find a workaround. I looked through the block.module and found (using lots of dpm()) where the order of array keys are being reversed:

function _block_render_blocks($region_blocks) {

// ...

  foreach ($region_blocks as $key => $block) {
    // Render the block content if it has not been created already.
    if (!isset($block->content)) {
      // Erase the block from the static array - we'll put it back if it has
      // content.
      unset($region_blocks[$key]); // THIS IS WHY THE ORDER OF KEYS CHANGE

// ...

      if (isset($block->content) && $block->content) {

// ...

        $region_blocks["{$block->module}_{$block->delta}"] = $block; // THIS IS WHY THE ORDER OF KEYS CHANGE
      }
    }
  }

  return $region_blocks;
}

Workaround: Manually sort the render array in a hook_page_alter(&$page) implementation.

function mymodule_page_alter(&$page) {
  if (!empty($page['sidebar_first']['my_block_1'])) {
    $page['sidebar_first']['my_block_1']['#weight'] = -1; // move it to the top
    $page['sidebar_first']['#sorted'] = FALSE; // indicate that it still needs to be sorted before rendering
  }
}

I only have two blocks in sidebar_first, of which the bottom one is cached. So I only need to lift the other block ('my_block1') above the cached block. A more sophisticated approach will be to query the weights from the block table again.

I'm not sure whether I should consider this to be a bug in the block module. It is a shortcoming, but it's only exposed because of my custom caching hack.


Mask User url with dynamic temprorary user Is there a module to mask user url with a temporary url which only last for a day and next time it generates another url for the same user?

I want to hide the users UID/username so that no two users can talk to each other but can view their profiles with a temporary url.

I checked with pathauto module but it generates a dynamic permanent url not a temporary ones.

Edit:-
I used uuid_link module for this and ran cron to generate uuid for users.

It's very unlikely; this sounds like a very specific use-case that wouldn't need a dedicated project. You're going to have to implement your own custom module to pull this off.

You could go an aliasing route in a manner similar pathauto but that is likely to leave source paths open (e.g. user/XXX) to accessibility. A better approach is to create a simple module that:

Uses a hook_cron() implementation to generate random hash to UID mappings periodically and storing them in custom table.
Implementing a hook_menu() to generate a dynamic path like user/%random_hash that maps the random hash paths in #1 to a user profile page (generated in the the same manner like user/%user)


How do I remove the Title "Languages" from the Language Icon Module? I am trying to create a bilingual site from a Drupal 7 site that already exists in English. I have absolutely no programming background, yet have managed to make it quite far thanks to reading other individuals' questions and answers on Drupal Answers. Thanks guys!

Now I have some questions of my own :) For these questions the page I am referring to is http://laidea.us/testingpage

I would like to remove the title "Languages" or "Idiomas" (in Spanish) from the Language Switcher block. I tried seeing if I could do that in views, but couldn't find the Language Switcher block there.
I would like to have my language icons be side by side, and without the list bullets next to them.
I've noticed that it says what language the content is in, and there is a language switch below my text. How do I get rid of/ hide these fields?

Thank you for your help!

-Jane

To remove the title 'Languages', configure the block, and set the title as <none>

To have the icons side by side and remove the list bullets you need to specify some css in your theme:

section.block .content .language-switcher-locale-url li {
  background: none; // in your case, you have background set
  display: inline-block; // to make them side by side
  list-style-type: none; // to get rid of listing bullets
}


Default to 'this display' when editing views I am working on a display of a view I have. I want to make changes that apply only to the display that I'm working on; however the various editing widgets (relationships, filters, fields, etc) keep defaulting to apply to all displays. For the most part I remember to change it to "this display", but sometimes I don't, and I end up changing all displays.

Is there a way to change the default application to "this display"? Or have views remember which I chose?

Not that Im aware of, Im afraid this is the default behaviour. I often catch myself out by not selecting "This block override". :-(

But actually - Breaking the default behaviour for the very first display when you create a new view would mean that every new display you add would have its own settings for filters etc. You would just have to remember to do this everytime you add a view


Contextual Filters with PHP code I am setting up a contextual filter for several taxonomy fields on a content type that stores my organizations records.  I want to present my users with a nice looking url, not the TID.  For the contextual filter, I have selected Provide a Default Value and selected Use PHP Code. This is the code:

$term_name = "Open";
$termObj = taxonomy_get_term_by_name($term_name);
$term = reset($termObj);
return $term->tid;

For now, I'm hard coding the term until I can get it working, then I'll switch it to a term out of the URL. When I save the contextual filter, the preview shows "No query was run". After I save the view and visit the page created by the view, Drupal gives me a Page Not Found message.

As I am always against adding PHP code in the UI may I suggest a different approach?

Add a relationship to your view "Content: age group", which is the relationship from your term reference field to the taxonomy term.

Then add a contextual filter "Taxonomy term: Name", using the relationship you just added.

Then the argument will be the term name without you having to add custom PHP code.


Select list in entity reference in VIews How to create an entity reference exposed filter in drupal 8 in Views?
The only option i have is input of type text

You need an additional module for that:

Entity Reference Exposed Filters

This might also help: Views field select filter

I'm not sure if this one supports exposed or only normal filters: Views Entity Reference Filter


How do I say to Twig where to look for the template files? I want to add another path where the templates are stored. In standard PHP I'd use $loader->addPath('../path/to/templates'). I found Twig_Loader_Filesystem::addPath(), but I have no clue where and how to use it.

Is there any hook?

What you found is the class used from Twig to load the template files from the file system, but what Drupal uses is its own class derived from that,  Drupal\Core\Template\Loader\FileSystemLoader, which is the default class implementing the twig.loader.filesystem service. Its only purpose is adding a namespace for each theme and module enabled from a Drupal site, so that is possible to reference a template file as @block/block.html.twig.

For how I understand it, replacing the class implementing that service with a class derived from the default implementation, you could be able to reference
a template in a different directory with, for example, @external_directory/template.html.twig.

See  FilesystemLoader::__construct() for how Drupal adds new namespaces, and Altering existing services, providing dynamic services for how to alter that service to use a different class.


"Fields pending deletion" stopping module unistall - how to delete manually? I'm getting a "Fields pending deletion" error when trying to uninstall the Dynamic Entity Reference module. I also cannot disable the module as the tick is greyed out (unless I'm missing how to disable modules in Drupal 8).

I've run cron and cleared the caches many, many times and have checked /admin/reports/fields but there is no mention there of any fields using this module.

I have found suggestions for Drupal 7 saying to delete the fields from the field_config database table but this table does not exist in Drupal 8. Is there any way to get rid of these zombie fields? They must be stored somewhere!

Please don't tell me to use Drush, I wish I could, believe you me, but I don't have shell access, just sftp and phpmyadmin.

It turns out that deleted fields in Drupal 8 are stored in the key_value table.

To find them:

select * from key_value where name = "field.field.deleted" or name = "field.storage.deleted"

The values are stored as a blob, but can be viewed (e.g. in phpmyadmin you can click on it to download, and view in vim or similar). The value does not make much sense to a human, but having gone through the code printing and error-logging various things it was clear to me that these entries were what was holding up the uninstall. I backed up the table and deleted the entries, and then was able to uninstall the module.

The same suggestion is made here in answer to a related issue:

https://drupal.stackexchange.com/a/230199/25792


How to create a view of all recent activity on a site? I want to create either a view or a module (preferably view) to display all recent activity on the site such as a new user joined in, a user read some article or blog, a user gained some points and so on...the display should be as:

User x just joined in
User y just got 30 points for creating a blog
User Z just read Some Article

I tried doing so using the Message, Views and Rules modules, but I was able to do so (only for one specific event such as User x created a blog ...).

Note: I want to create new events in Rules. I wonder how to use a message type to get different messages to be displayed. I am following this tutorial, but I wonder how to add more messages such as "[user] gained [user-points]", etc and be sure that it is displayed when that event triggers. Also what data selector should I choose in Rules?

You should take a look at the Heartbeat module.

  Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.


styling the views pager I'm using drupal 7 and i made a view that has a pager.
Is there any way to put the pager-item (pagers number) inside any html tag?

// new html tag

1

2

3

4

......

Ofcourse you can...

Make a copy of views-view.tpl.php in your theme.

Then you put your tag around the output of the $pager variable.

  <?php if ($pager): ?>
    <somemadeuptag>
       <?php print $pager; ?>
    </somemadeuptag>
  <?php endif; ?>

UPDATE

  "no that is not what i looking for, i need put html tag inside $pager variable"

You need to use hook_pager_link() in your theme.

Search for 'hook_pager_link' in your sites code directory to see example.


Does user_is_logged_in() check if there is at least one user logged in? Does the user_is_logged_in() method return TRUE if there is at least one user logged in? Or does it refer to the current session, and returns TRUE if the current user is logged in?

By looking at the Drupal API, you can see the function itself:

<?php
function user_is_logged_in() {
  return (bool) $GLOBALS['user']->uid;
}
?>

Which shows that it returns TRUE if the current session is a logged-in user, or FALSE if the current session is an anonymous user.


How to exclude nodes with matching field values using EntityFieldQuery This relates to a classified listings site, where nodes have an expiry date (date, field_period, start/end = value/value2) and a notifications field (text, checkboxes, 336=two weeks, 672=four weeks).

We want to query for nodes which are going to expire between two and four weeks from now -

$period = 672;
$paid_date_max = date('Y-m-d H:i', strtotime('+' . $period . ' hours'));
$paid_date_min = date('Y-m-d H:i', strtotime('+' . $period/2 . ' hours'));

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'entry')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_period', 'value2', $paid_date_max, '<')
  ->fieldCondition('field_period', 'value2', $paid_date_min, '>=')
  ->fieldCondition('field_period', 'value2', 'NULL', '!=')
  ->addMetaData('account', user_load(1));
$result = $query->execute();

That works fine, but includes nodes which have already been sent a reminder (in which case field_expiry_notifications will contain a value matching $period). field_expiry_notifications may have multiple values, so we need to accept only nodes where NONE of the field_period_notifications values match $period.

Q: How to exclude from the above resultset any nodes with a matching expiry_notifications value?

I believe you do need a subquery here. Apparently, you can actually do that with EntityFieldQuery. So first create your subquery, something like this:

$subquery = db_select('your_field_data_table', 't');
$subquery->addField('t', 'nid');
$subquery->condition('field_period_notifications', $period);

That gives you all nodes that have a matching value. Then add this to your EntityFieldQuery to exclude those:

->fieldCondition('field_period', 'nid', $subquery, 'NOT IN')

Or maybe you can do:

->entityCondition('entity_id', $subquery, 'NOT IN')


Views pager labels translation per context Now that I finally have managed to have Views pagers appear, I'm wondering how I could change the strings collection (prev, next, first, last...) per View. That's because in a View that displays items in chronological manner, I would rather see labels like older/newer rather than previous/next. Can this be done somewhere in views template or in template.php? (No jquery here, please :))

Use hook_pager() in your theme template.

function YOUR_THEME_pager($tags) {
  echo "<pre>";
  var_dump($tags);
  echo "</pre>";
}


User submission/restriction Beginner drupal user here, I know how to assign permissions to users to add/create content etc., my problem is I am trying to create a specific page where users can go to (from the main menu) to upload content whether it be images, video, etc. and the content is then displayed in its own page, for example, all images are displayed in a separate page called "images" and videos go in "videos", based on what file they uploaded. Is there a module that accomplishes this or am I just

If I understand correctly your requirement, then you want to provide a functionality to user to upload images or video and then save the images or video respectively.

I have already implemented similar functionality in one of my recent project with following concept:

Create a new content type as upload
Add a list (select) field Filter type with options image and video
Add two fields  image as 'image' field type
Installed Media module and add video field as 'Media file selector'
Installed Conditional field module and set condition that image field be only visible if user select 'image' as Filter type options and video field be only visible if user select 'video' as Filter type options
Set the permission to user to create content of upload content type.
Now Create two views to display image and video separately.

I hope that it will solve your problem.


How can I perform an operation programatically when the value of a user field is changed? On my user accounts, I have a text field, field_nickname.  Users can change this at any time.

When they do change it, however, when the user account is saved I want to copy the old value for field_nickname to a text field accepting unlimited values, field_nicknamehistory.

In Drupal 7, you could do this in Rules by making a rule "on user update" and accessing the old value through the tokens in the rule interface.  However, Rules isn't here yet for Drupal 8, so I'm trying to do this in code.

I tried to do this with hook_user_presave() but I don't know how to get the old value to compare it against the new value:

function mymodule_user_presave(Drupal\user\UserInterface $entity) {
  // How do I get $previousnickname?
  if ($entity->get("field_nickname") !== $previousnickname) {
    $entity->get('field_nicknamehistory')->appendItem($entity->get($previousnickname));
  }

I looked through the API and found onChange(), but I don't see how that would help me here.

The Content translation module has code you could use, right in its hook_entity_presave() implementation (i.e. content_translation_entity_presave()).

if (!isset($entity->original)) {
  $entity->original = entity_load_unchanged($entity->entityType(), $entity->id());
}

In $entity->original you then find all the values that entity object had before being changed, as the documentation for entity_load_unchanged() says:

  Loads the unchanged, i.e. not modified, entity from the database.

  Unlike entity_load() this function ensures the entity is directly loaded from the database, thus bypassing any static cache. In particular, this function is useful to determine changes by comparing the entity being saved to the stored entity.

If you want to write code that will need less changes when passing to Drupal 9, you can use the following one, which replaces the call to entity_load_unchanged() (marked deprecated) with that function's code.

if (!isset($entity->original)) {
  $entity->original = \Drupal::entityManager()->getStorage($entity->entityType())->loadUnchanged($entity->id());
}

Also image_entity_presave() uses $entity->original, but it doesn't load it if it has not been set.

$original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;

Probably, you could simplify the code.

if (!isset($entity->original)) {
  // Get the old value of the field.
}

Looking at the method calling hook_entity_presave(), EntityStorageBase::doPreSave(), the latter seems a more correct code.

  $id = $entity->id();

  // Track the original ID.
  if ($entity->getOriginalId() !== NULL) {
    $id = $entity->getOriginalId();
  }

  // Track if this entity exists already.
  $id_exists = $this->has($id, $entity);

  // Omissis

  // Load the original entity, if any.
  if ($id_exists && !isset($entity->original)) {
    $entity->original = $this->loadUnchanged($id);
  }

  // Allow code to run before saving.
  $entity->preSave($this);
  $this->invokeHook('presave', $entity);

EntityStorageBase::doPreSave() already sets $entity->original for entities that aren't new; the code used from content_translation_entity_presave() seems excessive.


Preprocessed var not being passed to twig template I created a custom theme called wdocs as a sub theme of d8w3css. I made a template to override the menu template for the user account menu, calling it menu--account.html.twig. For my theme, I added the function wdocs_preprocess_menu__account() to my wdocs.theme file, and introduced a new variable with $variables['tollfree_number'] = '555-1212'; So far so good; in phpStorm I can set a breakpoint there are do see it is getting set in $variables. In my twig, I have some text, followed by {{ tollfree_number }}. The text gets displayed, but not the variable.
The problem is the twig calls a macro; I can access the var outside of the macro, but not within it. Googling suggested I pass context when calling the macro, so I changed the call to
{{ menus.menu_links(items, attributes, 0, menu_name, _context) }}

I also tried "context" (no underscore). And also tried dereferencing it with {{ _context['tollfree_number'] }}, but nothing seems to help. Where am I going wrong?

You're correct in thinking that trying to access your var from within the macro is the issue. See Twig's macro documentation.

But as with PHP functions, macros don’t have access to the current template variables.

You can pass your variable into the macro.
{{ menus.menu_links(items, attributes, 0, menu_name, tollfree_number) }}

Then you have two options, you can update the macro definition to add an extra parameter for your custom var.
{% macro menu_links(items, attributes, 0, menu_name, toll_free) %}
  {# etc.. #}
  {{ toll_free }}
{% endmacro %}

Or you can use the special varargs variable without updating the macro definition.

If extra positional arguments are passed to a macro, they end up in the special varargs variable as a list of values.

Pass the var to the macro the same way, then access it like:
{% macro menu_links(items, attributes, 0, menu_name) %}
  {# varargs[0] has the first extra arg, varargs[1] has the second, etc #}
  {{ varargs[0] }}
{% endmacro %}

Using the special _context and varargs vars:
{{ menus.menu_links(items, attributes, 0, menu_name, _context) }}

{% macro menu_links(items, attributes, 0, menu_name) %}
  {{ varargs[0].tollfree_number }}
{% endmacro %}


Prevent duplicate drupal_add_js calls Issue: I have an input filter that, when triggered, executes drupal_add_js.  However, when I view source of the page, I see this command issued twice or more times.

Question:
Is there something I can do to prevent duplicate javascript commands on a page?

Code sample:
Below is the sample of the input filter that I'm writing. In some pages, for an unknown reason

<?php
function _js_slider_process($text, $filter, $format, $langcode, $cache, $cache_id)
    {

        preg_match_all("/\[slideshow:(#[\S]+)\]/", $text, $matches);

        // If no match return and be done.
        if (!isset($matches[1])) {
            return $text;
        }

        // gather information
        $text_to_remove = $matches[0];
        $elementid = $matches[1];

        // remove filter trigger text
        $text = str_replace($text_to_remove, '', $text);

        // Do we have any matches located in the firs match
        if (isset($elementid[0])) {
            // Inject javascript file
            drupal_add_js(drupal_get_path('module', '_js_slider') . '/' . _JS_SLIDER_JS_FILE_SRC, 'file');

            // Inject options into a javascript variable
            $js_slider_options = array(
                'first' => variable_get('_js_slider_control_first', _JS_SLIDER_HTML_CTRL_FIRST),
                'prev' => variable_get('_js_slider_control_prev', _JS_SLIDER_HTML_CTRL_PREV),
                'next' => variable_get('_js_slider_control_next', _JS_SLIDER_HTML_CTRL_NEXT),
                'last' => variable_get('_js_slider_control_last', _JS_SLIDER_HTML_CTRL_LAST),
                'ctnl_placement' => variable_get('_js_slider_control_placement', _JS_SLIDER_HTML_CONTROL_PLACEMENT)

            );
            drupal_add_js(array('_js_slider' => $js_slider_options), 'setting');

            // Call it
            drupal_add_js('jQuery(document).ready(function () { a = new SlideShow("' . $elementid[0] . '"); a.init(); });', 'inline', 'footer');
        }

        return $text;
    }

Safest and most straightforward way is to move js file to module's info file, and include it always. just make sure it works only on elements it should, and on all of them. For this you need appropriate classes.

Other way is to use ['#attached']['js'] of highest possible element, instead of calling drupal_add_js manually. if you will set script twice, you will override older instance, so no problem.

If, for reasons unknown to me, you decide you have to call drupal_add_js yourself, use drupal_static to make sure you didn't call it already. It will require least changes in existing code - and in my opinion is worst solution. But will work. Typical usage is:

$mycounter = &drupal_static(__FUNCTION__, 0);

That makes $mycounter shared among all scopes where it is called, and initialized to 0. Then, you can test if it's still 0, and if it is - add your JS and increment counter with good old $mycounter++


Fatal error: Unsupported operand types in field.info.inc I'm cloning my client's drupal 7.15 site from online to my localhost. I received a copy of site folder and a copy of a sql dump file. I installed them into my localhost.

When I run the site, firstly I encountered the error:

  Fetal error: Class name must be a valid object or a string in
  C:\xampp\htdocs\mysite\includes\common.inc on line 7679

But the error went away when I did clear all cache tables manually via phpMyAdmin.
Unfortunately, the next error appeared.

  Fatal error: Unsupported operand types in
  C:\xampp\htdocs\mysite\modules\field\field.info.inc on line 294

[Edit]
I installed Drush and navigated to my site in Drush command line, but I could not run commands except "drush" because of that error.

  C:\xampp\htdocs\mysite>drush user-login
  Drush command terminated abnormally due to an unrecoverable error.       [error]

  Error: Unsupported operand types in
  C:\xampp\htdocs\mysite\modules\field\field.info.inc, line 294

  C:\xampp\htdocs\mysite>drush status
  Drush command terminated abnormally due to an unrecoverable error.       [error]

  Error: Unsupported operand types in
  C:\xampp\htdocs\mysite\modules\field\field.info.inc, line 294

  C:\xampp\htdocs\mysite>drush cache-clear
  Drush command terminated abnormally due to an unrecoverable error.       [error]

  Error: Unsupported operand types in
  C:\xampp\htdocs\mysite\modules\field\field.info.inc, line 294

When I traced into field.info.inc, I found that $instance['settings'] ( of the first parameter of _field_info_prepare_instance ) is missing for the field field_tags. Thus, the "+=" operation for arrays failed.

print $instance
Array
(
    [id] => 5
    [field_id] => 3
    [field_name] => field_tags
    [entity_type] => node
    [bundle] => article
    [deleted] => 0
)
print $instance["settings"]

****************
print field_info_instance_settings() call on taxonomy_term_reference
Array
(
    [user_register_form] =>
)

Your problems indicate that the copy did not come out right. Rather than try to diagnose the symptom, start over and copy the site again from scratch. If you can use Drush, perhaps Drush rebuild would help.  You could also use the drush rsync and drush sql-sync commands directly.


Display the taxonomy term name in the page.tpl from a node I want to show the term name in the header for every node. Whats the best way, espacially if the node has 2 fields with taxonomy terms and the page is in different languages.

This display nothing, but gives me also no errors:

<?php if ( !empty($node) && $node->type == 'content-type') {
  print render(field_custom('node', $node, 'field_custom', array('label'=>'hidden', )));
}
?>

EDIT

preprocess_node:

global $language;
$wrapper = entity_metadata_wrapper('node',$variables['node']);
$variables['term1'] = $variables['term1'] ->language($language->language)->field_term_ref->value()->name;

page.tpl.php:

<?php print $term1 ?>

I don`t get any term name.

I would use an entity metadata wrapper for this:

// Load the current active language.
global $language;
// Put the node object in a wrapper.
$wrapper = entity_metadata_wrapper('node', $node);
// Get the term object.
$term = $wrapper->language($language)->field_term_ref_1->value();
// Translate the term.
$translated_term = i18n_taxonomy_term_get_translation($term, $language);
// Pass the term name to page.tpl.
$variables['term1'] = $translated_term->name;

// The same for term 2.

// Now you can print them in your page.tpl.
print $term1;

Not sure if the language part works, though.


Show sub menu via hook_menu Sorry for asking such a question, but I'm still new in Drupal. I want to show sub menu via main menu.

Ex:
- Top menu
1) Home
  a. Report
  b. Comment
2) Shopping
  a. Audi
  b. Honda

In this case, I would like to see 'a. Audi, b. Honda', or go back Home and see 'a. Report, b. Comment'.
What should my module's hook_menu implementation look like ?

You can simply achieve that by using the Superfish module.

  Superfish integrates jQuery Superfish plugin with your Drupal menus.

Image from Superfish module page

There is another module called Nice Menus

  Nice Menus enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)


How to override links in each Views feeds? I would like to override all links in all views feeds through a hook (potentially) - for example adding an extra query param to each item links.
I need a general function. When defining a new feed, the field name is unknown, so I can't rely on the exact name -> cannot use a specific preprocess hook.
I checked all Views hooks here: http://drupalcontrib.org/api/drupal/contributions%21views%21docs%21docs.php/6 but couldn't find a right one. I was playing a lot with different preprocess functions, no luck.
One idea is to override a field handler, but I'm not sure how to execute that.

What would you suggest?

Thank you!

I found the url_alter module: http://drupal.org/project/url_alter,
Some details from the module's project page:

URL alter is a utility module that adds two new hooks for other modules to implement: hook_url_inbound_alter() and hook_url_outbound_alter(). These hooks also replace the need for the special, silly custom_url_rewrite_inbound() and custom_url_rewrite_outbound() functions commonly found in settings.php.
It also provides an interface for administrators to enter in their own hook_url_alter code without needing to create a custom module.

It has some usable hooks:
hook_url_inbound_alter() and hook_url_outbound_alter()


Configuring Views into Features I have inherited a complex website which has the Features and Views module installed.
I can configure a Feature to include a View as you would expect.

However, I'm putting together a private website which also has Views and Features installed.
My problem is Views does not appear as an option to select data from when configuring the Feature.

Is there a setting or module which is responsibly for exposing Views in Feature create/edit mode ????

The image on the Feature project page seems to suggest Views should be there by default.

Any help, please !

Perhaps all the available views have been added to other features? Try enabling the checkbox "Allow conflicts to be added" in the 'Advanced Options' section of the 'Create' page. If you can see the views then, it means they are already assigned to other features.


How to apply a function to the title of a teaser made with display suite? I'm pretty new to functions and PHP (so please forgive my terminology) but here's what I would like to do:

Background

My homepage contains a view displaying various content type teasers. I would like to truncate the title of an article teaser (a custom teaser created with display suite) to 48 characters.

Action taken so far

If I add the following code to my subtheme's template.php file, nothing happens:

function THEMENAME_preprocess_node(&$variables) {
     if ($variables['type'] == 'article' && $variables['view_mode'] == 'teaser') {
     $variables['title'] = truncate_utf8($variables['title'], 48, TRUE, TRUE);
   }
}

However, if I add this other variation of the code (i.e. applying to all teasers, not just article teasers) the titles of some teasers are indeed shortened:

function eunic_global_preprocess_node(&$variables) {
if ($variables['teaser']) {
    $variables['title'] = truncate_utf8($variables['title'], 48, TRUE, TRUE);
   }
}

Conclusion & Question

I think the problem is to do with the fact that some teasers have been created using the Display Suite module while others use more or less the default teaser.

So my question is - how do I 'refer' to the title of a teaser made with display suite in order to apply the truncate_utf8 function? Fingers crossed there's a way to do it...

Thanks
A~

If you added the title as a field in Display Suite, I'd recommend you look at the field functions of Display Suite.

You may use a Code field, but I'd discourage that.

Rather remove the title from the display, then add the truncated title as a new field in the preprocess function, ie:

$variables['new_title'] = truncate_utf8($variables['title'], 48, TRUE, TRUE);

Then add a new preprocess field to display suite, using the exact same name as the new field, ie:

new_title

You can then place this new field in Display Suite.


How do you make a module integrate with the Rules module? Rules has so many uses but if another module is not integrated to it, you can not use rules with it. Does anyone know how to integrate a module with rules?

The module I would like to integrate is Metatags.

The best documentation you will find is in http://drupalcode.org/project/rules.git/blob/refs/tags/7.x-2.1:/rules.api.php. You will also find this file in the code you downloaded from drupal.org.

You also would probably learn something from looking at other modules that implement rules similar to how you would like it in metatags and seeing how they implement the above hooks.

Then it is up to you do decide what functionality from metatags you want to expose to rules using those hooks.


Margin before admin menu with Views admin pages Screenshot shows the problem:

This margin appears on all admin pages which use Views on Seven theme and module Administration menu. As example, Drupal Commerce products list. Actually this is because of body class .contextual-links-region. I didn't find any issues about it. Can anybody comment it?

UPD: Problem disappeared after Drupal update to 7.8.

The admin_menu module adds a margin to the top of the page so it can sit there.  I suspect the toolbar module does the same thing which gives you the double margin.

Looking at your screenshot you're using 3 menu modules, which seems overkill to me.  Disable the toolbar module and you should be right.  The admin and admin_menu modules can happily coexist. You can also add custom items to either or both of these menus.

Personally I'd just go with the admin module.


How do you programmatically get the current user's status? I'm trying to get the currently logged-in user's status (active or blocked) in template_preprocess_user. I tried the following with no luck.
function MYTHEME_preprocess_user(&$variables) {
  $user = $variables['user'];
  $variables['status'] = $user->status();
}

function MYTHEME_preprocess_user(&$variables) {
  $user = $variables['user'];
  $variables['status'] = $user->getStatus();
}

Assuming this is Drupal 8, try $user->isBlocked().
If this is Drupal 7, you probably just need to call user_load($uid) first in order to get a fully-loaded user object before checking the $user->status. Or try user_is_blocked($name).


Let users create / list their own restaurant menu I am building a site where a restaurants visitors could register. Now, I have created a content type where the restaurant owners could list up there restaurant. I have to also allow them to add there restaurant menu based on categories like 'starters', 'mains' etc.

Is there any module which could help me achieve this?

Not totally sure what you're looking for. I'm going to assume that you're looking for a particular form to create a restaurant menu from the backend.

Drupal allows you to create this functionality OOTB (out of the box):

Fields (formerly cck pre Drupal 7)
User Roles
User Permissions

You're probably going to need to output this in a pretty fashion so your best bet are some standard contrib modules:

Views
Fields Collections

Nonethless, these modules are standard fare for every Drupal project (except maybe Fields Collections).

Oh i googled and there are possibly similar questions out there on SO:

https://stackoverflow.com/questions/5204936/restaurant-menu-drupal-7
https://stackoverflow.com/questions/4935899/best-drupal-gui-for-displaying-a-tiered-restaurant-menu
https://stackoverflow.com/questions/1835562/drupal-content-type-restaurant-design


Cache-Control response header includes "private" Why does a vanilla Drupal 8 site add cache-control: must-revalidate, no-cache, private to all the pages?

A Drupal 7 site adds cache-control: must-revalidate, no-cache.

Is that addition of private for Drupal 8 somehow configurable? I'd like to not have it there.

It turns out that this response header in Drupal 8 is sent when system.performance:cache.page.max_age is set to 0. Setting it to anything greater than 0 (e.g 123) gives me max-age=123, public. The question still remains: Is there a way to get must-revalidate, no-cache?

The reason I want must-revalidate, no-cache without private is that I want browsers to always make requests for pages, and my cache server (fastly) to cache the content. Having private in the response headers bypasses fastly as per their documentation: https://docs.fastly.com/en/guides/cache-control-tutorial#do-not-cache

This is caused by symfony. private is added via vendor/symfony/http-foundation/ResponseHeaderBag.php and as far as I understand it's not possible to not have it when system.performance:cache.page.max_age is set to 0:

protected function computeCacheControlValue() {
  // ...
  if (!isset($this->cacheControl['s-maxage'])) {
    return $header.', private';
  }

Since I don't want to hack symfony, I can remove private via apache mod_header:

Header edit Cache-Control "(, )?private" ""


Struggling with view results I'm struggling with view results. This is the first time I've ever posted on one of these! I set up a view to filter responses from a survey on a webform. The responses are supposed to show up if one required question is marked true. The other filters are exposed.

The problem is that the results do not show up correctly. Two of the results are included twice, and after a certain date, none of the results are included. Can anyone help? Thank you!

Set query option distinct so that results are included just once

and check your filter criteria, maybe you included some date condition.


How do I put a block in a form? How do I put a block in a form?

My searches on this site and on google only have lead to questions of putting a form in a block. I want the opposite. I have a form definition array in a module, and I want to add in an existing block.

$block = module_invoke('module_name', 'block_view', 'block_id');

  $form['block'] = array(
    '#markup' => render($block),
  );


Is there a way to use a file field without having to upload the file when creating the content? I’m using Commerce File module for creating mp3 products. I’ve been unable to create a bulk feeds importer because of having to upload the files. Is there a way to simply add the file name when creating these products? The files would have already been put on the server.

You should be able to give it a filename of public://... and use that. Just point it to the file you've uploaded.


call javascript function after ajax form submit How do I call a javascript function after a successful ajax form submit?  I want to call a function in a file that I added with drupal_add_js() in my_form_name_form($form, &$form_state).

Have a look at the Ajax framework and Ajax framework commands topics in the API documentation.

Basically, instead of simply returning a single render array, you can return a number of so called ajax commands, which will be translated to javascript and executed on the client side. Replacing the specified wrapper with the returned content is just the default command that is done when nothing else is specified.

There doesn't seem to be a provided command that allows to execute any javascript method (only an invoke command that allows to execute an jQuery command on a defined selector) though. However, you can either define your own command (just have a look at what these helper functions return and the corresponding JS functions in misc/ajax.js (look for Drupal.ajax.prototype.commands = {...).

Or you might be able to replace your custom JS function with a number of the provided default ajax commands. They're pretty flexible and I'm for example using them to update the page title in userpoints.module.


What is the best practice to split up a long global.css in an Omega theme? I am building out a theme based on the excellent base theme Omega. I am using the standard CSS files for narrow, normal, etc. My global.css file is getting large. I would like to split it up. Is there any kind of best practice for this in Omega, or should I just do as I would any other Drupal theme?

Have you subthemed Omega? I would say just modify your .info file and include an extra css file. I do it all the time, splitting them on function, i.e. styling for node templates etc. in one file and so on.


Can't get Emoijone ckeditor plugin to appear on WSYISYG editor I am trying to add the Emojione CKEditor plugin on a Drupal 8.3.7 site. I've created a module using the CKEditor API. I modeled it after both the youtube and smiley CKEditor plugin modules.

In my custom module, I've added the file src/Plugin/CKEditorPlugin/EmojioneCKEditorPlugin.php:

<?php

namespace Drupal\emojione\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "emojione" plugin.
 *
 */
class EmojionePlugin extends CKEditorPluginBase {

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return array(
      'Emojione' => array(
        'label' => t('emojione'),
        'image' => 'libraries/emojione/icons/emojione.png',
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFile() {
    return 'libraries/emojione/plugin.js';
  }

  /**
   * {@inheritdoc}
   */
  public function isInternal() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getDependencies(Editor $editor) {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getLibraries(Editor $editor) {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    return array();
  }

}

The above is basically what both the ckeditor_youtube and ckeditor_smiley have. The relevant methods seem to be getFile() and getButtons().

I have the relevant ckeditor plugin sources under libraries/.

When I enable my module and clear the cache and go to configure text formats and editors at /admin/config/content/formats, I don't see the emojione button, but I do have buttons for smiley and youtube.

I've found this question and this answer, but in the answer, it isn't clear in what file the Template class goes. Also, the answerer mentions some custom js, but doesn't indicate where that goes either.

What am I missing?

You need to add annotation for ckeditor plugin (more info about annotations based plugins here).

Youtube plugin is using this:

/**
 * Defines the "Youtube Button" plugin.
 *
 * @CKEditorPlugin(
 *   id = "youtube",
 *   label = @Translation("Youtube Plugin")
 * )
 */
class YoutubePlugin extends CKEditorPluginBase {

So you will need to add an annotation like this:

 /**
  * Defines the "Emojione" plugin.
  *
  * @CKEditorPlugin(
  *   id = "emojione",
  *   label = @Translation("Emojione")
  * )
  */
 class EmojionePlugin extends CKEditorPluginBase {

EDIT (thanks @kevin): clear caches after changes.


Multiple upload image using managed_file I'm trying to do a very simple thing (seems not that simple at all) in my custom form, to add multiple files using the managed_file form api. Like in the admin, select a file, upload, then a new input file appears.

But I can't achieve that... do I need a callback ???

    'gallery' => array(
        '#type' => 'managed_file',
        '#name' => 'gallery[]',
        '#title' => t('Gallery'),
        '#upload_location' => 'public://',
        '#attributes' => array(
            'multiple' => 'multiple',
        ),
    ),

Thanks

In Drupal 8, add '#multiple' => TRUE

Example:

$form['images'] = array(
  '#type' => 'managed_file',
  '#upload_location' => 'private://images/',
  '#multiple' => TRUE,
  '#upload_validators' => array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_size' => array(25600000),
    'file_validate_image_resolution' => array('800x600', '400x300'),
  ),
);

More about form api: Introduction to Form API


how to allow Inline css tag? I am unable to  use inline css in ckeditor wyswig for full html . In Allowed HTML tags i have added  but the tag "style" get removed in ckeditor and appears as  in finally render of the page  .how can i get  be rendered.

I am trying to use Content  but it appears as Content.

If you have the "Limit allowed HTML tags" checked, it will generate a textarea at the bottom of the configuration of your full_html profile.

You need to authorize the "style" attribute on the span tag by adding this attribute on the list.

<span style>

By default, you have for links :

<a href hreflang>

If you define a new style explained on this documentation it will be added automatically.

EDIT: It seems that for XSS reason, style tag are stripped out everytime, see this thread where they talked about that.
You have to create styles and define what kind of stuff your end user will be able to add. If you absolutely need your user to be able to add some style directly from code source of  your ckeditor, you have to disable the option "Limit allowed HTML tags" but it's not recommended.


generate a coupon automatically after checkout I have a gift store, customers buy a gift cards. I want to generate a gift code after checkout based on the giftcard they bought (I have gift cards from £25 to £200). they can also buy a gift (product) directly. so the cart might be a mixture of giftcard and products. how can I create a coupon after checkout? I will email them this code after successful checkout

there is no action for creating coupon automatically in rules.

Here is a little help.

Actions

Add Action - Entites - Create a new entity - select Commercce Coupon - Continue - Save
Add Action - Data - Set a data value - select the field you want (ex. entity-ecreated:commerce-coupon-number-of-uses) - enter the value you want - Save
Do the 2. for the fields you want

--

At the end I decided to do my custom Rule action for creating a coupon, because is more flexible.


How to create entity reference field from custom entity to specific content type I'm on Drupal 8, using BaseFieldDefinition::create('entity_reference') on my custom entity type to add entity reference field;

I also use this ->setSetting('target_type', 'node') to get nodes but this gives me all nodes of any content type;

Is there any way or possibility to filter these nodes to specific content type?

Here is the code for my field:

$fields['project_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Project'))
      ->setDescription(t('The project ID, transaction was created for.'))
      ->setSetting('target_type', 'node')
      ->setSetting('handler', 'default')
      ->setTargetEntityTypeId('project')
      ->setDisplayOptions('view', array(
        'label'  => 'hidden',
        'type'   => 'project',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type'     => 'entity_reference_autocomplete',
        'weight'   => 5,
        'settings' => array(
          'match_operator'    => 'CONTAINS',
          'size'              => '60',
          'autocomplete_type' => 'tags',
          'placeholder'       => '',
        ),
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

I want this field to be referenced to Content Type called project and not all types of nodes.

You're looking for the handler_settings setting, which provides configuration for the handler you've chosen, in your case, you want:

$handler_settings = [
  'target_bundles' => [
    'project' => 'project',
  ],
];

As always with fields, widgets and formatters, just create a configurable field in the UI, export it and look at the settings there. You can always copy the settings and other things almost 1:1 from the exported YAML files to a PHP array.


How do I hide the display of a field if another field is set? I have a content type with a date field. The date is mandatory, but I want the option to not show the date in all displays if the option is selected. This date field is not published date.

The content type has several display modes, so I want to disable this in all of them. What would be the best way?

My thought is to add an additional boolean field, "Hide date", but then I'm not sure what is a nice clean way to hide the date field everywhere if "Hide date" is selected.

Use the #states property. Here is a tutorial.

Alternatively just use the Conditional Fields module which provides a nice easy to use UI making it easy to set up multiple rules.


Get a list of all enabled block deltas I need an array of all enabled blocks' deltas.

For example, if I display the array, it should output the block deltas e.g. search_form, user_new, user_login, and not the block titles e.g Search, User etc

I've found a few candidates:
http://api.drupal.org/api/drupal/modules!block!block.module/function/block_list/7

http://drupalcontrib.org/api/drupal/drupal%21modules%21block%21block.module/function/block_get_blocks_by_region/7

But they all crash my site. Really can't get it to work, please give some examples that works for you.

I can't imagine why your site is crashing using the two functions you link to (Drupal calls them both internally so it certainly shouldn't be), but you can use the following custom query to grab that data directly from the database:

$query = db_select('block', 'b')
  ->condition('theme', $your_theme_name)
  ->condition('status', 1)
  ->condition('region', -1, '<>');

$query->addExpression("CONCAT(module, '_', delta)", 'delta');

$deltas = $query->execute()->fetchCol();

// $deltas now contains a list of deltas for all enabled blocks in the provided theme


Condition in variation product template is not triggered correctly (ajax caching ?) I have a commerce project with a specific product type using an attribute to generate variation.
Variation product has two specific fields that I want to hide switch attribute.
I implemented hook_preprocess_commerce_product to check this. In my hook, I check for a variation in POST (purchased_entity) or GET (v=xyz). If no one is found, I retrieve the default variation and set into the $variables array a new value called "is_custom_variation". This value is set to TRUE when the variation is a "custom" one. Only one variation in a product can be a custom variation, other are standard variations.
The "add to cart" form use a "select" form element to (ajax) switch between variations.
In the product template (commerce-product--full.html.twig) I added the following code :
<article{{ attributes }}>
{% if is_custom_variation %}
  {{- product|without('variation_attributes', 'variation_field_1', 'variation_field_2') -}}
{% else %}
  {{- product|without('variation_attributes') -}}
{% endif %}
</article>

Strange thing appears when I test the code :

I load the product page with the default variation as "custom" variation : field 1 and field 2 are hidden. When I switch to another "non-custom" variation, fields are hidden too.

I load the product page with a "non-custom" variation : field 1 and field 2 are displayed. When I switch to the "custom" variation, fields are displayed too.

By enabling xdebug, I see that each time the template is called, the variable "is_custom_variation" is correctly set (TRUE on custom variation, FALSE otherwise)
Maybe anyone can point me what is wrong on my implementation... I don't know why the template is using always the same process after the first display. Is it related to ajax reload of the variation ?
Thanks in advance for any suggestion.

If you have other input data(url, query params, timestamp, cookie, etc) than $variables in your HOOK_preprocess you have to update your cache rules otherwise first time you get trough that hook will get cached for the rest of iterations of same $variables input.
In your case I suggest using cache context or cache tags where they change based on POST and GET variables.
https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays


How to theming on webform field element in single twig file (for example webform--contact-us.twig.html? I have tried a lot to get form element in webform twig file. But variables are not coming.For example : when I'm using  {{ element.elements.name }} in webform--contact-us.twig.html , nothing I'm getting. Only {{ children }} is giving me a whole form.

Any help will be appreciated.

Make sure that you are pointing on the right template and try this code :

{{ form.elements.YOUR_FIELD_NAME }}
example : {{form.elements.full_name}

you can check this link : https://www.drupal.org/project/webform/issues/2865940


Which hook to use for updates of all nodes of a particular type This question is about Drupal 7.
For a particular node type, let's take three examples:

a) book
b) article
c) customcontenttype

I would like to be able to capture the moment of an update of an existing node of this type.

I would like to know if there is a way to target only that node type directly from the hook and not to have the hook triggered for all nodes and then checking the node type.

I've seen some internet articles talking about

mymodule_node_update - for me this is a general hook for all
nodes
mymodule_book_update or mymodule_article_update or
mymodule_customcontentype_update
mymodule_form_book_node_form_alter or
mymodule_form_article_node_form_alter or
mymodule_form_customcontenttype_node_form_alter

Which one of the three above hooks should I use? all of them? if none of them are good then which hook to use?

Many thanks

I would like to know if there is a way to target only that node type directly from the hook and not to have the hook triggered for all nodes and then checking the node type.

Node hooks aren't that granular, they're invoked for all nodes and there isn't a system in place to make that selective based on the type. If you're worried about performance, don't be; the difference between the hook being invoked for all nodes, and a system to allow it to be selective would be negligible.

If you want to react to existing nodes being update, hook_node_update() is definitely the right choice.

You just need to test the type in that function:

function MYMODULE_node_update($node) {
  if (in_array($node->type, ['book', 'article', ...])) {
    // Do something.
  }
}


Replace the file on disk while running the migration I am changing the migration code (not written by me) to not create new files on migration but to re-use (or rewrite) the existing files.

The migration code looks like the following:

Source part:

$url = url('filename.json', array('absolute' => TRUE));
$this->source = new MigrateSourceJSON(new MultiListJSON($url), 'name', $fields);
$this->destination = new MigrateDestinationFieldCollection(
  'field_product_documents',
  array('host_entity_type' => 'node')
);
$this->map = new MigrateSQLMap($this->machineName,
  array(
    'name' => array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
    ),
  ),
 MigrateDestinationFile::getKeySchema()
);

Destination part:

$this->destination = new MigrateDestinationFile('file', 'MigrateFileBlob');
$this->addFieldMapping('value', 'blob');
$this->addFieldMapping('destination_file', 'name');
$this->addFieldMapping('filename', 'name');
$this->addFieldMapping('destination_dir' ,'dest_dir')
  ->defaultValue('private://');

This migration is only responsible for creating of the file entities from the blob which comes from a third party service.
There is another migration that is executed after this migration and is responsible for associating the file ids of the files created by this migration.

Following the documentation of the MigrateDestinationFile, the following code could be used to replace the file on the directory:

<?php
    $this->addFieldMapping('field_my_image:file_replace')
         ->defaultValue(FILE_EXISTS_REPLACE);
?>

But, during the file migration I am not associating it with any field. Hence, it could not be used. Or I am not sure of the exact way to use it.

My main concern is (let's say) if I have a file ABC.pdf on disk (might not be associated with any entity), the migration should not create a new ABC_0.pdf.

Any pointers would be highly appreciated!

As a temporary fix I have implemented the following in the prepareRow function.

function prepareRow($row) {
  // Delete the file if already present.
  $file_path = drupal_realpath($row->dest_dir . '/' . $row->name);
  if (file_exists($file_path)) {
    unlink($file_path);
  }
}

However, I am still not sure about the way it is recommended in the Migrate module.


Drupal 7, MySQL, InnoDB, and transactions I was reading default.settings.php for Drupal 7.x this afternoon, and came across this comment:

/*
 * Some database engines support transactions.  In order to enable
 * transaction support for a given database, set the 'transactions' key
 * to TRUE.  To disable it, set it to FALSE.  Note that the default value
 * varies by driver.  For MySQL, the default is FALSE since MyISAM tables
 * do not support transactions.
 */

This is different in Drupal 8:

/*
 * Transaction support is enabled by default for all drivers that support it,
 * including MySQL. To explicitly disable it, set the 'transactions' key to
 * FALSE.
 * Note that some configurations of MySQL, such as the MyISAM engine, don't
 * support it and will proceed silently even if enabled. If you experience
 * transaction related crashes with such configuration, set the 'transactions'
 * key to FALSE.
 */

So, how does db_transaction() work then on MySQL in Drupal 7?

Is this comment outdated, or should I explicitly set

$databases['default']['default']['transactions'] = TRUE;

if I know everything is InnoDB (which is the default for Drupal 7.

The constructor for the DatabaseConnection_mysql class, has this code and comment:

public function __construct(array $connection_options = array()) {
  // This driver defaults to transaction support, except if explicitly passed FALSE.
  $this->transactionSupport = !isset($connection_options['transactions']) ||
    ($connection_options['transactions'] !== FALSE);

In addition, there is support and workaround for the MySQL implementation of transactions (including no proper support for DDL transactions).

This suggests that the documentation in the settings file is incorrect.


Add extra fields to a node display I want to add extra fields when a node is displayed, the data of this fields are fetched from an external db.

I'm uncertain if I've to use the hook_node_view_alter function or hook_node_view.

I don't understand if the extra fields to add are in the node form or into the page(display of node). If it's the first thing I think you can use hook_form_alter to add the extra fields and in the second case you can use hook_preprocess_node to add the variables to 'send' to the front-end of site.


Return a 404 when a view pane in a page manager page has no result? When you have a view page that takes a contextual filter, you can easily set the no result behavior to a 404. But I am trying to do this when I have a view pane, in a page manager page like in the screenshot attached

If the view has no result (contextual fitter does not validate) I would like the page to return a 404.

You can implement hook_views_pre_render in your module to do this task

/**
 * Implements hook_views_pre_render().
 */
 function mymodule_views_pre_render(&$view) {
   if ($view->name == 'myview' && $view->current_display == 'mypane') {
     if (empty($view->result)) {
       drupal_not_found();
     }
  }
}


Moving / Migrating image files from another site into an existing Drupal 7 site I'm currently doing a data migration from one Drupal 7 site to another Drupal 7 site. So far I exported the data from the old site into a CSV file and then have it get imported into the new site by looping through each row of each result and doing a $node object and then node_save.

The problem now is how do import/copy the images over? I have the url path from the old site.Do I use file_unmanaged_copy() function to get them into the system? But from the docs, it says I can only use public:// and I'm not sure if http urls to the images would work. Or is there another function I need to use for this purpose?

Why not use Feed Import  I am using it to import content from Joomla and WP sites into new Drupal sites with Drupal to Drupal export import should be a lot easy.
My process is as follows:

Create desired content types with all matching fields on the new
site.
Create Import profile for this content type go to mystie/import to
download csv template
Export content from the old site with path to images so to have
matching content with image
Upload images to new web site and change paths in csv file
Import and create or update content.


MEGA MENU please help trying to assign it the right region but no luck :( Hey can you guys please help me out iv tried researching and asking other but unfortunately have screwed it up many times and cant seem to get an answer out of anyone. Can someone please help me understand how to create a new region? I have mega-menu atm but when it was created in the files it went driectly under the menu bar which is not desirable... all im trying to do is put the mega-menu "menu" over the default one so it looks nice and professional anyone that can help me out, thanks.

It depends a bit on your theme but for bartik here is answer:

In theme info file add this:

regions[my_custom_region] = My Custom Region

Then copy page.tpl.php from the base theme, or else from modules/system directory into your theme's folder. Open it up, and look for the bit where it prints out the main menu. It will be something like this:

<?php if ($main_menu || $secondary_menu): ?>

        <?php print theme('links__system_main_menu', array('links' => $main_menu,
'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline',
'clearfix')), 'heading' => t('Main menu'))); ?>
        <?php print theme('links__system_secondary_menu', array('links' =>
$secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' =>
array('links', 'inline', 'clearfix')), 'heading' => t('Secondary menu'))); ?>

<?php endif; ?>

Remove this bit, then add this in its place:

<?php print render($page['my_custom_region']); ?>

Now clear your cache and place your block inside it.

Rename the my_custom_region to whatever you like, but make sure it is same in info file and page.tpl file.

If you don't want to replace the main menu then you can just paste the new code underneath the main menu, and in the menu settings UI select no main menu to hide it.


How to create a custom design of an existing view block? I have a block I created via views ui. It is in a table format. It has 3 columns with 3 fields. Every field shows in a separate column.

Now I want to change the design of this block in an easy way to my likings.

For example here is the screenshot of one of the blocks to explain what I mean.

This shot is showing user-pic, username and follow-flag resp. As indicated in the snapshot, I want to show follow-flag below the username.

How to easily change the design of my view or block? The best would be a drag & drop. I guess this is an easiest way.

By modifying the view templates the views can be altered.
You can add custom html design and styles to modify design.

From Page: Theming information select the template. For eg:  views-view--sample--page.tpl.php, template for the view named Sample.


How should I use a field in views? I have a CCK field that I want to use in a view. How can I do it?

When you are in edit mode of your view:

you should have an option of adding fields

When you click on add field, you should see a drop down of all types of field available.

Choose Content from the drop down.

You should be able to see your cck field there, click add and review the settings for the display of the field.
I suggest you checkout this video to get overview of views - http://mustardseedmedia.com/podcast/episode9