Custom breadcrumb on user profile page I am using profile2 module for my User profiles.

Now breadcrumbs on user profile pages are:

  Home > Username

I need breadcrumbs to be like this:

  Home > Custom page > Custom profile2 field

How can I change it? Thanks for your replies.

You can use Path Breadcrumbs module. This module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL.

If this module is not satisfy your requirements, then visit Comparison of Breadcrumb Customizing modules to get more information.


Add custom title and custom alternative text to Logo Image Settings I am looking for a module that adds custom Title and Alt fields to the box shown below in the Appearance Settings of a theme

You can alter theme form using, form_system_theme_settings_alter in theme-settings.php

function test_form_system_theme_settings_alter(&$form, &$form_state, $form_id = NULL)  {

$form['logo']['settings']['alt_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Alt Text'),
    '#description' => t("Alt text")
  );
$form['logo']['settings']['title_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Title Text'),
    '#description' => t("Title")
  );

}

You can get this value theme_get_setting('title_text') in page.tpl.php,and i haven't tried this. Check from your side, let me know if you face any issue.


Addressfield entries not showing up when entityform sends an email I have an Entityform that uses the Address Field module. Viewing a submission in the interface is fine. However, when the admin email goes out, only labels are shown; the address fields are empty. Has anyone had this problem?

This was addressed in an issue on Drupal.org. Which version of Entity2Text are you using? The fix was added to 7.x-1.0-alpha2.


Adjusting the content size of my theme I have not messed around with themes much yet, but I would really like to be able to adjust the relative width of different blocks in my Bartik theme. As you can see in the screenshot, my panel is not quite big enough to display both views without overlapping, and there is plenty of extra space on the sides.

How does one change the relative widths assigned to each block?  Also, when I start making changes like this, would it be wise to make my own copy of Bartik and store it elsewhere?

This is something you would most likely want to adjust using your style.css file and an inspector program (such as DOM Inspector for Firefox) in the browser.

Another way to do it would be to use a grid-based theme like Omega that lets you choose how many columns wide to make zones and regions. Using Omega Tools you can do that directly in the Appearance admin configuration UI.


Dynamic form building - cleanest way to substitute tags with form elements? I have a string with tags, and form elements with elements corresponding to that tags:

$line = "This module contains [quantity] items of type [type]."
$elements = array(
  'quantity' => array (
    '#type' => 'textfield',
    //other settings
  ),
  'type' =>  array (
    '#type' => 'select',
    //other settings
  ),
}

Now, I have:

I want to generate:

What's the most standard Drupal way to do this? Elements and string will be taken from database. I assume it should happen in hook_theme, but how to pass all values to it?

If the tags are not dynamic you can have an array of possible form elements and then just foreach over them with matches from a regex. Then just have your mymodule_form call a builder function that would look something like:

<?php
function my_dynamic_forms_dynamic_form($form, &$form_state, $id) {
  $string = my_dynamic_forms_db_call_for_strings($id);

  $elements = my_dyanmic_forms_get_array_elements();

  $form = array();

  $reg = '/\[(.*?)\]/is';

  if($c = preg_match_all($reg, $string, $matches))
  {
    foreach($matches[1] as $match) {
      $form[$match] = $elements[$match];
    }
  }

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit Form',
  );

  return $form;
}

function my_dyanmic_forms_get_array_elements() {
  $elements = array(
  'quantity' => array (
    '#type' => 'textfield',
    //other settings
  ),
  'type' =>  array (
    '#type' => 'select',
    //other settings
  ));

  return $elements;
}

function my_dynamic_forms_db_call_for_strings($id) {
  $sql = 'SELECT string s from my_dynamic_form_strings_table s WHERE id = :id';

  $result = db_query($sql, array(':id', $id));

  return $result->fetchField();
}
?>


An illegal choice has been detected. after leaving form page I have a form with only a select element and no submit button. Upon change, I issue an ajax call to retrieve the details of the selected Project. Everything works as expected, however after I leave the page, I see the error "An illegal choice has been detected. Please contact the site administrator."

I only get the error if I change the select input. Ex. if I navigate to:

  Home->Projects->Home

I don't see the error on the last Home page. If i navigate to:

  Home->Projects(change select input)->Home

I see the error on the last Home page.

Here is my module code:

class ExpeditionController extends ControllerBase {
  public $client;

  public function __construct() {
    $this->client = \Drupal::service('http_client');
  }

  public function listProjects() {
    $select_form = \Drupal::formBuilder()->getForm('Drupal\myModule\Form\ExpeditionSelectForm');
    // Remove the submit button.
    unset($select_form['actions']['submit']);

    $result = $this->client->get('myRESTService', ['Accept' => 'application/json']);
    $expeditions = json_decode($result->getBody());

    foreach ($expeditions as $value) {
      $select_form['expeditions']['#options'][$value->{'expedition'}->{'expeditionId'}] = $this->t($value->{'expedition'}->{'expeditionTitle'});
    }

    return array(
      '#theme' => 'myModule_expeditions',
      '#form' => $select_form,
    );
  }

  public function expeditionDetail($form, $form_state) {
    $expedition = [];
    $response = new AjaxResponse();
    if ($form['expeditions']['#value'] != "") {

      $client = \Drupal::service('http_client');
      $result = $client->get(
        'myService' . $form['expeditions']['#value'],
        ['Accept' => 'application/json']
      );
      $expedition = json_decode($result->getBody());
    }

    $response->addCommand(new HtmlCommand(
      '#expeditionDetail',
      array(
        '#theme' => 'myModule_expeditions_detail',
        '#expedition' => $expedition,
      )
    ));

    return $response;
  }

  public function deploymentDetail($project_id, $deployment_id) {
    $result = $this->client->get(
      'myService' . $project_id . '/' . $deployment_id,
      ['Accept' => 'application/json']
    );

    return array(
      '#theme' => 'myModule_deployment_detail',
      '#deployment' => json_decode($result->getBody()),
    );

  }
}

class ExpeditionSelectForm extends ConfigFormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'myModule_expeditions';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['expeditions'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose Project'),
      '#empty_option' => $this->t('Select a project'),
      '#default_value' => '',
      '#ajax' => [
        'callback' => 'Drupal\myModule\Controller\ExpeditionController::expeditionDetail',
      ],
    );

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

  /**
   * Gets the configuration names that will be editable.
   *
   * @return array
   *   An array of configuration object names that are editable if called in
   *   conjunction with the trait's config() method.
   */
  protected function getEditableConfigNames() {
    // TODO: Implement getEditableConfigNames() method.
    return [];
  }
}

You change the options after the form is built:

 $select_form['expeditions']['#options'][$value->{'expedition'}->{'expeditionId'}] = $this->t($value->{'expedition'}->{'expeditionTitle'});

The Form API doesn't know about this. On submit the Form API checks if the submitted option is in the original option list. If not, it rejects the submit with the error "An illegal choice has been detected. Please contact the site administrator."


How can I add Support module's tickets to the homepage? I am trying out the Support module to create a client support ticketing system. Out of the box it seems to be configured so that I need to navigate to mysite.com/support to view the table of support tickets. How can I change this so that the support tickets appear on the homepage? Drupal version is 7.9

You could change the default front page for your site in the admin section at example.com/admin/config/system/site-information.  Enter support and it will now be your front page.


Is it possible to create a view of Nodequeues I'm trying to create a list of all my nodequeues using Views, To be clear I'm not trying to create a view that showing the content within a Nodequeues, but rather create a views that lists the Nodequeues themselves is this possible? if so how do do it?

Excerpt from the Community Documentation of Nodequeue (about "Automatic Creation of Views"):

When configuring Nodequeue, you can opt to "Automatically create one view per queue" (you may wish to leave this off if you plan to create the views yourself).
The views created automatically cannot be deleted from the Views interface because they are implemented "in code". However, if you disable the auto-creation, then clear caches, these views will be removed.
It is highly recommended that you use the Views module to display your subqueues. However, if you choose not to, you can alternatively use a small PHP snippet.
To use nodequeue from Views (D7), add a 'relationship' to the queue, and typically set to 'require this relationship'. Optionally add 'nodequeue: Position' to match the preset queue order.


Call to undefined function menu_load() in .../public_html/includes/menu.inc on line 579 I really need your help. Actually, my journey begin with the installation Drupal and some modules. After a couple of days I suddenly get an issue "500 Internal Server Error".

I asked my hosting provider why this happened, they said "That because of the file .htaccess and you should add to this file php display error". So i did this and I get a new issue :

  Fatal error: Call to undefined function menu_load() in public_html/includes/menu.inc on line 579.

By the way that's line 579 else {$return = $function($value);}.
P.S I am a beginner in PHP. I really want to study Drupal more and create cool sites, but this problem...

Here are few tips:

Make sure your Drupal core has all the files in the right place (especially menu module).
Make sure your imported database is in UTF-8 format.
Upgrade your Drupal core to the latest version (drush fr && drush up drupal).
Clear all your caches (drush -y cc all), including your memcached (killall memcached).
Rebuild your registry by using Registry Rebuild.
Ff you're using modules which are implementing drupal_bootstrap() (such as Secure Site), disable them.
Try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem.
Test it on different environment/machine.
Check your database collation (it should be case insensitive, e.g.: general_ci).
Eventually restore your database from the point where it was working before.


How to use the Rules module to attribute a new user role after a product was bought? I use these modules: Drupal Commerce, Rules, Node option premium.

My question: with Rules, how attribute a new user role, when the product was bought, and when this product is a premium content ? So that, when a user bought the product, that user can have access to full content.

Refer to the tutorial Selling Content with Drupal Commerce using Content Access and Roles for granting access to premium content to users who have a "premium" role.

Here is a summary of the steps required (= quote from that link):

Enable Content Access and the ACL (optional) module.
Create a role called "premium".
Create a content type called "Premium Content" and put some great content in it.
Verify that users can only access the premium content if they have the premium role.
Create a product representing the premium role.
Create a rule that grants the premium role on order completion:

After updating an order.
If the order state is Completed.
And the order contains our premium product.
Add a role to the user who is the owner of the order.


Datelist element in webform not working I was just going through webform configurations and I changed the date list element format from default to raw. After doing this Im not able to add any element of type dateform to my webform and also not able to open the element configurations also. The error i get when clicked on element tab (refer the attached image) is "The website encountered an unexpected error. Please try again later."

This is a bug. I created Issue #3029964: Datelist element in webform not working in the Webform's issue queue.  Please try the provided patch.


View Shows Latest Members - How to Limit Count by Last 3 Months I created a view that shows all recent members. Right now it shows members, from the newest to the oldest. I want to limit this view to show only the last 3 months of latest users.

In your views 'Filter criteria' add another filter and choose 'User: Created date' and choose an operator which suit your needs, An example shown below. It will list users that are created between last 90 days


Large file upload guidelines I have a site built in Drupal 7.23, which is supposed to handle large files uploads to it.

I have a node form with 5 File upload fields which is supposed to take 200MB files for each.

What should be the Apache server adjustments that i need to taken in favour of making the upload process seamlessly?

Also i have Video module with FFMPEG configured to convert on cron. Someday I got message form server support team that my FFMPEG is taking 100% CPU.

Also i got some MySQL errors, like Lock TimeOut etc. what to do ?

Please let me know an optimal settings for these kind of server which runs Drupal.

It is normal for the CPU usage to be at 100% when FFMPEG runs. Video compression is a computationally difficult task.

See this related question. If you have a two core VPS then you could make sure that FFMPEG only uses one core and thus always leaves at least one core for Apache/PHP/MySQL.

I created a similar site and it generally worked but it certainly had the occasional errors. It was a 4-core VPS and when transcoding all four cores were often at 100%. If I were to design the site again I think I would use a video transcoding service such as Amazon's Elastic Transcoder. Making sure FFMPEG would recognize all the different file encodings especially MP4 was quite a pain.


What are the advantages or disadvantages of using reference based modules instead of taxonomy module? I wonder how to decide either to use core Taxonomy module or Entity Reference module?

I didn't use Entity Reference module before but I've used the taxonomy module (and some related modules) on 10-15 websites.

What are the advantages or disadvantages of using reference based modules instead of taxonomy module?

Recently, I've started to build a magazine archive website.

There are lots of magazines.
These magazines have issues.
Each issue has articles.

The smallest (and deepest) part here is the articles.

Article

Page number (range):
Title:
Author:
Article type:
Keywords:
Magazine:
Issue:

Issue

Issue number:
Cover image:
Date (published):
Magazine:

Magazine

Description:
Cover image:

Here, there are (at least) 2 methods to implement this website:

1. There will be a content type called article and all others (issue,
    magazine, author) will be taxonomy terms (hierarchical). There would be a hierarchy between issue and magazine etc.

2. There will be lots of content types: article, issue, magazine,
    author. While creating articles; issue, magazine and author could be referenced etc.

So, theoretically both ways are seem very similar.

Is there anybody who faced similar situation and could you please say which method you preferred, why?

There are also other solutions to your problem.

Field Collection

You can use field collection and field collection views modules to store and organize contents. Using this approach the Issue and Magazine are going to be Field Collection type, Issue is a field of Article and Magazine is a field of Issue. I have experience of implementing such structure. In my case the requirement was a Library that should contain books (with Title, Publisher and ... fields), Every book contains multiple volumes (Number of pages, translator, ... ) and each volume also contains unlimited number of some other items (like the scan of some pages that are not the same among the books).

I implemented this using Field Collection approach and it is very nice. You can easily create a link to edit every individual items of every field collection and you can also filter by items of field collection. I posted an answer to Group items in Views by value in Field Collection which shows how to work with Field Collection Views

Entity View Attachment

Also known as EVA module.

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

You can use EVA to display only fields values for a particular piece of content, giving incredible control over the display and formatting flexibility of the fields. For example you may desire to have two fields concatenated in some special way. You can add your fields to your EVA display, set the contextual filter to NID, add a Global: Text Field, and using tokens format your fields with HTML. Don’t forget to exclude your fields from display if you are going to use them together in a Global: Text Field. Example: You may have a city, state, and zip fields. You can combine them in a Global: Text Field in Views to display as “City, State ZIP”. When you manage the display for your content type add the EVA just created to the display and whenever a node the type is displayed it will pass its nid to the EVA and the EVA will return the fields you select, formatted as you desire. (source : EVA and Entity Reference Use Case How-to)

This module is perfect, It attaches a View as a field to nodes of a content type. I used this module to create an Album. The album contains singer (with some information about each one) and songs that contains a File, Title, Rate and ... . So I created a View of type EVA and I attached it to a node. So on the node page of every Singer, I displayed this View which gets it's appropriate information from the node. The Views with Entity Reference is a perfect tutorial of how to use this module.

Taxonomy Terms V.S Entity Reference

I recommend you to read Entity reference vs. taxonomy and Are there any benefits/caveats with using Entity Reference over Term Reference? , As it says Taxonomies are best used when organizing similar items in a hierarchical fashion. Like tags.

Taxonomy allows you to use free tagging (it can be disabled using Content Taxonomy module), which enables the creation of new tags on-the-fly. It is very easy to modify the skeleton of contents. Using this approach, regular or at least some authenticated users (who have no knowledge of programming) can change this skeleton. Hierarchical Select module is perfect example of such approach.

Even though Taxonomy is easy to use but I myself prefer Entity Reference, it opens up lot's of possibilities and scalability and allows of creation very complex structures. The concept of entity in this context is not limited to content. It can be comments, users, taxonomies and ... . It is much more scalable so you will not be worry about the customizing content types, or modifying it in the future (as it was pointed out in Entity reference vs. taxonomy). I believe the Entity approach is more powerful than Taxonomy.

There are also some other combinations of these approaches which it is unnecessary to mention them.

Anyway I recommend you fully understand Entity approach and it's related modules. If you use it in multiple projects, despite of it's complexity it will be very easy to you to use it. Not only in the yours current requirement but also in the future it is going to be a Very Reliable Tool for you.


Update user profile picture using entity_metadata_wrapper I am trying to update the user profile picture using entity_metadata_wrapper. But I am getting

  "Unknown data property picture." error.

When I check the user property info, I cant see the picture field as well. Below is my example code:

$user = entity_metadata_wrapper('user', $form_state['entity_id']);
if (isset($form_state['values']['user_profile_pic'])) {
   $file = file_load($form_state['values']['user_profile_pic']);
   $file->status = FILE_STATUS_PERMANENT;
   file_save($file);
$user->picture = $file;
}

Thanks in advance.

Try this out :

  $wrapper = entity_metadata_wrapper('user', $form_state['entity_id']);
//- Get the user object.
  $user = $wrapper->value();
  if (isset($form_state['values']['user_profile_pic'])) {
    $file = file_load($form_state['values']['user_profile_pic']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    $edit = array(
      'picture' => $file,
    );
    user_save($user, $edit);
  }


How to filter by language in default search On a D7 (7.60) site, we're currently using the default search tool for a little search form block on the page. Our site has multiple language versions, dependent on url.

Right now, content in 4 languages is giving 4 search results. I want to filter this to just current user's language. But when I go into the view (admin/structure/views/view/search/edit), I'm not seeing "current user's language" as a filter.

Ah heck.. nevermind. I wasn't understanding how to get that setting. All good now. Filter by content language, and 'current user's language' is one of the checkbox options within it.


How do I insert a view into an article based on filters that are only defined at node publish? I have a website that uses data in tables. I want my copywriters to use a filtered view which will be in the node edit form to create the view they want for a particular article then somehow insert code into the page so that the data shows.

The views that are created will be different every time so this cannot be a pre-defined view as such, more a view with the filters that they decide to use at the time they publish the article.

Does anyone know how I might achieve this?

So if I understand correctly you have a node edit page, with a view provided by the views module with exposed filters, probably in a block in block somewhere on the page.

Your copywriter will then put some parameters into the exposed filters and get some results.

If this is a custom view that you have made then there are not going to be any pre-made modules that suit your needs so to put the content that is returned into the body your options are:

1) Copy and paste

2) Write some jQuery that runs upon clicking the view row that insert the copy into the body

Here is some information on adding js in Drupal.


How can I show a block only on the edit page for a specific content type? I have a block that I would like to display on the edit page for a specific content type.  Since the content of this block describes the site policy for editing that specific content type, I only want users to see it when editing nodes of that content type.

I tried setting the block display path to node/*/edit* and checking the appropriate content type on the block display menu, but that didn't work.

You could implement hook_block_list_alter() to alter the status of the block. (Replace $bid with the block ID, and $content_type with the content type you are interested to.)

function mymodule_block_list_alter(&$blocks) {
  if (!empty($blocks[$bid]) && ($node = menu_get_object()) && arg(2) == 'edit' && $node->type == $content_type) {
    $blocks[$bid]->status = 1;
  }
}


What will happen at worst if I change the "Number of values" of CCK field I have a CCK text field and set "Number of values" to a certain number.
Now I want to change it to "Unlimited".

It says

Warning! Changing this setting after data has been created could result in the loss of data!

What will happen at worst if I change this?
The values of already existing nodes might be really gone as it says?
If yes, there is no way to change this to "Unlimited" if I already have some existing nodes?

Changing it to unlimited isn't going to cause an issue. It's a standard warning message for any change on that setting for a field.

So really the only time you would be concerned is if you took an already unlimited field and set it to a static value, which could potentially remove values if the delta of that field on a node exceeded the static value.

Edit: But always be sure to take a backup before doing those kinds of changes, and always do this on a development environment.


How do plugins store their configuration/field data? I'm creating a custom Commerce License and I notice that I'm handling defaultConfiguration(), buildConfigurationForm(), submitConfigurationForm(), and buildFieldDefinitions(), but I cannot figure out where in the database this information is stored. I know that it must exist somewhere as the data loads up when I view the entity, but I cannot seem to find it. It doesn't seem to have anything to do with Configuration that would exist in a sync folder despite the similar names.

I'd assume buildFieldDefinitions() has something to do with it, but I cannot seem to figure out exactly what that method is doing at all.

Sounds like the answer is "the data is probably the config table... but it could also be anywhere else depending on the implementation." In the commerce_license example I noted, instances of LicenseTypes on Product variants get their own entry in commerce_product_variation__license_type, where the data for that instance is stored in the license_type_target_plugin_configration column. Just like data stored in the config table, this is a hex blob which, when decoded, is the config field data as a serialized array.


How to get taxonomy term by description, programatically In a D7 custom module, I wish to retrieve a taxonomy term by it's description (and not it's name or TID).

Right now I do have it working, but I feel the code is a bit clunky, and I feel like there is a more elegant / Drupally way of doing it.

Is there a better way of doing it then this?

$vocabulary = taxonomy_vocabulary_machine_name_load('my_vocabulary');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

foreach ($terms as $term) {
  if ($term->description == 'my_term_description') {
    // Do stuff when there is a match.
  }
}

Ideally, I feel like there is a better way I cannot find through Google / Drupal API etc. Something like:

$term = taxonomy_by_description_load('my_vocabulary', 'my_term_description');

Thanks everyone.

Using the EntityFieldQuery (this is untested)

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', array('my_vocabulary'))
    ->propertyCondition('description', 'my_term_description');
  $result = $query->execute();
  $tids = array_keys($result['taxonomy_term']);

  return $tids;

More information https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-use-entityfieldquery-for-drupal-7


Checking if user is logged in and inputting their username I have a form on my website and i would like the page to check if the user is logged in, if they aren't, then redirect them to a login page, if they are, then show the form.

When they are submitting the form, how can I get that users username and get that review that they submitted show up on their account?

If you need any more details just comment.

I am using Drupal 7

First make sure only users with a specific role can access this form. You can use the #access property to restrict the access to a specific form.
The LoginToboggan module can redirect the user to the login page if they get an access denied.
In the submit hanlder of your form you can access the current user by adding global $user at the top of your method.


Shared Field Name Between Entity Types? I have always separated my field names by entity. e.g.

field_paragraph_h2 or field_content_h2,

but when you look at config, fields are designated by their entity type as well.

field.field.paragraph.paragraph_type.field_paragraph_h2 or field.field.node.content_type.field_content_h2

Am I safe using just field_h2 for both entity type field names, or are there instances with Drupal where this may be problematic?

e.g.

field.field.paragraph.paragraph_type.field_h2 or field.field.node.content_type.field_h2

You are safe to use the same name. The fields are unique for each entity type, even when they have the same name.

They have their own field storage configuration, instances and will be stored to dedicated database tables per entity type.


How to port active configuration to module configuration Scenario: I have a website which was initially developed with a single site (A) in mind. Now, because reasons, I need to make this a multi-site setup (A & B). So, I have functionality in A I want to share with B. We built A with all config exported to it's config sync folder, which means all config is intertwined.

Problem: How would I go about converting all sharable configuration to modules, which would allow me to maintain the modules from one codebase in both A & B? Putting everything into module_foobar/config/install/ will not work that easily for A, since it already has that config in it's active config.

Use Features: It basically does exactly what you want, it turns your existing configuration into a module_foobar/config/install/

Be aware though that Features merges config (it does add and update existing config, but it does not remove/delete unused config like core configuration management).


In code, only create a revision if a field is changed I have a custom revisionable entity with a few dozen fields. I'm importing data about the entity on a periodic basis. If the entity has changed, I'd like to save it and create a new revision.

$dogs = \Drupal::entityTypeManager()
  ->getStorage('my_entity')
  ->loadByProperties(['my_entity_id' => $my_entity_id]);

$dog = reset($dogs);

$dog->set('name', $record['TheName']);
$dog->set('birth_date', $record['Dog Birth Date']);
// Lots more ->set happening here.
$dog->set('notes', $record['Notes']);
if ($dog->someMagicComparisonFunction()) {
  $dog->setNewRevision(TRUE);
  $dog->save();
}

I searched for the someMagicComparisonFunction but didn't find it. Does it exist?

This may do the trick in a hook_entity_presave(), or get you close:

$old_dog = clone $dog;
update_the_dog($dog);

// Use == to allow for out of order keys.
$same = $dog->toArray() == $old_dog->toArray();

This is kinda of cheating, and you may want to filter the arrays for just the fields and not the properties.  It also isn't multilingual-safe.

To do it properly, start reading ContentEntityBase::hasTranslationChanges() and FieldItemList::equals().  The code above makes a lot of assumptions about fields and storage, which ContentEntityBase() does properly.


Show modal modal message on form success I have a custom form that submits via AJAX. On form error, i simply return the whole form on my callback function, and the HTML is replaced, but i want it to open a modal dialog on success. What is the best way to do this? This is what i'm currently doing (i don't like this solution because i can't clear the form values, among other things):

    public function ajaxCallback(array &$form, FormStateInterface $form_state) {

        drupal_get_messages(); // Hide the status messages

        $form_state->setRebuild(TRUE);

        if ($errors = $form_state->getErrors()) {

          return $form;
        }
        else {

          $response = new AjaxResponse();

          $title = 'Consectetur adipiscing elit';
          $text  = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';

          $response->addCommand(new OpenModalDialogCommand($title, $text));

          return $response;
        }
      }

Here is what i came up with (many thanks to @4k4):

    public function ajaxCallback(array &$form, FormStateInterface $form_state) {

        drupal_get_messages(); // Hide messages

        $form_state->setRebuild(TRUE);

        if ($errors = $form_state->getErrors()) {

           return $form; // Simply Return the form
        }
        else {

         $response = new AjaxResponse();

         $title = 'Consectetur adipiscing elit';
         $text  = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';

        $response->addCommand(new OpenModalDialogCommand($title, $text));

        // Or add the $form as parameter to an HTML command.
        $response->addCommand(new ReplaceCommand('#my-form-wrapper', $form));

        // Do notice i added a wrapper to my form in the buildForm() method:
        // $form['#prefix'] = '
';
        // $form['#suffix'] = '
';

         return $response;
    }


Pagination in a rest view api How to handle this situation in the Rest Export View as api.

We want to fetch a limit of 20 items in the api and with a load more feature. Currently our api produces hundreds of items.

In the Pager section, I can ofcourse select Paged output, full pager and specifiy  Items to display, say 20. But how this works in the api? Since its only displaying 20 items, how does load more feature occur? Thanks!

This is my Pager settings.

PAGER
Items to display:Full | Paged, 20 items

Simply pass the “page” parameter with the request, like ‘api/foo/bar?page=1’. Views will return the next set of results as you increment the page number. You can do the load more interaction however you want on the front end so long as you specify the page and keep track of total results.


Creating hyperlinks in wysiwyg editor I installed the tinymce wysiwyg editor and it converts hyperlinks into [url= tags.
How do I convert this to html i.e. <a href="

Maybe in your formats, there is no <a> allowed? You can find it under /admin/config/content/formats
Or you checked that HTML will be rendered as text.


How to track the number of clicks on a link? I have created a views in grid settings. I have displayed 5 columns and 4 rows n this view. Over all i have 20 items present in this view.
In each item i have a link field. This view is very similar to  http://www.amazon.com/ (What Other Customers Are Looking At Right Now). Now i would like to track the number of clicks on each link. The result should contain the user who clicked it or how many number of times it has been clicked.
I am struck with this please some one help me to find a solution. By the way  I am using D7.

This link might help you. http://activelamp.com/blog/add-and-track-any-link-google-analytics


Grouping fields with field group doesn't work on display of Drupal Commerce product in product variation I've got a content type for a product and fields for variation. I'm writing about fields in that variation. I have created new group containing some fields using field groups.
Let's say:

[Field group]
 1. Foo
 2. Bar

The group setup is done properly on content type/field display in product variation tab. I'm using drupal commerce, I have tried updating CRON, flushing cache, drinking beer, resaving content. It didn't help. Anyone has any idea?

The Field Group module provides the ability to group on both the edit form and the display independently.

This means to add a field group to the form you have to do so on admin/structure/types/manage/CONTENTTYPE and to add a field group for display you do it on admin/structure/types/manage/CONTENTTYPE/display (this is for nodes, this will be in different places for other entity types).

If you want the group on both the form and the display you have to add it in both places.


Permission issues with Custom Content Entity exposed to REST API I hope it's not a duplicate entry.

I've recently created my Custom Content Entity within a Custom module and I'm currently having trouble with permissions. (Please see permissions below)

The permissions work perfectly when using the add/edit/delete Drupal forms. It throws a 403 if the current user has not the permission, which is great because everything is normal here.

But when I expose the Custom Content Entity via RESTui module : GET, POST, UPDATE. (please see screenshot below). Anonymous users don't get 403 and are able to create, edit.

Are the permissions defined under mymodule.permissions.yml only for Drupal entity form ?

How do we define REST permissions for a Custom Content Entity ?

Thank you very much for your help

Actually, this was a false positive error.. I did some testing with my REST Client in Chrome (please see screenshot at the end of the paragraph) and permissions are correctly working.

The issue was related to my XHR request which was (for some reasons) keeping a valid CSRF token and because of this I appeared to be identified as admin. And of course as admin ID 1, I was granted full access on CRUD..

Sorry and thanks for your time guys!


Register user with empty password I create a cordova app, and trying to register new user from my app using drupa 7, drupal 7 service 3 and angularjs 1.

I send post request with below data and user created successfully.

    $http({
        headers: {
            'X-CSRF-TOKEN': $rootScope.globals.auth.token
        },
        method: "POST",
        url: registerUrl,
        data: {
            name: data.name,
            pass: data.password,
            mail: data.email,
            "field_ac_mobile_number": {"und": [{"value": data.mobile}]}
        }
    }).success(function(userData) {
    }).error(function(data, status, headers, config) {
    });

But my problem is- after create user, password is empty.

How to solve it?

UPDATED QUESTION:

I altered registration form by three step registration form for verify customize 6 digit character instead url for email verification.

All works fine. But when I send final request with all params, user created without password.

But if I register from site, all values set well.

I don't understand, whats my problem...

UPDATED QUESTION 2nd:

It is very simple.

The steps are the following:

Please go to: admin/config/people/accounts
In the secction "REGISTRATION AND CANCELLATION
" select "Visitors".
Uncheck "Require e-mail verification when a visitor creates an account".
Click in the buton "save configuration".

Try again register one user.

I did a test and everything went well.


Ask Drush to list which modules have database updates available I specifically want Drush to list, of the modules that have available updates, which of those contain database updates.  Is this possible with Drush?

Edit for clarification: I know drush up will list all modules that have available updates, yes, but not all of those updates will have database updates that go along with them. I strictly want a list of updates that have associated database updates.

drush updatedb --no (shorthand: drush up -n) will list them and take no further action.


How to add module libraries to the page through an admin page? Looking for some guidance on how to create a custom module, mymodule, that will pull all the libraries from the custom module and display it in an admin screen. Once the libraries are displayed, I want to be able to set Add to Pages (checkbox) for each library to determine if it should be added to the nodes. It would be ideal if the setting became a configuration.

The goal is to be able to add any libraries I need to the custom module, but selectively add them to nodes using hook_page_attachments. How would I do this?

I initially tried this, but couldn't find a way to get all the libraries.

mymodule.libraries.yml

library1:
  version: 1.x
  header: true
  js:
    path/to/library/file1.js

library2:
  version: 1.x
  js:
    /path/to/library/file2.js

mymodule.module

/**
 * Implements hook_page_attachments().
 */
function mymodule_page_attachments(array &$attachments) {
  $libraries = [
    'mymodule/library1',
    'mymodule/library2',
  ];

  foreach($libraries as $library) {
    $attachments['#attached']['library'][] = $library;
  }
}

Your module is referencing the library names wrong. It should be “mymodule/library_name” instead of just the library name.

As long as you get that right, it wouldn’t be hard to loop node field values or a config object and add them like that.


how to get the translated taxonomy term programmatically? I have tried this

$term = taxonomy_term_load($tid);

and this:

$term = i18n_taxonomy_localize_terms(taxonomy_term_load($tid));

Both return the default language (English) term

I am using D7.

Try

$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_term_get_translation($term, $langcode);

Also, a good place to look for more information: /sites/all/modules/i18n/i18n_taxonomy/i18n_taxonomy.module


Use "view" inside a loop / clone a view I'm trying to use a view inside a loop but it's not working,
I'm using "views_get_view($name)" but "clone_view()" / "copy()" is not working, I can't create another reference.

I have a view with a contextual filter and by settings different arguments on each loop with "set_arguments" the result should be different. I get the result for the first loop but all the others are empty.

I'm trying to use something like this:

for($i=2; $i<=4; $i++){

    $view = views_get_view('view_name');
    $view->set_display($i);
    $view->set_arguments(array($i));
    $view->execute();

    dpm($view->result);
}

and the result is:

... (Array, 4 elements)

... (Array, 0 elements)

... (Array, 0 elements)

The first result is working great (4 elements inside the array) but the others are empty.

I know the above code is not correct as this is not the way to handle objects but at least you will know what I want, a different result for each set of arguments, arguments which are connected to a contextual filter inside view.

Can someone help me with a method to use the view inside a loop ?
I only managed to generate the result once no mather what.

Thanks.

The $view->set_display($i); will not work unless you have an integer as the display name of your view (which is something I'm not sure if possible or if you need it).

try changing the $i in $view->set_display($i); to the display name of your view:

for($i=2; $i<=4; $i++){

    $view = views_get_view('view_name');
    $view->set_display('display_name'); //Example: page, page_1, block_1, custom_display_name ..etc
    $view->set_arguments(array($i));
    $view->execute();

    dpm($view->result);
}


How to enable the Views UI module? I have the Views UI module on my Drupal site, and I would like to enable if but I can't.

How can I enable the Views UI module?

When I try to enable this module by using admin panel I am not able to enable because that

check-box itself disabled and I am not able to check that check-box

Make sure that you have the required modules installed and enabled.
Your most probalby missing Chaos Tools

Module filter is also a easier way to manage modules


How can I add an BCC or CC email with programmatically? I am sending email programmatically and I am using plugin.manager.mail to send email, I want to add a CC ó BCC.
Do you know the way to achieve it?

What you want to do is ensure you are defining a message type in your custom module, you can then target the message within a hook_mail_alter() to add the desired CC or BCC.
function MYMODULE_mail_alter(array &$message) {
  $bccEmail = 'test@test.com';

  if ($message['xxx'] == 'xxx') {
    $existingBcc = isset($message['headers']['Bcc']) ? $message['headers']['Bcc'] : '';
    $message['headers']['Bcc'] = implode(' ', array_merge(
      explode(' ', $existingBcc), [$bccEmail])
    );
  }
}

https://git.drupalcode.org/project/bcc/-/blob/8.x-3.x/bcc.module has an example of adding a bcc.


filter with taxonomy-term-alias instead of term-ID? I've my view filtered by taxonomy term ID.

http://aelasoca.cat/web/

(in the main menu I've links to taxonomy ID's 3 to 8). How can I filter with the taxonomy term alias instead of it's ID ??

(not sure if it's the same issue as in: Views, Taxonomy, Block and Context... What am I doing wrong? )

Create a new Taxonomy:Term ID contextual filter.
Under the form "When the filter value IS in the URL..." select the option "Specify validation criteria".
Select "Taxonomy Term" as the validator.
Select which of your vocabularies you'd like to use.
Under "Filter Value Type" select "Term name converted to term ID".

That should do it. If you have multiple-word taxonomy terms, you should allow the contextual filter to convert dashes in the URL into spaces for the term name. If you have unusual characters in your taxonomy terms, see this post for tips.


Drupal Commerce Product Pricing Rules disapear When I add a new rule in Product Pricing rules they disappear out of the Product Pricing Rules Window. They are still available in Workflow->Rules.

I am also finding that it seems to be hit and miss weather I am able to access all data on the system. Sometimes the rule I create sticks in the Product Pricing Rules window for a few minutes and those rules when created give full access to all referenced data. But I create a new rule and cant see data that I know I should be able to I know then that this is going to be one of the rules that will disapear into the Workflow->rules window.

Any idea what is happening.

Thanks
Simon

It sounds like for some reason the event is getting removed or changed to something other than "Calculating the price of a product." However, without seeing a screenshot of your Rules list, there's no way to tell. Look at the list and see what the event is getting set to.

If you use the product pricing rule add link from the product pricing interface, it should be altering the form to pre-select the proper event and hide the select list. Perhaps you have some other code on the site that undoes that selection or otherwise invalidates it.


Why can't I call theme functions declared in template.php in mymodule_nodeapi hook? I have some theme functions defined in my theme's template.php file that I am calling in my modules with no problems.

I also have some theme functions defined in my_module.module that are also working.

I'm doing some work on themed automated emails with custom rules actions and I found that when rules calls theme functions defined in my theme's template.php file they don't return anything, but when calling the same functions copied and pasted to my_module.module the return what I expect.

I also found that bypassing rules and doing the same process (calling the functions from both locations) in a hook_nodeapi in the 'presave' case gives me the same behaviour. (Strangely however they work in the 'load' case.)

Is there a way I can have my theme functions neatly defined in my theme's template.php where they are already working for all my other modules, and still get at them with rules / hook_nodeapi?

Thanks!

EDIT - more info:

Thanks guys. The reason I put them in the theme to begin with is because I'm working on a multi-domain profile with a parent theme and a subtheme for each sub domain. They were template functions for html emails that need to be branded in with images and styles from each subtheme. I've had problems with putting template theme functions in modules because the path to the templates defaults to the module directory, and I need the template to be selected dynamically based on which subtheme it was called from. Thats why I wanted to define them in the parent theme so they could be overridden per child theme.

Functions defined inside of template.php will not reliably be available (nor are they meant to be) outside of the theme. When it comes to overriding preexisting theme functions, the overrides created within template.php will automatically be applied by Drupal core, there is no reason to actually invoke the function.

For example, if you wanted to override the functionality of theme_menu(), and you created in your theme's template.php a function named mytheme_menu(), that new function will not actually be invoked anywhere within the site's code. The function that is invoked will still be theme_menu() and Drupal core will automatically override that invocation with the functionality within mytheme_menu(). This is the intended use of the template.php file; to override existing themable output, not to create new theme functions.

Now, if you create a custom element and need to create a brand new theme function for that custom element, this function must be declared within the context of a custom module. For example, you would need to define the function theme_myelement() inside of mymodule.module. You will also need to implement hook_theme() by defining the function mymodule_theme() in order to tell the Drupal theme system about your new function. There's a bit more to it, which is explained in the Drupal module developer's handbook for Drupal 6 and Drupal 7.

If this doesn't answer your question, please edit your question to provide specific details about your custom module and custom theme functions.


How can I conditionally show a field in the node/add page? When users are in node/add/page, I want to show the body field when the title is not empty. How can I achieve this?

By default in Drupal 8 "Seven" is the admin theme.

(Assuming you're using Seven as your admin theme) In /core/themes/seven/js add/create custom.js file.

custom.js

(function ($) {

   $('#edit-body-wrapper').hide();

   (function Forever(){

     var title = $('#edit-title-0-value').val();

     if (title != '') {
       $('#edit-body-wrapper').slideDown(1500);
     }
     // slides down and shows the body field in 1.5 secs if the title field is not empty

     else if (title == '') {
       $('#edit-body-wrapper').slideUp(1500);
     }
     // slides up and hides the body field in 1.5 secs if title is empty

   setTimeout(Forever, 1);

   })();

})(jQuery);

Now edit seven.libraries.yml

In the node-form: section add

  js:
    js/custom.js: {}

So it should look like this:

node-form:
  version: VERSION
  css:
    layout:
      css/layout/node-add.css: {}
  dependencies:
    - node/form
  js:
    js/custom.js: {}

PS: Don't forget to clear the cache to see changes.


Create a view of views? I love Drupal views and tags but I'm having a bit of trouble figuring out how to do this.

We have several online seminars with multiple sessions in each.

For example:  Refocusing on Family part 1, Refocusing on Family part 2, True Womanhood part 1, etc.

For each of these articles I have a view created that will return all the articles in that category.

For example, when you click on Refocusing on Family you get a page with teasers and links for:

Refocusing on Family part 1
Refocusing on Family part 2
etc.

What I would like to do is create a new view (something like "Life Academy" for example) that had a description and link to each of the top level views (which, in turn, link to the articles).

So the user would go to the Life Academy page and see links and descriptions for Refocusing on Family, True Womanhood, and any future seminar groups.  Clicking on these links will then take you to the view page (with links to the articles) for the appropriate group.

What I want to avoid is having to manually update the page every time a new seminar category is added.

Any help is greatly appreciated!

Sounds like you just want a taxonomy term view. Then output the name field and and use the Rewrite Results, "Output this field as a link". You'll want to make the links for the other view predictable by using arguments like TID. Then you can set your link to use tokens like seminar/tid. I think you can use term name as well with a little bit of magic on the contextual filter.

If you just want to display all categories and seminars on the same page, create a view that outputs seminars and add the taxonomy term field. Then group by the term.


Rules - Page redirect not working on "after saving new content" Using Drupal 7.7 and Rules 7.x-2.0-beta3

The rule set up is:

Event: After saving new content
Conditions: Content is of type news
Actions: redirect to url news

When adding a news story and clicking submit, the redirect does not happen and I get left with a 'Connection was reset' error in the browser.

Had anyone else this issue?
Any ideas how to overcome this?

There are a couple of serious bugs in the Rules 7.x beta (frequent 503 errors). Release candidate just came out that fixes these bugs. Try an update to the latest module version and see if the error goes away.


Update status behind a proxy I'm running Drupal in an intranet which is behind a simple HTTP proxy. I'd like for the module and core update checks to actually work.

I seem to remember there was a core hack to do this on Drupal 6, but I can't find the page anymore.

Does anyone know how I can get this working?

One of our corporate installations had a forward proxy that prevented direct access to the internet, we ended up patching core with 'the proxy patch' (thus named this way because this issue has been open since 2004 - http://drupal.org/node/7881).

http://drupal.org/node/7881#comment-4134240 - has a patch for drupal 7
http://drupal.org/node/7881#comment-2446280 - has a patch for drupal 6

Once the patch is installed, then you will be able to alter drupal_http_request() to send all queries through the proxy.

This way all modules that require access to the internet will function as expected, e.g. update statue, aggregator, openID etc

UPDATE: The patch is already merged in Drupal 7 trunk ( https://drupal.org/comment/6425278#comment-6425278 ), and hopefully will be out with Drupal 7.16


form submit hook handler not getting called in drupal I have Drupal 7 site. It has custom module named say myproducts. This module has following hook

function myproducts_form_alter(&$form, &$form_state, $form_id) {

if(isset($form_id) && $form_id=='product_node_form')
{
   $form['#submit'][] = 'myform_form_submit';
}

}

function myform_form_submit(){
 echo 'test submit handler'; exit();
 }

But `myform_form_submit` is not getting called.

Any help highly appreciated.

The submit for the node form is attached to a specific button, so something like this should work:

$form['actions']['submit']['#submit'][] = 'myform_form_submit';


Sub tabs similar to Media library I am trying to replicate the user interface Media library provides in 8.8.

I've created a view with 2 displays:

View 1:

Menu tab where Parent is "Content"

/admin/content/media-image

View 2:

/admin/content/media-image-shared

No menu in the Views UI.

I've then defined:

custom_media.image_space:
  title: 'Images'
  route_name: view.media.page
  parent_id: view.media.page
  weight: 20

custom_media.image_shared:
  title: 'Shared images'
  route_name: view.media.shared
  parent_id: view.media.page
  weight: 20

The main tab next to Content / Media / Files / Images is present. However, the subtabs on my view Images are not displayed.

What am I missing?

Figured it out!

The parent must be the Views local task id for both definitions.

So parent_it should be views_view:view.media.page


Create unordered list in render array I'm attempting to create an unordered list using a render array in a custom block in a custom module.

I understand if I wanted to wrap things in div I could always use the 'container' type. Like so

    $content = [
        'container'    => [
            '#type'       => 'container',
            '#attributes' => [
                'class'      => ['container'],
            ],
            'item 1'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'p',
                '#value'      => 'Item 1',
            ],
            'item 2'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'p',
                '#value'      => 'Item 2',
            ],
        ],
    ];

But I'd like to be able to use an unordered list like so

    $content = [
        'container'    => [
            '#type'       => 'html_tag',
            '#attributes' => [
                'class'      => ['container'],
            ],
            '#tag' => 'ul',
            'item 1'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'li',
                '#value'      => 'Item 1',
            ],
            'item 2'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'li',
                '#value'      => 'Item 2',
            ],
        ],
    ];

What I'd like that to produce is

Item 1

Item 2

But instead it produces

Item 1

Item 2

Is there a way to create an unordered list using render arrays?

Use the theme 'item_list':

$content = [
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#title' => 'My List',
  '#items' => ['item 1', 'item 2'],
  '#attributes' => ['class' => 'mylist'],
  '#wrapper_attributes' => ['class' => 'container'],
];

The wrapper_attributes are not used in all themes. In core this is classy and bartik, which is based on classy.


Does a Context Condition Path need to exist? I have a context that has a condition Path of FooBar/*
I added a block (Reaction) view for that context.
When I go to /FooBar/Mens_Bible_Studies, the view shows, but I also get "Page not found"?

Page not found

    Mens Bible Studies

    Overview of Mens Bible Studies. Delete if you don't want an overview
        Curabitur tortor - Meets every Wednesday, 6:30 am.

The requested page "/FooBar/Mens_Bible_Studies" could not be found.

What am I missing?

Rich

Update based upon the first two responses.

Thanks Boriana and rooby for answering! Here is a little more about what I am doing. At this point I am really not sure why I didn't use a page view. I am leaning to using contexts instead of panels. I want a responsive site and the theme handles that for me so I don't want to force a layout with panels. I want to select my block view based upon the "FooBar" root path.
I have a fairly large number of content types tagged with different taxonomy terms. I have a compound view that does all the work. It just looks at the last leaf of the URL (/FooBar/bla1/bla2/blanN... there is a variable depth) and uses that as the taxonomy term and builds a recursive output that descends the taxonomy tree in a way that I can CSS style each level differently. Content tagged as sub-category heading displays differently than content tagged with terminal terms (the lowest level in the branch of the taxonomy hierarchy they are in). I have heading content and then child content under that in the term hierarchy.
I thought I could just have the reaction point to the view and have it output. I will try both approaches you both suggested to see what works best. I believe I have to go with rooby's suggestion since I don't think I can have menu entries point to non-existent content. After I posted, I was thinking of just creating a panel page with empty variants that reacted to all the URLs I needed to create. Each of these would point to the same block view.

So Ideally, the new module I would need create (I never created a module before) would take a list of my hierarchical URLs, create phantom pages for them and create menu entries for them. My context would provide the content.

Or, perhaps I should just commandeer the taxonomy term views with what I want since the URLs that I want match the taxonomy term hierarchy.

Yes, the context module does not create pages, it allows you to position blocks on existing pages.

If you want a page that is not a node or a view you can use the empty page module or the panels module.

If you want a bunch of pages that are dynamic like FooBar/* where there are lots of sub pages, you could also create a custom module to create the pages, by using hook_menu() and returning an empty string for you page content.


how to obtain proper 'call back URL' I have installed drupal 7 using MAMP and following this tutorial to configure drupal with oAuth,

While adding consumer I tried call back URL with domain name like http://mastmobilemedia.com/oauth/request_token which gave http status 404 error in browser , when i tried with IP Address http://192.168.1.4/drupal/services/xmlrpc ( as i found in one of the sample code) i got page not found error in browser

so please can anyone help me in knowing what is the proper call back URL to be specified ? how to get client side URL ?

You are getting 404 error because actually there is no page in your site with that url.

In your referenced tutorial the following statements can found as a note:

"
Note: The sample callback URL above is incorrectly shown. The callback URL should be an URL on the client side. When Drupal has authorized the consumer, it will call this URL with the access token as a parameter."

So you have to define a page call back with path as you want. You can define in your custom module.  OR You can give a valid site path as callback url. So When Drupal has authorized the consumer, it will call this URL with the access token as a parameter.


Order list: Pay unpaid invoices I have created some extra statuses: Paid and Unpaid.

Now they got the functionality and react on the transaction balance perfectly fine. However, on the user site, it is kind of a dumb thing.

Even if the invoice is unpaid, there is no option to pay the invoice from the user --> orders pages. It looks like you can ONLY pay at checkout; apparently you cannot pay with Paypal later on.

Either way, I am looking for the function that users can pay the amount (or remaining amount) using Paypal WPS. Can any one help me accomplish this?

Secondary, as small addition to this, I would love the user to be able to see transactions that have been done AND the open balance (if any) similar to what the Admin view got.

Can anyone help me accomplish these 2 points? I am not a coder so please keep it simple.

I would ask joachim about the status of this module. He's very good and was interested in finishing it up a little over a month ago. I'm not certain where he is but it's worth a try.


Using SQL how do I select the value of a translated field in a specific language? Give an entity field that has been translated into the target language, how do I retrieve a specific language version using SQL - not php.

Give this query for instance (using an imaginary field called data on an entity form):

SELECT field_method_value
FROM entityform
LEFT JOIN field_data_field_method
ON entityform.entityform_id = field_data_field_method.entity_id

And assuming that we have a default language of English (en) and Spanish (es) enabled on our site, and that a translated value for the spanish version of the field is stored...

What SQL statement would return the Spanish version rather than the English one?

The field language is stored in the language column of each row in the field table.

So you just need to add a simple condition to your SQL, e.g.

language = 'es'


Content type structure (nested content: Gallery / Photo) I've been digging for some days how to organize my Drupal 7 site.
I want to build a site with multiple galleries, each one of them with multiple photos:
 - The galleries will show a cover photo, a description and thumbnails of the pictures;
 - Each photo will have a title, a description, date, will allow for comments, have tags, etc.
I want both the gallery and the photos as nodes (so I can have a page for a gallery and a page for each single photo with different layout).
So, I thought this would be the structure of the content types, where 1 gallery has multiple photos:

content type: GALLERY

description (text)
cover (image)
photo_entries (unlimited | content type: PHOTO)
...

content type: PHOTO

file (image)
title (text)
date_taken (text)
...

I tried a solution (like the one explained here:http://megadrupal.com/blog/creating-an-image-gallery-in-drupal-7) where I have an unlimited image field in my gallery, but I really want the photos to be nodes and this is the thing I don't know how to do.
I've been unsuccessfully trying using some modules like Views and entity reference, or even taxonomy, but I'm not sure what should be the approach to get this.
This can be a very simple question and I'm sorry if it is, but I'm stuck...
I really appreciate if someone could give me advice and put me on the way.

I think I found a solution for this using the Node Gallery module. Here is a quote about it (from the module's project page):

  ... allows you to create multimedia galleries where both the galleries and the gallery items are nodes (as opposed to gallery items being file fields, like Media Gallery).


Allow users to >only< upload images to existing nodes? I want to allow users to upload images for exsits content, for example for article, but i will not allow they to delete already exist images.

How modules i can use? How to create this submit form for they?

I use drupal 7.

Thank you!

EDIT:
Hi Vincent,
thanks for reply.

On example:
I have article about Rome with title "Rome". I create description for that beautiful city and i want to allow users to upload images to this exist article about Rome and create gallery of users pictures under descripton.

User can submit photo, but can't remove own or anyone images.
Admin must accept every image before it's publish.

Greetings.

Hints for your updated, clarified question (from NOT an expert)

Considering your updated question, there exists a documentation-page on Drupal.org on attaching images to nodes:

Attaching images to other nodes

But, perhaps easier to start off, is to read some answers posted to identical / very similar questions, here on StackExchange:

How to allow users upload images to existing nodes?
Add new images to existing nodes

Having referred to these, I would like to add that I would intuitively enable pictures in comments, and let people post the pictures in to the comments; but I don't know if that's what you're looking for.

If you would choose them to use the comments: after having enabled comments to include pictures, one can disable unneeded fields, similarly to the method described below, via

Structure >> Content Type >> Content type >> Comment fields.
Structure >> Content Type >> Content type >> Comment display.

For further fine-tuning of the display of the comments, the module Views is advised, which will allow you to first select a lay-out in the "Comment display" referred to above, via:

Structure >> Content Type >> Content type >> Comment display >> Layout for comment node content type

& will then allow fine-tuning of the fields in the comments.

The approving of the content by the admin; considering comments; can be tweaked via the row:

People >> Permissions >> Comment >> Skip comment approval

Alternative modules for admin approval of general content can be found in the following StackExchange-post:

Allow users to submit content that is approved before it is published.

Just a final extra remark (more of an alternative easy work-around really): if the text format (cf. Configuration » Content authoring >> Text formats) to be used for your users allows for the HTML -tag, one can of course tell your users how to "post" (but not upload technically) images as a comment, by explaining that they could use <img src="URL">, like you can find explained e.g. @ the W3C-wiki or @ W3-schools.

P.S.: You are a funny guy to re-use Rome.

I will leave my original answer below, which is more applicable to letting people upload pictures as separate nodes; but (as described below) is not a good method for letting people upload multiple pictures to already existing nodes (as you have now updated your question).

Answer to your original question

What you can do is to create a new content type.

To do this, use the administrative overlay & go to:

Structure >> Content Type >> Add content type.

Perhaps you could name the content type "Add a photo", or something.

Then, I would manage & display the fields such that all fields are hidden, except a field for a photo. This can usually be done after creating the content type, by going to:

Structure >> Content Type >> Add a photo >> Manage fields.
Structure >> Content Type >> Add a photo >> Manage display.

Then, I would restrict access to authenticated users (all of them / or some authenticated users; as you'd like) to create &/or edit certain content types only. This can be done (again, using the administrative overlay) by going to:

People >> Permissions >> Add a photo: Create new content
People >> Permissions >> Add a photo: Edit own content

The two boxes of these row can be checked at the column "AUTHENTICATED USER". (That is, if you'd like only authenticated users to be able to post pictures). Then, Creating & Editing of all the other content types should be disabled; if I understand you well. This can be done on the same page, by disabling the checkmarks for "AUTHENTICATED USER"s in e.g. the default content type "Article", via:

People >> Permissions >> Article: Create new content
People >> Permissions >> Article: Edit own content

This is just only what first comes to my mind. You'll see that Drupal is very flexible, and multiple roads lead to Rome.


Passing Promo Code to Drupal Commerce via URL I'm using Drupal 7 and Drupal Commerce Module. I'd like to be able to provide customized links with promo codes in them (promo codes would be a key/value pair in a format like www.url.com/?promo=specialK or some such thing). So Group A, for example, would get their link and click on it and it would bring them to our Registration/Product page form.

This would be the same form for every group with different discounts applied to the product price depending on the promo code attached to the URL.

If the promo is expired I'd like Drupal to just give the user a page that says something like 'Your promo is expired. Sorry. blah blah blah.' However, if the promo is NOT expired it would just apply the discount to the price and let them fill out the rest of the form and submit their payment information, etc > the normal drupal commerce procedure with the discount applied.

I'm thinking of approaching this with Drupal Coupon module to enable the discounting functionality, but I don't know if it's possible to use a URL to pass that promo code automatically to Commerce. Does anyone know?

There are a number of ways you could do this. Probably the best way is to use a custom module, define a menu path with a token, and do it all in PHP. But I live mostly in the GUI world. You could also do this using Rules.

I have done something similar in a 10 minute youtube video that describes how to use rules to construct a url that passes in information and does things (like adding a product to a cart, or in your case you could use it to add a discount/apply a coupon).

Video: Using Rules to create a url to add a product to cart

Step by Step

Download Rules URL Arguments
Create a rule that fires on the event "Drupal is initializing"
Add a "Text Comparison" condition. Compare the site:current-page:path token against your first parameter "promo" for a url like "test.com/promo?coupon=123"
Add all of the actions you need to react to the rest of the parameters. In the video you'll see how to get at those parameters in the url.


Import excel in field collection items I m using field collection items in my content type for particular upload function.

I want to use import excel feature to bulk upload with field collection item fields.

when i click on import excel upload button the field collection fields filled with excel data.

Can anyone help me, how to achieve this feature.

Thanks in advance.

Have you checked the field collection feeds module? It does exactly what you are looking for.

  Provides feeds integration for field collection module.
  Require Feeds alpha7 or later version.


Multiple source IDs error I'm getting error

Drupal\Core\Database\DatabaseExceptionWrapper</em>: SQLSTATE[42S22]: Column not found: 1054 Unknown column &#039;map.sourceid2&#039; in &#039;field list&#039;: SELECT map.sourceid1 AS sourceid1, map.sourceid2 AS sourceid2, map.destid1 AS destid1

when trying to use two value ids in migrate yml file:

id: recipe_daily
label: Recipes
migration_group: recipe
status: true

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  urls:
    - http://mysource.com/data
  item_selector: /recipes/recipe

  fields:
    -
      name: text
      label: 'Text'
      selector: text
    -
      name: title
      label: 'Title'
      selector: title
    -
      name: recipe_day
      label: 'Day'
      selector: '@day'
    -
      name: recipe_id
      label: 'Recipe id'
      selector: 'detail/@id'

  ids:
    title:
      type: string
    recipe_id:
      type: string

destination:
  plugin: entity:node

process:

  type:
    plugin: default_value
    default_value: recipe_daily

  title: title
  text: text

dependencies:
  enforced:
    module:
      - recipe

Since it's called ids I assume it takes multiple values but cannot find any examples anywhere. Any ideas much appreciated

I think you used to have 1 ID before and that you added the second ID after you ran the migrations?

If your migrations aren't in prod, you can simply delete these tables and try again:

migrate_map_recipe_daily
migrate_message_recipe_daily

I think it should work.

If your migration is in prod, you might have to:

Create a sourceid2 column matching with your ID type
Update the table keys to consider sourceid1 and sourceid2 as composite keys

I have tried the first one many times.


Subscriptions template: test for imagefield I send digest newsletters with the subscription module (using the templates that comes with the module), sometimes containing a small image before the teasertext (positioned with tables/row/column). This is all working well.

However in case there is no image available (because there is no teaser image uploaded to the applicable field or the contentitem doesn't even have a image field with that name) I get an ugly image outline in most email clients.
I would like to test if there is an image available and if not, not adding the first ... leaving only the teaser text.

Can someone explain which "template" code must be used in order to achieve this?

Code used so far:

    Your subscriptions on [site:name] notify you of the following changes since the previous digest:

    {{[subs:items:count]#

    #1 of [subs:items:count] {{[subs:items:index:#0:subs:is-new]?(new):}}{{[subs:items:index:#0:subs:is-updated]?(updated):}}{{[subs:items:index:#0:subs:is-old]?(commented): [subs:items:index:#0:as-node:title]}}

            [subs:items:index:#0:as-node:summary]

    Read more: [subs:items:index:#0:as-node:url]

    }}

If you can use php in the template (?) I would just wrap the cell containing the image in an if statement, something like this:

Your subscriptions on [site:name] notify you of the following changes since the previous digest:

{{[subs:items:count]#

#1 of [subs:items:count] {{[subs:items:index:#0:subs:is-new]?(new):}}{{[subs:items:index:#0:subs:is-updated]?(updated):}}{{[subs:items:index:#0:subs:is-old]?(commented): [subs:items:index:#0:as-node:title]}}

        <?php if(**code to determine if image exists**): ?>

        <?php endif ?>

        [subs:items:index:#0:as-node:summary]

Read more: [subs:items:index:#0:as-node:url]

}}

That way if there's no image it just won't print the cell at all and the other cell will take the entire width of the table.

If you can't use php in the template then I'm not sure how you could deal with it except perhaps by merging the two cells like this:

  [subs:items:index:#0:as-node:summary]


Import po-files using Drush I have about 20 sites that have a common translation. I don't want to go into admin of each site each time the po-file is updated.

Is it possible to import a po-file using Drush?

I found a way to do this using Drush and Localization Update.

Install Localization Update  drush en l10n_update
Configure a local path for po-files (admin/config/regional/language/update)
Configure automatic updates from remote servers or just local sources

Now you can put your own po-files in a local path (for example sites/all/translations). If you have translations for your own module then you name it according to this naming convention:

modulename-version.language.po

So a Swedish po-file for 'my_module', version 7.x-1.1 would be named:

my_module-7.x-1.1.sv.po

Now you have everything setup and you can start updating your sites translation with Drush:

drush l10n-update-refresh # Looks for new po-files
drush l10n-update # Updates translations


Pre-select a role on user register form and hide from display? I have this scenario that I am trying to walk through. I am new to creating custom modules, but I'm working on it (only way to learn...right?)

How would I go about doing this as I'm currently getting an error when trying. I have a role: 'venue admin' that will be responsible for adding other users with the role of 'customer'. I already am using the module: Role Delegation to handle the permissions side of things. But on the User Registration screen, I would like the customer role to be pre-selected and hidden from display.

This is what I have so far:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 */

function mandatory_role_form_user_register_form_alter(&$form, &$form_state,   &$form_id) {
global $user;

if(in_array('venue admin', $user->roles)) {
// by default notify user of new account is checked
    $form['account']['notify']['#default_value'] = TRUE;
// the only role the venue admin role can create is a customer so this is checked and hidden.
    $form['account']['roles']['#access'] = FALSE;
  }
}

obviously, this is not complete and missing the ability to set the role. Any suggestions?

well..after staring at this question and trying a bunch of things on my own I think I stumbled upon the answer. Using HOOK_user_presave did the trick! This helped immensely: https://drupal.stackexchange.com/a/79065/28353

function mandatory_role_user_presave(&$edit, $account, $category) {
global $user;
if(in_array('venue admin', $user->roles)) {
  if($account ->is_new) {
    $roles = user_roles(TRUE);
    $rid = array_search('customer', $roles);
    if($rid != FALSE) {
      $edit['roles'][$rid] = 1;
        }
      }
    }
  }


Redirect User: Delay + Intermediate page I have been trying to get a quick easy way to redirect the user, no matter where they go to the site straight to the user login page. But before I do, I want to redirect them to another page saying some message like "Sorry, you need to be authenticated to view blah blah... you are being redirected to the login page".

I currently have:

function mytheme_preprocess_page(&$vars, $hook) {
  global $user;
  if ($user->uid == 0 && arg(0) != 'user'){
    drupal_goto('user/login');
  }
}

Before the goto call you can add
   drupal_set_message( $message, $status);

Its the more straightforward solution, although the message will be displayed inside the login page and there wont be any delay.

Or just change the goto path to a custom... 'user/sorry' page with your message, and something like:

and a JavaScript function

function myRedirect(){ window.location = "user/login"; }

Add the standard "if you are not redirected, click here" link in case JavaScript is disabled.


Can Search API filter "Index full entity" be used in Search API views? I have set up a Solr index for user profiles on my site with the Search API Solr Search.  The profiles are pretty complicated-- several relations, lots of fields, and many theme templates to render them with complex logic.

I am trying to speed up the performance of my search views, and I found this option under Data alterations on the Solr index:

Complete entity view

Adds an additional field containing the whole HTML content of the entity when viewed.

I thought I could use this as a cache by saving the rendered HTML to Solr for the user profiles, and then, in my view, I could just display this one item, the complete entity view, instead of having to configure all my fields and views formatting templates.

So, I did the following:

At /admin/config/search/search_api/index/MYSEARCH/fields, I selected the field for indexing (complete entity view) as fulltext.
At /admin/config/search/search_api/server/MYINDEX/edit, I turned on "Retrieve result data from Solr" as noted in this D.O post.

When I do this, I can now select the "Complete entity view" under Fields in the Views UI, but no result (no HTML output) is returned in the display.  How can I add the output of the "Complete entity view" in Views?

This should be possible. I did the same thing with Search API + Elastic search (No Views module though). And yes it did speed up the results. However, in retrospect I may have been better of using Render Cache module in conjunction with an object cache like Redis and or Memcache.

The main pain point that I ran into doing full storage of HTML in the search server was that nearly every theming/template change required rebuilding the search index.

All that being said, if you want to keep going down this route I suggest using Solr's built in inspection tools to first validate that the user profile HTML has made it into Solr at all.


Count of nodes filter in views for a taxonomy with depth sorry for my English.
In views, Drupal 8/9, is it possible to have the count of nodes for a taxonomy-term with depth?
I would like to have it for the filters in views.
I can't find any modules to get this information.
Maybe I don't know how to look or a complex module gives this possibility but I couldn't find it.
Aggregation doesn't really help me. Performance is not a problem.

There are several ways to do it, based on how you are going to manage your content.
But for your problem I guess the solution can be this:
1. In Fileds: add Taxonomy term: Name
2. In Relationships, add a Taxonomy term: Content with term
3. Add a contextual filter for Taxonomy term: Name
    3a. Choose 'Display a summary'
    3b. Choose 'Display Record count with link'.

Here is several resources that can help:
Views and node count for taxonomy terms
How to display number of nodes with current term?
Showing how many nodes are associated with a term
Display node count per node reference field


Serving CSS, images and JavaScript in Drupal Does the whole Drupal stack get fired up (bootstrapped) each time one of these static content types gets requested?

Nope, it does not.
But if you have let's say in one of your stylesheet files a reference to a missing image, or your code is trying to load a missing js file then because of the Rewrite Rules in .htaccess this requests are redirected to index.php and that causes the bootstrapping of the whole system to render the 404 page.


How to add a CSS class to field label and items div? I want to add a class in the field label and field items, the HTML I want is the following:

Price:&nbsp;

100

I've tried field_formatter_class, the module allow me to add a "row" class into the container, but not in field-label and field-items. I want to add col-md-2 class for such two divs

How to do that without writing a module to do that?

have you try hook_preprocess_field().

please check this link everything is given in this blog may be it help you
http://atendesigngroup.com/blog/adding-css-classes-fields-drupal


How do I debug with Xdebug in Visual Studio Code? When I try to debug Drupal 8 (8.6.11) using Xdebug in VS Code (I'm on Win 10 but I doubt it is relevant in this case) I get the following error:

  Exception has occurred. Dotenv\Exception\InvalidPathException: Unable
  to read the environment file at /app/.env.

The problem is either with VS Code or with Drupal as someone has reported exact same behaviour on High Sierra and they were using Drupal 8.6.10:
https://github.com/lando/lando/issues/1501

I did not find anything in drupal docs about the neccessity of creating a .env file to use Xdebug, so I suspect a bug eihter in Drupal 8 or VS Code.

Has someone encountered similar behaviour?
Should I file a bug report on Drupal site?

InvalidPathException is an exception related to the vlucas/phpdotenv composer package so this issue isn't related to the Lando & VS Code codebases; it's an issue with your Drupal code base.

You can confirm phpdotenv is a Drupal dependency by looking at your composer.json file and looking at the require section.

The issue is the package dependency isn't finding the /app/.env file in your Lando environment. Confirm that the .env exists in your Lando project root (the same dir as your .lando.yml file).


What function should I use in instead of mimemail()? I was using mimemail(), a function defined from the MIME mail module, in Drupal 6 to send emails using attachments.
The Drupal 7 module doesn't have mimemail().
What function should I use in Drupal 7, instead of mimemail()?

The reason the mimemail() function does not exist for Drupal 7 is because it is not needed.

See, for instance, issue: API function for quick send html mail without uneccessary operations (mimemail analog from 6.x) in the project's issue queue;

  On Drupal 7 calling drupal_mail() is enough. See the README.txt and drupal_mail_system() for more information.

The general idea is that you set up the Drupal to use MimeMailSystem for some or all mail messages sent by your module:

mailsystem_set(array(
  '{$module}_{$key}' => 'MimeMailSystem', // Just messages with $key sent by $module.
  '{$module}' => 'MimeMailSystem', // All messages sent by $module.
));

and then calling drupal_mail() is enough.


How do I show a percentage value in a views_field? How do I show the percentage value in a views_field?

col(1) (group by) field_a
col(2) (count)field_a *100/number of results " -->@total"

I'm still not able to use @total in a computed_field or a math-expression_field or a global_custom_field.

I need this value for the Highcharts module, so using "aggregation plus" also seems not the solution.

Using a PHP field inside views is highly risky for security reasons as I read here in other answers.

to achieve some calculations I see 2 different solutions.

1/ You create a custom sql query with (db_query) inside a custom module that gonna trigger a view to render, your select clause will make the calculation for you so you will have your result that you are going to display inside a custom field in your view.
You can see the actual query you are executing by using the devel module and then tweak it.

2/ You can use computed_field module but it's a really dangerous thing to integrate PHP inside a field somewhere, because if your php breaks, you will break your complete site, and need to rollback your database. But I don't suggest this solution because it's really risky for your site.

I hope it helps

Cheers


Problem using entity reference to show links to content types associated with a content type I have a content type called module and a content type called lesson.  Module can contain unlimited lessons.

I installed entity and entity reference module.
In module, I created a field type of entity reference and set target to node, entity selection to simple and lesson.
I saved these settings and found I now have select box which allows me to add select lessons when I edit a module type.

However, when I go to the module page I don't see any lessons or even a label for lessons.

Does anyone have any idea how I can troubleshoot this, or what might be wrong?  Also, would i be better trying to create a view rather than using entity selection simple mode?

Thanks in advance,

First thing I'd do would be to check the display settings for your module content type. The field may be hidden or otherwise not configured as you want.


Undefined property: stdClass::$collapsible After creating a vertical tab in my installation profile I keep getting these notices:

Notice: Undefined property: stdClass::$collapsible in field_group_pre_render_tab()

and

Notice: Undefined property: stdClass::$collapsed in field_group_pre_render_tab()

Here is the code I use to make a vertical tab in my installation profile:

$verticalTab = new stdClass();
$verticalTab->disabled = FALSE;
$verticalTab->identifier = 'group_attachments|node|foo|form';
$verticalTab->group_name = 'group_attachments';
$verticalTab->entity_type = 'node';
$verticalTab->bundle = 'foo';
$verticalTab->mode = 'form';
$verticalTab->label = 'Attachments';
$verticalTab->children = array( 1 => 'attachment');
$verticalTab->format_type = 'tab';
$verticalTab->weight = '0';

So am I missing something? or has this notice got nothing to do with the vertical tab and do I have to look elsewhere?

Any help to fix this notice would be appreciated.

Normally the collapsed and collapsible properties are used on fieldsets.
It looks like field_group is expecting for an undefined property on the vertical tabs object.

You could try adding them to your definition as such:

$verticalTab->collapsible = FALSE;
$verticalTab->collapsed = FALSE;

That should keep the field_group module happy.


How to change the HTML Output of a view? This view is a black book directory that will have a long list of links to static pages. The problem I am having is the output isn't coming out as an unordered list like I have set. Each link is set in a span and a row. Is it possible to output a simple ul with an id on it. I am having trouble matching my design.
Thanks

Drupal likes to put  and
 around every item. When you don't like that, you can override the PHP file that's causing this.

Look in the sites/all/modules/views/theme folder at the views-view-list.tpl.php, views-view-field.tpl.php and views-view-fields.tpl.php files.

Save a copy of these files in your own theme's 'templates' folder. Then you can edit the copies to strip code that makes   and
 etc. You should also rename your version of these files according to the view's template suggestions so the changes only affect your view.

I used this for a view where I wanted to make 3 columns, so I wanted the classes li_1, li_2 and li_3 (in file views-view-list.tpl.php)

<?php
// $Id: views-view-list.tpl.php,v 1.3 2008/09/30 19:47:11 merlinofchaos Exp $
/**
 * @file views-view-list.tpl.php
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */

global $cnt_ul;
global $cnt_li;
$cnt_ul++;

$classNameUl = (($cnt_ul % 3) == 0)? "ul_". $cnt_ul ." last" : "ul_". $cnt_ul;
?>
<ul class="<?php print $classNameUl ?>">
<?php
foreach ($rows as $id => $row): $cnt_li++;
$className = (($cnt_li % 3) == 0)? "li_". $cnt_li ." last" : "li_". $cnt_li;
?>
<li class="<?php print $className ?>"><?php print $row; ?>

<?php endforeach; ?>


The best way to store drupal Configuration I know three options to store the configurations:

Use the UI and store the values into the variable table.

Also you can store them in settings.php and use the $conf[''] array to store the information.

The last options is to store the values with variable module.

What do you thing is the best one, not for an final user but for a developer.

Oskar

I don't add "strongarm + features" because sometimes features is a little nightmare, and I'm trying to leave it far from me.

If you're literally looking for variable storage, then variable_set() and variable_get() are the way to go...during development.  However - that means the variables are stored in the DB rather than the file system which can make deployment a bit painful later on.  From your question, I assume this is what you are trying to avoid.

If you're looking to store sitewide configuration as opposed to just variables, then there are a couple of options.

Features

I know you said you don't want Features, but Features 2.x is actually a MASSIVE improvement over 1.x, so if you've not ooked at it for a while I'd suggest giving it another go.

Disclaimer: I love Features 2.x :-)

Configuration Management

Then there's Configuration Management which is an attempt at working some of the Drupal 8 CMI work to Drupal 7.  It's relatively easy to use, and also pretty easy to extend.

On another note; Clive is kind of a Configuration Management evangelist - so if you have any difficulties with it then you have a wealth of information here.

Manual

Lastly, you could create a custom module that implements default configuration hooks (such as hook_views_default_view or hook_default_rules_configuration).  A keen eye will notice that these hooks are a key element in getting configuration into Features :-)

Strongarm is also not dependent on Features, so you can utilise the Strongarm API yourself :)

Extra

I tend to use $conf[] in combination with a Git-excluded local.settings.php (see this question for a reason as to how and why) file for storing environment-specific configuration (such as site e-mail - things that might change between environment).


Drush with a dockerized Drupal install I'm trying to setup a development environment for Drupal using docker.

I've already succeeded on creating a PostgreSQL container and a Drupal container using official images for both, and I can replicate the production environment.

How do I get drush to detect my Drupal install?

I've tried both https://hub.docker.com/r/drush/drush/ and https://github.com/DockerDemos/appstack-drush (had to build that last one) but when I run drush inside the containers they don't see the Drupal install.

I run "docker run --volumes-from <my-drupal-container> --link <my-db-container>:postgres -it drush/drush dd" and it shows nothing, "drush cc" finds no caches.

There are 2 things you can do here:

Use Docker as external container like you are doing. You need to pass the --net parameter too to make that work, see example below. You will always use this drush container as a running command, not a container that is up and running with your stack all the time.

docker run --net={your_container_network_name} --rm -it -v $(pwd):/app drush/drush sqlc

Simply add drush to your Drupal container and connect to that container to run drush commands:

Dockerfile:

ENV DRUSH_VERSION 8.1.2
RUN curl -L --silent https://github.com/drush-ops/drush/releases/download/${DRUSH_VERSION}/drush.phar \
  > /usr/local/bin/drush && chmod +x /usr/local/bin/drush

Connect to your container and then run any drush command inside it:

docker exec -it {container_id} bash

root@{container_id}:/var/www/html# drush status


Views programmatically remove node access (tag) I'm trying to remove the node access check from a view programmatically.
But i'm not sure where the access tags are added/executed.

function MYMODYLE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
kint($query);
}

If i print the $query the tags are empty, and i can't really figure out where or when those access tags are added. And how to manipulate them.

Can someone point me in the right direction?

Drupal: 8.3.2

Found it:
MYMODULE_query_node_access_alter().

$query->condition contains al de realm conditions, these can be adjusted here.


I want to get all of the allowed values of a field Let's say I have a field in Drupal called resource_type, and I wanted to get all allowed values. Is there any easy way to do this with a command, or do I have to do a database query? I'm not seeing anything specifically that would make this easy.

For list type field you can use list_allowed_values function , You can also use field_info_field($field_name) for more details about field.

$my_field = field_info_field('field_resource_type');
$allowed_values= list_allowed_values($my_field);