Removing the email validation requirement I'm building a premium membership site where a visitor can purchase a role, and gain access to the privileged content using the Ubercart module. I've got all that working fine, but the last tiny snag that my client wants to remove is to remove the validation email requirement that's fired when someone signs up on the site in Login Toboggan (6.1.9). I've got nothing set that is forcing this extra step and I've come to believe that this may be a feature in Drupal (Acquia distro 6.22) core for any user that registers. I was hoping that this module (Logintoboggan) would eliminate that step but I've not as of yet been able to do so.

I can allow the newly registered user access by setting that in the module, but the notification and validation email requirement still remains. Can anyone recommend a way around this? I just want them to be able to come to the site purchase their membership without any validation/confirmation email. Is this possible?

That setting is part of core Drupal.

Go to admin/user/settings, and under 'User Registration Settings' set 'Public registrations' to 'Visitors can create accounts and no administrator approval is required'. Also untick the 'Require e-mail verification when a visitor creates an account' checkbox and you should be good to go.

Once you've done that it might be worth re-checking your Login Toboggan settings just to make sure there's nothing interfering with your new settings.


Boost not working on pages with ?_utma Google Analytics cookie in url Boost works on every page, but it doesn't work on pages with Google Analytics variable in the URL. For example, http://stratton.wanderlustfestival.com/?__utma=1.485948833.1348167330.1348796515.1348837057.31&__utmb=1.3.9.1348837058695&__utmc=1&__utmx=-&__utmz=1.1348167330.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)&__utmv=-&__utmk=172983075 doesn't show <!-- Page cached by Boost @ 2012-09-27 16:23:18, expires @ 2012-09-28 04:23:18 --> while http://stratton.wanderlustfestival.com does.

Boost saves the page cache in a file named after the page + the query string, the limit on the length of a filename is 255 in Linux so for pages with very long name/query string combinations caching will fail.

This should show up as an error in the Drupal log and if it does the solution is edit the .htaccess: Find the comment "Caching for anonymous users", after this you'll find a line "RewriteRule .* - [S=4]", replace this line with the following code:

RewriteRule .* - [S=6]

# If the page/query string combination is not over 255 characters, skip the following 2 rewrites
RewriteCond %{QUERY_STRING} "utm_campaign"
RewriteCond %{QUERY_STRING} "utm_medium"
RewriteCond %{REQUEST_URI}_%{QUERY_STRING} ^(.*\/)([^\/\n]{0,255})$
RewriteRule .* - [S=2]

# Custom Campaign Query
# Create file if not already boosted
# One campaign item is lost for file creation.
ReWriteCond %{QUERY_STRING} "utm_campaign"
ReWriteCond %{QUERY_STRING} "utm_medium"
RewriteCond %{DOCUMENT_ROOT}/cache/normal/%{HTTP_HOST}%{REQUEST_URI}_\.html !-s
ReWriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI}? [L,T=text/html]

# Boosted file for campaign (now with query string).
ReWriteCond %{QUERY_STRING} "utm_campaign"
ReWriteCond %{QUERY_STRING} "utm_medium"
RewriteCond %{DOCUMENT_ROOT}/cache/normal/%{HTTP_HOST}%{REQUEST_URI}_\.html -s
RewriteRule .* cache/normal/%{HTTP_HOST}%{REQUEST_URI}_\.html [L,T=text/html]

This makes sure that if the page/analytics query string combination is too long it will cache the page without query string instead, the first request will be redirected to the page without the Analytics query string, the next request will be served from cache and the query string will stay intact.

Note that this code is aimed at long url's with Google Analytics tracking variables only but can be (and possibly should be) rewritten so it can be used universally.


excluding non english field values from search_api index (or facet) I have a CT product and a CT factory. Products have an entity reference field pointing to factories. I use node translation on factories (en, fr, de) but products are not translated (en only).

Creating facet on the product's factory (entity reference field) and indexing works well but the problem is that the facet displays all translated versions of factories. e.g:

china factory in english (14)
china factory in french (14)
china factory in german (14)
taiwan factory in english (6)
taiwan factory in french (6)
taiwan factory in german (6)
EU factory in english (2)
EU factory in french (2)
EU factory in german (2)

Since the search page regards products which are only in english, I'd like to be able to remove the fr and de values from that facet, or even better, not allow them to be indexed at all.

I've tried the facetapi_bonus module but its options for values exlusions doesn't suit me because I don't know the titles of the factories or their node ids beforehand.

I will venture a guess that when choosing indexed fields for the Product CT, you selected 'Factories' field and created the facet against this. Since you are using node translation, it is quite sensible that all available nodes (in various languages) are displayed in the facet. I suggest you try the following:

Remove/disable field 'Factories' from the list of indexed fields and remove the respective facet
At the bottom of the fields configuration for the index, you will find an option labeled 'Add related fields'. Choose field 'Factories'. With this action, all fields of the referenced Factory CT will become available for indexing
Enable the field that is correlated with the translation source node. Label should be something like this 'Factories >> Translation source node'. Create a new facet against this field
Clear indexed data and re-index

Most probably, the new facet will only display the facet terms in the default translation language (English in your case)


How to implement template file that would reside in database? I was wondering if it would be possible to have a template "file" that would be stored only in DB and would not exist physically?

Twig tempaltes are parsed from files only once and they are processed and stored in DB anyway so would it be possible to have such DB entry from the get-go?

You can register a loader, see Drupal\Core\Template\Loader for the implementations that drupal core uses and their parent classes/interfaces.

See also how they're registered in core.services.yml, for example:

twig.loader.filesystem:
    class: Drupal\Core\Template\Loader\FilesystemLoader
    arguments: ['@app.root', '@module_handler', '@theme_handler']
    tags:
      - { name: twig.loader, priority: 100 }

So, it's certainly possible to do it, if it's a good idea is another question ;)


How to create a select list that contains url links This is probably a very noob question but here it is none the less. I want to create a select list that contains the names of places around the world. When the user clicks on a name, it uses a hidden url to go to that place. So what the user sees is a normal select list of place names (not links), when they select an item then they are taken to that page.

On the manage field tab of the node that this is implemented on, I tried creating a select element with the following options:

 http://www.australia.com|Australia
 http://www.germany.com|Germany

But this doesn't work. What do I need to do to accomplish what I want?

With views you van create jump menu's: http://nodeone.se/en/learn-views-with-nodeone-part-18-jump-menu

You can use that view as a block on your page.

If you want to use it between your other fields, you can use the module https://www.drupal.org/project/viewfield. Add a field of type viewfield on your content type, choose the view you created earlier and pass the nid as parameter.


How do I hide the title on a specific node? How can I hide the title on a specific node?

I have tried the following three modules, but none of them do what I'd like.

Page Title
Exclude node title
Automatic Node titles

I added field_hide_title to the page content type, the code in hook_preprocess_node() function. It can't work fine.

The value shown from print_r($vars['node']) is the following:

stdClass Object(
  [vid] => 4
  [uid] => 1
  [title] => search_material
  [log] =>
  [status] => 1
  [comment] => 1
  [promote] => 0
  [sticky] => 0
  [nid] => 4
  [type] => page
  [language] => zh-hant
  [created] => 1339055801
  [changed] => 1339727555
  [tnid] => 0
  [translate] => 0
  [revision_timestamp] => 1339727555
  [revision_uid] => 1
  [body] => Array(
    [und] => Array(
      [0] => Array(
        [value] =>
        [summary] =>
        [format] => php_code
      )
    )
  )
  [field_hide_title] => Array(
    [und] => Array(
      [0] => Array([value] => 1)
    )
  )
  [rdf_mapping] => Array(
    [rdftype] => Array([0] => foaf:Document)
    [title] => Array(
      [predicates] => Array([0] => dc:title)
    )
    [created] => Array(
      [predicates] => Array(
        [0] => dc:date
        [1] => dc:created
      )
      [datatype] => xsd:dateTime
      [callback] => date_iso8601
    )
    [changed] => Array(
      [predicates] => Array([0] => dc:modified)
      [datatype] => xsd:dateTime
      [callback] => date_iso8601
    )
    [body] => Array(
      [predicates] => Array([0] => content:encoded)
    )
    [uid] => Array(
      [predicates] => Array([0] => sioc:has_creator)
      [type] => rel
    )
    [name] => Array(
      [predicates] => Array([0] => foaf:name)
    )
    [comment_count] => Array(
      [predicates] => Array([0] => sioc:num_replies)
      [datatype] => xsd:integer
    )
    [last_activity] => Array(
      [predicates] => Array ([0] => sioc:last_activity_date)
      [datatype] => xsd:dateTime
      [callback] => date_iso8601
    )
  )
  [cid] => 0
  [last_comment_timestamp] => 1339055801
  [last_comment_name] =>
  [last_comment_uid] => 1
  [comment_count] => 0
  [name] => admin
  [picture] => 0
  [data] => b:0;
  [entity_view_prepared] => 1
)

============================================================
UPDATE:

but I found one thing. before I change the title to NULL, the title has been displayed out...

print_r($vars) in mytheme_preprocess_page function:

[summary] => [format] => php_code ) ) ) [field_hide_title] => Array ( [und] => Array ( [0] => Array ( [value] => 1 ) ) ) [rdf_mapping] => Array ( [rdftype] => Array ( [0] => foaf:Document ) [title] => Array ( [predicates] => Array ( [0] => dc:title ) ) [created] => Array ( [predicates] => Array ( [0] => dc:date 1 => dc:created ) [datatype] => xsd:dateTime [callback] => date_iso8601 ) [changed] => Array ( [predicates] => Array ( [0] => dc:modified ) [datatype] => xsd:dateTime [callback] => date_iso8601 ) [body] => Array ( [predicates] => Array ( [0] => content:encoded ) ) [uid] => Array ( [predicates] => Array ( [0] => sioc:has_creator ) [type] => rel ) [name] => Array ( [predicates] => Array ( [0] => foaf:name ) ) [comment_count] => Array ( [predicates] => Array ( [0] => sioc:num_replies ) [datatype] => xsd:integer ) [last_activity] => Array ( [predicates] => Array ( [0] => sioc:last_activity_date ) [datatype] => xsd:dateTime [callback] => date_iso8601 ) ) [cid] => 0 [last_comment_timestamp] => 1339039221 [last_comment_name] => [last_comment_uid] => 1 [comment_count] => 0 [name] => admin [picture] => 0 [data] => b:0; [entity_view_prepared] => 1 ) )

You can create a cck field(checkbox/boolean) for that will act as a flag. So you can have a dynamic option if you want to hide the node or not.

Pseudo code:

In template.php

function yourtTheme_process_page(&$variables) {
  if($variables['node']->field_hide_title['und'][0]['value']) {
    $variables['title'] = NULL;
  }
}

Haven't try this code but I think this will work.

EDIT: Added screenshot of a new field

This should be the value of your cck


How to retrieve the order id of an order in drupal commerce? Is there a way to do it from the tpl?

ie: page--admin--commerce--orders.tpl.php

I've tried this, but naturally, I get an undefined $order_id variable

if (commerce_order_load($order_id)) {
  echo $order->uid;
}

If you're looking for the order ID related to the current cart you can use commerce_cart_order_id():

$order = commerce_order_load(commerce_cart_order_id());

But you shouldn't use it directly in a template file. Use a preprocess hook instead, it's better all round.


How can i redirect the path from the product save button? In my drupal commerce installation are two roles and one of them havn`t the permission for the admin/commerce/products path. They get an "access denied". Thats not so nice. How can i overwrite the path from the submit button in the product form to another site (maybe to a views page)?

I`m little bit confused, is it not possible to show only the products from the current logged in user on the admin/commerce/products path? I be really convinced that i give all the right permission.

Thx! Bruno

Easy to do with Rules, no coding required.

You can import this rule export, but will need to adjust the role ID and redirect path to match

Redirect on product save using Rules

{ "rules_redirect_on_product_save" : {
    "LABEL" : "Redirect on product save",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : [ "commerce_product_update" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "somepath" } } ]
  }
}


Forward authenticated user to user.page on /login uri If an authenticated user navigates to /login on a Drupal 8 site, she gets the "access denied" error. I want the site to redirect that user to /user (route user.page) instead.
Unfortunately my RouteSubscriber doesn't work:

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {

    /* @var \Symfony\Component\Routing\Route $route */
    if ($route = $collection->get('user.login')) {
      $route->setPath('/anmelden');
      $route->setRequirements([]);
      $route->setDefaults(array(
         '_controller' => '\Drupal\asdentbase\Controller\LogonController::login',
         '_title' => 'Anmelden'
       ));
    }

And my LogonController looks like

public function login() {

    if ($this->currentUser()->isAuthenticated()) {
      return $this->redirect('user.page');
    }

    $rc =
    ...

The route redirection to /anmelden works fine. But my LogonController::login function is never called for already authenticated users. There's seems to be any further magic in the core.

More detail:

I also have a route in mymodule.routing.yml like

asdentbase.login:
  path: '/anmelden'
  defaults:
    _controller: '\Drupal\asdentbase\Controller\LogonController::login'
    _title: 'Anmelden'

You also need to register your class in the event subscriber serivce. Create a YML similar to this:

asdentbase.services.yml

services:
  asdentbase.route_subscriber:
    class: Drupal\asdentbase\RouteSubscriber
    tags:
      - { name: event_subscriber }


CKeditor adding an extra  tag when a  tag is encountered I am experiencing a very annoying problem with ckeditor 4.4.7.3. Everytime a
 is entered into the editor, it displays the next line right below the existing line as one would expect. However, when you view the page, an extra
 tag appears along side the original
 tag. You can see this when looking at the source for the page.

Rendered output

  Age

  24

Looking at the source html while in ckeditor reveals that there is only one
 there.

Source as seen in ckeditor

  Age

  24

This would seem to indicate to me that Drupal is adding line breaks while rendering the output. I have tried disabling the option: Convert line breaks into HTML (i.e.
 and
) in the text format, but that doesn't change anything. I have also disabled JavaScript to see if some JavaScript file is doing this - but that makes no difference either.

I have googled this issue and have not found a solution yet (other people have been experiencing as well but no solution given). I would appreciate any suggestions in fixing this problem.

As it turns out, disabling the option: Convert line breaks into HTML (i.e. <br> and <p>) in the text format does make a difference. I needed to flush the cache to see the results. Hopefully this will help other people who experience this problem.


How do I get a list of Drupal 7 active contexts for the current page/form in hook_form_alter? I have several contexts defined for my site. In hook_form_alter I need to find out which of them are active. I am trying to use context_active_contexts, but that is only showing 2 of the (at least) 3 that are active. i.e. I have contexts A, B and C. C has a block reaction and the block is visible. My code only outputs A and B. If I disable C, the block disappears from the output, giving me some confidence that it really is context C that is responsible for it. Why can I not see A, B and C in the output?

function MyModule_get_current_location_contexts() {
  $contexts = context_active_contexts();

  $locations = array();
  foreach ($contexts as $context) {
    $locations[$context->name] = $context;
  }

  return $locations;
}

function MyModule_form_alter(&$form, &$form_state, $form_id){
  dsm('Contexts (form):');
  if ($form_id == 'MyForm') {
    $contexts = MyModule_get_current_location_contexts();

    foreach ($contexts as $context) {
      dsm($context->name);
    }

    dsm($form);
  }
}

function MyModule_node_view($node, $view_mode, $langcode) {
  dsm('Contexts (entity):');
  $contexts = MyModule_get_current_location_contexts();

  foreach ($contexts as $context) {
    dsm($context->name);
  }
}

The context name is the array key, not it's ->name field. See my answer here on how to programmatically check if a context is active.

No need for foreach loop on $contexts on the 2nd and 3rd functions. Instead of loopoing on $contexts and printing for each context it's name field, you should simply print the array keys:

print_r (array_keys($contexts));


How to write a view of a user signed up nodes? There is a content-type (event) with signup enabled. I want to show, on a user profile, the events this user has already signed up. I am having several frustrations with the signup relations and arguments. Is this possible with the current 2.x release?

There is a default view called signup_current_signups that provides this functionality out of the box.


Where does the style guide get generated? I just enabled the Zen theme, created a new sub theme and ran gulp successfully. On the Zen documentation, it says a gulp task should generate a styleguide for me, but I am not sure what the url is or how to find the generated styleguide.

  Zen now includes a KSS-based living style guide. KSS reads comments in your Sass files and automatically generates a Style Guide that shows how your actual CSS works on your Drupal site.

Once you run gulp, the style guide will be generated in

  /path/to/your/theme/styleguide/

Just open the index.html file in your browser to view the contents.


Uploading via default image on Articles not working I am trying to upload images on the default Article node type on D7.

The upload works and the image is confirmed via Linux on the file system.

However, the icon of the uploaded image is a broken link image and the same when viewing the page.

I get the following error message:

Forbidden

You don't have permission to access /RT/sites/default/files/field/image/prayer.jpg on this server.

Please help.

UPDATE:

I have been looking into permissions as a solution but with no luck. I went as far as assigning 777 permissions to the files folder and all it's sub-folders and even the target image.

Strangely, I tried uploading an image to an article node on a different website running on the same server which worked. I installed a fresh website and tried it there and that also worked.

Basically, it seems one website among three all on the same server is not responding correctly when I attempt to upload images.

This is a permissions issue. You need to chmod the directory tree.

Edit: A tutorial on setting directory permissions can be found on drupal.org at Securing file permissions and ownership .


Featured image for teasers? I have a client who is an architect. I've created a content type called "project" that allows them to select multiple images to display on a page. These project items get promoted to the home page as teasers, however I'd like the customer to be able to select a featured image to display in the teaser, rather than having every image display.

Anyone know an easy way of doing this without having multiple image fields?

I would say the easiest way is to make the first image also be the "featured" one, as then you already have most of the functionality built in.

It is then trivial to use a view that filters on "Image field: delta = 1", to give you only that one image, and then output it where appropriate.

A php savvy themer could also pull out the first image right in the template as well.


variable_get with prefix It's there a chance to retrieve all key/value, stored in variable table, that have a prefix, using variable_get()?
e.g: variable_get("prefix_*")

Or I have to use db_select('variable')?

I'm afraid not, variable_get() is a very simple function that just returns an item in the global $conf array, there's no method for searching built in.

You could write your own variable_select() function though, and you wouldn't have to go into the database as the entire variable table is loaded into $conf at the start of the page build. It might go something like this:

function variable_select($prefix) {
  $found = array();

  global $conf;
  foreach ($conf as $key => $value) {
    if (strpos($key, $prefix) === 0) {
      $found[$key] = $value;
    }
  }

  return empty($found) ? FALSE : $found;
}

I'm sure that could be improved but it's a start. It's worth noting that this method might match elements from the settings.php file that aren't actually variables in the database as such.

For example, if your prefix is data, it's likely you'll see the $conf['databases'] variable from settings.php in your results. There wouldn't be a way around that without going directly into the db I don't think.


Forms api validate float when using the Drupal FAPI and needing a float number field you have to use type textfield.  What's the best way to validate that this data is a float during hook_form_validate9)?  Is there a built in function. or do you have to do is_float()?

Thanks.

Because form input is always a string, is better to use is_numeric().

See is_float() note.


How to create a view displaying fields only from block it was created in (Custom Blocks Types + Paragraphs) So I'm trying to create a view on a slideshow content type. I want to create multiple slideshows. However, whenever I create a slideshow, I want to run a slideshow that only displays the slides from the paragraphs I created in that specific node.

NOTE: I don't want to add filters that only show from that specific node ID. I want something that works exactly how field collection views worked in Drupal 7.

Anyone know of any solutions?

[Update]

So while I started to go into this, I decided to change route of what I wanted to do. Learning more about how Drupal 8 works, I decided to change from making a slideshow content type to creating a new block type for slideshows. Inside the new block type I am using paragraphs for the slide information.

What I want to do is create a display view for the slides in each block type created (slideshow).

In my views settings I created a context filter by Paragraph ID. It's almost where I want it to be however, my view is only displaying the first item of the paragraph (the first slide fields). Its not until I put, (display all fields inline) does it show my slides. However, this doesn't help me with using flexslider or slideshow. I need them to be separate to have the slideshow work properly.

When I go to my fields tab and I look at my Slides (Paragraph). Under "Multiple Field Settings" it has the checkbock "Display all values in the same row".

I obviously want this unchecked because I need them to be in different rows for the slideshow to cycle though. If I leave it unchecked it only shows the first item in the paragraph.

Lastly, under the checkbox it says "If not checked, each value in this field will create a new row. If using group by, please make sure to group by "Entity ID" for this setting to have any effect."

However, it's not doing that, it just shows the first item and that's it. I'm not using grouped by so the last part shouldn't matter...at least I think it shouldn't.

"Help me, I'm poor"

To start, I cannot think of any benefits for creating a block type to act as a container element for slideshows. Especially since you will be using views to create the slideshow. If you like, please write in a comment why you felt it was a good idea. IMO content types make more sense.

The main cause of your problem is probably a misunderstanding of what is happening. A paragraph field on a drupal entity (block, node, whatever) is a one to many relationship. Every paragraph you add to the field will be a separate entity with its own id. If you have a contextual filter on the paragraph id, it does make sense that Drupal only loads one slide. You instruct it to load one id. (In fact I am surprised that you somehow managed to show more).

Normally you would add the reverse relationship (from paragraph item to container entity) and then use a contextual filter on the container entity: I would create a slideshow of paragraph items, add a relationship to the node and then use a contextual filter on node id. Then if I filter on node id 1, I would see all paragraph items linked to node 1.

Since you are now dealing with a block, I think you might be able to build a similar construction (relationship to the block and contextual filter on block id?) But I encourage you to reconsider.


Garland sub-theme color functionality is not working I have a subtheme in Drupal 7 for Garland theme. below is my my_garland.info file for the sub-theme

name = My Custom Sub Theme
description = Custom sub-theme of Garland
core = 7.x
base theme = garland
stylesheets[all][] = my_garland.css

i have also include some information in the template.php file to help with the color module

function my_garland_process_html(&$vars) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($vars);
  }
}

I have also copied the color and images file from the garland theme therefore the initial blue works perfectly and i can see the color wheel but the total page layout is not changing.
I have also tried to follow this link to see if it will be resolved but all in vain. Thanks in advance for your assistance.

From Example: Creating a Garland Subtheme That Utilizes the Color Module

  That said, even if you do not have a style.css file in your subtheme
  directory, you still must add it to your .info file with
  stylesheets[all][] = style.css


How to get the node ID in jQuery/JavaScript Is there a definitive, universal way to do this? For example using some environment variable that comes with Drupal.behaviours?

I have done some research and there seems to be no common answer.

As mentioned above, Drupal core has no use for the node ID on the client side so it doesn't pass it through. if you want access to it you'll need to add it manually:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full') {
    $setting = array('MYMODULE' => array('currentNid' => $node->nid));
    $node->content['#attached']['js'][] = array(
      'data' => $setting,
      'type' => 'setting',
    );
  }
}

Then on the client side you'll have access to it through Drupal.settings:

var currentNid = Drupal.settings.MYMODULE.currentNid;


Where do i enable caching for drupal 7 panels data for Logged in Authenticated users? For drupal 7 panels where do i set the settings to enable caching for logged in authenticated users?

You can enable Panels caching on a per-panel-pane basis.

Edit the panel pane and set the "Cache" configuration there.

You can also create your own cache plugins via the ctools plugin API.


Override the body field with another field in hook_node_view I have a node type that can be scheduled. Before the start time the page will redirect to another. This is all custom functionality and is currently working.

Now I need to create a coming soon page to allow the page to be active before the start time but not show any of the details.

I've created a coming soon field in the node and I have the logic set up correctly but I am struggling with the render array.

function MODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'TYPE') {

    // admins see the page no matter what
    if (!user_access('administer site configuration')) {

      // if not started, show coming soon page
      $coming_soon = FALSE;
      if (!STARTED) {
        $coming_soon = field_get_items('node', $node, 'field_coming_soon_body');
        if ($coming_soon) {
          $node->content['body']['#object']->body[$node->language][0]['value'] = $coming_soon[0]['value'];
        }
      }
    }
  }
}

This however still shows the actual body of the page and not the coming soon page. I really want to do this in hook_node_view as well.

How can I go about replacing the content of the page with this single field?

Just hide your body field, if there's a value in your field_coming_soon_body:

    if ($coming_soon) {
      $node->content['body']['#access'] = 0;
    }


Finding out what file was called immediately before error I'm getting the following errors in dblog whenever I look at a page:

Notice: Undefined offset: 0 in _menu_check_access() (line 635 of /home/mysite/public_html/includes/menu.inc).

Notice: Undefined offset: 1 in _menu_check_access() (line 635 of /home/mysite/public_html/includes/menu.inc).

I know it's not Menu that's causing the issue, but rather, some module is passing permissions incorrectly via hook_menu.

I remember reading a long time ago that one way to find out which module is causing core to emit notices, is to drop a function right before the line in question. Alas, I cannot find that page at all.

Any thoughts?

If you are tracking down a weird error, editing core is perfectly acceptable.

Make sure everything is in your RCS.
Edit includes/menu.inc
Place a print_r(debug_backtrace()) near line 635, preferable at the top of _menu_check_access().  Alse print_r() the arguments.
Trigger the problem.
Figure out what happened.
Revert the site to the checked in RCS version.

My guess is you are getting weird path, and the argument is wonky for your access check.  In other words, you are trying to access check something that should really 404.


The connection to the server was reset after trying to log as admin to Drupal I did upgrade on Drupal 7 and imported these sites and database from localhost to another server. On localhost everything works well, on the server I can´t log to Drupal as admin. After  entering password every browser shows similar message:The connection to the server was reset while loading page. When I want to change address in browser after that I have to delete all history, cookies, cache, etc., otherwise it writes the same message. I changed base_url, cookie_domain in settings.php, deleted cache and session tables in database. It didn't help.

Notes:

Putting /?=admin doesn't work, I am redirected to homepage, even on my localhost page where I can login .htaccess has the same content as old .htaccess
My pages are on web hosting. I am not sure if I can restart webserver by myself.
About server log messages: any special thing except of missing of favicon.ico in folder. I repaired it.
I tuned the .htaccess file. I don't see effect for a while. Maybe after server restart?
I don´t have Coder module.
my web hosting doesn't allow me increase stack size. Is this problem always connected with some Drupal module? Is somewhere some list of Drupal modules which causes page reset after admin login? Code module isn't my case.

This problem was finally solved by Php upgrade on the side of hosting server!

Restart webserver

Might be a webserver issue. Try restarting you webserver and check if it solves your issue.

Check server logs

If that doesn't help either, check your webserver's error log to see if there is any special error message in these that helps.

Tune the .htaccess file

Modified the .htaccess file and replace the default clean URL rewrites with this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Coder module

Option a: Remove the Code module

A complete different reason for this issue is Coder makes Drupal go to "Connection was reset" browser error. So if you have the Coder module installed/enabled, then disable and uninstall it and ALSO remove that module from the module folder.
Option b (if using WAMP): increase the stack size

Be aware that preg_match_all uses the stack which may be too small. PHP crashes and then Apache crashes (and restarts). The fix is to increase the stack size to match a default Linux PHP Apache setup. To do so, increase the Apache stack size to 8MB by adding a line to the end of httpd.conf (surrounded by a IfModule mpm_winnt_module and matching /IfModule tag):

  ThreadStackSize 8388608

After restarting the webserver you can then use any version of the Coder module (and other modules which have this issue ...).

More details: https://www.drupal.org/node/1597820#comment-6094060


Views 3 (D7) Attaching custom markup to individual view results Ok so a bit of background first on why I want to do this, this may also spark someone to suggest a better way of doing this also. I'm always open to ideas!

Basically I have a bunch of content types, call them rooms for the moment.
I am using views to sort/search these rooms, works great (as expected with views).

Now what I want is to attach some php and an jquery script to each view result itself, this script will get an ID from a field attached to the view result, this will then be sent as an ajax request get some information and then come back with some results which will then be printed underneath the view result.

How do I go about doing this? I've taken a look at a few of the different hooks available for the views api but can't really figure out which one is the one I want.

Any suggestions are greatly appreciated. Dan

Try hook_views_pre_render() see docs and drupal_add_js().

Add the correct JS using drupal_add_js by injecting the JS file using hook_views_pre_render() to fire on the correct view.
Your JS will have to understand the default views output to re-theme / alter HTML output accordingly. Firebug or Chrome Developer tools can help you with that.
you can use $view->attachment_after to attach like a custom blob of HTML like

 so you can muck with this div on your Ajax callback. You can add the view attachment in the view_pre_render


Drupal 7 form missing from $form object during Ajax callback function I'm using this example code to create a 'add another field' to my custom Form. The form itself is quite big and showing a full example here isn't possible.

The problem I'm having is that when I hit my callback button to 'add another field' the $form variable is missing most of the form I wish to utilise. My form is an admin area only form, but using the above example works fine in my implementation as POC.

The form utilises vertical_tabs but I have also tried without. I have a lot of validation around this form and in essence it's being built of a yaml file but I can't work out why the form elements are missing during the ajax callback. $form_state contains all the values submitted by the form including the missing data from $form.

I had assumptions that #tree was the issue but, I have this set to TRUE from the start.

Just incase anybody wants to know the issue was I was trying to obtain a value from arg() and this was different for the ajax callback funtion. So in my hook_form function I set the following:

  // This is needed for the ajax callback
  if (arg(1) != 'ajax') {
    // We need to set the variable before we load the form.
    $form_state['value'] = arg(3);
    $key = arg(3);
  }
  else {
    // Ajax callback can now reference correct key.
    $key = $form_state['value'];
  }

This allowed me to obtain the correct value during the ajax callback function.


Error 500 when downloading updates for modules Recently I've transferred several Drupal sites to DigitalOcean.com VPS server (Ubuntu).
Almost all work well.

But when I try to downloading updates for modules I get error:

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?render=overlay&id=82&op=do StatusText: Internal Server Error ResponseText

I see the error for every Drupal sites at VPS.
I can successfully update modules by drush.
But I want to understand the problem.

There is no error record at error.log (Apache)
And there is following line at access.log:

POST /batch?render=overlay&id=83&op=do HTTP/1.1" 500

How can I solve the problem?

UPDATE:
It seems the problem in PHP.
There is known bug with gzopen() for Ubuntu32.

It was PHP bug with Ubuntu 32bit.

I've solved the problem after installation of newer PHP version


Override forum topics list The forum topics list has this in the table header: Topic, Replies, Created, Last Reply. I just want to remove the Created heading.

Template file forum-topic-list.tpl.php prints the table header with <?php print $header; ?>

The template file documentation explains that:

  $header is pre-generated with click-sorting information. If you need to change this, @see template_preprocess_forum_topic_list() @see theme_forum_topic_list().

So I dig around in forum.module and find template_preprocess_forum_topic_list(). This function appears to prepare the variables for the header, but doesn't create the HTML for the output.
I look up the other function that was referenced, theme_forum_topic_list().

The API documentation reports the following:

  This function is never used; see the corresponding template file instead."

What am I missing here?

template_preprocess_forum_topic_list() initializes the variable with the value returned from _theme_table_cell().

global $forum_topic_list_header;

// Create the tablesorting header.
$ts = tablesort_init($forum_topic_list_header);
$header = '';
foreach ($forum_topic_list_header as $cell) {
  $cell = tablesort_header($cell, $forum_topic_list_header, $ts);
  $header .= _theme_table_cell($cell, TRUE);
}
$variables['header'] = $header;

function _theme_table_cell($cell, $header = FALSE) {
  $attributes = '';

  if (is_array($cell)) {
    $data = isset($cell['data']) ? $cell['data'] : '';
    $header |= isset($cell['header']);
    unset($cell['data']);
    unset($cell['header']);
    $attributes = drupal_attributes($cell);
  }
  else {
    $data = $cell;
  }

  if ($header) {
    $output = "$data	";
  }
  else {
    $output = "$data	";
  }

  return $output;
}

The variable $variables['header'] in template_preprocess_forum_topic_list() is the same variable that in forum-topic-list.tpl.php is accessed as $header.


Get values from a multi value field? I have a field that can accept unlimited values. I want to print those values in my template.

The array that I can see with the devel module looks like this....

Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [value] => Dustin
                    [format] =>
                    [safe_value] => Dustin
                )

            [1] => Array
                (
                    [value] => Jen
                    [format] =>
                    [safe_value] => Jen
                )

            [2] => Array
                (
                    [value] => Mike
                    [format] =>
                    [safe_value] => Mike
                )

        )

)

What I'd like to do is have these values printed to a comma separated list like: Dustin, Jen, Mike

I've been using this code to print single value fields in my template but that of course isn't going to work well with a multi value field..

<?php echo $entityform->field_team_name['und'][0]['value']; ?>

field_get_items() will do the trick:

if ( ($items = field_get_items('entityform', $entityform, 'field_team_name')) ) {
  $values = array_map($items, function($x) { return $x['safe_value']; });
  $comma_separated = implode(', ', $values);
}


Dropdown SubMenus Based on Roles Stopped Working My site has a menu/top nav of course and I have various dropdown/sub menus.  Yesterday it was all working fine.  If you are an anonymous user, you see a particular menu item, that has a particular dropdown.  If an authenticated user, you see another menu.

Today, I looked at the page, first as an anonymous users, the top level menus are there, but when I hover the dropdown menus items do not appear.  I then logged in and same thing, the top level is there, but the hover does not display the submenus at all.

I then logged in as the admin and can see the top level menu and on hover, all the submenus appear.  So natural thought, something happened with the permissions settings, but I checked everything "seems" fine.  The only changes between today and yesterday afternoon where several updates to a stylesheet and I did add/install several modules [webform, token, date, calendar geolocation], I have not done anything to turn off the menu.  The top level is checked to show as expanded and of course, they show and function correctly when I am logged in as the ADMIN.

To explain my setup: where needed, I created two top menus for "speakers" for example:
speakers ->one ->two (permissions set to display for anonymous users)
speakers ->five ->twelve  (permissions set to display for anonymous users)

In the above example, anonymous user goes to page, hovers over speakers menu item, and should see in the dropdown [submenu items one and two] and this has been working for weeks now.  Same would apply for the authenticated user hovering over the second "speakers" and seeing [five and twelve in the submenu].

How do I debug this scenario to find out what is wrong?  I've been doing this long enough to know it is probably something I have done, but after checking permissions, checking menu visibility - oh I am also using the "Menu Per role" module that has been in place for weeks, I would like some insight on how to attack this problem.

Any suggestions would be greatly appreciated.

just posting my solution for those who may come after.

As I stated above, I did suspect that it was something I had or had not done to cause this issue.  Knowing for certain that the only changes made were related to stylesheet updates, which I knew could not cause this problem, and loading of new modules,  I decided I would have to uninstall them one-by-one, but before doing that, I went over the modules I installed yesterday [just a note: the reason I didn't see this issue yesterday was because the correct display had been cached] and thought about the problem and which module would most relate to that problem, so I started with jquery_update. [jquery/javascript typically used for these types of effects, hover onClick, etc.]

I installed jquery_update yesterday.  I did change the admin display option to version 1.7, but I left the working option at 1.10.  I disabled the module, refreshed my page and the submenus did appear on hover.

I was going to uninstall the module completely, then decided to set the working version back to 1.8 and the dropdown on hover continued to work.

I have not had time to really look, but the original developer set up the site with an older theme and I bet there is a conflict in the version used in the theme he/she chose and the most recent version of jquery.

Hopefully this will save someone a few hours of their life.

I do still love Drupal.


views: all terms as images I have a node view and want to show all terms (which have one image field per term) related to that node (which might be multiple terms), explicitly showing their respective images. How can I do that?

I was assuming that I would choose 'all taxonomy terms' as a field and then would e.g. rewrite the output, showing the terms' image fields. But they don't exist, hence don't show up. I know some workarounds based on theming with overwritten .tpl.php files, but I prefer dynamical solutions... So - does anybody have any suggestions for me?

The solution given by DrupalMonster is a straightforward, but barely scalable. I've been through a similar scenario and I eventually gave up on it when it got to real life.

I haven't been at Drupal for some time but I hope my suggestion will get you going.

Make a view that lists the terms. You will want to use contextual filter with node ID to tell Views which node you are viewing, and then test it (using normal environment) to make sure that it retrieves appropriate terms.
Once your view is working well, install Viewfield module. The module will provide a new field "Viewfield". Attach an instance of it to your node content type and configure it to display the View you have tested.
Theme the view using Views' tpl naming convention, accessible from Theme information in the Views editor.

HTH


Edit old revision without changing the current revision I'm using revisions to keep a public archive of changes in my nodes. Is it possible for me to edit an old revision of a node (both the message and the fields) directly, and not change the current revision? Basically, what I'm trying to do is what the User Revision Edit module does, but for nodes.

So far, in my custom module, I have something like this (notice that I'm also using the Revisioning module):

/**
 * Implements hook_menu().
 */
function node_revision_edit_menu() {
  $items['node/%node/revisions/%vid/modify'] = array(
    'title' => 'Modify this revision',
    'load arguments' => array(3),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_revision_edit_form', 1, 3),
    'access callback' => '_node_revision_edit_link_access',
    'access arguments' => array('modify revisions'),
    'file' => 'node_revision_edit.admin.inc',
  );
  return $items;
}

and the essence of the logic that I'm trying to apply:

function node_revision_edit_form($form, &$form_state, $node, $vid) {

  // Prepare loading the node edit form
  form_load_include($form_state, 'inc', 'node', 'node.pages');

  // Populate the form state.
  $form_state += form_state_defaults();

  // Save the form id for the current content type.
  $nfid = $node->type . '_node_form';

  // Rebuild the entire user edit form for our needs
  $form = drupal_retrieve_form($nfid, $form_state);
  drupal_prepare_form($nfid, $form, $form_state);

  // Setup the already existing log in the field
  $form['revision_information']['log']['#default_value'] = node_revision_list($node)[$vid]->log;

  // Set the "Modify current revision, no moderation" as the default revision operation
  $form['revision_information']['revision_operation']['#default_value'] = 0;

  // Unset the options that we do not need
  // unset($form['options']);

  // Create a new submit button since we do not want to invoke the standard callback functions
  unset($form['#submit']);
  $form['#submit'] = array('node_revision_edit_form_submit');

My problem is that I have no idea as to where to go from here. I obviously can't use node_save since it automatically handles revisions. Any ideas on what my next step should be? Is there a function that I'm missing and could be useful for my problem? Or will I have to go for direct database edits?

Any feedback is greatly appreciated.

I'm afraid that not even _node_save_revision allows that. Revisions were designed to keep old stuff archived and unchanged. Of course sometimes we need to violate that principle for the sake of moderation.

You will have to smartly adapt piece from above function:

$node->uid = $uid; // Make sure revision's author stays unchanged
drupal_write_record('node_revision', $node, $update);

I don't have time to experiment with it, but I'm sure you will find out pretty easily.

Carefully consider if you want to also call

module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

before save, and

module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

after save. Probably you don't, but it depends - some modules may use revision data for search or other purposes.

Last but not least: I must admit I have no idea how field_attach_update handles field revisions.


Export set variables from site to include in install profile Is there a module, separate from Features, that can export currently set variables (as you can see if you run drush vget) - in the correct format so that I can copy and paste into the install profile. - e.g. as variable_set('admin_theme', 'minimal'); for example.

A year or so ago I was working on a Drush command to export a working site as an installation profile. I haven't worked on it for a while, but it was my intention to use something like the Configuration Management module, or perhaps Drush CTools Export Bonus to include site configuration information with the installation profile.

If you are hand-generating your installation profile, typically you do write variable_set commands and put them directly into your installation profile.  When generating configuration information, though, I think it is typically the case that the config information is bundled in some other module.

Answering first question

By convention, variables in the variables table are  named after the module that defined them, so if everyone is cooperating, you know where the variables are coming from.  Install a fresh copy of Drupal, and make note of the variables that it defines, and their default values.  Compare these against the values in your site to find the ones you have changed.  Do the same thing for contrib modules, installing each module in your scratch site, and checking the default values.  Another option is to use Strongarm, which will show you the variables that changed (when they change), just like other features modules do.

The catch here, though, is that not all configuration is stored in the variables table.  Some modules define their own tables.  If you want to hand-code your configuration, you need to investigate the APIs for each module you use in turn, and figure out how to make settings programatically.  This is a difficult thing to do, which is why most people use features, or the configuration management module, or Ctools export bonus.  Even these modules are not always enough, as not everything supports exportables. It's a good thing that the CM initiative in D8 is addressing this problem.


Keep submenu expanded when parent or children are active I have a two-tiered menu system using the Nice menus module, which I've adapted to run horizontally with the children beneath the top level, as in the following menu.

  Home - About - Adopt an animal - Events - Get Involved - Contact

  Cats - Dogs - Small Animals - Birds

At the moment, the second tier is showing only on hover of the parent. After clicking through or landing on a page I need the children to be expanded when their parent or siblings are active and I'd like the parent to be highlighted as active in this case too - so in this example if I'm on Adopt an animal page or dogs / small animals / birds  then I need that expanded.

I'm not sure where to even start on this, I don't really want to hack it by duplicating false second tier menus and using context or block to display them on certain pages because I need to be able to hand over the menu administration so the integrity is important. Thanks for any suggestions.

Menu Trail By Path sets the active-trail on menu items according to the current url.

For example if you are at yoursite.com/blog/category1/article1
Menu Items with these paths will get the active-trail class on them and expand accordingly.

blog
blog/category1
blog/category1/article1

This is particularly useful if you want a lot of nodes to appear as children of certain nodes / taxonomy term / views / referenced nodes / etc, but do not want to add them all to the menu. eg. hundreds of blog articles.


Slow query with large dataset in Drupal views — better to process in SQL or PHP? I have a large userbase in my Drupal 7 site, which contains a People finder. Because there are hundreds of thousands of users and we want to display the People finder in a random order on page load, I presume it's transferring the whole userbase into memory at some point, in order to paginate (using the Pager built-in to Views2 Views3).

I've noticed that the query has no limit against it (presumably because of pagination) and that it joins against users_roles twice (because I need to include all users of rôle A but not also of rôles B, C and D). I've added comments against the WHERE clause to explain each line's purpose and how it's come out of my View.

SELECT
    users.uid AS uid,
    'user' AS field_data_field_user_image_user_entity_type,
    'user' AS field_data_field_user_field1_user_entity_type,         -- custom field
    'user' AS field_data_field_user_field2_display_user_entity_type, -- custom field
    'user' AS field_data_field_user_field3_user_entity_type,         -- custom field
    'user' AS field_data_field_user_field4_user_entity_type,         -- custom field
    RAND() AS random_field
FROM
    users users
    INNER JOIN users_roles users_roles ON users.uid = users_roles.uid
    LEFT JOIN users_roles users_roles2
        ON users.uid = users_roles2.uid
        AND (users_roles2.rid = :views_join_condition_0
          OR users_roles2.rid = :views_join_condition_1
          OR users_roles2.rid = :views_join_condition_2)
WHERE
    (( (users.status <> :db_condition_placeholder_3)      -- Active users only
    AND (users_roles.rid = :db_condition_placeholder_4)   -- Must be in rôle A
    AND (users_roles2.rid IS NULL)                        -- Must not be in rôles B, C, D
    AND (users.uid != :users_uid OR users.uid IS NULL) )) -- Must not be current user
ORDER BY random_field ASC

So I have two questions:

Is there some way in Views2 that I can somehow get this query to be limited (potentially by sorting on something else that pretends to be random)? I assume that transferring fewer result rows per query is likely to help with the memory overhead?
If I want to mess with that WHERE clause, am I better off using a PHP Filter Criterion to do the roles messing (which would presumably remove the double-join) or should I move the whole damn query into either a custom module[a] or a mySQL view[b]?

a: I assume that would attach to the relevant hook with a function modulename_views_pre_execute(&$view).
b: I assume a mySQL view would still need to do both joins, one inner join and one left join, so I can't quite see how this would help.

For what it's worth, I know that my site will have a relatively short lifetime and, during that, the rôles won't change, so I am happy to hardcode the rôle IDs, if that will give me a performance benefit.

Are you 100% positive that the view isn't paging in SQL?  When you turn on Query Logging in the Devel module, what do you see for your view?  I just double checked a site and am seeing (formatting is mine):

SELECT node.nid AS nid, RAND() AS random_field
FROM node node
WHERE (( (node.status = :db_condition_placeholder_0)
  AND (node.type IN (:db_condition_placeholder_1)) ))
ORDER BY random_field ASC LIMIT 10 OFFSET 0

when I am on paged view with a random sort.

I have seen the double JOIN thing before.  Often, you can adjust the view parameters and get the query to run the way you want.

Optimizing these queries is really use dependent.  I am pretty sure that both of the columns you are joining on are both indexed already.  You can try to replicate the query manually, and then EXPLAIN it, and manually improve it.  You can then implement this query in a custom block, but then you lose out on other things that Views give you.  Caching the view results, may help, too.

Keeping everything in MySQL is likely best (it is meant for heavy lifting like this), but only profiling will give the true results for your system.  Just make sure you have MySQL, Apache, and PHP tuned so that you aren't chasing the wrong problem.


Content type - field type - Select list: Add options: Existing content on the website I want to do something in my website, but I can't figure how. Let me explain:

I have a content type called bananas, and I have created a lot of bananas pages.

I want to create a content type called peaches and add a field with a select list called "Existing bananas on this peach" - and I want to be able to select from all the bananas pages my website has.
Then, if it is not asking too much, I want this field to be a link to the specific bananas page.

Am I making myself clear? For me it's simple, but I don't think there's a way on Drupal to do that. Or maybe there is, but I'm just not seeing it.

Hard or easy, do you have any solution?

Thank you so much in advance, hope you guys can help me.

Assuming you are using Drupal 7, I think you need the Entity Reference module.

This module provides a field that you can add to your content type peaches and provides the requested widget that allows you to select from all the bananas nodes your website has. When outputting the peaches node, the standard formatter (that the Entity Reference module offers) creates a link using the selected bananas node's title.


Is it possible to add a button to a field_collection? I've created a custom entity module, and the form for it uses field_collections. The only form field I've defined programmatically is the title, the rest of the fields and field collections for this form I've defined via the Drupal 8 interface.

I have a particular field collection with 8 dropdowns and a large textarea. I want the person using the form to be able to set the 8 dropdowns to certain values automatically based on the contents entered in the textarea, but only by clicking a button since they should also be able to manually set the dropdowns. The field_collection itself has unlimited allowed values, so there should be one button for each instance of that field collection in the form.

It was my plan to just get an inactive button into the form and add a front-end script to have it trigger a Javascript function, but I can't seem to figure out how to get a button in the form. It doesn't seem to exist as an option in field_collection field definitions. I had a prototype of this working in jQuery, but I'd rather not use jQuery to insert elements into the form if I can avoid it. So far Googling has proven fruitless. Is it possible to do this with hook_form_alter() perhaps?

I ended up asking Sacrilegious, one of the regulars in #drupal-support, and he offered this solution:

Define a new class in {module root}\Plugin\Field\FieldWidget names FieldCollectionCustomEmbedWidget.php

<?php

/**
 * @file
 * Contains \Drupal\{module}\Plugin\Field\FieldWidget\FieldCollectionCustomEmbedWidget.
 */

namespace Drupal\{module}\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\field_collection\Plugin\Field\FieldWidget\FieldCollectionEmbedWidget;

/**
 * Plugin implementation of the 'field_collection_custom_embed' widget.
 *
 * @FieldWidget(
 *   id = "field_collection_custom_embed",
 *   label = @Translation("Embedded custom"),
 *   field_types = {
 *     "field_collection"
 *   },
 * )
 */
class FieldCollectionCustomEmbedWidget extends FieldCollectionEmbedWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element['custom_button'] = [
      '#markup' => '
button text
',
      '#value' => t('button text'),
      '#attributes' => [
        'class' => [
          'my-custom-button-class'
        ],
      ],
    ];

    return $element;
  }
}

Then under Structure, I went into the settings for the form containing the field that needed this button, and under "Manage Form Display", I changed the widget type of the field to the newly added "Embedded Custom." Now the button is there.


hide image title in slide show Trying to show just the images in a slideshow 'view'.
Not sure where to turn the title off, I've tried changing it to <none>,
but it's still printing out over the image. I even changed it under 'manage display' to hidden field and I'm unchecking the default option of creating a label.
Where do I need to adjust this at?

Change the FORMAT to Show: Fields and then add only your image field and configure its formatter to show what you need – original image or image style or URL to image ...


How to track which external link users who registered on my site came from Google Analytics shows how many and from which links people have visited to my site as I have installed the Google Analytics module. How can I know from which link the individual registered users came from?  For example, I would like to know something like:

  The user (uid:30) came from  http://example.com
  The user (uid:31) came from  http://somesite.com

Or do I have to ask users directly by making a kind of "Where did you know about us" profile field?

I believe StatCounter allows for this
http://statcounter.com/
http://drupal.org/project/statcounter

I believe what your asking for is against GA's TOS http://drupal.org/node/318974


Image Field Browser Option Is there any way to alter the default Drupal 7 image fields to allow a browse server option along with the default upload file option? Kind of like imce or ckfinder but for image fields instead of content (text) fields.

It seems like this could be pretty useful and I don't really see any modules that offer this kind of functionality.

You could use the FileField Sources module.  To browse the server it looks like you need to use this with IMCE.  From the FileField Sources project page:

  The FileField Sources module expands on this ability by allowing you
  to select new or existing files through additional means, including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Select existing files through the IMCE file browser


Using Exposed Form to filter by referenced entity First, I'd like to start with my content structure:

Classrooms:
Title
Students_Attending [entity reference field with multiple values]

Students:
Name
Gender
Country
Classes
Avatar

Ok now, let's say I have a View that essentially lists Students. It has exposed fields for gender, country, and classes. You can use these to narrow down the subset of students listed by the view.

I want to add another exposed filter to this view. This filter will be a select box with a list of Classrooms, and you are able to select multiple classrooms. What this does in practice is that it limits the resulting subset list of Students to those that are referenced by the "Students_Attending" entity reference field of the "Classroom(s)" that was/were selected. So if I select "Classroom 1" on the exposed filter, the View will only list students who are referenced by the  "Students_Attending" field of "Classroom 1."

How do I achieve this with Views on Drupal 8? Is it even possible with Views alone?

It's not possible with views alone without custom code or another module.

See https://www.drupal.org/sandbox/el/2698765 or D8 entity reference exposed filter for ideas on how to proceed.


"\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container." I am attempting to write a PHPUnit test for a service of mine.

My test looks like the following.

class CustomServiceTest extends UnitTestCase {

  public function testDefaultBehavior() {
    $service = new CustomService(\Drupal::service('custom_utils.some_resolver'), \Drupal::configFactory());
    $service->execute();
  }
}

However, it raises the following exception.

Drupal\Core\DependencyInjection\ContainerNotInitializedException:
\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

What am I doing wrong?

You need to mock the services you will be using in your test, so that they return values. You can do that as follows:

public function testDefaultBehavior() {
  $some_resolver = $this->getMockBuilder('Drupal\namespace\for\custom_utils\someresolver')
    ->disableOriginalConstructor()
    ->getMock();
  $config_factory = $this->getMockBuilder('Drupal\Core\Config\ConfigFactory')
    ->disableOriginalConstructor()
    ->getMock();
    $service = new CustomService($some_resolver, $config_factory);

}

Note that you should use the actual interface (or class if you have no interface) instead of Drupal\namespace\for\custom_utils\someresolver

You'll need to set up expectations to return the values from the services you mocked. You can read more on that here:

https://www.drupal.org/docs/8/phpunit/understanding-phpunit-expectations


Where to find structure of objects that I can access in PHP snippets added to different parts of UI? In views I can add PHP snippets for custom validation or when I want to provide default value for contextual filter. It is telling me that I can use $view or $argument - but where is documentation of these objects? Where can I read what are my possibilities in these areas (or how check this, by using debugger for example)?

You can install the devel module and use the dpm function to check it out.
You can check the whole list of devel functions at http://ratatosk.net/drupal/tutorials/debugging-drupal.html


How to disable option for users who aren't logged in I've got custom content-type. On the main page I set teaser display of contents and I decided to show off only several fields there. Next to each content I can notice text "Read more". After entering it, I am redirected to full display of contents (There are show off all fields).

Action, described above can be done by everyone. But, I'd like to allow it only logged in users. How can I disabled it for users who aren't logged in.

Use the premium content module

Restricts access to premium content by role and provides a general API
for other modules to help decide if a user has access to premium
content.
This is useful on a news or membership site where teasers are
available to the general public but the full body is only available to
privileged users. Premium nodes appear in listings with full title and
teaser available to anyone. If a user does not have adequate
privileges, the default behavior is to show a simple message, but you
can use Panels or theme overrides to do more custom things.

All you need to do is enable the module, go to the edit page(admin/structure/types/manage/yourcontenttype) of the content type you want to make premium, and on the publishing options tab, select premium content


Why is my cron not running as intended? crontab -e displays

*/5 * * * * /persistent/sitename/scripts/cron-curl.sh
~
~
~
"/tmp/crontab.XXXX1FOZWa" 1L, 51C

Why is it not running every 5 minutes?

Did you modify cron-curl.sh to use the URL for your site? By default, it tries to load http://example.com/cron.php.


Exclude a single module from a Drush update? Is there a way to exclude a module from a Drush update so it can be ignored when running eg 'drush up' ?

I ask because Rules 2.8 is causing problems with Drupal Commerce but it would be great if everything else could still be updated with Drush.

You can use the following command:

drush pm-update --lock=modulename

There is a post here about it: http://blog.wassill.eu/en/blog/short-excludes-modules-drush-update-09-04-2013


Clearing local tasks cache Using a deriver, I'm able to produce local tasks for each entity of my custom configuration entity type. So if I have two configuration entity labeled "Foo" and "Bar", I can have similarly labeled tabs on a report page.

However, when adding or removing one of my configuration entity, the local tasks are not updated (ie. the tab for the deleted entity is still visible). This is not a surprise as these things get cached.

I've been able to fix the issues using implementations of hook_ENTITY_TYPE_insert() and hook_ENTITY_TYPE_delete() calling drupal_flush_all_caches(). But clearing all caches in order to only get the tabs on a single page updated seems a bit overkill. I already tried to call both menu_cache_clear_all() and Drupal::cache('discovery')->invalidateAll() without success

The tabs are build using the following code:

MODULE.tasks.yml:

MODULE.settings.webhooks_list:
  deriver: 'Drupal\MODULE\Plugin\Menu\LocalTask\ReportLocalTasks'
  base_route: MODULE.settings.list

src/Plugin/Menu/LocalTasks/ReportLocalTasks.php:

namespace Drupal\MODULE\Plugin\Menu\LocalTask;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\MODULE\CustomEntityTypeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ReportLocalTasks extends DeriverBase implements ContainerDeriverInterface {
  use StringTranslationTrait;

  protected $entityManager;

  /**
   * Constructor.
   *
   * @param $entityManager
   * @param $stringTranslation;
   */
  public function __construct(EntityTypeManagerInterface $entityManager, TranslationInterface $stringTranslation) {
    $this->entityManager = $entityManager;
    $this->stringTranslation = $stringTranslation;
  }

  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('string_translation')
    );
  }

  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = [];

    /** @var EntityStorageInterface $entityStorage */
    $entityStorage = $this->entityManager->getStorage('custom_type');

    /** @var CustomEntityTypeInterface $connection */
    foreach ($entityStorage->loadMultiple() as $entity) {
      $this->derivatives["MODULE.settings.list.{$entity->id()}"] = [
        'title' => $entity->label(),
        'route_name' => 'MODULE_ecom.settings.list',
        'route_parameters' => [
          'connection' => $entity->id(),
        ],
      ];
    }

    foreach ($this->derivatives as &$entry) {
      $entry += $base_plugin_definition;
    }

    return $this->derivatives;
  }
}

In order to have up to date tabs when adding or removing custom entity, I'm using the following code. What I'm trying to do is to have something more specific than the call the drupal_flush_all_caches().

MODULE.module

/**
 * Implements hook_ENTITY_TYPE_insert();
 */
function MODULE_CUSTOM_ENTITY_ETYPE_insert(\Drupal\MODULE\CustomEntityTypeInterface $connection) {
  drupal_flush_all_caches();
}

/**
 * Implements hook_ENTITY_TYPE_delete();
 */
function lMODULE_CUSTOM_ENTITY_ETYPE_delete(\Drupal\MODULE\CustomEntityTypeInterface $connection) {
  drupal_flush_all_caches();
}

First of all it might be that you found a bug in core (a caching issue), so it would be great if you could report it to the Drupal core issue queue as well. There is extensive test coverage for local tasks, but it might be that there is none for adding new entities and that those in core just work due to side effects.

To solve your immediate issue I would try to invalidate just the render cache of the local task blocks.

To find out the cacheability metadata of the local tasks the easiest is to install the renderviz module:

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

and apply the patch from this comment

https://www.drupal.org/node/2640280#comment-11286381

Once you have that installed and you go to the page with your local tasks, you will see a list in the JS console of all cache tags present.

For the bartik theme you will find (e.g. tested with core search pages, which have similar code to yours):

config:block.block.bartik_local_tasks

If you put into the console:

  renderviz('tags', 'config:block.block.bartik_local_tasks');

Then you will see that indeed the primary local tasks will be highlighted.

So in your hook_entity_insert() / hook_entity_update(), you can just do:

 Drupal\Core\Cache\Cache::invalidateTags('config:block.block.bartik_local_tasks');

And that will invalidate just the local tasks block and solve your issue for now.

What should have happened however is that the local tasks block should show both the cache tags for the list [entity-type] and the entities itself. (like a normal listing of entities)

e.g. if you want to change the title of any of your entities, core should based on the deriver update the local tasks block.

And that we don't do that is likely a core bug in regards to cacheability metadata, so please file it. Unless I miss something and there is some special code that makes this work for core's derivers out-of-the box.

Edit:

We correctly add the cache tags of the config entities, however there is no 'list' cache tag, which means that whenever you add or delete a config entity the local tasks don't get invalidated.

As you have a plugin, you can likely just add your own custom cache tag to the plugin definition.

e.g.

$base_plugin_definition['cache_tags'][] = 'local-tasks-my-entity-type-list-cache-tag';

Then just invalidate that list cache tag in your insert / update.

But that definitely is also an issue in Drupal core as I can reproduce it purely with core search pages.

I missed in your question at first that caches fail to get invalidated only when adding or deleting new entities.

That however was the key clue.

Edit 2:

Core should be invalidating list cache tags automatically, so the easiest is to just use the pre-defined list cache tags.

This is the diff that fixes the bug for me in core:

diff --git a/core/modules/search/src/Plugin/Derivative/SearchLocalTask.php b/core/modules/search/src/Plugin/Derivative/SearchLocal
--- a/core/modules/search/src/Plugin/Derivative/SearchLocalTask.php
+++ b/core/modules/search/src/Plugin/Derivative/SearchLocalTask.php
@@ -52,7 +52,9 @@ public function getDerivativeDefinitions($base_plugin_definition) {
           'route_name' => 'search.view_' . $entity_id,
           'base_route' => 'search.plugins:' . $default,
           'weight' => $entity->getWeight(),
 -        );
 +        ) + $base_plugin_definition;
 +
 +        $this->derivatives[$entity_id] += ['cache_tags' => []];
 +        $this->derivatives[$entity_id]['cache_tags'] += $entity->getEntityType()->getListCacheTags();
       }
     }
     return $this->derivatives;

That fixes the bug for me for core search pages.


Create renderable nested tree array like Menu Tree or Taxonomy Tree I am getting a nested array with children property from the WebSerice. I want to create the render able array so that I can use "drupal_render" function to render final HTML. I looked at the 'menu_tree_output' and 'taxonomy tree" that Drupal generates, but there is not proper documentation that mention how to structure the array to make it render able nested list.

Lets make it short: How do I restructure the final array that I get from Webservice so that I can make it renderable using drupal_render api. Final output is nested list(Folder tree).

What you are trying to solve is a recursive problem.... See below code which solves problem..

function listArrayRecursive($array_name, $ident = 0){
  if (is_array($array_name)){
    foreach ($array_name as $k => $v){
      if (is_array($v)){
        for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; }
        echo $k . " : " . "
";
        listArrayRecursive($v, $ident + 1);
      }else{
        for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; }
        echo $k . " : " . $v . "
";
      }
    }
  }else{
    echo "Variable = " . $array_name;
  }
}

$ages = array(
        "ahmed" => "25",
        "mohamed" => "35",
        "group" => array("omar" => "15", "abdalla" => "20", "sub group" => array("john" => "10", "peter" => "20")));

listArrayRecursive($ages);

Output will be


Drupal 7 Custom Page shown only for logged-in users My problem is that, I need to create a new Page (path f.e. //panel), but I want there only logged-in users. If user is not logged in, he should be redirected to login form. I was trying to do it with Custom Pages, but I dont know how to do it, I can create variant only with HTTP response code, and its working good, but I dont know how to show content of this page, it's simply redirected me if I'm not logged in or displaying, that page is not found if I'm logged in.
Do you know a solution for my problem?

You are creating a custom page, so you should use user_is_anonymous() in the calback of the page.

For example:

$form['custom_path'] = array(
  'page callback' => 'some_random_function',
);
function some_random_function() {
 if(user_is_anonymous()) {
  //call the login block
 }
 else {
  // What ever u want.
 }
}


Understanding namespaces I am new to namespaces and I am practicing with Drupal 8. I have created a custom module and have installed the contrib, devel.
Inside my module, I have defined a block.
namespace Drupal\twitter_pull\Plugin\Block;
use Drupal\block\BlockBase;

/**
 * Provides a block for executing PHP code.
 *
 * @Block(
 *   id = "twitter_pull_tweets_block",
 *   admin_label = @Translation("Twitter Tweets")
 * )
 */
class TweetsBlock extends BlockBase {

  /**
   * Builds and returns the renderable array for this block plugin.
   *
   * @return array
   *   A renderable array representing the content of the block.
   *
   * @see \Drupal\block\BlockViewBuilder
   */
  public function build() {
    dpm(array('this','is','a','test'));
    return 'this is a block';
  }
}

It works fine. Why do I have access to the devel functions? Where in my code do I include the namespace for devel that I should have access to dpm()?

Straight from the PHP Global space docs:

  Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

Devel's dpm() is declared in 'Global space', and since there's no other dpm() function declared in your namespace, the 'global' one is used (no need for the preceeding \).


Access $user object on comments I use the following snippet in template.php to access user profile fields on comment.tpl.php. $persianName works fine when the user is administrator, and returns nothing for the anonymous users. Actually, when I use dsm($variables) in anonymous viewing, I see that all UIDs are set to 0.

function apblog_preprocess_comment(&$variables) {
  $user = $variables['user'];
  $user = user_load($user->uid);
  $persianName = field_get_items('user', $user, 'field_user_pname');
  if ($persianName) {
    $variables['persianName'] = $persianName[0]['safe_value'];
  }
  else {
    $variables['persianName'] ='';
  }

  // …
}

In drupal by default anonymous users have UID=0 , and you just need if $user->uid==0 set your variable to what you want , some string like "mehman" ,

because of doing little changes in your code I use inverse checking  of uid value ( the are as the same ,

if ( $user->uid ==0 )  $variables['persianName'] ='mehman';

or

if ( $user->uid !=0 ) ...... else  $variables['persianName'] ='mehman';

)

function apblog_preprocess_comment(&$variables) {
  $user = $variables['user'];
  $user = user_load($user->uid);
  $persianName = field_get_items('user', $user, 'field_user_pname');
  if ($user->uid !=0) {
    $variables['persianName'] = $persianName[0]['safe_value'];
  }
  else {
    $variables['persianName'] ='';
  }

  // …
}

I hope this work to you

be win ;)


Disable AJAX in a form I need to disable AJAX proccessing for a multiple value field in forms.

Can somebody tell me how to disable it?

Ajax behavior is attached to form elements when there is a record in Drupal.settings.ajax for the HTML-id of the form element. Therefore in order to disable Ajax for a given form-element, you need to remove the appropriate ajax settings record. You can achieve that by implementing hook_js_alter:

function hook_js_alter(&$javascript) {
  foreach ($javascript['settings']['data'] as $index => $item) {
    foreach ($item as $key => $settings) {
      if ($key == 'ajax') {
        // The prefix id for a field_collection with the name fc:
        $field_id_prefix = 'edit-field-fc-und';

        // Remove ajax settings for the "Add another item" button
        unset($javascript['settings']['data'][$index][$key][$field_id_prefix . '-add-more']);

        // If you also need to de-ajaxify the "Delete" buttons:
        foreach (array_keys($settings) as $element_id) {
          if (preg_match('/' . $field_id_prefix . '-[0-9]+' . '-remove-button/', $element_id)) {
            unset($javascript['settings']['data'][$index][$key][$element_id]);
          }
        }
      }
    }
  }
}


How to drush rsync and sql-sync on windows with Acquia-Dev? Answer (just to share some hours of experience):

To get rsync and sql-sync to work on remote server using Windows (w/Aquia) it is necessary to make changes to 2 files filesystem.inc and SqlBase.php

First delete cygdrive/ from  $path = preg_replace('/cygdrive/(\w):/', '/${1}', str_replace('\\', '/', $path)); in line 61 of filesystem.inc

and change drush_shell_exec('gzip -d %s', $input_file)

instead of

drush_shell_exec('gunzip %s', $input_file) in line 144 of SqlBase.php

Happy Syncing!

0
down vote
favorite

Answer (just to share some hours of experience):

To get rsync and sql-sync to work on remote server using Windows (w/Aquia) it is necessary to make changes to 2 files filesystem.inc and SqlBase.php.

First delete cygdrive/ from $path = preg_replace('/cygdrive/(\w):/', '/${1}', str_replace('\', '/', $path)); in line 61 of filesystem.inc

and change drush_shell_exec('gzip -d %s', $input_file)

instead of

drush_shell_exec('gunzip %s', $input_file) in line 144 of SqlBase.php

Happy Syncing!


Problem changing language - Redirection to installation By browsing my website in Drupal, I can browse perfectly through all the sections.
The website has 3 languages.
For Spanish, I can navigate well.
For English, I can navigate well

But any page I try to access in Portuguese, redirects me to "core / install.php"

I have cleaned cache, I have reviewed everything, and it only happens to me when I change or try to navigate in Portugues.

Because it can be?
Drupal version: 8.3.7
Drush version: 9.0-dev-g105e0aa

Increase the size of max_allowed_packet = 16M in the my.cnf file of mysql


Italicizing content pane titles A few of our content pane titles need to be italicized because they contain book titles.

I've added an "italicize-title" class to the content pane in Panelizer > Content > Content Pane > CSS properties. This has some drawbacks. The main disadvantages are that the whole title is italicized and I have to manually add the class to each piece of content needing its title italicized.

I've tried the HTML Title module, but that didn't work.

Is there a way for me to allow content editors to use a limited number of html tags in a content pane's title field?

Thank you for looking...

This is untested but I would try implementing a template_preprocess_panels_pane():

function mytheme_preprocess_panels_pane(&$vars) {
  $content = &$vars['content'];

  $title = !empty($content->title) ? $content->title : '';
  $title = preg_replace("/\*\*(.*?)\*\*/", "$1", $title);
  $title = preg_replace("/\*(.*?)\*/", "$1", $title);

  $vars['title'] = $title;
}

Adapted from this answer, and would allow some simple markdown in the titles.


How do I get backslashes to save? Everytime that I type a backslash into a textbox on my drupal site (in content editors, administration pages, you name it; I mean any textbox), it gets filtered out before it reaches the module code.

So I end up typing something like this:

  This is just some content with an \n
  or a directory structure like
  C:\Program Files\whatever

And it gets converted to this on save:

  This is just some content with an n
  or a directory structure like
  C:Program Fileswhatever

This really makes it hard to edit content on my D6 site; anyone know a fix for this?

Related issues:

http://drupal.org/node/673748
http://drupal.org/node/564166

This is on admin pages; so filters aren't used.

This sounds like it may be a magic_quotes issue. If at all possible, disable this in your PHP configuration. Instructions on how to disable them are on the PHP website. If this is enabled on a live, shared server and you don't have access to the PHP configuration then I would highly recommend looking for a new host. The magic_quotes_gpc option has been deprecated in PHP 5.3, and will likely be removed very soon.

Magic quotes provide a way of escaping incoming input, and have been frowned on for quite a while in favor of validating input properly in your application, which Drupal does.


Delete nodes using Rules and VBO Rues and VBO are not working as expected to delete nodes. Can someone tell me what I'm missing? Thank you.

What I have:

A View with VBO field which successfully selects all nodes of a certain type based on how long ago they were created. (The Preview shows all the desired nodes.)
A Rules Action set which:

A. Load a list of entity objects from a VBO View. Obviously the chosen View is the View from step 1 above.

B. Loop through the list of entity objects.

C. Deletes each list item using "Delete entity".

A Rule which runs on cron and has for its only action the above Action Set (and no conditions).

However, it's not working. I run cron via drush and none of the nodes are deleted.

I have cleared all caches, recreated each part of the process from scratch (i.e. not cloning anything)... but it's still not working.

I have also created a Page display in the View (because the Rules Action set uses the Master display) and I can successfully manually delete the nodes with VBO - it's just not working when used in a Rule/Action Set.

However, the site is already deleting User entities with an identical Views/VBO/Rules/Cron setup.

Has anyone come across this or have any idea what might be wrong? Thanks.

Here is an "educated" guess:

Your site is configured so that anonymous users are NOT allowed (= do not have the permission) to delete nodes.
Cron (always) runs with user anonymous.

Up to you to confirm if bullet "1." applies, but rest assured that bullet "2." is true (in any Drupal 7 site). So if "1." indeed applies, the answer to your question (= "What am I missing") is that to get this to work you need to grant delete of nodes to anonymous users. I bet it is not going to be what you want to do (I wouldn't ...), but trust me, that is what you're missing.

And BTW, it must be that the userid you used to "successfully manually delete the nodes with VBO" does have the required permission.

To verify if my guess makes sense: (temporary) grant access to the VBO view to anonymous users, logout from your site, and repeat your manual attempt to delete the nodes with that VBO view again (as anonymous user). I bet it will fail with some sort of permission issue. Turn on Rules debugging (within Rules sessings) to get more details about that via the Rules logging messages shown near the top of your screen).


Setting #states property for a field_collection item added with the add_more button This is a D8 question as the solution in Using #states with field collection doesn't work for D8.

Here are the solutions I have tried, but none of them was working:

1- Adding an after build function for the field_collection element

$form['my_fc_field']['#after_build'][] = 'my_fc_field_after_build';

=>The function is not called when the "add_more" button is pressed

2- Adding an after build function for the field_collection item element

$form['my_fc_field']['widget'][0]['fc_item_field']['#after_build'][] = 'fc_item_field_after_build';

=>The function is not called when the "add_more" button is pressed

3- Altering my field_collection widget

function artprod_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition->getName() == 'my_fc_field') {
    $widgets_that_need_states = &$element['my_fc_field']['widget'];
    $childs = Element::children($widgets_that_need_states);
    foreach ($childs as $child) {
      $widgets_that_need_states[$child]['value']['#states'] = array(
        'visible' => array(
          "select[data-drupal-selector=\"xxxx\"]" => array(
            'value' => 'yyy'
          )
        )
      );
    }
  }

=>The function is not called when the "add_more" button is pressed

Conclusion: with all of those 3 methods I could set the #states property to the already constructed element, but not for the added elements.

I could solve it myself...

The solution is to alter the field_collection widget. In the point 3 of my question, I have made a mistake in the code. Here is a generic code to handle this behavior for changing the visibility of a text field according to the value of a select field:

function your_module_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  $fn = $context['items']->getFieldDefinition()
    ->getName();
  if ($fn == 'your_field_collection')  {
    // Get the delta
    $delta = $element['#delta'];
    $element['your_fc_text_field']['widget'][0]['value']['#states'] = array(
      'visible' => array(
        "select[data-drupal-selector=\"edit-your-field-collection-$delta-your-fc-text-field\"]" => array(
          'value' => "your_value_when_visible"
        )
      )
    );
  }
}

Note 1: I used "data-drupal-selector" because this was the only jquery selector which was working for the "select" (select seems more tricky then other fields)

Note 2: Adding ":" before "select" like ":select[data..." is breaking the feature. I don't know why!

Note 3: take care of the $delta in the data-drupal-selector

Note 4: Use "Inspect element" of your browser to get the correct value of your "data-drupal-selector"


Extra text field for Status order in Commerce I do have extra order status (Available for download) in Commerce. And when I choose this status I want to add a link to download a file. How can I add extra field for the order?

Probably, I even need two fields: "link" for the link and "text" for the description of link.

Consider using the Conditional Fields module. Excerpt from its project page:

Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.


Redirecting the home page to index.php, not index.html I have an index.html file in the server root directory.

When users browse the domain, the index.html page should come first. In that index.html, I have created a link like enter website that links to index.php present in the server root directory to enter the Drupal site. When I click on the Home menu link, it automatically redirects to index.html; I need it to redirect to index.php.

Why use separate index files when you can use a splash screen:

  We define a splash page as being content that shows up at a specified interval, at a specified location, one time. If someone goes to a certain page for the first time, we want to make sure the splash content shows up. But if the person is coming from an internal link on the site, we don't want the splash content to show up over and over again (otherwise, the splash page would become a nuisance).

These modules implement the flash features in a Drupal site:

For D6 : https://drupal.org/project/splash
For D7 : https://drupal.org/project/splashify


Views taxonomy listing of terms linked via contextual path What this really boils down to is a contextual block view of terms with relative paths to a second taxonomy vocabulary, I'm just not sure on how to get there.

Here is what I'm trying to do:

I've created a basic block that contains links to taxonomy pages, but I need the links to which they point to be contextual based on the path that's in the current URL.

I have a content type that uses two different vocabularies on each node. One is a location type vocabulary of terms something like this:

Florida
USA
North America

Then I also have another vocabulary that contains a number of different award types something like this:

Award X
Award Y
Award Z

The same set of awards can be listed in each of the location type pages above as well.

By request we've created the Views to display the locations as pages, then the awards listed under each location.

So when we have visitor on the "Florida" page for example, we want to present a list of taxonomy links that point to awards by type, with the location included in the link contextually/dynamically. We don't want USA links showing on Florida pages, nor "Florida" links showing on "North America" pages.

Our path currently looks something like this from the Views Page displays:

domain.com/VIEW-PATH/term-name

domain.com/florida/award-x
domain.com/usa/award-x
domain.com/north-america/award-x
etc.

our taxonomy View pages look like this:

domain.com/term-name

domain.com/award-x
domain.com/award-y
domain.com/award-z

I need to find a way to contextually set the link in the taxonomy list block include that location vocabulary term, dynamically.

They NEED to look like the first set only with the location added dynamically:

domain.com/[florida]/award-x
domain.com/[usa]/award-x
domain.com/[north-america]/award-x

The problem is that we don't have the location term in the path. Any ideas on how to make this happen? Hope this makes sense.

Thanks in advance.

edited for clarification:

The end result I'm trying to achieve for the taxonomy link created by the View would look something like this:

domain.com/florida/award-x/node where florida

(the location) is added dynamically depending on the location taxonomy page that the visitor is on. I've not seen a way to set the location taxonomy term variable in to the path in admin/config/search/path/patterns which is where I've been looking the most for a solution. It seems I should be able to do it here, but I've not been able to figure it out due to the location being a different vocabulary that the award name.

You dont have to pass all these parameters via the URL. If you know the location or award from within your master view simply embed another View into the view passing it hidden or visible Fields in from the parent view. You want to use views_field_view to do this:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

  It's highly recommended to use this module in conjunction with views
  caching. Views Content cache and Cache Actions are good ways of
  caching views.


Present users with form to create new node I have created a content type called "member" in my project. Logged in Users have permissions to create nodes of type "member".

I want to my users to be able to create the nodes without having to click "create member"

I simply want to present them with the form when they log in and all they have to do is 1. Enter the values and 2. Click save.

Thank you.

You could redirect the user upon login to the create form. A good module for this (and a lot of other stuff) is: logintoboggan


Problem with calling drupal_get_form from an AJAX callback So, I have a paged, AJAX-enabled list view of entities. As a part of the entity build process for rendering, an AJAX comment form is built, rendered and attached to it.

Now, when I move to the second page in the view (retrieved via AJAX), the comment form shows up but the AJAX property is not attached to it anymore. I used Drupal 7's #ajax on the submit button. Also, the form action is now set to views/ajax when I want it to be the same as the original page. Any way to get around these two issues?

Ensure that Drupal.attachBehaviors() is called from your AJAX callback. See Drupal 7 JavaScript API for more details.


Determine whether a field has changed during hook_node_submit Basically I need a way of checking whether a node field changed during some event hook...I am using hook_node_submit() but this doesn't seem to work:

$form['field_status']['und']['#value'] !== $node->field_status['und'][0]['value']

Produces equality all the time...any suggestions on which hook and how I would check equality when I know a value has changed it should fire off an email...

Alex

As said from @Clive, the only way is to compare the value in $node with the value contained in $node->original. As far as I can see, that value is only available in hook_node_edit(), hook_node_update(), and hook_node_presave() since entity_load_unchanged() is called from node_save() (which also unset $node->original before exiting). If you need it in hook_node_submit() you could simply add the following code in your implementation.

if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}

Since you are checking for field properties, the other, more general, hook would be hook_field_attach_submit().