Set form value to empty on validation fail I have a requirement to set a single field to empty, if it fails validation. The form is built using Drupal 8's Form API.

In my validateForm() function, I have the following:

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  if($values['myfield']!='something') {
     $form_state->setValue('myfield', '');
     $form_state->setErrorByName('myfield', $this->t('Sorry, this field value is not correct.'));
  }
}

Unfortunately, the above has no effect - when the form is rebuilt myfield still contains the user submitted value.

I assume this is something to do with the order in which these functions are called? Or perhaps, because $form_state is not passed by reference? (I cannot do this, as it's then no longer compatible with the FormBase class I'm extending).

One solution I've found is to access the form element from the $form array in my validateForm() function:

$form['myfield']['#value'] = '';

But the above doesn't really feel like the correct solution?

Use setValueForElement:

$new_value = '';
$form_state->setValueForElement($form['myfield'], $new_value);


Mixing field collection items with regular fields in views I've got a content type that contains fields like this:

title
field collection
body
link

The field collection contains:

image
text

The field collection is going to be for 3 iterations in one node. In views this is the desired output:

title
field collection 1 image
field collection 1 text
field collection 2 image
field collection 2 text
field collection 3 image
field collection 3 text
body
text
link

I've set the relationship in views and retrieved the field collection fields. The problem I'm running into is it's duplicating all the single fields for every field collection item. The output looks like this:

title
field collection 1 image
field collection 1 text
body
text
link
title
field collection 2 image
field collection 2 text
body
text
link
title
field collection 3 image
field collection 3 text
body
text
link

How can I get it to draw all the field collection fields without duplicating the rest of the fields along with it?

I think this is not the right views set-up for what you want to display, you have done wrong field selections. To see direct solution scroll down to Solution section.

What is the Issue:

If you see your views field setting it is like as follows,

Content: title
field collection item: Bubble title
field collection item: Bubble image
Content: Body
Content: Link

So, here in above view set-up the field collection item is just one field, so through views you are just accessing one field, hence, the concept of field collection module dies here. Here, it is just a field which you are accessing through the Relationship.

Now, why you are observing what you are observing in the view,

Your Node: Following is the correct representation of your Node, Not what you have shown in your Question. Your node has FIVE main fields- and whatever inside the field collection field are field-in-field.

   1. title
   2. field collection
     2.1a field collection 1 image
     2.1b field collection 1 text
     2.2a field collection 2 image
     2.2b field collection 2 text
     2.3a field collection 3 image
     2.3b field collection 3 text
   3. body
   4. text
   5. link

Now, you have set your views like as follows,

   1. Content: title
   2.xx field collection item: Bubble title
   2.xx field collection item: Bubble image
   3. Content: Body
   4. Content: Link

I think by this time you would have understood why you are getting what you are getting in views.

Let me explain:

Cycle:1 Views start the first cycle and iterates from its Fiest field to Fourth field, so it will showing following fields:

   1. Content: title
   2.1a field collection item: Bubble title
   2.1b field collection item: Bubble image
   3. Content: Body
   4. Content: Link

Cycle:2 Now, views works stops there, But wait, Views discover that another 2.xx and 2.xx are there on node, So it starts second cycle so again from TOP to Bottom,

   1. Content: title
   2.2a field collection item: Bubble title
   2.2b field collection item: Bubble image
   3. Content: Body
   4. Content: Link

Cycle:3 Then  again third cycle, So that why you are getting this,

   1. Content: title
   2.3a field collection item: Bubble title
   2.3b field collection item: Bubble image
   3. Content: Body
   4. Content: Link

So whatever views are showing it showing correct as per your field selection, But that is not what you want, please see the solution in following section, it is very simple.

Solution:

The solution is very simple: You just need a field which represent the entire field collection of that node and luckily that is present in views.

Remove the relationship: You do not need the relations ship.
Modify the field: Instead of selecting individual field, select entire field collection which you can find as Content:nameOfFieldCollection. in my case it is FC101.

Example:

I have created Content type with:

1. Title
2. Body
3. Field collection(FC101)
   - Image
   - text
   - Image
   - text
   - Image
   - text
4. Body2

My views set-up:

Output in VIEW:

1. Title
2. Body
3. Field collection(FC101)
   - Image
   - text
   - Image
   - text
   - Image
   - text
4. Body2


Adding 'Add to Cart' to 'Collection Products' view I want to add an Add to Cart button to my products when they are still in the Collection Products view (Category overview). By default, when you navigate to a category like /commerce_kickstart/product-category/sample-category-1, you will find the single products display like this:

I would like to have all of the single products be shown like this:

In the Product Display content type, the add-to-cart-form is stored in $content variable. It is pretty easy to access via field_productand I can for example add multiple forms and stuff. But how can I get the form in the Collections Product view?
I went to Structure -> Views -> Collection Products -> Field and looked through the available fields. I found field_product but when I add this, everthing that changes is that a link to the product is shown underneath the price.

So how can I add this to the Category overview?

Edit:

I have added this field (because the name appeared to be familiar scince the cart form is stored in this variable (field_product) in node--product_display

https: //i.stack.imgur.com/CaNo9.png

And that caused this to appear, wich only adds a link to the product underneath the price.

https: //i.stack.imgur.com/1vbWW.png

And this is basically all the configuration besides some more irrelevant stuff:

https: //i.stack.imgur.com/fk9BB.png

In your view, can you add a relationship to the product category in your cart? It should be visible as Referenced Entity or Referenced Product... basically in views you need to join your node/product to its related store/product, once you have done that you should see an available field "% to buy" with the formatter "add to cart button"


Delete a block of all layouts I am using Layout Builder (Drupal 8.7.1)

I have a block in several Layouts. How can I programmatically remove all instances of this block and update all layouts without the message "This block is broken or missing. You may be missing content or you might need to enable the original module." ?

here it is, tried it with a custom content block and a views block

i executed the code in php/devel from devel_php module

$storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
foreach ($storage->loadMultiple() as $display) {
  foreach ($display->getSections() as $section) {
    foreach ($section->getComponents() as $component) {
      // Custom views block
      // $to_delete_plugin_id = 'views_block:my_news-block_1';
      // Custom block
      $to_delete_plugin_id = 'block_content:fb4ad848-0f3c-4296-a6ba-1a9da886335b';
      if ($component->getPluginId() == $to_delete_plugin_id) {
        $section->removeComponent($component->getUuid());
        $display->save();
      }
    }
  }
}

for a particular node :

// This can be adapted to be used for a set of nodes
$node = node_load(42);
$display = $node->layout_builder__layout;

foreach ($display->getSections() as $section) {
  foreach ($section->getComponents() as $component) {
    // Custom views block
    // $to_delete_plugin_id = 'views_block:my_news-block_1';
    // Custom block
    $to_delete_plugin_id = 'block_content:fb4ad848-0f3c-4296-a6ba-1a9da886335b';
    if ($component->getPluginId() == $to_delete_plugin_id) {
      $section->removeComponent($component->getUuid());
      $node->save();
    }
  }
}

Hope this helps :)


PO files inside contrib modules Situation is that inside contrib modules folder I found out that each module has /translations and inside a .po file which is not cool when it comes to modules update. I want to take out these translations out of each module folder and place them in single location.
My questions is any idea why they were placed there in first place, is this some kinda of convention or? Also if I extract them to another folder what type of configuration must be provided ? And last question is I assume that simply removing/moving them wont affect translation at all as they were already import into the database?

After research in drupal.org I found out that best way is to place translations in /sites/all/translations. Naming convention is module_name-version-language.po

Moving them out did not affected the current translations as they are already imported into the database.


Drupal 7: Local site URLs all point to production site I've been trying to figure this out for a while on this one particularly large site.

Every single URL on every page and menu, even the admin menu as the wrong url. I've tried this with WAMP, MAMP, Vagrant, Docker and Docksal with the same results.

A better explanation:
I'd expect all urls to be what I've setup on my local machine as the base. Like mysite.loc, or for docksal, mysite.docksal.

But when I pull the repo for this site and set it up, then load it...all urls are the production urls. Anything I click on goes to production. All submit buttons goto production. Almost like they are saved in the DB, but the definitely aren't.

I've tried setting the base URL. That doesn't work.

I've turned off all the modules, both contrib and core. That doesn't work.

I've changed themes. That doesn't work.

It's something within the filesystem of this site but I'm not sure where to look at this point. Probably a hack someone put in somewhere.

Any thoughts of where to look?

I found the issue.

If you're using the module "Domain Access", the uninstall hooks do not work properly (or at least they didn't on our site).

You'll need to go into your DB and change the domain settings after you've disabled your module.

All of the Domain module tables that have your production (or old URL) in them need to be changed. Removing those tables will likely corrupt your DB and make the site unusable.


Exporting a block/module? I'm working on migrating a theme from Drupal 6 to 7 but my dev site doesn't have a block used on the old one. I need to export the block from the old one to the dev one, but I can't figure out how. Help please.

You can not export Drupal core blocks directly.  You can can either write it in a custom module, see http://fourkitchens.com/blog/2012/07/18/building-custom-blocks-drupal-7.
Or, you could recreate it using boxes: https://drupal.org/project/boxes, which can be exported using Features.

Boxes module is a reimplementation of the custom blocks (boxes) that the core block module provides. It is a proof of concept for what a re-worked block module could do.
The module assumes that custom blocks are configuration, and not content. This means that it is a reasonable action to ask for all blocks at one time, this is in fact exactly what the core block module does.
Boxes provides an inline interface for editing blocks, allowing you to change the contents of blocks without going to an admin page.
Boxes provides exportables for its blocks via the (required) Chaos tools module. This allows modules to provide blocks in code that can be overwritten in the UI.

Or, you could copy and paste the block contents into a new block too.


I get "/tmp is not writeable by the webserver" on migration I migrate a Drupal website from Apache to IIS.All the image that customize whit ImageCach not shown and I get this error "/tmp is not writeable by the webserver"!
please help me soon!:(

If you search Google for "drupal iis tmp not writeable by the webserver", the first result is a post on drupal.org, telling you to:

  Try going to admin/settings/file-system and set /tmp to just tmp

and a comment saying:

  Confirming this fix. It might have something to do with going from linux system to windows.

I guess that will work in your case too.


Filtering nodes shown on taxonomy menu block As in the picture, the taxonomy terms are showing count of nodes tagged with the term( using taxonomy_menu module). That nodes are of type classified ads.

Is it possible to filter out expired ads ? I mean in the picture, the first menu item is "10th" with 24 nodes in it. But I want to filter out 5 nodes which have expired containing a hidden flag that it has expired. So that is should show as "10th(19)"

How can I do it?

Looks like in the file taxonomy_menu.database.inc we have this function:

function _taxonomy_menu_term_count($tid) {
  $result = db_select('taxonomy_index', 'tn');
  $result->condition('tid', $tid);
  $result->join('node', 'n', 'n.nid = tn.nid AND n.status = 1');
  $result->addExpression('COUNT(n.nid)', 'term_count');
  $temp = $result->execute();
  $temp = $temp->fetchObject();
  return $temp->term_count;
}

Along with n.status I should add n.field_expired check to exclude I think.  I wouldn't mind to temporarily hack the code of Taxonomy Menu though.

Since you said you "would not mind temporarily touching the code" (I would highly advise not to touch and try to find alternative ways) here is my quick solution and also alternative ways of accomplishing it.

Assuming the field_expired is a boolean field (single on/off check-box values 1/0) and you are not using revisioning.(see the three lines I added), also make sure you resave at least one node to recalculate.

function _taxonomy_menu_term_count($tid) {
  $result = db_select('taxonomy_index', 'tn');
  $result->condition('tid', $tid);
  $result->join('node', 'n', 'n.nid = tn.nid AND n.status = 1');

  $result->join('field_data_field_expired', 'fdfe', 'fdfe.entity_id = tn.nid');
  $result->condition('fdfe.field_expired_value', '1', '=');
  $result->condition('fdfe.entity_type', 'node', '=');

  $result->addExpression('COUNT(n.nid)', 'term_count');
  $temp = $result->execute();
  $temp = $temp->fetchObject();
  return $temp->term_count;
}

Another ways of patching it would be to add a module_invoke_all higher up the code to allow other modules to interact (hook into), or use "addTag" along your query and allow other modules to alter the query itself (the latest one would be recommended). Both this require you to write your own custom module.


get form_state values from ajax callback through hook_form_alter? I'm having a little problem with my drupal 7 module.
I'm trying to get the $form_state['values'] from $form['base']['st-volume-pricing']['price'] and $form['base']['st-volume-pricing']['till-amount'] in my ajax callback so that I can add them to a results table.

Is this the right way to do it or am I missing something?

function mymodule_form_alter($form, &$form_state) {
  $form['base']['st-volume-pricing']['price'] = array(
    '#type' => 'uc_price',
    '#title' => t('Price'),
    '#description' => t('Set the price for this volume\'s reduction'),
    '#size' => 10,
    '#prefix' => '

',
    '#suffix' => '	',
  );
  $form['base']['st-volume-pricing']['till-amount'] = array(
    '#type' => 'textfield',
    '#title' => t('Till Amount'),
    '#description' => t('The amount till which the volume discount applies'),
    '#size' => 10,
    '#prefix' => '',
    '#suffix' => '	',
  );
  $form['base']['st-volume-pricing']['add'] = array(
    '#type' => 'submit',
    '#value' => t('Add'),
    '#submit' => array('mymodule_add_volume_standard'),
    '#ajax' => array(
      'callback' => 'mymodule_add_volume_standard_ajax_callback',
      'wrapper' => 'st-volume-results',
      'method' => 'append',
      'effect' => 'fade',
    ),
    '#prefix' => '',
    '#suffix' => '
',
    '#title' => t('Click this button to add a standard volume price'),
  );

  //this is our results table
  $form['base']['st-volume-pricing']['st-volume-results'] = array(
    '#type' => 'markup',
    '#markup' => '

' . t('Price') . '	' . t('From Amount') . '	' . t('Till Amount') . '

',
  );
  variable_set('vol-st-price', NULL)
  variable_set('vol-st-from', 1)
  variable_set('vol-st-till', NULL)

  //this is our row that will be inserted
  $form['base']['st-volume-pricing']['st-volume-results']['row'] = array(
    '#type' => 'markup',
    '#markup' => '
' . variable_get('vol-st-price') . '	' . variable_get('vol-st-from') . '	' . variable_get('vol-st-till') . '
',
  );
}

When I'm using it inside here:

function mymodule_add_volume_standard_ajax_callback($form, &$form_state) {
  //check if there is a previous volume price and set the from field
  if (variable_get('vol-st-till') !== NULL) {
    variable_set('vol-st-from') = variable_get('vol-st-till') + 1;
  };
  //add or overwrite the value entered in price
  variable_set('vol-st-price') = $form_state['values']['base']['st-volume-pricing']['price'];
  //add or overwrite the value entered in till
  variable_set('vol-st-till') = $form_state['values']['base']['st-volume-pricing']['till-amount'];
  //create new row in results table
  return $form['base']['st-volume-pricing']['st-volume-results']['row'];
}

drupal_set_message("
" . print_r($form_state['values']) . "
");
displays 1.

I suppose that $form_state['values'] should only work during the submission of a form.
How would one go about doing this when using a hook_form_alter() and ajax callbacks?

I also tried displaying drupal_set_message("
" . print_r($form_state['values']) . "
"); in my function mymodule_add_volume_standard. Which also displayed 1.
Neither does it work when trying it in the hook_form_alter() which is default behaviour I suppose?

I'd really appreciate it if someone could clarify some things for me.

Some basics:

function mymodule_form_alter($form, &$form_state) {

hook_form_alter is a generic alter function that receives a third argument $form_id to distinguish the possible forms. Right now you would alter every form in your site.
The correct function signature is:

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

You can see, that the $form itself is passed as a reference and can be changed. There is no way of changing $form_state directly during the form building process, which is when hook_form_alter is invoked.

Concerning $form_state['values'] in validation and submit handlers: All elements defined in the $form array are by default inserted into a flat structure in $form_state['values']. This means that with your setup, you would access the value entered in $form['base']['st-volume-pricing']['till-amount'] as $form_state['values']['till-amount']. You can change that behavior by defining #treefor the form element's parent, see for example: https://drupal.org/node/48643

Edit: The general approach for ajax forms is that in the submit you store values inside $form_state, e.g. in $form_state['storage'], set $form_state['rebuild'] which assures that the form builder and hence your alter function is called again, and then test for the presence of stored values inside your form alter function. Depending on the submitted values you would then implement the logic to achieve what you want.


Get the submitted values from $form_state Is there a function (in Drupal 8) to build an array containing the submitted values in $form state? If I use $form_state->getValues(), I get more values than the ones I need.

If you are getting values like form_id, form_token, or form_build_id, which you don't want, then you need to use the following code.

$values = $form_state->cleanValues()->getValues();

The documentation for FormState::cleanValues() says:

  This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.

  form_id
  form_token
  form_build_id
  op

FormState::cleanValues() returns $this, so it can be used in chained calls, as in the code I showed.


Cannot find PHP type in Data Format I am new to Drupal and using Drupal7.23 in windows7 with XAMPP installed. While I am creating any content I cannot find "PHP type" in the Data Formats. Kindly tell how to add PHP type in Data Format, as I need to add PHP to the content.

Enable the 'PHP Filter' module available in drupal core:

Go to modules list: /admin/modules and than in Core you will find PHP filter module as indicated below, so just enable it.


Drupal alternative to PHP's strip_tags? Is there a Drupal 7 function that is equivalent to PHP strip_tags?

Drupal 7 uses strip_tags directly in plenty of places (theme.inc, common.inc, etc.).

If there was an equivalent, core would use that instead, so you can safely assume that you should use strip_tags when you need the functionality it provides, not a Drupal-specific method.


Clean URLs aren't being displayed I want clean URLs like webpage.com/page instead of webpage.com/?q=page, specifically in my menus.

I have gone here http://v6.dev/admin/config/search/clean-urls (which is a clean URL and works) and ticked the 'enable clean URLs' option and saved. But nothing happens, the page reloads without the tickbox checked.

Clean URLs are working, I can navigate to webpage.com/page fine, but the menus aren't being generated as clean URLs.

I have gone through this page: https://www.drupal.org/getting-started/clean-urls but can't solve the problem. I think the servers set up okay, because I can succesfully navigate to clean URLs, it's just that links aren't rendered as clean URLs.
I've also tried cleaning the cache, and restarting server.

If it helps, I'm generating menus with this code:

<?php
    $menu = menu_navigation_links('menu-top-menu');
    print theme('links__menu_main_page', array('links' => $menu));
?>

First thing I would check is the .htaccess is indeed working...maybe your getting a cached version of:

http://v6.dev/admin/config/search/clean-urls

What happens when you enter a URI which you know has never existed (and been cached) such as:

http://v6.dev/xxx-237347-3iu33

Does it 404? Does drupal handle it and say "page cannot be found"?

I had a similar issue a few days back...I had to manually disable "clean uri's" in the database...flush all cache tables...re-enable mod_rewrite...log in and enable clean URI's

Let me know how you turn out. :)


Render a custom block programmatically How do I render a custom block type (block_content) programmatically with a specific display view?

In hook_preprocess_page() add the following code.

$block_entity = Drupal\block_content\Entity\BlockContent::load(BLOCK_ID);// BLOCK_ID
$block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'DISPLAY_VIEW_NAME');
if ($block_view) {
    $variables['page']['my_block'] = $block_view;
}

In your Twig template, print the block with the following code.

{% if page.my_block %}
  {{ page.my_block }}
{% endif %}


hook_file_download and style images According this bug issue,
hook_file_download is called twice when private style image is requested. The first time is requested original image without style and then the style image is called. Is there any workaround to skip checking access of original image?

In particular, I have a website, where user can share his private images on his facebook account. Then I need to allow facebook to send http request to download image. The problem is, that facebook hs limitations on size of images. Facebook doeasn't accept larger images when downloading thumbnails from my website. As I tested it, although my image thumbnails are small, drupal system check access against large original image so facebook doesn't accept the thumbnail.

Is there any workaround, how could I solve this problem?

thanks for advice
Tomas

Disclaimer - Use this method at your own risk, it has security implications if you don't set up and test it properly :)

A quick and dirty way to override that functionality would be to implement hook_module_implements_alter(), remove the image module's implementation of hook_file_download(), and then implement your own version which has the desired logic. e.g.

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'file_download') {
    unset($implementations['image']);
  }
}

function MYMODULE_file_download($uri) {
  // Copy the code from image_file_download() and alter as required.
}


SMTP configuration issue in drupal 7 In SMTP module configuration I have set the following fields:

SMTP Server: smtp.live.com
SMTP port:25
Use encrypted protocol: NO

In E-MAIL OPTIONS,

E-mail from address: myadress@hotmail.com
SEND TEST E-MAIL: myadress@hotmail.com.

but it gives me the long detail of errors with the last line SMTP Error: Could not authenticate. Same error when I try to use below configuration:

 SMTP Server: smtp.gmail.com
 SMTP port:25
 Use encrypted protocol: SSL

In E-MAIL OPTIONS,

E-mail from address: my_gmail_address
SEND TEST E-MAIL: my_another_address.

But when I used port 80 instead of 25 then it gives me the following error for SMTP.live.com

SMTP -> ERROR: Failed to connect to server: Connection timed out (110) drupal 7

UPDATED:

Below is the screen shot for gmail configuration.

Change Port number to 465 or 587 in case of SMTP Server: smtp.gmail.com and 587 in case of SMTP Server: smtp.live.com.

As per : https://www.arclab.com/en/kb/email/list-of-smtp-and-pop3-servers-mailserver-list.html.


Proper way to ajaxify links? According to a comment on Drupal's AJAX framework it should be possible to define a link as a render array which Drupal then would turn into an ajaxified link. As far as I understand it, the essential part of this is :

$link = array(
  '#type' => 'link',
  '#title' => t('something'),
  '#href' => 'some/path',
  '#ajax' => array(
    'callback' => 'some_callback_function',
    'wrapper' => 'ajax-response-goes-here',
    'method' => 'replace',
    'effect' => 'fade',
  ),

However, I'm not quite certain which url the client would use to actually invoke the AJAX request? I know forms use 'system/ajax' to access callback methods from there, but what about this case?

If anyone would have the chance to shed a little light on how to properly ajaxify links, I'd be very greatful!

I would be rather suspicious about the '#ajax' way. Try to have a look here : http://api.drupal.org/api/examples/ajax_example%21ajax_example_misc.inc/function/ajax_example_render_link/7

What they say :

include the ajax.js
add use-ajax class
implement ajax callback under the link your link directs to

what should be done after the callback executes can be set by the ajax commands.


Drupal 8 - taxonomy term field without "title" attribute I have a simple view block with exposed the taxonomy term linked to the taxonomy page, but I have noticed that the attribute is missing, I tried to rewrite the term but every attempt went wrong.

What I need is simple, this is the view generated field:

Events

I want to add title="Events", like this:

Events

But I can't find any solutions in Drupal 8 view!

You should be able to use template_preprocess_views_view_field to accomplish this. Create that hook in your custom theme like:

/**
 * Alter field_MY_TAX_FIELD link to add title attribute.
 *
 * Implements template_preprocess_views_view_field().
 */
function MY_THEME_preprocess_views_view_field(&$vars) {
  if ($vars['field']->field == 'field_MY_TAX_FIELD') {
    // Add title attribute to link.
  }
}

Alternatively you could create a new field formatter that extends Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter. Override the viewElements method. First call $elements = parent::viewElements($items, $langcode);, then traverse $elements and add your title attribute when appropriate. After you create the formatter, clear cache and then go back to your view and select your new formatter as formatter for the taxonomy field.


Webforms messed up 'Add content' button After I installed and enabled the webform module, my admin toolbar got messed up.

Whenever I click on 'Content -> Add Content' I immediately get redirected to #overlay=node/add/webform. I can still go to the separate content types by altering the link (eg. '#overlay=node/add/news').

I have tried disabling the module and uninstalling / reinstalling, but to no avail.

Is there a way to restore the functionality?

EDIT: Apparently my content types have disappeared...

SOLUTION:

Discovered that the items for basic page and article had both been marked as disabled (though not by me) in the navigation menu. Re-enabling them under admin/structure/menu/manage/navigation fixed the problem immediately.

D7 Add Content is missing content types


Best way to inform users after file upload I'm searching for a good solution to inform users after a file was uploaded (with standard upload URL: ...file/add).

I would solve this with rules, but I can't find the right events for this.
Has anybody a good idea.

Have you checked out the Entity Rules module? I believe this is exactly what that module is for.

I did a brief check and you can create a reaction rule on a Create Entity action and then check the type of that entity.


How to make block title words themable in D6 I need to have my block title for Newsletter Signup block appear like this:

Sign up for mail

Note: Sign up = red colored font
for mail = blue colored font

Please help, I know how to override a block.tpl.php file, but I am not sure what my code would be to separate the word groups and add a div or span.

Quick and dirty in your block.tpl.php:

<?php
  if ($block->subject=='Sign up for mail') {
    $block->subject='Sign up for mail';
  }
?>

And in your .css file:

.blue {
   color: blue;
}

.red {
    color: red;
}


Expose a computed field (or external data) to Views I want to add a virtual field to a "node", its content should be computed  from other fields of this node (with the module of the same name or with a hook) AND it must be usable by Views filter and sorting.

Is this possible (using modules or PHP code) ?

I found answser on this site:
http://barcelona2012.drupaldays.org/sessions/displaying-external-data-fly-views-and-ctools

This simple module give a clear example on how to expose external data (webservice) to a views.


How to allow users to 'add' values to a multi-value field but not edit any previously add values? I have a field called 'Remarks' on an ECK entity (not a node) and Role A is allowed to leave remarks but I don't want them to edit previous remarks, I just want to give them the option to add one. Note: they are not the author or owner of the entity. Right now, I use an Edit Page Variant for this entity that they have access to and where this form for 'field_remarks' appears. The problem is that the previously added remarks are still showing up and therefore now they can still edit someone else's remarks.
potential solution 1
I would probably be possible to hide the fields that already contain values with jQuery but that is not really the Drupal way, I believe.
potential solution 2
Could it possibly be done with a Rules component that adds the value (text) to this field programmatically? And if so, how and where to show a text field that would accomplish that?

You can programmatically disable them in module like this:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'eck__entity__form_edit_ENTITY_NAME_BUNDLE_NAME') {
     $lang = $form['field_name']['#language'];
     foreach ($form['field_name'][$lang] as $key => $value) {
       if (is_numeric($key) && !empty($value['value']['#default_value'])) {
         $form['field_name'][$lang][$key]['value']['#disabled'] = TRUE;
       }
     }
   }
}

Result


Include Drupal modules inside composer.json file I am doing a custom code of OpenSocial template/site.

In OpenSocial or other composer file, there are some modules that are added in the "require": {} section and they are installed properly when running the file.

Ex.

   "drupal/entity": "1.0-alpha4",
   "drupal/features": "3.5",

My question is how can I install module that requires to run composer for it to be properly working?

My goal is to include Simple Oauth in the composer file.
I can just do this, but is there any additional input outside the file?

"drupal/simple_oauth": "2.0-rc1",

Also I noticed that when adding the Address module in the require section, there is some lines added here, for example.

I am new to this method and I really appreciate your help! Thanks!

There are general two kind of dependencies you can make in a composer file.

Other Drupal modules
PHP/JS/FOO libraries

If your module depends on a specific library, you should do like the address module and make sure that the library is present when it's being installed, so you can prevent installation if the library is not available. It's a clever way of making sure you don't install the module in a broken setup, which could cause fatal errors etc.

IF you simply depend on other drupal modules, you should also add the dependency in the info file which should be enough.


How to set default value of select list field on add node form? I am trying to set the default value of a select list field on a node add form. The field name attribute in the HTML of the form is:

field_state[und]

The ID of the add form is:

local-affiliate-node-form

I created a little module to try to do this. It just has this code in it:

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'local-affiliate-node-form'){
        $form['field_state']['und']['#value'] = 17;
    }
}

I enabled the module and cleared cache but it doesn't appear to work. I also tried these lines inside the IF statement:

$form['field_state']['und']['value'] = 17;
$form['field_state']['und']['value']['#value'] = 17;
$form['field_state']['und']['#default_value'] = 17;

In case you're wondering, I can't use the Drupal interface to set the default value because eventually that "17" will be dynamic, so it will change depending on what the user clicks and I will use a string in the URL in place of a static number.

Thanks for any help!

If you need "code" way you need set default value like this.

$form['field_name']['und']['#default_value'][0] = "1"

"1" -  its number of element which you want set default.

I use that when i need set programaticaly default value for field which use term reference.


Date field in FormAPI, remove Day field? Using a 'date' field in the FormAPI, is there something I can set to hide the day field from showing?

There isn't a setting for that, but you could do it with the #after_build option, as it will allow you to alter the form element after it has been processed (day, month and year fields have been created).


How do I access the Node Access User Reference configuration? I've installed the References and Node Access User Reference modules on my Drupal 7 system.  I've added a User Reference field to a content type, and can happily add user references to nodes.

However, on the Node Access User Reference's project page, it shows a screenshot of a configuration form which I cannot find.  I want to grant referenced users editing rights, but cannot find where to do this.  Where do I find this form?

I found a clue in the README.txt which I'd previously missed

  Create a field to reference users in a content type using the Field UI.  The field's
  configuration page will contain the settings for Node access user reference.

I edited the User Reference field I'd created, and on the Edit tab was a collapsed heading for Node access user reference that I'd previously missed.  Clicking the heading revealed the configuration form.


File upload empty in custom form I have a really simple form with a file upload. It actually used to work until I recently noticed it's not saving the file. When I check for the submitted values, the file field is empty, but the file is in $_FILES.

Here is how I build the form:

function tag_graphics_form($form_state) {
    $form = array();
    $form['tag'] = array(
        '#required' => TRUE,
        '#type' => 'textfield',
        '#title' => t('Tag'),
        '#size' => 30,
      );
    $form['image'] = array(
        '#type' => 'file',
        '#title' => t('Image for tag page'),
        '#description' => 'Recommended width for image: 605px'
    );
    $form['description'] = array(
        '#type' => 'textarea',
        '#title' => t('Page Description for SEO')
    );
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save'
    );
    return $form;
}

And this is how I process things in the submit:

function tag_graphics_form_submit( $form, &$form_state ) {
    // save the image and put to the database
    print_r($form_state['values']);  // the image field is completely empty here. other fields are ok
    print_r($_FILES); // the uploaded file is here just fine
    if ($form_state['values']['image']) { // all of this used to work...
        $validators = array();
        $file = file_save_upload('image', $validators, file_directory_path());
        file_set_status($file, FILE_STATUS_PERMANENT);
        $filepath = $file->filepath;
    }
    // more code...
}

function tag_graphics_form($form_state) {
    $form = array();
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['tag'] = array(
        '#required' => TRUE,
        '#type' => 'textfield',
        '#title' => t('Tag'),
        '#size' => 30,
      );
    $form['image'] = array(
        '#type' => 'file',
        '#title' => t('Image for tag page'),
        '#description' => 'Recommended width for image: 605px'
    );
    $form['description'] = array(
        '#type' => 'textarea',
        '#title' => t('Page Description for SEO')
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save'
    );
    return $form;
}

function tag_graphics_form_validate($form, &$form_state){
  $field = 'image';

  $directory = file_directory_path();
  if (file_check_directory($directory, FILE_CREATE_DIRECTORY, $field)) {
    $validators = array();
    if ($file = file_save_upload($field, $validators, $directory)) {
      file_set_status($file, FILE_STATUS_PERMANENT);
      $form_state['storage']['file'] = $file;

    }
  }
}
function tag_graphics_form_submit(&$form, &$form_state){
  print_r($form_state['storage']['file']);
}


Saving form after altering it I'm altering the "Edit menu link" form

function module_name_form_menu_edit_item_alter(&$form, &$form_state, $form_id) {
    $form['html_content'] = array(
        '#type' => 'textarea',
        '#title' => t('HTML Content'),
        '#maxlength' => 180,
        '#required' => FALSE,
        '#description' => 'Put here the HTML code of the menu'
    );
}

The text area is showing fine, but it's not saving the information I put into.
How can I solve that?

Generally speaking, only the form builds with system_settings_form() automatically saves the form field content of all the form fields present in the form. This is because its form submission handler (system_settings_form_submit()) contains the following code.

  foreach ($form_state['values'] as $key => $value) {
    if (is_array($value) && isset($form_state['values']['array_filter'])) {
      $value = array_keys(array_filter($value));
    }
    variable_set($key, $value);
  }

The form you are altering has a different form submission handler, menu_edit_item_submit(), which doesn't contain similar code. The function that is called for saving the menu item, menu_link_save() saves the fields it knows of, and which are defined in the database schema for the table used for this purpose.

  if (!$existing_item) {
    $item['mlid'] = db_insert('menu_links')
      ->fields(array(
      'menu_name' => $item['menu_name'],
      'plid' => $item['plid'],
      'link_path' => $item['link_path'],
      'hidden' => $item['hidden'],
      'external' => $item['external'],
      'has_children' => $item['has_children'],
      'expanded' => $item['expanded'],
      'weight' => $item['weight'],
      'module' => $item['module'],
      'link_title' => $item['link_title'],
      'options' => serialize($item['options']),
      'customized' => $item['customized'],
      'updated' => $item['updated'],
    ))
      ->execute();
  }

db_update('menu_links')
  ->fields(array(
  'menu_name' => $item['menu_name'],
  'plid' => $item['plid'],
  'link_path' => $item['link_path'],
  'router_path' => $item['router_path'],
  'hidden' => $item['hidden'],
  'external' => $item['external'],
  'has_children' => $item['has_children'],
  'expanded' => $item['expanded'],
  'weight' => $item['weight'],
  'depth' => $item['depth'],
  'p1' => $item['p1'],
  'p2' => $item['p2'],
  'p3' => $item['p3'],
  'p4' => $item['p4'],
  'p5' => $item['p5'],
  'p6' => $item['p6'],
  'p7' => $item['p7'],
  'p8' => $item['p8'],
  'p9' => $item['p9'],
  'module' => $item['module'],
  'link_title' => $item['link_title'],
  'options' => serialize($item['options']),
  'customized' => $item['customized'],
))
  ->condition('mlid', $item['mlid'])
  ->execute();

In your case, you need to alter the form, adding the form field, and a form submission handler that saves your data in your own database table.
As there are more than one button on that form, I prefer associate a new form submission handler to the specific button, such as with the following code.

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

You could also be interested in doing something when the menu item is deleted (in which case, you should delete the data from your database table); the delete button is $form['actions']['delete'].


How to exclude a cache table from memcache? I have created a one custom table for storing the data, based on cache rules i have created a table.

Installed and enabled Memcache module in site.

Configured memcache in settings.php

  $conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
  $conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
  $conf['memcache_stampede_protection'] = TRUE;
  $conf['cache_default_class'] = 'MemCacheDrupal';

  // The 'cache_form' bin must be assigned to non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
  // Don't bootstrap the database when serving pages from the cache.
  $conf['page_cache_without_database'] = TRUE;
  $conf['page_cache_invoke_hooks'] = FALSE;
  $conf['cache_thrive_tips'] = 'DrupalDatabaseCache';
  $conf['memcache_servers'] = array('localhost:11212' => 'default');

When i configure memcache in my site, at that time onwards my custom table(cache_abc) not storing any values.

How can i exclude only this table from memcache?

You do it in the same way the  code you are showing does for cache_form.

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

Adding that line in the settings.php file, you are telling Drupal to save the cache for cache_abc in the database.

Keep in mind that, in Drupal cache terminology, cache_abc (which would be the name of the database table containing the cache data, when the cache is saved in the database) is called bin.


comment_admin_overview is missing I am working on hook_theme_registry_alter. I have tried to dpm($theme_registry). But comment_admin_overview is missing, The version of drupal is 7. Any ideas??.

function hook_theme_registry_alter(&$theme_registry) {
  dpm($theme_registry);
  $theme_registry['comment_admin_overview']['function'] = 'theme_hook_comment_admin_overview';
}

comment_admin_overview() is a form function in Drupal 7 (it was a theme function in 4, 5 & 6).

You can use hook_form_alter() to make your changes instead.


Access denied on admin/structure I have defined a new user role "Webmaster", and assigned it the permissions to administer forms, menu & menu items and taxonomy terms (all). Going to the admin/structure url still yields an "Access denied".

What permissions do I need set to allow my webmasters access to the admin/structure url?

The user needs the permission "Use the administration pages and help".

Then the user can access /admin and /admin/structure.

If the user has no other admin rights, the admin menus will be rather empty. They will fill up if you assign more permissions.


How do I programmatically add a product reference to a commerce product node? I am trying add a commerce product to a node when a person fills out a content node. I am generating the product, but can't add it back to the node.

When I try to add the data to the node, there is no product reference field data when Do not show a widget is selected in the content type > Manage fields.

Do not show a widget seems to remove the field from the node completely.

If I try to load in hook_node_presave():

$product = commerce_product_load_by_sku($sku);

$field_studio_pass_product = array(
  LANGUAGE_NONE => array(
    0 => array(
      'product_id' => $product->product_id,
    )
  )
);

$node->field_studio_pass_product = $field_studio_pass_product;

It won't work since there is no current field. I don't want to show the field to editor as they can't change it.

Further. This above code does work if the product field has a widget, or the ideal code:

$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_studio_pass_product->set($product->product_id);

Again, if you set the field type to Do not show a widget there is no property on the node object, and as a result no ability to add a value.

Your issue isn't that there wasn't a field available in the data model to edit but that you used the wrong array structure for the product reference. Instead of the "value" key you should've been using "product_id".

I highly recommend against directly inserting field data like your answer proposes. The Entity / Field APIs should be allowed to perform their full jobs on this data when it's entered. For example, in your case you didn't put the necessary data into the field data revision table at the same time.


How to compare 2 row fields in a view and don't display them if some conditions are verified? I have a view table with 12 Fields & 10 Rows and I wish to compare two known fields with defined field names and check if both fields are:

If data partially matches (Field 1 with Field 2 or vice versa) then display rows, e.g.:

Field 1: Apples, Oranges.
Field 2: Oranges, Grapes.

If none matches then don't display either of the two rows.
If row data is blank for one of the fields then don't display them.

Views Conditional

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

  Equal To
  Not Equal To
  Greater Than
  Less Than
  Empty
  Not Empty

  Views conditional allows you to output text based on the result of the
  condition.


How to check if a user is logged in inside a view I can easily check if a user is logged in in most templates by simply using a twig variable, or making a custom one myself. My issue is that I would like to be able to check if a user is logged in inside a custom text field in a view.

I used

{% if logged_in %}
     Test
{% endif %}

But it didn't seem to work. Also

{{ dump(logged_in) }}

came up null. Also I looked in the available options for context filters and relationships but nothing seemed to have anything to do with the current user. Only authors of the content.
Is there a way to know if the user is logged in from a view?

I suspect that it might be possible with some preprocess hook for views but if that can be avoided by using an option in views that would be preferable.

For clarification this is a view that displays a list of articles. Each with an image, title, and a snippet of body text. The article node has a field deciding whether a user login is required. If the user login is required then the body text is replaced for anyone that isn't logged in.

UPDATE: I attempted adding the variable in a preprocess hook but that didn't seem to do anything either.

function mymodule_preprocess_views_view_field(&$variables){
    $variables['logged_in'] = (\Drupal::currentUser()->isAnonymous())?false:true;
}

But {{ dump(logged_in) }} still came up null.

I managed to accomplish this task by creating my own custom view field plugin

in mymodule.views.inc I used

function mymodule_views_data() {

  $data['views']['table']['group'] = t('Current User');
  $data['views']['table']['join'] = [
    // #global is a special flag which allows a table to appear all the time.
    '#global' => [],
  ];

  $data['views']['logged_in'] = [
    'title' => t('Logged In'),
    'help' => t('Check if user is logged in'),
    'field' => [
      'id' => 'logged_in',
    ],
  ];

  return $data;
}

and then in /mymodule/src/Plugins/views/field/LoggedIn.php I had

<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("logged_in")
 */
class LoggedIn extends FieldPluginBase {

    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
        parent::init($view, $display, $options);
        $this->field_alias = 'logged_in';
    }

    /**
     * {@inheritdoc}
     */
    public function usesGroupBy() {
        return FALSE;
    }

    /**
     * {@inheritdoc}
     */
    public function query() {
        // Do nothing -- to override the parent query.
    }

    /**
     * {@inheritdoc}
     */
    protected function defineOptions() {
        $options = parent::defineOptions();

        return $options;
    }

    /**
     * {@inheritdoc}
     */
    public function render(ResultRow $values) {

        $logged_in = \Drupal\mymodule\Modules\CurrentUser::isLoggedIn();
        return $logged_in;
    }

}

Some of the contents of LoggedIn.php might not be necessary (not 100% sure) I was using another module as an example.


Can't filter Calendar according to event date instead of date added Hi I'm trying to figure out this issue as well. i have calendar that only shows the dates the event has been posted, not the actual start date for which I created the field.
I can't seem to filter dates according to their start day. When I try to filter it, it's not giving me the date field option. :( Can someone direct me toward good tutorial or help me set it up. Thank you in advance.

You need to set up the Date argument. See Drupal therapy's video tutorial on this http://www.drupaltherapy.com/date. Also here's an output a properly configure calendar view

$view = new view;
$view->name = 'calendar';
$view->description = 'A multi-dimensional calendar view with back/next navigation.';
$view->tag = 'Calendar';
$view->view_php = '';
$view->base_table = 'node';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('fields', array(
  'title' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 1,
    'exclude' => 0,
    'id' => 'title',
    'field' => 'title',
    'table' => 'node',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Override',
    ),
  ),
  'field_date_value' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'none',
    'format' => 'time_only',
    'multiple' => array(
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_to' => '',
      'group' => 0,
    ),
    'repeat' => array(
      'show_repeat_rule' => 'hide',
    ),
    'fromto' => array(
      'fromto' => 'value',
    ),
    'exclude' => 0,
    'id' => 'field_date_value',
    'table' => 'node_data_field_date',
    'field' => 'field_date_value',
    'relationship' => 'none',
  ),
));
$handler->override_option('sorts', array(
  'sticky' => array(
    'order' => 'DESC',
    'id' => 'sticky',
    'table' => 'node',
    'field' => 'sticky',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
  ),
  'field_date_value' => array(
    'order' => 'ASC',
    'delta' => '-1',
    'id' => 'field_date_value',
    'table' => 'node_data_field_date',
    'field' => 'field_date_value',
    'relationship' => 'none',
  ),
));
$handler->override_option('arguments', array(
  'date_argument' => array(
    'default_action' => 'default',
    'style_plugin' => 'default_summary',
    'style_options' => array(),
    'wildcard' => 'all',
    'wildcard_substitution' => 'All',
    'title' => '',
    'breadcrumb' => '',
    'default_argument_type' => 'date',
    'default_argument' => '',
    'validate_type' => 'none',
    'validate_fail' => 'not found',
    'date_fields' => array(
      'node_data_field_date.field_date_value' => 'node_data_field_date.field_date_value',
    ),
    'year_range' => '-1:+1',
    'date_method' => 'OR',
    'granularity' => 'month',
    'id' => 'date_argument',
    'table' => 'node',
    'field' => 'date_argument',
    'relationship' => 'none',
    'default_argument_user' => 0,
    'default_argument_fixed' => '',
    'default_argument_php' => '',
    'validate_argument_node_type' => array(
      'product' => 0,
      'event' => 0,
      'audio' => 0,
      'blog' => 0,
      'gallery' => 0,
      'gallery_image' => 0,
      'page' => 0,
      'simplenews' => 0,
      'story' => 0,
      'video' => 0,
    ),
    'validate_argument_node_access' => 0,
    'validate_argument_nid_type' => 'nid',
    'validate_argument_vocabulary' => array(
      '1' => 0,
    ),
    'validate_argument_type' => 'tid',
    'validate_argument_php' => '',
    'override' => array(
      'button' => 'Override',
    ),
    'default_options_div_prefix' => '',
    'validate_user_argument_type' => 'uid',
    'validate_user_roles' => array(
      '2' => 0,
      '3' => 0,
    ),
    'validate_argument_transform' => 0,
    'validate_user_restrict_roles' => 0,
  ),
));
$handler->override_option('filters', array(
  'status' => array(
    'operator' => '=',
    'value' => 1,
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'status',
    'table' => 'node',
    'field' => 'status',
    'relationship' => 'none',
  ),
  'type' => array(
    'operator' => 'in',
    'value' => array(
      'event_product' => 'event_product',
      'event' => 'event',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'type',
    'table' => 'node',
    'field' => 'type',
    'relationship' => 'none',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
  'role' => array(),
  'perm' => '',
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler->override_option('title', 'Calendar');
$handler->override_option('header_empty', 1);
$handler->override_option('items_per_page', 0);
$handler->override_option('use_more', 0);
$handler->override_option('style_plugin', 'calendar_nav');
$handler = $view->new_display('calendar', 'Calendar page', 'calendar_1');
$handler->override_option('fields', array(
  'title' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 1,
    'exclude' => 0,
    'id' => 'title',
    'field' => 'title',
    'table' => 'node',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Override',
    ),
  ),
  'field_date_value' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 1,
      'text' => '([field_date_value])',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'none',
    'format' => 'time_only',
    'multiple' => array(
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_to' => '',
      'group' => 0,
    ),
    'repeat' => array(
      'show_repeat_rule' => 'hide',
    ),
    'fromto' => array(
      'fromto' => 'both',
    ),
    'exclude' => 0,
    'id' => 'field_date_value',
    'table' => 'node_data_field_date',
    'field' => 'field_date_value',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Use default',
    ),
  ),
));
$handler->override_option('path', 'calendar');
$handler->override_option('menu', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler->override_option('calendar_colors', array(
  '0' => array(),
));
$handler->override_option('calendar_colors_vocabulary', array());
$handler->override_option('calendar_colors_taxonomy', array());
$handler->override_option('calendar_colors_group', array());
$handler->override_option('calendar_popup', 0);
$handler->override_option('calendar_date_link', '');
$handler = $view->new_display('calendar_block', 'Calendar block', 'calendar_block_1');
$handler->override_option('block_description', 'Calendar');
$handler->override_option('block_caching', -1);
$handler = $view->new_display('calendar_period', 'Year view', 'calendar_period_1');
$handler->override_option('style_plugin', 'calendar_style');
$handler->override_option('style_options', array(
  'display_type' => 'year',
  'name_size' => 1,
  'max_items' => 0,
));
$handler->override_option('attachment_position', 'after');
$handler->override_option('inherit_arguments', TRUE);
$handler->override_option('inherit_exposed_filters', TRUE);
$handler->override_option('inherit_pager', FALSE);
$handler->override_option('render_pager', TRUE);
$handler->override_option('displays', array(
  'calendar_1' => 'calendar_1',
  'default' => 0,
  'calendar_block_1' => 0,
));
$handler->override_option('calendar_type', 'year');
$handler = $view->new_display('calendar_period', 'Month view', 'calendar_period_2');
$handler->override_option('fields', array(
  'title' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 1,
    'exclude' => 0,
    'id' => 'title',
    'field' => 'title',
    'table' => 'node',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Override',
    ),
  ),
  'field_date_value' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 1,
      'text' => '([field_date_value])',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'none',
    'format' => 'time_only',
    'multiple' => array(
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_to' => '',
      'group' => 0,
    ),
    'repeat' => array(
      'show_repeat_rule' => 'hide',
    ),
    'fromto' => array(
      'fromto' => 'both',
    ),
    'exclude' => 0,
    'id' => 'field_date_value',
    'table' => 'node_data_field_date',
    'field' => 'field_date_value',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Use default',
    ),
  ),
));
$handler->override_option('style_plugin', 'calendar_style');
$handler->override_option('style_options', array(
  'name_size' => '2',
  'with_weekno' => '0',
  'max_items' => '0',
  'max_items_behavior' => 'more',
  'groupby_times' => 'hour',
  'groupby_times_custom' => '',
  'groupby_field' => '',
));
$handler->override_option('attachment_position', 'after');
$handler->override_option('inherit_arguments', TRUE);
$handler->override_option('inherit_exposed_filters', TRUE);
$handler->override_option('inherit_pager', FALSE);
$handler->override_option('render_pager', TRUE);
$handler->override_option('displays', array(
  'calendar_1' => 'calendar_1',
  'default' => 0,
  'calendar_block_1' => 0,
));
$handler->override_option('calendar_type', 'month');
$handler = $view->new_display('calendar_period', 'Day view', 'calendar_period_3');
$handler->override_option('style_plugin', 'calendar_style');
$handler->override_option('style_options', array(
  'name_size' => '99',
  'with_weekno' => 0,
  'max_items' => 0,
  'max_items_behavior' => 'more',
  'groupby_times' => 'hour',
  'groupby_times_custom' => '',
  'groupby_field' => '',
));
$handler->override_option('attachment_position', 'after');
$handler->override_option('inherit_arguments', TRUE);
$handler->override_option('inherit_exposed_filters', TRUE);
$handler->override_option('inherit_pager', FALSE);
$handler->override_option('render_pager', TRUE);
$handler->override_option('displays', array(
  'calendar_1' => 'calendar_1',
  'default' => 0,
  'calendar_block_1' => 0,
));
$handler->override_option('calendar_type', 'day');
$handler = $view->new_display('calendar_period', 'Week view', 'calendar_period_4');
$handler->override_option('style_plugin', 'calendar_style');
$handler->override_option('style_options', array(
  'name_size' => '99',
  'with_weekno' => 0,
  'max_items' => 0,
  'max_items_behavior' => 'more',
  'groupby_times' => 'hour',
  'groupby_times_custom' => '',
  'groupby_field' => '',
));
$handler->override_option('attachment_position', 'after');
$handler->override_option('inherit_arguments', TRUE);
$handler->override_option('inherit_exposed_filters', TRUE);
$handler->override_option('inherit_pager', FALSE);
$handler->override_option('render_pager', TRUE);
$handler->override_option('displays', array(
  'calendar_1' => 'calendar_1',
  'default' => 0,
  'calendar_block_1' => 0,
));
$handler->override_option('calendar_type', 'week');
$handler = $view->new_display('calendar_period', 'Block view', 'calendar_period_5');
$handler->override_option('style_plugin', 'calendar_style');
$handler->override_option('style_options', array(
  'display_type' => 'month',
  'name_size' => '1',
));
$handler->override_option('attachment_position', 'after');
$handler->override_option('inherit_arguments', TRUE);
$handler->override_option('inherit_exposed_filters', TRUE);
$handler->override_option('inherit_pager', FALSE);
$handler->override_option('render_pager', TRUE);
$handler->override_option('displays', array(
  'calendar_1' => 0,
  'default' => 0,
  'calendar_block_1' => 'calendar_block_1',
));
$handler->override_option('calendar_type', 'month');
$handler = $view->new_display('block', 'Upcoming', 'block_1');
$handler->override_option('fields', array(
  'title' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 1,
    'exclude' => 0,
    'id' => 'title',
    'field' => 'title',
    'table' => 'node',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Override',
    ),
  ),
  'field_date_value_1' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'none',
    'format' => 'time_only',
    'multiple' => array(
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_to' => '',
      'group' => 0,
    ),
    'repeat' => array(
      'show_repeat_rule' => 'hide',
    ),
    'fromto' => array(
      'fromto' => 'both',
    ),
    'exclude' => 1,
    'id' => 'field_date_value_1',
    'table' => 'node_data_field_date',
    'field' => 'field_date_value',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
  'field_date_value' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 1,
      'text' => '[field_date_value] <br />([field_date_value_1])',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'none',
    'format' => 'date_no_time',
    'multiple' => array(
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_to' => '',
      'group' => 0,
    ),
    'repeat' => array(
      'show_repeat_rule' => 'hide',
    ),
    'fromto' => array(
      'fromto' => 'both',
    ),
    'exclude' => 0,
    'id' => 'field_date_value',
    'table' => 'node_data_field_date',
    'field' => 'field_date_value',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Use default',
    ),
  ),
  'field_teaser_value' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 1,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'none',
    'format' => 'default',
    'multiple' => array(
      'group' => TRUE,
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_reversed' => FALSE,
    ),
    'exclude' => 0,
    'id' => 'field_teaser_value',
    'table' => 'node_data_field_teaser',
    'field' => 'field_teaser_value',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('arguments', array());
$handler->override_option('filters', array(
  'status' => array(
    'operator' => '=',
    'value' => 1,
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'status',
    'table' => 'node',
    'field' => 'status',
    'relationship' => 'none',
  ),
  'date_filter' => array(
    'operator' => '>=',
    'value' => array(
      'min' => NULL,
      'max' => NULL,
      'value' => NULL,
      'default_date' => 'now',
      'default_to_date' => '',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'date_fields' => array(
      'node_data_field_date.field_date_value' => 'node_data_field_date.field_date_value',
    ),
    'date_method' => 'OR',
    'granularity' => 'day',
    'form_type' => 'date_select',
    'default_date' => 'now',
    'default_to_date' => '',
    'year_range' => '-1:+1',
    'id' => 'date_filter',
    'table' => 'node',
    'field' => 'date_filter',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('title', 'Upcoming Events');
$handler->override_option('items_per_page', 4);
$handler->override_option('use_more', 1);
$handler->override_option('use_more_always', 1);
$handler->override_option('use_more_text', 'view calendar');
$handler->override_option('style_plugin', 'default');
$handler->override_option('style_options', array(
  'grouping' => '',
));
$handler->override_option('block_description', 'Upcoming');
$handler->override_option('block_caching', -1);


How can I use drupal_static() to save an element in an associative array? I'm making repeated calls to a few related object instances, and I need to cache them in memory.

If I have an array of objects, like:

array('object_a' => $obj_a, 'object_b' => $obj_b);

I want to do something like:

$obj_a = getmyobj('object_a');

Where the object is created if it doesn't exist in memory already.

You can use drupal_static to store an array of object.

You can then define a method, lets call it 'getmyobj', to get your data like this :

function getmyobj($obj_name) {
  $objects = &drupal_static(__FUNCTION__);

  if (! isset ($objects[$obj_name])) {
    // Here you load your obejct
    $objects[$obj_name] = method_to_load_your_object($obj_name);
  }
  return $objects[$obj_name];
}

Then you will be able to get you object with the above code :

$obj_a = getmyobj('object_a');


Categorize without taxonomy How can we categorize things on our site without using taxonomy. I have learned Taxonomy but want to know how to categorize things without Taxonomy.
Can anyone help me Please.

You could always add "List" field type to your custom content type. By default you could choose between lists of Text, Integer and Float. While configuring you could choose whether or not it will be checkboxes, radio buttons or select lists.
Later in Views you could filter content with use of these fields.

It's in Drupal core, no additional modules (except of Views of course)


Is it possible to add css class to the page's body tag with rules when certain conditions are met? I seem to have read that there is a way of making Rules add a css class to the body tag, but I can't find out how to do it. Any ideas?

Yes - the Context module allows you to add CSS classes to the body (Theme HTML condition) based on whatever events you specify. You would then combine this with the Context Rules module which extends Context to allow for context events from Rules.


Can I get a upload progress bar when submitting the form with "submit"? In D7, I've got some forms that are responsible for uploading potentially large video files via managed_form fields.  My server is properly set up for showing uploadprogress (or seems to be, according to phpinfo and Drupal's status report), but when I submit the form via the Submit button, I get no progress bar.  Is this just "how it works"?

It's probably worth noting that I've hidden the "Upload" button after a long series of usability problems with my site's users, so that may be a blindingly obvious factor in my problem.  But I'm still interested in getting some sort of upload indication in response to the Submit button; I'm not averse to bashing some stuff into the page via a jQuery .submit() handler or whatever if that's what it takes.  Is there a way for me to have my cake and eat it too?  Thanks!

Is this just "how it works"? - Yes, it's just how it works. This is a problem with HTTP protocol, if your site does not provide client-side implementation for that progress bar, it will not be shown. And Drupal forms are standard HTML / HTTP POST forms, so no implementation provided for traditional, old style POST.

What I do in such situations is:

With plupload

uploader.bind('QueueChanged', function() {

to automatically start upload and disable form's submitting. Then

uploader.bind('StateChanged', function() {

to reenable form's submitting once upload is done.

Without plupload

AutoUpload module has some good example code how to react on file selection and upload finish. I steal from it to do basically the same thing as above - disable form submitting when new file is added, enable it when it's uploaded. Alternatively, form submit behavior may start uploading files not yet uploaded, and only submit form when uploads finished.

Without traditional POST

If you can give up traditional submit, and re-write it with AJAX, leaving traditional way in place for graceful degradation, you can have a progress bar for a whole form. But it is a quite big task, too broad to cover in Q&A format (at least for me).


Compile files from URLs in table as zip I've got a Views table with a column displaying links to files (images, pdf's etc.). I've got a button below the table that exports the entire table. I need another button that should start a .zip download of all images currently shown in the table. The table has a filter on it, so it's important that only the files from the filtered results are downloaded.

I haven't been able to find a module or similar use case, so I hope there's someone here that can point me in the right direction.

Cheers,

Enable the PHP input filter and add a text area to the footer of your view, then use something like the following to build an array of all of your files (taken from this tutorial):

<?php
function views_get_current_view_result() {
  $view = views_get_current_view();
  return $view->result;
}
?>

And then use that array to build the zip according to download multiple files as zip in php

This would be a lovely idea for a views display handler plugin module, which many would probably find useful.


How to get value from form field in rule? I created a webform, and a rule. The rule works on the "form submit" event.

How do I get the value from a webform field in this rule event?

You have to use - %value[key] means - enter filed key name, for example: %value['first_name']. You will find this key name by following steps:

Go to webform -> Form components -> edit -> you can find the entered "field key" value.


Create new content type with a user reference I have a process of adding contents where user1 has to search for user2, when user2 is found, there is a button that adds a specific content type (i.e. "Create a report for this user") for the searched user. then it goes to a page where i can enter information and save the content. how can i do this?

Your user selection/search process may need some custom work to implement the various node-reference modules in the way you've described, but there are several modules that may do what you need out of the box. The References module will be easier to implement while creating new content, but the Relation module may be more agile as you can add fields to your relations, 'user report' for example.

I would be happy to elaborate if you'll clarify your user selection process.

1 - References

This adds a field to an already created content type.  Generally simpler to implement.

  This project provides D7 versions of the 'Node reference' and 'User
  reference' field types, that were part of the CCK package in D6, at
  functional parity with the D6 counterparts. See
  http://drupal.org/node/533222 for details.

Video Series (NodeOne) Using the Reference module

2 - Relation

Rather than being a 'field' on an already created content type this is for all intents and purposes a new content type.  Relations are fieldable as well, so adding the 'report' fields you need will be easy.

  Relation is an API module and storage model for both simple and the
  most complex relations between entities. The module can handle both
  directional and symmetrical relations very well.

Video Series (NodeOne) Learn the Relation Module


How to setup node references im creating website for racing events, basically website have added all races that are happening during one year, and it stores data for previous races. I was asked to move from website from .net N2CMS to Drupal.

Im having problems with setting up proper content types and their references.

In the old website they have added several races. Every race node contains basic details ( town, country, best time, website url... ) and besides that details every race have data about previous years winners ( Name, Timings, Car ).

On the main race node there is this basic data and bellow that there are results from latest 5 years with ability to expand and show all previous years.

So its clear to me how to make main race content type and add fields, but i was wondering how to make it easy for admin to add winners of previous years, and this has to be modular as much as possible, because some races have this data all the way down to 1972, but yet some of them have just few years back.

So i guess some kind of node reference should be used here but just dont have it clear in my head what i need to do.

Sorry if my questions is not clear, i tried to explain it so that everyone can understand it.

Thanks

You can create two content types

Race Details
Race Standings

Node reference to Race Details as a field
Year
A Field Collection with details (Fields) like

Race Winner Name
Timings
Car
Position etc


background-image and sites.php I have a multisite configuration with Drupal7, my prod site is mysite.example.mydomain.com and dev is mysitedev.example.mydomain.com I have set in sites/sites.php :

$sites = array('mysite.example.mydomain.com' => 'mysitedev.example.mydomain.com',
);

so searching for sites/mysite.example.mydomain.com would result as sites/mysite.dev. example mydomain.com, but I have a background Image Url:

background: url("/sites/mysite.example.mydomain.com/files/myimage.jpg");

if the Url is /sites/mysitedev.example.mydomain.com/files it works, otherwise with /sites/mysite.example.mydomain.com/files it don't!
What am I missing???

Thanks.

It sounds like you're confusing hostnames with file system paths.

The array mapping in sites.php is:

Hostname => Instance Folder

So taking your example, requests for http://mysite.example.mydomain.com will use the folder /sites/mysitedev.example.mydomain.com.

In that scenario, the path /sites/mysite.example.mydomain.com/files doesn't exist, so requests for files under it will return a 404. That's to be expected.

You can always add an alias/redirect via your server config, but it might be best to just use the system as it was intended.


Using Drupal as a server application user front-end (feasability question) I am very new to Drupal. I am currently watching videos and reading many online tutorials. I came to Drupal, because I understand it is a good CMS system (at least recommended by many, and the more I learn, the more I agree).

But, the more I learn, the more I am wondering whether it could solve another of my needs: acting as a user front-end for a server-side application. Let me describe this.

I have a couple of experts entering technical information in a system (i.e. database). I understand I can create specific screens with specific fields in Drupal (that's great, no coding) and that it would be stored in the database when ready.
After information is entered by experts, heavy time and cpu consuming asynchronous processes should be started in background and resulting information stored in the database.
Next, users should be able to read results with another screen in Drupal.

Instead of performing the heavy processes on the web-server, I was wondering whether I could use another server to connect to the drupal database instance (with a deamon application written in Java for example), perform the heavy duty tasks, and store the information in that same database.

My questions are:

Is this realistic? Has anyone attempted this?
Is it easy for a 3rd party application to read data from a Drupal database and store results in it? Does Drupal offer specific modules faciliting this? Any documentation or tips available?

Thanks.

Absolutely.

Do not be put off by the 'CMS' label, Drupal is actually quite a framework in itself.  Drupal really does a good job for small to mid-sized applications, as the application gets larger though one has to tweak and push the limit a bit more. To be fair, this is true of most any PHP application.

I have built quite a few applications myself that leverage the power of Drupal, some internal, some public: production management, calendaring applications, rental/item reservation for 4000 items +, mailing list management, (and more).

In my (very humble) opinion, Drupal saves a lot of time, especially for the 'user-management' aspect of application building. As a bonus, you have the rest of the framework to play with when developping your app.

Hope that helps, happy coding, good-luck!


Display suite fields visibility restriction Is there a way in DS fields visibility restriction with url pattern?

Yes. You can create a custom view mode with DS, add or remove fields as you wish, configure that view mode to use a DS layout, then access the view mode through a URL.

The structure looks like this for the "full" view mode: node/x?v=full.

You need to enable a DS Extra setting called "View mode per node" at admin/structure/ds/list/extras


Empty  items within Rules UI Has anyone encountered behaviour similar to this and have any idea how to resolve it? I've checked the issues for Rules and can't find anything similar. I've run update.php and flushed caches, neither make a difference. Also tried completely uninstalling Rules and Rules UI and reinstalling from fresh.

This is odd, but it's probably not rules-centric.  It looks like the system itself is in a funky state.  Have you had any other problems with white screens?  Do your mysql logs show any errors (I have seen similar problems when the max_allowed_packet size was too small, for example, or when the mysql server ran out of disk space.)


How to obtain the average of the number of a field according to the term of taxonomy? I am using the default view Taxonomy term.

I added a "number" field to my article content type.

I would like to obtain the average of the fields of the nodes listed by term of taxonomy.

For example, I have two nodes, which have as fields numbers: 2 and 4, and whose term is common taxonomy: A.

I would like in the view of the term taxonomy A, get the average of the fields "number" of these nodes, namely 3.

I tried views aggregation, add two fields: a field of type "Content: title", with aggregation: Group together, and a field of type "AVG (Content: Note)", with aggregation: "Average".

But it does not work.

I tried to add different relationships, but without success.

Someone would know the right configuration of views to do that? Thank you

I'm not aware of a configuration that can do that out of the box on the Content type Views. But if it must be that exact Taxonomy Terms Views you can do it with the help of an additional module (check out Views Calc and Views Aggregator Plus).

But if you only want the result, to show the Average number on Term pages, then you can create a different View, of type Taxonomy term and display it as a Block on term pages. This type will work without additional modules.

Create Term Views type
Filter to your Vocabulary, filter Note field to be Not empty
Add the Taxonomy Name field, just to test, you'll see terms listed in separate Views rows
Add the Relationship to all content using the field Content using Note, (Relate each Content with a Note set to the term.) You can require this Relationship
DO NOT add any Sort criteria, sorting often messes up Aggregation
Add the Note Field, it will show separate Nodes' Note numbers in separate Views rows
Turn ON Aggregation
Edit the Note Field Aggregation and set it to Average, Group column Value

You should now again only see individual terms in rows, and the Note will show the average number calculated
Check the Note field Formatter, the Default might round the numbers not to show decimal places, Unformatted might show more
If this is all working the last thing to do is to add a Contextual filter to filter according to the term page you're viewing: Add the Contextual for the field relating to your relevant Taxonomy terms and configure it:
 When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from term page
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID

Now you can enter a term ID into Preview field and you'll see what the block will display on that term's taxonomy page.

Place the block in a region, configure the block, limit the Visibility to term pages etc.


Exposed filters submit with AJAX not working - regular submit instead I created and customized exposed forms. When I change some values I change exposed filters widgets accordingly. Then I call submit with JavaScript, but my form is send with regular submit not like I checked on Views Advanced Settings form to use AJAX. What could be wrong with that? Pagination also change current URL.

-- edit --
When I click on item connected with exposed filter I execute this code:

$('#category-product-finder .frame a').each(function() {
    var $a = $(this);
    var $exposed_filter = $('#views-exposed-form-product-finder-page');
    $a.click(function(e) {
        e.preventDefault();
        $exposed_filter.find('#edit-product-category').val($a.attr('rel'));
        $('#views-exposed-form-product-finder-page').trigger('submit');
    });
});

And this make my form to submit without using AJAX.

Found a solution. Ambidex idea is the key. My problem was that I didn't have printer classess within views-view--XXXX.tpl.php. After this everything works OK and there is something like "view-dom-id-82374yrcnuerhnw875yt3o8743y" (first line of Ambidex code) class added, which is probably needed by AJAX calls.


Updating / Pushing Changes to a Views from Local to Staging Server? I'm working on a complex view which is from an existing view that currently just needs a bunch of fields and exposed filters added. I have it working on my local desktop and now I want to make these same changes on the Staging/Dev server. How can I update the server without doing everything from scratch?

If your working on an existing View and not a new one, you can just use the import View option on your server. Once you click into that page just check off the following:

Replace an existing view if one exists with the same name

It will update the existing view with what you have done on the local. On your local desktop just click on export on the view and copy and paste the code given to the server Views import page.


Adding Boolean or Tag to Image File Field I am using File Entity and have added a boolean to the image file field. This checkbox is to check when I want to make a favourite photo.

My problem is, I'm not seeing this on the node creation page, I upload the image(s) and I just still have alt and title fields available and no boolean.

I have gone through manage form display, manage display and I can see it there for Default and Thumbnail view modes.

What step am I missing?

Drupal 8

The module File Entity has it's own field widget "Editable file".

You have to change the image field to use this widget in manage form display of the content type.

Then add a new image in the node creation page and a button will appear to edit the custom fields inline.

The widget has no preview image. So you have to choose, if you want inline fields or preview images.

The File Entity module is a basic solution with a very simple user interface.

A complete media solution for D8 will be provided by the Drupal Media Initiative, here are the latest news:

http://janezurevc.name/releases-of-various-drupal-8-media-modules


How to print the URL path of a referenced node using paragraphs? I'm trying to print out the url path of a node from a referenced entity paragraph field in my twig template however have not had any success so far. I have tried various common twig functions but with no luck.

Any ideas?

Use the Twig path() function and build a node route with the target id of the reference field:

paragraph.html.twig

{% if paragraph.field_example.target_id %}
  {{ 'View node page'|t }}
{% endif %}

See https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates


How do I create a Machine Name type of field? I need to add a Machine Name type of field to Nodes of a certain Content Type. It's the same Machine Name field that Drupal is using when creating Content Types.

  Example: If I enter "My Title" in the title field, the Machine Name
  field will be populated with "my_title" via javascript.

Why do I need it? I am referencing nodes to other nodes and want to generate an URI, based on a node referenced, i.e. example.com/node-referenced/node-content

There is a machine_name element type for the Form API, but it appears there is no machine name field type in core or in a contrib module. From there, I see three code-driven solutions:

It should be possible to crudely alter your node form to replace a text-field widget with a machine name element,
but the proper way would be to define a new Field API widget type based on the machine name Form API element type.
You can also not use the Field API for, directly add a machine name element in your node edit form through a form alter hook and handle storing it's value yourself.


Convert variable_set to d8 variables i have a variable_set  defined in d6 as follows :

variable_set('cleanupeditform_formkeys', array(
 'menu' => t('Menu settings'),
 'revision_information' => t('Revision information'),
 'attachments' => t('File attachments'),
 'comment_settings' => t('Comment settings'),
 'author' => t('Authoring information'),
 'options' => t('Publishing options'),
 ));

How i can convert to drupal 8 form ? I know for a single case it would be like

\Drupal::state()->set('cleanupeditform_formkeys','my_value');

Thanks .

It's no different, you can also save an array in state:

\Drupal::state()->set('cleanupeditform_formkeys', ['foo' => 'bar']);


Show all user profiles and geolocated content on a map I'm trying to create a map that shows user profiles and other geolocated content (for example, news and events). A view doesn't allow to mix users and other content. I know I can show content that is referenced from a user, but how can I accomplish this without references?

The users and the content share the same taxonomy, though.

edit:

I have tried rovr138 suggestion to no avail, I always get the error (below image) as soon as the both views share the same display name that i have set here:

  Error: Class 'Views' not found in combine_views_views_pre_render() (row 24 in /var/www/html/myproject/web/modules/custom/combine_views/combine_views.module)

Here's the code i adapted minimally:

use \Drupal\views\ViewExecutable;

function combine_views_views_pre_render(\Drupal\views\ViewExecutable $view) {
if($view->id() == 'page_test' && $view->current_display == 'map') {

  $args = []; //these are contextual filters on the view
  foreach ($view->argument as $argument_key => $argument_value) {
    if(is_string($argument_value->argument)) {
      $args[] = $argument_value->argument;
    }
    else {
      $args[] = $argument_value->argument[0];
    }
  }

  // Get user view
  $user_view = Views::getView('event_test');
  if (is_object($user_view)) {
    $user_view->setArguments($args);
    $user_view->setDisplay('map');
    $user_view->preExecute();
    $user_view->execute();
  }

  if (!empty($user_view->result)) {
    $view->result = array_merge($user_view->result, $view->result);
  }
}
}

Alternative,

Create your 2 views. Let's say they're called, user_points and node_points and both have a display called map.

You could then create a simple module that does,

use \Drupal\views\ViewExecutable;
use \Drupal\views\Views;

function hook_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'node_points' && $view->current_display == 'map') {

    $args = []; //these are contextual filters on the view
    foreach ($view->argument as $argument_key => $argument_value) {
      if(is_string($argument_value->argument)) {
        $args[] = $argument_value->argument;
      }
      else {
        $args[] = $argument_value->argument[0];
      }
    }

    // Get user view
    $user_view = Views::getView('user_points');
    if (is_object($user_view)) {
      $user_view->setArguments($args);
      $user_view->setDisplay('map');
      $user_view->preExecute();
      $user_view->execute();
    }

    if (!empty($user_view->result)) {
      $view->result = array_merge($user_view->result, $view->result);
    }
  }
}

On your node_points view, you'll now have the results from user_points.


How to load all remaining content of a view after clicking a "load more" link? I have a view block that list contents.

What I want to do is to show only 5 items in this view and a load more link at the bottom of the view and if this link clicked, then show all remaining content of the view.

I tried the Views Load More module and the Views Infinite Scroll module. The Views Load More module didn't work, the Views Infinite Scroll module works good but I couldn't do what I want. It has an option to show X items per "show more" link clicked but it doesn't have an option to show all the remaining content of the view.

How to load all remaining content of a view after clicking a "load more" link?

You need Views show more module with ajax under views advanced setting. This module provides Initial item selection option, and rest of the item you can put in the section of on-click.

Steps-

Download and enable the module.
Select show more pager in the Pager section as shown in the image. Then go for setting for that. Now in my case I took 15 items, and I want to initially show 5 items and on clicking rest of the item. So I did put 5 under the Initial items and 10 items under Items to display as shown in second image. And under Animation section select Scroll to new content. Save this, so pager setting ends here.
Under advanced setting of views enable, Use Ajax: Yes

Views Block UI

Pager UI

Out put image:

Initial stage

After clicking show more

It does not require the page refresh to load content.


Does Composer patch core automatically? I am using Composer on a Lightning drupal distro. In my composer.json file I set enable-patching true. And I added one core patch for /patches/core-file_upload_ajax_message-1489692-68.patch. WHen I run composer update it applys 3 other patches. See output. Is Composer doing this by itself?

Applying patches for drupal/core
./patches/core-file_upload_ajax_message-1489692-68.patch (Incorrect handling of file upload limit exceeded - file widget disappears)
https://www.drupal.org/files/issues/no_hook_to_edit-2822460-2.patch (multi-value field widget hook)
https://www.drupal.org/files/issues/2652138-41.patch (2652138 - ImageFormatter does not support SVGs)
https://www.drupal.org/files/issues/1356276-303.patch (1356276 - Allow profiles to provide a base/parent profile and load them in the correct order)

Composer doesn't patch core automatically, but the cweagans/composer-patches plugin allows dependencies to patch other dependencies if:

You have enable-patching set to true in the "extra" section of your root composer.json file, or
You have at least one patch defined in your root composer.json file

In your case, it looks like Lightning is pulling in those other core patches.


CSRF token not working (access denied) I can get CSRF token to be generated on particular route by putting _crsf_token in a routing file, but on visiting that route , I keep getting an Access Denied error.

Removing CSRF token line from the routing file gives me back access to the access instantly.

What could be possibly wrong?

I have tried to make sense of Menu Callback and CSRF but don't think it is related to my problem.

@Berdir
Applying patch #14 on this page has solved the problem!
Thank you very much!

Twig template variables containing result of Drupal::url() and Drupal:l:() don't bubble up their cacheability and attachment metadata (e.g. token placeholder)