Workbench Moderation and Custom Field Issue

Due to the underwhelming response, I had to figure it out for myself :-). To save any other newbie hours of angst, here is the solution:

As predicted, the answer was simple, but finding it was the problem! I eventually found how to load the latest revision by looking at the workbench moderation module source code. If you add the line under the $node variable assignation below, it will return the value on the current revision:

<?php

$node_id = arg(1);
$node = node_load($node_id);
$node = workbench_moderation_node_current_load($node); //NEW LINE!
$fieldname='field_approvers';
$items = field_get_items('node', $node, $fieldname);
if($items)
{
 $key = $items[0]['value'];
 echo "key = ". $key;
}
else
{
 echo $node_id;
}
?>

Hope this helps someone.


Yet another solution from this discussion that works without panels or other custom modules.

In your theme folder locate template.php and write this code. Replace YOURTHEME with the name of your theme:

function YOURTHEME_preprocess_page(&$vars) {
  $header = drupal_get_http_header('status');
  if ($header == '404 Not Found') {
    $vars['theme_hook_suggestions'][] = 'page__404';
  }
}

Whenever 404 occurs your page--404.tpl.php will be used. Remember to put "--" not "__" in your template file name.


It would appear your using a 'Display output' template when you probably want a 'Row style' output so you can access fields. You will need to change your tempate by going to 'advanced > theme information', it will probably be something similar to 'views-view-fields--homepage-suppliers.tpl.php'.

You can then get a nid from the field and access a whole host of information through the node object.

  $nid = $row->{$view->field['field_supplier_image']->field_alias};
  $node = node_load($nid);

If you var_dump() the $node variable you can see what you have to play with.


What does INTERNAL form properties mean?

Internal means that these properties are not supposed to be used by module developer.


You can try using Bundle Copy Module...

  Has export/import support for:

  Node types
  Taxonomy
  User
  Field API fields
  Field groups

  You can find the export/import links for the supported entities on
  following paths:

  Nodes: admin/structure/types
  Taxonomy: admin/structure/taxonomy
  Users: admin/config/people/accounts


The hostmaster-install command has options for --profile and --makefile.

I use these options for OpenDevShop, which has it's own makefile and profile.

You can use a URL or a path for makefile option.

    drush hostmaster-install --makefile=/path/to/mymake.make --profile=mycustomprofile


How to prevent views from loading the results upfront

Here is the way to solve your issue:

Add Contextual filter of "Global: Null" type
In "When the filter value is NOT available" section check "Provide default value" and specify "Fixed value" and "all". Notice! If view still display results - then try select "Raw value from URL" here.
In "When the filter value IS available or a default is provided" section check "Specify validation criteria" and select "PHP code"
Specify this code

if (count($view->exposed_input)) {
  return TRUE;
}
In "Action to take if filter value does not validate" select "Display all results for the specified field" value
Don't forget to add any "No results behavior"!

Now results will be shown ONLY if filters are sent. View will be empty on       first display.


Hope this will  help you,

In Drupal 7 you can use these modules for your requirement

Extended path aliases
Sub-pathauto (Sub-path URL Aliases)


Using a Drop Down and available Dates in a Content Type

You can use Date module. Read more here: http://drupal.org/node/262062

If you are already using that, then you probably need to change, widget type of the field to Popup-Calender or Select List


How to check if the current page is a 404 error from a module/template?

In Drupal 7, you can use drupal_get_http_header().

In the template.php file, use this code.

$status = drupal_get_http_header("status");
if ($status === '404 Not Found'){
  // Do something.
}

In Drupal 8, you can use the following code in a hook.

$route_name = \Drupal::request()->attributes->get('_route');
if ('system.404' === $route_name) {
  // Do something.
}


How to use tokens in a filtered text field

I am using this module Token Insert Text

Perhaps you need this to get it to work. (I know my version is outdated, I did this a long time ago)

Then go to admin/config/content/ckeditor/edit/Advanced and under EDITOR APPEARANCE

Scroll alway the way down and click save.


Adding a css in preprocess view not woking

the path is wrong!

drupal_get_path('theme', 'mytheme') already provides the path to your theme folder.  no need for '../../../...'

you should probably use

drupal_get_path('theme', 'zenon') . '/css/image-gallery/css/style.css'.


Default image is not displayed while creating a node

Here is the screen shot for  field type. The drupal version i am using is Drupal 7 .


To alter the value returned from an implementation of hook_libraries_info(), a module or a theme needs to implement hook_libraries_info_alter(). As with other alter hooks, there isn't a way to override the value returned from a specific module, so the hook name is the usual one: modulename_library_info_alter() or themename_library_info_alter().

As side note, you code contains also an error: The parameter is $variables, but the code is using $libraries.


You can accomplish that using ajax_command_invoke.

Here is an example using your own code:

function ajax_example_autotextfields_callback($form, $form_state) {
  // $a = $form['first_name'];
  // $a['first_name']['#value'] = 'foobar';
  // $a['first_name']['#disabled'] = TRUE;
  // return $a;

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      // First we add the disable attribute into the html input tag.
      // which makes the the input field inaccessible.
      ajax_command_invoke('#WRAPPER_SELECTOR input', 'attr', array('disabled','disabled')),
      // Then we grey it out by adding the form-disabled CSS class.
      ajax_command_invoke('#WRAPPER_SELECTOR .form-item', 'addClass', array('form-disabled')),
    ),
  );
}

You can instead grey out using CSS attributes by calling ajax_command_css


Properly bootstrap drupal for standalone PHP file?

By far the easiest way to manage the bootstrap is to use drush php-script, alias scr.

file.php:

<?php
echo l('Link', 'path');

Cli:

drush @alias scr file.php

Output:

Link

This way you need to deal with nothing with regard to the bootstrap, drush will solve it entirely for you, and gives you the ability to use it easily across sites thanks to aliases. (Might even work on remote sites, though I haven't tried that)


There are two approaches I know to make inline images in WYSIWYG editors open in Colorbox. The one which I used in my last project was inserting images with Insert module. Which requires you to add an image field to your content type and upload your images to that field and than insert them with any image settings (instead of uploading them via the Media button on the editor).

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

This approach allows you also to get the images with Views etc, since they are actually stand-alone fields.

The second approach is adding a CSS class to the inline image uploaded via the media button. I'm not quite sure about how and which class but I did use this approach a few years ago and back then the mentioned modules had their 7.x-1.x versions, still. I was looking for the current state of using this approach but didn't find anything new. I'll experiment it a bit and write here.

Edit: After investigating about an hour, couldn't find any better way than the approach with the Insert module. It's the best user experience among all other approaches, if not still perfect.


How do I do a regex query in reverse in entity query?

Okay, is seems like this is in fact impossible to do right now with config entities.

If you look at \Drupal\Core\Config\Entity\Query\Condition, and into the function match, it shows what operators are available for config entity queries. REGEXP isn't even an option. Nor is there anyway to query a value against a field, instead of a field against a value.

The only way to really do this seems to be to load all of the config entity records into memory, then do the comparison with php.


Notices and Warnings Drupal Commons 7.x 3.9 Undefined index, invalid argument, illegal string offset

title is not defined. #items is not defined. foreach is not getting a value to work with. #children doesn't exist to render.#printed doesn't exist to render.
go into the function where title is supposed to be defined and check that there is a value. Do the same for the rest. Check what further up the chain in your code is calling these values. Try doing a backtrace.


How to hide set up database step in a installation profile?

You wanted an example -- which is basically showing you how to do it. From the docs I supplied and the help others that gave you cookie crumbs provided should have lead you towards a solution, Other than saying "show me" all the code.

A working profile example is in this GIST, you make a shortprofile directory in your /profiles directory and select "Short Profile" from the Installation screen. This is the "long way" to do this, there is a shorter way in-theory ... see my code comments.

Be sure to change the $databases['default']['default'] in line 47 of .profile to the existing database credentials that will work in your environment. Look for my comments in the code to change the db credentials and db password (line 125 of .profile).


How to Create Membership Groups for Products?

Another alternative to look at is the Group module, which is an alternative to Organic groups ...

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

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


How can I extract info from the user_profile array

In drupal 7 on the user-profile.tpl.php to which you refer the whole user object is loaded so you can output the different pieces you see in devel by doing this (a modification of the default user-profile.tpl.php you've copied to your theme):

Default:

<div class="profile"<?php print $attributes; ?>>
  <?php print render($user_profile); ?>

Modified:

<div class="profile"<?php print $attributes; ?>>
  <?php print render($user->name); ?>
  <?php print render($user->signature); ?>
  <?php print render($user->timezone); ?>
  //and so on...

On Drupal 6 the only difference is

<?php print $user->name; ?>
//dropping the render wrapper (which is good practice in D7 but is not used in 6)

As the questioner mentioned in the comments the above will display the currently logged in user's info.  To get the info of the user's page you are visiting (ex. YOUR_BASE_URL/user/2) you can do this (this will also work with aliased user pages):

<?php
   /*call this ($user_page_object) whatever you want but it is ill advised to
     call it $user as that will conflict with the $user object for the currently
     logged in user*/
   $user_page_object = user_load(arg(1));
?>
<div class="profile"<?php print $attributes; ?>>
   <?php print render($user_page_object->name); ?>
   <?php print render($user_page_object->signature); ?>
   <?php print render($user_page_object->timezone); ?>
   //and so on...

And to access additional fields you may have added you can drill into the $user_profile array which contains those fields. (Which would've been added here admin/config/people/accounts/fields).

I recommend using the devel module to kpr or dpm (I prefer kpr) to look into those two vars, ie:

<?php
kpr($user_page_object);
kpr($user_profile);
?>


What are the conditions for the "is one of" operator being enabled for filters on a particular field?

'Is one of' operator in views filter aka ORoperator in SQL, it is only available for list fields or fields with allowed values that means any field which has the select list, radio buttons, or checkboxes widget can have and use 'Is one of' operator in views filter.

Theoretically, any reference field or any list field should have 'Is one of' operator available in views filter.


Categorize Feeds with taxonomy terms automatically

If you add a term reference field to the feed node, you can map the value to the feed item node (inheriting values). The term can then be added when creating the feed node.


Drupal 7 check all solution for 2017, is it possible?

You want to create a custom module for this

my_module.module

function my_module_form_node_form_alter(&$form,&$form_state,$form_id) {
     if($form['#node']->type == "my_content_type") {
        $form['#attached']['js'][] = array(
          'data' => drupal_get_path('module', 'my_module') . '/js/example.js',
          'type' => 'file',
        );
     }
}

Change all my_module to the actual name of your module
Change my_content_type to the actual name of your content type.

my_module/js/example.js  (using code from the link you gave)

(function ($) {
    Drupal.behaviors.selectAll = {
      attach: function (context, settings) {
        $('body.page-node .form-type-checkboxes > label').click(function() {
            $(this).nextAll('.form-checkboxes').find('input[type="checkbox"]').trigger('click');
        });
      }
    };
}(jQuery));

If it doesn't work, try changing the line

$(this).nextAll('.form-checkboxes').find('input[type="checkbox"]').trigger('click');

to

$(this).nextAll('input:checkbox').trigger('click');


Caching Views: Query results Vs Rendered Output

First some explanations:

Caching your query results, means you store the results. So the next page load you don't have to perform your heavy time consuming SQL query again.

Caching the rendered output means you cache the generated HTML output; the system does not have to render the page again.

It would make sense to have most of these exipire at the same time,  after all, if the data changes, you'd want to show the changes to the user.

The only situation I can think of to cache the query results longer than the SQL data, is in a situation where the template file changes very often. Your theme might for instace randomly change the color of each table row, or show the current time (provided via a theme variable and a preprocess function) on the display. You might want to keep this out of the cache to give the user the impression the data is current, while still being able to serve the page relatively fast.

Caching the rendered output longer than the query seems like a bad idea. You'd be performing the resource intensive SQL query for new data, yet discard the data directly because you choose to display the old data instead. So I'd recommend against doing that.


Rewriting image output in views: how to provide replacement pattern inside twig tag?

Remove quotes.
Remove wiggly brackets around.
Surround image_responsive_style by quote.
responsive=true Should passed as object:

    {{ drupal_image(uri , 'image_responsive_style', {responsive: true}) }}


you could set it to language neutral and allow both content in the selected language and language neutral to be shown


I was playing with configs and finally found a solution. The configs should be:

langcode: en
more_info_text: 'More info'
first_link_list:
  format: 'full_html'
  value: ''
second_link_list:
  format: 'full_html'
  value: ''
third_link_list:
  format: 'full_html'
  value: ''

And the scheme file should not contain the following line

class: '\Drupal\Core\TypedData\Plugin\DataType\StringData'

Another thing I noticed is that you should translate the whole custom form, otherwise it will give an error at config inspector, so in my case I had to split my form into general and language specific.

Hope this helps somebody


Yes. The patch needs to be placed inside the media_entity_image folder alongside the media_entity_image.info.yml file. And then you should be able to execute

patch -p0 < media_entity_image_thumbnail_problem_2767501_13.patch

without any issue.

If you are using composer- I would highly encourage you to use the cweagans/composer-patches composer package. Details at https://groups.drupal.org/node/518975


How to stop download in hook_file_download

I have this to check that the users has remaining downloads or redirect them to an upgrade page.

/**
 * Implements hook_file_download().
 */
function mymodule_file_download($uri) {
  // Check if user is logged in
  if (\Drupal::currentUser()->isAuthenticated()) {
    // Load entity of current user
    $current_user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    // Check if current user is: access || student || (professional && trial_actived)
    $download_control = $current_user->hasRole('professional') && $current_user->field_user_free_trial->value == 'trial_actived' ? TRUE : FALSE;
    $download_control = $download_control || $current_user->hasRole('access') || $current_user->hasRole('student') ? TRUE : FALSE;

if ($download_control) {

  // Declare files that decrease the counter
  $controlled_uris = [
    'private://mechanisms/files',
  ];

  // Check if requested uri matches with controlled uris
  foreach ($controlled_uris as $c_uri) {
    if (strpos($uri, $c_uri) !== FALSE) {

      // Check if user still has remaining downloads
      if ($current_user->field_user_download_counter->value > 0) {

        // Decrease user downloads counter
        $current_user->field_user_download_counter->value--;
        $current_user->save();
      }
      else {
        // Prepare redirect url to the prices page
        $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 39])->toString();

        // Set message
        $message = t('Your account has reached the maximum limit of downloads.');
        \Drupal::messenger()->addWarning($message);

        // Send response to url
        $response = new \Symfony\Component\HttpFoundation\RedirectResponse($url);
        $response->send();
      }
    }
  }
}
  }
}


How can I limit the exposed filters to only display values for which content exists?

This works for me:

function mymodule_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (isset($form['tid']['#options'])) {
    foreach ($form['tid']['#options'] as $key => $value) {
      // Limit to numeric keys to exclude the 'All' option.
      if (is_numeric($key)) {
        // Start database query.
        $query = \Drupal::database()->select('taxonomy_index', 'ti');
        $query->fields('ti', ['nid']);
        $query->condition('ti.tid', $key);
        $nodes = $query->execute()->fetchAssoc();
        // Remove option if term has no instance.
        if (!$nodes) {
          unset($form['tid']['#options'][$key]);
        }
      }
    }
  }
}

You will probably need to adjust the 'tid' in $form['tid']['#options'] to the Filter identifier as defined in your views' filter settings.
Credits for the quick and efficient database query go to https://drupal.stackexchange.com/a/219368/25154.


You should implement hook_permission.
Then you will be able to add custom permissions to view, edit and delete for your custom form.

Nice tip I'm using myself with Drupal is to open the code of one of Drupal's core/contrib modules that implements the same thing you need and learn how it was implemented there.


How to remove form elements before submitting the form?

There are two ways, actually:

Wrap them into a proper modules. You will avoid conflict with Form API by cooperating with it. See Datepicker's code to get idea how to do it.
Create onsubmit javascript event and remove elements with jQuery.


Difference between #type and #theme in Render API

The purpose is a little different:

'#type' is telling to the render API to merge what returned from hook_element_info()
'#theme' is saying to the render API which theme function to use

In the example you are making, the theme function used is theme_html_tag() because system_element_info() returns the following data.

  $types['html_tag'] = array(
    '#theme' => 'html_tag',
    '#pre_render' => array('drupal_pre_render_conditional_comments'),
    '#attributes' => array(),
    '#value' => NULL,
  );

If '#theme' were set to 'tag_html', theme_tag_html() would be the theme used by the render API.


How to install a taxonomy system that represents records in another high-volume, non-content-node table?

You don't specify Drupal 6 or 7. If you can, use 7. Then you can do the following

Have your content (gossip posts), as
nodes.
Put your celebrity names as taxonomy terms
Apply whatever fields you like directly to the taxonomy term. No need for attached nodes or custom content.

There are several auto tagging modules out there, Open Calais is free and would suit your needs. You could even just use the 'Person' results from it to only tag celebrities.

Drupal 6, did have some issues with very large taxonomies (over 100,000 terms and 2,000,000 individual tags). D7 has sorted most of these, so it is unlikely that you will have to go down the custom code route.

If you do you will not only need to sidestep the node system, but also the taxonomy system and mysql, so it is not as easy as creating a custom table.


How can I add a class to a link output via a form?

Take a look at the l() function:

l(t('link_text'), 'path', array('attributes' => array('class' => array('your_class'), 'id' => 'your_id')));


How to tell if the current revision is the original?

NodeStorage::revisionIds() will let you retrieve all revisions of a node which will let you compare against the current node's version.

 // Retrieve all vids.
 $nid = 123;
 $node = Drupal\node\Entity\Node::load($nid);
 $vids = \Drupal::entityTypeManager()->getStorage('node')->revisionIds($node);

 // Does the original node's vid match the current node's vid?
 return (reset($vids) == $node->vid->getString());


As a site builder, how can I learn when modules I use are (going to be) deprecated?

You could subscribe with RSS to tag data on projects such as:

Maintenance status: Unsupported
Development status: No further development

That can give you notice of deprecation assuming the relevant tag has been assigned to the project.


7 - Sorting in a view seems to not be alphabetical?

Since the course field is an entity reference the sort would be working on the node id and not the node name. can you check this.

What you could do is add the node title instead of the node entity field. and create a relationship to the node title to the entity reference field. Now the sort should work properly.

EDIT : Adding the steps mentioned in comment

Add Content:Title to the view.
Go to advanced, add a relationship to the content type.
Go back to that title field configuration and select the relationship from the drop down.
Go the the format settings and make the new field sortable.


You may have to create a custom rule if the profile2 fields are not available individually.

This guide is a good example on how to make a custom events, conditions, and actions for rules.

If you have any questions about the guide feel free to ask.


How create a file type field in custom entity programmatically?

The only way i have found is to move this param into the Entityform :

  $form['fid'] = array(
      '#type' => 'managed_file',
      '#upload_location' => 'public://produits/',
      '#default_value' => $entity->get('fid')->value,
      '#description' => t('png jpge jpg'),
      '#upload_validators' => array(
          'file_validate_extensions' => array('png jpg jpeg'),
      )
  );


The Views PHP Module provides a custome field that is click sort enabled

Value code example:

....
$result = db_fetch_object(db_query("SELECT stamp FROM {workflow_node_history} WHERE nid = %d AND sid = %d", $row->nid, $sid));
if(isset($result->stamp)) {
   return $result->stamp;
}
return 0;

Output code:

<?php
print date('d.m.Y', $value);
?>

Enable click sort: sort numerically


How to load translated entity values in Twig for SEO purpose?

You can get the translated node with getTranslation():

{% if node.hastranslation('en') %}

{{ node.translation('en').title.value }}

{% else %}

No translation

{% endif %}

If you are not sure that the translation exists, check first with hasTranslation(), because a missing translation throws an exception.


How do I query a content type with custom fields in the 'condition' statement

You'd be better off using an EntityFieldQuery for this:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'myContentType')
  ->propertyCondition('status', 1) // in case you need it
  ->fieldCondition('field_customfield3', 'value', $user->uid)
  ->fieldCondition('field_customfield4', 'value', $anemailaddress);

$results = $query->execute();

if (isset($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  foreach ($nodes as $node) {
    $customerfield1 = field_get_items('node', $node, 'field_customerfield1');
    $first_value = $customerfield1[0]['value'];

    // etc...
  }
}

Even though it's more code, and more overhead, it has advantages over going into the database tables directly.

You don't need to make the JOINs yourself
EntityFieldQuery respects node revisions, which will be harder to keep track of well using a custom query
Your code is now portable if you decide to change the storage backend for fields to something other than MySQL (MongoDB for example).


See the Rename Admin Paths module. The purpose of this module is to secure drupal backend by overriding admin path. You can change user/login to something like member/login.
I would also suggest adding a redirect in your htaccess to the standard user/login user/register. This way Drupal doesn't also have to serve up the 404 when a bot tries to access those pages. Huge performance savings.

EDIT: Thinking about this further, you don't need an extra module at all. Just add an alias at /admin/config/search/path/add for user/login, user/register etc, then just add redirects in your htaccess for the old aliases.


Fatal error: Call to undefined function field_create_instance()

Just to update this question, if anyone else comes across this - I worked out the solution in the end. Rather than implementing the hook_install() function I added the field information to the config/install/ folder which adds the necessary user fields instead.


Views taxonomy listing of terms linked via contextual path

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

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

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

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


Creating a vanilla instance from a site already set up

There are 2 easy options:

Use the Delete All Module and it's Drush interface.
If that's not thorough enough, I typically just end up using an SQL script to set foreign key checks to 0; and then truncate all fields, cache, revision, users, user_roles ... etc tables specific to my site. While it seems like alot of work it's basically a 1 time audit of the underlying DB for the script creation and simply tracking what new tables are needed for wiping when you add new modules. I've then used Rules_Link and the php filter to make this SQL statements runnable via a button press from a displaysuite panel ...


How do I change a product variaton through an image field?

Try using Commerce Fancy Attributes along with Field Extractor Module

This module provides:

A formatter for reference fields
A views field for reference fields (called "Field extracted from entity referenced through $field")

This module uses field_view_field hook

  Returns a renderable array for the value of a single field in an
  entity.

  The resulting output is a fully themed field with label and multiple
  values.


Filter criteria not working on new field because data table is not storing data

Okay, I figured it out. We have the workbench module installed on this site for multi-stage moderation, and the node I was editing was not the published version of the draft :þ


the payments usually are done in the same session then the checkout and has to be done by the user.

some gateways allow batch processing of payments, maybe try another payment gateway ?

or change your business logic. refunding is easier in most gateways ;)
so the user pays, but gets refunded, if the order is not processed after X days.


Any idea why view->field is empty when executing a view returning user emails?

If anyone else sees this it is because view does a checkAccess before adding the field during preExecute. Since it is the mail field there is no other way to allow access to that field unless you give administer users. But, there is a patch coming out that introduces a mail field access permission.
https://drupal.org/project/drupal/issues/2799049
With patch and permission set everything works.


Load a view block into a custom page generated in a module

Just like in D7, using views_embed_view.

print views_embed_view('view_name','machine_name', $parameter);

In case you are wondering, this is the machine_name

Example:

$parameter = 1;
print views_embed_view('hello_world','block_1', $parameter);


Categorised Multiple File uploads within a page in Drupal 7

Assuming you want all of these attached to one node and the categories need to be dynamic, I'd use field collections where each category is a field collection item which has a title field and a multi value file field.


A view only shows if a certain filter criteria does not exist?

Under the advanced tab you can define "No Results Behavior".  This will allow you to add a view or html instead.  This will be in the same view.


listing page in breadcrumb of single item

(EDIT)
Drupal core will build breadcrumbs based on the menu structure. So if you manage to create a menu link for each of your activities, then Drupal core has you covered (see the answer by General Redneck).
If you don't want a new menu link per activity node, then you can use Path breadcrumbs or Crumbs, see below.
(/EDIT)

There are different modules that can help you with breadcrumbs, and I am sure more than one of them can help with this particular issue.

One of them is Crumbs. If you choose this, here are some steps for configuration (after enabling the module):

Go to admin/structure/crumbs/entity-parent, and specify the views page as the parent path for the node type of your choice.
On admin/structure/menu, edit the main menu (or another menu), create an item that links to the views page, and give it a title like "Activities". (*)
On admin/structure/crumbs, make sure that the menu.link_title.main-menu and menu.hierarchy.main-menu are enabled. Or just enable menu.*.
(enabling means to move those lines up into the "Enabled" section with drag+drop)
To see what going on behind the scenes, you can visit admin/structure/crumbs/debug.

(*) Creating the menu item is one option you have so that Crumbs can determine a title for the breadcrumb item that points to the activities view. There are other ways, but this is the most straightforward, and you probably want to create this menu link anyway.


Features - Is there a way to push changes back into the database

Once the module generated by Features has been activated and the status on the overview page reads "Default" the changes are in the database. "Default" means that the database configuration matches the configuration defined in the module. (The status "overridden" indicates that the module generated by Features does not match the database configuration.

I think what you want to ask is, "How can I disable a Feature-generated module without losing the configuration that it provided?", which has been asked on this site before.


Programmatically set the number of Multiple Value CCK fields in node edit form

Use template.php and override the form functions and apply your logic there before rendering the form.
Example override function

/* Overiding the question creation form */

function yourthemename_question_node_form($form) {
//  dsm($form);
  // Modify title text
  unset($form['title']['#title']);
  // Set a default value for the title field
    // Set a default value for the title field
  $title_value =   $form['title']['#value'];
  if($title_value ==''){
  $form['title']['#value'] = t('Enter Title Here');
}
  else { }
  $form['title']['#attributes'] = array(
       'onblur' => "if (this.value == '') {this.value = '".$form['title']['#value']."';} this.style.color = '#333333';",
         'onfocus' => "if (this.value == '".$form['title']['#value']."') {this.value = '';} this.style.color = '#333333';" );
  $title = drupal_render($form['title']);
  $body = drupal_render($form['body_field']['body']);
  $form['body_field']['format']['#collapsed'] = FALSE;
  $form['body_field']['format']['#collapsible'] = FALSE;
  $form['body_field']['format']['#title'] = NULL;
  $body_filter = drupal_render($form['body_field']['format']);
  $tags = drupal_render($form['taxonomy']['tags']);
  $thematic_areas = drupal_render($form['taxonomy']['47']);
  $buttons = drupal_render($form['buttons']);
  $remaining_form = drupal_render($form);
    return '

'.$title.'
'.'
'.$body.'
'.$body_filter.'

'.$remaining_form.''.'	'.$thematic_areas.$tags.'
'.$buttons.'
'."

";
}


How can I limit the number of chars/words in a long text field to 3000?


Without more information on the issue, there could be a lot of causes for this. For example, most emails are sent when cron runs, is cron set to run periodically?

Are you able to see your logs on the site?

If so, are there errors associated with email not being sent (Go to http://your-site-url/#overlay=admin/reports and select recent log messages)? Is your server configured to sent emails?

Some error logs are found on your /etc/httpd/logs/error_log folder, looking there would be helpful too while you try and submit a form to see what gets logged.

As I mention above, more info perhaps can help us troubleshoot it.

Hope this helps.


No problem, yeah when you see an error page like that, most of time the issue is in one of the template files.


How to render a contact form as rendered entity

Use https://www.drupal.org/project/contact_storage.

It provides a view builder for contact forms that displays the form.

It also results in contact messages being stored, among many other optional features. If you do not want that, then you can re-use the code from it for the view builder and add it yourself.


In Simpletest each time the test is run. New Drupal install will occur. You are testing the Simpletest Database right now. There is a possibility to run simpletest on "live" db. To do so add $this->originalPrefix = $GLOBALS['db_prefix'] to your setUp()


What url do you use to access this Drupal site? I notice that drush reports Site URI as http://default. This is not necessarily a problem (I have multiple working sites running on a MAMP server, and this is what they report too), but what do you get if you re-run the command with the --uri flag?

drush pmi --url=example.local

If that does make things work, you can create a drush alias file as shown below and use drush @example pmi to run commands:

$aliases['dev'] = array(
  'root' => '/path/to/example.local',
  'uri' => 'example.local',
);

For the record though, I've never needed to do this when using MAMP--but I do create virtual host records for all local development sites so that may be a factor.


New content pane (in view) not showing up for adding to panel

Turns out you have to save prior changes to the panel in question. In the list of panels you'll see a padlock icon and a hover-caption of "you have locked this panel, until you save these changes."

Once you save the panel in question, you'll see new content panes that you've created in a View.


Custom Drupal breadcrumbs - how to disable the last item

To answer my own question:
The last link should point to route name '<none>' and that removes the href attribute from the item. So after all super easy.

// untested
foreach($prepared_data as $data) {
  $links[] = $is_last_link($data)
     ? Link::createFromRoute($page_title, '<none>')
     : Link::fromTextAndUrl($page_title, Url::fromUserInput());
  }

Related:
It appears Drupal 8 core does not provide the current page in the breadcrumbs.
The contributed module Easy Breadcrumbs does this for D7. The D8 version is in still in sandbox.
Reference: Blog post.


Take a look at

Modal Forms (with ctools)
Colorbox
Lightbox2

to name a few.  There are probably more out there, but one of those should do what you want.


Views and how to get calendar taxonomy legend

To see an option in the term field as above (e.g. field_event_type) make sure you add the Taxonomy field to your view and select Create a label in the Configure Field options. The label you create will then appear in the term field. If you do this with multiple term fields that are added to the view you can use the drop down to select.

Not sure at this stage regarding the Legend option however.


Create custom form and store form data into database

Creating the module structure
The first step in creating the module is to create a folder for the module. You should put this in "sites/all/modules/{name of your module}." Keep in mind that whenever I say "{name of your module}," you should insert the name of your module. For example, we will use the module directory "sites/all/modules/form_example."

Now, create two empty text files called "{name of your module}.module" and "{name of your module}.info."

These two files are required by your module. The .info file contains information about what your module does, while the .module file contains the actual code including hooks. Hooks are functions with special names that will be called by Drupal when actions occur. For example "form_example_menu()" is called when menu information is gathered. In many examples, you will see names such as "hook_menu()" or "my_theme_menu()" and in these cases "my_theme" and "hook" should be replaced by the name of your module or theme.

Build the basic module files

Here is what we will put into the form_example.info file. This tells Drupal and users about your module.

core = "7.x"
description = "An example module used to learn module development and forms creation."
name = "Form Example Module"

There are more options that you can put in the .info file, but the ones above should be added.

Here is the start of our form_example.module file. This will create a very basic form that only has one field, a submit button.

<?php
function form_example_form($form, &$form_state) {

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}
?>

Note: Do not include the last "?>" part of the PHP code and leave a trailing blank line at the end of the file. This is the Drupal standard.

The module right now contains one function that will create a form. It is important to note that the function takes the inputs $form, and a reference &$form_state. This function will be called when Drupal tries to build the form "form_example_form."

The process for creating a form is mainly two steps. The first is to build an associative array $form that contains all the fields. The second step is to return that $form variable.

To add a field, you set the variable $form[{name of your field}] = array(); Each field can then have a number of attributes, such as "#type" and "#value." Most of these attributes are named with a proceeding "#" sign.

The field we added above is a submit button with the text "Click Here!" on the button. Note that t() will output text and is a Drupal function that plays nice with translation.

Now that we have a form, we need to add two more function: form_example_form_validate, and form_example_form_submit. These two functions are hook functions that will be called when Drupal validates the form and when it submits the form (assuming it validated).

form_example.module:

<?php
function form_example_form($form, &$form_state) {

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

You will note that these three functions take the same variables. $form is the original form information and can be seen as the original structure of the form. $form_state holds all of the submitted values as well as other information, some of which you can add yourself. These two functions need to named similar to the other form, but with "validate" and "submit" at the end.

We want to see the form!!! We will add a menu link to this form.

form.example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

Now enable your module and try to access the link. You will probably need to clear the cache.

Add more functionality to the form.

Now we will add one more field to the form.

form_example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

 $form['price'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Price?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );

$form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
    ),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

Here we have added a new textfield and made it required. We have also set the maximum length. You'll see if you try to submit the form, that Drupal will automatically produce an error for the user if they don't fill in the required fields. We will add some more validation in the next step.

Add validation

form_example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

 $form['price'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Price?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );

$form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
    ),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
  if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }
}
function

form_example_form_submit($form, &$form_state) {
}
?>

You will now see that the form will not submit unless price is a positive number. We do this by checking the value of price, in $form_state['values'][{name of your field}]. There are similar variables for all of your fields.

We then set an error with form_set_error. Adding this error will alert Drupal that the form did not pass validation.

What to do when your form is submitted?
From this point, you will want to either save the form data, send an email, or display some information. That is beyond the scope of this How To at this point.

I have built some module "tools" or "calculators" using the above method and included the calculation steps in the submit function. You can set the variable "$form_state['rebuild'] = TRUE;" in the submit function so that Drupal does not clear the form. You can therefore edit the $form_state to change a "markup" field type to have your output.

This can also be done with AJAX so that the form displays the calculated values without a page load. That gets a little more complicated and may be added as a separate How To.

Conclusions
Hopefully this is helpful for people interested in writing a module, or adding a form to a module.

Reference: How to Make a Simple Module with a Form and Menu Link


Best practice, removing admin access from many websites

Maybe you could use Drush for these operations, such as change passwords for admins ? Also to write a script with several drush commands, which would run via SSH console.

Unfontunately, I am not expert in writing these scripts, but I think that you should look in this direction.

For Drupal 8 another solution Drupal Console has been developed.

P.S. Drush and Drupal Console hardly work on virtual hosting. If you decide to use it, you will have to host your site on VPS as least.


Body field data not showing in View or Edit mode but exists in database

At this point, the issue seems to relate to language. Both live and dev have 'en' as the default language, but any new content on dev is being created as 'und', but as 'en' on live.

By way of a test, i copied the html from the db for one of the problem nodes, pasted it via Edit and saved, and the body then showed, but in the db it was flagged as being 'und'

BINGO - we had pulled a feature on to this site from another site. The other site had all fields set to 'not translatable' (field_config table).

On this 'inherited' site, some of the fields eg Body had been set to translatable, even though there were no other languages on the site.

And yes, the feature overrode the 'translate' setting in the db (there is no where to see this in the UI).

Setting body to '1' in the db has restored body being displayed, and some sanity.


You need to edit your page.tpl.php file, and add this where you have the <body> tag.

<body class="<?php
   print arg(0, request_path());
?>

This will print the first part of $_SERVER['REQUEST_URI'] delimited by a slash.
arg() and request_path() are Drupal functions.


Get tag(term) name for multiple nodes without a performance hit

If you're already looping over an array of nodes, have you considered collecting the term IDs before loading them in one query? That should save a lot of the overhead of running multiple queries:

$map = [];
$tids = [];

// Collect IDs for each node:
/** @var \Drupal\node\Entity\NodeInterface[] $nodes */
foreach ($nodes as $nid => $node) {
  /** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $item */
  foreach ($node->field_tags as $item) {
    $tid = $item->target_id;
    $map[$nid][$tid] = $tid;
    $tids[$tid] = $tid;
  }
}

// Load terms and collect their labels:
$term_labels = [];
/** @var \Drupal\taxonomy\Entity\TermInterface $term */
foreach (Term::loadMultiple($tids) as $tid => $term) {
  $term_labels[$tid] = $term->label();
}

// Assign the term labels to each node.
foreach ($map as $nid => $node_tids) {
  foreach ($node_tids as $tid) {
    $map[$nid][$tid] = $term_labels[$tid];
  }
}


This can sometimes happen if you are using softaculous installer (or similar one-click installer provided by your web host). Perhaps you installed several instances of Drupal using the same database name, and just left the 'dr_' prefix in place for one by accident.

If I were you, I wouldn't worry too much about it. Having the additional tables there won't cause any problems with your Drupal installation (the one using the non-prefixed tables), and the 'dr_' prefixed tables won't increase in size as time goes on.

You should be able to safely leave them as they are, or, if you want to, remove them using phpMyAdmin to permanently delete (drop) the tables prefixed with 'dr_'.


Views not respecting Contextual filter and Referenced Entity relationship

I think you want a View of basic pages (meaning filtered down to Content Type = Basic page) with a contextual filter narrowing down to the current Basic page using the Content ID (NID). Then add in a relationship to Spotlight through the entity reference field. And then for your three fields, make them use the Spotlight relationship.


Why do you need the .pdf part in the hook menu?  Can't you just perform a check on the arg() function in your _pdf_get function to ensure that the argument contains ".pdf" and if not, redirects the user to the url with ".pdf" appended?


Selecting the right pattern for adding in robots.txt

Adding the line you suggest to you site's robots.txt will stop googlebot from crawling the URLs that contain this string.

However, what attributes modules add to the URL is up to the module.  You need to examine the source code of the modules you use to avoid any conflict. I doubt there is anyone here with encyclopedic knowledge of what attributes every module use (there are more than 20000 on Drupal.org).

Instead of searching through modules for possible conflicts, I would invent a "magic" string that is pretty much guaranteed to be unique or not used for any other purpose by a Drupal module (e.g. "dontcrawlme") and add that "magic" string to the path to the views I don't want crawled, or add a dummy attribute with "magic" string as name to those views, then Disallow any crawling of an URL containing the "magic" string. This is simpler and more robust than relying on sort_order= being unique for exposed filters in Views.

You need to take care not to overwrite your custom additions to robots.txt when you do a minor upgrade of the Drupal core.

Note that wildcards is not part of the Robot Exclusion Standards (but are supported by googlebot and bing), so don't expect any rule with wildcards to be widely recognised by robots.


How can I flag content programmatically?

Here's how to flag or unflag an entity programmatically, using the Flag service.

$flag_id = 'bookmark';

$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);

// Flag an entity with a specific flag.
$flag_service->flag($flag, $entity);

// Unflag an entity with a specific flag.
$flag_service->unflag($flag, $entity);


How to remove duplicate results from views block?

For anyone else looking for a Drupal 8 solution for Views Distinct, I was able to get this to work by creating a custom module with MY_MODULE.views_execution.inc file with this code:

<?php

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_render().
 */
function MY_MODULE_views_pre_render(Drupal\views\ViewExecutable $view) {
  $unique_uuids = $new_view_result = [];
  $new_row_index = 0;

  // Loop through results and filter out duplicate results.
  foreach ($view->result as $row) {
    // Use UUID so this works for all entities
    $uuid = $row->_entity->uuid();

    if (!in_array($uuid, $unique_uuids)) {
      $row->index = $new_row_index;
      $new_view_result[] = $row;
      $unique_uuids[] = $uuid;
      $new_row_index++;
    }
  }

  // Replace $view->result with new array. Apparently views requires sequentially keyed
  // array of results instead of skipping keys (e.g. 0, 2, 4, etc), so we can't just
  // unset the duplicates.
  $view->result = $new_view_result;

  // Update the view index to match the new number of rows.
  $view->total_rows = $new_row_index;
}


In Drupal, how can I set a role to allow/deny user account requests but not be able to change User 1's password?

User protect: protects specific fields of users from being edited.
Administer Users by Role: lets you decide which roles a user can edit. Assign a dummy role to the admin user and give permissions for every other role.

First one says it is complicated, second one may be a pitfall if you add new roles but don't give access to edit them.


Blocks created using multiblock module are not working

I checked your site out specifically the footer area as you've instructed. This is not the module's issue but a Bootstrap/theming issue. Notice in the screenshot:

The block-9 block is using the col-md-12 which spans the whole content area and covering everything under it that's why the links aren't clickable.

I tested and just changed col-md-12 into col-md-2 and now the links are clickable.

Please check your markup and CSS to confirm.


Unable to set Singularity grid total to 16

Make sure that you aren't overwriting your grids variable.  I believe that by default, it's overwritten when the browser reaches the $tab size via: $grids: add-grid(12 at $tab); so searching for that line would be a start.

To help visualize your grid, singularitygs has the @include background-grid($color: blue); option that might be helpful while testing.

Lastly, you can always set your grids on the fly with a 3rd argument in your grid-span calls.  For example:

// Override the default $grids variable to use 16 grids
@include grid-span(16, 1, 16);


How to Translate Content type name using i18n module?

First, I must point out that if all you want is a single language non-English website you should not install the Internationalization project, and not enable the Multilingual content module (part of the Internationalization project).

If you have this problem with a single-language non-English web-site, all you need to enable the Locale module (part of core) and enable the Localization update module.  See the first part of this answer to see how to deal with this if you've a problem with content type names not being translated on a single language non-English website.

However, if you're creating a multi-language website where the user interface and the content shall be in multiple languages (due to various detection and selection strategies), then you need to install a project named Internationalization and enable several of its sub-modules, including one named Multilingual content.

However: Do not do this if all you want is to have the the site user interface and its content in a single language that is not English.  The Internationalization project is (IMHO) hard do configure correctly, and still have some serious bugs unfixed. Do not install it unless it is absolutely required.

If you need a multi-language website and you've configured it and you've configured the language settings and already set another default language than English, then the names of content types will not be translated by default, even if the translations for the names of these types are already present in the translated strings listed for the built-in interface.

When you enable the Multilingual content module, a column named Node types will appear in the translate interface overview (if this column do not appear, then the Multilingual content module is not enabled).  For  the names of the content types to appear, you ned to have these translated in the text group Node types as well.  The recipe below tells you how to do this.

I really think this is a bug in the Internationalization module, and as such is off-topic here.  See  Translate interface for nodes, fields, etc. show wrong language in the column for the issue.

However, I was able to get the node types translated at my site by doing the following:

First, I made sure that I installed the Internationalization module and all the required helper modules (such as Multilingual content) before I added any languages.  I also made sure that I used English as the default language all the way during the translation process.

So you do the following with English as the only language enabled (if you've got additional languages enabled, uninstall them, you will also need to disable and uninstall the Internationalization module and all its helper modules to get a clean start):

Download and install the Internationalization project.
Enable the Multilingual content module (part of the Internationalization project).

Then add any additional languages you want, but do not enable them.  This is supposed to add translations for the Built-in interface and Node types. However, to me it looks as if the translations for text group Node types is not automatically imported when you enable a new language after you enable Multilingual content.

You can confirm this by looking under the "Overview" tab of the translation interface:

If the percentage in the "Node types" for your second language is ("Norwegian Bokmål" in the image above) is 0%, the translated strings for the Node types has not been imported into the translation interface.  This means that even after you enable that language, the fallback English strings will be used.

However, it should now be possible to add these translation by hand.  Navigate to the translate tab of the translation interface, and limit search to Node types.

The strikethrough over the string with the two letters in the Languages column means that the translation is missing.  Click "edit" to add the missing translation.

This exact procedure fixed it for me as can be seen from the "Overview" tab below.  The percentage for "Node types" for "Norwegian Bokmål" in now 100%.

After doing all the above, it is OK to set a non-English language as default.


Custom module's output is not wrapped in the site theme

What would help is the code for the mymodule_display() function. However, it sounds like you are printing the output in the function instead of returning it.

Blank page:

/**
 * Creates a blank page with only the module output.
 */
function mymodule_display() {
  print 'Module content';
}

Themed page:

/**
 * Output the content in the main content area of active theme.
 */
function mymodule_display() {
  return 'Module content';
}


How to display a message on login until a user fills out a specific Webform?

I think the module you are looking for is 'Rules Webform Submitted'.

This module is similar to Webform Rules in that it supports integration between Webform and Rules, but different in that Webform Rules supports the Event "Webform Submitted", while Rules Webform Submitted provides a Condition which is typically triggered by a Node Event.

So, you can use the event 'On user login' and the condition that 'Rules Webform Submitted' offers to create your rule.


What is the best choice to create a node through code?

The safest method is to use drupal_form_submit(). If you take at look at the services module it does the same thing. Form validation should be important if you are creating nodes programmatically. Are you importing or creating multiple nodes at once? If this is the case and you are concerned about performance you can use Drupal's batch api or queue. Batch is great if you need user feedback but if you are creating nodes on cron and don't require a ui with feedback then queue is the way to go. In both cases they take care of memory management for you.

I wouldn't be to concerned about how long it takes to create one node as that is how long it would take with the ui. Unless the reason you are doing it through codes is to increase creation times.


Custom Entity's Custom Fields doesn't show in when trying to Add Field in Views

I ran into this just today. Turns out you shouldn't set data_table in the entity type annotation if translatable is FALSE. Otherwise views associates all of the fields with the data_table, but data_table is never associated with base_table due to translations being disabled.


How to use taxonomy fields with Views and avoid duplicates?

I don't know if this will help, but it seems similar. (Drupal is still pretty confusing to me, so I am sorry if this is not helpful.)

I eliminated duplicate rows in my view by changing the filter criteria. I could filter with two different criteria and get the same view, but one view had duplicates and one didn't.

The filter criterion that gave me duplicates was "Content: Producer_category (taxonomy vocabulary 5)."  Producer_category is the name of a field. With this filter, if the content had multiple terms of the vocabulary applied, it appeared multiple times.

The filter that worked was "Content: has taxonomy term". After choosing this, I was prompted to select a vocabulary, and then to select term(s). I used the dropdown to display the terms. Also, Since I only selected one term for my display, i did NOT check "reduce duplicates", but I guess if you choose multiple terms you should.

Also, FYI, I was getting multiple errors when using Views since updating to Drupal 7, and I figure I probably did something wrong in the update process; all my Fields disappeared, among other things. So I ended up re-building the View from scratch. It seems like there are a bunch of new settings and options, and my view had some old, obsolete settings, and it just seemed better to start over and eliminate any hidden errors.

Good luck.


importing XML file with drupal 6 nodes to drupal 7

You're best bet would be to download a views data export from drupal 7 and one from drupal 6 and find the difference (it is easiest if the drupal 7 and drupal 6 contain the same data). Then find a way to convert one to the other, either using PHP to transfer all the data into an array then output in the required format or maybe it's as easy as just a few small changes.

Sadly there is no views data export drupal 6 to drupal 7 conversation module.


Since taxonomy terms are entities, you can simply do this:

$link = $term->toLink();
$breadcrumb->addLink($link);

As a side-note, the route name for taxonomy terms is "entity.taxonomy_term.canonical".


Replace username with unique hash when users delete their own accounts

You can use hook_user_cancel() like below:

  /**
   * Implements hook_user_cancel()
   */
    function example_user_cancel($edit, $account, $method) {
      // Define in which method you are canceling the account, else remove it and
      // proceed with below code by removing this if condition.
      if ($method == 'user_cancel_block') {
        $user_load = user_load($account->uid);
        $user_load->name = 'anonymous-'.time();// Here you can add your random number.
        user_save($user_load);
      }
    }


How to limit entity and/or field translation permissions to selected languages only?

Interesting (valid!) question. But to my knowledge, and assuming this is for D7 (not D8), this is NOT possible ... yet.

Refer to (active) issue # 1829630 for more details, which also references (fixed) issue # 1807776 related to D8 (and contains a lot of interesting details ...).


Exposed Filter not shown in view which has a Custom Filter Handler

I would do this by adding a contextual filter, previously called an argument in D6 Views. You can set contextual filters / arguments in code when you embed a view. So, you could add a contextual filter for field_labpoints (not sure what kind of field this is) and pass along the argument you want to filter for when you embed the View in a .tpl file or a panel or whatever:

print views_embed_view('my_view_name', 'block_1', $labpoints_value);

This allows you to make the View more dynamic without tinkering with the existing filters.


Updating a modified image file across entities using it

The image width and height are stored in the field tables (field_data_FIELD_NAME/field_revision_FIELD_NAME), in the FIELD_NAME_height and FIELD_NAME_width columns.

If you know the file id (fid) of the file you need to change the data for, and the width and height of your new image, you can just run the following queries against the database:

UPDATE field_data_FIELD_NAME
SET FIELD_NAME_width = WIDTH, FIELD_NAME_HEIGHT = HEIGHT
WHERE FIELD_NAME_fid = FID

UPDATE field_revision_FIELD_NAME
SET FIELD_NAME_width = WIDTH, FIELD_NAME_HEIGHT = HEIGHT
WHERE FIELD_NAME_fid = FID


Seller and Buyers Own Comments (Commerce Communicae)

Have you tried commerce_message? In Kickstart 2, we created an order commenting system, where buyers and sellers could leave messages for each other and the system could also leave notes about the history.


How to re-add deleted articles using the same node ids?

It really depends on the amount of data you have at hand. If the missing nodes have simple structure with only default body field,title, none or just a few custom fields, then 40 is not that big number to sweat over the code, so I would do it via database UI as phpMyAdmin. Just note other involved tables like node_revision and custom field tables if nodes had ones.

However, if the missing nodes have multiple fields and too much data to enter manually, then I would create and upload data to 40 new nodes iterating:

$entity = entity_create('node', $values);
$service_wrapper = entity_metadata_wrapper('node', $entity);
$service_wrapper->title->set($product->title);
$service_wrapper->field_custom_field_1->set($data_1);
$service_wrapper->field_custom_field_2->set($data_2);
$service_wrapper->field_custom_field_N->set($data_N);
$service_wrapper->save();

Then I would replace nids either manually in nodes and node_revision tables or by saving the missing nids in form of $nids = array(0 => 'first nid', 1 => 'second nid, 2 => '2nd nid', n => 'so forth') and then iterating them through foreach loop in custom module's function.


Dynamic "My Account" text in navigation menu

Drupal caches menu items, so if you're using hook_menu_alter you'll need to clear the menu cache to make your changes apparent.  For your requirements, hook_menu_alter is no good anyway, as the menu has become dynamic!

My suggestion would be to use Menu Per Role.  Create one menu that has each of your required menu titles in as seperate menu items (ie one menu containing three menu items; one for each type of account) and then restrict the visibility of those menu items to users with particular roles.

eg

My Account Links

My Account - only visible to standard users
My Guest Account - only visible to guest account holders
My Premium account - only visible to premium account holders

When set up correctly, this will only display one link per user (although when logged in as user 1 you will see all links).


Is it acceptable to modify Drupal's composer.json file?

It is possible to consume Drupal 8 into your own composer.json file:

{
    "name": "davidbarratt/mydrupalproject",
    "require": {
        "drupal/drupal": "8.*"
        "composer/installers": "1.*"
    },
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "drupal/drupal",
                "type": "drupal-core",
                "version": "8.0.0-dev",
                "source": {
                    "url": "http://git.drupal.org/project/drupal.git",
                    "type": "git",
                    "reference": "8.x"
                }
            }
        }
    ],
    "minimum-stability": "dev"
}

There's a pull request to composer/installerswill allow installation of drupal-core project types:
http://github.com/composer/installers/pull/38

Would love your input on the above pull request, as well as this other one in the queue that allows installation of modules/themes/profiles.

Another solution that currently works is the Composer Manager module, which facilitates composer.json use for modules. It's currently available for Drupal 7, and will be available for Drupal 8 once the Drupal 8 alpha releases are close.

Thanks a lot,
Rob


How do I change my site time to test my recurring payments?

If you are working with 5.3+ you can do a trick with namespaces: implementing a new time() function inside your current namespace and create a shared resource where you set the return value in your tests.

You can found a complete description in this blog post:

PHP: “Mocking” built-in functions like time() in Unit Tests


I ended up solving the problem by using hook_node_insert:

/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {

  // Only act if we are dealing with a content type supporting translations.

  if (translation_supported_type($node->type)) {

    if ($node->tnid != $node->nid) {

      $sql = "INSERT INTO node_field( nid, type ,title ,machine_name ,show_title ,hidden ,value ,weight ,settings)
          SELECT :new_node, type, title, machine_name, show_title, hidden, value, weight, settings
          FROM node_field
          WHERE nid=:old_node";

      db_query($sql, array(':new_node' => $node->nid, ':old_node' => $node->tnid));
    }
  }
}


Make phone field required if certain shipping method is selected

You will have two functions in your custom module. The first one is hook_form_FORM_ID_alter:

/**
 * This function adds an additional custom validation function to the delivery phone field
 *
 * Make sure you update MYMODULE and YOURFORMID to match your circumstances.
 */
function MYMODULE_form_YOURFORMID_alter(&$form, &$form_state) {
  $form['panes']['delivery']['delivery_phone']['#element_validate'] = array('MYMODULE_phone_validate');
}

The second function is the custom validation function that we added using hook_form_FORM_ID_alter above:

/**
 * Make sure you update MYMODULE again and update the array to match your shipping method
 */
function MYMODULE_phone_validate($element, &$form_state) {
  if (($form_state['panes']['shipping']['shipping_method']['#value'] == 'THE SHIPPING METHOD') && ($element['#value'] == '')) {
    form_error($element, t('You must enter a phone number if you select XXX as a shipping method.'));
  }
}


It sounds like you want to store the file in Drupal's private file system.  There is no need for a module - this is in core.
Files that are in the private system will:

Be protected from access by Drupal's core access control system. If the user don't have access to the page where the file field is attached, he/she will not have access to  the file.
The URL will not be generally usable. (i.e. the link will be displayed in the browser's  address field, but only works "inside" Drupal).
If you place your private files outside the webroot (strongly recommended), they can only be accessed through Drupal's access control system. There is no real URL that can be guessed.

There is plenty of tutorials about setting up and using a private file system in Drupal [GIYF].  Here is a link to one example:
https://www.cmsdrupal.com/blog/how-secure-private-files-drupal-tips-safely-configuring-your-file-system


How to change core search result snippet?

You could build your own search result .tpl file inside your theme and take control over what displayed and the markup by creating a file named like search-results--[searchType].tpl.php After that you have to clear the cache in order to be recognized in theme registry

In your case you could limit the number of words displayed or divide based on empty line which mean a pragraph.

Take a look at D7 theme suggestions


It seems you are connected to page rendering process. Images are created with separate php calls, one for each image. If you want to connect to image generation call, disable retrieving images in your browser, load HTML, get image url with safety token and hit it directly, debugging.


Custom function doesn't get triggered by hook_cron()

Can you change:

function _my_custom_function() {
    // Define fields
    $fields  = array('field1', 'field2', 'field3');
    // Trigger Batch for import
    batch_set(_start_my_batch('myfile', 'mytable', $fields));
}

Into

function _my_custom_function() {
    // Define fields
    $fields  = array('field1', 'field2', 'field3');
    $function = '_start_my_batch';
    $batch = $function('myfile', 'mytable', $fields);
    // Trigger Batch for import
    batch_set($batch);
}

I think you should check every functions separately (hook_cron, batch function..) and make sure they work. After that put on the same place and play. The Example Module also is the very good place for doing this kind of stuff.


How to use use db_rewrite_sql() with db_query() in D7?

You have to use db_select() with the addTag() modifier.

The query you mention doesn't sound too crazy so it should be fine for db_select().
The only downside is it can be a bit slower.

As per the db_query() api docs:

  Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db_select() instead.


$form_state for an autocomplete callback

The autocomplete callback just gets the string that needs to be auto-completed.
In your case, the only solution I can think of is that the checkboxes use an AJAX callback that is used to set a value the autocomplete function can then access.


It seems somewhere you have something referencing that file. First place I’d look is on the theme folder.

If you have access to a Linux or Mac machine, you can cd into the folder and run,

grep -rn ‘entypo-icon-font.woff’ . 2>/dev/null

This will tell you if there’s a file that has a mention to that file.

To fix, you can either remove the reference to that file or see if you’re able to find the file and add it to the path on the url.


Why I should use dependency injection in Drupal 8?

From Services and dependency injection in Drupal 8:

  ... is best practice to access any of the services provided by Drupal via
  the service container to ensure the decoupled nature of these systems
  is respected.

A clear example can be found in Drupal 8 Dependency Injection, Service Container And All That Jazz:

  Take the following simple class:

class Car {

  protected $engine;

  public function __construct() {
    $this->engine = new Engine();
  }

  /* ... */

}

  When you instantiate a new class Car you go like this:

$car = new Car();

  And now you have an object handler ($car) that has an $engine property
  containing the handler of another object. But what if this car class
  needs to work with another engine? You'd have to extend the class and
  overwrite its constructor for each new car with a different engine.
  Does that make sense? No.

  Now consider the following:

class Car {

  protected $engine;

  public function __construct($engine) {
    $this->engine = $engine;
  }

  /* ... */

}

  To instantiate an object of this class, you go like this:

$engine = new Engine();
$car = new Car($engine);

  Much better. So now if you need to create another car using another
  engine, you can do so easily without caring about the Car class too
  much since it is supposedly equipped to work with all the engines in
  your application.

$turbo = new TurboEngine();
$car2 = new Car($turbo);

  And that is dependency injection. The Car class depends on an engine
  to run (dooh), so we inject one into its constructor which then does
  what it needs to do. Rather than hardcoding the engine into the Car
  class which would not make the engine swappable. Such constructor
  injections are the most common but you'll also find other types such
  as the setter injection by which we would pass in the engine through a
  setter method.

  So there you go. Dependency injection is a very simple concept that
  has to do with the practice of decoupling functionality between
  classes. By passing dependencies to objects we can isolate their
  purpose and easily swap them with others. Additionally, it make is
  much easier to unit test the classes individually by passing mock
  objects.


For Drupal 6:

$result = db_query("SELECT title FROM node WHERE type = '%s' ORDER BY title ASC", 'foo_type');
$titles = array();
while ($row = db_fetch_object($result)) {
  $titles[] = $row->title;
}

For Drupal 7 you have a bunch of options

Static:

$args = array(':type' => 'foo_type');
$titles = db_query("SELECT title FROM node WHERE type = :type ORDER BY title ASC", $args)->fetchCol();

Dynamic:

$titles = db_select('node')
  ->fields('node', array('title'))
  ->condition('type', 'foo_type')
  ->orderBy('title')
  ->execute()
  ->fetchCol();

And a couple of less-direct methods...

EntityFieldQuery:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('type', 'foo_type')
  ->propertyOrderBy('title');

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));
  $titles = array_map(function($x) { return $x->title; }, $nodes);
}

API (deprecated):

$nodes = entity_load('node', FALSE, array('type' => 'foo_type'));
$titles = array_map(function($x) { return $x->title; }, $nodes);


With a 'review' node type and a node reference to a 'product ' node type limit number of user reviews to one

You might need to try a custom module for this.  Rules are too generic as you can only control a user's right to create a type of content.  If I was to write a module for this, it would go something along these lines:

• Use hook_form_alter to add an extra validation function to your Review node form
• Check if the user has submitted a review before in the db
• Throw an error if a record exists in the database

Something like the following code should work, but this is untested.

Edited to note that this is Drupal 6 code but if you use it as a template it shouldn't be too far away.

<?php

function MYMODULE_form_alter($form_id, &$form) {
    // If the form is a "review" node form
    if ($form_id == 'review_node_form') {
        // Add an extra validation function
        $form['#validate'][] = 'MYMODULE_user_node_limit';
    }
}

// Validation function
function MYMODULE_user_node_limit($node) {
    // Get our logged in user's details
    global $user;
    // Run a database query (something like this)
    $sql = "SELECT {node}.uid \n"
    . "FROM {content_type_review}, {node} "
    . "WHERE {content_type_page}.field_node_ref_nid = {node}.nid "
    . "AND {node}.nid = %d"
    . "AND {node}.uid = %d";
    $result = db_query($sql, $node->nid, $node->uid);
    if ($result === FALSE) {
        // Throw error
        drupal_set_message('You have already submitted a review of this item.', 'error');
    }
}
?>

Edited to answer additional comment by asker

Regarding the comment made by Adam S - you could use the code I have already posted in conjunction with the Drupal 7 equivalent of Drupal 6's hook_nodeapi. Here is a list of Drupal 7's node hooks for you to have a look at.  Also, have a look at Eric London's Drupal 6 example of a problem similar to yours of limiting a user's node writing privileges.  Apologies for not providing an exact Drupal 7 example but if you follow the basic premise of Eric London's link but modify it in conjunction with my code, you should be able to solve your problem.


You shouldn't use a date format for your field

I advice you to use CCK module (7.x-2.x-dev)

  some miscellaneous helpers to do things that core will not do, like
  maintain the PHP code snippets some fields may have been using to
  define allowed values (partially working)

With this module, you define these kind of allowed values from a php code


Something along the lines of Bean or Boxes would probably be your best options (assuming one of the many Node in block modules aren't good enough).

I've got more experience with Bean, so I'll give a general idea based on that.

Both modules allow blocks to be created as fieldable entities.  You should simply be able to add an entity reference field as one of the fields on your block and set it up to display in exactly the same way as you currently do with your node/entity reference combo.

Looking through the issue queue, these modules may merge at some point, but I couldn't see anything that says which one is better.  My personal preference is Bean.


How to eMail webforms to 2 alternating email adresses?

1. Userids with those eMail IDs
Assume that some userid exist for a user named X, with emailadress A, and similarly user Y for emailadress B.
2. Enable the Webform Rules module
Use the Webform Rules module to transform your Webform question to a Rules question. Some details about it (from its project page):

This module adds rules integration on webforms.
Did you ever want to react on webform submission using rules but couldn't find the proper event?
Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

To get you going, have a look at this example rule (in Rules export format):
{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occurred",
          "message" : "A new webform submission has occurred (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

I intentionally did not include any Rules Conditions here, just to illustrate that by using this Rules Event (= a form is submitted), you do have access to a limited set of tokens related to the user who submitted the webform, such as [user:id], [user:name] and [user:mail].
3. Enable the Flag module
Use the Flag to create a flag for flagging users. Its purpose is to (automatically) indicate which of both users (X or Y) should receive the next eMail, i.e the next eMail should go to the user who is flagged at the time of the webform submission.
4. Create 2 custom rules
a) Send an eMail to user X
Create a 1st custom rule like so:

Rules Event: a form is submitted
Rules Condition: if user X is flagged
Rules Actions:

Send an eMail to user X.
Unflag user X.
Flag user Y.

Note: you probably have to use "switch to direct input mode" multiple times (to be able to enter the uid of user X or Y).
b) Send an eMail to user Y
Create a 2nd custom rule like so:

Rules Event: a form is submitted
Rules Condition: if user Y is flagged
Rules Actions:

Send an eMail to user Y.
Unflag user Y.
Flag user X.

Note: you probably have to use "switch to direct input mode" multiple times (to be able to enter the uid of user X or Y).
5. Perform an initial flagging of a single user
Decide which user (X or Y) should receive the very first eMail, and flag that user. After doing so, next time a webform is submitted the process to send those eMails will start. And as long as you don't flag either one, nothing will happen (as per the implemented Rules logic in step 4 ...).
Note: If you ever want to stop the process, just unflag the user (X or Y) that is flagged.


drupal bootstrap theme working with superfish

Superfish allows you to add custom css classes to the menu items. If you prefer to do it that way

you might want to first select the classes from bootstrap that you want to use to style your superfish menu items. Second add those classes correspondingly in the superfish menu block settings(click configure next to the block).

I also added a html wrapper under advanced HTML settings around the main UL element which is simply , (comma denotes the beginning and ending wrapping elements).

Let me know if that helps!


No access stats for user after registration

Usually a state "never" means that the user has registered but they have never logged in with their username/password


ajax_command_invoke adding a new item in a field collection

Actually, it was quite simple... I use Drupal.behaviors to attach my jQuery plugin initialization to the form, and it's now called on ajax callback as well, when a part of the form is updated by this ajax call.
So it's fixed !

The drupal documentation helped me, and the Lullabot article as well !


How to add a button in the header of a table form?

Finally, I did it this way:
if (some condition) {
  $data = [
    '#type'     => 'inline_template',
    '#template' => '<input type="submit" id="edit-toggle" name="button" value="{{ foo }}" class="button js-form-submit form-submit">',
    '#context'  => ['foo' => $this->t('Toggle')],
  ];
}
else {
  $data = '';
}

$form['inscriptions'] = [
  '#type'   => 'table',
  '#header' => [
    [
      'data'    => $data,
      'colspan' => 2,
    ],
    [
      'data'    => 'Distribution',
      'colspan' => 2,
    ],
    [
      'data'    => 'Réserve',
      'colspan' => 2,
    ],
    [
      'data'    => 'Référent',
      'colspan' => 2,
    ],
  ],
  '#id'     => 'planningofdistributions',
  '#sticky' => TRUE,
];


How can I rebuild node / view cache based on the contents of an entityqueue

Every view that lists nodes is tagged with node_list and will be invalidated when a node is added, changed or deleted, so you don't need to worry about adding your nodes to the view.

But you do need to add the entity_subqueue tag to your view's cache tags, and you need to add the entity_subqueue tag and banner content type to your news content type's build array.  I haven't tested the way you're adding it, but I know you can add cache tags to a node in hook_entity_view:

  function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

      if ($entity->bundle() == 'news') {

        $tags = ['entity_type:node.front_page_banner', 'entity_subqueue:front_banner'];
        $build['#cache']['tags'] = array_merge($build['#cache']['tags'], $tags);

      }
    }

I know this is similar to what you were doing, but need to add it to the build array, not the node object.

Then you need to add the entity queue to the build array of your view

function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() == 'news' || $view->id() == 'front_banner') {
    $view->element['#cache']['tags'][] = 'entity_subqueue:front_banner';
  }
}


Drush out of memory when php memory limit is 1024M on my dedicate server. (CentOS)

Your particular setup might be one that (deliberately) has 2 php.ini files:

for Apache, e.g. on your server at: /etc/php5/apache2/php.ini (or similar path depending on your distro)
for command line (i.e. for drush) e.g. on your server at: /etc/php5/cli/php.ini (or similar path depending on your distro)

(I believe that this is perfectly normal kind of setup to have 2 files, I have this myself.)

You need to ensure that memory_limit is 1024M is set for /etc/php5/cli/php.ini(or similar path depending on your distro) php executed in the command line/terminal/console i.e. drush. You could also try memory_limit is -1 which allows the server to allocate as much memory as is available.


access the node id of a field collection

It works for me. You can do it as follows-

/**
 * Function hook_preprocess_field.
 */
function [theme_name]_preprocess_field(&$variables) {
  if ($variables['field_name'] == [FIELD_COLLECTION_NAME]) {
    if ($variables['element']['#entity_type'] == "node") {
      $node_id = $variables['element']['#object']->id();
      //Rest of the code.
    }
  }
 }

Hope it works for you too.


Drupal cannot contact itself. The system module reports this error when a system_check_http_request(). Assuming this is the cause of the AJAX errors, you could try, as the error message suggests, to set $conf['drupal_http_request_fails'] = FALSE; in your settings.php file. This might fix the symptoms, but not the cause however.

The fix lies in figuring out why this check fails:

drupal_http_request(url('', array('absolute' => TRUE)), array('max_redirects' => 0));

It could be that url() is not returning your front page URL. If you have drush on your server, you can run the command drush php-script my_test_script.php. With my_test_script.php containing a simple test script:

<?php echo url('', array('absolute' => TRUE)), array('max_redirects' => 0); ?>

If it is returning the correct home page URL, another likely problem, since you're hosting multiple sites, is that your domain is not resolving the correct virtual host. You can test this with the server command:

wget -O- http://www.example.com/

If your site's home page HTML is output to the console that should tell you that the server can contact the resolve & connect to itself. If this is the case it might be something like a PHP config preventing retrieval of HTTP URL's.


Block not displayed on translated views page

Ok, I figured out the issue was there was a menu position rule for consumers/news* in any language appearing under a menu item in the English language menu. I set this rule to be English only then replicated it for French language items under the French menu


Create Drupal Commerce stores as a Service

This is known as the "marketplace" use case.

There is a 250-comment discussion on this in the Drupal Commerce issue queue:
http://drupal.org/node/990204
See http://drupal.org/node/990204#comment-5880498 for a fairly simple implementation plan.
Of course, it goes into details that your project might not need, but you can just ignore those.

Quoting the relevant part about the basics needed:

  1) An entity that represents the store. That can either be the user, a store entity clicked together through the ECK module, or a store entity provided by a module.

  2) Entityreference. Then a bunch of entityreference fields that point to the "store" entity (or user). One on products, one on product displays, one on orders.

  3) Form alters that hide the entityreference fields on product displays and products (or just use a "hidden" widget) and fill it in with the known value (you always know which store the user has. If not, give him a dropdown...).

  4) A custom submit handler for the add to cart form (replacing the existing submit handler) that adds a product to an appropriate order (since there's an order per store for each customer), and if the order doesn't exist yet, creates it and sets the value of the entityreference field.

  5) Custom view for cart/ that shows all active carts to a customer.

  6) Custom views filtered by the entityreference field that show the merchant the products and orders for his store.

Organic Groups fits neatly on top. You then need to figure out how you're handling payments, see the linked issue for various approaches.


Printing outout of a view in to a field in user profiles

I'll make an assumption, and answer based on the assumption. The assumption is that the field "Father username" is an entity reference field, and you want to use the view of registered users to populate the options for that field.

If that is so, you need to create an "entity reference" view display, then refer to that view display in the field settings of the "father username" field.


Calendar Module: Calendar block with mini-calendar to show next month instead of current

You can adjust the Contextual Filter for this block. Instead of providing a default value of "Current date" you can set it to "PHP Code" and use the following:

return date('Y-m',strtotime('+1 month'));


This is an issue I have been sturggling with myself.  You may want to start by looking at hook_views_query_alter() and read this related Drupal Answers question.

Then you can use these functions: views_plugin_query_default to actually affect change on your query.


Update a content type field via db not working D8

To update the value of a field for a node, you need to.

Load it
Modify it
Save it

In code it looks like this:

$node = \Drupal\node\Entity\Node::load($nid);
if ($node) {
  $node->field_p_frontip = '192.168.1.100';
  $node->save();
}

How you set the value of the field, depends on the field itself. Most fields are simple, and can be set with a scalar value. If field has multiple values or stores more complex data (like the address field), you need to account for this complexity. Usually this is done with arrays.


Looking for an employee scheduling module

I created a shift scheduler module about a year ago.

Documentation and Releases: http://code.google.com/p/drupal-shift-scheduler/

Video tutorial: http://www.youtube.com/watch?v=9pPHtoE2ivg

Development: http://drupal.org/sandbox/mcstrother/1075572

I'm no longer actively developing it, but I believe both the 6 and 7 versions are actively in use on at least one production site each with no new bugs reported.


Views Data Export: Multiple Columns with Unique Rows (D7)

Have you noticed the following setting on the field which has multiple values:

That should be a collapsed section right under where you specify the label, etc of your field.  Just make sure you check that you want them to appear in the same row and select a separator (comma by default).

That should be all you need!  Does it transfer well for the export?


Updated:
Try with this code:

$image_original_path = '.. here my original path..';
$image_object = file_get_contents($image_original_path);
$file = file_save_data($image_object, file_default_scheme().'://'.basename($image_original_path),FILE_EXISTS_RENAME);
// Add this code also
if (is_object($file)) { // if you get back a Drupal $file object, everything went as expected so make the status permenant
  $file->status = 1;
  $file = file_save($file);
}


How to display comments and comments form on custom node pages

Add your theme hook suggestion in Node preprocess hook instead of Page Preprocess

if (isset($variables['node']->type) && !empty($variables['node']->type)) {   $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type; }

Now $content variable should be available for you.. Please remember Clear Cache


Pass title of current node to subsequent node created in modal

If your form is not loaded via ajax then you can write a form alter hook in your module and alter the photo node form and provide a default value for the title field of the photo node form. You can either query or do node_load() of the current review node to get the title. You can retrieve the nid of the current node by the arg(1) function.

When you have the title of the review node you can assign it as the default value of the photo node.


Can Panels just be uninstalled if you want to switch themes?

Usually, uninstalling removes everything created by the module, its setting and its database tables.

But for what you are after, you don't even need to uninstall them, not even disabling to be honest, just don't use panels tools in your new theme.

Considering that, I would delay the idea of removing them and the old theme to after the new one is ready.
Just because of "how i did it in the other theme?" kind of questions


Avoid user to multiple purchase of same product

The best way to do this would be to use the method (How do I prevent a product from being added to the cart?) but implement custom logic to look for that product being purchased by the customer.

You can do this by using EntityFieldQuery() and loading all of the user's orders and then you can loop through the line items and look for the product...

$orders = commerce_order_load_multiple(array(), array('uid' => $user->uid, 'status' => 'completed'));
foreach ($orders as $order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    if ($line_item_wrapper->commerce_product()->sku->value() == 'SOMESKU') {
    //user has bought it
    }
  }
}


To add informations to the view, which are not displaying of whatever reasons - you can hook into the view and "print" the informations manually.

Step 1 Create a custom module
(https://www.drupal.org/docs/8/creating-custom-modules)
I'm not sure, but probably you can add the preprocess in the MYTHEME.theme-File. Then you do not need your own module for this.

Step 2 Add the preprocess hook (https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/function/template_preprocess_views_view/8.5.x)

MYMODULE_preprocess_view(&$variables) {
    // Todo: check if the view is the view you want to add the user email.
    $user_id = 1; // Change for other users.
    $user = Drupal::entityTypeManager()->getStorage('user')->load($user_id);
    $variables['users'][$user_id] = $user;
}

Step 3 In the twig-template of the view you can add the userdata (https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views_templates/8.5.x)

{{ dump(users) }}     {# for the user array. #}
{{ dump(users[1]) }}  {# for the user with the id 1 #}


Call to undefined function making site unavailable

You can try to (re)move the faulty module's directory, at least temporarily. It should prevent the call and let you access the necessary admin pages.


Cant figure out what's wrong with my image style generation code

The first argument should be array in the image_style_create_derivative() function, so the error is in the caller code.

  Parameters

  $style: An image style array.

  $source: Path of the source file.

  $destination: Path or URI of the destination file.

https://api.drupal.org/api/drupal/modules%21image%21image.module/function/image_style_create_derivative/7.x

There is a incorrect sample in the comments at api.drupal.org.