Render an HTML element before the menu with hook preprocess menu I want to render an HTML element like This is my menu before my menu. I thought the most easy solution is to alter the menu. I already altered my menu to add a class. But how do I add an element before my menu with a hook preprocess function?

I know I can extend menu.html.twig to menu--my-mwnu.html.twig and add it there but I think it's less overhead to add it with a preprocess function.

/**
 * Implements hook_preprocess_menu().
 */
function mytheme_theme_preprocess_menu(&$variables) {

  if (isset($variables['menu_name'])) {
    if ($variables['menu_name'] === 'my-menu') {

      $variables['attributes']['class'][] = 'my-menu';
    }
  }
}

In this case you should edit the template. Changes to markup should be done in templates.

  Ok thank you. I will extend the twig file. But just to know. How do I add it within my preprocess function?

Looking into the standard menu.html.twig there isn't any place left to preprocess content to have it prefixed with some markup for example. There are just menu items that must be of type URL and attributes.

So your best bet probably is to add the markup to the block instead (in case you print your menu in a block).

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_block__footermenu(&$variables) {
  $variables['content']['#prefix'] = 'This is my menu';
}


adding block region inside of menu section I have a menu section in my theme where i display the main-menu menu. This works as expected. with the following code.

<?php print theme('links', array(
                    'links'         => menu_navigation_links('main-menu'),
                    'attributes'    => array('class'=> array('navbar', 'navbar-collapse', 'collapse'))
));?>

I would like to make a block region inside of this rendered menu section for the search box. The end results will be block region at the end of the menu that i can style to be to the right of the menu. I could do this in css but was hoping to make the rendered html a little cleaner. This is what I have tried.

<?php print theme('links', array(
                'links'         => menu_navigation_links('main-menu'),
                'attributes'    => array('class'=> array('navbar', 'navbar-collapse', 'collapse')) ,
                'region'        => render($page['search']);
));?>

There looks to be no tutorials on adding a block region to the menu array. Is is possible to inject a block region into the menu render array?

Part of the problem is that regions aren't really what you're looking for here. Drupal regions are just areas of the page, and you set content to appear in a given region. One way of utilizing regions for this would be to have a menu region defined in your theme's .info file, and then putting the menu and the search block in that region. I'm betting that's not really what you're after, though, because it doesn't result in very clean code.

There are two other options that I can see. One is to create your own theme callback for menus so that instead of calling theme('links', array(...)), you're calling theme('your_new_theme_callback', array(...)). You can define different variables for this theme, and one of them could be for the search block.

Of course, because this is Drupal, there's already someone who's gone "Man, I really want blocks in my menu and there's no nice way to do that in Drupal" and created a module. The Menu Attach Block module lets you attach a block to your menu. I've not used it before so I'm not 100% sure how to implement it in the way you're looking for. It doesn't look like you'd have to change your code at all, I don't think, because it looks like the module overrides theme_link() for you.

Does that make sense? If you want more details, let me know!


What better way to add new features on a project already in production? We know that drupal is based on nodes.

I feel it difficult to make updates to a project already in production.

Currently I have two environments. A testing, and other production.
I make changes in the test environment, then I redo the production environment.

Is there any way I can do packages with content types, views, and maybe even taxonomy nodes, and import them into production?

Thank you.

I think you are looking for what KiamLalluno is answered in the comments.
I would just like to supply it by saying
These module have been helpfull for me when I was in your situation

Deploy Module

GO live checklist

Drush

Feeds Module

Features Module

Enviroment Indicator

Hope it helps


How could I send daily or weekly email in cron() function? I have a content type in which I have drop down list with the values of "daily" and "weekly" and one field is of email. I want to setup the cron function like when the value of that drop down list is "daily" then email will be send daily to the email address of whatever entered in the email field and when the value is "weekly" then the email will be send weekly.

I don't have any idea about this. How will I do this?

How are you generating your email?  It sounds to me like you need a custom module that implements hook_cron.  It would have to save the email address and send_interval to it's own table (or you'll have to build a query to select the email and interval from wherever you've stored it) in the database during hook_nodeapi with the update $op and/or the insert $op.  I recommend creating a 3rd column in your table with a date for the last time email was sent.  That way if cron gets interrupted it can continue where it left off.  Use a sql query to select all of the rows with column interval == daily and date < NOW() and send emails out.  Then do the same if the date is a Sunday or whenever you want to send weekly emails for those.  As you process a row, update the date field to the current time which indicates the email was sent.

If you're not up for custom development, you may want to see if the notifications module suites your needs.


Link translation for custom block I'm here

I need to create a link to three languages. for example

     Link 1

     Link 2

     Link 3

other in Spanish

     Link 1

     Link 2

     Link 3

In Portuguez

         Link 1

         Link 2

         Link 3

When I go to the block to see its links, by default it always appears / link / 1 no matter what language I am in.

It does not take in language: it ES or EN o PT-BR

Link 1 --> hover url = http://url_site/link/1
in any language.

should be

Link 1 --> hover url = http://url_site/en/link/1
OR
Link 1 --> hover url = http://url_site/es/link/1
Link 1 --> hover url = http://url_site/pt-br/link/1

configuration of my block.

To do this for custom blocks, you will need to enable translations for blocks and custom blocks in the settings.  Then you will need to create translations (with the correct links) for each language.

Details:

Go to /admin/config/regional/content-language
Make sure custom blocks is selected at the top.
Save
Scroll down to Custom Block section
Make sure the basic block and at least the title and body fields are translatable.

To Edit the block.

Go to the Custom Block library
The Edit drop down should have a translate option
Select this and in the translate screen, create a translation.
Edit for the needed language.

Result is that if you are looking at a page for lang X and there is a lang X block translation.  You will see this block.


cache set in custom table not working? I am trying to set cache with in my custom created cache table which is created with below code:

function custom_activity_dashboard_schema() {
  $schema = array();
  $schema['activity_dashboard_cache'] = drupal_get_schema_unprocessed('system', 'cache');
  return $schema;
}

function custom_activity_dashboard_update_7021(){
  $schema = custom_activity_dashboard_schema();
  if(!db_table_exists('activity_dashboard_cache')) {
    db_create_table('activity_dashboard_cache', $schema['activity_dashboard_cache']);
  }
}

Table created looks like screenshot :

Just added simplly this code to test if cache entry get created or not :

   $cache_time = '+10 minutes';
   $expire = strtotime($cache_time);

  $t_revisions = total_revisions();

  // set cache
  cache_set("total_revisions", $t_revisions, 'activity_dashboard_cache', $expire);

  // get and print cache value
  $cache = cache_get("total_revisions",'activity_dashboard_cache');
  echo $cache->data;

with above code there is no entry in database table when I run query to see :

But when I print value by cache get it prints value that was cached on my page.

I am not able to figure out what I am doing wrong and why cacnot I see entires in database table but the value after cache get is printed.

Please suggest what I am doing worng.

With same code I can see entires in database table on my loacl environment.

UPDATE :

We are using redis and entity_cache for full site.

Thanks!

If you are using redis, wouldn't your cache bins not be controlled in the Drupal database anymore? You would therefore need to explicitly set the cache bin to use DrupalDatabaseCache so that it uses the Drupal database in settings.php.

Example:

$conf['cache_class_activity_dashboard_cache'] = 'DrupalDatabaseCache';

This is how it used to be done with Memcache... Redis should be the same, but check the README:

http://cgit.drupalcode.org/redis/tree/README.txt?h=7.x-3.x

It would explain why you can query this on your local machine, if you only have Redis configuration set for the remote environments running it. You are querying the database, but the cache is pulling from Redis.

This is for Memcache, but sheds more light on excluding certain cache, like cache_form - which remains in the database. https://www.drupal.org/node/1131468


Drush equivalent setup on Windows? One of my clients insists on using WAMP for hosting Drupal 7. I've always been using Ubuntu for development, but now I have to work with WAMP. I do much Drush administration with sql-dump and modifying Drupal from the command line. I tried Drush on windows, but it is PITA to use.

What are some ways to use Drush as close as possible to the Linux versions? For some reasons, some Drush commands don't properly work on Windows. I usually use drush sql-dump > backup.sql, but in Windows there is no equivalent to that.

There are four possibilities:

Using Git Bash for Drush. Off the top of my head, this won't work for SQL commands, though
If you're using Windows 10, you may want to install the anniversary edition update. It gives a Linux bash shell. It also has its limits (no kernel modules), but those limits shouldn't impede Drush use
CYGWIN. It may take some fiddling, but may do the trick too
Try and persuade your client to use Vagrant, then run Ubuntu in there


Need help for Drupal 7 Ajax Add more form elements $form['feedbackmarkup']['feedback']['num_domains'] = array(
    '#type' => 'hidden',
    '#default_value' => 1,
);
       $num = isset($form_state['values']['num_domains']) ? $form_state['values']['num_domains'] : 1;
     for($i = 1; $i <= $num; $i++){
    $form['feedbackmarkup']['feedback']['fname_'.$i] = array(
        '#type' => 'textfield',
        '#size' => 12,
        '#required' => true,
        '#prefix' => '
',
        '#suffix' => '	',
    );
    }
       $form['add_more'] = array(
        '#type' => 'button',
        '#value' => t('Add More'),
        '#href' => '',
        '#ajax' => array(
           'callback' => 'for($i = 1; $i <= $num; $i++){
    $form['feedbackmarkup']['feedback']['fname_'.$i] = array(
        '#type' => 'textfield',
        '#size' => 12,
        '#required' => true,
        '#prefix' => '
',
        '#suffix' => '	',
    );',
           'wrapper' => 'feedback_replace',
         ),
       );

and In my Ajax callback function

  function ajax_example_simplest_callback($form, $form_state) {
         $test = isset($form_state['values']['num_domains']) ? $form_state['values']['num_domains']+1 : 1;
        $form['feedbackmarkup']['feedback']['num_domains']['#value'] = $test;
       drupal_set_message(print_r($form_state['values'],true)); //It is printing form_state with values but not adding my fields above in for loop
        return $form['feedbackmarkup']['feedback'];
}

It was not adding my field because #required is set to true. Now I removed it, and my problem is solved.


Exposed filter render as autocomplete but I need a select field I have a moderation queue that uses these filters:

published: no
content type: xxxx
author uid: EXPOSED

Drupal renders the exposed filters as auto-complete, but I need to use a select field. Is it possible?

This is an advance solution.  Checkout how this guy did it for a similar problem by creating his own view filter. Creating custom filters in views 2


Failed opening required" symfony/class-loader/ApcClassLoader.php on line 110 I get this error after installing a module in modules/contrib and then uninstalling and moving it to a different directory. I accidentally installed the module in the wrong place.

This is in a local BLT/Drupal-VM environment. I've tried drush cr and rebuilding the drupal core directory as well as nuking the vendor folder that composer installs.

Seems that the paths to the installed modules gets stored in PHP memory some how and after the move php is not picking up the changes.

Restarting apache doesn't do anything either.

Restarting php from within the VM seems to have done the trick.

sudo service php5.6-fpm restart


How can I check, if node has a new (unpublished) revision in node-template? I have user created content. I use the content-moderation plugin, so user can update their nodes but the updates will only be published after moderation. I like to display a little batch (has new unpublished update) on the user-nodes, to give the user an information about the moderation state.

For nodes with new revision in draft-state shows drupal a "last-version"-link in node-links-menü. It must be possible to check, if there is a new revision in draft state (in preprocess_node). Who can help me and write a little php code for this check so I can generate a twig_variable "has_draft_state".

Thanks in advance

Maybe this could help you

{% set isNew = node.isNewRevision %}

Otherwise use template_preprocess_node() in your theme to generate needed variable.


How can I add a custom CSS class to checkboxes labels? I'm using Drupal 8 with the Form API and the AJAX API, now I want to add a custom CSS class to every checkbox label, because I need to use the bootstrap custom checkboxes.

PHP (slimmed):

$form['colors'] = array(
    '#type' => 'checkboxes',
    '#options' => array('1' => $this->t('Black'), '2' => $this->t('White')),
    '#attributes' => [
        'class' => ['custom-control-input'],
    ],
    '#prefix' => '
',
    '#suffix' => '
'
);

HTML Result (please notice every label has the class "option"):

        <input
          class="custom-control-input form-checkbox"
          data-drupal-selector="edit-colors-1"
          data-msg-required="Black is required."
          type="checkbox"
          id="edit-colors-1"
          name="colors[1]"
          value="1"
        />
        Black

        <input
          class="custom-control-input form-checkbox"
          data-drupal-selector="edit-colors-2"
          data-msg-required="White is required."
          type="checkbox"
          id="edit-colors-2"
          name="colors[2]"
          value="2"
        />
        White

My Twig Code:

 {{form.colors}}

I know about the "template_preprocess_form_element" function, but I had no luck.

Do you guys have any ideas or tipps? Is there a simple way to modify the label class, or should I try the "Form Options Attributes" Plugin?

Thanks

According to issue #2774255 and line 38 in the FormElementLabelTest.php you should be able to use #label_attributes for this.

'#label_attributes' => ['class' => ['meow']],

Update: Seems you can also try to do this by implementing template_preprocess_form_element. There's an example on line 493 in the form.inc. In your theme implement template_preprocess_form_element and hopefully you find some unique identifiers in there to have this class added only for elements in certain forms or elements of certain types. And then it's

$variables['label']['#attributes'] => ['class' => ['meow']]

Last but not least there's the new Formdazzle! module you could try to use to override the label element templates directly.

  Drupal form theming with less pain

  Theming Drupal forms can be difficult and time-consuming. This module
  provides a set of utilities that make form theming easier.

  Currently, this module provides theme suggestions for forms that are
  much more useful than those provided by Drupal core.

  Theme suggestions for all form elements (including buttons)
  Theme suggestions for all form element labels
  All theme suggestions include the form ID and the form element name; e.g. [element-type]--[form-id]--[form-element-name].html.twig


Drupal Language Switcher menu item I am using D 7.28 with Boostrap theme (https://www.drupal.org/project/bootstrap).
I am using the theme's 'Main menu' to display my links. The language switcher works well for me (changing homepage, Hero banner block and navigation into the appropriate language).

I would like to move the language switcher to the 'Main menu' and display it as an item only showing the inactive language.

Could anyone please provide instructions how to do it?

I have a small module hosted on GitHub that does just that:
Locale Menu
From the README file:

Overview
Alters the href of any menu item whose title is "English" or "Español" to point to the translated version of the current menu item. If no translation exists for the current menu item, the link will point to the translated version of the homepage.

You'll need to tweak Lines 6, 15, and (especially) 21 of the localemenu.module file to match the name and language code of your language.


How do I link Drush to my Drupal site on Pantheon? A friend of mine got me into Drupal and did the initial setup for me. At first, I was using localhost to play with Drupal and Drush to download and enable modules.

Now I have my own Pantheon hosting site that lets me install Drupal on their side, but how do I link my Drush command prompt to my online site? Before on localhost, it was just a matter of changing directories, but how do I connect it for a site online?

Edit: This is for Drupal 7.

Start off by installing Terminus. Terminus now supports machine tokens; once you set these, up you can authenticate automatically without a password simply by running terminus auth login <email address>.

Once you are authenticated with Terminus, terminus sites aliases will download Drush aliases for all of your Pantheon sites. Since this list can change over time (e.g. when you add or delete sites on Pantheon), you will want to periodically re-run this command.  You might even want to have Terminus log in and update your aliases in your shell startup script (e.g. .bashrc).

Once your aliases are up-to-date, you can use a remote site via:

drush @pantheon.mysitename.dev status


How do I reduce  elements? How can I reduce div elements Drupal creates in a view block?

for exmaple I have a block created by view and I see these many divs:

aaaaaa

                    bbbbbb

Are these two many div really needed? Can I reduce them by define a theme for this block?

I use Semantic Views to remove a lot of the cruft from views.

  This Views plugin makes unformatted styles, field row styles and other
  output more readily configurable without needing to override template
  files. Instead of overriding row style templates for views where you
  want to specify different HTML elements (tags) and class attributes,
  you can specify these inside the Views UI and avoid overriding
  templates for each view.


How do I plot a graph or chart on the confirmation message? How do I plot a graph on the confirmation message, on a webform and Drupal 8?
I searched a lot, but did not find anything useful, but these results.

There are several modules involved in graphing, including the Charts module.

There is a programming solution (Display webform results data in a Google Chart), but I don't think it works, since the site will contain dozens of questionnaires. Drawing charts should be easy, something similar to Twing or only in the confirmation message textBox area.

images files can be displayed if uploaded to the site via the questionnaire in this way (from How to Display Image after submitting webform in the confirmation message page).
<img src="[submission:values:image_key]"/>

There are previous attempts at Drupal 7, such as the Webform Charts module. I don't know how it worked.

Since there doesn't seem to be a solution for this, I would define a webform handler that would preprocess the confirmation page with the chart that you generate.
There are plenty of D8 module for charting, and in the handler you have access to the webform submission values. You could even use a different method and save the chart image into a hidden image field on the submission. Handlers are sweet like that.
Check out WebformHandlerBase class/interface for the full method list. Checkout this other answer involving webform handlers to get you started. Once you have your handler, check out these examples for your methods.
Acting on presave()
/**
 * The example below demonstrates:
 * - retrieving a submission value
 * - processing it
 * - setting a field value to that result
 *
 * @param WebformSubmissionInterface $webform_submission
 *   A webform submission.
 */
public function preSave(WebformSubmissionInterface $webform_submission)
{
  $age = $webform_submission->getElementData('age');
  $ageChart = $this->someInjectedFooChartingService($age);
  $webform_submission->setElementData('age_chart', $ageChart->BarExportPng());
}

Acting on preprocessConfirmation()
/**
 * The example below demonstrates:
 * - retrieving a submission value
 * - processing it
 * - passing data to the confirmation template
 *
 * @param array $variables
 * @throws Exception
 */
public function preprocessConfirmation(array &$variables)
{
  /** @var WebformSubmissionInterface $webform_submission */
  $webform_submission = $variables['webform_submission'];
  $age = $webform_submission->getElementData('age');
  $ageChart = $this->someInjectedChartingService($age);
  // Add data to the confirmation template
  $variables['agechart'] = $ageChart;
}


Displaying users who click the button I have 2 user roles in my Drupal 7 site 'A' and 'B' respectively:

users of role 'A' can create and publish content.
users of role 'A' can see content they created on their profile page. (For this purpose I created a block to display content and put it on user's page.)
users of role 'B' can not create content but they can view all published content.

Content in my case is an invitation to some event (ie "Who wants to play football on Friday?")

Each content has 'Participate' button which users of role 'B' can submit.

How can I display in 'A' users pages the names of 'B' users who want to participate in their event?
How can an 'A' user confirm participation of some 'B' users and dismiss the rest?

This is quite a complex task your planning – and it's hard to answer in just a few lines of text. I can basically just recommend you have a closer look at the mighty Rules module in combination with the Flag and the Entity reference module.

Here's just a vague suggestion / outline of how this could probably be done by combining the above modules:

Put a flag 'participate' on content type event users of role 'B' can use
Define a new content type 'participation' with checkbox/flag 'confirmed / dismissed' and reference the event and the user to it, editable by 'A' users
Make a rule that generates a new node of content type 'participation' and alerts users of role 'A' of a new request
Extend your profile pages' view with the referenced items of content type 'participation'

There is probably different ways to do this – most likely also easier ways than the one described above. And then there is also a more specific module 'Rules link event' that might fit your demands.


SMS Framework - Multiple destination numbers I'm using SMS Framework module to send sms from Drupal site; Clickatell is setted as my default gateway. Using Rules module I'm able to notify users via sms when new node is created, but i can only setup one destination number.
Is there anyway to setup mutiple destination number?

A screenshoot of my rule configuration below:

Assuming your question is about D7, you could try to create a view (using the Views module) of those users that you want to send an SMS to.

After you succeeded in creating such view, you can process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions (in the rule you already have in place):

Load the VBO list of those users.
Add a loop to perform a Rules Action "send an SMS" (similar to what your current rule already does), for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


how disable edit for a certain content type, and a certain role, in a drupal 7 site i have been given to maintain, it seems that permissions are not working as expected. I check and uncheck the buttons for a certain user role, but that user role always has the right to edit any node that belongs to this particular type.
1. What could be the cause for this?
2. If this is not working from the gui, how i could achieve something similar with code?
I would appreciate an example

In /admin/people/permissions Under "Node" category you can uncheck the permission "Edit content X" for your desired role.

I would recommend using this module if your site has a lot of modules/permissions since due max upload vars limitation by PHP could led to not storing your chages when submitting the form.

Also by code you can implement hook_node_access and put there some logic. Take a look on how core does it.

/**
 * Implements hook_node_access().
 */
function node_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if (in_array($type, node_permissions_get_configured_types())) {
    if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
      return NODE_ACCESS_ALLOW;
    }

    if ($op == 'update') {
      if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
        return NODE_ACCESS_ALLOW;
      }
    }

    if ($op == 'delete') {
      if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
        return NODE_ACCESS_ALLOW;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}


Wysiwyg with ckeditor and custom configuration Is there any way to add custom configuration to ckeditor when using through the wysiwyg module?

Using the ckeditor module there is an advanced option and there it is possible to edit that.

Take a look at this Denver DrupalCon2012 Talk: What-you-see-not-always-what-you-get-it-can-be

Google Docs here


How can I get the labels of values of a field? I have created a List (text) field that has key|label pairs as options. How do I get the label, when the key is what is stored in the node?

This was my solution:

  if (isset($node->field_k_status[LANGUAGE_NONE][0]['value'])) {
    $info = (field_info_field('field_k_status'));
    $status =  $info['settings']['allowed_values'][$node->field_k_status[LANGUAGE_NONE][0]['value']];
  } else {
    $status = "Not Set";
  }

At this point, $status will have the label of whatever field_k_status is set to.
field_info_field() gets the details about the field, and $node->field_k_status[LANGUAGE_NONE][0]['value'] gets the value. I think that there is likely a better way, but I couldn't find it. There is a somewhat similar question asked here, but I didn't find what I was looking for anywhere else.


Table view: "Hide Empty Column" checkbox doesn't seem to work I've created a view, formatted as a table.

I'm trying to hide empty columns – so, in the table settings, I've checked the "Hide Empty Column" checkbox for most of the table columns.

However, this doesn't seem to have any effect – these columns are still included in the rendered table, with empty <td>s.

I expect this checkbox to hide the column entirely when all data cells contain an empty value. Am I understanding this correctly?

This certainly seems to be how it worked in Drupal 7. (I'm converting an existing D7 site to D8 – and this is how the table columns were hidden on the D7 site.)

Is there anything I should check which might be preventing this from working as expected?

Thanks.

Someone elsewhere suggested that I disable Twig debugging. This fixed this issue. Weird.


Get Views field value in Twig template I'm trying to get the value of a field and use it as a class for a wrapper of another field within a Views display. So essentially what I need is to be able to get a string representation of the first field. The field already is a text field but when I try getting the content it doesn't just give me a string, which is what I need to be able to use is as a class for my second field.

I've tried using {{ fields.[field_name].content }} but that renders the twig template recommendation along with the data. I tried using the getValue() function, but that doesn't return anything. I tried passing the data through the raw twig filter but that doesn't return anything. I tried rendering the array using dpm and kint but they both give me way too much information and I can't narrow it down to what array item or object I need to use. I'm new to Drupal so maybe I'm not using Devel and Kint correctly to find what I'm looking for.

Is there a function I have to use to get the content data as a string or just raw, or is there some other way I can accomplish this?

I am using Drupal 8.1.

field.content is the rendered field. And in views that means it is no longer a render array, but the finally rendered markup. So this is very problematic to use it as a class name, not only because of twig debug.

Better use the row data, where you find the entity object with the field data from the database. Use clean_class to escape it for using it as a class name:

{{ row._entity.field_myfield.value|clean_class }}


How do I prevent a product from being added to the cart? A common question I hear is "How can I prevent a product from being added to the cart?" There are several reasons why you'd want to do this, most end up being related to some logic being required to determine if a product is eligible without actually deactivating the Add to Cart button.

While you probably ought to actually disable the Add to Cart button, you'd actually put logic for determining whether or not a product should be added to the cart in a validate handler.

The first step us to add a form_alter hook that adds a validation handler to the add to cart forms.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  // Add a validate hook so that the order can be checked to ensure that the
  // our constraints are met.
  array_unshift($form['#validate'], 'MYMODULE_validate_some_stuff');
}

Note: this works because of commerce_cart_forms() which adds the generic form callback instead of requiring us to look for the string in the $form_id.

Now, you just need to implement your logic:

/*
 * Check the product/order against my constraints.
 */
function MYMODULE_validate_some_stuff(&$form, &$form_state) {
  $order = commerce_cart_order_load($form_state['values']['uid']);
  $line_item = $form_state['line_item'];

  if (/* your logic here */) {
    form_set_error('product_id', t('Sorry, you can\'t do that!'));
  }
}

You'll notice that the commerce_order is loaded by the user's UID and you've got access to the commerce_line_item that you can then use to grab the product (use $line_item->commerce_product). Also, there is no need to return TRUE or FALSE. Just set an error.


Setting automatically created taxonomy terms using rules module I am using the rules module to automatically create a taxonomy term when i create content of a certain type.  I would also like to automatically populate the taxonomy term reference in the the created content. I have tried many different configurations using the set data function in rules however it does not ever set the taxonomy term to the the new-term which is created.

Is there any way that this operation can be carried out using rules.

I have exported the rule for you to take a look at.

/**
 * @file
 * advertising_region_creator.rules_defaults.inc
 */

/**
 * Implements hook_default_rules_configuration().
 */
function advertising_region_creator_default_rules_configuration() {
  $items = array();
  $items['rules_auto_taxonomy'] = entity_import('rules_config', '{ "rules_auto_taxonomy" : {
      "LABEL" : "Auto Taxonomy",
      "PLUGIN" : "reaction rule",
      "REQUIRES" : [ "rules" ],
      "ON" : [ "node_insert" ],
      "IF" : [
        { "node_is_of_type" : {
            "node" : [ "node" ],
            "type" : { "value" : { "savings_viewer" : "savings_viewer" } }
          }
        }
      ],
      "DO" : [
        { "entity_create" : {
            "USING" : {
              "type" : "taxonomy_term",
              "param_name" : "[node:title]",
              "param_vocabulary" : "2"
            },
            "PROVIDE" : { "entity_created" : { "new_term" : "New Term" } }
          }
        },
        { "data_set" : {
            "data" : [ "node:field-savings-viewer-region" ],
            "value" : [ "new-term" ]
          }
        }
      ]
    }
  }');
  return $items;
}

I apologize if this is posted in the wrong format I am new to all of this but will keep trying to get better.

Simply add a autocomplete taxonomy field to the content type and when node saves, rule to set data into this field. Taxonomy module will then create the new term if it does not exist.


Views: how to display different buttons before/after associated date? I've got a node that has a deadline date field.  I am configuring a view that shows a list of all the nodes.

If we are past the deadline for a given node, I want to show "closed" text.  If not, I want to show a link that says "Apply".

I suspect that I may have to use views_php but I'm not sure exactly how to do this, and I also want to make sure there isn't another way to do it without the performance hit of views_php.

There are three ways to do this kind of conditional logic:

Use the views_php module
Make a views field template
Write a views widget (or formatter, or something - what is the correct terminology?)

I ended up taking a bit of a shortcut and going ahead with views_php for now.  I'm never going to be dealing with more than a few hundred rows, so I'm not to shaken up over the poor performance of views_php.

This module is pretty easy to use.  Add a "Global: PHP" field.  I found dpm( $data ) and other variations to be very useful.


How to not display redundant information in table Views? In a custom module of mine (Drupal 8.2.6), I have two custom entities A and B with a one to many relationship from A to B.
I use Views (table view) to display content of A and B and by default I get this:
Field1 (from A) Field2 (from B)
xxx aaa
yyy bbb
yyy ccc
zzz ddd
I'd like to NOT display yyy the second time.
How can I do that?

[Edit] just an example, instead of what is (by default) on the left, I'd like what is on the right of the picture:

You can try Views Field View module.

Create a "secondary" view of Field2 contextualy filtered by
relationship with EntityA.
In your main view, use Field1 and new Views Field of your "secondary" view (this field type is added by module).
Set up that new Views Field in your view to pass proper argument to "secondary" view contextual filter (and therefore show relevant Field2s related to EntityA)


nodes in views and views in search results I'm building a website, where I don't want to display nodes directly.
All nodes are presented using Views. The idea is that i've got 10 basic pages without content. On each of these page I've got one or more Views as blocks. In these Views i show my nodes.

THE PROBLEM:
When I use drupal search I get results with direct links to nodes. Instead I would like get links to pages where the View is located, containing that node. I can easily achieve that by changing alias to page with that View. For example: I've changed alias content/function-one to /functions (page with View which presents functions) and it works, but there are another problems there.

First, I can still access nodes directly by url /node/%nid.
Second, I can have links only to pages with Views, but I still want to navigate to the nodes. I thought I can achieve it using anchors. I modified my alias to /functions#functionOne. But my href looks like /functions%23;functionOne and the anchor doesn't work.

So my goal is to disable access to nodes by /node/%nid and make my search results to give me link to the page that contains View with that node and navigate user to that node.

Any ideas how I can achieve that? Alternative approaches?

Thanks in advance

Take a look at Rabbit Hole ( https://www.drupal.org/project/rabbit_hole ) , it has several options as to what has to happen when a Node is viewed ( or trying to get viewed ) directly.


How can I list the users who are associated with a given Profile2 profile using Views? I have a site that has an Organization content type. Each organization has an associated Profile2 profile that contains a reference to a Taxonomy vocabulary depicting the hierarchy of the organization. When users register, they are presented with the given Profile2 profile associated with the organization they belong to.

I am creating a report in Views that needs to display the following:

Organization

Hierarchy

User

I can establish a relationship between the organization and the Profile2 profile, and the profile and the taxonomy. However, I cannot find a way to establish a relationship between a given Profile2 profile and the users who are associated with that profile. Does anyone know if I should be able to establish this relationship, or is it going to require some custom Views code?

Or, if anyone has a better suggestion on how to create this hierarchy, I'm open to suggestions.

Thanks!

As I understand it,  several 'profile types' with different fields and questions relevant to various 'organizations' in your company.

Here's a suggestion to create a view which shows a list of the details in all profiles grouped by 'organization field' and sorted by the various 'hierarchy fields'.

The key to making this work is that the different profile types have a couple of fields in common eg. organization, first name, surname etc.  Assuming each profile type uses the same 'field_organization', 'field_first_name', 'field_surname' we can use table view and grouping.  If we need to display profiles with different fields, then add the fields and select another view type such as list view instead.

You may be able to do this even if only field_organization is in common in all the profiles (with list format instead of table format.  Even if the profiles have other fields which don't match, they can be combined into the same report using 'list view' instead of table view.

Create a new view.
Either: Show 'Profiles' of type  'profile type for particular organization'
Or:     Show 'Profiles' of type  'All'
Create as a block and/or page as required.
This will show a list of profile ids.
(optional) In view editor, add a relationship "Profile: User uid"
This will give you access to the person's username and email.
Add fields as required eg. mail from user, username from user,
Add fields fields "Organization"
Add each of the "Hierarchy" fields
(optional) add field "Profile: type"

If the fields are shared and appear in more than one profile type,  you should see "Appears in: profile2:org_1, profile2:org_2, profile:org_head_office etc. as you select the field to be added.

To group by organization as you outlined, avoid 'grouping and aggregation', and instead select 'Format: HTML list". In the  'format settings' use the 'Grouping field Nr.1 ' to 'Organization'.

Caveat
- if someone has more than one profile, they will appear more than once in this list.

If there is just one 'hierarchy' taxonomy  reused in all the profiles, then you might be able to add this as 'Grouping field Nr. 2' instead of relying on sorting.

With luck you should end up with a list such as:

Organisation Unit 1:

Firstname
Surname
Heirachy position1
Firstname
Surname
Heirachy position2
Firstname
Surname
Heirachy position3

Organisation Unit 2

Firstname
Surname
Heirachy position1
Firstname
Surname
Heirachy position2


View files from multiple (filtered) nodes I have content type Band and content type Performance. Performance has a reference field to the Band. Both content types have a media field where you can attach photos and videos. What I am trying to do is have the files from a specific Band and its Performances show up in a section (view) in the Band page. And I also want to sort them based on the Date each of the files has in its field.

All my efforts so far have been in vain. Tried to make this work with a content type view and with a file view. I feel like I will have to work with reference filters but again I can't seem to figure out how these work. I have been searching for far too long.

Any tips?

Update

Here are two screenshots of two attempts that managed to manually bring the results I am looking for, but don't really feel right.

Attempt #1

Attempt #1 tries to filter the performances and bands by taking the band name into a filter (performances have the auto label feature that adds the band name in their title). However if I have a band called "lost" and another one called "lost in space" I think I can't filter them correctly.

Attempt #2

Attempt #2 uses two reference filters (this is the first time I tried to do anything with reference filters so I guess I am using them wrong in the first place). The first reference filter brings the band node and the second brings the same band's performance nodes. If I put the node id in the preview filter below I get the correct results. However in this case that view does not accept a node id as a contextual filter because it's a file view. If I try to put a contextual filter it automatically binds to the relationship underneath it and then the reference filters don't work.

It won't let me post the reference filter views, but they are pretty basic. One takes the band id as input and renders the... band id (monkey patching at its best). The other takes the band id as input and returns the band's performances ids as a reference filter list.

Here is a different approach, give this a try:

Ok, get rid off all the FILTER CRITERIA except for File: type = image
Under Advanced, add RELATIONSHIP of [Your Entity Reference Field
Name] make sure you select the one that says, "Referecing" and NOT "Referenced".
For your FIELDS File: name and Content: title, click on them and for
relationship select your Content Referencing Content from [Your Entity  Reference Field Name]

Under Advanced, add a CONTEXTUAL FILTER of nid.

Select provide default value
Content ID from url (This will automatically pick up the nid (node id) from the Band node/page.

Lastly, would be to add SORT CRITERIA and add the date field.


Is CiviCRM data vulnerable to the Drupageddon bug? Would CiviCRM data have been exposed to a Drupageddon exploit if it happened before I updated the site to Drupal 7.32?

CiviCRM is in a separate MySQL database. However, the site uses Views/CiviCRM integration so all the tables in the CiviCRM database are listed in Drupal’s settings.php file.

Since a potential attacker got access to the database, and through the evil php module, could execute code, everything on the same server must be considered compromised.


Authentication cookie in a load balanced environment Hopefully this is a basic question.  I'm going to be setting up a drupal website there there will be multiple servers in back of a load balancer.  The user will hit one web server where they will authenticate and the cookie will be added to the browser's session.  On subsequent requests if the user is sent to another server, will that server recognize the user as authenticated since the authentication cookie is present, or is the cookie somehow tied to the server that authenticated the user?

Yes, if you've configured your servers correctly.

Authentication state is stored in the DB. As long as each Drupal node (app server) in your load balancer pool is configured to talk to the same database, it shouldn't matter what server the browser is talking to. Login data will persist in the database and each Drupal node should be able to find it via the user's cookie data.

The challenge is making sure all the infrastructure correctly. Those details are off topic here, but you might find Using a load balancer or reverse proxy on drupal.org helpful for other Drupal-specific stuff to know when dealing with Drupal behind a proxy (load balancer).


Is it currently possible to have Views respect RSS Display settings on a Content Type? I have enabled and configured a 'Custom Display Setting' under 'Manage Display' of a content type for RSS

 admin/structure/types/manage/{my-type}/display/rss

I can't seem to find a way for Views to respect this new Display Setting.  The only available options for "Feed: Row style options" under a Feed View are:

Full text
Title plus teaser
Title only
Use Default RSS settings

None of which follow the Display options I specified for in the Content Type for RSS

Is there not currently a way to do this in D7? Does it require another module?

Thanks in advance.

There is a current bug in views that does not respect any changes you make to the default RSS display settings. See Issue #1301788: RSS Feed - Title plus teaser --- still grabs default node view?. There is a patch but it hasn't been rolled into a release yet.


Re-render current form in submit-hook under certain conditions I have a form:

function _scratch_tests_for_users() {
  $current_user_number = current_user_number_from_session();
  $form = drupal_get_form("_scratch_forms_test_for_user", $current_user_number);
  return drupal_render($form);
}

With the form callback:

function _scratch_forms_test_for_user($form, &$form_values, $current_user_number) {
  $form["user"] = array(
    "#type" => "value",
    "#value" => $current_user_number,
  );
  $form["submit"] = array(
    "#type" => "markup",
    "#markup" => "Play number {$current_user_number}",
  );
  return $form;
}

And a submit callback:

function _scratch_forms_test_for_user_submit($form, &$form_values) {
  if ($form_values["values"]["user"]) > 3) {
    _store_some_stuff();
    return "ready";
  }
  else {
    //...re-render the form.
  }
}

In above example code, I would want to render that form three times, the fourth time, values should be stored.

Note that my actual code is a lot more complex and has more complex criteria then simply "the first three times"; just to avoid answers like "just copy-paste the form three times" :).

drupal_rebuild_form() constructs a new $form from the information in $form_state.

I think you can also set $form_state['rebuild'] = TRUE; in a validation or submit hook as well to trigger the form rebuild.


How can I configure the backend to get a comfortable image insert functionality with captions? Since Drupal offers many different approaches to inserting images, I am a bit lost. I am looking for a configuration that allows editors to comfortably insert images with captions. My requirements are:

Works with WYSIWYG editors
One input form to upload the image and enter the caption
At most one more step in the workflow to position the image in the text
Ability to create blocks with several images side-by-side
Ideally, no code changes (inserting JavaScript or altering PHP) should be necessary in order to retain upgrade capabilities

It seems that many people are using a combination of the wysiwyg module with IMCE and the IMCE wysiwyg bridge. However, I don't see any support for image captions in that toolchain.

The other alternative is the Insert Image With Text module, which is still in beta and rarely discussed anywhere. As far as I understand, this method is not really practical because it limits users to one image per node (or would require several image fields in the respective content type).

Is there any combination of modules and content settings that can fulfil those requirements?

Have you tried the Media module? From the project page:

Add media (images and video) into any textarea (requires Wysiwyg module).
Use the fields API (formerly CCK) to add fields to any type of media, eg. captions on images.
Plugins to use remote media from sites like YouTube, Flickr, ...
A unified interface for adding any type of media as a field to nodes.
Mass importing of files.
Drag and drop upload (with Plupload module).
Responsive image support (with Picture module).


Show total search result count I'm trying to display the number of total search results on my search results page, using the core search module. I've tried manipulating item-list.html.twig and item-list--search-results.html.twig by displaying items|count but when there are more than ten results, items|count only captures the number of results on that page.

I'm considering installing Search API and working with views, but that seems like overkill for this one little modification.

The search queries of Drupal 8 use the global pager. The total results count is available within its global $pager_total_items variable.

So the easiest way of showing the amount of total items is using this variable within a hook_preprocess_HOOK() of your template in your *.theme file.

For example, if you'd like to use the total results count within the item-list--search-results.html.twig, HOOK needs to be replaced by its theme hook item_list__search_results:

/**
 * Implements hook_preprocess_HOOK() for item_list__search_results.
 */
function mytheme_preprocess_item_list__search_results(array &$variables) {
  // The $pager_total_items variable is a global
  // array keyed by the pager element increments.
  global $pager_total_items;

  // Assuming you have one paged list on your page only,
  // the element's key should be 0.
  $variables['total_items_count'] = isset($pager_total_items[0]) ? $pager_total_items[0] : 0;
}

Then you can access this variable like {{ total_items_count }} within the template.


Where does Drupal store its url/domain name? I created a site using an IP address and imported a live site on another server, then I made the domain name live on the new server created with the IP address.  Since then I get permissions error for the admin when logged into the domain name/ url.  However if the same admin logs in using the IP address, I can see the broken links report. Otherwise it says I don't have permissions.    I'm trying to reset the root domain url but uncommenting it in the settings file doesn't fix the permissions issue. I think it is something deep in the DB

Check https://www.drupal.org/node/776864 under Troubleshooting - No user login. It might help.

Basicly, it says Enable clean URLs, check Apache config, check .htaccess, you probably want to uncomment rewritebase. Also check that "$cookie_domain" is not set to your old domain.


Search a product - Search API Module I'm creating a e-commerce website, with a type of content "Products". I'm using Search API to be able to have Facets filters on my views. I linked the type of content "Products" to the search API. So i have different facets filers available. Everything is working perfectly.

Now I would to be able to search a product. On my search results page i can have my facets filters.

So I tried 2 options :

1) I found this tutorial and I tried but it didn't work

2) I tried the Search API Pages module
and I have the same problem, nothing is working. When I search something, it found nothing. I tried to find out some tutorials to see if I miss something.

I tried to find out some tutorials about how to use Search API Pages module, but I found nothing useful.

I found this previous post which is similar as my problem :

But that doesn't help me either

Does anyone have an idea ?

Edit : I'm not using Apache Solr on my server

I solved my problem.

Well i don't if what i did was the issue but it's working so ^^

I went in the parameters of the Search API Module. I went on the tab "Filters", in the "Precesseurs" part i just activated this 2 things : HTML filter Tokenizer I re-indexed everything and by magic it's working.


Collapsible Search Bar I have an exposed form (from a view) in a block. I'd like to make this block collapsible so that a user is presented with a search box and one other field and when a user types in the search box the form expands out to include the remainder of the form fields. I know I can use ctools_collapsible to make content collapsible but how do I extend this to any div/region?

If I understood you correctly:
You have exposed filter in block, which have for example two fields, search by title and checkboxes.

So you can use: https://www.drupal.org/project/better_exposed_filters

After installing module: change Exposed form style from Basic to Better Exposed Filters
Click to BEF Settings
Check Enable secondary exposed form options
Expand yours fields what you need to hide before type in search box and check this: This is a secondary option
Use jQuery:

$("input.yourSearchBox").keyup(function(){

    $(".views-widget-filter-secondary a").trigger('click');

});


simple news confirmation message i am using simplenews module in drupal7 . i mentioned simplenews block on home page.
 when i enter email id it shows message "You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription." on home page . now i need to show this message on  new page(not on home page).
also i want to change the text of that message

Any idea ?

Thanks in advance

You could try setting the subscription confirmation pages at: /admin/config/services/simplenews/settings/subscription > "Confirmation pages"

  SUBSCRIBE CONFIRMATION

  Drupal path or URL of the destination page where after the
  subscription is confirmed (e.g. node/123). Leave empty to go to the
  front page.

It may be that that page is only used when confirming from the email link, but might work for the subscribe block as well.

The message text could be overridden with the stringoverrides module


Redisplay Captcha on form error in Ajax form submit I have a Fancybox form and the form is sent via Ajax. I know that there is the error about "reuse attack" for Captcha, but this is not my case.

When I wrong the form (some required fields missing) I see the fieldset of Captcha, but no Captcha inside. It's empty.

How can I fix this ?

If user can submit the form when there is no captcha after errors, it's by design. In captcha settings you checked an option to only verify humanity of an user once. User gets validated as a human on first, failed submit, and is not bothered any more on that form. Go to captcha settings and make him validate each and every time and it will not disappear, but your users will not love you.


Automatically open linked pdf (bypassing download box) I've created a Content type that allows me to upload files (specifically pdf's).

After uploading a pdf file and then linking to it in a static document, clicking the link gives me a download page.

I want the link to open the pdf directly. I tried the recommendation at http://www.drupalgardens.com/content/file-content-type
but get a similar page, without the link.

Assistance in fixing this would be greatly appreciated!

Try it for yourself

There are three bulleted links on the page:
 http://roguepublishing.ca/content/Communicating_Science

The regular 'Table of contents' leads to a page with one URL on it. That is the same URL as the hard-coded 'Table of contents'. As you can see, using these links opens the pdf's.

The 'Resource' Content type has
 * Enable Display field is checked
 * Files displayed by default is checked
 * The Manage Display is set to "URL to file"
If I change Manage Display to "Table of files", I get a table with a link to the file. Clicking that link launches the pdf.

Simply: how do I get Drupal to launch the pdf from the alias on the first page?

You are just linking to files, and the default action for the browser to take is to ask to download the file.
Files will sometimes automatically open if the browser is set up to do so.
If you want to make sure the pdf is always displayed, you will have to look into pdf viewer modules. Here is a site that compares a few.
https://drupal.org/node/1781960


How to implement per user caching when restricting display of comments by author I have threaded comments on a site where there are two roles, reviewers and administrators.

Comments are shown in a view block added to the node (in this case a webform). The view format is set to 'content' and it's using tag based caching.

Admins are allowed to see all comments
Reviewers can write comments and only seen their own, or replies to them

This is all ok and I've implemented it with hook_ENTITY_TYPE_view_alter (simplified example below).

The problem is caching - the view for one reviewer is being cached and shown when the other logs on.

Scenario:

Alice and Bob are reviewers
Alice leaves a comment on a node. Logs out.
Bob logs on. If the cache hasn't been cleared in the meantime, he'll see Alice's comments even though he shouldn't. (And then, were I then to clear the cache, his view would be correct, but should he logged off and Alice logs back in, she'll now see the view intended for Bob.)

Can I give each user their own cache,  or failing that, not cache the view at all? (setting caching of the view block to 'none' doesn't appear to change anything, would be useful to know why in answer.)

function mymodule_comment_view_alter(
    &$build,
    Drupal\Core\Entity\EntityInterface $entity,
    \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display ) {

    // ... some logic that deals with admins (omitted)

    $comment_uid    = $entity->getOwnerId();
    $parent_comment = $entity->getParentComment();

    if ( $comment_uid === $current_user->id() ) {
        // current user's own comment? Show it
    } elseif ( isset( $parent_comment ) &&
               $parent_comment->getOwnerId() == $current_user->id() ) {
        // a comment in  reply to current user's comment? Show it
    } else {
        // otherwise, don't show it
        $build['#access'] = false;
    }

    return;
}

As Clive said in the comments, all I needed was the following.
I won't mind if people down vote the question for being too stupid…

// was user.permissions, but that means there will only be a single
// cache shared by all reviewers, and we must cache according to authorship
$build['#cache']['contexts'] = ['user'];

Caveat: the view block cache setting also needs to be 'none'.

Drupal docs - cacheability of render arrays


User directories for blog images I am setting up a multi-blog site in Drupal. I'm currently learning Drupal and I'm a beginner. I am setting up Organic groups, to make blogs for groups. I have added CKEditor to get RTE in the text fields for the blog entries. I have also added IMCE to be able to upload images in the RTE.

Now my question is. How can I give each user an individual folder for uploading files? I don't want the users to access the full upload root.

Seems like I had to assign a profile to my user role. Configuration>Media>IMCE. Create a profile with access to browse, upload, thumbnails, delete and resize for \users\user%uid. Atleast that worked for me.


Cannot change checkboxes options in drupal form using AJAX callback I am trying to apply the #options value of a checkboxes in a form inside a Ajax callback.

Even after using $form['tags']['table']['#options'] = $final; the value in the form is not changing.

I have tried printing the #options value in the watchdog and the value seems to have changed.
But it is not getting reflecting on the form page.

The form field which needs to be updated

$form['tags']['ask_button'] = array(
      '#type' => 'button',
      '#value' => t('Next'),
      '#ajax' => array(
        'callback' => 'ajax_tag_callback',
        'wrapper' => 'replace_tagfield_div',
      ),
    );
$form['tags']['question_tags'] = array(
      '#title' => t("Tags"),
      '#type' => 'textfield',
      '#prefix' => '
',
    );
$form['tags']['table'] = array(
      '#type' => 'checkboxes',
      '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
      '#suffix' => '
',
    );

The Ajax callback

function ajax_tag_callback($form, &$form_state) {
\\some code\\
  $final = drupal_map_assoc(array(t('SAT'), t('ACT')));
  $form['tags']['table']['#options'] = $final;
  $form['tags']['question_tags']['#value'] = $tag_names;
\\returned the form here
 return $form['tags'];
}

Even after returning the form field, my form is not getting updated. Please suggest me a solution..

* Update using new code *

Form definition:

$form['tags']['ask_button'] = array(
  '#type' => 'button',
  '#value' => t('Next'),
  '#ajax' => array(
    'callback' => 'ajax_tag_callback',
    'wrapper' => 'replace_tagfield_div',
  ),
);
$form['tags']['values'] = array
(
  '#prefix' => '
',
  '#suffix' => '
',
);
if(isset($form_state['values']))
{
  $final = drupal_map_assoc(array(t('SAT'), t('ACT')));
  $form['tags']['values']['question_tags'] = array(
    '#title' => t("Tags"),
    '#type' => 'textfield',
    '#value' => $tag_names, // Note - you didn't show how this is created
  );
  $form['tags']['values']['table'] = array(
    '#type' => 'checkboxes',
    '#options' => $final,
  );
}
else
{
  $form['tags']['values']['question_tags'] = array(
    '#title' => t("Tags"),
    '#type' => 'textfield',
  );
  $form['tags']['values']['table'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
  );
}

And your ajax callback will look like this:

function ajax_tag_callback($form, &$form_state) {
  return $form['tags']['values'];
}

* Original response *

Not enough information provided to say for sure what your problem is, but it's likely one of these:

Problem 1:

You are making changes to the form in the ajax callback. You cannot do this. Here is how the form API works.

1) Form is generated

2) Form is cached on server

3) Form is sent to user

4) User initiates some ajax

5) Values are sent to server

6) Form is rebuilt, with submitted values

7) New form is cached on server

8) Form is sent to ajax callback

9) Relevant values are returned from ajax callback

10) Drupal sends data to browser, and the new parts of the form are injected into the page

11) User submits form

12) Drupal checks submitted values to the cached form, to see if the received values match the cached form, giving an error if they don't. This is the major strength of the Form API.

Step 7 and 8 are the key points here - the form has already been cached before it is sent to the ajax callback. So any changes you make won't be part of the cache causing errors.

Problem 2

You don't have a #prefix set on $form['tags']. You have only set the suffix. You need to provide a wrapper with your #ajax definition (which you didn't show us), so maybe the wrapper you have provided does not exist.


POST: 403 error in REST I created a custom entity, next I enabled (via RESTui) the GET and POST methods. I gave anonymous users permissions to "Access GET", "Access POST" and "Create new content" of that entity.

When I navigate in my browser to "http://mywebsite/my_entity/1?_format=json", I get a proper JSON response. When I navigate to "http://mywebsite/my_entity/add", I can add a new entity.

When I try to POST a new entity via "http://mywebsite/my_entity?_format=json", I get a 403 repsonse with following body:

  {   "message": "" }

Does someone have an idea what I'm missing here?

EDIT: When i put a die('give me something') in the method post() of the class "EntityResource" (which is the base class for all entities), the message isn't displayed...

EDIT2: I added headers "Content-Type" and "X-CSRF-Token"

Do you provide a (Basic) authorization header, as well as a X-CSRF-Token header in your POST?

See also:
https://www.drupal.org/documentation/modules/rest/start - "2.2 Unsafe methods & CSRF protection: X-CSRF-Token request header"

Edit:
So you should at least specify the following HTTP headers:

Content-type: application/json
X-CSRF-Token: [TOKEN RETURNED FROM A REQUEST TO /rest/session/token]


Change page title of a module generated page I'm using the Tagclouds module to generate a list of items grouped by taxonomy. The URL looks like this:

http://example.com/tagclouds/list/2

This works fine. However the automatic generated title of this page is 'Labels'. Any ideas how I can substitute 'Labels' by something else?

The module is using its own menu definition. The title of the menu item is used for displaying the page title of the page in question (which is 'Tags' in English and 'Labels' in your Dutch version):

/**
 * Implements hook_menu().
 */
function tagclouds_menu() {
  $items = array();

  // [...]

  $items['tagclouds/list/%tagclouds_vocs'] = array(
    'title' => 'Tags',
    'page callback' => 'tagclouds_page_list',
    'page arguments' => array(2),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  // [...]

  return $items;
}

As you are using a localized version of Drupal, you have several options to change the page title.

The first and most easy solution is to change the translation of 'Tags' to your desired string. You can use the localization interface which is located at /admin/config/regional/translate/translate.

However, the above solution will change the translation for 'Tags' within your whole site. Which means that the new translation might appear somewhere else as well, and on an English page the title would still be 'Tags'.

The second solution is changing the menu item's title. You can do so without side-effects as the menu item of question is a menu callback. Its title will not be shown within your menu structure, but as page title only. As you should never touch the sources of a contributed module (for your customizations), writing a small custom module is the way to go here.

Follow this guide to get started with custom modules and create the required files. Within your custom module's MYMODULE.module file you can implement hook_menu_alter(), which allows you to change the menu items of other modules. In this case, we'll change the menu item of the tagclouds tag overview page:

/**
 * Implements hook_menu_alter()
 */
function MYMODULE_menu_alter(&$items) {
  // Whether the tagclouds menu item is defined.
  if (isset($items['tagclouds/list/%tagclouds_vocs'])) {
    // Change the menu item's title.
    $items['tagclouds/list/%tagclouds_vocs']['title'] = 'Your New English Title';
  }

  // For translation extractors, you may also implement
  // this little function call.
  t('Your New English Title');
}

Change MYMODULE to your module's name, activate the module and/or clear your Drupal caches. You might have to visit the page once, so that the translatable string will be known to Drupal's localization system. Afterwards you can head to the translation interface as described within the first solution and add a translation for 'Your New English Title'.

The third solution is to hook into the page pre-processing within your theme. Locate your theme's template.php file. If your theme is implementing the theme hook THEME_preprocess_page() already (which is very likely), you may just add the lines from the following function's body. If your theme does not implement this hook, you may add the whole function, renaming THEME to your theme's name. This little code checks, whether you are at the tagclouds listing page and - if so - changes the page title using drupal_set_title():

/**
 * Implements THEME_preprocess_page()
 */
function THEME_preprocess_page(&$variables) {
  // Load the current path into a variable.
  $current_path = current_path();
  // Whether the current path is the tagclouds listing path.
  if (strpos($current_path, 'tagclouds/list/') === 0) {
    // Set the page title. We use drupal_set_title here, as
    // the static page title will be evaluated within the
    // process_page function, which follows the pre-processing.
    drupal_set_title(t('Your New English Title'));
  }
}

Once again, following Drupal standards you set the English title here, so after you cleared the Drupal caches and visited the page once, you should follow the steps of the first solution to add an appropriate Dutch translation to your localization.

The last solution is suggesting the module maintainer to allow editing the page labels within the module settings. This change however might take a little longer as most module maintainers are contributing to the modules within their spare time.


Why are JavaScript files read from an external URL? Drupal adds the following markup to pages.

<html class="js" xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:sioct="http://rdfs.org/sioc/types#" xmlns:sioc="http://rdfs.org/sioc/ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:og="http://ogp.me/ns#" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:dc="http://purl.org/dc/terms/" xmlns:content="http://purl.org/rss/1.0/modules/content/" dir="rtl" version="XHTML+RDFa 1.0" xml:lang="fa" xmlns="http://www.w3.org/1999/xhtml">

I need to remove it and force my site not to read from an external URL.

How can I achieve this? Is it really bad, or doesn't it need to be changed?

You're confusing the attributes on that tag.

class="js" is a class name, it has nothing to do with loading javascript from external sources. It's simply added to the tag by javascript when the page loads so that any process (css usually) that needs to know about it can easily tell whether javascript is enabled or not.
The xml:* attributes are required to identify the document as XHTML. They're not related to javascript in any way.

There's no need to change anything, unless you want to get a bit more up-to-date and install a theme that produces an HTML5 document.


Remove '-Any-' value from exposed filter term field I have a view with an exposed filter field. This field always shows the -Any- value. The data shown is dynamic so I cannot select the values to show. I have to remove that option in some way.

I've looked at this answer but this is for a form and I'm trying to do this for a views page of type chart. Anyway, I can't even dpm the form name as is said in the example.

My view name is x_report_plus_feature_dashboard and the display is page1.

How can I do this? Thanks!

EDIT:

I was able to remove the '-Any-' value with the following code:

function HOOK_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    unset ($form['field_MYFIELD_tid_selective']["#options"]['All']);
  }
}

But now I have a problem. When I go to the view, the data shown is still the same that was shown when -Any- was selected. For me it's ok to show the data for the first entry as default but how to do it?

Setting the exposed filter to required will remove the -Any- option.


Using one view for multiple Content Types So I have four content types in each there is a field called offer, I intend to make a view to display all nodes of those four content types with offer value equal yes.

I have tried the following: I have made a view of the four content type and add the four fields as filters and make a new filter group but I can not separate content types so that I can group each content type with its field.

Is my approach right? What do I need to do?

Thanks in advance!

If you are using the same field for all content types and want to display them all on the same view and grouped by content type. Here is the step by step.

Create a view for all content type in Unformatted list or table.
In Filter Criteria: Add the "Content: Type" and check the content types you wish to display
In Filter Criteria: Add the "Offer" is equal to "Yes"
In Fields: Add any field you wish to display, and add "Content: Type" set that exclude from display
In Format Settings: Set "Grouping field" by "Content: Type"

This way, The view will list all those node content type with Offer equal to yes, and grouped by content type.


Contextual filter by author id Ok, so here's my problem. I feel it's really very simple and I am missing something. I have a Drupal 7 view which shows a certain type of content. Say it has a url mysite.com/article. What I want is, if the url is like mysite.com/article/me, it would load the articles posted by this current user. "me" will always be "me" and would not take any id/username.

Hope the problem is clear. Thanks

I think you are missing one of the buried options.

Make a view, configure it the way you need.
Make a Page display, and set the path to article/me
Add a Relationship for Content: Author.  This is likely not needed, unless you want to pull in author fields and display them or if you need the author name explicitly somewhere in another filter.
Add a Contextual Filter for Content: Author uid; it should automatically pick up the relationship.  In the options for When the filter value is not available, select Provide default value.  In the dropdown, choose User ID from logged in user.

I think you are missing the last part of the final step.  I always forget where that one is.  It helps if you configure views to always show the advanced settings (see admin/structure/views/settings).


Attached view ajax call (lazy load) with exposed filters I'm using views with a main view and an attachment to put 2 views on a single page. Each view is in it's own Bootstrap togglable tab. Because I don't know how many people will actually switch to the non-default tab, I'd like to wait to load that view until it's needed, then load it via ajax.

Is there any way to do this within the Views UI, or is it time for custom coding? This post is kind of old, but is that the best method for executing an ajax call to render a view?

Edit: A complicating factor is that I need to include exposed filters, which also need to fetch the data via Ajax. Right now, the filters work with the second tab, but not the first. I believe this is because Quicktabs creates multiple sections with .view-dom-id-<settings.view_dom_id>, which is the selector used in Views js/ajax_view.js.

Any solutions that work with exposed filters and Ajax?

U can use quicktab module for the same. Create Tab with it, and select your view which u want to use. After that there is an option to check how to load content of the tab, u can either choose to load at once, or on click of tab using ajax.


Twig template for custom entity not working I created a custom entity called 'Representative' using the drupal console 'generate:entity:content' command.

The entity works correctly I added a bundle of fields to it, added some content, and can query this entity using the EntityTypeManager query.

My problem is - I can't render this entity in twig.
When I pass this entity to the render array:

    $build = [
  '#theme' => 'representatives',
  '#representative_entity' => $representative
];

I get the following error:

Exception: Object of type

  Drupal\kelk_representatives\Entity\RepresentativeEntity cannot be
  printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line
  476 of core/lib/Drupal/Core/Template/TwigExtension.php).

(I was using drupal console to automatically generate the twig files and preprocess functions)..

Can anyone help?

You must render the correct view mode of the entity, like this:

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('ENTITY_TYPE');
$entity_view = $view_builder->view($representative);

$build = [
  '#theme' => 'representatives',
  '#representative_entity' => $entity_view,
];


Customize the output of the Drupal 8 Aggregator module I am using the Core Aggregator module to aggregate content from RSS feeds, and then using a View to output the content.

The Aggregator module has two view modes, default and summary. The view modes themselves are editable, but the feed items themselves are grouped into the "items" field, that has no options.

In default mode, the title, blog, description etc. for each item are rendered, but in summary mode only the title and blog name are rendered.

How can I influence the fields that are rendered in summary view mode?

I believe what you are looking for is the 'Manage Display Option" viewable from

admin/config/services/aggregator/display

In other words from the aggregator admin ui.

Not sure how much control this gives you in reality. Also I am having issues with Aggregator appearing to strip out image tags from my feeds for some reason, so I am also considering using the feeds module instead that seems to have better support than the core module.

UPDATE

Ended up using the migrate module which enables custom mapping of fields from a field to a content type of your choosing with custom fields etc.


Using "IN" with db_query() First off, let me say that I've tried the Drupal 6 answer shown in Using IN clause in db_query and it doesn't work.
I have a query that previously only needed to include items from a single taxonomy id:
$images = db_query("SELECT n.nid, n.title, f.filepath,
cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND tn.tid = %d AND n.status = 1
ORDER BY n.created DESC LIMIT %d", $user->uid, 134, $displays_count);

The requirement has changed and we now need to pull images from multiple taxonomy ids. Based on the linked post above, I tried this:
$tax_ids = array(134, 139);
$placeholders = db_placeholders($tax_ids);
$images = db_query("SELECT n.nid, n.title, f.filepath,
cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND tn.tid IN ($placeholders) AND n.status = 1
ORDER BY n.created DESC LIMIT %d", $user->uid, $tax_ids, $displays_count);

I just get a blank screen there. When I turn on Devel and display the query log, what it shows as running is:
SELECT n.nid, n.title, f.filepath, cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = 1)
WHERE n.type = 'imagevault' AND tn.tid IN (1,5) AND n.status = 1
ORDER BY n.created DESC LIMIT 0

I have no idea where the 1,5 is coming from in the rendered query. What do I need to do to make this work? Does it only work for nid when selecting directly from a node? If so, how can I use an array in the query? Do I skip the placeholder for that param and just put it directly in the WHERE clause?
Updated info
So it appears that completely aside from the strange case of 134, 139 being translated to 1,5, I also have another issue. Although the variable $displays_count is set further up the page to 5, it's still translating in the query to 0. (I've echoed the value out right before the query, and it's still 5 there, so I don't know what's happening or why changing the tn.tid placeholder would have any effect on the limit placeholder.)
$tax_ids = array(134, 139);
$params = $user->uid;
$params[] = $tax_ids;
$params[] = $displays_count;

$images = db_query(db_rewrite_sql("SELECT n.nid, n.title, f.filepath,
cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND tn.tid IN (" . db_placeholders($tax_ids) .") AND n.status = 1
ORDER BY n.created DESC LIMIT %d"), $params);

The last three arguments you are passing to db_query() are wrong; you should merge them in an array, and pass that instead of them.

block_list() contains the following code:

$result = db_query(db_rewrite_sql("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.theme = '%s' AND b.status = 1 AND (r.rid IN (" . db_placeholders($rids) . ") OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), array_merge(array($theme_key), $rids));

Similarly, blogapi_mt_validate_terms() contains the following code:

  $term_list = array_unique($node->taxonomy);
  $params = $term_list;
  $params[] = $node->type;
  $result = db_query(db_rewrite_sql("SELECT t.tid, t.vid FROM {term_data} t INNER JOIN {vocabulary_node_types} n ON t.vid = n.vid WHERE t.tid IN (" . db_placeholders($term_list) . ") AND n.type = '%s'", 't', 'tid'), $params);

In your specific case, your code should be similar to the following one:

$tax_ids = array(134, 139);
$placeholders = db_placeholders($tax_ids);
$args = array_merge(array($user->uid), $tax_ids, array($displays_count));

/**
 * Alternatively the previous three lines could be replaced by the following ones:
 * $args = array(134, 139);
 * $placeholders = db_placeholders($args);
 * array_unshift($args, $user->uid);
 * $args[] = $displays_count;
 */

$images = db_query("SELECT n.nid, n.title, f.filepath,
  cti.field_iv_source_name_value AS source, bf.nid AS flagged
  FROM node n
  JOIN content_type_imagevault cti ON n.nid = cti.nid
  JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
  JOIN files f ON cfaf.field_att_file_fid = f.fid
  JOIN term_node tn ON tn.nid = n.nid
  LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
  WHERE n.type = 'imagevault' AND tn.tid IN ($placeholders) AND n.status = 1
  ORDER BY n.created DESC LIMIT %d", $args);


How to list all nodes with alphabetical headings? I want to list all nodes with alphabetical headings like this example http://www.animeseason.com/anime-list/
How can I do this?

You can achieve this using the Views module (http://drupal.org/project/views) which actually comes with a pre-built view called "Glossary". Enable that and tweak it to suit your needs.

Hope this helps.


Issues migrating site back to local server I have issues migrating my Drupal 7.14 site from Live Server back to local. This might be more sql related, but not sure at this point where the error comes from. Might be specifically Acquia related.

The site is now perfectly running on the live server. I made some new nodes etc and now I wish to work more on the structure. I was trying to migrate it back to my local Acquia server by doing the following:

creating local safety copy of the current local site (also to preserve the local settings.php file)
creating safety copy of local sql db
exporting live sql db, then dropping tables of local db and replacing them with the live one
replacing local site files with the ones downloaded from live
updating settings.php from the original local safety copy

What happens is:

when trying to access local address (mysite:8082) I get 'could not find' error message. this comes from google, so the local drupal site doesn't even get recognized in any way
i am still able to set up new Drupal installations via Acquia and they run perfectly
if I replace the sql db of a newly installed site with the one I got from the live site I get the same error
i can't seem to get the local site running even if I use the safety copy sql + safety copy of the local site
if I go to a definite url such as 'mysite:8082/index' I get the following: "The requested URL /index was not found on this server."

Where should I look next? What could be in the sql that makes the whole server unrecognisable?Any completely different ways to do this? Thanks!

As the OP noted in a comment, there is documentation available from Aquia that explains how to do this. For a better formatted answer please follow the above link.

  IMPORTING AN EXISTING SITE OR CODEBASE INTO ACQUIA DEV DESKTOP

  To run an existing site or new Drupal distribution on your local
  computer, complete the following steps:

  Ensure that your local computer contains a copy of your site's Drupal
  files and directories (codebase).

  Save your site's codebase in a place where you can find it and where
  you won't delete or move it unintentionally. This protects your site
  from accidental removal, and helps when you need to modify site
  content or change the installed modules.
  You cannot import zipped or compressed codebases into Dev Desktop.
  Ensure that your site's code is uncompressed.
  For more information about backing up the Drupal file system, see
  Drupal file system backup.

  Note: Dev Desktop does not move or copy your site's code into the Dev
  Desktop installation directory. Instead, Dev Desktop records where the
  Drupal directories are stored on your local computer.
  Open the Acquia Dev Desktop Control Panel, click Settings, and then
  select the Sites tab.
  Click Import. The Import site window opens.
  In the Codebase section, click Browse to select the source code
  directory (also known as [docroot]) of your Drupal installation. This
  directory contains Drupal's files and directories, including
  index.php, the /includes directory, and the /modules directory.
  After you select the your codebase, in the Subsite drop-down menu,
  select the site to import from the source code directory. For
  single-site codebases or Drupal distributions, select default. If
  you're importing a codebase that contains multiple subsites, select
  the subsite you want to import from the Subsites drop-down menu.

  Note: Dev Desktop can only import one site at a time.
  Configure the database settings for the site import process. The
  settings are based on the type of site or codebase you're importing
  into Dev Desktop.
  In the Database name field, enter a name for
  the database. If you're restoring a backed up database, the name does
  not have to match the backed up database's previous name.
  Under Domain, enter the elements (server, subdomain, and URL path) of
  the local URL you want to use for your site. For example, if you want
  to reach your site locally at http://my.example:8082/mysite, enter my
  for the Subdomain, example for the Server, and mysite for the URL
  path. The subdomain and URL path are optional.
  Click Import.

  Acquia Dev Desktop records the location of your site's Drupal
  codebase, creates its new database (if selected), and adds the site to
  the list of sites in the Sites tab.


Views generating JSON output I want to pull a JSON file out of a view that has images. This is similar to the way views_datasource works in D6.  I am not a drupal coder, but I would like to give this a try.  but I am guessing that is would be something like  http://mearra.com/blogs/juha-niemi/drupal-7-custom-node-view-modes#comment-218

but I would like to make this a module as much as possible.
any sample code, examples would be great.
thanks

There is now a Drupal 7 version of Views Datasource. Here is a quote about it (from the module's project page):

... is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML. These formats allow content in a Drupal site to be easily used as data sources for Semantic Web clients and web mash-ups. Views Datasource plugins output content from node lists created in the Drupal Views interface in a variety of formats - XML data documents using schemas like OPML and Atom, RDF data documents using a vocabulary like FOAF, JSON data documents in a format like Exhibit JSON, and XHTML data documents using a microformat like hCard.
The project consists of 4 Views style plugins (and related row plugins):

views_xml - Output as raw XML, OPML, and Atom;
views_json - Output as Simile/Exhibit JSON, Canonical JSON, JSONP/JSON in script;
views_rdf- Output as FOAF, SIOC, and DOAP;
views_xhtml - Output as hCard, hCalendar, and Geo.


Drupal Commerce: Allow anonymous users to choose password I'd like to allow anonymous users to make purchases on my store, however I don't want them to have to login and then change their password as their first port of call. Is there anyway I can collect a password from the customer during checkout, like it is possible to in Ubercart 3 and with LoginToboggan?

You should look into modules that handle this use case. See below for examples:

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

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

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

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


Array argument to rules action I am building a Rules action that needs to take an array argument, that I would populate using a PHP script on the action UI.

Let's say the action is called TranslateMessage, with arg1 = text, arg2 = array

How to declare arg2 so that it shows up as a text area with PHP input in the Rules UI, and send the array (that I create in the PHP area) as an argument to the action function?

you might want to serialize that array or json decode it, than it can easily be passed as a string.


How to consume data about drupal contributed modules? Is there a feed or feeds that expose data about all drupal contributed modules? I want to consume drupal.org data about modules in a certain category e.g. https://drupal.org/project/modules?f[0]=im_vid_3%3A59

I would love to get the catagories information e.g "Categories: Actively maintained, Under active development, Administration, Modules, Developer, Site Navigation"

I've seen http://drupal.org/node/63589, but the "Compatible with Drupal core 7.x" (http://drupal.org/taxonomy/term/103/0/feed) only lists about 72 ftp urls when I load it in a web browser.  That is not all of the D7 modules...

I also looked at the About page on http://drupalmodules.com for clues about how they get the data, but didn't find anything useful.

Thanks for any pointers!

While it is not an rss feed, there is this page:

http://drupal.org/project/usage

which lists usage stats for all the modules 11899 of them. They each appear to have a page that has a bit more detail on it.


View and fixed operator I've made a view that contains a filter that the visitor can change.
The problem is that it give the possibilities to filter trough a combobox:

Is equal to
Is not equal to
Contains
Contains any word
Contains all words
Starts with
Does not start with
Ends with
Does not end with
Does not contain
Length is shorter than
Length is longer than
Regular expression

I don't want them! I just want the user to see an input field and click "ok" (something like that). And the search would be "Contains all words".

How to do this?

in your exposed filter, is the "expose operator" option checked ?

This might be the obvious answer.


How to insert any view inside of another view? I wonder how to insert any view inside of another view in Drupal 8?

Simply, we have products pages, which contains product details pages in views. When I click on any product detail page from view, it should open window with text which is set up in one view and display another second view with related receipts.

Both views should be filtered according to Taxonomy reference.

How can I achieve this?

OPTION 1
If you want to display it after your current view In Views, click on +Add button and select Attachment.
Now go to your page view in the FOOTER add Global: View area and select your attachment.
OPTION 2
Download and enable Twig Tweak
If you want this as a field, add a Global: Custom text and put:

{{ drupal_view('view_name', 'machine_name') }}

Ex:
{{ drupal_view('frontpage', 'page_1') }}

OR
If you want to display it after your current view, in footer add Global: Text area, checkmark ☑ Use replacement tokens from the first row put
{{ drupal_view('view_name', 'machine_name') }}
 and select FULL HTML as your text formatt.


Search API / Facets: How can I define a range / manipulate the search query in D8? I've defined a facet for the field "Authored on". I'd like to create display filters like "current week", "current month", etc. on my website.

The creation of the links was no problem. I have facet links like this:

Current week

How can I manipulate the search query if a period has been selected? I need something like "get all search results, which are younger than tstamp of monday this week" or "get all search results between date X and date Y".

Afterwards here my solution: I've solved it with condition groups in the hook_search_api_query_alter() function:

function MYMODULE_search_api_query_alter($query) {
    //...

    $conditionGroup = $query->createConditionGroup('AND');
    $conditionGroup->addCondition('created', $firstDayOfYear, '>=');
    $conditionGroup->addCondition('created', $lastDayOfYear, '<=');
    $query->addConditionGroup($conditionGroup);

    //...
}


Front-end page to add content for a specific content type I am new to Drupal and I am working on a page created by the Views module and I am displaying my content as a grid.

As I already know it is possible to add content to my specific content type from the admin panel, I would like to have a front page which has the same functionality.

Is there anything which helps me achieve this?

You can simply go to achieve
Using the 'Admin Menu': Configuration > Site Information.

Under the Front Page section, change FRONT PAGE to content add information.

I think you should look into

Form Block module.

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Advanced Form Block module.

  Create any number of blocks with a particular node edit form.

  Create any number of blocks with a particular node add form of a content
  type.

  Create as many blocks as you like of each kind.


Contextual links only appear the first time I know this is a really specific issue, but it's a mystery that annoys me.

The contextual links menu that allows me to edit articles is only showing up the first time I view it. By this, I mean, if I refresh the page, they will no longer work. If I click the edit tab, save the node and let it return me to the node's view page, they work again. But, then I refresh, and they are broken again.

I've noticed that the focus class is appended to the article (on hover) on the page when it works, but not when it doesn't work after being refreshed. I've also noticed by debugging that in StateModel.js and VisualView.js, that toggleOpen happens twice (on the broken version -- after refresh), opening and then closing the contextual links menu. But, I can't figure out why.

The content div, which contains the html for the article & contextual links, is 99% identical in bother versions with the only difference being a changed form-build-id for the comments.

The css/js files loaded on the page when it works/doesn't are nearly identical in both versions, with the only differences being a css file that does 2 unrelated things.

This is on both Firefox and Chrome.

If anyone has any ideas, it would really help me sleep at night.

I figured out that someone else has hit this error, and has contributed a patch for it:

https://www.drupal.org/node/2834346

The patch stops the Contextual Links module from adding a contextual link placeholder to the array if it's already in there.  I'm still not quite sure why there's a cookie for the contextual link (as I said in the comment above) if it's going through them and adding them anyway.  If anyone else knows more about this issue, feel free to answer.