How to decide between module_exists and function_exists? I'm familiar with using module_exists in a module, and using it in situations like:

Enable some extra functionality in a module, provided some other module is available in the site also. The Reservations: Email module contains an example (actually there are plenty of examples of this), as shown in its module source: to use tokens (in the eMail body) requires that the Token module is enabled.
Implement module dependencies in a theme, as shown in the answer to "How to implement module dependencies in a theme and package modules with a theme?".

However, there is also function_exists, such as shown in the answer to "Is it possible to declare a Javascript library dependency at Hook.info?".

I have the impression that using function_exists is a more robust (safe) approach as compared to module_exists. Especially if you want to be sure that some function (added in a newer version of a module) is available, whereas by just using module_exists, you risk to run into errors like those:

if a site is still using an old version of a module, which doesn't have that function yet (so you shouldn't try to use it  yet).
if a site is already using an new version of a module, which doesn't have that function anymore (so you shouldn't try to use it  anymore).

My question: what are the typical criteria, or pros/cons, to decide for using either  module_exists versus function_exists?

You should always program to the API and not the implementation.  If Drupal provides a mechanism to do something, use it.

module_exists() should almost always be used for soft dependencies on something provided by a Drupal module.  You can always get version info, and decide what to do, using system_get_info().  There have been cases where functions are available when modules have been disabled (some of the class autoloader modules have has this problem).

function_exists() should be reserved for checking whether a PHP feature or library is available.  Core has some examples of this in some of the drupal_ wrappers for string manipulation and character set conversion.


/tmp folder still not writeable PDOException: SQLSTATE[HY000]: General error: 1 Can't create/write to file '/tmp/#sql_e0f_0.MYI' (Errcode: 13): SELECT DISTINCT SUBSTRING_INDEX(source, '/', 1) AS path FROM {url_alias}; Array ( ) in drupal_path_alias_whitelist_rebuild() (line 380 of /var/www/html/includes/path.inc).

After noting report status for updating .htaccess in this tmp folder i found in root directory I then changed permissions to 755 and ownership apache:apache
also tried owner:apache Anyway, when tested and trying to delete content as admin it throws above error.

UPDATE: All of this occurred due to erroneous status report for drupal 7.24 saying needing to add security update to files and tmp folder .htaccess but it is a bogus bug and you need to delete them then run cron will recreate and status report disappears.

SEE http://www.ostraining.com/blog/drupal/drupal-724-tmp-directory/

problem solved

You need to find the user your server is running with (or the owner of files and folders). If your drupal is working correct besides this error then go to your website root and type ls -l in terminal. It will show you something like this:

-rw-rw-rw-  1 www-data charlie 6604 aug  8 04:04 authorize.php
drwxrwxrwx  3 www-data charlie 4096 nov 12 13:02 cgi-bin
etc.

Here you see the owner (www-data) and the group (charlie). This can be different on your system, but remember which you have for the chown-command below.

Give your /tmp folder the same owner. Go to /admin/config/media/file-system on your site and see the path to your tmp folder. If it starts with a '/' then it's located in the root of your system. If it doesn't start with a '/' then its relative to your website-folder, tmp for example is then really /var/www/httpdocs/tmp.

Then use chown -R www-data:charlie /path/to/tmp and you should be good to go. When you use your systems tempfolder at /tmp you really should create and set a subfolder inside /tmp.


How to realize ajax on a form element with autocomplete I have a form textfield element, which contains autocomplete feature using #autocomplete_route_name.

Could you clarify me, how to call ajax function when the textfield value has been set via autocomplete ? That is, for example, an user has selected a value from the autocomplete list, set it into the textbox and right away something should be executed via ajax depending on new value of the textbox.

Which ajax event should I use for it ?

I managed to find the solution.
My code works with an event "autocompleteselect".

Here's an example of code

$form['autocomplete_field'] = [
            '#type' => 'textfield',
            '#title' => t('Autocomplete search'),
            '#autocomplete_route_name' => 'autocomplete_route',
            '#ajax' => [
                'callback' => '::ajaxFunctionAfterAutocomplete',
                'event' => 'autocompleteselect',
            ]
        ];


How to set different logout times for roles? I would like to define/set a log out time for different roles for my Drupal site.

Say for example if I set log out time for X role for 30 Minutes. The users under that role would be logged out in 30 Minutes from the time they logged in and also I would like to show notification to users for their remaining time for timeout.

How can I achieve that in Drupal?

We can achieve that using the Automated Logout module. combination of the Javascript Timer module.
Using the Automated Logout module we can set different timeouts for user roles and using Javascript Timer we can display remaining session time (countdown timer) for a logged in user.
Automated Logout

This module provides a site administrator the ability to log users out after a specified time of inactivity.
It is highly customizable and includes "site policies" by role to enforce logout.
Features

Different timeouts based on role
Disabling of timeouts based on role
Permission for users to set their own timeout
Includes some JS mechanisms to keep uses logged in even if multiple    tabs are open or if the user is working on a form for a long period
of time.
Includes developer hooks to allow users to remain logged in depending    on your own project specific requirements
Optional integration with Javascript Timer Timer


How to push values from views attachment to Javascript? I have a table view with both filters and exposed filters, and attached to it there is another view that uses views_aggregator_plus to display a summary of months and different value counts.

I want to have the attachment visualized so I attached ChartJs script to the page view and had another function loop through the attachment html table rows to fetch the data while separating each column into its own array.

This works though I am not sure. It doesn't feel right.
Wouldn't it be better if I pushed the values from the view directly to the script rather than have it done by the browser?

I am not sure about how to do it, but I found the values needed in hook_view_post_render under $view->style_plugin->rendered_fields..

How to proceed from there? Or maybe there is an entirely different and better way to achieve the same?

Thanks,

It really depends on what you want and what data structure you have.
Normally I would say if you want only chart on the page/views, than create a new views type (Like block, page, etc) and then you can do whatever you want, and you can still attach it to another views. (I think this is it: https://www.drupal.org/docs/8/creating-custom-modules/building-a-views-display-style-plugin-for-drupal-8)
If you just want to show a chart side-by-side with some other data, maybe you need to create a new field (for views), than you can put there the stuff. (https://www.webomelette.com/creating-custom-views-field-drupal-8)
You can also hook in any time to a view, but it will make a mess after a while, however, every time you need to use the drupalSettings (Pass variable to drupalSettings) if you want to pass php data to javascript and some custom JS code to glue the ChartJS to the drupalSettings.


I am unable to login using linkedin integration module drupal 7? I have installed Drupal linkedin Integration 7.x-1.x-dev and Oauth module .

I have entered the details like api key and secret key and all other settings properly

Now when I login using linkedin using the option as shown in the image
I am redirected to the page as shown in the image

but after I  enter linkedin credentials I am redirected to following page with no drupal user created

what is the reason for that?

The LinkedIn Integration module won't automatically create a new user account for you. From step 5 of the directions in the module's README:

  Usage : Users will have to associate their LinkedIn account with their
  local Drupal account (at user/%user/edit/linkedin) to use any
  functionality provided by submodules.

So if you log in via LinkedIn with a LinkedIn account that isn't yet associated with a Drupal user account, you still need to create the new Drupal user account, and then the module will automatically associate the LinkedIn account with the new Drupal account in a submit handler that it attaches to the user register form.


How to create a directory during a module install? I need to create a directory in public:// when the module is installed via file_prepare_directory(). I used this code in function mymodule_install():

$mydir = 'public://mydir';
file_prepare_directory($mydir, FILE_CREATE_DIRECTORY);`

Upon uninstalling, clear the cache, and installing the module it does not create mydir.

Are you sure the directory where you are creating directory is writable?

file_prepare_directory checks that the directory exists and is writable.
You can try drupal_mkdir statement to create directory in hook_install


Defining a sitemap variant I'm trying to add a new sitemap variant using Simple XML Sitemap referenced here.

For the most part I understand it but I'm not sure where to actually place my definition and use the simple_sitemap.generator service to add it.

If I place it inside of an alter hook it never gets recognized by the site. I'm not sure how/where to add this new variant.

Thank you for your help.

I would have caught this question if you posted a support request ticket it in the module's issue queue.

The information in the post you are referring to is outdated. When using the newest version of the 3.x branch, you can define variants easily in the UI accessible under admin/config/search/simplesitemap/variants.

A variant is a sitemap instance of a particular sitemap type. When creating a variant, you can reference existing sitemap types or write your own by adding a sitemap type plugin which references URL and sitemap generator plugins.

Simple XML sitemap is heavily relying on the plugin architecture as opposed to hook architecture. Hence most of the time you would use the module's API service methods or write plugins inside of a custom module. There is still a couple of alter hooks remaining for convenience.

The 3.x branch has a release candidate which is very stable. You can read all about it in this blog post.


Can't get Varnish working properly, not caching anything. (varnishd is running , status is tick) System info:

Ubuntu / LAMP
Drupal 7.14
Varnish 3.0.2
Varnish module: 7.x-1.0-beta1
http port 80

I have installed Varnish in server.

I started it as:

$ sudo varnishd -f default.vcl -s malloc,1G -T 127.0.0.1:2000

varnishd started and running.

default.vcl details (from this page: https://www.varnish-cache.org/trac/wiki/VarnishAndDrupal)

backend default {
    .host = "127.0.0.1";
    .port = "80";
}

sub vcl_recv {
  // Remove has_js and Google Analytics __* cookies.
  set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+$
  // Remove a ";" prefix, if present.
  set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
  // Remove empty cookies.
  if (req.http.Cookie ~ "^\s*$") {
    unset req.http.Cookie;
  }

  // Cache all requests by default, overriding the
  // standard Varnish behavior.
  // if (req.request == "GET" || req.request == "HEAD") {
  //   return (lookup);
  // }
}

sub vcl_hash {
  if (req.http.Cookie) {
    hash_data(req.http.Cookie);
    return (hash);
  }
}

Vanish module enabled.

Following conf added to settings.php

$conf['cache_backends'][] = 'sites/all/modules/varnish/varnish.cache.inc';
$conf['cache_class_cache_page'] = 'VarnishCache';
$conf['page_cache_invoke_hooks'] = FALSE;

Varnish module configuration page screenshot:

Performance page screenshot:

Then I browse my site. (as anonymous), repeatedly refresh various pages. Checked stats of varnish

$ varnishtop

apparently it is not receiving any request, not caching anything.

Also check the site on http://www.isvarnishworking.com/  , shows Vanish is not working on the site.

What is wrong?

Thanks for any help.

By default, Varnish is not working on port 80 (and in this case it could not be either since your Apache is occupying that port). You should configure your Apache to listen to another port, then use that port for your backend setup in Varnish. You should also configure Varnish to listen to port 80.

To debug, you should try to figure out what port your Varnish is listening to now and browse using that port, then you should see traffic in varnishtop.

The reason I'm being vague on the varnish configuration is that I have only used Varnish on CentOS which reads in the startup defaults from /etc/sysconfig/varnish - since you are using Ubuntu you should try to find out where that default configuration is being kept on your system. A fair starting point might be the /etc/init.d/varnishd script which might give some clues.


Upload directory for a field instance I've been searching a lot for this, but no luck.
I've created a custom file field along with an instance for my custom content type in the .install file.

I've set up everything except that I want that by default this instance of the file file that I created to upload to the 'private' directory and if it's not defined, to define it with this module.

  $file_download_link_instance = array(
  'field_name' => 'file_download_link',
  'required' => true,
  'entity_type' => 'node',
  'bundle' => $machine_name,
  'label' => t('Files to upload'),
  'settings' => array(
    'file_extensions' => 'txt doc docx pdf ods odt xls xls png jpg jpeg',
    'description_field' => TRUE,
    ),
  'description' => t('Please upload here the files.'),
  'display' => array(
    'default' => array(
      'type' => 'hidden',
      ),
    'teaser' => array(
      'type' => 'hidden',
      ),
  ),
  'locked' => TRUE,
);

I believe that I have to edit the 'settings' array, but I don't know the syntax.
Thanks!

You just wanted to add attribute file_directory inside the settings array

  'settings' => array(
    'file_directory' => 'myModule/images',
    ),

Here is other attributes that might be added:

  'settings' => array(
    'file_extensions' => 'png jpg jpeg',
    'file_directory' => '',
    'max_filesize' => '20 MB',
    'alt_field' => 1,
    'title_field' => 1,
    'max_resolution' => '300x200',
    'min_resolution' => '200x125',
    'default_image' => 0,
  ),


How to hide specific fields and the according label in a view, based on field permissions? I have a view called Profile that displays some of the user fields. Amongst these is a Name field (field_name). I'd like to hide this field except for the administrator and the user himself/herself. I installed the Field Permissions module, wich nicely gives me the opportunity to mark the field as private. When this is checked, the Name's value disappears in my Profile view, but the according label is still there - and that's not very nice.

How can I hide the label aswell?

On the Name field's edit config popup, remove the text from the Label field and disable the label checkbox; expand the Rewriting section, and paste in the label followed by the name field's  substitution pattern.... it will look something like this Name: [field_name].  Finally,  ensure the option to disable rewriting when field is empty checkbox is checked.


Drupal Less cache keeps generating cache file that does allow access to the apache server How do I ensure that auto-generated css cache files (related to the Less module) are being generated with the permissions necessary for the server to access.

Currently, whenever I clear all caches (with drush cc all), I lose all of my site's css styles and get the following error:

  LESS could not create a directory in sites/default/files/less/52741f7e343834.56376384/sites/all/themes/my_custom_theme/css

When I go to look at the permissions (ls -l) for the files in sites/default/files/less, the directory 52741f7e343834.56376384 (which I assume is the new cache file the server is trying to create the other stuff in) it has the wrong ownership <correct-user>:<correct-user>, rather than <correct-user>:apache (it's centos, so that's the apache server group). All the other cache directories have the correct owner permissions.

So how do I ensure that the system is creating these cache files properly such that I don't have to set the file ownership every time I clear the cache to get my styles back?

This is a new problem for my site and I suspect it is because I updated the Less module for Drupal 6 and added the lessphp library to my site (though perhaps I am mistaken).

I do three things.

I put myself in the apache group.
Set my umask and the httpd process to 0022
chmod sites/default/files to 2775

The first step lets me write to the directory. The second step makes sure that files I create have group write permission, and that apache does the same.  The third step tells the OS to always use the group of the directory owner.

You should then be able to drush cc all and have Apache create the LESS files.

For your initial fix, you may have to fix up the perms recursively. Eg,

chown -R apache.apache docroot/sites/default/files/
find docroot/sites/default/files/ -type d -exec chmod 2775 {} \;
find docroot/sites/default/files/ -type f -exec chmod 664 {} \;

I would also suggest reading Securing file permissions and ownership.  The comments have a good duscussion about the setgid bit and potential downfalls.


Cannot print $variables using template_preprocess_views_view_rss() in readable format How can I print out $variables from template_preprocess_views_view_rss() in a readable format?  The RSS view page uses a non-rendering format and is impossible to read. I need to manipulate the feed because no D8 RSS module is stable at this point.

My solution was to use kint() and print_r() with array_keys() to locate all the objects for manipulation.  In some cases I was debugging with the kint() display and in others just looking at plain text by using the other mentioned functions.

For note the template_views_view_rss() and template_views_view_row_rss() hooks are located in view.theme.inc (core) and no where in documentation on drupal.org for D8.  I believe they are soon to be deprecated.

// Specific feed filter
if( $variables['view']->id() == 'blog' && $variables['view']->current_display == 'feed_1') {
  // Iterate rows
  foreach($variables['rows'] as $key_1 => $row) {
    // Do stuff
    foreach($row['#row']->elements as $key_2 =>  $element) {
      // Do stuff
    }
  }
}


Error message in checkout step I'm getting the following error on the return page of my off-site payment:

#1 ... /httpdocs/core/modules/editor/editor.module(554): _drupal_error_handler(4096, 'Argument 1 pass...', '... /httpdocs/ ...', 554, Array)
#2 ... /httpdocs/core/modules/editor/editor.module(384): _editor_get_file_uuids_by_field(NULL)
#3 [internal function]: editor_entity_update(Object(Drupal\commerce_order\Entity\Order))
#4 ... /httpdocs/core/lib/Drupal/Core/Extension/ModuleHandler.php(402): call_user_func_array('editor_entity_u...', Array)
#5 ... /httpdocs/core/lib/Drupal/Core/Entity/EntityStorageBase.php(169): Drupal\Core\Extension\ModuleHandler->invokeAll('entity_update', Array)
#6 ... /httpdocs/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(730): Drupal\Core\Entity\EntityStorageBase->invokeHook('update', Object(Drupal\commerce_order\Entity\Order))
#7 ... /httpdocs/modules/contrib/commerce/src/CommerceContentEntityStorage.php(88): Drupal\Core\Entity\ContentEntityStorageBase->invokeHook('update', Object(Drupal\commerce_order\Entity\Order))
#8 ... /httpdocs/core/lib/Drupal/Core/Entity/EntityStorageBase.php(470): Drupal\commerce\CommerceContentEntityStorage->invokeHook('update', Object(Drupal\commerce_order\Entity\Order))
#9 ... /httpdocs/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(615): Drupal\Core\Entity\EntityStorageBase->doPostSave(Object(Drupal\commerce_order\Entity\Order), true)
#10 ... /httpdocs/core/lib/Drupal/Core/Entity/EntityStorageBase.php(395): Drupal\Core\Entity\ContentEntityStorageBase->doPostSave(Object(Drupal\commerce_order\Entity\Order), true)
#11 ... /httpdocs/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php(820): Drupal\Core\Entity\EntityStorageBase->save(Object(Drupal\commerce_order\Entity\Order))
#12 ... /httpdocs/core/lib/Drupal/Core/Entity/Entity.php(391): Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(Object(Drupal\commerce_order\Entity\Order))
#13 ... /httpdocs/modules/contrib/commerce/modules/checkout/src/Plugin/Commerce\CheckoutFlow\CheckoutFlowBase.php(130): Drupal\Core\Entity\Entity->save()
#14 ... /httpdocs/modules/contrib/commerce/modules/payment/src/Controller/PaymentCheckoutController.php(88): Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowBase->redirectToStep('complete')
#15 [internal function]: Drupal\commerce_payment\Controller\PaymentCheckoutController->returnPage(Object(Drupal\commerce_order\Entity\Order), Object(Symfony\Component\HttpFoundation\Request))

(any stack beyond this is, afaik, Drupal boiler plate)

Digging into editor.module, obviously the original property of my order entity is NULL, and that causes the error.

Does this indicate that my order has not been updated, and does not need saving? As in, I should just patch the CheckoutFlowBase class to check if the original property is set, and if so, save?

Or is the fix going to have to be more complicated?

That error most commonly occurs if an order is being double-saved, by calling $order->save() within a hook_entity_presave() or a matching event, including pre/post transition events.

If you need to modify the order during a state transition, do it in a pre-transition event and let the system take care of the rest.


Splash page for mobile website I am working on a mobile website and I need to have a splash page for 3 sec displayed when the client access the website for the first time. Is there any plugin I can use or what solution can I use.

Thanks

Put a meta refresh tag in the header of your mobile splash page template:

<meta http-equiv="refresh" content="3;url=http://WHEREYOUREALLYWANTTOGO">

This will display the splash page for 3 seconds before moving on to the page you want them to see next.


Expose the required fields in listing view I have created a content type say "Form" which have one of a field named as "gender" set as a radio buttons.
This radio button I want to expose or make it visible with its functionality when I am displaying it in a View which can be called as "Form display" on a listing page.
I hope my question was clear,if not then please ask me in comments.

Use hook_form_alter() on the views_exposed_form. You can then change the type from select to radios or checkboxes.


How to expand the fieldsets in node-add form? When I am adding new node by admin/content/node-type/story, there are a lot of settings ordered by groups:  Submission form settings, workflow setting, comment settings. But all these fieldsets are all by default collapsed.

My question is: how to make them all default to expanded?

I believe you have one of two options...

In Code: Have a look at hook_form_alter() and modify the applicable field groups to be $form['the_form_fieldset']['#collapsed'] = FALSE;
In UI: Modify the CCK types form. Go to your content types, click manage fields on the one you want and then select the 'Manage Form' tab.

Hope that helps!


Inserting Fields from A Custom Content Type into Custom Form I created a custom content type called 'Building Location' that contains a custom field called 'US_States'.

Is there a way I can access and include the 'US_States' field into a custom form I'm building without having to re-create it with the Form API?

I'm looking to include the same drop down list, 'US_States,' from the 'Building Location' content type in a custom form that is part of a module I'm building, ensuring the two will always have the same options available.

There isn't an API for attaching a single field from an entity to a form, there is one to attach all fields. field_attach_form. I wouldn't suggest you doing that do, since it can quickly become unmaintainable.

Instead I would suggest that you simply get the field options, or allowed values as they are called. That is pretty simple as well.

$info = field_info_field('field_machine_name');
$options = $info['settings']['allowed_values'];


View of taxonomies connected to view of each taxonomy I'm creating a store using Drupal commerce and I'm trying to show a catalog of products.

First I create taxonomy of product types
Then I use taxonomy to create a view of product types(product type
view) and I'm showing taxonomies image
Then I add a taxonomy reference field to product contents

I want to show all products of a type every time I click on a taxonomy in product type catalog view.

Can anyone help me?

With this solution yo can get the result with some struggle, but I have a better solution for you.
Create a list that show all product in categories. (If you do not need this,  skip this step.)

Create a view of product type
Add a relation to category (taxonomy you used in product display)
Add a taxonomy field (also images)
Group the result by category

Create a view with  path something like product/* and pass the category ID to it.

then add contextual filter on your category field,and get default value from the URL.

for getting better involve with views contextual filter read this article.
if you need more details tell me to provide it.


Alter a form's values on submission but before validate? I'm trying to set up the user registration form to populate the username field with the email address field. Is there a way to do this without using hook_validate and having to manually do the form validation?

hook_form_alter() (or hook_form_FORM_ID_alter()) can be used to populate any field before rendering.


Webform: send uploaded files as attachments I have a webform where a user can upload a file; I want this file to be attached to the email sent to the site manager.

What is the best practice doing so? I tried finding a helper module, but I didn't find one.

Or you can use Mail System and Mime Mail modules. A "Include files as attachments" checkbox will appear in Webform E-Mails configuration.


Forum should just show up in groups I would like to have, on my Drupal 8 site, a forum that can be visited only by the members of the group XY; all the other users should not see the forum.

In the permissions I can't find one for viewing the content of the forum.
How can I do that?

I solved the problem with the module Forum Access.

  This module changes your forum administration page to allow you to set
  forums private. You can control what user roles can view, edit,
  delete, and post to each forum. You can also give each forum a list of
  users who have administrative access on that forum (AKA moderators).


How to programatically get the machine name of a node? I want to add the machine name of every node into my page.tpl.php template as a class on the body.  How can I get that machine name?

I have access to the node object, but I don't see the machine name in there.  Is there an api call I can use?

Individual nodes don't have machine names in Drupal 6 or 7, so you can't.

If you want a unique ID for each node, and Node ID won't do (for staging or migration for example), then try taking a look at the UUID module.

  This module provides an API for adding universally unique identifiers
  (UUID) to Drupal objects, most notably entities.

Also of note...

  Features in Drupal 6 version

  Automatic UUID generation for nodes, node revisions, users and taxonomy.
  Allow choosing which content types and vocabularies to create UUIDs for.
  Option to batch create UUIDs for objects which don't have it already.

If, however, you want the node TYPE to be available to your template, and you have the node object, it should be under $node->type, or possibly $vars['type'].


Twig invalid render array keys from a valid array In hook_preprocess_menu I am creating an array to send to the menu twig tpl (eventually it will be entity paragraph data but for now they are hard values as examples). However, I just receive array key invalid errors. How should this be formatted correctly for the template?

function hook_preprocess_menu__main_menu(&$vars) {

  $node = \Drupal::routeMatch()->getParameter('node');
  if($node->field_menu_highlights){
    $highlight_values = $node->get('field_menu_highlights')->getValue();

    foreach ($highlight_values as $key => $item){
      $ent = \Drupal\paragraphs\Entity\Paragraph::load($item['target_id']);
      $vars['highlight'][$key]['title'] = 'Title here';
      $vars['highlight'][$key]['desc'] = 'Description here';

    }
  }
}

The template:

{% for value in highlight %}
    {{ value }}
{% endfor %}

Error eg:

User error: "title" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

Build the array with renderable children:

  $vars['highlight'][$key] = [
    'title' => [
      '#markup' => 'Title here',
    ],
    'desc' => [
      '#markup' => 'Description here',
    ],
  ];

Now the loop to render each value separately should work or have the same result by rendering the complete render array:

{{ highlight }}


Sub Menu items not showing I am trying to create a navigation with a sub-menu in Drupal 9. I added the top level nav item with and used # as the value for the link, and checked "Show as expanded"
Then I created a new item and chose the Top Level Item as the parent nav.
Top Level Item
Sub Item
On my menu now the Top Level Item has an arrow, but the sub item is not there. And in dev tools under inspector I do not see the code for the sub item.
Is there a step I missed?

Found a solution here - https://www.drupal.org/forum/support/module-development-and-code-questions/2019-08-03/menu-item-children-not-rendered-in
I needed to change "Number of levels to display" under the Navigation block to Unlimited


How to get custom field labels translated I want to get the labels and descriptions of custom fields translated in Dutch, but no matter what I try they always remain in English (the language I use for creating them). I hope my steps below makes sense because I don't understand why it isn't working.

What I do is I create a field (with the site language set to English) in either a profile (using the Profile 2 module) or directly in the account.

Then I edit the field and use the translate button (provided by Field translation in i18n) to add a Dutch translation. But if I then switch the site language to Dutch, the field label and description are still in English.

If I edit the field again (with the site language still set to Dutch), the translate tab now shows the Dutch translation with status original and English as "niet vertaald" or not translated. If I edit the Dutch translation, I'm presented with the English version.

I can change that again to the Dutch text and it will show correctly (in Dutch). Nice, but when I switch the site back to English the field remains Dutch! When I edit the field, the translate tab shows the Dutch text in the English language, but the status for English is back to original.

I cannot make heads or tails of this. Am I completely missing something or is this perhaps a bug? I'm using Drupal 7.

Last days, I got the same issue to translate labels and descriptions of custom. here is what i did to solve it.

Enable i18n's i18_field "Field translation" submodule
Go to admin/config/regional/translate/i18n_string
Checked 'fields' (properly check all) and Click on "Refresh strings".
Go to admin/config/regional/translate/translate
Search desired string and translated it to other lang.


Drupal 7: Article with Multiple Image Thumbnails Embedded in it I'm using Drupal 7. Whats the best way to create an article with multiple images embedded at various places in the article.

The way I wish to do is that insert image thumbnails and then click it to open the full version in the lightbox or something. How do I achieve this.

Thanks,

With Colorbox and Insert, it should be a breeze.


Embed form within a form I am building on an existing site, adding / modifying functionality to it.

There is a form, which is a part of a (sort of a) multi-step form which I need to alter, and add another form to it.

So, I added the following to the existing form:

// Some form elements above this.
$form['new_form_element']['search'] = drupal_get_form('MY_PROJECT_search_form');
// Some form elements after this

And the MY_PROJECT_search_form function returns the form, which is then embedded in the original form. The form is rendered properly.

However, when I submit the form, I get the following notice :

  The form has become outdated. Copy any unsaved work in the form below and then reload this page.

I believe that is because the two forms are getting submitted at the same time, and the submission of one of them is failing.
I have tried adding $form_state['rebuild'] = TRUE to the submit functions, but it did not work.
I have also tried adding an markup type field and embedding form in as
'#markup' = render(drupal_get_form('MY_PROJECT_search_form'));
But, I am not able to implement AJAX in the embedded form after that.

Is there any other better way to embed a form?

Note: There is no other option then to embed a separate form to the current form.

Nesting forms in other forms is not valid in html.
see this post
html nesting forms in forms

You can always try calling the form directly via the actual form function instead of via drupal_get_form since the function returns a valid array of form elements.
you'll have to somehow compensate for the missing hook_form_alter and hook_form_FORM_ID_alter.

Note I haven't actually tried this, so I'm not sure how it will react on the empty $form/$form_state params.

That already gets you all the fields in a dynamic way.
Perhaps you can build a similar work around calling the submit/validate handlers directly too.


Persistent session cookies: remember session even after closing the browser I would like to store anonymous users $_SESSION in a cookie so that their cart and other custom information is still available even after closing the browser.

I found this interesting post which tells me I should add this to my local.settings.php:

ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);
ini_set('session.gc_maxlifetime', 60 * 60 * 24 * 7);
ini_set('session.save_path', '/home/yoursite/sessions');

So that session cookie would be available for a week.
But it also stands that we should use session_regenerate_id() elseway the cookie lifetime is not updated.

I could not find session_regenerate_idin Drupal 7 source code, but I believe Drupal might already handle this from what I read in the code comments.

My questions are:

is this a good approach to have persistent cookie sessions?
do I need to add to my local.settings.php session_regenerate_id() too?

Thank you very much for your advises

Hi you could use javascript for this.

Using these 3 functions.
its properly the best way and then you wont have problems if your are using Varnish

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}


Can I merge two views into a third one I'm new to views and was wondering how I can accomplish this:

I have two views one that takes receivable invoices and displays them and then totals them at the end of the table using View Aggregate Plus. Another view that grabs invoices that are payable and once again totals these together.

What I'm looking for is a way to take the total of these two views and then display it in a third view called balance which will take the total of receivable invoices and subtract the total of payable invoices.

Is there a way to do this?

Here is the way to render multiple views on a single template file.

you need to make use of views_embed_view
Using this function, you can embed Views and even dynamically pass them filter arguments. - See more at: http://www.webomelette.com/drupal-embed-view-template-tpl

you can use this function multiple time to get your both views rendered and then do your operations on variables available from them [you need to figure out this at-least], here is the help


Webform custom submit handler rebuild I am acutally trying to build a custom webform submit handler to force the form to be rebuilded. I know that this is possible with the integrated webform settings, but I need to do it programmatically.

Here is what my code looks like at the moment:

function he_helper_form_alter(&$form, &$form_state, $form_id) {
    dsm($form);
    dsm($form_state);
    dsm($form_id);

    if(strpos(current_path(), 'print') !== false && $form['#node']->type == 'genericforms') {
        $form['actions']['submit'] = array (
            '#type' => 'submit',
            '#value' => 'submit',
            '#submit' => 'he_helper_custom_redirect'
        );
    }
}

function he_helper_custom_redirect($form, &$form_state) {

    $form_state['rebuild'] = TRUE;

}

The problem now is, that the rebuild works as expected, but the form data does not get submitted. I tried it with $form_state['redirect'] as well, but ran into the same problem.

Anyone got an idea how to solve that?

UPDATE:

function he_helper_form_alter(&$form, &$form_state, $form_id) {
  // dsm($form);
  // dsm($form_state);
  // dsm($form_id);
  if(strpos(current_path(), 'print') !== false && $form['#node']->type == 'genericforms') {
    // $form['#after_build'][] = 'he_helper_after_build';
    $form['actions']['submit'] = array (
      '#type' => 'submit',
      '#value' => '2hello',
      '#submit' => array('_he_helper_custom_submit'),
    );
  }
}

function _he_helper_custom_submit(&$form, &$form_state) {
  $form_state['redirect'] = 'print';
  $form_state['rebuild'] = TRUE;
}

This is what my code now actualy looks like. The redirect now works fine, but the data wont get submitted. I tried the after_build function as well, but when i am using this, even my redirect wont work. This is what my code looked like with the after_build

function he_helper_form_alter(&$form, &$form_state, $form_id) {
  // dsm($form);
  // dsm($form_state);
  // dsm($form_id);
  if(strpos(current_path(), 'print') !== false && $form['#node']->type == 'genericforms') {
    $form['#after_build'][] = 'he_helper_after_build';
  }
}

function he_helper_after_build(&$form, &$form_state) {
  $form['actions']['submit'] = array (
    '#type' => 'submit',
    '#value' => '2hello',
    '#submit' => array('_he_helper_custom_submit'),
  );
  return $form;
}

function _he_helper_custom_submit(&$form, &$form_state) {
  print 'hello';
  dsm('hello');
  $form_state['redirect'] = 'print';
  $form_state['rebuild'] = TRUE;
}

I think I've just used $form_state['redirect'] in the submit handler in the past.

However I'm not sure what order your submit handlers are firing in, maybe it would work if you added the after_build function to the form array as opposed to the button array. (If your custom submit handler is firing first then your redirect could get overwritten.)

E.g: $form['#submit'][] = 'he_helper_custom_redirect';

If that doesn't work then this post suggests using rebuild with redirect:

$form_state['redirect'] = 'where-do-you-want-to-go-today';
$form_state['rebuild'] = TRUE;

This code shows how to add a new custom submit handler without overwriting the original one:

function he_helper_after_build(&$form, &$form_state) {

  // add to the existing submit array to not override the default submit handler
  $form['actions']['submit']['#submit'][] = '_he_helper_custom_submit';

  // change the button text
  $form['actions']['submit']['#value'] = '2hello';

  return $form;
}


Ajax callback function is un-callable I’ve built a Drupal 8 Form example using code found here:
http://www.drupalcontrib.org/api/drupal/contributions%21examples%21ajax_example%21ajax_example.module/function/ajax_example_dependent_dropdown/8

The code, when run, dispalys 2 selects.  When a change is made to the first Select an Ajax call is made and is supposed to set a new set of options in the second Select.  However when changed I get a “Uncaught PHP Exception” - "The specified #ajax callback is empty or not callable."  I’ve tried multiple adjustment but am unable to get the code to run as desired.

Any answers or ideas would be greatly appreciated.

<?php
namespace Drupal\dependent_selects\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;

include 'dependent_selects.config';

class DependentSelectsForm extends FormBase
{
public function getFormId()
{
    return 'dependent_selects';
}

public function buildForm(array $form, FormStateInterface $form_state)
{
    $options_first = $this->_ajax_example_get_first_dropdown_options();
    $formValues = $form_state->getValues();
    $selected = (isset($formValues['dropdown_first'])) ? $formValues['dropdown_first'] : key($options_first);

    $form['dropdown_first'] = array(
      '#type' => 'select',
      '#title' => 'Instrument Type',
      '#options' => $options_first,
      '#default_value' => $selected,
      '#ajax' => array(
        'callback' => 'ajax_example_dependent_dropdown_callback',
        'wrapper' => 'dropdown-second-replace',
      ),
    );

    $form['dropdown_second'] = array(
      '#type' => 'select',
      '#title' => $options_first[$selected] . ' ' . t('Instruments'),
      '#prefix' => '
',
      '#suffix' => '
',
      '#options' => $this->_ajax_example_get_second_dropdown_options($selected),
      '#default_value' => isset($formValues['dropdown_second']) ? $formValues['dropdown_second'] : '',
    );
    return $form;
}

public function ajax_example_dependent_dropdown_callback($form,  &$form_state)
{
    return $form['dropdown_second'];
}

public function _ajax_example_get_first_dropdown_options()
{
    $instType = array(
      'String' => 'String',
      'Woodwind' => 'Woodwind',
    );
    return $instType;
}

function _ajax_example_get_second_dropdown_options($key = '')
{
    $options = array(
      'String' =>
      array(
        'Violin' => 'Violin',
        'Viola' => 'Viola',
      ),
      'Woodwind' =>
      array(
        'Flute' => 'Flute',
        'Clarinet' => 'Clarinet',
      ),
    );
    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

public function validateForm(array &$form, FormStateInterface $form_state)
{
    $a = 1;
}
public function submitForm(array &$form, FormStateInterface $form_state)
{
    $a = 1;
}

}

They way you specify your callback means that it is a function. You define it in your class, which means, it is not.

Prefix it with ::, that's a shortcut that tells Drupal that it's a method on the form class. You should also use camel case for the method's names. So, something like ::ajaxExampleDependentDropdownCallback (to be clear, you also have to rename your method, not just the callback string).

I also don't understand what you're trying to do with include 'dependent_selects.config';?


How can I attach a phone number field to the user account and optionally validate it via SMS? On my site, after registering their account, I want users to optionally be able to go to their account page, input a phone number, and then verify that number by SMS.  When they verify the phone number, I want to award a special role (ideally via Rules).

It seems like there are several modules that might be able to do this:

Two-factor authentication-- this supports SMS with the TFA Basic plugins, but I don't want to use SMS for authentication, just once to verify the number.
Twilio-- this module has user phone number verification, but it does it in a special database table (not a Drupal field) and does not have a rules event for "when a number is verified."
SMS Framework-- this module contains a submodule ("SMS Framework Users") for phone number verification, but it only works on registration; there is no option to register a number later (and in my case, I do not want to collect numbers on registration; I want to collect numbers later optionally).

Related questions:

Verification code when adding new number
Cell phone validation using SMS message

To address the modules mentioned:

This is a non-starter as it's a different use case from SMS number verification.
Here you'd have to build off the back the Twilio module. You could  modify user setting form twilio_user_settings_form() so that the callback twilio_user_settings_confirm_form_submit() is altered with your own custom callback that triggers a callback. Alternatively, you could evoke a hook_user_presave() as twilio_user_settings_confirm_form_submit calls user_save() with 'status' => TWILIO_USER_CONFIRMED, in the $edit array. In either case, you'd have to build/evoke your own custom rules event.
The SMS User module does provide verification for existing users. The form can be found under the path user/{UID}/edit/mobile. It triggers User validated SMS code event once the user has completed the verification process.

Given the above, both modules can achieve what you're looking for, it's just a matter of how much modification vs. what each service provides (Twilio vs. any other SMS Gateway provider).


Add new field to custom content entity type I have created a custom content entity type called Course. When I installed my module, Drupal automatically created the table schema for my entity, so all the fields I defined in Course::baseFieldDefinitions() had their column in the database table course, as specified in the base_table annotation of my class.

Now I want to add an extra field to my entity. I edited the Course::baseFieldDefinitions() method to define my new field in the same way as I did with the previous ones. The problem is that I don't know how can I create the appropiate column in the database.

The relevant part of my Course entity is:

class Course extends ContentEntityBase implements CourseInterface {

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference');
      // Settings and constraints for this field

    $fields['name'] = BaseFieldDefinition::create('string');
      // Settings and constraints for this field

    $fields['price'] = BaseFieldDefinition::create("float");
      // Settings and constraints for this field

    $fields['status'] = BaseFieldDefinition::create('boolean');
      // Settings and constraints for this field

    $fields['created'] = BaseFieldDefinition::create('created');
      // Settings and constraints for this field

    $fields['changed'] = BaseFieldDefinition::create('changed');
      // Settings and constraints for this field

    // New field being added
    $fiels["place"] = BaseFieldDefinition::create("string")
      ->setLabel(t("Place"))
      ->setDescription(t("The place of the course"))
      ->setSettings(["max_length" => 255, "text_processing" => 0])
      ->setDefaultValue("")
      ->setDisplayOptions("view", ["label" => "above", "type" => "string", "wegith" => -3])
      ->setDisplayOptions("form", ["type" => "string_textfield", "wegith" => -3]);

    return $fields;
  }

}

I've tried using the Drupal console command update:entities but it is not updating my database schema.

How could I add the place field to my database table?

After installation, you need to handle updating the schema yourself. There are some different scenarios, some are more easy to deal with than others. The most complex is moving data from one field type to another which means you would have to do a migration of data.

Anyways Drupal core has the entityDefinitionUpdateManager() which can be accessed doing \Drupal::entityDefinitionUpdateManager(). This manager can do a lot of the things you need to do when you change the base fields of content entities.

Creation of a new field is pretty easy, and all you need to make your own update hook:

function hook_update_8xxx() {
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}

This will apply all updates to all entities. This can generally be used for most things, but if there are data in Drupal has a failsafe that throws an exception to make sure it doesn't accidentally mess data up. During the beta the system attempted to handle data migration as well, but it didn't work well so it was decided that this is something module maintainers should do themselves.


Add additional element to exposed view form? I'm trying to modify an exposed view form by adding some additional markup.  My current code looks like this:

  if ($form_id == 'views_exposed_form') {
    if ($form_state['view']->name == 'products_page') {
        // $element = array();
        $form['filter_by']['#type'] = 'item';
        $form['filter_by']['#markup'] = '
Filter by:
';
        $form['filter_by']['#weight'] = -10;
        // $form = array_merge($element, $form);
        $form['solution']['#options']['All'] = 'By Solution';
        $form['technology']['#options']['All'] = 'By Technology';
        $form['platform']['#options']['All'] = 'By Platform';
        $form['brand']['#options']['All'] = 'By Brand';
        $form['category']['#options']['All'] = 'By Solution';
    }

    dpm($form);
  }

Now I'm trying to move the 'filter_by' element to appear first, before every other element, so I attached a weight value of -10 to it.  However, the element is being added to the container that the submit button would normally be found.

I'm completely confused...  any insight?

Well then... apparently it's a weird lopsided solution that is necessary.  See comment #10 here http://drupal.org/node/893392.


Negate contextual filters in views I got a view, which lists nodes of same type, a "Other activities" view, i use this view on a activity node view. However i don't want the node i am currently viewing, to show in the list as well.

So what i did, was to make a contextual filter for nid, and provide a default value of "Content ID of URL", of course now my list only provides me with the currently viewing node.

Isn't there anyway to negate this? So it shows all other nodes, that don't have the nid, og the current?

There is an option on contextual filters to exclude the resulting value, rather than limiting the search to that value. Turn on this checkbox, and you should have the results you are seeking.


How to setup Drush core development environment? I would like to create a PR against Drush, so one of the core commands has additional options. But I'm not really sure, how should I setup my development environment, so I'm not losing my time moving code between my site-specific Drush and master branch I checked out elsewhere.

I see that Drush contains docker compose file (https://github.com/drush-ops/drush/blob/master/docker-compose.yml),  but the wodby/php image apparently doesn't contain Drupal Core. I wasn't able to find any tutorial about this.

a) Start by reading the following material (if you haven't already):

https://github.com/drush-ops/drush/tree/master/tests/README.md
https://github.com/drush-ops/drush/blob/master/CONTRIBUTING.md

b) Fork the drush-ops/drush repository, so that you can track your work (and eventually start a PR from your fork back to the original repo).

c) Install the local dev environment provided using docker-compose:

git clone https://github.com/stefanospetrakis/drush.git
cd drush
git checkout -b YOUR_BRANCH
docker-compose up -d
docker-compose exec drupal composer install

At this point you have the source code of drush, equiped with tests. You can do your changes and additions to it and commit/push to your fork, as your project evolves.

d) You can test your changes at any time, against the official drush test suite to make sure you didn't break something:

docker-compose exec drupal composer test

e) Additionally, you can test your work in progress inside your own drupal projects, by replacing the standard drush in composer with your own fork, that would need three things:

Adding an extra repository in your Drupal's composer.json, e.g.:

"type": "git",
"url": "https://github.com/stefanospetrakis/drush"

Aliasing the "drush/drush" package, in order to pull from your current working branch in your repo, based on the exact version number found in composer.lock, e.g.:

require "drush/drush": "dev-YOUR_BRANCH as 9.5.2",

Use source (git) for your drush package, e.g.

{
"config": {
    "preferred-install": {
        "drush/drush": "source",
        "*": "dist"
    }
}

}
Possibly do manual pulls inside the vendor/drush/drush folder in order to get your latest work.

And as @greg_1_anderson mentioned in a separate answer, you will find Drupal Core under the sut directory of drush's source code.

Good luck!

P.S.: Replace https://github.com/stefanospetrakis/drush.git with the URL of your fork of drush-ops/drush repository, this is just an example.


2 sites sharing one user table How can I make 2 Drupal websites share the same user table so when a user is logged in on one they are automatically logged in on the other?

Your question seems to be all over the place. However, the Bakery Single Sign-On System module sounds like what you need.

  Bakery provides a "single sign on" feature for Drupal based sites that are on the same second-level domain (i.e. example.com, subsite.example.com, subsite2.example.com). It could also provide support for any other website that implements the same web cookie, xmlrpc, and POST methods.

  This module started at the 2009 Drupal.org redesign sprint in San Francisco as a way to manage single sign-ons across *.drupal.org infrastructure.

  Read the bakery documentation for more information.


How do I define a route and controller for the home page? A custom module called TSA contains almost all of the functionality for the /tsa subsite on my Drupal 8 multisite.

I want to define a route for http://localhost/tsa/, so that I can serve up dynamic content on the homepage depending on who the authenticated user is.

Here's tsa.routing.yml:

tsa.homepage:
  path: '/'
  defaults:
    _title: 'TSA Home'
    _controller: '\Drupal\tsa\Controller\HomepageController::content'
  requirements:
    _permission: 'access content'

And here's src/Controller/HomepageController.php:

<?php

namespace Drupal\tsa\Controller;
use Drupal\Core\Controller\ControllerBase;

class HomepageController extends ControllerBase {
  public function content() {
    return [
      '#type' => 'markup',
      '#markup' => 'Hello World from the HomepageController',
    ];
  }
}

But when I navigate to http://localhost/tsa, I just get Page Not Found.

Why doesn't it work? How should I go about doing this?

This is a classic case of trying to do something in the non-Drupal way -- conceptually, defining a custom route for your home page route makes sense, and it's possible in other frameworks, but Drupal has a different way of doing things that makes this approach completely unintuitive.

Here's how to do it:

Define your route as something other than '/' (i.e. '/students/overview')
In /admin/config/system/site-information, set your "Default Front Page" to whatever your route was:

Voila!


How to add class to specific TD in view table? I have a view created /admin/structure/views and it is a table.

How do I add a class (f.ex. "bgred") for a specific TD (f.ex "title")
in this table without using JavaScript ? I mean I have some hidden field
(f.ex. "Status") and want to add class for field "Title" only when Status==1,
is this possible ?

I want to add class to TD element not some div inside TD...

<td class="bgred">

1) click on desire field under 'Fields' in your view

2) select 'Style Settings'

3) check 'Customize field HTML' checkbox

4) check 'Create a CSS class' checkbox

5) enter 'replace-this-class' in 'CSS class' text field

then you should look into hook_views_post_render - this where you can access the actual html output for each row. if you add a class to the field as described above, you will be able then do php find and replace based on any logic.

my_module_views_post_render(&$view, &$output, &$cache) {

    foreach ($view -> result as $result) {

        //not sure about that - you would need to debug that
        $result_status = $result -> status;

        //your php logic and new class assignment
        if($result_status == 1) {
            $class = 'new-class';
        }

        //what you want to replace - again double check that
        $replace = '<td class="replace-this-class';

        //alter `$output` variable
        $output = str_replace($replace, '<td class="'. $class .'"', $output);

    }

}

This is very ugly but it works. Of course you will need to look into the $output variable to make sure that you are targeting correct html.


Date Display: How to hide part of repeat rule? When displaying recurring event dates for end users I would like to hide a part of the repeat rule (the until date has no meaning for end users):

Current display:

  Repeats every week every Thursday until Mon Dec 31 2012

Expected display:

  Repeats every week every Thursday

How to do this ?

The recurrence description is defined in date_repeat_rrule_description() in date_repeat.module.

At this time, there is no way for themes to change it. See this issue: http://drupal.org/node/342665

EDIT

Actually, you may override theme_date_repeat_field(), which calls date_repeat_rrule_description(). You could call your own version of that function to customize the display.

This would leave the contrib modules untouched, but you would be duplicating some effort and have more code to maintain.


Adding a target='blank' attribute in D7 module for Nice Menus I'm trying to add a target=_blank to all of the menu items inside Nice Menus. Has anyone ever figured this out?

I suspect that it's like adding title tag but I'm unsure.

Consider using the menu attributes module to add additional attributes with your particular menu item:

  This simple module allows you to specify some additional attributes
  for menu items such as id, name, class, style, and rel.

Unfortunately, I'm not sure if it integrates with nice menu. You'll have to give it a try nonetheless.


How can I print a referenced media extension I am working in the node template. In my content type I have a referenced field to media called 'field_event'. I created a new media type called 'document'. Inside document there is a file upload field called 'field_document'.
I need to print the file name, size and extension all separately in table cells.
Example: Myfile | 80kb | pdf

This renders the file, link and name.

{{ content.field_event }}

Gives me: mypdf.pdf 80.00 KB, This is the name of my pdf

This prints out only the name

{{ node.field_event.entity.name.value }}

Gives me: This is the name of my pdf

How can I get the file extension? I have tried these.

{{ node.field_event.document.entity.field_document.entity.filesize.value }}

{{ node.field_event|field_target_entity.field_mime_type.value }}

{{ node.field_event|field_target_entity.field_mime_type.entity.filemime.value }}

I am using twig tweak

{% set extension = node.field_event.entity.filemime.value|split('/') %}
{% set extensionDot = '.' ~ extension[1] %}

// File name
{{ node.field_event.entity.filename.value|replace({extensionDot : ''}) }}

// File size
{{ node.field_event.entity.filesize.value / 1000|round }}KB

// File extension
{{ extension[1] }}


How do I customize a Superfish Menu for Drupal 7? I have successfully installed Superfish by installing the Libraries module, downloading the Superfish library and putting it in /sites/all/libraries, and installing the Superfish module.

Now I would like to customize the look of it. The pre-built styles that show up in the drop-down in the Superfish Configuration could be a decent starting point, but I really would like to get into the details and get the measurements and colors just right.

How can I do this?

You need to overwrite the styles in your own custom stylesheet.  Use firebug to find which styles you would like to adjust.

Keeping it in your custom stylesheet will keep the styles from being lost when you update the module.


Change data export download link label I want to change the label shown to export csv file download link that generated with data export of a view. I didn't get any setting to change the label of download link - download full list.

The download button is actually rendered from a twig template found at /views_data_export/templates/export-icon.html.twig. This means that you can override it in your theme by copying that file to /themes/YOUR_THEME/templates/export-icon.html.twig and modifying it to what you need.
You can of course put that twig file into any subdir of /templates/ that makes sense to you - e.g. /templates/views_data_export/export-icon.html.twig will work as well.


How to create a rule which after several updates in 5 minutes of a node sends 1 message? When a node is being updated I have a trigger for this in the rules engine.
I want a notification of this in the email.

The node is however updated several times in 5 minutes.

I only need 1 notification of this.

I first had the idea to compare the node:changedate with site:current-time with 300 seconds diff in a php rule, but then all email is not send as the first email is also within the 300 seconds.

Any suggestion how to solve this?

Assuming your question is about D7, and that you can think of creating a view for such updated content for (say) "the last 5 mins", there is a solution to do what you're asking about. This solution uses the Rules, Views and Views Rules module, as further detailed below.

1. About the Views Rules module

The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

  ... provides two types of elements in Rules, configured with a "Rules" view display:

  Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

  Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

  Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'

After you enable the Views Rules module, use Views to create a view of your "updated content for (say) the last 5 mins" (as in your question). Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

3. Create a Rule Component using the view of display type 'Rules'

Create a Rules Component, using these guidelines:

Add whatever Rules Conditions you might want (if any).
Some Rules Actions you'll need to create (add) for sure:

Create a variable, with no initial value, say you name it "eMail Summary" (machine name email_summary), which will be used in subsequent Rules Actions.
Add a Views loop (by using the link that says Add view loop), and select the "Rules" display created in the previous step. Configure the parameters and variable names. And for each views result contained in your Views loop (about some "flagged content / user", as in your question), perform a Rules Action like Set a data value, for the email_summary variable from the previous Rules Action. The actual value to be assigned, is the previous value of email_summary, to which you append the desired data about the Views result being processed. For this you can use the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed).
Add a Rules Action to Send an eMail to a selected role (as per your "periodic summary email that gets sent to a specific role"), whereas for the body of that eMail you simply use the value of the email_summary variable.

If you're not familiar enough with Rules to create and populate that email_summary variable, you may want to have a look at the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?", in which a similar variable is used.

Try to execute your Rules Component "manually" (just to test), to unit-test if it works as desired. To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).

4. Schedule the Rules Component for periodic execution

Make sure you have the "Rules scheduler" enabled (a sub-module of Rules).

Improve your Rules Component from the previous step, by adding a Rules Action (as the last action to be performed) to Schedule a Rules Component, whereas the actual Rules Component to be scheduled is the Rules Component itself. You want it to be scheduled in "5 mins from now" (to make it happen every 5 mins).

To execute this Rules Component the very first time, just execute your Rules Component "manually". To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).

Assuming your QA-testing succeeded, and assuming your cron jobs are running also, the eMail should get created next time cron runs (after an amount of time, depending on the amount of time you configured in your Rules Component to get it rescheduled).


How to increase the width to the Omega sub-theme more than 950 usable pixels I have created a new sub-theme of the Omega theme (version 7.x-2.1) in Drupal 7.

But I want to use 970 usable pixels instead of 950 pixels as the sub-theme offers in "Default container width".

How can I do this? Shall I change the 960.css file from themes/omega/omega/css/960.css or shall I overwrite the 960.css file form my sub-theme? What you suggest?

My guess would be not to touch to the original theme and create a new one where you can override without touching anything to the original.

Now, I can't help any more, I never used that theme and Drupal 7 yet.


How to use field.tpl for rendered node in views3 i have set up a view (drupal 7) with a field that rendered the full node (node referenced field), and i want to get rid off the extra classes and tags wrapped around the fields.

i have copied field.tpl to my templates dir, and no matter what i name it it doesn't effect anything. I have selected that in the field settings in views. and yes, cleared the cache always.

would i name it after the content type. or the view.  i even left it at just field.tpl and still nothing.

If you want to override the views field template, the correct template file name would be views-view-fields.tpl.php.

You need to copy the template sites/all/modules/views/theme/views-view-field.tpl.php to your current enabled theme folder. Then update the file as you need.

Rescan template files in your view theming information. The file views-view-field.tpl.php should be highlighted with bold. You may need to fluch the cache. It is a view template to all the fields as a row.

If you want to theme a specific field, you could use views-view-field--[field_name].tpl.php. It is the most specific view template.
You can check more in Views theming.


Multiple Active Themes is it possible to have more than one active theme? Basically what I'm trying to achieve is another theme that has none of the extra CSS/JS output by Drupal modules -- this would only be used for E-Newsletter display. I see the "default" setting for a theme, but how would I apply certain content types, etc to a specific theme? I've searched a bit and am stuck in the mud at the moment. Any help would be greatly appreciated. Thanks!

The Themekey module has that functionality built in:

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties


rules scheduler performance I use drupal 6 with rules. I have more than 200 scheduled tasks (updating node's field)waiting to be executed at one time. Do I need to worry about server crash or is there some kind of queue implemented in scheduler? Thank you.

You need the Ultimate Cron module. It is an advanced system for managing scheduled tasks. You can set rules and custom schedules for every single task. Can be found here:

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


How can I find out what's denying permission to access a path? user/uid/edit is giving permission denied where uid = the current user's uid. The permissions all look correct. Is there any way to find out what exactly is denying the permission?

Users should always be able to edit their own profile. The access callback used for "user/%user_category/edit" is user_edit_access(), which contains the following code:

return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;

When the currently logged-in user tries to edit his/her account, the function returns TRUE, which means s/he has access to the edit form.

There could be a third-party module that altesr the access callback for that menu item, and which is using code that doesn't allow the currently logged-in user to edit his/her own account, or that doesn't consider such a case.


How to fix 'Call to undefined function node_load() in menu.inc' fatal PHP error? Copied my live site to my local computer. From Windows server 2008 to Windows 7. Took a backup of the database via mysqldump. Restored the database on the dev-db-server.  Now I'm trying to get my local copy up-n-running. Browsing index.php gives me

Fatal error: Call to undefined function node_load() in C:\inetpub\wwwroot\my_drupal\includes\menu.inc on line 577

My hunch is that I have missed some web server settings allowing parent path or similar?

I have installed PHP and 5.3.13 and URL Rewriter via Web Platform Installer. According to CHANGELOG.TXT I'm running Drupal 7.0

However phpinfo(); works fine.

Edit / Update: I tried to narrow down the error. Following code fails on line 3. If I change the path on line 2 to something wrong the require_once will fail. Apparently IIS is able to find bootstrap.inc, but bootstrap.inc cannot find user_access()

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Problem was the file encoding from mysqldump. My solution: Downloaded the sql file to my local computer. Saved it in UTF-8 with Sublime Text 2. Run the script. And things worked fine with the original drupal files copied from web server. Did not need to run registry_rebuild etc.


How to get all terms with services module? I am working on an app (react native) and when i make a request to get the taxonomy terms i don't get all the terms

This is the url i used to get the terms:

http://example.io/api/taxonomy_term?parameters[vid]=2&pagesize=1000

But when I go to the url from my browser i get the full list of terms!

Here is my fetch code:

fetch('http://dev-fnyan.pantheonsite.io/api/taxonomy_term?parameters[vid]=3&pagesize=500').then((response) => response.json()).then((response) => {
    let data=[]
    response.map(i =>{
      data.push({label:i.name, value:i.tid, parent:i.parent})
    })
    this.setState({
      categories: data
    })
  }).done();

Can anyone suggest where is the problem?

You need to grant permission for Perform unlimited index queries at admin/people/permissions. Alternatively, you can set this in settings.php:

$conf['services_taxonomy_term_index_page_size'] = 200;


How create a role that only can create users? I want to create a role in Drupal. I want create role assign to specific user.
Specific user can create only user and not anything.

Go to admin/people/permissions/roles and create your role. Then go to admin/people/permissions and uncheck all the permission for the new user and check the Administer users permission in the User section:

To uncheck all the permission I can sugest you the use of the Permission Select module.

  Permission Select is a module that allows for quicker editing of role
  permissions on /admin/user/permissions.

And as Pierre Vriens says in his comment:

  "do not grant ANY permissions to authenticated users". Because any
  user with permission to create users is also an authenticated user.


How to insert a view in the body field of a node? Is there any way to insert a view in the body field of a node?

Something similar to the insert module for inserting images in the body field.

I've found this module Insert View

I haven't tried yet. Let me know if it fits your request.

I found this as well Views Reference
I tested both and I think the second is more appropriated for you.


Adding team information to migrate_d2d I expect this is a trivial question for those familiar with OOP/PHP. The migrate_d2d module provides an example module that demonstrates implementing a D6 -> D7 migration. I'm making great progress in defining the migration as I need. However, I am stumped on how I can add team information to my custom migration. The provided beer examples show performing this step when extending the Migration class.

abstract class BasicExampleMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->team = array(
      new MigrateTeamMember('Liz Taster', 'ltaster@example.com',
                            t('Product Owner')),
      new MigrateTeamMember('Larry Brewer', 'lbrewer@example.com',
                            t('Implementor')),
    );

    $this->issuePattern = 'http://drupal.org/node/:id:';
  }
}

With migrate_d2d, the chain of dependency starts with the migrate_d2d class definitions:

Migration > DrupalMigration when then forks to:
DrupalUserMigration > DrupalUser7Migration
DrupalTermMigration > DrupalTerm7Migration
DrupalRoleMigration > DrupalRole7Migration
...etc

For my purposes, I'd like the DrupalMigration object to have the team properties set.

How do I modify DrupalMigration class properties so that I can set the team's properties and have all the children classes inherit this property?

I just followed the dependency chain of the example module:

ExampleNodeMigration extends DrupalNode6Migration
DrupalNode6Migration extends DrupalNodeMigration
DrupalNodeMigration extends DrupalMigration
DrupalMigration extends Migration

That means that as long as your class, like ExampleNodeMigration, extends a class down the chain from class Migration, your team implementation should be as in the example you gave.

In light of the changes you made:

  How do I modify DrupalMigration class properties so that I can set the team's properties and have all the children classes inherit this property?

You insert your own custom class that extends the lowest class in the chain that has what you need, then have your migration modules extend it. So if you are migrating users, you would extend DrupalUser7Migration in some custom class, then have your various user migration classes extend DrupalUser7Migration, and so on for each variety of thing that migrate_d2d can migrate. That may be the best you can do because PHP is single-inheritance.

There is another way to get around single-inheritance and not repeat yourself. You can create a trait, called, for example, MyMigrationSettings.

trait MyMigrationSettings {
  function setTeam() {
    $this->team = array(
    new MigrateTeamMember('Liz Taster', 'ltaster@example.com',
                        t('Product Owner')),
    new MigrateTeamMember('Larry Brewer', 'lbrewer@example.com',
                        t('Implementor')),
    );
  }
}

Then, use the trait in your migration classes:

class ExampleNodeMigration extends DrupalNode6Migration {
  use MyMigrationSettings;
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->setTeam();
    // ...
  );
}

I have not tested this code and I am just literally typing it into the comment box.


Making taxonomy dropdown on the basis of previously selected dropdown of two different taxonomies? I have two different taxonomies
Taxonomy 1:

Category
-music
-football

Taxonomy 2:

Sub-category
-Jazz
-Rock
-Fifa
-Russian Open

I have linked Jazz, Rock to music and
Fifa, Russian Open to football by term-reference field.

I have content type event, having term-reference to both Category and Sub-category. I want drop-down for sub-category should be populated after selection of Category.
Eg. if we select music as category then in sub-category only jazz and rock should be shown.

I think you will have to go for some custom code if you want to use seperate taxonomy vocabularies.

An easier way would be to have all terms in the same hierarchical vocabulary and use Hierarchical Select to create the "populate dropdown"-feature.


How to redirect on node save to fill out extra fields attached to terms I've added a mandatory email field to terms in a vocabulary I have called Instructor.  This field is displayed on my content type as an autocomplete term reference.  Because it is an autocomplete field, it will save new non-existing tags.  I am curious how I can redirect to a page on node  save (and subsequently term save) so that users can fill out the email fields?

Better yet, is it possible to limit autocomplete tags to existing terms, and then add a local action for "add a new instructor" where users have to fill out all fields?

I've found there's a new module called Entity Connect which adds a button to entity reference fields for creating new references on the fly.  The module sends the user to the entity creation page (add term, etc) allowing you to fill out all necessary fields, then redirects back to the original node form.

This works great.  Now the only thing necessary now for my use case is to figure out how to programmatically add taxonomy terms based on the value(s) of the entity reference field.


Best way to add edit + flag links to a node being displayed inside Colorbox Node? One of my content types opens in a colorbox node but I need an edit link and flags to appear for certain roles. I'm not using panels for this content type and I'm not using Display Suite either.

Blocks don't get displayed in a colorbox node so I'm wondering what's the easiest and most efficient way to add these links.

Php filter is fine to use.

Thanks

You could use Views, create a block view.

Under advanced, add relationship of flags of the node and check mark require relationship.

Add flag link and edit link as fields.

Add Contextual filter of nid and select provide default value, then select get ID value from url. (preview will go blank, which is normal here)

Place view block on your node.

  Php filter is fine to use.

This is very risky, see: What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?, if you want to use php, create a template file for your node, block, or view.

Therefore, another option is to create a template file for your content type.

node--[type-name].tpl.php and do php code there.

Ex: node--article.tpl.php

In your template file put

  <?php print 'nid . '/edit"> edit '; ?>

  <?php print flag_create_link('FLAGNAME', $node->nid); ?>

<?php print render($content['title']); ?>
<?php print render($content['body']); ?>
<?php print render($content['field_name']); ?>

and so on, you print all the fields you have.

Remember to flush/clear the cache to see changes.


How create a new variable according field value Please I need a hand, I would like to create a new variable like the native "frontpage" variable. I have a content type called "Config", in this CT I have some boolean fields and I need check for this field values to print a view in my page.tpl

Something like this, my example field "display reviews block?", its may be set "yes" or "no". So, I need create a new variable "$display_reviews" according this value and print this in page.tpl:

<?php if (isset($display_reviews)): ?>
 <?php print views_embed_view('reviews', 'block'); ?>
<?php endif; ?>

Sincerly, I dont know how to do this, but i tried something like this:

function mytemplate_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $n = $variables['node'];

    if ($variables['node']->type == 'config') {

        if (isset($n->field_display_reviews == 'yes') {
          $variables['display_reviews'] = 'this variable need be created';

        }
    }

 }
}

UPDATE

Considering I want to print this variable in my node.tpl not in my page.tpl, I have decided to try with directly query, I dont know if is the better and fast way, but this is my code. Its not working yet, this is broking my site, but now I can display the FIELD ID. Im trying to use the field_attach_load to get the field value but no luck:

/**
* Implementation of preprocess_().
*/
function mytemplate_preprocess_node(&$variables, $hook) {

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'config')
  ->propertyCondition('status', 1)
  // value 1 from boolean field
  ->fieldCondition('field_display_reviews','value', '1', '=');
$result = $query->execute();

if (isset($result['node'])) {
  $stories = $result['node'];

  $fields = field_info_instances('node', 'config');

  // Get id of field
  $reviews = $fields['field_display_reviews']['field_id'];
  field_attach_load('node', $stories, FIELD_LOAD_CURRENT, array('field_id' => $reviews));
  $output = field_get_items('node', $stories, 'field_display_reviews');

  $variables['display_reviews'] = $output;

}

}

Your code is already there, i think you didn't extract the value of the field_display_reviews correctly, try the following:

 /**
 * Implements hook_preprocess_HOOK().
 */
function mytemplate_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $node = $variables['node'];
    if ($node->type == 'config') {
      if (
        isset($node->field_display_reviews[LANGUAGE_NONE][0]['value'])
        && $node->field_display_reviews[LANGUAGE_NONE][0]['value'] == 'yes'
      ) {
        $variables['display_reviews'] = 'this variable need be created';
      }
    }
  }
}

NOTE: if your display_reviews field of type Boolean the value it will be 1 instead of yes, print the value of $node->field_display_reviews[LANGUAGE_NONE][0]['value'] before if to see.


Display NOT a title field in Entity Reference field but my own field By default 'Entity Reference' field uses 'Title' field to resolve Nodes.
Is there any good way to change that behavior so it use another field to do that?

What if I want to use URL field or my own custom field what should I do?

I just would like to know what are the good ways to do that.

Thanks.

If by "resolve" you mean what is searchable in the entity reference autocomplete field, then yes you can change the entity selection mode in the fields settings from simple to view and create a custom view to populate options. There is a good step by step tutorial on how to do that here: http://www.jackrabbithanna.com/articles/creating-entity-reference-view


Is it possible to pass a Field value Via URL when creating a Node? This may be posted elsewhere but I was having trouble finding anything answering my question directly.

I have a content type called Ticket that I want to have different fields based on what page a user is on when they push the button to create new ticket.

I am doing this because I would like a grand overview of all tickets entered, but there is different information needed from the user based on what queue they are entering a ticket for.

If there is a better way to do this I am open to suggestions.

Thanks in advance

For passing values to forms:

There is a Drupal Module called Prepopulate which allows you to prefill fields on node forms using $_REQUEST variables.

It is quite simple to use and merely requires you to rewrite the links to contain the field values you want to pass along. If you want to fill field_your_fieldon your ticket node, the link would need to look like this:

http://www.example.com/node/add/ticket?edit[field_your_field]=desired field value

That said, this wont hide any fields on the form, merely provide default values for them. If you want tickets with different fields, you could always use multiple node types.

If you want to actually hide fields based on the url, you could reuse the node form on custom pages and manipulate their fields there as you need.

You will  need menu entries for your different node displays to distinguish which node form you want to call.

function ticket_module_menu() {
  $items['ticket/add/tech-ticket'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ticket_module_tech_ticket'),
    'access callback' => 'create ticket content', //or put a custom permission
  );

  $items['ticket/add/support-ticket'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ticket_module_support_ticket'),
    'access callback' => 'create ticket content', //or put a custom permission
  );

  return $items;
}

And then create a form for each entry:

function ticket_module_tech_ticket() {
  module_load_include('inc', 'node', 'node.pages');

  //get node add form for node type ticket
  $form = node_add('ticket');

  //Hide fields you do not want to display
  $form['field_your_field1']['#access'] = 0;
  $form['field_your_field1']['und'][0]['value']['#disabled'] = TRUE;

  return $form;
}

function ticket_module_support_ticket() {
  module_load_include('inc', 'node', 'node.pages');

  //get node add form for node type ticket
  $form = node_add('ticket');

  //Hide fields you do not want to display
  $form['field_your_field2']['#access'] = 0;
  $form['field_your_field2']['und'][0]['value']['#disabled'] = TRUE;

  return $form;
}


Fixed width for columns in grid view (Views) I have a block(page same problem) on www.bluraykopen.nl with a grid view with 3 columns. As you can see the 3 products are next to each other on the left side.

I can not get them to use the full with of the block, so that each column has a fixed width like 33%.

I have searched for an answer the whole day, and tried some CSS adjustments, but can't get anything to work.

Hope you can help.

I had success with explicitly setting the width of the table that contains the images/titles.

Set the width of <table class="view-view-grid cols-3> to 100% in your CSS and see if that doesn't help.


Get Fields of a custom Content Type from Database in Drupal 7 I'm trying to get custom fields of my custom content-type "slideshow". I've chosen to get the fields from template (.tpl.php) file for some reasons (mainly because I've to write lots of formatting HTMLs and modifying lots of template files did not sound good).

So far, What I've got is individual nodes:

$result = db_query_range('SELECT n.nid
                      FROM {node} n WHERE n.type = :ntype', 0, 10, array(':ntype' => 'slideshow'));
foreach ($result as $record) {
    $node = node_load($record->nid);
    // Got $node! What to do now????
}

The code works & I've got nodes in $node. Now What to do to get individual custom fields & work with the raw data of these fields? Please help.

PS I've tried Get content type with PHP from database but the code does not work... guess it's for older Drupal versions.

You could always try field_get_items if you know the names of the fields you want. field_get_items('node', $node, 'field_name');

Although node_load() should be providing the fields for you and can be found at $node->field_name

Also Attiks advice is sound, I would also not recommend doing this in tpl


How to embed views in a particular custom block template I have created a views block in D8 and thinking to embed it within a particular custom block template I created to override (e.g block--myblock.html.twig), I wonder how to do this ?

Ok, I have found a way to do so from another post, tested and it works ! So basically..

1) Create a new variable in mytheme.theme file located in your default theme folder.

function mytheme_preprocess_block(&$variables) {

  $variables['view1'] = views_embed_view('view_name', 'block_news');

}

'block_news' is your views block's machine name actually.

2) And then use this twig in your block template.

 {{ view1 }}


How to print rest of the form using "without" function in twig while printing custom user field present account array? I am writing custom template to style my "edit user profile" form page.

Below is the code in twig file :

  {{ form.first_name }}

  {{ form.last_name }}

  {{ form.account.mail }}

  {{ form.account.current_pass }}

  {{ form.account.pass }}

  {{ form.actions }}

  {{ form|without('first_name', 'last_name', 'account.mail', 'account.current_pass', 'account.pass', 'actions') }}

The Problem is that it is print all account field for example account.mail. I guess it is is not understood by "without" function and it prints that field twice so I am unable to print all account custom field elements individually.

Here is the Dump output of twig form:

It is very important to print rest of the form using "without" function but "without" function printing my custom account field twice and not understanding that it is already printed on page.

Also I tried to directly use "account" as argument in without function which is working fine but this may miss some important content render which is present in account array. I want to render all account data except the fields which I want to print individually.

try to print it this way it gives you more control :

{# 1.use the attribute to set the form action and other attributes #}
<form{{ attributes }}>
 {{ title_prefix }}
 {{ title_suffix }}

     {# 2.print the form elment using : {{ element.elements.key }} #}

       {{ element.elements.nom }}

       {{ element.elements.telephone }}

     {# 3.print the captcha if you have a cpatcha #}
     {{ element.captcha }}

     {# 4.you need to output a couple of hidden form elements that is required for the form to be submitted properly and securilly#}
     {{ element.form_token }}
     {{ element.form_build_id }}
     {{ element.form_id }}

     {# 5.output the form action (submit) at the end of the form link  #}
     {{element.actions }}

 </form>


How to collect time periods, calculate the total, and present in ISO 8601 format? I am trying to get few inputs of time periods from users (it can be by choosing in dropdown).
let's say a user will be able to input in one field: "1 hour and 5 minutes" or 01:05;
In second field the user will be able to input: "2 hours and 25 minutes" or 02:25;

Then, I want to calculate and add up the  two time peirods for: "3 hours and 30 minutes" or 03:30;

It's important that all the date and time fields will be saved in ISO 8601 format, for google.

Someone can help, How can I do that?

Thanks!

You're asking two completely unrelated questions here.  To rephrase:

How can I provide Google with dates in a format that Google's scraper will recognize, as specified in Rich snippets - Reviews?
How can I accumulate time periods and present the result in a format suitable for humans?

Asking two unrelated question in one question is depreciated on SE, and will usually get your question closed, but I am going to answer them anyway.

First question: The ISO 8601 format requested by Google is YYYY-MM-DD with leading zeros if required, so July the 4th 2013 would be 2013-07-04.

To format the ISO date you can use the PHP function date like this:

$isodate = date('Y-m-d', $timestamp);

where $timestamp is an integer with the number of seconds that has elapsed since the Unix Epoch (January 1 1970 00:00:00 GMT).

Further, Google expects the $isodate string to be embedded in the page attached to the dtreviewed property using the syntax one of three metadata schemes (microdata, microformats, or RFDa).  You do this in Drupal by overriding the template of page, node, etc. you want to embed the dtreviewed property in.

Second question: To accumulate time periods, you need to convert periods input by users (such as "1 hour and 5 minutes" or "01:05") to an integer format with seconds resolution.  To convert to seconds you multiply the days with 86400, the hours with 3600 and the minutes with 60, so "1 hour and 5 minutes" becomes:

1 (hour) * 3600 + 5 (minutes) * 60 + 0 (seconds) = 3900 (seconds)

and  "2 hours and 25 minutes" becomes:

2 (hour) * 3600 + 25 (minutes) * 60 + 0 (seconds) = 8700 (seconds)

To accumulate, you just add the seconds:

3900 + 8700 = 12600 (seconds)

To display in a suitable format, you can use format_interval.

$interval = 3900 + 8700;
$intervalstring = format_interval($interval, 2);

and $intervalstring will now be:

3 hours 30 minutes

(You will lose the "and" by using this standard function, if this "and" is important, you'll need to write your own.)

For avoidance of misunderstanding: Goggle is not interested in your time period data. A time period is typically an interval made up of hours and minutes, and not attached to a particular date.  Google wants dates (as in year, month and day of month).  Dates and time periods are different things, and there is no way you can format a time period as a date, or vice versa.


Change navigation (sublinks) according to main menu (headlinks) I would like to create a main menu with some links in it. And when you click on a link in the submenu, the content of the navigation menu changes according to the link clicked in the main menu (= subnavigation elements). Here is an image to clarify:

I now have a main menu and a navigation, but the links stay the same for this moment. So now I would like to get the navigation to be dynamic. How could I do this the best way?

The easiest way will be to create a menu for each top level menu page.

Then put all those menus as blocks in your sidebar region, with a rule so they only appear on the correct page, or subpages.

E.g.

Menus:

Top Menu:  Home | News | Blog
    // show on all pages

Home Menu: Info | About
    // show on home and home/*

News Menu: Current | Archive
    // show on news and news/*

Blog Menu: My Blogs | Other Blogs | Archive
    // show on blog and blog/*

Pages

/home
/home/info
/home/about
/news
/news/archive
/blog
/blog/other
/blog/archive

So, step by step instructions would be:

Create a main menu for your site.
Add items for Home (URL: /home), News (URL: /news) and Blog (URL: /blog) to your main menu.
Create another menu called Home.
Add pages info (URL: /home/info) and about (URL: /home/about) to this menu.
Add this menu to your theme in a block. Set the block visibility to only appear on "home" and "home/*". This is the clever bit because the submenu for home page will appear on the main /home page, and also any subpages of that as long as you follow the url structure.
Repeat same process for the news and blog menu so now each of your sub-menus only appear on their specific pages.
Do a little dance (can even have a sing if you want).
Done.


Language switcher shows wrong language on front page after detection by browser settings Content and interface are displayed correctly but the language switcher shows the default language when the language negotiation is set to these options:

URL (language prefix)
Browser
Standard

Means: Browser detection leads to displaying content in german for example, but the language switcher itself shows still "english" as selected. Even when clicking on it the language still is german.

This only happens on the front page, on other paths the prefix takes effect and the switcher shows the correct, selected language.

Any ideas how to fix this?
Thanks in advance!

EDIT: The frontpage is designed with translated blocks only, there's no node to point the multilingual variable to.
For multilingual we have following modules installed and used:
- Internationalization (i18n)
- Block languages (i18_block)
- Multilingual content (i18n_node)
- String translation (i18n_string)

For each language there are several "standalone" blocks, meaning not translated via the block translation option. Visibility is set through these settings:

It could well be that your issue is due to the fact that you do not have any nodes (Drupal without ANY nodes ... go figure ... a CMS without any "real" Content). So to get it to work you may have to make Drupal give "a few nodes" (i.e. 1 for each language ...).

If you agree, and based on what is described in Multi-language website and language switcher in front page, you may want to try if the steps below, or a subset of it, resolve your issue (probably replacing all 'IT' by something like 'GE' for 'German'):

Assign "path prefix only" to the language settings.
Assign the prefix EN for English.
Created an IT front page (e.g. node/1), chose language IT and leave the menu link title empty in the primary links (you probably want to leave the body empty also).
Create the EN front page (e.g. node/2), chose language EN and leave the menu link title empty in the primary links as well. You probably want to leave the body empty also, though for testing purposes you may temporary want to put some visible content in it also.
In both the IT page and the EN page check "promoted to front page" in the publishing options.
Not sure if you need this step also (first try by skipping this step): in Administer > Site building > Menus > Primary links, create a menu item for "Home" and assign its path to "front", parent item "primary links" and language "all languages".
In "Site information",  put "node" as default front page.
Check if your language switcher now works fine: verify if it changes the content from node/1 to node/2 (each of them with their related blocks to be shown) based on selected language. If you also performed step 6, then verify if the primary link "Home" always goes to the corresponding front page (and related blocks).