How to remove duplicate terms in a vocabulary I have a vocabulary with many terms that are duplicates. How can I remove those terms?

I have many duplicates; I need a way to delete them that is not deleting them one by one.

The Term Merge module could help you.

  When using taxonomy for free tagging purposes, it's easy to end up with several terms having the same meaning. This may be due to spelling errors, or different users simply making up synonymous terms as they go.

  You, as an administrator, may then want to correct such errors or unify synonymous terms, thereby pruning the taxonomy to a more manageable set. This module allows you to merge multiple terms into one, while updating all fields referring to those terms to refer to the replacement term instead.


Print out a Drupal Commerce field only if it has a value In Drupal Commerce, you can use the following to print out a field in your node.tpl.php file:

<?php print render($content['product:field_NAME']); ?>

See here fore more information

But how do you print a field only if it has content?

For a normal Drupal field you would use the following:

<?php if (isset ($node->field_NAME)): ?>
  <?php print $node->field_NAME['und'][0]['safe_value'];?>
<?php endif; ?>

But that doesn't work with a Drupal commerce field.

I would appreciate if someone could offer any pointers!

Content for the referenced product fields is incorporated into the product display(node) using field_extra_fields and normally contents go into the #markup key.

You can use template_preprocess_node and use something like this:

if (!isset($variables['content']['product:field_NAME']['#markup'])) {
  unset($variables['content']['product:field_NAME']);
}

You could also try Field formatter conditions module.


FAPI text_format field value not being passed to submit handler I created a form that I wanted to be reusable. So I created to form below to imported into a add form and a edit form. Please be aware I do have the validateForm, and submitForm function in my code.

class PaneConfigurationForm extends ConfigFormBase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'admin_pane_settings';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state, $element = null) {

       $form['description'] = array(
          '#type' => 'text_format',
          '#title' => 'description',
          '#default_value' => '
The quick brown fox jumped over the lazy dog.
',
          '#value' => '
The quick brown fox jumped over the lazy dog.
',
          '#format' => 'full_html',
       );

       return parent::buildForm($form, $form_state);
    }
}

So in my AddPane form I use the \Drupal::formBuilder()->getForm() function to get the form and apply it to my parent form. For some reason when I submit the form the value is not passed to the submit handler, only to form format.

class AddPaneForm extends Formbase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'add_admin_pane';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state, $element = null) {

          $form = \Drupal::formBuilder()->getForm('Drupal\_module_\Form\PaneConfigurationForm');

          $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Save'),
          );
    }

    public function submitForm(array &$form, FormStateInterface $form_state)
    {
          $form_state->getValue('description')
    }
}

What can I do to allow the format and value to be passed to the submit handler, not just the text_format field's format.

Just remove the #value:

$form['description'] = array(
  '#type' => 'text_format',
  '#title' => 'description',
  '#default_value' => '
The quick brown fox jumped over the lazy dog.
',
  '#format' => 'full_html',
);

#value permeates all the way through a form build/validation/submission, and doesn't get replaced with user input.

#default_value will cover the initial value when the form loads.


How do I obtain the result summary from within a form on the view page? I have a design requirement or ask that wants to have a search form at the top of a Views page look like the attached image.

So there is an exposed full text input, exposed sort by filters.

However, the result summary for the view would appear to need to go in the middle of the form.

Since this is on a View page, is there a way to get the current View and fetch its result summary within a hook_form_alter()?

However, the result summary for the view would appear to need to go in
  the middle of the form.

  Since this is on a View page, is there a way to get the current View
  and fetch its result summary within a hook_form_alter()?

Don't complicate your Drupal life, and just KISS.

I assume you already added the Result Summary to your View's header. So just:

style.css

.view-id-[your-id] .view-header {

  position: absolute;
  top: 70px;

}


Printing a term using custom formatter On a custom template for a taxonomy view, I want to render the current term (the one being viewed) using my custom taxonomy term formatter, how do I do that?

I have looked at the field_view_field function, but it's not clear to me how I would use its parameters field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL) - esp. the $field_name part is not clear. I am afraid this is not the right function... Any help please?

if you want apply specific display formatter to some field like taxonomy terms, the best way is to write a display formatter module, and apply it to your entity_type via display setting on specific view mode, so if you want do this completely programmatically you need:

write display formatter moule
define view mode if necessary (e.g. for node we have full, teaser and ...)
add configuration to field instance setting

if you need some sample code to write display formatter module, let me know...

EDIT: if you want pass field instance setting to field_view_field you have something like this:

$display = array(
    'label' => 'hidden',
    'type' => 'colorbox',
    'settings' => array(
        'colorbox_node_style' => 'simpledeal_company_medium',
    ),
);
field_view_field($entity_type, $entity, $field_name, $display, $langcode = NULL);

this example code is about colorbox display formatter, should be replaced by yours

to do above via admin you should go to vocabulary display setting admin/structure/taxonomy/VOCAB_NAME/display, in CUSTOM DISPLAY SETTINGS check Taxonomy term page and set your display formatter, in this way you may do not need to change taxonomy-term.tpl.php


Where does Drupal render the content of the  tag? I'm calling drupal_add_html_head() a few times to add meta data for facebook integration. To my surprise, this data is not rendered in the order I add it.

Where is this data actually rendered? I would like to examine the code so I can understand the logic behind it.

I'm aware there's hook_html_head_alter too, but without understand the render order, messing with the order of input data is not likely helpful.

template_preprocess_html() gets the tags for the <head>, and adds them to the html.tpl.php template file as $head.

The template file looks like this:

..
<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
..


How can I access this site as the administrator? I have a dev site that I cannot access that contains content ad structure I want to extract. To gain access I created a new dev website and copied over the contributed modules and theme I am using. I then imported the database containing the data.  When I go to the custom home page there is no login (I had not yet added it to the panel containing the home page display).  To access the site, I must do one of two things:

Access the site using Drush.  I tried using Drush user-login which returns a link "http://default/user/reset/1/..." It is not clear how to use the link.  Using it directly as-is leads to an unknown website search.  Using it as example.com/default/user/reset/1/...  leads to a page not found error.  Having never done this before, I am not sure what to expect.
If I could change the theme to a standard one such as Bartik through the database or other means I would then have access to a login block.  Where is the current theme stored?

Any other suggestions gratefully accepted:)

I think default is substituted for the site name in your drush result, try http://example.com/user/reset/1 which would be the standard password reset page for a user with a uid of 1 (the admin user).

If that doesn't work the default theme is set by the theme_default variable...you can edit the variable table in the database manually and set the value column for that variable to whatever theme you want.


Problems with migration D7 to D7 I'm using the modules Migrate and Drupal to Drupal Migration. And I'm just using the UI of the migrate_d2d-module to migrate some content of a D7 site to another D7 site.

It works very well for users and there pictures, and the nodes are migrated too with the fields: title, author, date, body etc. BUT not with the image field! That means the images of the nodes are missing. :-/

How can I solve this? I'm sure I have to do some kind of mapping?

What data I have to use for this:

[field_product_image:destination_dir]
[field_product_image:destination_file]
[field_product_image:source_dir]

The image field is field_product_image and I have exported/imported the content type of the nodes to my new D7 installation.
the Images are stored in default/files/image/galerien.

Thanks for helping me!

Thanks very much Sumit Madan,

he gives me the solution:

Mapping:

for the file class of the image field enter this as "standard value": MigrateFileFid

set "TRUE" for preserve_files of your image-field.

thanks again!


Will URLs with spaces in the path work on all major browsers? Will a path to content such as example.com/content type/page name work? or must it have a filler such as dashes -  example.com/content-type/page-name?

Spaces should be at least encoded as %20 .

It's not a good practice, not a standard, to use spaces in URLs at all. In my opinion it is better to replace all spaces with dashes or to concatenate them.

Spaces will cause problems with links, for example you might get:

www.example.com/problem with link

instead of:

www.example.com/problem with link


Suggestions for sending email to third party merchant when checkout is completed I need to build a site that will sell products on behalf of merchants referenced on the site and I need to notify these merchants every time a sell of their products occurs and send them information about the order we received for their product. Out of the box, commerce uses rules to send an email to the buyer and can also notify the site admin that a new order was created.

That is great but what if I need to notify a third party? Is there a way to do this out of the box or via configuration? Or is there a module for that?
I have been looking and couldn't find anything. When I try to use rules the only email available for order checkout as tokens are the customer email and the site admin email.

For the sake of clarity here is the setup I have gone for so far and where I am stuck:

I have setup a field collection on my product pages listing the contact details for the merchant selling the product.

I collect three fields information inside the field collection:

name of merchant
address
contact email

I can easily make them visible on the order form with views by using relationships but I need to make the contact email available to rules so that I can set up a rule that will send and email to the merchant when the checkout process is completed.

That's it.

Thanks for your help

You can use a rule for that.

Use the action "Send a mail to an arbitrary mail address"

Set the recipients with php, like this (it's more powerful than tokens) :

<?php print _get_custom_emails_list( $node->field_custom );?>

Add this custom function in your custom module

<?php
// Your custom function
function _get_custom_emails_list( $field_custom ){
  // your query here.....
  return 'test@test.me, test2@test.me'
}
?>


how to access $user from commandline? I'd like to access $user from the commandline to see what properties are available on it.  I could sdpm($user) in my code and go inspect it in my browser, but isn't there a way I can inspect it right from my terminal?

It looks like drush php could be helpful here, according to http://blog.damiankloip.net/2015/drush-php, but when I use it and do dump -a $user I get 'Unknown variable: $user'.  That's probably obvious, so I probably need to load $user into the repl first (I'm guessing)... but how?  That blog post shows how to load objects in D8, but how would I do this in D7 for $user???

You need to define the $user variable first. You can run the drush command as a particular user by specifying --user on the command line:

drush --user='admin' ev 'global $user; print_r($user);'

If you don't specify a user, drush runs as anonymous by default.

Or, you can do it like this:

drush ev '$user = user_load_by_name("admin"); print_r($user);'

It will display this:

stdClass Object
(
    [uid] => 1
    [name] => admin
    [pass] => *****
    [mail] => info@example.com
    [theme] =>
    [signature] =>
    [signature_format] => filtered_html
    [created] => 1443708895
    [access] => 1515415027
    [login] => 1515411954
    [status] => 1
    [timezone] => Europe/London
    [language] =>
    [picture] => 0
    [init] => info@example.com
    [data] =>
    [uuid] => f6800524-c092-4abc-abcd-f71d091623cd
    [roles] => Array
        (
            [2] => authenticated user
        )

    [force_password_change] => 0
)


How to add a span before a tabs item? I would like to add a little icon before the tab item 'Edit'. Firebug shows that the default code looks like this:

    Edit

My idea is to add a span before the ...:

    Edit

where the edit class has the underneath CSS.

.edit {
    background-image: url("MY_IMAGE.png");
    background-repeat: no-repeat;
    display: inline-block;
    height: 16px;
    padding-right: 2px;
    vertical-align: middle;
    width: 16px;
}

Adding the  directly with Firebug gives the wanted result, but I don't know how to do this in a template or with a function. What is the correct way to achieve this?

Instead of adding a <span> element, you could also use the ::before CSS selector. If a combination with :first-child or :nth-child() is not helpful, most likely you have to implement hook_menu_local_tasks_alter() and add a specific class to the desired link(s) (you can add them through attributes in localized_options of the #link property, see https://api.drupal.org/comment/25393#comment-25393) and then you could use the ::before selector. Or you could implement/overwrite theme_menu_local_task() (probably in combination with a theme preprocess or the earlier mentioned alter function) to add your <span> element.


Possible to make admin's flags worth more points? I'd like the admin's flagging of a node to carry more clout than with regular users. Is it possible to either;

Insert the count into the mysql database as a number larger than 1
whenever admin flags a node.
Allow flag counts to be additive, ie: Admin can flag a node many
times with each count being added to the total.

Perhaps it can be done using rules and php? If so what would be the procedure in rules?

Flags work like an on/off switch. Depending if the Flag is global or not, that on/off switch can apply to every user (each user can have a separate room w/ the lights on or off), or globally - every user is in one room, with only one light bulb, and one light switch.

Basically what you're asking is: is it possible to turn on the lights on twice?

No. In our light bulb analogy, that Flag switch doesn't come with a dimmer option ;)

What Rules allow you to do is aggregate the count of the Flag "votes" by multiple users (when not using global flags), and execute an action based on the sum of user "flags". But that is not what you're looking for.


How to manage by cron a long-running queue of very many items I'm creating a File Checker module that verifies files managed by Drupal actually exist at the uri where Drupal believes they are.

It places an item in a queue for each file entity. As there could be large amounts of files on a site, so there can be large amounts of queue items (10000, 100000 ...). Each item (file entity) can take a few seconds to process if the files are stored remotely e.g. on Amazon S3 or Dropbox. So the queue could take hours to process.

File checking can be scheduled to happen at regular intervals, i.e. by cron, so queue processing needs to happen by cron queueWorkers.

What is the best way to handle the duration of these cron queueWorkers? Their plugin annotation has a cron time option (default 15 seconds) that controls how long they run for when awoken by cron. I could either:

1) set their time option to something very long like 86400, so they can process queue items for a whole 24 hours if they need to; or

2) set their time short like 60 seconds, and use something like the Ultimate Cron module to specify that just this queueWorker is woken up every 60 seconds (and not other cron tasks).

The problem with using queue for an operation like this is that you have to fill up the queue frequently.

Queue makes sense if you have something that is e.g. user or somehow else triggered one by one (or a few at a time), added to the queue and then processed in background. For something like your use case, you want to process tens of thousands of entries, it is a lot of overhead to add them to the queue first and then process them again.

Instead, a simple approach would be to keep track of the file ID. process the first 100 files, sorted by fid, ascending. store the last file ID in state, then on the next run get the next 100 files, where fid is bigger then the last processed fid. If you reach the end (identified based on having processed less than 100 files, you reset the fid back to 0 (possibly combined with some kind of timestamp, so you only start again after N seconds passed since you started the last time). 100 could be configurable, so users can process fewer or more files per run, depending on whether they have them local or not.

Keep in mind that by default, there is only one cron process, if you're running for a long time, it will block everything else. Ultimate Cron could help there, also with running your cron job more frequently than others. It supports multiple threads, but I honestly don't know how well that works already in 8.x (And I am the 8.x maintainer of that module ;)).

You could also always expose it as a drush command, then it would be easy to do it as a completely separate, standalone cron process.


How to use token [comment:original:url:absolute] I want to use the token service for [comment:original:url:absolute].

As far as I understand, it should be something like this

$message = $token->replace('Hello the comment is: [comment:original:url:absolute]', ['comment' => $comment_entity]);

Unfortunately, it doesn't seem to work like this.

I'm not sure what I'm doing wrong here since the documentation is vague when it comes to specific examples.

Any pointing in the right direction is appreciated.

[comment:original] only exists when a comment is being updated - without context, it will always be empty. And if you had the context to pass it in this case, you wouldn't need to use the token service in the first place, you could just use what you already had to get the URL.

You probably want to use;

[comment:url:absolute]


Why implementation of node access for different content type breaks my other type access control? System architecture:

Main entities:

Company
Employee (and other user types)
Document

References:

Every document has reference to company and employee.
Every employee has reference to company also (at least one company)

I've implemented custom access control for documents, which suppose to working fine (my unit tests gives me all green also).

Now I'm creating View - documents list for an employee. Basic version of View is working correct. I want to add exposed filter for a company. By default this is a list of all companies. But I want to restrict this list only for companies from employee documents, related to current logged in employee.

Code:

/**
 * Implements hook_node_access_records().
 */
function mymod_company_node_access_records($node) {
  if ($node->type <> myCompany::CONTENT_TYPE_NAME) {
    return array();
  }

  return array(
    array(
      'realm' => MYMOD_COMPANY_LOCK_NAME,
      'gid' => $node->nid,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    )
  );
}

/**
 * Implements hook_node_grants().
 */
function mymoo_company_node_grants($account, $op) {
  if ($op <> 'view') {
    return array();
  }

  if (mymod_user_is_an_employee($account)) {

    $myUser = myUser::createFromUser($account);
    $companies = $sdUser->getCompanies();
    if (empty($companies)) {
      return array();
    }

    $grants = array();

    foreach(array_keys($companies) as $nid) {
      $grants[MYMOD_COMPANY_LOCK_NAME][] = $nid;
    }

    return $grants;

  } else {
    return array();
  }
}

Indeed filter list is restricted to employee related companies, but in my View, I'm seeing ALL documents related to these companies. Why?

My View main content type is Document. Company is related node via entity reference field. I don't understand why company access control has some type of precedence here.

While browsing through the Drupal docs about hook_node_access_records, I stumbled upon this comment:

  Note that (as of 7.35) if your module and every other module in your
  installation implementing this hook return empty arrays, Drupal will
  automatically insert a record into the node_access table for the given
  node with GID 0, grant_view set to 1, and grand_update and
  grant_delete set to 0.

You can find it here (last comment).


Altering a form to set it's target to _parent I have a form in an iframe, when the form gets submitted I need the target to be _parent.

How do we add target="_parent" to a form element in drupal 7. I am pretty sure hook_form_alter is the best way to go just not sure about what var gets edited and how.

-thanks.

to change your form you can use hook_form_alter
example

function login_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id=="user_login_block")
    {
         $items[] = '<a id="fpassword" target="_parent" title ="'.t('Request new password via e-mail.').'" href="#">'.t('Request new password').'<a>';
         $form['links'] = array('#markup' => theme('item_list', array('items' => $items)));
    }
}


How do I mass flag a node on behalf of users (possibly with VBO)? I have a view that returns the og members of a group. Users can additionally flag groups. I want all users returned by the view to flag the group. So I tried to do this with Views Bulk Operations (VBO), but the only available operation is "Flag (or unflag) a user". The flag is attached to the group, not the user. How do I do that?

What you could do to get this to work, is to use the integration of VBO with the Rules module, as further detailed below.

Step 1: Create a Rules Component

Create a (rather basic) Rules component to flag a node by a user. Here is such component in Rules Export format:

{ "rules_flag_node_flagged_by_a_user" : {
    "LABEL" : "Flag node flagged by a user",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "flagged_node" : { "label" : "Node to be unflagged", "type" : "node" }
    },
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "your_flag",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      },
      { "drupal_message" : { "message" : "Node flagged for user  [flagging-user:name] (uid=[flagging-user:uid])" } }
    ]
  }
}

This Rules Component uses a flag with machine name your_flag. After you edit that machine name to fit the name of your flag, you should be able to import this rule in your own site (using the Rules UI, which needs to be enabled).

BTW: the Rules Action to display a message is just to see it at work while QA-testing this rule, feel free to remove that if you want.

Step 2: Let VBO do the work

This step is pretty easy ... Just use your VBO view. The clue to what you want VBO to do as an operation is ... Execute the Rules Component from Step 1.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 records at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

Happy VBO-ing while Rules-ing!

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


Override field module function in custom module? I want to override field_sql_storage_field_storage_write(), defined in /modules/field/modules/field_sql_storage/field_sql_storage.module.

I tried with MYMODULE_field_storage_write_alter($entity_type, $entity, $op, $fields), but it doesn't work.

How should I override that function?

You could try hook_field_storage_info_alter

Other candidates are

hook_field_insert
hook_field_update


Or operator in Views I've got content-type includes 'field1', field2' and 'field3'. These fields are integer value. Thanks to Views module I created page 'Page1' with contents. In main menu I've got search whit some filters. After filling filters and entering, we can see appropriate contents in 'Page1'. I'd like to create filters or fields in search to allow user to fill in 'min' and 'max' values. After it I want to choose a content only if 'field1' or 'field2' or 'field3' of that content is beetwen 'min' and 'max'. How can I do it?

In Views where it says Filter criteria there is a button that says Add, if you click on the arrow to the right you can access "And/Or, Rearrange", click that.

You now have an UI where you can group filters together and use OR between groups of filters.

In the example below the node should be Published or of type flickr_image. First thing you need to do is click Create new filter group. From there you can drag your filters into your groups. Next select if the operator between the filters should be AND or OR.

After this add your three fields. Use the filter between, if the filter is exposed it will look like this.

I would keep the first filter exposed and the other not exposed. But then comes the tricky part. The other two filters must inherit the value from the first exposed filter.

I think you need a little bit of glue code to get this going. Put the code below in a custom module. You need to change MYMODULE to the name of your module, MYVIEW to the machine name of your view. And of course field_1 and field_2 to their real names.

function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'MYVIEWNAME') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_2_value']['value']['min'] = $view->exposed_input['field_1_value']['min'];
    $filters['field_2_value']['value']['max'] = $view->exposed_input['field_1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}


is there hierarchical user level structure in drupal Is there any hierachical structure of user in Drupal?
I just see user role in drupal, but can we define some level of user?
As example:

user1
--user2
---user3
--user4
---user5
---user6

Check out Subuser module to see if it fits your needs.

If you want "just" the roles to be hierarchical, Role delegation might be useful

Related: https://stackoverflow.com/questions/1281964/drupal-for-users-creating-sub-users


VBO: "Change owner" Vs "Change the author of content" I would like to change the author of a content for a bunch of nodes. So I've chosen Views Bulk Operations (VBO) module to achieve it.

Part of it, created a VBO view, but in the VBO options I see "Change owner" and "Change the author of content" (shown below).

What's the difference?

Change owner is an action implemented by the Views Bulk Operations module, while Change the author of content is an action implemented by the Node module. (See views_bulk_operations_change_owner_action_info() and node_action_info().)

The VBO module implements that action for any entity for which that action makes sense. (In other words, if the entity doesn't have an owner, the action is not implemented for that entity.) Apart that, the underline code doesn't change much.

// This is the function for the VBO action.
function views_bulk_operations_change_owner_action($entity, $context) {
  $entity->uid = $context['owner_uid'];
}

// This is the function for the Node module action.
function node_assign_owner_action($node, $context) {
  $node->uid = $context['owner_uid'];
  $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(
    ':uid' => $context['owner_uid'],
  ))
    ->fetchField();
  watchdog('action', 'Changed owner of @type %title to uid %name.', array(
    '@type' => node_type_get_name($node),
    '%title' => $node->title,
    '%name' => $owner_name,
  ));
}

The obvious difference is that the VBO action implementation doesn't log for which node the owner has been changed. When changing the owner for many nodes, its implementation could be faster than the Node module one.


How do I show all "songs" that reference an "album" (for example)? Suppose I have a content type (Song) which has a content reference field, referencing an Album node to which it belongs. When I view an album, I want to show a list of all songs which reference that album.
Can this be done?

I'd rather not use a taxonomy term. I've looked at the "Manage Display" screen for the Album content type, but I could not find any way to display the songs which reference it. I know that I can create a view which filters by album, but I want to display this information directly on the Album view screen, so when users click the album link, a list of all songs on that album will show up. Is this possible?

Thanks for this comment pointing me to the EVA module.  Here are the exact steps I had to take in Drupal 8, which is slightly different than Drupal 7.

Steps for Drupal 8:

Make sure your reference field is already set up (e.g., the Song entity has a field referencing an Album)
Install and activate the EVA module
Add a new view (Manage > Structure > Views > Add View)
Type in the view name, and in View Settings, set it to show Content of type Recording (i.e., the "child" entity).  No need to "Create a page" or "Create a block".
Under the Displays heading will be a label called Master.  Click the Add button just to the right of that.
Select "EVA", not "Entity Reference" (this is a difference from Drupal 7)
Under Displays > Format, I like to change "Unformatted list" to "Table".
Under Display > Entity Content Settings, change "Entity type" from "None" to "Content".
Change "Bundles" from "All" to "Album" (i.e., the "parent" entity)
Under Advanced, add a "Contextual filter".
Search for the field which links Recording to Album (i.e., the field in the child entity which references the parent), and select it, and click "Add and configure contextual filters".
Under "When the filter value is not available", select "Provide default value" and choose "Content ID from URL".
click "Apply".
If you know the ID of an album (parent entity), you can enter it in the parameter in the "Preview" section to make sure it is working as expected (you will need to pre-populate entities to test this).
Click "Save" under the "Display" section for the view.
A message should show up: "The view ___ has been saved."
Clear all caches (Manage > Configuration > Development > Performance > Clear Cache > Clear All Caches).
Navigate to a sample parent entity, and the child entities should show up on that page.


Drupal Commons 3 and Original Drupal Core Updates I'm may be planning to switch over to Drupal Commons 3. When the original Drupal core gets security updates, will I be able to get those updates in the Drupal Commons or do I have to wait for Drupal Commons to release their own patch? I'm not sure if Drupal Commons modifies the original Drupal Core's code. Sorry if this question is already answered in an FAQ somewhere but I couldn't find the answer and I'm pretty new to Drupal.

The Commons team has committed to having a new release of commons within a short period after a core or contrib security release so you should just be able to upgrade by following the Commons upgrade procedure.

It's a bit risky to update core or contrib modules inside of a distribution. If you can do it on a test site first, confirm that it's working, and report your problems with the test site to the issue queue then you'll help getting the fully packaged Commons out.


Using Media, views, and colorbox to create a image gallery Currently I am running in D7 with the following modules:

Media 7.x-2.0
Views 7.x-3.7
Colorbox 7.x-2.4

I am trying to create an image gallery using these modules with the following steps. Please note problems I am running into will be in bold.

Go to admin/structure/views
Click Add new view
Select File for show, and image for type
Unchecked Create a page, and check Create a block
Select Grid of File for Display Format
Click Continue and Edit

This is where things go off the rails for me, what I would like to do is have ALL images that are tagged display in a custom image style I already created (200x200) in a 4 column grid, and when you click on them they open up into a normal sized image colorbox.

Now I have seen this done when you create a image content type, but that way is clunky compared to using the media module, and I have to believe that there is an easy way to do this with these modules, and I am simply missing it.

I have read about Media Gallery module, but there seem to be a lot of errors with it and I am not thrilled with the idea of it.

Any help on how to get what I am trying to do done would be greatly appreciated as this is becoming a bother.

I don't see anything in bold but is the issue showing the image in your custom style or having it open in a modal?

For the latter, opening the image in a modal, you would need to set one field item to be the colorbox trigger.

The trigger needs to be a field you have already added, in your case the image field which you will use the custom display format with. Then you add the image field again with the desired popup format. You set this field to display within the colorbox trigger.

There are several related screencasts on drupal.org that may help:

https://drupal.org/project/colorbox


How to add a redirection at the end of Delete entity process? I used Drupal Console to create a custom content entity called 'Service' (with command drupal geco) which generated all expected code including 'ServiceDeleteForm.php':

<?php
namespace Drupal\sel\Form;
use Drupal\Core\Entity\ContentEntityDeleteForm;
/**
 * Provides a form for deleting Service category entities.
 *
 * @ingroup sel
 */
class ServiceDeleteForm extends ContentEntityDeleteForm {
}

I added some code of mine there:

class ServiceDeleteForm extends ContentEntityDeleteForm {

  protected function getDeletionMessage() {
    $entity = $this->getEntity();
    drupal_set_message($this->t('Le service « %label » a été supprimé.', [
      '%label' => $entity->label(),
    ]));
  }

  public function getQuestion() {
    return $this->t('Êtes-vous certain de vouloir supprimer le service « %label » ?', [
      '%label' => $this->getEntity()->label(),
    ]);
  }

}

which works fine.
I'd like to add a redirection at the end of the Delete process, something like  $form_state->setRedirect('elsewhere', [some argument]);
but I don't know how to do it.
Could someone help? Thanks in advance.

Finally, this code works:

<?php
namespace Drupal\sel\Form;
use Drupal\Core\Entity\ContentEntityDeleteForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a form for deleting Service entities.
 *
 * @ingroup sel
 */

class ServiceDeleteForm extends ContentEntityDeleteForm {

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $entity = $this->getEntity();

    $entity->delete();
    $form_state->setRedirect('elsewhere', [some argument]);
    drupal_set_message($this->getDeletionMessage());

  }

  protected function getDeletionMessage() { some code }

  public function getQuestion() { some code }

}


Scaling image using Imagick Module i'm currently using the Imagick module for Drupal 8 and the imagick php extension on the server. Whenever I try to resize images with this tool, using the settings below, I get a really down sampled version of the image, as if the all the meta data is still stripped although I specify to keep them.

As seen below the image gets really pixelated and sort of "over saturated". However I got this to work on a local server using the same settings. I just can't get it to work properly on the remote.

Setting:

Desired result:

The result I get:

So far i have tried already to switch off the meta tags, but this seems what was originally the problem on my localhost. I have also tried some of the other filters and changed the quality, but it all doesn't seem to matter. So what am I doing wrong, or what could I try to get the desired result?

Yes, this module has a critical error for your problem. A week ago an issue was opened and need to be revived. But you can add your own patch to the module by yourself.
Here is the issue and solution for Drupal v7:
https://www.drupal.org/project/imagick/issues/3026933

and you can apply to Drupal v8 under file imagick\src\Plugin\ImageToolkit\Operation\imagick

protected function process(Imagick $resource, array $arguments) {
    $color = $arguments['HEX'];
    $color = empty($color) ? 'none' : $color;
    //return $resource->colorizeImage(new ImagickPixel($color), 1);
    return $resource->colorizeImage(new ImagickPixel($color), 1, true);
  }


Make a custom view mode default I made a custom view mode in Display Suite and I would like to use it as the default view mode for a given content type. Can anybody enlighten me as to how to do it?

This is the way i set the 'fullpage' view_mode of a node as default:

<?php
/**
 * Implements hook_entity_view_mode_alter().
 */
function YOUR_MODULE_entity_view_mode_alter(&$view_mode, $context) {
  // Set default view mode.
  if (isset($context['entity']->nid)) {
    if ($context['entity_type'] == 'node' && $context['entity']->type == 'YOUR_CTYPE' && $view_mode == 'full') {
      $view_mode = 'fullpage';
    }
  }
}

It actually sets the view_mode to 'fullpage' when in full mode (default), but you could ommit that part (&& $view_mode == 'full').

Remember that 'fullpage' is the machine name of my view_mode and 'YOUR_CTYPE' is the machine name of your content type.

Not sure if this will work with Display suite though...


Ubercart Marketplace vs Ubdercart Affiliate? We want to implement a multi-seller, affiliate-like shop but I'm stuck at which module to proceed with. What exactly is the difference between the two? Documentation is quite general and one can not tell which one is better.

Ubercart Marketplace is where you want your "sellers to post their products" - more like eBay.

Whereas Ubercart Affiliate module is where "you sell your products" but affiliates help marketing those by spreading your site's links. This is much like the affiliate programs that are run by most hosting providers.

This is the primary difference. And they both plug to Ubercart. So they can leverage all UC features.

However it is possible that you use both in conjunction. Never tried that out. Would be interesting.


Order in entity_load I see Documentation of entity_load but I didn't find anything about ordering of results,
How can I order the results entity_load by delta?

as example I fetch all product of one node by

$node = node_load(313);
$field = field_view_field('node', $node, 'field_product_select');
$pids = array();
foreach ($field['#items'] as $key => $value) {
  $pids[] = $value['product_id'];
}
$products = entity_load('commerce_product', $pids, array(), TRUE);

$return = array();
foreach ((array) $products as $key => $product) {
  $return[$key]['product_id'] = $key;
  $return[$key]['product_type'] = $product->type;
  if($product->field_is_selected_price['und'][0]['value'])
    $selected_price=$product->commerce_price['und'][0]['amount'];
  $return[$key]['price'] = $product->commerce_price['und'][0]['amount'];
  $images = field_view_field('commerce_product', $product, 'field_product_images');
  foreach ((array) $images['#items'] as $image) {
    $return[$key]['img'][] = $image['uri'];
  }
}

I want fetch products order by 'delta'(or other field ),(results are order by entity_id by default) , how can I achieve it?

Most entity controller implementations of ::load() will return entities in the same order as the array of IDs passed in to be loaded. This is the case with DrupalDefaultEntityController and EntityAPIController, which are the two most common controllers.

In this case you could structure your initial query to get a list of IDs to be loaded with EntityFieldQuery and then use the results of that to pass to entity_load.

Looking at your original example, you just need to load a list of products based on the product field on a node. Here's a quick example of what it would take to handle that (since you don't need EntityFieldQuery):

$node = node_load($nid); // If you don't already have access to the node
$wrapper = entity_metadata_wrapper('node', $node);

$product_ids = $wrapper->field_product_select->raw();
$products = entity_load('commerce_product', $product_ids);

This works because the field data is always queried with order by delta when using Drupal core's field SQL storage: https://api.drupal.org/api/drupal/modules%21field%21modules%21field_sql_storage%21field_sql_storage.module/function/field_sql_storage_field_storage_load/7


Expanding the HTML view I am new to Drupal and am having trouble getting my custom HTML to take up most of the page. As you can see below, it is confined to the center and takes up a tiny percentage of the screen.

Here is the image of my module:

Thanks for all the help!

First of all, you should't use a Drupal default theme. As when you update Drupal core, you're going to overwrite all your theme files. So if you want to use a default Drupal theme you need to create a sub theme, if you haven't already. Follow this tutorial Creating A Drupal 7 Sub Theme.

Secondly, it looks small because you have items in your left column.

Thus, you need to remove the left column blocks. Go to /admin/structure/block and disable those blocks. OR Edit those blocks and in the Show block on specific pages you can control on which pages you want them to show up or be excluded from.

If that still doesn't do it, you need to edit your theme files. Go to /sites/all/themes/YOURTHEME/ folder and edit the page.tpl.php file and get rid off the left column.

Even after doing this, if you still want it bigger, then right mouse click on the page and select inspect element. Find the name of the div class or id that is controlling your output.

example <div id="hello" class="cool">

then on your css you put

#hello { width: 5000px; } if its and ID

.cool { width: 5000px; } if its class

If it has both, pick whichever you want

BTW: Your themes css file is located in the sites/all/themes/YOURTHEME/css folder.

Finally, after you make changes always remember to clear/empty your cache


Best way to dynamically change only the href of a link in the main menu not the markup I have been digging quite a bit for this and cannot believe that I am not finding way to do this as I didn't think it would be all that difficult. I would like to alter the href property of my main menu items (potentially) on each page load.

I am building a site that will take the state name in to consideration on most pages. The default main menu links do not contain the state names in the urls. I want to be able to check for the existence of a state name on a given page, and when present, append that to all the main menu items so that the state continues to be taken in to consideration on future pages.

I have seen solutions for theming links, but I do not wish to change the markup of my main menu in any way, I simply want to have the link go to a new location. I would much prefer to do this on the server side rather than using jquery to update them.

Here is what I thought would work:

function THEME_preprocess_page(&$variables) {

  foreach($variables['main_menu'] as $key => $item) {
    $variables['main_menu'][$key]['href'] = 'my_new_url';
  }
}

However, when I print the results, I see that the values in $variables are changed, but they are not reflected in the markup. Is there another simple way that I can do this without having to rewrite the markup of my menu with a theme_links__system_main_menu() call?

Check out theme_menu_link. You can add it to the template.php file of your subtheme. Be sure to return the correctly formatted string.


How can I serve a separate CSS file for Internet Explorer? I am setting responsive design for only IE (Internet Explorer) in Drupal 7.

Is there any method or solution this file is working with only IE not for Firefox and Chrome?

Use drupal_add_css with the option 'browsers'.

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

You should add this function call in your theme's template.php file through template_preprocess_html like this:

function MYTHEME_preprocess_html(&$vars){
  drupal_add_css(
      path_to_theme() . '/css/ie.css',
      array(
        'browsers' => array(
          'IE' => 'lte IE 9',
          '!IE' => FALSE
        )
      )
    );
}


How can I get path aliases arguments from a URL in a template? I have a content type which has an automatic path alias to latest-news/[title] (e.g. latest-news/example-news-title).

I need to get the first part of the path alias in my page.tpl.php file, but when I use arg(0) I am given node and not latest-news.

How can I get the first part of an aliases URL in a page template?

You can use function drupal_get_path_alias() to get the path alias, then strstr() to get the first component of the path, like so.

echo strstr(drupal_get_path_alias(), '/', TRUE);


hide the webform after submission in webform 3.0 I have a webform (webform 3 module) embedded on my websites homepage. I was looking for a way to hide the webform after it has been submitted.

-> Tried to check the $_POST but that does not work
-> Maybe the webform API could help?

Thanks.

Do you want to allow users to submit it just once ?
If so have a look at node/123/webform/configure (where 123 is your form node id), there's a "Submission limit" option. If you choose "1" and "ever" then the form will be hidden with the following message: You have already submitted this form. View your previous submissions".

If you want to redirect your user to another page after submission, you can use the redirect option in the settings page.

Does this answer your question ? Can you elaborate it a little more if it doesn't answer it ?


How to force users to logout after X minutes of inactivity using Rules, Views? How to force users to logout after X minutes of inactivity using Rules, Views or any other popular module ?

update 2012-01-27

Where can I find an example how to do the forced session expire using Rules module ?

Drupalmodules.com shows two potential modules:

Session Expire - "Expires rows from the session table older than a certain time."

Automated Logout - "This module provides a site administrator the ability to log users out after a specified time of inactivity."

Either module would probably be able to give you the functionality you want. The automated logout module looks like it could give you a timer to show how much longer a user has before being logged out.


States don't work for a block rendering a form I created a block in which I called a form inside the build() function.
The form class has elements like radio button, input field type number, and submit button. I added a state condition to make the number field and submit button only visible on a certain condition of radio button.
The submission button is working correctly based on state condition, but not the number input field.
Does anyone has any idea?
$form['age'] = [
  '#type' => 'number',
  '#min' => 0,
  '#title' => $this->t('age'),
  '#default_value' =>'',
  '#states' => [
    'visible' => [
      [':input[name="marital_status"]' => [['value' => 'single'],['value'=>'couple']]],
    ]
  ],
];

$form['mybutton'] = [
  '#type' => 'submit',
  '#value' => $this->t('button'),
  '#states' => [
    'visible' => [
      [':input[name="marital_status"]' => [['value' => 'single'],['value'=>'couple']]],
    ]
  ],
];

$form['marital_status'] = [
  '#type' => 'radios',
  '#title' => $this->t('Marital status'),
  '#options' => [
    'single' => $this->t('single'),
    'couple' => $this->t('couple')
  ]
];

I had to override the twig files for the form-element so some classes were missing like js-form-item' and 'form-item'. After adding thoses classes in the twig file,  the states worked.


Is it normal that Organic Groups group creator is not automatically "Administrator member"? I am getting my head around OG and its permissions. I have a user (not super-user uid=1) who can create OGs. Rather to my surprise, when I look at the OG members, the user who created the OG is there as a member but has not been given the "Administrator Member" role. Yet he seems to have full management rights on the Group rather like a local super-user. Does this mean that he should create an "Administrator" separately?

I should have seen this myself.
In fact the answer is in the slightly obscure "OG Settings" (Config > Organic Groups > OG Settings).

In this there is an option called "Group Manager default roles" which is applied to every OG content type. This allows you to "Select the role(s) a group manager will be granted upon creating a new group"

Problem sorted!


How do I Convert time/date format? I have created a View and added a filed Date. This Field have 4 type of Formatter

1) Date and Time
2) Time Ago
3) plain
4) Services Raw

If I select First it give HTML tags in output and if select 3rd or 4th it give output like these numbers "1439393400"

I need the simple date in output without any HTML tags. Please tell me how I can get rid of HTML tags if I select first option. If its not possible then how I can convert the output which I get from Plain Formatter so that I get simple date not these number.

For creating a new date format to be used in views:-

Go to yoursite.com/admin/config/regional/date-time
And create the new format.

Now, Go to the view you're working on, add date field, change its format. Yes, it's as simple as that.

Plus: You can use Date module, it has got amazing features.


How to set the filter condition by default for specific condition in view How to set the filter condition by default for specific condition in view i,e i have view with the filter condition STATUS drop down list has 1]live 2] discard,so here i want to filter by default for live status when i open this view can any please tell me how to do this?

Thanks a lot in advance.

Use group filters, that way it will allow you to set a default.


How to add link to Comment Author's User Profile page The below code is from the comment.tpl.php file:

<?php print $picture ?>

<?php print render($content['submitted_by'] ['#markup']);?>

I want "$content['submitted_by'] ['#markup']" to link to the user profile of the user who posted the comment.

i have tried editing the code to something like this:

<?php $link = drupal_get_path_alias('user/' . $user->uid);?>

<?php print $picture ?>

<a href="<?php $link ;?>"><?php print render($content['submitted_by'] ['#markup']);?>

But it links to the user profile of the currently logged in user.

What I would like is to link it to the profile of the Comment author.

Thank you.

Comment module does add a link to comment author name on comments view. The link is conditionally visible to user's i.e. If user has permission to "View user profiles" or administrative permission then he will be able to see author name as link, else plain text. See screenshots below (tested with Anonymous user with and without permission "View User Profiles"):

Permissions:

Comment preview with permission:

Comment preview without permission:

You can still add a link to author name by your own, by implementing template_preprocess_comment() function in your theme's template.php or .module file. This might lead to access denied page:

/**
 * Process variables for comment.tpl.php.
 *
 * @see comment.tpl.php
 */
function [THEME_NAME]_preprocess_comment(&$variables) {
  if (!empty($variables['elements']['#comment']->uid)) {
    $variables['comment_author'] = l($variables['elements']['#comment']->name, 'user/1/' . $variables['elements']['#comment']->uid);
  }
  else {
    $variables['comment_author'] = t('Anonymous');
  }
}

And then printing "$comment_author" variable in comment.tpl.php file, see below.

<p class="commenter-name">
  <?php print $comment_author; ?>
</p>


Make page accessible to logged in users only I need to make a basic page available to logged in users only and also need to retrieve information based on their login. I installed the Content Access module but it is not granular enough for me. Where would I modify the page that non-logged in users see?

Also, is there a way to store additional information in the user account such as an ID to our third-party database that we use to store user information? I will be retrieving this information to show in my first sentence above.

If it's a specific page on your system, create a page-----.tpl.php for it and put in there something like:

<?php if ($logged_in): ?>
  // do whatever you want for logged in users
<?php else: ?>
  // do whatever you want for anonymous users
<?php endif; ?>

If you are using Drupal 6, the http://drupal.org/project/content_profile module allows for all sorts of additional profile content fields.  In Drupal 7 I am assuming you'd use profile2 but I am only now learning about D7 (mostly from answering D7 questions with D6 answers ;)


Add HTML Chars To Breadcrumb Kickstart 2 How does one enable html special chars (eg. ® ) in the breadcrumb?

Apparently, the Kickstart 2 uses a custom Crumbs module and I can't figure out how to override the PHP generated as with a 'regular' Drupal theme since it doesn't use the core theme_breadcrumb() function.

There are different parts to this answer.

  since it doesn't use the core theme_breadcrumb() function.

By default, it does use theme('breadcrumb').
But you should have a look at the settings in admin/structure/crumbs/display.

But the check_plain() that causes special characters to be double-escaped happens in theme_crumbs_breadcrumb_link() and theme_crumbs_breadcrumb_current_page(), which you could also override.

You could also look at the $double_encode option in htmlspecialchars(), so you could use your own version of check_plain().

This being said:
Simply omitting the sanitization for all breadcrumb links is a bad idea, and potentially exposes your site to script injection. If anything coming from a non-trusted source ends up in the breadcrumb, or if people add broken html into a node title or menu link title or elsewhere, this could cause broken or malicious html on your site.

I think the better option is to just use the literal character in the node title, instead of the html entity.

Some general info:

With Crumbs, every breadcrumb item title is provided by a plugin. The plugins take these from menu links, from the title / title callback of the router item, or elsewhere. In most cases there is already an existing plugin which provides the breadcrumb item title you need.

Otherwise you can write your own plugins. I can give you a hint about that, but I need more information where you want the special char to show up. (I will edit the answer then)


Statistics module doesn't show the "Enable access log" checkbox Drupal 8 Statistics Configuration http://curiosidad-racional.tk/drupal8statistics.png

I dont know what to do to show "Enable access log" option.

I activated logging all messages and checked all statistics permissions.

Thanks.

I'm not sure what you are looking for exactly. That's the only thing that statistics.module is doing in 8.x.

Anything else was removed. Maybe there will be or already are contrib modules providing what statistics module did in 7.x. But tools like Google analytics or Piwik provide a lot better data anyway.


Can't remove document file from Media I've created a WebForm that allows a user to upload a document file.  The file stores to Media which I'm using for images.  I can delete the image files but I'll be dog-gone if I can figure out how to delete the document files.  I've deleted the WebForm submission but when deleting the file in Media, I get the 'in use and cannot be deleted' message. Does anyone know how to delete this type of file?  I'm in the Administrator account so privileges shouldn't be the issue.  Thanks!

You probably need to delete or remove the file from any nodes, or webform submissions that it references. There should be a usage tab on the actual media resource. I don't have a media site handy so I can't provide screenshots. Once that usage tab is empty, it should be possible to delete that file. Otherwise I'd check the recent log messages in admin/reports to see if there's a file permissions issue, like the only file owners can delete files.


How to use custom class methods in the .theme preprocess functions? In a try to get code cleaner, I thought I could write a service in a custom module and use its methods within mytheme.theme, but obviously the preprocess functions signatures don't accept extra parameters.

In modules/custom/custom_module/src/Service/FooThemeHelpers.php

namespace Drupal\custom_module\Service;

class FooThemeHelpers
{
  // Add a specific custom format
  public function format_profile_adresse($field_profile_adresse){

    // do stuff ...

    return $markup;
  }
}

Then in mytheme.theme

use Drupal\custom_module\Service\FooThemeHelpers;

function mytheme_preprocess_views_view_fields(&$variables, FooThemeHelpers $themeHelpers) {

    if($variables['view']->id() == 'bar') {

      $markup = $themeHelpers->format_profile_adresse($variables['fields']['field_profile_adresse']->content);
      $variables['fields']['field_profile_adresse']->content = $markup;
  }
}

  TypeError: Argument 2 passed to
  mytheme_preprocess_views_view_fields() must be an instance of
  Drupal\custom_module\Service\FooThemeHelpers, string given

I tried also with template_preprocess_page_title(), same error.

Should I declare and use static methods instead in my service ? Is there any Drupal coding standard way to export these helpers functions in a dedicated class, so that .theme remains lighter and readable... ?

The dependency injection coding standards only apply to most * classes.
In functions, use $service = \Drupal::service('service_name') to get the service.

To test code written in these functions, mock the services then build a custom container for them and assign it to Drupal using \Drupal::setContainer($container).

See Drupal\Tests\Core\Annotation\TranslationTest for an example of building a test container.

* Entity types, classes implementing TypedDataInterface, and certain plugins with custom plugin managers do not support dependency injection.


View's row style output is NULL, template file not found in ./ I'm theming a block view that displays content that is related to the current node. When I preview the view results they show up fine, but the content doesn't render in my theme.

When I examined more, I noticed the views-view-unformatted template renders correctly and contains three rows as expected, but each of the rows just contains the value NULL.

The theme information tool in Views gives the following error regarding row style output:

  Row style output: views-view-fields.tpl.php, views-view-fields--read-next.tpl.php,
  views-view-fields--default.tpl.php,
  views-view-fields--default.tpl.php, views-view-fields--block.tpl.php,
  views-view-fields--read-next--block.tpl.php (File not found, in folder ./)

I created the file views-view-fields--read-next--block.tpl.php with the following content:

<?php foreach ($fields as $id => $field): ?>
    <?php print $field->content; ?>
<?php endforeach; ?>

Unfortunately that did not help. The file is still not found and nothing is rendered. Other things I've tried:

Disabling devel_themer
Clearing all caches
Restarting Apache
Checking file permissions
Changing the view formatting back and forth a few times
Edit: Rescanning the template files

What can be the problem? I don't know where to look next. I'm using Views 7.x-3.10.

After creating a new tpl file for views to pick up you need to hit the button called " rescan template files" at the bottom of the window. So that your new tpl gets highlighted.


Adding attributes with hook_node_view_alter I'm trying to modify the "Add new comment" link in certain nodes, and for this I'm using hook_node_view_alter like this:

function example_node_view_alter(&$build) {
//    $build['links']['comment']['#links']['comment-add']['attributes']['class'] = 'nice small radius blue button';
      $build['links']['comment']['#links']['comment-add']['title'] = t('Add a review');
}

The commented line is causing trouble though,... since the array doesn't have a 'class' attribute. If I just add it to the array like that, every time I clic on the "add a review" link, the website isn't rendered properly... so how can I add it without ruining everyhting else?

The class property is an array so you need to initialise it like this:

$build['links']['comment']['#links']['comment-add']['attributes']['class'] = array(
  'nice',
  'small',
  'radius',
  'blue',
  'button'
);


CSS selectors for specific pages I'm working on a custom theme which involves styling specific pages and nodes. At first, to target these specific nodes, I used the selector page-node-##, where ## is the node ID. But this was on my local machine, and when I exported these nodes, I found that the node IDs would be different on both the staging and production servers. Is it better to use the section-XX, selector instead?

I was wondering if there is a recommended CSS selector for this kind of use cases, where the CSS is applied on specific pages/nodes?

A good way to do this using context:

Under conditions select Path and input your path

then under Reactions select Theme HTML.  Here you can select the class you wish to add to the body.


How to alter price in checkout page and when submit order I have a discount price for product. I want alter price of product  using discount price if user has voucher.
How to alter price of page cart, cart/checkout and when user submit order.
Please help me!

You could use a HOOK for your needs, just read a little bit about hooks, and then create a hook for your content type and change that price.

You can check here how to first create a module and then a hook

Hooks in drupal tutorial


How do I change my Admin theme? I'm brand new to Drupal and have just installed Drupal 7. When I was configuring it, I originally selected "Stark" as my Admin theme, thinking I would create my own CSS later. In trying to learn Drupal and add content, I have decided that I would like to change my Admin theme. I went to the Admin tool bar (across the top) and clicked "Appearance" and changed my theme there, I even disabled the "Stark" theme, but my Admin theme is still defaulting to the Stark theme. How do I change this?

Go to admin/appearance and you will see a fieldgroup called "Administration theme" at the bottom.


Change the cardinallity ratio of a an already existing field from 1 to unlimited I've created a webform with a text field which has cardinality of 1 and there are submissions made for that webform. I now want to change the cardinality to unlimited, but I can't do it in the webform UI. I'm not able to change the value.
This is the tootltip shown when I hover over the Allowed number of values field in webform form element settings Allowed number of values field.

There is data for this element in the database. This setting can no longer be changed.

I tried to programmatically change it using hook_form_alter().
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_id') {
    $form['field_name']['cardinality']['#default_value'] = FIELD_CARDINALITY_UNLIMITED;
  }
}

That didn't work either. Where am I going wrong?

It is possible to change an element with a singular cardinality via the YAML source without any data loss. You would definitely lose data going from multiple cardinality to singular.
In the YAML source, add the '#multiple': true property to the element.
name:
  '#type': textfield
  '#title': 'Name'
  '#multiple': true


Check if the user has flagged content with any flag It is possible with the following code to check if a content has been flagged by the current user with a certain flag:
$flag = flag_get_flag('flag_name');
if ($flag && $flag->is_flagged($node->nid, $GLOBALS['user']->uid)) {
  print "This node is flagged";
}

But, how to check if the user has flagged content with any flag ?

The flag module has a utility function flag_get_flags() that retrieves multiple flags, with an option to filter on the entity type of the flag:
// Same logic, looped over multiple node flags:
$flags = flag_get_flags('node')
foreach ($flags as $flag_name => $flag) {
  if ($flag && $flag->is_flagged($node->nid, $GLOBALS['user']->uid)) {
    print "This node is flagged";
  }
}


How to tell if XML Sitemap is correct? I have installed the XML Sitemap module, and enabled the xmlsitemap_menu sub-module.  I found how to add the main menu to the sitemap (via this site - no thanks to the module's documentation). When I go to the XML Sitemap admin page, it lists mysite/sitemap.xml as having 91 links and 1 pages. Shouldn't the page count be higher?  Also, I would like to view the generated output, but when I click the sitemap.xml link, all I get is a table with link to the front page.

How can I see the actual XML or sitemap output?

To make sure you have the content types that you want in your sitemap, you can enable xmlsitemap_node.  After enabling, visit each content types configuration page and select "Include" under the xmlsitemap tab.

After setting each content type, you can check the Included/Excluded status for all content types under the xmlsitemap module config page.

Once that is complete, you can run cron manually to regenerate the sitemap links.  Check www.yoursite.com/sitemap.xml to view the newly generated sitemap.


autocomplete tags in textarea? I need a tagging functionality for my content type. The normal term reference tag autocomplete widget has a problem, because I can't find a way to use textarea instead of textfield for it. I would need textarea to be able to see all tags while typing them. One node will have 10-20 tags, some of which are not just words, but expressions. So it all takes place and textfield is not acceptable.

How to enable entering tags into textarea with autocomplete?

You should use Autocomplete Delux module. After installing and enabling the module you can change your tag field widget in your form.
Autocomplete Delux:

This is an enhanced autocomplete element, that uses the JQuery UI autocomplete. It will also implement a widget for taxonomy.


What's best module to built pie chart? I want to build a pie chart to make a statistic for all my events. But, there are a lot of module. I want to know what's the best and responsive? I'm using drupal

I would suggest https://www.drupal.org/project/easychart. It has support for both Drupal 7 & 8. I don't have a lot of experience with the module itself but I have used the Javascript library (http://www.highcharts.com/products/highcharts) it uses and it is nice.


How to add a button to report (flag) some content item to an administrator for that content? I would like to print near a given type of content a button "report" that, when pressed, send a notification to the admin related to that content.

In this specific case, I have a textual field with a link and I would like to allow users to be able to report (signal) some content item to the administrator if some link is not working anymore. So that the administrator can fix it.

You should investigate the flag module https://www.drupal.org/project/flag and Rules https://www.drupal.org/project/rules (remembering to use version 2.7 of the latter if using drupal commerce) that should allow you to create a "report" flag and send a notification to an admin.


Drupal and node relationships For our final CS project, we have been tasked with building a project management system for a large corporation (which the company wants us to use Drupal). So far we have a few entities created (project, request, and task). A project can have many tasks, and a project can only have one request attached (the request is created first, once approved, a project is created).

Since Drupal is really more of a content (blogs/comments/articles/pages) management system, it is difficult to create dynamic forms that allow showing tasks attached to a project with the ability to add tasks directly within the project "form". I guess this would kind of be a master/detail view.

How can I go about building these types of add/edit/details "forms"? My first two ideas are:

Build custom add/edit/delete forms for each entity type
Build a node-add-project.tpl.php, node-edit-project.tpl.php, etc... for each complex view required

The downside to this is that my fields in my forms are now hard-coded. One requirement is that this system must be dynamic so the end-user can add a field if they need to.

How can I go about this? Templates? Custom Forms?

By the way I have googled, and googled, and googled (probably 5-8 hours) of different things (master details, complex forms, complex entity relationship forms) to no avail.

I am aware of the nodereference and entity reference (and all other reference) types. But these only allow you to use a dropdown list, or a select list, etc...

EDIT:

It is looking like building the database with the Schema API, and utilizing the Form, Theme, and security APIs are going to be our best bet.

Here is a good read.

You should be able to duplicate this functionality using the Field Collection module.

In short, you attach a Field Collection field to an entity, and then define the Field Collection in a separate UI (/admin/structure/field-collections) by attaching additional fields to it. It will behave like (and is in fact internally represented as) a first-class entity, and the module allows you to manage these items from the same parent form you attached the Field Collection field to, complete with drag-and-drop for reordering and the like. It also has a number of other nice features, such as letting users with appropriate permissions add/edit/delete Field Collection items while viewing the parent node without having to go into the edit form itself.


Let the user choose the field type I'm working on a drupal project and part of it is a sort of "tile overview" page. Its a 3x? grid, with a variable length.
|--|--|--|
|--|--|--|
|--|--|--|
|--|--|--|
 .. .. ..
Sort of like that, I hope you can tell what I'm trying to describe.
Each row of 3 is a field_collection.
Now, each field can be either an image field or a text field. I want the user to be able to choose. How would I implement such a feature?
My solution as of now is to have 6 fields per row: one image field and one text field per each single field. Then the user would be told to only fill in one. If he fills in both, one of them gets ignored (php: isset() priority). Obviously this is far from optimal. What I'm looking for is like a radio button functionality so that when the user has a value set for one of the two possible field types, the other one gets disabled. Or just let the user decide first which he wants and then only display that one.
Help would be much appreciated.

Check this module:

Conditional Fields

This module lets you to set things such a visibility, depending on other form elements.

It works based on Drupal's States API ( which you could also use in your custom module to achieve what you want )


Automatic Node titles to generate a title based on taxonomy I’m using Automatic Node titles to create node titles based on taxonomy terms.
In my node I have 3 flat vocabulary:

Color, size, year.

One CCk field for the price.

And 1 hierarchical vocabulary(Makes and models)using a dropdown list.

I want the title to Show only terms from the hierarchical vocabulary(Makes and models)..Something like this:

 [Make term][ Model term ]  for [ price ] $.

This is easy to do with Drupal 7, using term patterns, but with Drupal 6, I guess the best option would be to use PHP. Which I have no clue about.
I found this code  here:

      <?php  $terms = array_values($node->taxonomy[1]);
       print taxonomy_get_term( $terms[0] )->name;
       print taxonomy_get_term( $terms[1] )->name;
       ?>

But It’s not working at all. Any idea?.

I suppose that one of the simplest things to check would be that you're calling the correct taxonomy id at this step: array_values($node->taxonomy[1]). If the taxonomy id of the make and model vocabulary you created isn't 1, this won't work as you expected.

The Devel module is very helpful for this. If you have it installed, you can open the node in question, click on the "Devel" tab and scroll down until you find taxonomy. It'll list the ids currently in use on the node.

Another way, if you don't have or want Devel, is to go to your taxonomy listing at 'admin/content/taxonomy'. When you click on "list terms" for your make and model vocabulary its id will be displayed in the URL.

That is the id you want to have in your first line: array_values($node->taxonomy[1])

-------------[edit]---------------

As per your comment below, I would suggest using something like this:

$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid');

Where $node is the node object, $vid is the id of the vocabulary you want to limit the term search to.

Then you can loop through the terms using:

foreach($terms as $term) {
  print $term. " ";
}

------------[update]--------------

Use the standard PHP function implode to put in your spaces:

implode(" ", $terms);

The added space will put spaces between the terms in the array. This is, of course, assuming the terms will be returned in an order that makes sense for what you're doing.


How to install Accelerated Mobile Pages (AMP) without composer I do not wish to use composer.
I wish to try out Accelerated Mobile Pages (AMP) (in D8).
Is this possible and how do I do it?

Since the AMP module requires the Lullabot AMP Library, there really is not a great way to install this without Composer. That is because Composer will update the autoloader information with that namespace and vendor information and fetch dependencies. Downloading the tarball of the module and the GitHub download unfortunately will not do the trick - you must use Composer. The module will block installation if it cannot find the class namespace of \Lullabot\Amp.

The Lullabot AMP Library also has its own dependencies listed in its composer.json, so Composer is required here.


Is there a way to show the Google Analytics panel inside a drupal site? I'm using the Google Analytics module to track the visits.

Is there a way to show the Google Analytics panel inside the Drupal site?

Google analytics reports Provide you a default report page. You can use the Query hooks to make your own query and show it as a block or panel.

They provide common queries like visits, Top pages viewed etc.


Desaturate not working in image styles I have an image style which has Desaturate and Scale & Crop turned on.

I call it using this:

<a href="<?php print image_style_url('gallery_full', $image['uri']); ?>"><img src="<?php print image_style_url('gallery_thumb_grey', $image['uri']); ?>" />

It outputs the image resized but doesn't desaturate it. There are no errors.

Any ideas?

This is kind of a crappy answer, but the fix was to switch to using ImageMagick. I still don't know what was wrong with GD.


Convert Uploaded Files To .pdf I'm reviewing a spec. that calls for all files uploaded via a file field to be automatically converted to PDF format.  I have two questions:

Is this wise?  Files would be uploaded by anonymous customers.  Allowed file extensions (.doc, .xls, .png, .jpg, etc) would be provided as per normal file field use.

(Edited to clarify my main concern is security)

Are there any conversion tools you would recommend?  Paid or free is fine.  Remote service is fine, local server-based is preferable.  I can't find anything in the Drupal-verse, but have uncovered tools such as unoconv and JODConverter that look promising.

Personally, I would store the file as it was uploaded, and then render it as a PDF for users when they download it.  Your spec may say PDF now, but you want to have the flexibility should things change in the future.

Is this a good idea?  That is a tough question, and really depends on the exact scenario.  Personally, I would push back on this requirement.  Format conversion can tax system resources, and I don't think you can really constrain the .doc and .xls formats enough, like you can with images, to be something reasonable.

Tools?  The Printer, email and PDF versions module has a list of of the PHP-based PDF modules:

dompdf
mPDF
TCPDF
wkhtmltopdf

I am unaware if any of these will support .doc or .xls formats.  I have used Ghostscript to convert images to PDF, and I am pretty sure it has some support for .doc.  I am unaware of any Drupal-ready solution for this, though.

As for security implications, the scenario "makes my spidey sense tingle", but I can't point to anything in particular.  I don't think you would have any problems with any of the malicious payloads in .doc and .xls files that normally affect Windows machines.  However, if you go with a solution like GS, you will have to use a popen() or something similar, so you run the risk of an exploit there.


Separate users content by year chosen Website has several types of users and all can post images, videos, events etc.

One user type is hard to solve for me.

This user type is summer school that is happening every year and last for few weeks.

This user as all other can post images, videos, events etc. but i would like to separate all of these by the year.
So summer school happened in 2009, 2010, 2011 etc.

For other user types i have menu in sidebar:
Bio
Photos
Videos
Etc.

For summer school i have the same menu but somehow i would like to have a year above the menu with drop down if possible ? When year is picked website should remember it so the menu gives content based on year picked.

Also when user (summer school) creates content it should be able to pick which year it happened. I can use date field here i guess, but the bio should remain the same for any year chosen.

Hope i was clear enough.

A "user type" is a role, right?

You can create a Year field as either a Date, Taxonomy, or plain Text field.  Then you can attach it to each of the content types that these users are allowed to post.

I have not used it myself, but I think that the Field permissions module will let you restrict this field to just the desired role.  If that does not work, you could do a little theme work to add the user's role(s) as CSS classes on the <body> tag, then hide the Year widget with CSS.


How to count elements grouped by an specific field? I have a view with elements grouped by some categories, I would like to add the number of elements grouped in the same category, something like this:

Categ A (2)

element
element

Categ B (3)

element
element
element

I tried with aggregations but I didn't get the result I was looking for. Is there any way to resolver this?

You can use Views Aggregator Plus for this.


Inject service(s) into Drupal unit test? I am writing a unit test upfront for a service that does not exist yet. Let's just say it is called ResponseFormatter.

I want to start adding unit tests for what I expect this service to do. How do I inject it to a UnitTestCase, or reference it?

Example, I am trying to do something like:

class FormatterTest extends UnitTestCase {

  /**
   * @dataProvider responses
   */
  public function testThisWorks($response, $expected) {
    // the following line I want to call a service,
    // ex. like $this->responseFormatter->format($string);
    $clean = html_entity_decode(strip_tags($response));
    $this->assertEquals($expected, $clean);
  }

  public function responses() {
    return [
      ['not-set', 'not-set'],
      ['foo', 'foo'],
      ['&amp; #93 bar', '& #93 bar'],
    ];
  }
}

If your new service is sufficiently independent (it doesn't have any or many of it own dependencies), then just create it the setUp().  And then if you have dependencies, you set up mocks (also called doubles).

An example of a this in core is TimeTest::setUp() does:

protected function setUp() {
  parent::setUp();

  $this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
  $this->time = new Time($this->requestStack);
}

A mocked request stack is created, and the setup then directly instantiates the service class being tested (Time() in this case), passing in the mocked dependency to the constructor.

Then assertions in test methods are pretty simple

public function testGetRequestTime() {
  $expected = 12345678;

  $request = Request::createFromGlobals();
  $request->server->set('REQUEST_TIME', $expected);

  // Mocks a the request stack getting the current request.
  $this->requestStack->expects($this->any())
    ->method('getCurrentRequest')
    ->willReturn($request);

  $this->assertEquals($expected, $this->time->getRequestTime());
}

The mock simulates what the service's dependency would do, and then the service method is invoked directly.

If your service has a lot of dependencies, or mocking them is hard, then you should do a KernelTest instead of a TestCase or UnitTest.  However, that may be an indication that your service is too complicated and needs to be broken up (I am also having a problem thinking of a core service that is kernel tested and not unit tested).


How to put google map field in my form of my custom module? i like to build a form field based on google map, where user can put in their address, city and country, then the map will automatically search for it.
and then you can put a pin to define the exact location, which the expected output is latitude & longitude which will be saved during form submit.

how to approach this? is there any module in Drupal 8 that i can use during form generation?

maybe something like:

 $form['map'] = array(
      '#type' => 'gmap',
      '#otherProperty' => propertyValues,
 );

Thank you,
AnD

use this
it works for me
https://www.drupal.org/project/google_map_field
.
.
.
.
.
.


Drush cannot find your database connection details I try to install open social using drush-8.3.0 and drupal-8.7.5. The first step is to run composer create-project goalgorilla/social_template:dev-master public_html/peer/opensocial --no-interaction. that works fine. The next step is drush -y site-install social --db-url=mysql://root:root@db:3306/social and results in the following error:

Drush\Sql\SqlException: Unable to find a matching SQL Class. Drush cannot find your database connection details. in phar:///home/username/bin/drush/drush/commands/sql/sql.drush.inc:554

Using MySQL Wizerd and MySQL admin I have created the social database and defined username, password and ip address in drush -y site-install social --db-url=mysql db_username db_password://root:root@IP address:3306/social.
I have no ida how to find out what is realy going on? I am on a linux shared server. Can anybody help? Here is stack trace:

#0 phar:///home/username/bin/drush/drush/commands/sql/sql.drush.inc(539): drush_sql_get_class(Array)
#1 phar:///home/username/bin/drush/drush/commands/core/site_install.drush.inc(124): drush_sql_get_class()
#2 phar:///home/username/bin/drush/drush/includes/command.inc(422): drush_core_pre_site_install('social', '://root:root@10...')
#3 phar:///home/username/bin/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#4 phar:///home/username/bin/drush/drush/includes/command.inc(199): drush_command('social', '://root:root@10...')
#5 phar:///home/username/bin/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#6 phar:///home/username/bin/drush/drush/includes/preflight.inc(67): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#7 phar:///home/username/bin/drush/drush/includes/startup.inc(465): drush_main()
#8 phar:///home/username/bin/drush/drush/includes/startup.inc(369): drush_run_main(false, '/', 'Phar detected. ...')
#9 phar:///home/username/bin/drush/drush/drush(114): drush_startup(Array)
#10 /home/username/bin/drush/drush(10): require('phar:///home/oi...')
#11 {main}

when I run drush @hpc.dev sql-conf I get this:

Scanning into /home/username/public_html/peer/opensocial/html/sites/default for /hpc.dev.alias.drush(8|)rc.php$/ [0.33 sec, 7.29 MB]                                                                                [debug] Could not find the alias @hpc.dev [0.33 sec, 7.29 MB]

First of all, you should really use Drush 9 or 10 - see https://docs.drush.org/en/master/install/#drupal-compatibility And install Drush site locally as described on the same page.

However, the message Unable to find a matching SQL Class probably means that shared server you are running Drush on is missing the needed PHP database extensions. This is typically PDO with MySQL (pdo_mysql and mysqli) - see https://www.drupal.org/docs/8/system-requirements/php-requirements#database

A typically problem is that PHP in the web server has these extensions, but not PHP on the command line.


Attaching additional queries to webforms I'd like to limit the ability of a form submission based on whether a user has submitted the form already.

So basically if a user has submitted a form, they can not submit again.
I've already created the form using webforms, I just need to figure out how to limit the submissions now.

Webform has already this option, that you can find in the Submission settings. Otherwise, if you need to check something more you still can use some Webform hooks.

But if you need more complex submission checking, the best way from my point of view is to add a validate callback with the help of hook_form_alter().

Edit

Here is an example how to use the hook_form_alter(); For it, you must install the module Devel before.

// First you have to create your module
// you will find more information about it
// here http://drupal.org/node/231276
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // To add your validate callback to any form, you must find
  // the right form_id before
  // the form_id is an id that identify the form
  // from all that drupal can generate.
  // My solution to find it quickly its to show
  // all form_id with the help of Devel
  dsm($form, $form_id);
  // This will show you a drupal_set_message with something like that
  // form_id_form => Array()…
  // When you found the form that you want add the validate callback you
  // change it like that
  if($form_id == 'the_form_id') {
    $form['#validate'][] = 'mymodule_myvalidate';
  }
}

function mymodule_myvalidate(&$form, &$form_state) {
  // Here you can see want you receive
  // by checking the content of $form_state
  // still with Devel, like that
  dsm($form_state);

  // You should see the values in $form_state['values']
  // After you can make your additional checks and retur errors like that
  if($error) {
    form_set_error('field_error', t("You can balbla"));
    return;
  }
}


How to re-generate Node Object from database stored Serialized Node Data .. and then Save as New Node? In Drupal 7, for some reason, i am storing some serialize($node) objects into Database. So these data in the database (in text column) are storing like:

O:8:"stdClass":47:{s:3:"vid";s:5:"78629";s:3:"uid";s:3:"523";s:5:"title";s:12:"Sync Node #6";s:6:"status";i:1;s:3:"nid";s:5:"77429";s:4:"type";s:4:"page";s:8:"language"; ..... etc

Now how can i transform these data back into Drupal $node Object please?
Then how can i node_save($node) (as new node) upon them? (What tricks will i need?)

Any idea please?

Now how can i transform these data back into Drupal $node Object please?

As said you can use the following code,

$node = unserialize($data);

  Then how can i node_save($node) (as new node) upon them? (What tricks will i need?)

You can null the nid, vid and use node_save to save it as a new node like this:

$node->nid = NULL;
$node->vid = NULL;
node_save($node);


Creating paragraph entities and adding to a node I am using the Paragraph module in and I need to programmatically create paragraph entities and attach them to nodes.

Using the following code in a for-loop:

$paragraph = new ParagraphsItemEntity(array('field_name' => 'field_page_body', 'bundle' => 'text'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);
$paragraph->save(TRUE);

The paragraph entities are created and attached to the target node but the data is NULL for all 3 entries as the image below shows:

A properly working set of Paragraph entities attached to a node look like the following:

So, instead of UND i:e undefined, I am trying to attach programmatically created arrays of paragraph entities to my nodes.

Can anyone advice how I can modify my code to include my array of Paragraphs data?

I have a similar function and would recommend that if you already know what language your node is, you capture it from the node and use it for the language in the paragraph field. I only had 1 language to worry about but you could easily replace LANGUAGE_NONE('und') with the appropriate language code from the node.

$paragraph = new ParagraphsItemEntity([
  'field_name' => $host_field_name,
  'bundle'     => $para_bundle,
]);
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', node_load($this->node->nid));
$paragraph->field_long_text[LANGUAGE_NONE][0]['value'] = $field_content;
$paragraph->field_long_text[LANGUAGE_NONE][0]['format'] = 'wysiwyg';
$paragraph->save();


Submit a custom form as a webform submission I have a custom form i created using FAPI and i wanted to submit the values into the webform  database table and/or content type as a node. i wasnt sure of the "drupal Way" of doin this. Here's my current submit  function, Please tell me if im doing this correctly or if not what is the correct way? (P.S. i dont want to use a different r another module or save to my own custom table.)

function contracts_webform_submit($form, &$form_state) {
 module_load_include('inc', 'webform', 'includes/webform.submissions');
 module_load_include('inc', 'webform', 'includes/webform.components');
 global $user;

$node = $form['#node'];
$sid = $form_state['values']['details']['sid'] ? (int) $form_state['values']['details']['sid'] : NULL;

// If there is no data to be saved (such as on a multipage form with no fields
// on the first page), process no further. Submissions with no data cannot
// be loaded from the database as efficiently, so we don't save them at all.
if (empty($submission->data)) {
 return;
}

 // Save the submission to the database.
if (!$sid) {
 // No sid was found thus insert it in the dataabase.
 $form_state['values']['details']['sid'] = $sid = webform_submission_insert($node, $submission);
 $form_state['values']['details']['is_new'] = TRUE;

 drupal_set_message(t('The form has been submitted.'));
 }
}

Without really knowing much else about the custom requirements of your form it's difficult to give a complete answer however your on the right track by using Webform.

You should recreate as much of the form as you can using webform as a base rather than FAPI. Then you can use FAPI to alter (hook_form_alter) the existing form that webform outputs.

Your custom FAPI code can then be worked into the way webform works, you may have to massage some of the data based on your requirements though.


Reinstall a module that has .yml file in config\install A good enhancement in Drupal 8 is having list of yml file to import via installation in mymodule_root\config\install, but this means I can not reinstall a module because the configuration settings already exist in the active configuration.

Actually the problem is when uninstalling the module: The imported configuration settings, imported during installation, aren't waived.

Test scenario

Put this sample .yml file in yourmodule_root\config\install\systme.site.yml.

name: 'Admissions at Adelaide'
mail: admin22@example.com
slogan: ''
page:
  403: ''
  404: ''
  front: caslogin
admin_compact_mode: false
weight_select_max: 100
langcode: en
default_langcode: en

See How to remove mymodule configurations on uninstall for a best-practice solution.

Basically, you can enforce the dependency on your module in your configuration files.  So when the module is uninstalled, it's associated configuration will be uninstalled as well.


Add Field as Entity in Group Module The group module is an alternative to the og module.  The og module allows you to assign permissions to fields per group.  I would like to be able to do the same thing with the group module.  It appears that in order to do this, I need to add a field or fields as an entity in the Group module. All my searches seem to indicate that the GroupContentEnabler plugin will enable me to do this. But I can't find any clear example of how. Can someone point me to some documentation on how to go about coding this?

Follow up:

It appears that hook_entity_field_access() will allow me to do what I wish to do.  I found an example of it's use in the group module:

This is the code used in group.module (not gnode.module):

/**
 * Implements hook_entity_field_access().
 *
 * {@inheritdoc}
 *
 * @todo Move this to a form controller so we can hide the field if it has no
 *       options available to it?
 */
function group_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  // Can't retrieve an entity from an empty item list.
  if (!isset($items)) {
    return AccessResult::neutral();
  }

  // We only care about the group_roles field when on a form.
  if ($field_definition->getName() != 'group_roles' || $operation !== 'edit') {
    return AccessResult::neutral();
  }

  **// We only care if it is attached to a group content entity.
  if ($items->getEntity()->getEntityTypeId() != 'group_content') {
    return AccessResult::neutral();
  }**

  /** @var \Drupal\group\Entity\GroupContentInterface $group_content */
  $group_content = $items->getEntity();

  // We only care if the group content entity is a group membership.
  if ($group_content->getContentPlugin()->getPluginId() != 'group_membership') {
    return AccessResult::neutral();
  }

  // Now that we know we're dealing with a group_roles field on a group
  // membership form, we need to check whether the group membership belongs to a
  // group yet. If not, we can't check for access and should always hide it.
  if (!$group = $group_content->getGroup()) {
    return AccessResult::forbidden();
  }

  // Only group administrators should be able to change the membership roles.
  return AccessResult::forbiddenIf(!$group->hasPermission('administer members', $account));
}

It appears that all I have to do is create a group permission, then check access to the field in question against that permission using hook_entity_field_access().

My only question is with this code:

// We only care if the group content entity is a group membership.
  if ($group_content->getContentPlugin()->getPluginId() != 'group_membership') {
    return AccessResult::neutral();
  }

Let's say I create a custom field called "my_test_field".  And, I create a group permission called "access test field".  I then change above code:

// We only care about the the my_test_field field.
          if ($field_definition->getName() != 'my_test_field'
...
...
// Only users with 'access test field' should be able to see my_test_field.
  return AccessResult::forbiddenIf(!$group->hasPermission('access test field, $account));

If this field is attached to a node that is in a group, I am assuming that it is now attached to the group node entity.  But what about this?:

 if ($group_content->getContentPlugin()->getPluginId() != 'group_membership') {

Is the field also now automatically a group membership?  I guess I don't understand what that means in this context.

I am not sure how you would approach this by adding the fields as entities via the GroupContentEnabler (that'd mean one custom plugin per field? Given a large number of fields that might not be the best solution). However, for an example how to implement your own custom group-content-type plugin see this answer.

Another possible approach that might be worth checking is to implement hook_entity_field_access() to define access checks for single fields programmatically (that's how I've solved a similar problem). See the group module's gnode.module file for an example how to check permissions/roles for users and add cache-tags to access results.


hook_onload() replacement I want to add JS functions to the body tag's onload and onunload attributes with a custom module. The only hook I found was hook_onload() from Drupal 4.7, but this method has been deprecated. What is the Drupal 7 way of achieving this?

You don't use PHP hooks to execute Javascript. You would put the Javascript you want to execute into a .js file, and then use PHP to just attach that file to any page where it is needed, for example, using drupal_add_js().

For example if you wanted to attach it to every page with a certain type of form you would put drupal_add_js() inside of a hook_form_FORM_ID_alter).

If you want it on every page all the time, you can add it to your module's .info file like so:

scripts[] 'path/to/js/foo.js