Programatically redirect to node/nid doesn't redirect to url alias From what I understand the module 'GlobalRedirect' has been merged into the 'Redirect' module. So the redirect module should also redirect links as node/nid to it's url alias. When creating redirects trough the interface this works perfectly. But if I programatically do a redirect to a node/nid page it isn't being redirected to it's url alias..
Not sure if this is bad coding on my part, or feature not implemented in the module.

  /* @file EventSubscriber.php */

  public function onRequest(GetResponseEvent $event) {
    $baseUrl = $event->getRequest()->getBaseUrl();
    $attr = $event->getRequest()->attributes;
    if(null !== $attr && null !== $attr->get('node') && $attr->get('node')->get('type')->getString() == 'product_group' &&
    $attr->get('_controller') == '\Drupal\node\Controller\NodeViewController::view') {
      $node = $attr->get('node');
      $references = $node->get('field_references');
      $values = $references->referencedEntities();
      if($values){
        $nid = $values[0]->id();
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $event->setResponse(new RedirectResponse($baseUrl. '/' . $language . '/node/' . $nid));
      }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['onRequest'];
    return $events;
  }

I'm using this code to redirect a product group to it's first referenced entity node, which uses automated url structure generated by a pathauto pattern, but the url alias isn't being shown after the redirect, it shows node/nid. I've verified that the url alias on that page actually works, and even added a redirect from that specific node/nid to it's url alias trough the interface, but no luck.

Am I doing something wrong? Is this working as intended? Is there a cleaner/better way for me to redirect? Still quite new to Drupal 8..

Using:
Drupal 8.1.3
Redirect 8.x-1.0-alpha1
Pathauto 8.x-1.0-alpha3

Try using Url.

$url = Url::fromRoute('entity.node.canonical', ['node' => $node->id()]);
new RedirectResponse($url->toString());


Drupal UberCart how can users see thier own orders I'm setting up a shop on one of my sites, and I've set it so users create an account when they order. When users log in, I cannot workout the link to show their past orders, or registered addresses.

Is there anything built into UberCart for this? All I've found are some permissions and I've set "View own order." Do I have to write up a module for this?

If the users are not anonymous users, they should have a tab in their user profile that shows their orders.


How to create a taxonomy terms dropdrown with Views I need to achieve a block containing a dropdown list of vocabulary terms (called topics). Each topic describe one or many of the content articles. Each topic which is assigned to no articles should not be displayed. When selecting the topic from a dropdown list a page with assigned articles should be displayed.

It seems like achieving a dropdown list of terms from within a view is harder than expected.

Here my steps:
I created a View with display page and exposed form in block: Yes
I selected the term ID and term Name fields; then I expose the filters as "Operator: Is one of," and I selected all. It seems like nothings happens.

There are several approaches:

A. Create a View out of Taxonomy Terms with a Page Display.

For fields add: term id, term name
For filters: Term name (with widgets) and expose the filter

Choose then:

Dropdown,
Vocabulary (of your choice)
Expose this filter to visitors...,
'Is one of' then select all terms from the vocabulary
Remove duplicates

In Views UI, on Advanced Tab

Exposed form in block: Yes
Exposed form style: Basic | Settings
Adjust settings to have autosubmit

B. Create a View out of Content and choose Taxonomy Terms among fields, similar to above.

C. Create a View with Block display from Taxonomy Terms and at Format Tab choose Jump Menu. If you need to overwrite the Jump Menu path you need to add a custom text field and create your desire path out of Replacement Patterns.

Than select the created custom text field from Jump Menu path settings


Cloning content type edit link When developing a site I often want to be able to access content type definition from the level of a viewed node representing it. So basically I'd say I'd need a new MENU_LOCAL_TAB with the path /admin/structure/types/manage/%.

What hook should be used so to not replace/override the already existing path? I would not like the corresponding item to disappear from Admin Menu. I just want to have a handy duplicate shortcut tab within a node.

You won't be able to get a tab with exactly that path in it, as it won't match the node/% path and the tab simply won't show.

The easiest way I can think of to do it would be to create a proxy page that does match that pattern. Something like:

function MYMODULE_menu() {
  $items['node/%node/manage-ct'] = array(
    'title' => 'Manage content type',
    'access arguments' => array('something appropriate to your install'),
    'page callback' => 'MYMODULE_node_manage_proxy',
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK
  );

  return $items;
}

function MYMODULE_node_manage_proxy($node) {
  $type = str_replace('_', '-', $node->type);
  drupal_goto('admin/structure/types/manage/' . $type);
}

That way the tab will appear, but as soon as the user clicks through to the page it will redirect to the node type form.


Serve drupal page to secondary domain I have a drupal site running on a server with two domains pointed to it: domainA.com and domainB.com. I would like domainB.com to serve a specific landing page, http://domainA.com/landing-page. I know I can do a normal htaccess redirect like this:

RewriteCond %{HTTP_HOST} ^domainB\.com
RewriteRule ^$ http://domainB.com/landing-page [L]

Which will serve my users the correct content.

But I would rather the path wasn't added to the url.  Is there a way to do a 'transparent' redirect for domainB.com so that http://domainB.com/ serves up the content from http://domainB.com/landing-page without modifying the url? So that it seems more like the 'homepage'?

At least two ways of doing this come to my mind:

1. "Masking" your subdomain and proxying the content. What you do in this case, is that besides your mod_rewrite's redirection, you use mod_proxy to show your other domain's content without changing your URL. Have a look at Using mod_rewrite for Proxying.

2. Using the Domain Access module. Another option, maybe overkill if you are going to use this only for one page, but useful if you have to repeat this with many domains/landing pages.

Since this module allows you to create individual homepages on a per domain basis, you just have to add a second domain (domainB.com) and set /landing-page as Drupal's default homepage in the domain settings. Now when you go to domainB.com, your url bar will just show http://domainB.com but will render /landing-page's contents (since it's the homepage).


Using Rules to Update the Data of a Relations Endpoints (Referenced Entities) I have a Rule which triggers on a Relation update. It then checks for the Entity type of the first endpoint of the Relation. Then checks for a specific field. When I try to set an action to change this specific field, I get these errors related to the Revision ID which I can't seem to figure out.

Notice: Undefined property: stdClass::$revision_id in drupal_write_record() (line 7030 of ...\www\includes\common.inc).

Notice: Undefined property: RedhenContact::$revision_id in EntityAPIController->saveRevision() (line 525 of ...\www\sites\all\modules\entity\includes\entity.controller.inc).

Notice: Undefined index: revision_id in EntityAPIController->saveRevision() (line 528 of ...\www\sites\all\modules\entity\includes\entity.controller.inc).

Notice: Undefined index: revision_id in EntityAPIController->saveRevision() (line 533 of ...\www\sites\all\modules\entity\includes\entity.controller.inc).

DatabaseTransactionNoActiveException: in DatabaseConnection->rollback() (line 1024 of ...\www\includes\database\database.inc).

Simply put, I need a specific field on an Entity to update when a related Relation is updated. This seems simple, but for some reason I cant get it worked out...

Just in case someone happens upon this, I did find a patch that provided the solution for this error. Turns out the Redhen module had some revision conflict with the entity API, so this patch here fixed the error, and it should be included in further Redhen updates


Drupal 7: Webform Emails: How to change content based on a condition? I have a webform and I want to send email on submission to this form.

Currently, I configured the emails and its working fine. However, I would like to put conditions on sending the email.
Like if field_1 = "xyz" then change the email content to "abcd"
     else change email content to "pqrs"

Can this be done using the inbuilt module for emails?
Please help

I reckon you can get there just using Webform and applying some Conditions. Here is the recipe I just tested.

Add a 'country' select field, with options NZ and USA
Add a 'usa1' textfield, set as private, and enter default value you want to go in your email when USA is chosen ('love usa').
Ditto for an NZ textfield (nz1) ('go nz').
Now set up a condition that will 'show' (to admins only as it is private) the USA text field when USA is chosen as country,
ditto a condition so if NZ is chosen, the NZ text fields 'shows'.
Now set up your email with eg [submission:values:usa1][submission:values:nz1]

and presto hey!

If i select USA as country I get email saying 'love usa'.
if i chose NZ I get 'go nz'

Is that pretty much what you need?

NB: I thought this route would work as we had done similar when we needed an email to go out to addressX 'only' if a user chose USA as country.
We used webform conditions and
We craeted an email field that was set to private. Then used conditions to 'show' it (to admin only) if USA was chosen.
Then we could just set up a new webform email using that field, and it only fired if the condition was met.


Migrate file field paths not the actual file Say I drag and drop files from a source site into the folder structure of a new site (destination site) that I'm migrating content to. The source sites file paths are the exact same as the destinations paths.

Source:      sites/default/files/attachments

Destination: sites/default/files/attachments

So instead of migrating the actual file I just need Drupal to point to the same location as the source site and the file will be there but when migrating the files over it wants to migrate the entire file.

Is this possible? Maybe after content migration I will need to reconfigure the attachments paths?

Say I drag and drop files from a source site into the folder structure of a new site (destination site) that I'm migrating content to.

Dont do this. Migrate D2D has file handling classes to move the files for you. In the UI it's super easy, in code you select the correct file handing class.

Read the documentation on migrating files for D2D. There are 4 cases it supports, depending on how the remote file needs to be fetched.

In the D2D UI you just want to be sure to setup the File_class value for your migration ok. Typically the Files are migrated (moved) to Drupal as 1 of the 1st auto-generated migrations. Then in Node content that relates the migrated files to the (migrated) Node you set file class to FileFID and select the previous Source Migration that moved the file into the new site.

EDIT

So for example with a website with existing image fields in a content type. On the destination Drupal 7 side of the migration I tell it the legacy field and tell the configuration to use MigrateFileFID this will map just the file ID between the 2 drupal instances:

See field_ofellow_photo above for an example of this configuration for D6 -> D7.

Then Migrate will see the information for the migration steps:

If you use MigrateFileFID then Migrate doesnt (necessarily) move the files I believe if you leave off the destination information, it just moves FIDs. See the documentation on MigrateDesinationFile and MigrateFileFid.


basics of settings.php and settings.local.php? What is the up-to-date basic workflow regarding database credentials when you launch a local version of a site that is already operating remotely?

What are the considerations and how is each best addressed? Are there advanced considerations that might require one to vary the basic approach?

Thoughtful confirmations of the community's understanding welcomed. (As appropriate) I'll happily help kick off documentation. It appears not to be documented clearly elsewhere, though if someone else has seen clear documentation on each point of the workflow and related decisions, please include links in your remarks.

UPDATE:

As promised above, I've started working on improving drupal docs. I've opened an issue https://www.drupal.org/project/user_guide/issues/3013725

Its common to either include a local settings file from settings.php or create a site folder for local development (local.mysite.com) that has a settings file that will be used. In either case, both are gitignored so its only for you. This also avoids the annoying issue when Drupal locks the site folders from being written, causing git errors when pulling or switching branches.


Is there a way to pass additonal php.ini settings to a drush command? I want to specify additional php.ini settings to a drush invocation in the manner they would passed using -d option if drush was a php script that could be passed to PHP using the -f parameter.

On looking at drush  shell script - /usr/bin/drush - I see that it executes the drush.php script in that manner.

Is there a way to add more of those through the command line?

In the Drush README file, in the section titled "CONFIGURING PHP.INI", you will find instructions on how to set php configuration variables without modifying the drush script:

export PHP_INI='/path/to/php.ini'
export DRUSH_INI='/path/to/drush.ini'
export PHP_OPTIONS='-d memory_limit="128M"'

The first option replaces the entire php.ini file with one of your choosing.  The second option allows you to specify an ini file that is merged in with the standard php-cli ini file.  The last option allows you to specify commandline options to set configuration values.  Note that the second option effectively works the same way as the third option -- all of the settings are converted to commandline options.  See the php documentation for more information on php commandline options.

If you want to do this for just one call:

alias specialdrush='/usr/bin/env PHP_OPTIONS="-f /path/to/my/php.ini" drush'


how to get the url to usefor a private path if I have a file saved in private:://somefile.txt  , what function can I use in drupal to give me the external URL to access that?

I tried PrivateStream::getExternalUrl()
but I get this error

PHP Fatal error:  Call to undefined method Drupal\mymodule\myservice::getTarget() in /opt/DrupalSites/drupal-wcms-migration/docroot/core/lib/Drupal/Core/StreamWrapper/PrivateStream.php on line 50

You can't call PrivateStream::getExternalUrl() directly because it's not a static function; it needs an instantiated stream before you can call getExternalUrl() on it.

You can retrieve it via the stream wrapper manager's getViaUri() method:

$stream = \Drupal::service('stream_wrapper_manager')->getViaUri('private:://somefile.txt');
$stream->getExternalUrl();


Quicktabs not looking like tabs I use quicktabs on D8. When choosing the formater "quicktabs" the tabs do not look like tabs at all, they are just shown as normal links. They have no outlines and so are hardly recognizable as tabs at all. Should they not look like the "normal drupal tabs"? (When I choose to show the tab title, it is also not formated, just plain text, I guess it should be formatted as a header?)

I tried different themes, does not make a change, of course the site looks different, but the tabs still have no outlines. Currently I use Bootstrap default theme.

I am quite new to drupal, just building the site structures now, not having any idea of theming yet. I was already searching a lot, no clues, and all pictures I find of quicktabs on D8 look like tabs, not like the "linklist" I see.

Any hints appreciated :) I am absolutely willing to read / learn more, so if anyone could tell me, where to find more information, that would be great!

(EDIT)
Looks like Quicktabs in D8 are causing several problems. Suddenly all context filters are no longer working for views inside quicktabs (they are working fine outside). And when I add a new quicktabs instance I have to clear the cache to make it show as an available block in the block layout page. Looks like I have to find a layout without tabs... :/

Is anyone using Quicktabs in D8 working as expected?

Did you try changing tab style? I haven't tried Drupal 8. But you can select no style option in tab style for Drupal 7. Which does not apply any CSS to tabs.


WYSIWYG Editor questions We've had a custom theme made out of two themes combined basically a news and a video content section--I've installed WYSIWYG and TinyMCE.  The weird thing is that the rich text editor only shows up when editing content in the video section, and not the news section. In the news section, not even the Enable Rich Text hyperlink shows up.

Is there a particular line of code I can look for that would enable the link (and therefore the editor) to show up in the news section?

It's likely that you need to set your news 'body' field's text format to 'Full HTML' instead of 'Filtered HTML'.

For more info on your current setup head to admin/config/content/wysiwyg to see which Text Formats have the WYSIWYG editor applied.


Get labels of view modes in Drupal 8 I'm trying to rebuild the pullquote module in Drupal 8 but am running into an issue accessing view modes. In the Drupal 7 version, the view_modes variable is set by the following lines:

$entity_info = entity_get_info('node');
$view_modes = $entity_info['view modes'];
$view_mode_options = array();

foreach ($view_modes as $mode => $settings) {
  $view_mode_options[$mode] = $settings['label'];
}

However, entity_get_info() has been depreciated in Drupal 8, and according to the documentation I found, replaced with \Drupal::entityTypeManager()->getDefinition().

So I tried replacing the first line:

$nodeEntity = \Drupal::entityTypeManager()->getDefinition('node');

but the array was empty, so maybe I'm using the wrong tool.

I then found this answer for accessing a list of all view nodes.

$view_modes = \Drupal::entityQuery('entity_view_mode')
  ->condition('targetEntityType', 'node')
  ->execute();

It worked, however, they were returned like this:

['node.full', 'node.rss', 'node.teaser']

But here's the problem. I'm using these view modes as options in a form. When the form is saved in configuration, having a key with a period breaks the YAML file with the following error: The website encountered an unexpected error. Please try again later. Drupal\Core\Config\ConfigValueException: node.full key contains a dot which is not supported. in Drupal\Core\Config\ConfigBase->validateKeys(). I'm confused though, because I map over the array so that I'm stripping the names of ".node"

Here's my full code for reference:

// Load the list of avialable view modes.
$view_modes = \Drupal::entityQuery('entity_view_mode')
  ->condition('targetEntityType', 'node')
  ->execute();

// remove "node."
$view_mode_options = array_map(function ($mode) {
  $parsed = substr($mode, 5);
  return $parsed;
}, $view_modes);

$form['view_mode_settings']['pullquote_view_modes'] = [
  '#type' => 'checkboxes',
  '#title' => t('View Modes'),
  '#options' => $view_mode_options,
  '#default_value' => $config->get('pullquote_view_modes'),
  '#description' => t('Choose which view modes will load pullquote code and render pullquotes. For better performance you should only load pullquote where you need it.'),
   '#states' => array(
     'visible' => array(
       ':input[name="pullquote_load_by_view_mode"]' => array('value' => 1),
       ':input[name="pullquote_scope"]' => array('value' => 0),
     ),
   ),
];

Now the view modes display properly on the page, but I still get the error that Drupal can't save "node.full" in configuration, which is confusing because the page displays only "full."

Is there a method for getting the label of different entity types? Or is there a way to actually parse "node.full" down to a string that is only "full"--both when it displays and how Drupal understands it?

Drupal 8 services are essentially helpful objects (tools), which live inside the services container (tool belt). Calling a service returns an object, essentially providing a clear path to the helper methods within that class. As previously answered, EntityDisplayRepository class contains various methods, specifically one that will return an array of entity view modes (see a list of available methods). By calling \Drupal::service('entity_display.repository') and storing it in a variable, you now have an object that you can then call EntityDisplayRepository methods from, which in your case, is to return 'node' view modes.

/**
 * Implements hook_preprocess_page().
 *
 * This function is called before the page is rendered.
 */
function modulename_preprocess_page(&$vars) {
  // call the entity service.
  $nodeEntity = \Drupal::service('entity_display.repository');

  // call the necessary method in order to return 'node' view modes.
  $nodeEntity->getViewModes('node');

  // one line: \Drupal::service('entity_display.repository')->getViewModes('node');
}


ZEN 5 Responsive - general questions For a couple of last days I've read dozens of articles about Zen 5, its grid system and responsive design. But there are still some questions need to be answered or maybe confirmed.

1. responsive-sidebars.scss file

Let's say I want to have different text color of main content for different media queries. I guess the overall definition of the color should be in pages.scss file, but for specific media queries it should to be in responsive-sidebars.scss, right? A've added a color: red; syntax to the example shown in the second question. Is this correct place for this property and value?

2. Override $zen-column-count variable

Let's assume that I want a scenario like this. For the front page I want to have 5 column grid at @media all and (min-width: 960px). But for non-front pages I want to use 10 column grid at the same media query. I reckon, I can do it like this:

@media all and (min-width: 960px) {
 $zen-column-count: 5;

 .sidebar-first {
  #content {
   @include zen-grid-item(4, 2);
   color: red;
  }

  .region-sidebar-first {
   @include zen-grid-item(1, 1);
  }

 /* not-front pages */
 $zen-column-count: 10;

 .not-front .sidebar-first {
  #content {
   @include zen-grid-item(7, 3);
  }

  .region-sidebar-first {
   @include zen-grid-item(3, 1);
  }

 }
}

3.Different max-width query for front and non-front pages.

Let's say I want to have different max-width query for front and not-front pages. In the responsive-sidebars.scss file I found this notation:

@media all and (max-width: 1125px) {

}

While the only difference between front and non-front pages is a body class, how can I prevent this to use it only for front page? Is the notation of ".front" class is enough to apply this media query to front page?

The short answer is yes; the .front class is more than adequate.

Using SASS nesting, your CSS would probably end up looking something like the following.

@media all and (min-width: 960px) {
 $zen-column-count: 5;

 .front {
   .sidebar-first {
    #content {
     @include zen-grid-item(4, 2);
     color: red;
    }

    .region-sidebar-first {
     @include zen-grid-item(1, 1);
    }
  }

 /* not-front pages */
 $zen-column-count: 10;

 .sidebar-first {
  #content {
   @include zen-grid-item(7, 3);
  }

  .region-sidebar-first {
   @include zen-grid-item(3, 1);
  }

 }
}

Note that I've removed the .not-front class from the second batch. Adding the .front class to the first block gives it a higher level of specificity, so it can't be overridden by what is in the second block. Basically, if you are using .front for the first bits, then it is redundant to use .not-front for the second block.

As an FYI, there is an awesome CSS specificity article here.


How do I programmatically create a node with an entity reference (to an user)? It is kind of strange because my code creates the node with the referenced user uid in node_field_data, but when I open this node the user reference isn't working. Then I navigated the database and found that, when I update the user reference field in the interface, it is also written as a new registry in the table node__field_user, so I guess I should insert it there too.

But, I don't know how to do this with the API, and I think making it with a SQL query probably means security issues and is probably much more complicated than however it can be done with the API.

This is my code:

  $node = Node::create(['type' => 'nodetype']);
  $node->set('title', $username );
  $node->uid->entity = $userId;
  $node->enforceIsNew();
  $node->save();

Set owner $node->setOwnerId($uid);

Set field reference $node->field_user[] = $uid;


How to only allow a node to be viewed in its assigned language? I have three languages on my site:

/en
/es

If I have a node with ID = 1234 and this node in english, then I can view it as follows:

/en/node/1234

And this will redirect to

/en/my-page

Which is great! The problem is, if I view this ENGLISH page from another language. I.e. If I open this:

/es/node/1234

Then it opens the english page but the link remains at /es/node/1234

I enabled the "Translation Redirect" module, but this doesn't do exactly what I was hoping it would do. In the above case, if you open:

/en/node/1234

And there IS a "ES" version of the page, it will redirect to that page. Which is great, except sometimes I have a page that does not have a translation, and in the case I want that link to redirect to the correct page. In other words, opening this:

/es/node/1234

Must take you to:

/en/node/1234

Which will then automatically take you to:

/en/my-page

Is there a way to enable this in i18n or must I write something custom to do this?

i18n_redirect module has simple code, so turn it off, and add next code to custom module:

/**
 * Implements hook_init()
 */
function CUSTOMMODULE_init() {

    $path = $_GET['q'];
    $language = i18n_language_interface();
    // Not for logged in users nor for home page
    if (!$path || drupal_is_front_page() || !empty($GLOBALS['user']->uid)) {
        return;
    }
    elseif ($translations = i18n_get_path_translations($path)) {
        if (isset($translations[$language->language]) && $translations[$language->language]['href'] != $path) {
            drupal_goto($translations[$language->language]['href'], array('language' => $language), 301);
        }
        else {
            // Here we working with node, since question about node redirections
            $node = menu_get_object();
            if ($node && $node->language && ($node->language != $language->language)) {
                $languages = language_list();
                if (isset($languages[$node->language])) {
                    $language = $languages[$node->language];
                    drupal_goto('node/' . $node->nid, array('language' => $language), 301);
                }
            }
        }
    }
}


How do I build a view of menu items? Scenario

"landing page" content type, with node 1 at path node/1
corresponding menu item A (with path node/1)
children menu items of this menu item, B, C, D (with arbitrary paths http://google.com, zee/bang, and node/1234)

Objective

Build a view which displays on node/1, whose results are links B, C, and D.

In Drupal 7, i would have used https://www.drupal.org/project/menu_views to accomplish this.

How best to achieve this in Drupal 8?

Right now, I think D8 is too initial state to have a contrib solution for something "custom" like this. Personally, I would leave Views, and going instead:

Set up a route to a controller
In controller inject your own custom services and return the results in twig.
In your own service, inject any other service you need and to the business logic here.


Visibility problem with 'restricted to certain pages' I'm porting a site from D6 to D8 and having problems with block visibility for listed pages. I have a config like this which worked on D6:

news
news/*

And pages like /news/op-ed-suu-kyis-plan-outsource-myanmars-presidency-problems-proxy would match and display the block. In D8.1.2 I have the same rules, but the migrated page with the same URL doesn't trigger the block. If I remove the rules, the block displays again, so it's definitely something here.

Am I missing some changes in how D8 handles these rules? or is it maybe something with URL aliases?

Of course! Now that Drupal 8 returns URL aliases with the leading slashes, I needed to update my rules to:

/news/
/news/*

to get it working as in D6


Migrating XML source twice, according to language I am writing a scheduled import using the Migrate module, where I have an XML feed which gives me a number of reports.
These reports have most of their fields in common, but have two fields ("location/name" and "desc") which are supplied twice, each specific to a language.

My question is how I could import this into two nodes, one for each language? My first thought went out to using stubs, but thinking on that I can't figure out how.

Ofcourse, the "location/name" and the "desc" elements should only import the one relevant to the language being imported.

Altering XML structure is not possible, data in the fields has been altered for privacy reasons.

Example XML and current code: https://gist.github.com/Tagini/8319661

P.S.: Any help on migrating the location (using Location module) is welcome.

Turns out I didn't look at SimpleXML enough.

Using XPath, I can very easily select one of the languages through the lang attribute, and as such have one language imported.

If i then make a second migration for the other language, my problem is solved.

For reference, the selector for the description now looks like this:

$this->addFieldMapping('body', 'desc')
  ->xpath('desc[@lang="nl"]');


Editing order confirmation email in Drupal 7 Commerce I am using Drupal 7 with Drupal Commerce (not Kickstart). I am having difficulties editing the order confirmation email. I am hoping to basically "duplicate" the Order review page from the Checkout process to be included in the email (order items, prices, total and billing info).

The module I installed is Commerce message and I just had no luck trying to edit the order confirmation email. I do have the Tokens module installed and enabled.

I tried to edit the email under Structure -> Message Types, however, the replacement tokens available (for example: [message:message-commerce-line-item]), don't seem to output anything in the email. Actually, the token itself is included in the email, like so:

[message:message-commerce-line-item]

I have tried several other tokens with the same result. I tried to select Filtered HTML and Full HTML.

Reading through the Drupal Answers I also tried to use !order-summary token, which seems to work, however the email is "unstyled" and includes HTML tags, like so:

     testing credit card payment

     $0.25

     1

     $0.25

What puzzles me the most is seeing answers like this or this, stating that

  You want the Commerce Message module and it's dependencies. It includes customer emails with a full order details, including customer profiles and all the products purchased

Any ideas on the issue? I failed to find any Commerce message tutorial or the way tokens should be used with it in Drupal Commerce. I'd be happy to go through one if it exists, I would be willing to even write one for future users who might have the same problems once I figure this out.

Thanks

I the end, I had to install the Mime Mail module. My site uses gmail for the site's email, so I had to use Mime Mail together with SMTP module.

The emails render html tags and tokens as needed.

For someone who might experience the similar issue, here is how I configured the Mime Mail witih SMTP:

In admin/config/system/mailsystem scroll down to the "New Class" fieldset. Create a new class using MimeMailSystem for format() and SmtpMailSystem for mail(). Use that newly created class for the "Site-wide default MailSystemInterface class.

I'm still not completely satisfied with this solution as I was hoping to make Commerce Message to work. If someone ever gets to respond to this I would be thankful for the answer.


Add class to views row instead of replace system classes I have this code:

function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image)) {
      $vars['classes_array'][$id] = 'has_field';
    }
    else {
      $vars['classes_array'][$id] = 'has_no_field';
    }
  }
}

It works, but replaces all system original classes.

How to just add class?
I tried with $vars['classes_array'][$id][] but I'm getting: Fatal error: [] operator not supported for strings

Your question is simply a PHP programming question, and not entirely Drupal related. But here goes:

function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image)) {
      $old_class_values = $vars['classes_array'][$id];
      $vars['classes_array'][$id] = $old_class_values . ' has_field';
    }
    else {
      $vars['classes_array'][$id] = $old_class_values . ' has_no_field';
    }
  }
}


How to identify all modules hosted on drupal.org that depend on a given module? Assume any contributed module X (e.g Quiz) on drupal.org (=D.O), or any of its sub-modules Y (e.g Quiz Stats). Any such (sub-)module may depend on one or more other contributed (sub-)modules Z (e.g Charts, disclosure: I'm a co-maintainer), as indicated in the (sub-)module's info file (e.g in the last line of the info file of the Quiz Stats module).

My question: How can I identify all modules X and submodules Y, which depend on module Z?

The question about "Is there a drupal.org API for retrieving the list of available modules?" is somehow related (not a duplicate IMO), but none of the answers there seem to help to find the answer to my question, or am I missing something in those answers?

Note: this question is really about modules "on drupal.org", so I may not even have Drupal installed anywhere ... Think of this question in the context of, for example, a d8rules campaign, where somebody wants to try to find other modules depending on Rules to reach out to the module (co-)maintainers of those other modules (for whatever reason related to such campaign).

As was mentioned above the solution could be parsing info files of all projects hosted on drupal.org. You can use this small tool to facilitate the process of obtaining the codebase of Drupal contributed projects.

Below is an example of searching dependencies for Quiz module.

drupal-project-loader -c 5 -b 7.x -d d7_modules -y &&
cd d7_modules && ag 'dependencies\[\] = quiz$' -G \.info$ |
sed 's/\/.*//;s/^/https:\/\/www.drupal.org\/project\//' | uniq | sort

The result:

https://www.drupal.org/project/certificate
https://www.drupal.org/project/certify
https://www.drupal.org/project/civicrm_cert_quiz
https://www.drupal.org/project/cloze
https://www.drupal.org/project/course
https://www.drupal.org/project/elms_features
https://www.drupal.org/project/grouping_question
https://www.drupal.org/project/image_target_question
https://www.drupal.org/project/kalvi_core
https://www.drupal.org/project/mark_word
https://www.drupal.org/project/og_quiz
https://www.drupal.org/project/opigno
https://www.drupal.org/project/opigno_pretest_app
https://www.drupal.org/project/opigno_quiz_app
https://www.drupal.org/project/opigno_quiz_import_app
https://www.drupal.org/project/qq_import
https://www.drupal.org/project/quiz
https://www.drupal.org/project/quiz_ddlines
https://www.drupal.org/project/quiz_drag_drop
https://www.drupal.org/project/quiz_evaluation
https://www.drupal.org/project/quizfileupload
https://www.drupal.org/project/quiz_h5p
https://www.drupal.org/project/quiz_progress
https://www.drupal.org/project/quizrubric
https://www.drupal.org/project/quiz_sentence_drop
https://www.drupal.org/project/quiz_share
https://www.drupal.org/project/quiz_userpoints
https://www.drupal.org/project/quiz_voice_answer
https://www.drupal.org/project/quizwebform
https://www.drupal.org/project/simple_mcq
https://www.drupal.org/project/tincanapi


Conflicting realm variables when using i18_variable I'm using i18_variable, and I'm using the hook_variable_info, hook_variable_group_info....I enabled the custom variables I defined after that from the admin/config/regional/i18n/variable page.

But I'm getting this error on the variable configuration page in the module

There are conflicting realm variables in the form. The variable New Name is enabled for more than one realm. Review your realm settings

Any particular reason on what could be triggering it?

Here is the relevant code.

function embed_form_menu() {

    $items = array();
    $items['embed-form-configuration'] = array(
        'page callback' => 'drupal_get_form',
        'page arguments' => array('get_embed_form_configuration'),
        'access arguments' => array('Embed Form Configuration Permission'),
        'access callback' => TRUE
      );
    return $items;
}

function get_embed_form_configuration() {
  return drupal_get_form('variable_module_form', 'embed_form');
}

function embed_form_variable_info($options) {

  $variable['embed_form_newname'] = array(
    'title' => t('New Name', array(), $options),
    'description' => t('Enter your new name, please.', array(), $options),
    'type' => 'string',
    'default' => t('Drupal user', array(), $options),
    'group' => 'embed_form',
    'localize' => TRUE,

  );

  return $variable;
}

/**
 * Implements hook_variable_group_info().
 */
function embed_form_variable_group_info() {
  $groups['embed_form'] = array(
    'title' => t('Embed Form'),
    'description' => t('Embed Form Config'),
    'access' => 'Embed Form Configuration Permission',
    'path' => array('admin/config/system/embed-form'),
  );
  return $groups;
}

function get_embed_form_configuration() {
  return drupal_get_form('variable_module_form', 'embed_form');
}

Found the fix thanks to some help from @piyuesh

  $items['embed-form-configuration'] = array(
    'page callback' => array('get_embed_form_configuration'),
    'access arguments' => array('Embed Form Configuration Permission'),
    'access callback' => TRUE
  );

It was silly in hindsight, as my page callback was a drupal get form, and in the callback function I was returning a drupal get form as well. THat is why multiple realms.


How to avoid url conflict when defining menu items, and make sure path without wildcards will be used in favor of path with %? In hook_menu, I have

$path = "events"

$items[$path] = array(
  'title' => t('Events'),
  'page callback' => 'my_events_page',
  'access arguments' => array('view my events'),
  'type' => MENU_NORMAL_ITEM,
  'file' => 'my_events.pages.inc',
);

$items[$path . '/past'] = array(
  'title' => t('Past events'),
  'page callback' => 'my_events_past_page',
  'access arguments' => array('view my events'),
  'type' => MENU_NORMAL_ITEM,
  'file' => 'my_events.pages.inc',
);

$items[$path . '/%'] = array(
  'title' => t('Events'),
  'page callback' => 'my_events_page',
  'page arguments' => array($depth),
  'access arguments' => array('view my events'),
  'type' => MENU_CALLBACK,
  'file' => 'my_events.pages.inc',
);

They were working, but not now.

If I change $items['events/past'] to $items['events/past1'], it works.

Does it mean I have path conflict? If so, how can I resolve it?

Rows in my {menu_router} table are as follows:

path: events
page_callback: views_page (but I set it to xxx_events_page in hook_menu)
fit: 1
include_file: empty (should not be empty)
--
path: events/%
page_callback: xxx_events_page (good)
fit: 2
include_file: a file path is there
--
path: events/past
page_callback: views_page (but I set it to xxx_events_past_page in hook_menu)
fit: 3
include_file: empty (should not be empty)

If I update the page_callback and include_file it works. If I clear the cache, everything set back to default.

Assuming you are using Drupal 7:

Order matters only a bit - menu_router_build() saves all path into the {menu_router} table just the way they are set. But there are no guarantees database will return elements in that order. Logic to decide which menu item should be executed is in menu_get_item().

Actual query is:

$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

As you can see, fitting elements are ordered by fit column, most specific first.

As you can see in actual _menu_router_build(), $fit gets initially set to 0 for each menu item:

foreach ($callbacks as $path => $item) {
  $load_functions = array();
  $to_arg_functions = array();
  $fit = 0;

It means it shouldn't be possible for the order of menu elements in hook_menu() to affect order of routing. Actual code is a bit complicated to understand, but elements specific should have higher fit than elements with '%' in them. As the comment in code says: // If there is no %, it fits maximally.


log / capture all the queries executed in drupal I want to log / capture all the queries executed by the drupal?
update, select, insert any query,
is there any hook or what will be the method to do this.

You want Devel.

It has a lot of helpful tools for Drupal developers, including a helper function to print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took.


Behaviors not work for anonymous users I have a script with a behavior which receive settings by a block. The problem is that when I'm logged as admin the behavior is executed but when I'm an anonymous user, the behaviors isn't executed.

Can you help me ?

I Define this block :

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

        // Check if the conf
        if (empty($config['token']) || empty($config['pagename']) || empty($config['pageurl']) || empty($config['limit']))
            return array('err' => array('#markup' => t('You must configure the block.')));

        $build = [];
        // Create the wrapper to include facebook posts
        $build['facebook']['timeline']['#markup'] = '

';
        // Push conf vars
        foreach ($config as $key => $value) {
            $build['#attached']['drupalSettings']['myc_fb'][$key] = $value;
        }
        // Includes libraries
        $build['#attached']['library'][] = 'myc_facebook/myc_facebook';

        return $build;
    }

And here is my js :

jQuery(document).ready(function($) {
    console.log("hello 1");
    console.log(Drupal);
    Drupal.behaviors.myc_facebook = {
        attach: function (context, settings) {
            console.log("hello 2");
    };
});

And it's how I define my library :

myc_facebook:
  version: 1.x
  js:
    js/script.js: {}
    js/timeago.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/drupalSettings

You probably need to pass a reference of jQuery and Drupal in your js file like this:

(function ($, Drupal, drupalSettings) {

  ...

})(jQuery, Drupal, drupalSettings);

Btw. your js has {{{ but only }}. And you don't need document ready when you use drupal behaviors.


View based on months or days - display certain items during specified times of the year I am trying to create a calendar-type view that will display links to specific nodes during certain months of the year. For example, this would show 'Taxes' in Feb and April, 'Travel' from May to September, etc.
So far I have added a boolean field to my node to appear in the view, but I am stuck on how to implement the date selector. Theoretically I would like to have people select the months that this node should appear in the view, and the view will contextually display the nodes depending on the current month.
The problems I'm running into are:

The date field seems to require a year, but I want this to be year agnostic
The date field doesn't allow selection of multiple months

I am thinking that I will have to use a date field so that I can use contextual filters to display based on month of the year. I don't have access to the codebase so I need to do all of this within the UI using modules, if possible.
Any tips on how I can achieve this?

Here's an idea for something you could do in the Drupal admin UI (using only modules that are part of Drupal 8 core) since it seems you don't have access to the codebase.
As you noted, the date field requires a year.  So you can't use it if you want your months to be year-agnostic.
I assume that your requirement is "each node should be assigned to one or more months" and we don't have to worry about days (for example, a node could be "January and February", but it could not be "Jan 12 - Feb 10").
In that case, you can add a field of type List (Text) to the node content type that you want to sort in Views.  For the value of the field, enter the 12 months and allow multiple values so that multiple months can be selected.
Then, you can configure the view to filter based on your month field.  To set the current month, I'm pretty sure you can use Twig date in a Views filter to input the current month (not tested, from memory).


Add custom operator for condition() in search_api I am trying to implement hook_search_api_multi_query_alter but it seems 'IN' operator does not work here. I have to check condition on array. Any pointers for start building custom operator.

function my_module_search_api_multi_query_alter(SearchApiMultiQueryInterface $query) {
$indexes = $query->getIndexes();
dpm($query->getFields());
if (isset($indexes['solr_content_index_dev'])) {
  $query->condition('solr_content_index_dev:nid', array(2918, 2367), 'IN');

}
}

Maybe this trick will help you. You can go upstream and implement hook_query_alter instead

function yourmodule_query_alter(&$query) {
if ($query->hasTag('search_api_db_search')) {
        $is_search = FALSE;
        $tables=$query->getTables();
        //dpm($tables);
        //only run for the query that really matters to you. Try to find something unique in this
          foreach ($tables as $table) {
            if ($table['table'] == 'search_api_db_your_important_table'  ) {
              $is_search = TRUE;
            }
          }

          if ($is_search) {
            //use query functions normally eg.
            $query->innerJoin('search_api_db_your_table', 'custom_table', "custom_table.item_id = t.item_id");
          }
  }
}


How know inside hook_entity_presave() if it's a create or update? How know inside hook_entity_presave() if the entity is create or update please ?
Thanks.

Note: I want use presave and not update and insert hook.

Like this:

if ($node->isNew()) {

}

Note that this only works before saving, in insert/update, it will always return TRUE, because the node has already been saved and is no longer new.


How to use webform submission data in a Rules Condition? I want to send an email when a user fills in a webform, but only if it is our review form and if the user gave the feedback higher than a 7.

So we are asking how good we are, and the user gives us a value from 1 - 10, we want to send an email if that number is higher than 7.

Basically, I have installed the Rules and the Webform_rules modules.
Now I can make a rule with an action: 'After a form has been submitted'

Next I made the nid equal to the nid of the specific webform.
And then I want make a second condition to compare the filled out value the be 7, 8, 9, or 10, so I make an data comparison condition.
With the condition 'data' and the field name like: 'data:grade-value-raw' it just tells me there is no grade-value-raw

If I set the reaction to display the [data:grade-value-raw] on the page, it works.

Why can't I use it in the Rules Condition?

The "clue" to what you're trying to get to work, is that you have access to all labels and all values of any field of a webform, ie:

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

So in your case, you should be able to get it to work using something like [data:grade-value].

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform)
the 2nd attempt explains what to do in case of Webform.

The above is a good start, but not sufficient to achieve your goal (= validate "... a second condition to compare the filled out value the be 7, 8, 9, or 10, so I make an data comparison condition", as in your question).
However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action (yes, "Rules Action", not "Rules Condition" ...) to Add a variable, with a value assigned to it equal to your [data:grade-value-raw] (and with a data type which is probably integer).
Use the Conditional Rules module to perform the data comparison as in your question (if it is 7, 8, 9, or 10). However, in this data comparison you now refer to the value of the variable you just added (that's the clue!).

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

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


D8: How to perform ajax call in javascript I'm trying to perform an ajax call from a javascfript file by executing this:

            $.ajax({
                url: '/lunapark/ajax/space-invaders/' + score,
                success: function (jsonData) {
                    window.location.replace(jsonData.redirect);
                }
            });

But I keep getting:

  GET /lunapark/ajax/space-invaders/90 404 (Not Found)

If I go to the url in my google chrome, it loads and gives me a JSON object, so the page does exist:

{"redirect":"\/lunapark\/overview","game":"space-invaders","score":"90"}

Now I'm trying this:

new Drupal.ajax();

But I can't seem to figure it out...

Instead of specifying an incorrect datatype in the client call, you fix your route and specify that you return json. Use the _format route key as explained in the route documentation


Recognize js files in the library folder If i put my .js files in sites->all->libraries folder. Will drupal recognize it ? Because i did not see the file in the source. Can i make it recognize ?

Just putting the files in a directory won't do any good.

You have to either put a reference to your file in your module.info file, or use drupal_add_js somewhere, depending on what you're trying to achieve.


"Invalid argument main.js" Gmap error in IE I have GMap Module and GMap Location version  6.x-1.1; in Internet Explorer (any version), on the GMap page I see this error:

  Message: Invalid argument.
  Line: 401  //in IE8, and 942 in IE6
  Code: 0
  URI: http://maps.gstatic.com/intl/fa_ALL/mapfiles/310c/maps2.api/main.js

I found a question on Stack Overflow, but the answer doesn't apply in my case, as the lat attribute is true.

What is problem?

i solved this problem.
in Gmap Module setting and Google Map Initialize check default center and enter valid  coordinates.
in my case default center was setted to 0,NAN. problem was with NAN.
at now it works in IE.


How to move the edit tab in user-profile.tpl.php I would want to reorganize the profile of the users, in the following way:

Name (h1),
Custom field 1,
Custom field 2,
Edit tab ($tab),
Block.

I tried to delete the $tab variable in page--user.tpl.php, and add it in user--profile.tpl.php, but it does not work.

How to move the edit tab in user-profile.tpl.php ?

Ok, i find the answer :

function THEME_preprocess_user_profile(&$variables) {
  $variables['tabs'] = menu_local_tabs();
}


Display a (view) block for everyone except one role I have a block which has been generated by a view, and would like to show this block to all users except people who have been granted a particular role, is this possible, and if so how, exactly?

Many thanks in advance.

-Sniper

In the Blocks Admin page, you can use PHP to display/not display the block, so you could put something like this in there:

<?php

global $user;

if (in_array('ROLETHATSHOULDNOTSEETHISBLOCK',array_values($user->roles))) {
  return FALSE;
} else {
  return TRUE;
}

?>

OR just check all the roles BUT the ROLETHATSHOULDNOTSEETHISBLOCK in the other part of the form :)

ADDITION:

With respect to PHP and security, I presume JoeS is referring to these paragraphs within The Definitive Guide to Drupal 7...

Avoid Using the PHP Filter Module

Although it’s handy to be able to write PHP code directly into your Drupal web interface without having to create a module, it’s also very dangerous! All PHP code should live in the form of modules or themes. Writing PHP in Drupal’s web interface is a bad idea for the following reasons:

• It’s unfriendly to edit and debug (no syntax highlighting and no proper error reporting).

• It makes code reviews difficult and versioning impossible.

• A trusted user might inadvertently damage your site with malformed PHP code.
• If your site was to be compromised, a hacker could penetrate and damage your server using well-crafted PHP code. Keeping the PHP Filter module turned off (or even better, removing it entirely from the filesystem) could help contain such intrusion to the Drupal level only.

• In terms of performance, storing PHP code in the database will prevent any opcode caching mechanism from working on this piece of code

Note that some contributed modules might offer a functionality similar to that of the PHP Filter module; they will suffer from the same flaws noted previously.

                                   **and**

■ Tip If the PHP Filter module is enabled, try to disable it. PHP Filter module should not be used to provide functionality on node (content) pages. Avoiding that is a good idea from both code quality and deployment perspectives. For placing functionality, rather than content, on a page or part of a page, use Drupal’s hook_menu(), hook_block(), or hook_page_build().

...which refer to the PHP Filter Module, not the admin interface.  This module allows users to enter PHP code into a node directly and I wholeheartedly agree that this opens far too many doors.

However, in this case, I am talking about using an option given to the administrator of a site by the drupal admin interface, one that hopefully is used by someone with far more PHP experience than casual users of the system.

Furthermore, using this option is most probably a one shot deal and would be properly tested, unlike the Filter option, which would allow a user to change the code at will, opening further doors to mayhem.

In any case, this discussion does highlight the fact that running a drupal site has many facets, security being a large part, and knowledge is key, but all I can hope is that there isn't a security hole that has gone unnoticed for several releases in the admin interface that would allow any code injection into the 6 lines of code suggested here.


Order total discount in ubercart? I want to total order discount in ubercart on drupal 7. I want to 10% discount on total order.Is there any way to do that?

Commerce Discount Extra

  Provides a number of common discount condition and offer types:

  Order discounts

  Condition types

  Order-owner role
  Total items in order

  Offer types

  Fixed amount per-quantity discount (Buy X product get Y (or X)    product at discount up to some number of (or unlimited) times)
  Percent per-quantity discount

Ubercart Discount Coupons

  A checkout pane, a cart pane and a block are available for customers
  to enter coupon codes, each of which can be enabled or disabled
  separately. Discounts can be shown as an item in the cart or applied
  on the checkout page.


Actual output in view is different than preview I have set up a view to display all nodes for 1 taxonomy term. Something got messed up and now the final view drops one node (which is also a different content type).

I cannot find rhyme or reason why the content type with images is being left out.

I have deleted the old view and copied a working one that has been set up for a different model again, changed taxonomy term, path and link and BANG the gallery node missing again.

The preview of the view shows it as it should be.

The page affected is this one:
http://www.riverlakesea.com/smartwave/skippa

A pointer where I must check would be much appropriated since I have been through node/content type/view gazillion times and cannot spot the problem.

Many thanks,
Susanne

Change your filter to include content of that particular content type. Does it pull just that gallery?

Also, screen shot of your view admin panel would be helpful.


Custom "account" pages I am creating custom account management pages in drupal with quite a few criteria. The first being that there is a page at /account which contains two separate forms: 1) To enter a new email address and a confirm new email address 2) To enter a new password and confirm new password

I'd like other pages for example /account/orders to view past orders and /account/billing to edit credit card data and billing address (I'm using ubercart and authorize.net for e-commerce and credit card processing, respectively) How can I access the billing data (address and last 4 digits of credit card number) from ubercart?

What are some general tips for this? Should I create a custom "account" module? Should I just try to edit some existing templates somehow? I know I'm asking a lot of big questions, and I'm not asking for a complete answer. Just some general advice and ideas.

Also, I hate the user account pages with numbers in them identifying the user. It seems simple enough just to have it know depending on who is logged in (i.e. /user/5/edit vs. /user or /user/edit

You will have to work on custom module implementation.

Custom solution would not effect content on account page.

hook_menu will define the menu items like account/orders and account/billing

If you are using Ubercart then you will have to carefully investigate if your required information are being stored and in which table. I am not sure if Ubercart stores Credit Cards data. I think Ubercart uses DPM (Direct payment method) to process cards which totally happens on Authorize.net pages.

Pathauto normally defines url alias also for user profile pages. But I think there is no way to skip user id from url while editing a user.


Can't install experimental modules A follow up to this thread: Can't install experimental modules

I've installed Drupal 8.2.5 two times on my server. First with the "minimal installation" option, and after that with the "normal installation" option. In both cases the installation worked without any errors. But in both cases I can't install experimental modules. I set the check mark next to an experimental module, then click install, the site refreshes and nothing changes. I can install other modules just fine. Since I must upgrade an existing Drupal 7 installation, I need the experimental Migrate modules.

No error messages are given, neither in "reports" nor on server level. Does someone know why this pre-alpha-like error occurs and how to avoid it?

Use drush to install it.

In case that don't work, try installing only BigPipe module to see if it is really a Core(experimental) modules problem or it's just some modules that are problematic and still need more development for drupal8 application.
As it is written here the only stable experimental module is BigPipe.


Custom views twig template I am trying to create a new twig template that defines different types of views templates - or some sort of option based format.

Example 1:

Generic view blocks: block--views-block.html.twig

Example 2:

News Block specific views with no container: block--views-block--news-elements-block-1.html.twig

Example 3:

List Block specific views with no container: block--views-block--list-elements-block-1.html.twig

What i want to achieve: - if i can present an option on the block, that would also work.

Views block with no container: block--views--no-container--block.html.twig

So far:

function THEME_theme_suggestions_alter(array &$suggestions, array $variables) {

  // dpm($variables);

  // $content = $variables['elements']['content'];
  // if (isset($content['#block_content']) && $content['#block_content'] instanceof \Drupal\block_content\BlockContentInterface) {
  //   $suggestions[] = 'block__' . $content['#block_content']->bundle();
  // }
}

For my circumstance i have adopted to use the block_alter hook to define the new suggestion for the template. Since homepage only contains the unique views template and the others wouldn't.

function THEME_theme_suggestions_block_alter(&$suggestions, $variables) {
  $path_check = \Drupal::service('path.matcher');

  if (in_array("block__views", $suggestions) && $path_check->isFrontPage() == FALSE ) {
    $suggestions[] = 'block__views__blah__custom';
  }

}


How to debug an empty cache_page table I have a bunch of sites built off the same profile, and recently noticed the pages aren't being cached. I spent some time doing the usual: looking for drupal_set_message calls, disabling all the modules that might disable page cache, as defined here. I've also dug into drupal_page_get_cache. This lead me to the database, where it turns out the cache_page table is empty.

This is clearly the source of the issue, I'm just not sure how/what is preventing the page cache. What I'd like to do is to figure out where page cache is writing to the database, and do a debug_backtrace, or just dpm from that point backward.

A) Is there a point in drupal core where cache_page is written to?
B) Any other ideas for debuggings this? (please don't say disable all modules, then re-enable, we have upwards of 200 modules in place with a dozen custom module with interdependencies)

After posting this I opened my IDE and realized I had found the DrupalDatabaseCache->set method, and that the cache_page $cid is never called into that function.

Whether or not a page is cacheable is determined by drupal_page_is_cacheable().

Set a breakpoint there and dig into call stack / step through the conditions to determine the reason why nothing is saved to the cache_page bin.

Also take a look at drupal_page_footer() which calls into drupal_page_set_cache() in order to store the built page in the page cache.


How update programmatically node entity with empty field_image? i need to make an import from one mysql table in my base.

I create node with :

$value= array(
                'type' => strtolower($typeProduit),
                'field_1'=>"test",
                'title'=>"test",
                'body' => array(
                    'value' => "test",
                    'format' => 'full_html',
                ),
                'field_2'=>"",
                'field_3'=>"",
                'field_4'=>"",
            );

 $nodeEntity=\Drupal::entityTypeManager()
        ->getStorage('node')
        ->create($value);

    $nodeEntity->save();

All node are create and if i have an image, i add it to my $value before save() :

$value['field_image_video']=array(
                    'target_id' => $fileImageVideo->id(),
                    'alt' => $catalogue->titreVideo,
                    'title' => $catalogue->titreVideo,
                );

if i have no image, i do nothing for this field.

I need to update some node programmatically after this first step.

And when i just try to change the title like this :

     $nodeEntityUpdate = \Drupal::entityTypeManager()
                    ->getStorage('node')
                    ->load(273);

     $nodeEntityUpdate->title="blabla";
     $nodeEntityUpdate->save();

if node don"t have image field set, i got this error :

  PHP Fatal error:  Call to a member function getFileUri()

If node has image, update work.

How can i set my image_field to null ?

i try to set my image field like that on creation :

$value['field_image_video']=array();

But that didn't work.

this image field is set to unlimited values

i got it in the update :

i set my image_field in the update:

  $nodeEntityUpdate = \Drupal::entityTypeManager()
                    ->getStorage('node')
                    ->load(273);

     $nodeEntityUpdate->title="blabla";
     $nodeEntityUpdate->field_image_video =array();
     $nodeEntityUpdate->save();

I try to set this field in the create, but that change nothing.

As i can see, we need to set image field in the update if she is empty at the creation.


Set "Use the administration theme when editing or creating content" to true in install profile I am creating an installation profile, and I can succesfully download and enable my custom theme as default. The issue I am running into is the "Use the administration theme when editing or creating content" setting is disabled on a fresh install, and I always want that enabled.

How do I enable the "Use the administration theme when editing or creating content" setting in my install profile?
What is the easiest way to find out how to configure settings like this in the future? The install profile documentation does not give any info on this, and I can't find anything in the API.

Update: I've found this API article api document to be helpful in figuring out which fields to target.

Setting it is as simple as:

variable_set('node_admin_theme', 1);

Most (not all, but most) config settings used in Drupal are managed using a system_settings_form(), which basically takes the array keys of the elements used in that form, and saves them as variables.

So an abridged version of the theme settings form would be

function some_form($form, &$form_state) {
  $form['node_admin_theme'] = array(
    '#title' => t('Use the administration theme when editing or creating content'),
    '#type' => 'checkbox',
    '#default_value' => variable_get('node_admin_theme', 0),
  );

  return system_settings_form($form);
}

When Drupal processes that form, a variable called node_admin_theme is created/updated with the appropriate value.

If you're certain a form is using system_settings_form(), finding the names of the associated variables is as easy as inspecting the elements themselves and looking at the 'name' parameter, e.g.

If you're not sure, lookup the function that defines the form and check. If it does use system_settings_form() then great, and if not you get an insight into how that form actually manages its data.


Website owners to claim their websites by uploading control file ? For my website directory I would like users to be able to claim their own websites.

This is needed to allow only validated and authorized users to edit website-related content.

I would like the system to ask users automatically to upload a control file with a filename generated in Drupal 7.

Drupal will check automatically if the filename can be downloaded from the claimed website and if so it will assign authorization to the claimant to edit related content.

How to do this in D7, preferably with existing modules ?

It shouldn't be too difficult to code it:

If you have the website URL and the control file name stored in a node you can use drupal_http_request to perform a GET against the URL and filename.

If you get a status 200 returned the file exists and you can update another field on the node to indicate that the URL has been successfully validated.


How to export a Field's Allowed Value List in a feature? I've made a drop-down list type Field and have exported it as part of a Feature. However, whilst every other facet of the Field (Name, Help text, etc)  is successfully exported the actual Allowed Values is not.

Does anyone know how I would include this in my Feature?

Turns out this is a bug(?) in Drupal 7.

The Dropdown list field's values are not saved in Features on a per-instance basis.

This can be fixed by using hook_field_widget_form_alter in the Feature's .module file, eg:

/**
 * Implements hook_field_widget_form_alter().
 */
function my_colors_field_widget_form_alter(&$element, &$form_state, $context) {

  if ($form_state['build_info']['form_id'] == 'my_colors_node_form' &&
    $context['field']['field_name'] == 'field_dropdown_text_single' &&
    $element['#entity_type'] == 'node') {
    $form_field_wrapper = entity_metadata_wrapper('node', $element['#entity']);
    $default_field = $form_field_wrapper->field_dropdown_text_single->value();
    $element['#default_value'] = !empty($default_field) ? $default_field : '';
    $element['#options'] = [
    'Red' => 'Red',
    'Blue' => 'Blue',
    'Green' => 'Green',
    ];
  }

}

...drupal is so great...


Difference between drupal_static and \Drupal::state? Imagine I have a hard-to-compute value.

$my_heavy_value = compute_heavy_value();

What's the difference, at performance level, between storing the computed value using drupal_static() and using \Drupal::state()?

Which one is stored in the database? Is there one that is stored in memory?

They perform different tasks.

drupal_static() only stores data for the current page load (or ajax load). For example, if you are loading something from a database table multiple times on a single page load (ie - a user account), the first time it is loaded it is saved to memory, and the next time it is needed, it is pulled from memory, rather than reloading it from the database, saving that second database query.

Drupal::state() saves data to the database, where it can be recovered in future requests. It's a cache of sorts.

You can actually use them in conjunction with each other as follows:

function get_some_value()
{
  // Instatiate the static
  $value = &drupal_static(__FUNCTION__);
  // Check if the value has already been set in this page load
  if(is_null($value))
  {
    // The value has not yet been set for this page load,
    // so retrieve it from the state if it exists, and if it
    // does, then save that to the static
    $value = \Drupal::state()->get('my_value');
    // Check if the value was retrieved from the state
    if(!$value)
    {
      // The value was not retrieved from the state, so
      // it needs to be generated. Below is an example
      // fetching it from the database
      $value = db_query('SELECT some_value FROM {some_table} WHERE some_column = :some_value', [':some_value' => 'some value'])->fetchField();

      // Save it to the state for future page loads
      \Drupal::state->set('my_value', $value);
    }
  }

  // Return the value
  return $value;
}

With the above code, the first time this function is hit, it will first check if the value exists in the static cache (this page load), and when it doesn't, it attempts to retrieve it from the state cache, and when it doesn't it finally generates it with a database query, saving it both to the static cache, as well as the state.

If it hits this function again on the same page load, the value will be in the static cache, so none of the internal code is needed, and the value is returned from the static cache.

On a future page load, the first time this function is hit, nothing is retrieved from the static cache, so it will pull it from the state cache. If the function is hit again on that page load, the value will be in the static cache and returned from that.


Tokens in Views don't seem to work I added a new view (block) with FIELDS type. I added "Content: Comment count" to see the comments number, and in "Rewrite results" I clicked to "Output this field as a link", and added the token "[comment_count] == Content: Comment count" as link.
This link doesn't work.

When I add a different token, such as "[body] == Content: Body" or "[title] == Content: Title," the links still don't work.

Am I doing anything wrong?

I wanted to do the same thing.  I had a view of blog posts and at the bottom of the post I wanted to put a link that had a comment count that was a hyperlink (as I've seen this done on many other blogs).  The way I did it was like this:

Originally my view was set up to just display the full nodes.  I clicked to edit the view and went to Page Details->FORMAT->Show and changed the setting from "Content" to "Fields".

Added the following fields:

Content: Title
Content: Body
Content: Path
Content: Comment count

The key and answer to this post is: Even though I don't want to display the path on my view I need to add it as a field so that I can later use it when building the link for the comment count.  Also I believe the order of the paths is important, so the path field must come before the comment count field.  For the Content: Path field I checked the "Exclude from display" check box.  This hides the path from showing up in the view. Next under "REWRITE RESULTS", I checked "Use absolute link (begins with "http://")".  This is necessary for a proper URL when using the path as token below.

For the Content: Comment count field, under "REWRITE RESULTS" I checked "Output this field as a link" and in the "Link path" box I put [path].


Are there any advantages or issues with using a Google Analytics CDN app with the GA module? I'm considering using Cloudflare with my Drupal 7 site.

I see that Cloudflare offers a Google Analytics app:
https://www.cloudflare.com/apps/google_analytics

I already have the Google Analytics module installed and configured on my site.

Are there any advantages to using both a CDN Google Analytics app and the drupal module at the same time?

CloudFlare acts as a reverse proxy and a CDN. So it can change the HTML output of your Drupal site. If your site has no Analytics script, it can add the code for you. That's for the convenience only. You are still using same Google Analytics.

For Performance

I would avoid GA module if there is a custom module that already has a hook_page_build or hook_page_alter hook. I'm more of a developer so I feel like the GA is an unnecessary load when I could include it in a custom module.

For Easy integration with precise tracking

With GA module, you can expose custom variables to GA, have per-path, per-role, and other contextual tracking, and also cache the snippet (This is actually a bad step IMHO because ga.js snippet is usually cached in the browser from your site or from some other site that uses GA).

If you don't have access to edit the modules, or would prefer to use the contrib, GA module would be better.

For the easiest integration with blind tracking

Use CloudFlare. They are a really good service (I took part in a CloudFlare guide ebook too), and responded quickly to the recent core SQL injection vulnerability. If you don't care about precising tracking, I would use CloudFlare.


profile2_load_by_user Trying to get property of non-object I use simple code to hide field from profile2 main profile based on another field inside the profile2 main profile. If field_testcheckbox is not checked, hide field_info.

function odbornik_fields_form_profile2_edit_main_form_alter(&$form, &$form_state){
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
$checkbox = $profile->field_testcheckbox['und'][0]['value'];
  if ($checkbox == 0) {
     $form['profile_main']['field_info'][LANGUAGE_NONE][0]['#type'] = 'hidden';
    };
}

This code works ok for all users browsing their profiles, except admin user browsing own or others profiles, where I get error: Notice: Trying to get property of non-object on line with this code.

$checkbox = $profile->field_testcheckbox['und'][0]['value'];

Admin has the main profile as well and the checkbox field is there too. What can be the problem? Thank you.

You are assuming there is a profile for all users and your admin user seems to not have one. Add a check if there is a profile for the current logged in user:

function odbornik_fields_form_profile2_edit_main_form_alter(&$form, &$form_state){
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
if($profile) {
  $checkbox = $profile->field_testcheckbox['und'][0]['value'];
    if ($checkbox == 0) {
       $form['profile_main']['field_info'][LANGUAGE_NONE][0]['#type'] = 'hidden';
     }
  }
}


How to add strip tags in drupal 8? How to add strip tag in field template i am using ckeditor in my content type because of using it its automatically inserting p tags in Text.

Here is mine field template code

         {% for item in items %}

{{ item.content }}

{% endfor %}

I was trying something like this for adding strip tags

{% for item in items %}
{% set conBody %}
 {{ item.content }}
 {% endset %}

{{ conBody|striptags }}

{{ conBody  }}

{% endfor %}

Only indexed value(conBody[0]) field tags are stripped(p tags removed) but remaining indexed value fields are remaining same not affected.

How could i use above code in loop.

I ran across this today and figured I would circle back and provide an answer that worked for me.

{% for item in items %}
    {% set conBody %}
        {{ item.content }}
    {% endset %}

{{ conBody|striptags }}

{% endfor %}


Override theme function inside module, template_preprocess_field I'd like to implement template_preprocess_field in a module for organizational purposes.

How can I do this?

Thanks!

Reference:
https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_field/8.2.x

Hook functions are named like so: MODULENAME_hook.

In your case that's:

function MODULENAME_preprocess_field(&$variables) {

}


Is there a module for using Google Analytics to display popular content? I'm actually looking to make a simplier version of the Radioactivity module.

I wonder if there are any modules out there that are using Google statistics to display content.

Google Analytics Statistics has integration with views...

Project page says

  This module provides views integration for the Google Analytics Data
  Export API.

  This allows you to use Google Analytics directly through views to do
  things like Most Popular, Most Read ect. You can combine the
  statistics to create interesting results.


How do I change the limit of user accounts gets blocked or suspended? After entering the wrong password for 5 time, a user account gets locked/suspended.
How do I change this? Instead of 5, I need the accounts are blocked after 10 tentatives.
I already seen the Flood Unblock module, but it unblocks the already blocked users who entered the wrong password more than 5 times.

This is a configuration setting. You can run the drush command:
drush cset user.flood user_limit 10


PDOException: SQLSTATE[42S22] When adding quiz content I am trying to implement the quiz module on a new website and it's throwing the following error when attempting to add content > quiz. I believe the code I have was part of a feature I was trying to migrate over from a different website so I could retain the functionality involved with it, but it's proven to be less than compatible. (Going from Drupal Commons 7.50 to Plain Drupal with a demo theme built in 7.54).

Can someone interpret this error and point me in the right direction as to what the missing piece of the puzzle is here?

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.allow_change_blank' in 'field list': SELECT base.qnp_id
  AS qnp_id,  base.vid
      AS vid, base.nid AS nid, base.uid AS uid, base.number_of_random_questions AS
      number_of_random_questions, base.max_score_for_random AS max_score_for_random,
      base.pass_rate AS pass_rate, base.summary_pass AS summary_pass,
      base.summary_pass_format AS summary_pass_format, base.summary_default AS
      summary_default, base.summary_default_format AS summary_default_format,
      base.randomization AS randomization, base.backwards_navigation AS
      backwards_navigation, base.keep_results AS keep_results, base.repeat_until_correct
      AS repeat_until_correct, base.quiz_open AS quiz_open, base.quiz_close AS
      quiz_close, base.takes AS takes, base.show_attempt_stats AS show_attempt_stats,
      base.time_limit AS time_limit, base.quiz_always AS quiz_always, base.time_left AS
      time_left, base.max_score AS max_score, base.allow_skipping AS allow_skipping,
      base.allow_resume AS allow_resume, base.allow_jumping AS allow_jumping,
      base.allow_change AS allow_change, base.allow_change_blank AS allow_change_blank,
      base.build_on_last AS build_on_last, base.show_passed AS show_passed,
      base.mark_doubtful AS mark_doubtful, base.review_options AS review_options,
      base.result_type AS result_type FROM {quiz_node_properties} base WHERE (base.vid
      IN (:db_condition_placeholder_0)) ; Array ( [:db_condition_placeholder_0] => 351 )
      in EntityAPIController->query() (line 187 of
      /Applications/AMPPS/www/example/docroot/profiles/cms/modules/contrib/entity/inc
      ludes/entity.controller.inc).

Here is how the process went:

I implemented an online training feature from our current website for the new one
It included syllabus and quiz content types, neither of which worked until I installed the Title module
Once Title was installed, I received a new error only when trying to create content type quiz:

  EntityFieldQueryException: Unknown field: title_field in
  EntityFieldQuery->fieldOrderBy() (line 954 of
  /var/www/html/example/docroot/includes/entity.inc).

I updated the quiz from 7.x-5.0-alpha4+77-dev to 7.x-5.1 and all seemed well
I removed a quiz field field_syllabus_ref and recreated it a different way, to reference the title of the syllabus page in the quiz.
Now I get the error below unless the module is uninstalled. When it is uninstalled, I am still able to add quiz content but I get a different error instead after saving it.

The error was somehow related to the UUID module, which couldn't be disabled without derailing the entire website. Here's how I fixed it.

uninstalled the feature that held the affected quiz module

drush pm-disable <my_feature>
drush pm-uninstall <my_feature>
uninstalled the quiz module and all the modules dependent on it:

drush pm-disable quiz
drush pm-uninstall quiz
moved the quiz module files to my temp backup outside the drupal root:

mv sites/all/modules/contrib/quiz ../<temp_backups>/quiz

downloaded the quiz module fresh and reenabled it and all the dependent modules and reenabled the feature that contained it:

drush dl quiz

drush en quiz

That took care of this particular error.

Please note: I did not yet have any quiz data or content set up; this guideline is only safe for a dev environment. I have not tested it with any actual content or user data.


Adding notes to a custom form I have created a custom form and have put in some notes but I am wondering whether it's the correct 'Drupal' way. I have added the notes using the following format:

  $form['notes'] = array(
    '#markup' => 'A few notes.

Item i

Item ii

Item iii

'
   )

You could use the preinstalled theme item_list:

  $form['notes'] = [
    '#theme' => 'item_list',
    '#title' => $this->t('A few notes.'),
    '#list_type' => 'ul',
    '#items' => ['Item i', 'Item ii', 'Item iii'],
  ];

See https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21item-list.html.twig/8.5.x


How do I associate a field value with another value of a multi-value field? I've run into a situation with a project in regards to field organization. I've got 3 data types, a price, a date range and a quantity. I've currently got 4 prices and a date grouped with it using field groups. Quantities are a multivalue check list with values between 1-12. I have since learned that there is to be a different price for every quantity, so I would end up with up to four price and dates for each value of quantity I have.

So what I would like to know is the best way to go about this. Is there a way to set fields so that I when I can set an association between a group of dates & prices with a value of quantity or do I need to go for some kind of table-based approach?

Currently it is set up like this:

Node {
    price1
    date1
    price2
    date2
    price3
    date3
    price4
    date4
    quantity: 4, 7, 9, etc.
}

and I need to re-organize it like this:

Quantity: 4 { price1, date1, price2, date2…}
Quantity: 7 { price1, date1, price2, date2, price3, date3…}

I've found what may be a possible solution using the Field Collection module.


Custom arrangement for fields with multiple values in Drupal 7 In Drupal 6 I used to make every sort of customised markup for CCK fields with multiple values. Usually this happened when I wanted to lay out thumnails for a gallery inside a table: I used to go into the relevant tpl.php file, grab the relevant $field_fieldname variable, loop through it, and print out the 'view' key for it, which contained the styled thumbnail, often linked to the original image and whatever.

Now, I'm a bit confused on how this should be done in Drupal 7. For now, I set up a suboptimal solution that goes like

    <?php foreach($content['field_gallery'] as $k => $v) : ?>
        <?php if(is_numeric($k)) : ?>
            <?php echo render($v) ?>
            <?php if((($k+1) % 4) == 0) : ?>

            <?php endif ?>
        <?php endif ?>
    <?php endforeach ?>

but it's obviously wrong. I can't seem to get my head around this, even after having read lots of docs about the Field API and theming for D7. Ideas?

You've got an explanation on how field_view_field and rendering api for fields work in this blog.

Here you've got an example (extracted from the link above):

$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

You just need to loop over the $delta value for the fields to render them in a multiple valued field.


What css framework is better between 960gs and Blueprint? For a new project what is better for drupal between Blueprint and 960gs?
I usually prefer 960gs, but for you?

I haven't used 960gs, but used to use Blueprint.  Blueprint worked fine if I was always making 960px width templates.  But, now I veer away from those CSS sizers.  They're too constricted in what you can accomplish.  Also, I always prefer to size the CSS with a min-width:960px and max-width:1200px.  So many of the screen res. are 15" and 17" now.  You can't really accomplish much beyond the scope of 960px with Blueprint and, I'm assuming, 960gs.


Two forms in register page Drupal I'm using Profile2 and Profile2 registration path module and I created two profiles.

I want to display their registration form in user/register page. So two forms in one single page.

I set their path to user/register but these forms merged together. But what I want is two separate forms.

Like this:

Any suggestions?

You can do it simple, add 2 form concurrent to the page you want ( if they are block  put two block in that page) and then with simple Jquery you can handle it with something like below code

(function($){
// change jquery selector with real ones
$('.user-register1,.user-profile-register').hide(); // or you can hide them with css
var selector= $('your radio option selecotr').value();
if(selector==1) {
     $('.user-register1).show();
     $('.user-profile-register').hide();
}
elseif(selector==2){
     $('.user-register1).hide();
     $('.user-profile-register').show();

}

})(jQuery);

This code IS the way how can you achieve it and if you copy/paste it it will not worked till you changes its selector and values with your forms


When and where is calling menu_link_save safe and appropriate? From what hooks (or "types" of hooks) is it appropriate to call menu_link_save?

I have a situation where I would like to add a bunch of entries to {menu_links} where an entry already exists in {menu_router}.  To state this another way, I would like to add direct links to a menu for which another module has defined a wildcard entry via hook_menu.

A concrete example would be that I would like to add a menu item to a menu for "taxonomy/term/123".  In this case, there is already a router entry for "taxonomy/term/%" which the taxonomy module created.

I know how to use this function.  I am just not sure where I can (or should) call this from.  This isn't a situation where a user is saving a node, or something else that would be considered an event.  Essentially, I just want my module to create a bunch of links so the end user doesn't have to.

Would this be best done by a hook_enable?  Are there any popular modules that I can take a look at for examples / use cases?

Yes, hook_enable() sounds correct.

To find examples, on way is look at what's using the function on drupalcontrib.org.  That points to menu_enable(), which is even a core function.


How to join 2 views block with a views page Created a content type x. Fields: title, body, serviceareas.
Added 5 nodes.

View1

Created a views page:

Views path: house/%.
Contextual Filter: added nid.
Selected body field to display.

View2

Created a views block:

Added nid. Excluded from display.
Added Title field. Output field as a link > link path: house/[nid]

Results:
When I click a title from the block, I get views page accordingly.

Addition:

View3
I would like to add one more views block which will select serviceareas field for that node.
This block will only display in all the views page.

When I click the title link (step 5), I like to display the body field(it works now already). I also like to display serviceareas field (step 7) to views 1 and views 2.
I am not sure how to join the views 3 to views 1 and views 2? So that I can see serviceareas related to the views page I am on.

Example:

Node/1
Title: title1
Body:  body1
Serviceareas: serviceareas1.

Node/2
Title: title2
Body:  body2
Serviceareas: serviceareas2.

When I click the title 1(views 2), views page(views1) should display body1(works) and on the same page another region, views block(views 3) should display serviceareas1.

When I click the title 2(views 2), views page(views1) should display body2(works) and on the same page another region, views block(views 3) should display serviceareas2.

      ------------------------<<<

I placed views2 and views3 block in the same region. Views 2 should display all the nodes titles(works). Views3 should display only field from the nid(does not work).

Views3 block: I added one field. Contextual filter: I added nid.

When I click a title link from views2, I get body from views1 page but I do not get the field from views3 block. Below is the view3 block -contextual section.

If I understand your question correctly, you want to display the result of a View into another View. You can do this by using the contributed module Views Field View:

  views_field_view allows you to embed one view into another view and pass arguments along

By using this module you can add an extra field to your View1 and View2, which shows the result of your View3.

===

In your updated question, Views3 has become a separate block. Using a contextual filter you can limit the rows to be only from a specific node (id), the one that is being displayed. The answer on How to associate the current Node ID when running from Block layout? should point you in the right direction, your contextual filter should be similar to the one you used in View1.


How to change a CCK value from a custom module I would like to change a CCK value from an action triggered by the user. I built a custom form with a submit button that leads to a hook_validate(). I would like to update a field value from my function. I know the nid and the field_name, I can't find how to do it using CCK API.

Any ideas ?

With the nid stored in $nid and changing FIELD_NAME to your specific field name, once you have your new field info back from your form nicely stored in $new_info all you need to do is:

$node=node_load($nid);

$node->FIELD_NAME[0]['value']=$new_info;

node_save($node);

This is assuming a couple things, one that it's the first value in a field, the [0] up there, and that the field is one that has a ['value'] component.  Other types of fields have different things here, the most common that immediately comes to mind is ['nid'] if it's a reference field.


Not all strings are translated With Drupal 7, we have a custom module that displays a form that will work in both English and Spanish. Throughout the form we used t() to translate the text, and it works in all but two places. One is in the form when we declare a fieldset, and the other is the menu entry declaration (which isn't using t()). For the menu entry we have '[SiteName] Events' like this:

$items['sitename-events/register'] = array(
    'title' => 'SiteName Events',
    'page callback' => 'sitename_events_event_register',
    'access arguments' => array('view events'),
    'file' => 'public.events.inc',
    'type' => MENU_NORMAL_ITEM,
);

For the form, the element is declared like this:

// Personal Information
$form['personal'] = array(
    '#type' => 'fieldset',
    '#title' => t('Personal Information'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
);

Other pages are translating just fine, as well as other elements in the form, including the other field sets. What would cause these two entries to not translate, and is there a way that I can force them to translate since we're only going to support English and Spanish?

The literal strings that are passed to t() are not directly translated from the function; the function just searches the provided string in the databases used from the Locale module ("locales_source" and "locales_target"; see locale()). Before searching in that databases, t() checks the Drupal variable locale_custom_strings_<lang_code>, where <lang_code> is the language code for the language to which the strings are translated.

In the first case, the strings are imported from the translation files. In the second case, the Drupal variable can be set in the settings.php file.

As you want to have the translation for strings used by a custom module, the first method (creating a .po file, and then importing it) is probably too laborious, especially because it's a custom module for which localize.drupal.org cannot provide the translation files (the ones with extension .po). The only alternative is to use code similar to the following one in the settings.php file:

$conf['locale_custom_strings_es'][''] = array(
  'forum'      => 'foro',
  '@count min' => '@count minudos',
);

The strings I used are just an example (I hope I translated the strings in Spanish correctly
); the strings I used already have their translation in Spanish as part of the core translation.


How do I output one node as XML I am creating a page flip for a drupal site using pdf_to_imagefield module to export PDf to JPG and then I need to have the list of JPG files as XML to use them in Dynaimc page flip.

The PDF and all JPOG files for each PDF page are stored in the same node of a certaine content type. How do I output this node as XML where I can control XML tags??

I have tried to create node-content-type.tpl.php but it comes as HTML.

I would recommend that you use views as your source for the list of jpegs to output your XML file from. Using Views for example, I was able to make list of event images and make a custom XML file used to display the images in the Cub3r Flash plugin (I thought it was a bad idea but the client really wanted a Flash slideshow). I used the Views Bonus Pack export module, that gave me a style 'XML file'. I had only the image field, that was set to output the full image URL, the label I set it to was used as the custom tag. I then did an override of the XML template that came with the module and customized it to my needs (adding config parameters to cub3r).

Hopefully this will help you out. I also saw that the export module now has a fork that uses the batch API. Make sure you also checkout the Views data source module.


Is there a way to let users edit something only if they are a members of an OG? We have a number of different users who want to edit 'sections' of our website. This mostly aligns to Organic groups.

Is there a way to allow people to edit pages of a group which they are members of?

You could, for sure, use the Group module to let users edit something if they are a member of some group. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".

Resources

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


Dynamically creating menu links from a node's fields I have to first, create a menu-like block based on the information in a content type. Below every link, there is a text area field from a content type (Conference) except for upcoming conferences and archived conferences. So basically, each link in the menu is a view that shows only one particular field from a node. I pretty much got that part down.

Next I needed the ability for these menus to be dynamically created whenever I created a piece of content. So the 8th annual conference should have a menu created due to the fields in the Conference content type being populated.

Does anyone know an approach to dynamically create these menus links when a node is added? The approach I took so far was trying to add arguments that could be used in the view based on the node ID.

You can do it with Field Group module and also use Display Suite which gives lot of options to display your content. Check out the image, it was created using field group.