How to assign nodes to an organic group in code How can I assign a node to an organic group in code?
After consulting following page

http://www.barnettech.com/content/adding-node-organic-group-programmatically
Programmatically assign a node to an organic group

And de OG API I ended up with this code, but it throws an error 'The website encountered an unexpected error. Please try again later.'

$node = node_load(5827);
$values = array('entity type' => 'node', 'entity' => $node, 'field_name' =>'og_group_ref');
og_group('node', 3, $values);
node_save($node);

More info:
OG-7.2.7

Found out removing the last line from the snippet 'node_save($node)' and the above type error was the reason for my problem. Thanks for the support.


alternative to storing api keys in migration yaml files? I've created a yaml file to import Twitter timeline items (not super simple since documentation on the migrate_plus OAuth plugin seems to be few and far between); this migration naturally requires the use of ostensibly-secret API information. I'd like to keep this out of the yaml and I've seen answers (like this one) that talk about setting things in code, but I'm wondering if there's another customer-serviceable way. For example, here's my config file, called migrate_plus.migration.migrate_sample_twitter:

id: migrate_sample_twitter
label: Sample Twitter Migration
dependencies:
  - migrate
  - migrate_plus
status: true

source:
  plugin: url
  data_fetcher_plugin: http
  authentication:
    plugin: oauth2
    base_uri: 'https://api.twitter.com'
    token_url: /oauth2/token
    grant_type: client_credentials
    client_id: <twitter app consumer key>
    client_secret: <twitter app consumer secret>

  urls: https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=tmountjr

  fields:
    -
      name: id
      label: Tweet ID
      selector: id_str

destination:
  plugin: table
  table_name: twitter_import
  id_fields:
    id:
      type: string

Now, running drush cget migrate_plus.migration.migrate_sample_twitter drops all that information on the console, which is fine. BUT, I'm unable to retrieve any information deeper than that. What I was hoping to do was, in my settings.local.php, specify this:

$conf['migrate_plus.migration.migrate_sample_twitter.source.authentication.client_id'] = 'consumer key here'
$conf['migrate_plus.migration.migrate_sample_twitter.source.authentication.client_secret'] = 'consumer secret here'

...and then just omit the client_id and client_secret keys from the yaml file. But that doesn't seem to work; when I make those changes and run drush migrate-status I get an error: The config is missing the following key: "client_id".

So short version of this question: is there any way to omit values from an exported yaml file and instead have those values stored in a user-editable settings file that can be .gitignored from the repo?

In Drupal 8, If the migration is one that is a config entity (shows up in /config rather than in migrations/) values can be overridden in settings.php or environment specific settings.

// Set migration settings from environment variables.
$config['migrate_plus.migration.node_article']['source']['urls'] = [getenv('CMS_ARTICLE_API_URL') . '/services/articles/facilities/all'];
$config['migrate_plus.migration.node_article']['source']['headers']['apikey'] = getenv('CMS_ARTICLE_API_KEY');


How do I re-queue a test that has been postponed on Drupal.org? I'm trying to run the tests on a patch on Drupal.org.  The relevant issue is here.  The status is marked as Test request sent but more than a week has passed and the test hasn't been run.

I tried changing the issue status from Needs review to Needs work and then back to Needs review but that didn't re-queue the test.  If the test has been run, whether it succeeded or failed, there is usually a Re-test link, but since the test is marked as "test request sent" then the link does not appear.

How can I re-queue such a test?

You can post an issue to the drupal.org testbots project issue queue and get someone to look into it.


Facet blocks are not appearing, when indexed view block is called programmatically with views_embed_view I have made an indexed view of my products. In that view, i have a page and a block. If I output the block from drupal/admin/structure/block the block view is shown together with the facet blocks.

Due to some conditions, I prefer to output the indexed view block programmatically, via page.tpl.php, and views_embed_view(), the indexed view block is shown correctly but then the facets are not displayed. Here is my code:

//level 2 webshop/categorie/subcategorie
            elseif( count($url_array)==4 && $url_array[1]=="webshop"){
                // if ($url=="/webshop/auto"){
                $tax_arr=taxonomy_get_term_by_name($url_array[3],"product_categorie");
                $tax=reset($tax_arr);
                $tax_chi=taxonomy_get_children($tax->tid);
                $tax_chi_tids = "";
                $counter=0;
                foreach ($tax_chi as &$child) {
                    if ($counter == 0){
                        $chtid =$child->tid;
                    $tax_chi_tids .=$chtid ;
                    }
                    else{$tax_chi_tids = $tax_chi_tids."+".$child->tid;}
                    $counter ++;
                }
                //echo views_embed_view('product_categorieen', 'block_1',$tax->tid);
                echo views_embed_view('view_products_index_product_hh','block_1',$tax_chi_tids);
            }

For now, i have fixed it, putting the facet blocks also in the page.tpl.php, for me in the first sidebar. I iterated all active facet blocks in the block table an d then displayed each one with this code:

        $block_facet = block_load($module, $delta);
        print render(_block_get_renderable_array( _block_render_blocks(array($block_facet))));


How to rewrite VBO results? In the 'Rewrite Results' section of the 'Configure Field' popup, there are several options to rewrite the results - but not in the way I need.  I want to substitute particular strings in the output.

How can I do that?

For string changes your best bet is altering the view in a custom module. Use  hook_views_pre_render to modify the output of the fields prior to the view result being fully outputted.


How can I sort the search results alphabetically? I would like to sort the search results alphabetically in Drupal 6.
How can I do that?

You can use the search results of Views, Then you can expose a filter related with you are looking for, and assign the sort condition alphabetically. If you want to expose the sort condition, you can do this with views 3, and with views 2 using the hook query_alter().

Remember that you can use the operator 'Contains' if you want to be more laxed in the search.


Wrong path with drupal.add.js The problem occurs when a node alias consists of a backslash.

My example:

drupal_add_js(path_to_theme() . '/js/script.js', array(
    'type' => 'external',
    'scope' => 'footer',
    'weight' => 5
));

Now I have a node with the alias EXAMPLE/example.html

The path to the script.js is now domain.com/EXAMPLE/sites/all/themes/example/js/script.js and not domain.com/sites/all/themes/example/js/script.js

What do I do to make the path right?

Try making it absolute:

$options = array(
  'type' => 'external',
  'scope' => 'footer',
  'weight' => 5,
  'absolute' => TRUE
);
drupal_add_js(path_to_theme() . '/js/script.js', $options);


Edit custom field using user_presave hook during account creation I have made a custom field for user field_custom_xyz from the admin GUI.
Now after i saved it i got two tables into the database : one for data and one for revisions.
I already have a huge database into which a lot of users are already there.

I have two questions :

How can i make sure that i can assign default value to each user at the time of creation of this field?
Let's say if i have to assign a default value of 0 (or null in case i don't follow step 1).
how can i change that value at the time of new registration using  hook_user_presave ?

I want to override the default value of this field using user_presave hook in some custom module lets say 'abc' module

so far i have tried :

$account->field_custom_abc['und'][0]['value'] = 0;

but that doesn't work, any suggestions.
thanks in advance.

Try this out:

/**
 * Implements hook_user_presave().
 */
function mymodule_user_presave(&$edit, $account, $category) {
  $edit['field_custom_xyz'][LANGUAGE_NONE][0]['value'] = 0;
}


How to hide edit tab on entity form I'd like to remove the ability to edit/update an entity form once it was been completed and submitted correctly.

I thought there might be a way to lock an entity form? Or remove access? or hide the edit tab.  Any suggestions on how to accomplish this?

Thanks

You could look into hiding the tab using hook_menu_alter. If you set access callback to FALSE then it will be hidden.


How to display admin login? I have created two logo block in left and right in my page.tpl.php page.
I am not able to see admin login.

Please guide me.

if you would like to display it programmically
This might be helpful. put it inside  page.tpl.php. best of luck!

$elements = drupal_get_form("user_login");
$form = drupal_render($elements);
echo $form;


Advantages of running cron via drush rather than via curl? Are there any major advantages of triggering Drupal's cron tasks via Drush rather than via a curl call to the site? The main thing I can think of is that no web server process would be needed, when using drush. Are there other benefits?

Thanks!

Advantages is a loaded term, but I'll describe the differences.

If you compare https://github.com/drush-ops/drush/blob/master/commands/core/core.drush.inc#L647 with http://cgit.drupalcode.org/drupal/tree/cron.php?h=7.x, you'll notice that they both ultimately execute drupal_cron_run(). The only difference at the code level is what happens before that.

cron.php checks that a cron_key is passed in the query string and that maintenance_mode is not on.  It also logs to watchdog.

Drush doesn't check either of those things and uses drush_log which is very different than watchdog (see Where are logs created by drush_log() stored?).

Finally, wget uses the service configured to handle http requests (most likely Apache or Nginx) even when configured to request cron.php through localhost.  Drush is PHP running in Bash which executes the Drupal functions like  drupal_cron_run() directly.

There are several reason you may or may not want to trigger cron through an http service, but here is one use case that might help illustrate a big difference.  Let say you have a Drupal site that is moving to a new server and domain and you configure a redirect at the .htaccess level to send all http requests for olddomain.com to the new site at newdomain.com.  Requests to execute cron using wget in a crontab would also be redirected, but calls to drush would continue to run cron.  If the wget requests being redirected to the new site used the old cron_key, you would begin seeing errors about that in your logs.

Someone could make the case that the memory and CPU footprint of the Drush request is smaller, but that should be very trivial compared to what happens in drupal_cron_run().

I don't think one is necessarily better than the other, but they are different.


Bootstrap 3 - parent nav element disabled Let's say I have a menu which is structured like this:

-- About (href="/about")
----- Company (href="/about/company")
----- History (href="/about/history")
-- Offer (href="/offer")
-- News (href="/news")
-- Contact (href="/contact")

So the 'Company' and 'History' are children of the 'About' element. Now, Bootstrap automatically creates the dropdown and if I want to visit 'About' and click it, it only opens the dropdown containing the children. So I can't actually visit 'About' from the menu. How can I force the Bootstrap theme to prevent this behavior?

Any idea how to do this?

it took me ages but if you go to menu-link.func.php and take out line 33       $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';

works!!! took me like 3 weeks of reading :)


Menu function of urls I know how to use Drupal's Menu and how to manage rights to access them function of profiles but I need to show secondary menu function of urls.
For example:
- A partner menu is only shown in page where url starts with /partners/
- This partener menu becomes beneficiary if url starts with /beneficiary.

Do you idea how can I manage it ? I cannot usse session :-(

Thank you.

Try to use any of these modules. I hope any of these modules solve your issues :

NodeSymlinks

  This is useful when you want to have the same page reachable though
  multiple menu items, each with its own URL, menu trail and breadcrumb
  path.

Menu Trail By Path

  Menu Trail By Path sets the active-trail on menu items according to
  the current url.


Custom module javascript Drupal.behaviours doesn't seems to load I have a custom module which has a javascript file.  Here's the content of the javascript file:

(function ($, Drupal) {
    Drupal.behaviors.promotionalOverlayBlock = {
        attach: function(context, settings) {
            console.log("hello world")
        }
    };
})(jQuery, Drupal);

The location of javascript file:

mymodule/js/overlayblock.js

In my mymodule.libraries.yml file it has the following:

mymodule:
  js:
    js/overlayblock.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupalSettings

When I load my drupal page, I expecting to see the "hello world" in the browser console.  However, nothing show up.  I view the page html code and search for my javascript there, but I can't seems to find anything related to my javascript file.

What could be the problem here?

Here's how I attached my library through the hook_preprocess_block() I'm not sure if this is the right place to add the attached.

function mymodule_preprocess_block(&variables){
  $variables['#attached']['library'][] =
  'mymodule/overlayblock';
}

When attached make sure to use the correct name of the "library"

Inside your mymodule.libraries.yml file.  The first line is your library name.

I use a different name inside my library file, and I attached a wrong library name.

 function mymodule_preprocess_block(&variables){
     $variables['#attached']['library'][] =
      'mymodule/mylibraryname';
 }

My library file mymodule.libraries.yml

mylibraryname:
  js:
    js/promotional-overlay-block.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupalSettings


How to NOT show results on view page This is going to be a ridiculously simple question and after getting this crazy view working, I don't' know why I can't figure this out.

I have created a view from entityform and field collections.  Got everything working, displays what I want. The user clicks on the link in the nav, page opens, exposed filter is displayed, along with the results of the view which is everything in the db/view.

I only want the user to see the exposed filter when they click on the link to the view/page, then the user will add the 'item number' to the filter, click search/apply and see the results. I am hoping I don't have to create another view and link things.

How can I accomplish this?

You can set the value of the Exposed form style to "input required". This shouldn't display the items when the first view the page.

Is that what you were after?


Updating content types using Features If I have a series of existing content types in a website and I want to update those content types using a new Feature module (I added some fields), what is the correct method?

Add the entire node?  Will this update the existing content type?
Add just the new and/or modified fields?

Also, these content types were originally created by hand and not by a Feature module.  I just want to add the new fields using the Features module

With the newest version of Features, it makes it really easy to just add the fields of the content type to the feature. Features are not meant to hold content, like entire nodes. Here's a good example of a feature I've built.

(http://i.stack.imgur.com/rYC7l.png)


Views duplicate result if multiple entity reference case: I have 2 content types A & B and there is field in B which is entity reference of A and this field can hold multiple values from A "Multiple Values",
so i created view to show records from B and i added some fields from A based on relation i made in the view "Entity Referenced", the problem is i get duplicated result if this field has multiple values even if i checked distinct in the view.

so is there direct way to solve it, or i have to fix it with custom code in custom module ?

I figured out good solution which is as follow:
-A is the content type & B is the second content type
-A is field entity reference in the content type of A with multiple values.
-in the views in creating view of content type B just render the field of entity reverence A normally, by default it will render the title whether its 1 value or more.
-now the views for this field in formatter option choose Rendered Entity.
-and in view mode we can choose Tokens.
-now we got to the content type A and then go to manage display tab.
-at the bottom left in the menu click on Custom display settings and then check the option Tokens and click save.
-now in the top right tab "Tokens" display will appear, click on it.
-now we choose which field we want to appear in the view & we can control the label, value, the format. for my case i just showed 1 field without the label and with plain text format and thats was great enough with out making relation and duplicate the content.


How to customise calendar week view's day title? For example, how can I show  Jul 4 (Mon) instead of the default Mon as day title?

Y rectify like this and that seems good for me:

function template_preprocess_calendar_week(&$vars) {
$min_date = clone $vars['view']->date_info->min_date;
foreach ($vars['day_names'] as &$cell) {
 $cell['date'] = $min_date->format('j');
 $cell['data'] = $cell['data'] . ", " . $cell['date'];
 $min_date = $min_date->modify('+1 day');
}
}


How to optimize already uploaded images? Is it possible to compress or optimize images that are already uploaded to the server? What about a method to optimize the images on upload?

Goal:

Take all existing images, compress them, and then save them with the same file name and directory so that the image URLs are not broken.
On upload of an image, optimize it so we don't have to repeat #1 above.

The common approach is not to modify the uploaded original image, but to calculate additional image variations and serve those to your visitors. All image styles created in /admin/config/media/image-styles are automatically compressed, using the settings form /admin/config/media/image-toolkit


Can we add different class to first row and last row of view? Can we add different classes to first row and last row of view only ?

I have created a view of products listing in which i need to add unique class only in  first row and last row of view.

I need to implement it for creating different designs layout of each row.
In drupal 7 i did it by using below code :

 end($rows);
$last = key($rows);
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id == $last): ?>
<?php $classes_array[$id] .= ' last-element'; ?>
<?php endif; ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php print $row; ?>

How we can do the same in drupal 8?

You would probably be fine with just doing this with css ( see Beebee's comment on your post), but I will answer the question.

You can use loop.first and loop.last in twig. Here is an example I used to make it work in a menu.

<ul class="menu">
    {% for item in items %}
        {%
            set classes = [
            'menu-item',
            item.is_expanded ? 'menu-item--expanded',
            item.is_collapsed ? 'menu-item--collapsed',
            item.in_active_trail ? 'menu-item--active-trail',
        ]
        %}
        {% if loop.first %}
            <li {{ item.attributes.addClass('first-element') }}>
               {{ link(item.title, item.url) }}
               {% if item.below %}
                  {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
               {% endif %}
            </li>
        {% endif %}
        {% if loop.last %}
            <li{{ item.attributes.addClass('last-element') }}>
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            </li>
        {% else %}
            <li{{ item.attributes.addClass(classes) }}>
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            </li>
        {% endif %}

    {% endfor %}
</ul>


Why is my custom block template applying to all blocks? I have a region on my home page called home_area_1. It contains several blocks. I want those blocks to be formatted in the same way, so I created a template called block--home-area-1.tpl.php. It is formatting those blocks correctly, but it's also being applied to blocks in other regions on the home page.

What am I doing wrong? I only want the blocks in this particular region to use this template.

I'm on Drupal 7.35, and am fairly new at this.

As stated in Drupal 7 Template (Theme Hook) Suggestions, it suggests the file name structure to be like block--sidebar_first.tpl.php.

==EDITED==

In my themename.info file I declared

regions[sidebar_first] = First Sidebar

Copied the core block.tpl.php file, renamed it to block--sidebar_first.tpl.php, added "BLOCK NAKO" text.

Then I Flushed Caches. The image below is the result.

As you can see the footer region blocks doesn't have the override that I only set for blocks within the sidebar first region.


In Ubercart, can I make a "View Cart" link appear only when an item is in the user's cart? Ubercart is only a small part of our site and we only want the default cart block to appear when a user is in that shopping section. Simple enough to do with "Show block on specific pages" rules.

However, when a user navigates away from the ubercart section, the cart block disappears, but I would still want to denote that the active cart exists. I don't want users to think their cart has completely vanished.

Preferably it would be a simple, tiny "View my cart" link to the default Ubercart cart page in the Header Block region. Or even added to the end of the main site navigation menu.

So, to reiterate, how can I make a Block (or menu link) render only when an item is placed in a user's cart?

Create a block with your "View Cart" html code then set block visisbility to "Pages on which this PHP code returns TRUE (experts only)" with the following:

<?php
$items = uc_cart_get_contents();
if (count($items) > 0) {
  return true;
}
return false;
?>


How can I save multiple (checkboxes) values in a configuration entity? I have a standard config entity in Drupal 8.
I'm trying to save multiple values in the form of checkboxes.
The form itself looks like this:

As you can see it's nothing too special about it.
If I try to save it, the following exception occurs:
InvalidArgumentException: The configuration property user_role.anonymous doesn't exist. in Drupal\Core\Config\Schema\ArrayElement->get() (line 74 of core/lib/Drupal/Core/Config/Schema/ArrayElement.php).

Drupal\Core\Config\StorableConfigBase->castValue('user_role.anonymous', 'anonymous') (Line: 211)
Drupal\Core\Config\StorableConfigBase->castValue('user_role', Array) (Line: 212)
Drupal\Core\Config\Config->save() (Line: 280)
Drupal\Core\Config\Entity\ConfigEntityStorage->doSave('pl_n_6467f20669ddf097337c47aab87e3c', Object) (Line: 392)
Drupal\Core\Entity\EntityStorageBase->save(Object) (Line: 259)
Drupal\Core\Config\Entity\ConfigEntityStorage->save(Object) (Line: 364)
Drupal\Core\Entity\Entity->save() (Line: 637)
Drupal\Core\Config\Entity\ConfigEntityBase->save() (Line: 130)
Drupal\pl_notifications\Form\PLNotificationsConfigurationForm->save(Array, Object)
call_user_func_array(Array, Array) (Line: 111)
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object) (Line: 51)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object) (Line: 585)
Drupal\Core\Form\FormBuilder->processForm('p_l_notifications_configuration_add_form', Array, Object) (Line: 314)
Drupal\Core\Form\FormBuilder->buildForm('p_l_notifications_configuration_add_form', Object) (Line: 74)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 656)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Which makes perfect sense since I haven't defined that field in the ConfigEntityType.
However, I can't define it since there may be other roles added later on or rather some other roles removed.

Config (schema) defines two basic types of complex/array definitions.

Mapping:
When you have limited, known set of keys, each with a specific type, e.g. a few strings, integers, booleans and so on.

Sequence:
When you have a unlimited list of values that all have the same type but with unknown or numeric keys. Each element must have the same type. The top level in a config entity and simple config is always a mapping (the type there is a config_object or config_entity or so, but those all extend from mapping)

In your example, you would define the user roles as type sequence in config schema, and as a standard php array in your config entity class.

You can also combine this in any way you can imagine, you have a mapping, one key is a list, each element is a mapping, and so on.


drupal webform styling pages I have a form that I created using webform. I have it styled like I want on the client side but whenever I view the submissions or edit the submissions I would like to style that portion as well on the admin side but cannot find a way to style these. Can some provide some help regarding how to handle this?

Have you considered ThemeKey?

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on
  current path, taxonomy terms, language, node-type, and many, many
  other properties.


CKEditor generates  when leaving a textarea field empty I'm using CKEditor module with satisfaction, but it behaves really frustrating in one case: when leaving textareas empty, it generates
 tags in them after rendering CKEditor's interface.

This can be a problem for example when using "Summary or trimmed" display, and on the node creation form, the Summary field would be left empty, but in fact it's not empty, because it contains a
 (so teaser will also contain a single
).

I can get round this problem with going to Source view and deleting the
 tag all the time, but it's not a solution (other users will not know how to do it).

Do you have any ideas how to stop this behavior?

There is an issue tracking this problem on drupal.org - http://drupal.org/node/550428. There is a patch in comment number 49 for it, hope it helps.


Views attach not working in my theme I can't seem to get views attach to work in the theme I've created... is there maybe a line of code I'm missing that needs to be included in page.tpl.php for it to work?

Thanks!

Pretty sure you can just do:

<?php
$viewName = 'WHATEVER';
print views_embed_view($viewName);
?>


How can I tell boost cron run to delete a file If I have a custom module that maybe adds some fields, or reorders some data which is to be shown in the frontend: How do I tell boost, that the cached files should be deleted on the next cron run after I've made some changes?

First you need to set a flag which indicates that new fields are added. Can be a variable_set() or something similar thats stores values in DB whenever new fields are added.

In your hook_cron() you should check if the flag is set or not. If set clear Boost cache using boost_cache_clear_all(). Unset the flag once cache is cleared.


Configure connection to mongodb for querying only We have an external mongodb instance and we need to query data from it and bring it to Drupal 8 site.

On shell this is how we connect (mongodb is running in a different container than drupal)
mongo --host docker_mongo --ssl --sslCAFile=/etc/ssl/mongodb-cert.crt

Adding the following at settings.php does not work and status report shows "No database aliases found in settings. Did you actually configure your settings ?"

$configureMongoDb = function (array $settings): array {
  $settings['mongodb'] = [
    'clients' => [
      // Client alias => connection constructor parameters.
      'mymongo' => [
        'uri' => 'mongodb://docker_mongo:27017',
        'uriOptions' => ['ssl=true&sslCAFile=/etc/ssl/mongodb-cert.crt'],
        'driverOptions' => [],
      ],
    ],
    'databases' => [
      // Database alias => [ client_alias, database_name ].
      'tutorial2' => ['mymongo', 'tutorial2'],
    ],
  ];

  return $settings;
};

Could anyone suggest how to connect to a mongodb instance?

Cross-posting this question at drupal-mongodb issue as well

You don't need to set a function in settings.php to define the connection. The documentation lists this as an example:

https://fgm.github.io/mongodb/install/#settings-configuration

// In sites/default/settings.local.php.
$settings['mongodb'] = [
  'clients' => [
    // Client alias => connection constructor parameters.
    'default' => [
      'uri' => 'mongodb://localhost:27017',
      'uriOptions' => [],
      'driverOptions' => [],
    ],
  ],
  'databases' => [
    // Database alias => [ client_alias, database_name ]
    'default' => ['default', 'drupal'],
    'keyvalue' => ['default', 'keyvalue'],
    'logger' => ['default', 'logger'],
  ],
];


Page hit count not visible on pages I installed and configured statistics module and I am successful of obtaining reports. However, I wanted to view the page hit count on each page, which I am not getting. What I did:
1. Installed and configured statistics module
2.Enabled Access Log --> discard access logs older than 3 days
3. Checked count content views
4. Administer statistics and view content access statistics permission only for the administrator
5.view content hits permission for all users (authenticated/administrator/anonymous).
After all these, when I open a node or a page, I am not able to view anything related to reads or hits or page views.
Please suggest me, what should I do?

I guess you need to enable Count content views in the same configuration page and don't need to enable access log.


Exclude fields from printing in Twig I am overriding the fields template

views-view-fields--machine_name.html.twig

I want to render some Fields in a different div than the other fields.  I do not want the fields to render twice.

<div class="foo">
  {{ fields.field_events_date_start.content }}
  {{ fields.field_events_date_start_1.content }}
</div>

{% for field in fields -%}
  {{ field.separator }}
  {%- if field.wrapper_element -%}
    <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
  {%- endif %}
  {%- if field.label -%}
    {%- if field.label_element -%}
      <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
    {%- else -%}
      {{ field.label }}{{ field.label_suffix }}
    {%- endif %}
  {%- endif %}
  {%- if field.element_type -%}
    <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
  {%- else -%}
    {{ field.content }}
  {%- endif %}
  {%- if field.wrapper_element -%}
    </{{ field.wrapper_element }}>
  {%- endif %}
{%- endfor %}

If I exclude those Fields from the display in Views it hides them both when they render before and in the normal content area.

{{ content|without('field_events_date_start,field_events_date_start_1') }}

...Does not work because I am rendering Fields, not content.

How do I get the fields to render before, but be excluded later?

You would have to remove the two fields from fields.

<div class="foo">
  {{ fields.field_events_date_start.content }}
  {{ fields.field_events_date_start_1.content }}
</div>

{% for field in fields|without('field_events_date_start',  field_events_date_start_1') %}
  ...
{% endfor %}


Stay with 7.19 or hack 7.22 (to avoid the "itok" issue) First things first, I don't need a DDoS prevention mechanism in Drupal since that is my server's job.

In all my Drupal installs, I usually hide the identity of Drupal for security reasons. Image style token (itok) is also a Drupal identifier. I tried a hack to remove itok in 7.22, and found out itok is not a small implementation, which may need more work to get benefit from the community after hack.

I'm just wondering if there is a better way.

No need to hack, just add the following line to your settings.php file:

$conf['image_allow_insecure_derivatives'] = TRUE;

Source

That will stop the itok parameter from being used.

It's even been wrapped in a module if you don't fancy editing settings.php.

Image Allow Insecure Derivatives

  Provides a user interface to allow Drupal to bypass the token security check when generating image derivatives.

As a side note, trying to hide your site's identity as being a 'Drupal' site is pointless. It's known in the field as 'Security through Obscurity', and it's a waste of resources that could be spent solving real security or performance issues.

See How can I obscure what I am using to run my site? for a more in-depth explanation.


db_select() ignores condition() when used with join I want to select all rows from 'ha' table, which access column are >= 0 and node type of that nid is equal $this->ctype.

  protected function queryAlter() {

    if(isset($this->ctype)) {

        $this->query->leftJoin('node', 'n', 'n.nid = ha.nid');
        $this->query->conditions(
                db_and()
                ->condition('ha.access', 0, '>=')
                ->condition('n.type', $this->ctype));
        //dpr($this->query);
    }
    else {
        $this->query->condition('ha.access', 0, '>=');
    }
  }

$this->ctype is set and equal to 'ad'. And I have not any nodes with that type.
But db_select() ignores condition('n.type', $this->ctype) and returns all rows from ha (which NID's are not ad type).

Why this happens? And how to debug db_select() in general?

HearthbeatStream::$query is an object of the class PagerActivity which extend the class SelectQuery; this is evident from the code for HeartbeatStream::createQuery(), where the value of the property is initialized with the following line.

$this->query = db_select('heartbeat_activity', 'ha')->extend('PagerActivity');

The fact PagerActivity is an extender of SelectQuery means that every method implemented by SelectQuery is also implemented from PagerActivity.

SelectQuery::conditions() is a getter method, not a setter method. The only method to set the condition associated with a SelectQuery object is SelectQuery::condition().

The code should be re-written as:

  protected function queryAlter() {
    if (isset($this->ctype)) {
      $this->query->leftJoin('node', 'n', 'n.nid = ha.nid');
      $this->query->condition(('ha.access', 0, '>=')
        ->condition('n.type', $this->ctype));
    }
    else {
        $this->query->condition('ha.access', 0, '>=');
    }
  }

To make a comparison, this is the code executed from blog_page_user():

  $query = db_select('node', 'n')->extend('PagerDefault');
  $nids = $query
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('uid', $account->uid)
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

There are some similarities with your code:

in both the cases, the value returned from db_select() is passed to the extend() method
in both the cases, more than one condition is applied

Using the value returned from db_and() with SelectQuery::condition() is not necessary, as the constructor of SelectQuery initializes the value of SelectQuery::$where (used by SelectQuery::condition()) with the following code:

  $this->where = new DatabaseCondition('AND');

The returned value is the same returned by db_and().

function db_and() {
  return new DatabaseCondition('AND');
}


Using field values in page.html.twig Using Drupal 8.

I want to display the value of a field (field_date) at the top of my page, in the header, so I need to output it in page.html.twig. I'm having issue with this, though, which I think boil down to the scope of where variables are available.

To clarify - I can print field_date in node.html.twig no problem by just using content, but since I need it so high on the page, I'm hoping for a way to print it in page.html.twig.

I'm open to any solution, but here's a possible solution I picked up from searching on this same topic:

In THEMENAME.theme

/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
    $element = $variables['element'];

    if($element['#field_name'] == 'field_date') {
        $variables['promo_date'] = $element[0]['#markup'];
        dpm($variables['promo_date']);
    }
}

In page.html.twig:

{{ promo_date }}

In this example, the dpm does work, but the promo_date displays nothing. Doing kint(node) returns a large number of methods, but none seem to be the fields I need.  Unfortunately the solution I borrowed from was taking a page-level variable and adding it to field.twig.html, and I think the scope reversal is the problem.

If you want to see the result of your code in THEMENAME_preprocess_field() you have to put {{ promo_date }} in a field.html.twig.

But in your question you asked about the page.html.twig. To access the field value in this template, you can use the node object, which is preloaded in the page template. But only if there is a node in the url of your page. Otherwise this will return an empty string:

{{ node.field_date.value }}


display different header text if view has taxonomy term I have a view which displays different taxonomy terms, I would like to set a different "header text" depending on what term the view is filtering by. Right now whatever header text I choose I can only apply to all pages of the view. I would like to display different header text depending on what term is being filtered.

Instead of a Global: text area, you should embed another (new) view in the header.

This blog post explains how you can display the term description that way. That way you would have a different text for each term.


Change role of users after deleting referred content via rules I added an entity reference field to user referring to a type book.

I also created a rule that each time e user update that field, selecting one book, his role changes from authenticated to reader.
So let's suppose there's a book and five users pointing to that book. These five users are readers. What i would like to do is that when that book is deleted, those 5 users role change into authenticated, being no more readers.

What i need is a way to reach the referencing users when deleting a book.
I think adding multiple reference field from book to users could be kinda dirty, because there's already a connection between book and reader.

I've already created a rule that when a user change his book field, selecting no book, his role reader is revoked. I hoped that in this way, considering that when i delete a book all the users referencing to that book change automatically their referencies, their role can change too, but unfortunately it seems that this is not considered a "After updating an existing user account" condition.

How could i do that possibly using rules? If it is possible, but not via rules, can you explain me in details how can i do?

I think i resolved it by using "fetch entity by property" and looking for the entity reference field that is equal to the current removed book.
Doing that create a list that you can iterate with the loop and inside this use actions to revoke roles.


Change path prefix URL for multilanguage I''ve got my drupal 8 content in 5 languages and now I'm trying to change path prefix foreach lang (e.g: zh-hant by zh).

The problem cames when trying to edit some content type and I've got a 404 error. There's no problem for the content with the new path prefix

old url --> www.mysite.com/zh-hant/mycontent
new url --> www.mysite.com/zh/mycontent (works fine on front)
new edit url --> www.mysite.com/zh/mycontent/edit (Crashes with a 404)

your node edit link should be rather something like

www.mysite.com/zh/node/NODE_ID/edit

I guess you are using the alias of the node and you are appending "/edit", which would not work usually.


How to configure an additional field for a bundle that is created by a custom module In Drupal 8 have a custom module for which bundles are created via yaml files in its config/install folder. I need to add an additional field to the 'schema.'

My steps were:

pm-uninstall the module
delete the content type via the ui
rebuild cache
add the new yaml file (a clone of an existing file with the field name changed)
re-enable the module

This gave me an unmet dependencies error.

If I remove the file and enable the module, the bundle is created, without the field of course.

I can create the field via the ui, but then its yaml file is not present in the install folder, so the module isn't deployable as-is.

You have to add the field via the UI.
Then you can export the yml config files required by the field by

Using drush cex sync
Navigating to admin/config/development/configuration/single/export and export the changed/new files on admin/config/development/configuration manually.

Copy the new/changed files to your config/install folder and you are good to go


Using LIKE %...% in Drupal 7, Views 3 I'm trying to change the Views SQL operator from = 'String' to LIKE 'String%'.

I thought the best way to do this was through function hook_views_pre_execute(&$view) at the bottom of views.module. I tried that, but any way I edited the query it would throw an error.

For example, I tried str_replace:

function views_views_pre_execute(&$view) {
    if ($view->name == "schools")
    {
        $view->build_info['query'] = str_replace("location.city = :db_condition_placeholder_3","location.city LIKE '".$view->build_info['substititions']['%2']."'",$view->build_info['query']);
    }
}

I expected this code to edit the query so it would search location.city LIKE 'Calgary%', but instead I got Fatal error: Call to a member function addMetaData() on a non-object in [...]/sites/all/modules/views/plugins/views_plugin_query_default.inc on line 1306.

I read the documentation, but it looks like when they refer to Wildcards like %1 and %2, they're referring to arguments passed as contextual filters, as opposed to an SQL LIKE %...% wildcard.

What am I doing wrong?

I wound up using the Computed Field module to create a custom SQL query.


Drupal 7 - How do I parse JSON data from a website and import them as Nodes and have them update hourly? I have drupal 7 with the Feeds and FeedsJSONParser module installed, but I can't seem to figure out how to configure this to parse the feeds.

I want to parse the following feeds into their own nodes: https://poloniex.com/public?command=returnTicker

{
    "BTC_LTC": {
        "last": "0.0237",
        "lowestAsk": "0.02383797",
        "highestBid": "0.0237",
        "percentChange": "0.00642712",
        "baseVolume": "5.69603109",
        "quoteVolume": "240.78778654",
        "isFrozen": "0"
    },
    "BTC_NXT": {
        "last": "0.00007000",
        "lowestAsk": "0.00007350",
        "highestBid": "0.00007000",
        "percentChange": "-0.06542056",
        "baseVolume": "0.84850609",
        "quoteVolume": "12014",
        "isFrozen": "0"
    },
    "BTC_NMC": {
        "last": "0.00403",
        "lowestAsk": "0.00489",
        "highestBid": "0.00404001",
        "percentChange": "-0.04952830",
        "baseVolume": "0.27214383",
        "quoteVolume": "64.24716761",
        "isFrozen": "0"
    }
}

I have the following settings for the JSONparser, but doesnt seem to do anything. Would someone be kind enough to take a snapshot of there setup?

I think you have a problem with the "context", and title query. I've tried this configuration and worked for me.

The context is the first query and in this case just selects all the nodes, the second one takes the value of the key "last" ant put it on the node title.

Then you can play with other querys, to create the nodes, but at least this one works.


How do I create relative menu links? I am busy working on a site on my localhost that needs to link to some content that is separate from Drupal.

I have the current menu paths set up like this: http://mylocalsite/the_folder_for_the_other_content. If I try
<front>/the_folder_for_the_other_content or /the_folder_for_the_other_content or the_folder_for_the_other_content, I get the error "The path 'whatever_I_use' is either invalid or you do not have access to it."

When I go live I obviously need all the menu items to point to http://myrealsite/the_folder_for_the_other_content.

How can I set it up so that I won't have to edit all the menu paths when I go live?

When you add a new link, the link is validated from menu_edit_item_validate(), which calls drupal_valid_path() to check if the path is valid, or it can be accessed from the user.
drupal_valid_path() returns TRUE if

The path is <front> (<front>/directory, or similar paths are excluded)
The path is an external path (the function url_is_external() returns TRUE)
The path is associated with a menu callback

Apart from using absolute URLs, the only solution is to have a custom module that defines a menu callback associated with the path you want to use.
When you use the URL that points to a file, or a directory, the web server should show that file or directory, without invoking Drupal. That is what happens with Apache, as the .htaccess file that comes with Drupal contains the following directives:

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

In your case, the custom module should contain code similar to the following:

function mymodule_menu() {
  $items = array();

  $items['the_folder_for_the_other_content/%menu_tail'] = array(
    'title' => 'Folder content',
    'page callback' => 'mymodule_view',
    'access callback' => TRUE,
    'load arguments' => array('%map', '%index'),
  );

  return $items;
}

You can use any values for title and page callback, as that menu callback should never be called. The value of access callback says to Drupal that every user has access to that menu callback.

As an alternative you can define a menu callback associated to "alias_for_directory/%menu_tail" that redirects the user to the directory you want they see (using drupal_goto()). I would use this solution when the server does not use the content of .htaccess, and it would invoke Drupal even when the URL is pointing to an existing file or directory.


how to check whether an error occurs due to a specific field in drupal? Inside a validate function how can I disallow errors for a specific field and allow errors for a specific field.
Like if I get errors for a field_abc I would like to clear that specific error and allow the form to submit.
But if I get error for a field_def I would like to restrict the submission.

This is what you are looking for:

https://api.drupal.org/comment/28464#comment-28464

Edit: Code excerpt from link:

/**
 * Custom Form Validation.
 * Removes all form validation errors caused by a 'foo][bar' form element.
 */
function my_module_form_validate($form, &$form_state) {
  $errors = form_get_errors();
  if ($errors) {
    // Clear errors.
    form_clear_error();
    // Clear error messages.
    $error_messages = drupal_get_messages('error');
    // Initialize an array where removed error messages are stored.
    $removed_messages = array();

// Remove all errors originated by the 'foo][bar' element.
    foreach ($errors as $name => $error_message) {
      if ($name == 'foo][bar') {
        $removed_messages[] = $error_message;
        unset($errors[$name]);
      }
    }

// Reinstate remaining errors.
    foreach ($errors as $name => $error) {
      form_set_error($name, $error);
      // form_set_error() calls drupal_set_message(), so we have to filter out
      // these from the error messages as well.
      $removed_messages[] = $error;
    }

// Reinstate remaining error messages (which, at this point, are messages that
    // were originated outside of the validation process).
    foreach (array_diff($error_messages['error'], $removed_messages) as $message) {
      drupal_set_message($message, 'error');
    }
  }
}


How do I modify and then render the Drupal login form in a page template in Drupal 7? I'm working on building a custom Drupal 7 theme using bootstrap. One of the things I want to achieve is a login form that is part of the standard page template, rather than sitting alone on its own login page.

Much like on pages like this, for example, where if you are not logged in, the login form sits on each page so you can log in directly from there.

I also need to modify the rendered form to use bootstrap containers and classes, so instead of just rendering the standard form, I need to wrap the form elements in divs with "col-md-4" etc classes.

Can anyone advise or direct me to any documentation on how to achieve this. I'm sure you know that for a beginner, Drupal can be very confusing!

1 )
Create the login and password empty page files and place them in your theme "templates" folder.
The name of the files are page--user--login.tpl.php and page--user--password.tpl.php. There's no need of all those steps of "hook", "alter", blablabla... Drupal will use those files automatically without any call or whatever.

2 )
Put this code inside your files.

page--user--login.tpl.php

<?php print $messages; ?>
<?php print drupal_render(drupal_get_form('user_login')); ?>
Request new password"

page--user--password.tpl.php

<?php print $messages; ?>
<?php print drupal_render(drupal_get_form('user_pass')); ?>
Go back

3 )
Done!
In thee steps. Now style your css as much you need and pimp your new fancy login page. "Inspect" your html output of your new login page and see how clean it is now. ; D

Afterwords )

I just spent this last hour reading posts and questions about this all over the internet, and the work around in some cases are simply crazy like using the dpm(get_defined_vars()); function, copying html and paste all of those input forms and attributes, blablabla.
I didn't found a concise post like this. It's crazy!!!

Also, you will need (if you still don't have it and if you want it) to disable "label/description" and enable "placehover" for the inputs. You can do it all together like this:

<?php
/*
 *  Remove labels and add HTML5 placeholder attribute to login form
 */
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if ( TRUE === in_array( $form_id, array( 'user_login', 'user_login_block') ) )
    $form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
    $form['name']['#title_display'] = "invisible";
    $form['pass']['#title_display'] = "invisible";
}
/*
 *  Remove login form descriptions
 */
function THEMENAME_form_user_login_alter(&$form, &$form_state) {
    $form['name']['#description'] = t('');
    $form['pass']['#description'] = t('');
}
?>

PS )
Do you have the "header", "footer" and "sidebar" visible and want to remove them too? No problem.
Go to admin/structure/block and click "configure". Scroll down and include this on "Show block on specific pages" option:

user/login
user/password

Done!
Drupal it's incredible powerful. I think people complicate things a lot and if you see it in a simple way it will be more efficient... Most of the things you can do it inside Drupal environment.

source: https://www.drupal.org/node/1195754


Number of item in cart at theme level I have to display number of item in cart/basket in design where I can't use the menu. So my question is...how to access number of item of cart at theme level?

Is there any function for template file which can return me this, so that I can show it in page.tpl.php ?

You can use commerce_cart_order_load() to load the order for the current user, and an EntityMetadataWrapper to extract the relevant field data, and commerce_line_items_quantity() to get at the actual quantities. e.g.

if ($order = commerce_cart_order_load($GLOBALS['user']->uid)) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $quantity = commerce_line_items_quantity($order_wrapper->commerce_line_items);

  // Do something with $quantity...
}

This code can be used in a module or theme.


Module is enabled but none of the hooks work I have created this simple module (named "youtube"):

echo 'outside function';

function youtube_view($node, $view_mode) {
   echo 'inside function<br />';

    return $node;
  }

I can only see the echo outside of the function. I've tried numerous hooks and I can't get any of them to work. The only thing different is that I am a new user to Drupal 7 and this is created on a multi site.

My structure for this module is:

sites/customsites/modules/youtube

And the site can see it fine as I have enabled it in the backend.

Do you have any idea on why this happens?

Hook implementations are cached in Drupal 7. After adding a new hook, you need to clear the cache for example using the devel block or drush cc all.

Also, hook_view() is not actually a hook. It is callback that is only invoked for the module which provides the given node type.


How can I AND two OR statements with the #states feature of Drupal 7? This page explains nicely how to use OR with the #states feature. However, when I try to AND two OR statements, It doesn't seem to AND them together. Is there a way to do this? This is what I tried.

 'visible' => array(
    array(
      array(':input[name="vehicle"]' => array('value' => 'truck')),
      array(':input[name="vehicle"]' => array('value' => 'car')),
    ),
    array(
      array(':input[name="mileage"]' => array('value' => '10')),
      array(':input[name="mileage"]' => array('value' => '20')),
    ),

  ),

I found out that this can be done this way:

$form['non_phd_student'] = array(
    '#type' => 'item',
    // This #states rule says that the "non_phd_student" item should only
    // be shown if the "student_type" form element is set to "Undergraduate" or "graduate".
    '#states' => array(
      'visible' => array(
        array(
          array(':input[name="student_type"]' => array('value' => 'undergraduate')),
          array(':input[name="student_type"]' => array('value' => 'graduate')),
        )

      ),
    ),
);
$form['non_phd_student']['thanks'] = array(
  '#type' => 'item',
  '#description' => t('Thanks for providing your graduate status and your country');
  '#states' => array(
  //Because this has ['non_phd_student']
  //The or in $form['non_phd_student'] is ANDed into the or of this statement.
  // Action to take: Make visible.
  'visible' => array(
    array(
      array(':input[name="school_country"]' => array('value' => t('Other'))),
      array(':input[name="school_country"]' => array('value' => 'UK')),
    )
  ),
),
);

There is another answer that takes more work. We can do this because AND statements can be inside the OR statements. Also, because of Propositional Logic we can get the same results this way:

'visible' => array(
  array(
    array(
      ':input[name="vehicle"]' => array('value' => 'truck'),
      ':input[name="mileage"]' => array('value' => '10'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'truck'),
      ':input[name="mileage"]' => array('value' => '20'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'car'),
      ':input[name="mileage"]' => array('value' => '20'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'car'),
      ':input[name="mileage"]' => array('value' => '10'),

    ),
  ),

),


How can I get a select drop-down menu based in terms of the a vocabulary to display in a block or a theme? I need to get a select drop-down menu based in terms of the a vocabulary.  I need to display this select drop-down in a zone of the theme or in a block not in the edit/create forms.

I have a vocabulary named:  "myterms" and I have the following list of terms in this vocabulary:

term1
term2
term3
term4

I need a menu - select -drop-down that shows term1 and term3 to select and when I put click in the term1 or term3 go to the respective page.  In the menu select drop-down won't show all terms, I need to choose the terms.

Thanks in advance for your help.

Have you tried http://drupal.org/project/entityreference? works well for me. basically your turn the field of "term" into a drop-down select on Node edit forms and a link on content.


Display error message when validating form in a specified region or div I have a Drupal 7 form, built by using Form API. I just want to validate using the hook_form_validate function, and if there are errors, display them using drupal_set_message. It is working perfectly. The problem is that in another page, I have the same form in a div, in the left side of the page, and would want the error message to appear in this region only, and not at the top of the page, where now it is appearing (that is controlled in page.tpl.php via $message variable, I think). Any idea of how could I achieve this easily?

If you use the form_set_error function instead of drupal_set_message, then the error message will be displayed within the form, which would mean that it would display inside your block.

If you would like to retain the drupal_set_message behaviour for your main form page then you would either need to differentiate which method is called in the validation based on url (or Context), or provide two separate forms so that you can simply validate each separately. In this instance you could build form and validate using a shared function to avoid duplication.


File Upload visible in $_FILES but drupal file functions create empty file I created a custom form with a file upload field:

$form['csvfile'] = array(
    '#title' => 'CSV File',
    '#type' => 'file',
);

When I submit the form, I can see the correct information in the $_FILES array:

However, when I try to use the code in the examples module to get the contents of that file and write it to an unmanaged file, the file is empty.

So, the resulting file is 0 bytes long.

How do I access the uploaded file in a drupal-y way? I know I can just use the basic PHP functions to access the file, but I'm trying to learn how to do it the way drupal intends.

My submit handler code is almost entirely lifted from the examples module.

function herdapi_form_bulkupload($form, &$form_state) {
    $form = array();
    $form['email'] = array(
        '#title' => 'Owner Email',
        '#type' => 'textfield',
    );

    $form['password'] = array(
        '#title' => 'Password',
        '#type' => 'password',
    );

    $form['csvfile'] = array(
        '#title' => 'CSV File',
        '#type' => 'file',
    );

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

    $form_state['rebuild'] = TRUE;
    $form_state['redirect'] = FALSE;

    return $form;
}

function mymodule_form_bulkupload_submit($form, &$form_state) {

    dsm($form_state);
    dsm($_FILES);
    $data = $form_state['values']['csvfile'];

    // With the unmanaged file we just get a filename back.
    $filename = file_unmanaged_save_data($data, NULL, FILE_EXISTS_REPLACE);
    if ($filename) {
        $url = file_create_url($filename);
        $_SESSION['file_example_default_file'] = $filename;
        drupal_set_message(
            t('Saved file as %filename (accessible via !url, uri=@uri)',
                array(
                    '%filename' => $filename,
                    '@uri' => $filename,
                    '!url' => l(t('this URL'), $url),
                )
            )
        );
    }
    else {
        drupal_set_message(t('Failed to save the file'), 'error');
    }
}

Drupal forms which include a file upload field must also set the encoding type to multipart/form-data.

  $form['#attributes']['enctype'] = 'multipart/form-data';

Reference: Drupal.org: Uploading Files

There is a good checklist for debugging your situation here:

https://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php

Not mentioned in the checklist there is that Suhosin, a commonly installed extension, can empty some submitted values. As well as following the checklist in the linked question, check to see if you have Suhosin installed - if so then you may be

One thing I'd try straight away is whether uploading a very small file triggers this bug. If so that might suggest that you're hitting a limit in PHP's max post data or Suhosin.


Getting the content type in Template.php I am trying to get the content type to conditionally add JavaScript code/files to the template.

The code in template.php is the following one:

echo $node->type;

The same line in "node.tpl.php" is returning the content type. How do I get it to work
in template.php?

You can put hook_preprocess_node() in your template.php.

function THEMENAME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'your_type') {
    //Add the JavaScript file.
    drupal_add_js('/path/to/jsfile.js')
  }
}


Show a block on a certain URL with wildcard How do I show a <div> inside page.tpl.php, on every page except for URLs that start with "audio/track"?

If the page is not a node (is a landing page, view, panel etc) you can use the function arg

if(arg(0) != "audio" && arg(1) != "track") {
  print "

";
}

Or if is a node you can make the conditional using a taxonomy or using the node type.

if(arg(0) == "node" && is_numeric(arg(1)) && $node->type != "your-node-type" ){
  print "

";
}


Link to small .php script on drupal page gives 404 I am new to drupal and have a page set up with a bunch of links. When clicked, the links are supposed to open up a php file (player.php, located in the root directory) in a new window. However, all I get is a 404 error. When I try to navigate to the page directly, I also get a 404 error (www.mywebsite.com/player.php).

If anyone has any suggestions on how to fix this, it would be a great help!

Make sure that your file player.php is in the right location; it should be in your Drupal root -- the same folder that has index.php.  In my test, a php file at the document root was executed correctly if it was readable by the webserver -- it would run even without execute permissions.  chmod 0 player.php gave me an internal server error, not a 404.  You should check your permissions, but this seems to not be the issue.

Is this site using your own web server configuration file, or is it on a shared or managed ISP?  Check to see if there are any rewrite rules that might be getting in the way.

The workarounds from my previous answer, below, should be unnecessary, but I will leave them here in case they may be of interest or help.

A. Put your file in a different location in the file system, and point at it with an alias.

    alias /player /srv/www/player
    <Directory /srv/www/player>
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

Put that in your Apache Virtual hosts file. If you cannot edit this file (e.g. on a shared hosting account), then this will not be an option.  If you set up your vhost conf file like this, restart Apache and put your code at /srv/www/player/player.php. Access it from www.mywebsite.com/player/player.php.

B. Instead of using a standard php file, write a Drupal menu.

function mymodule_menu() {
  $items = array();
  $items['player'] = array(
    'title' => t('Player'),
    'access callback' => TRUE,
    'page callback' => '_mymodule_player',
  );
  return $items;
}

Accessing the URL www.mywebsite.com/player will then run the code in the function _mymodule_player.

See: http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7


Programmatically remove exposed filter in a view I would like to remove a certain exposed filter on the taxonomy term view when certain conditions in the URL are met.

For example, I want to remove the "Color" exposed filter when the user is seeing the /color/red taxonomy term page, leaving only the "Shape" filter available.

Or remove the "Shape" exposed filter on the /shape/square page, leaving only the "Color" one.

The only code I could come up with is this, which is ugly and doesn't even work.

function hook_views_pre_render(&$view){
      if( CONDITIONS_ARE_MET ) {
         unset($view->filter['field_color_tid']);
         unset($view->exposed_data['field_color_tid']);
         unset($view->exposed_raw_input['field_color_tid']);
      }
}

Any ideas?

UPDATE

This is the code in mmo_views_alters:

function mmo_views_alters_views_pre_build(&$view){
    //dpm($view);
    unset($view->filter['field_tipologia_tid']);
}

This is the exported view: http://pastebin.com/JrYDmtZQ

It has 4 filters, and 3 of them are exposed.
I'm using BEF for displaying them, which generated another warning (undefined index filter-field_tipologia_tid) that I solved by patching better_exposed_filters_exposed_form_plugin.inc, line 896:

if( isset($form['#info']["filter-$label"]['value']) )
        $field_id = $form['#info']["filter-$label"]['value'];
else continue;

The warnings that I'm not able to solve are:

  Notice: Undefined index: field_tipologia_tid in
  views_handler_filter_term_node_tid->exposed_validate() (linea 258 di
  /var/www/drupal/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc).

  Notice: Undefined index: field_tipologia_tid in
  views_handler_filter_term_node_tid->exposed_validate() (linea 259 di
  /var/www/drupal/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc).

They appear even with BEF disabled.

Implement hook_views_pre_build() and unset using unset($view->filter['field_color_tid']);

Else, you can also try altering the exposed form in hook_form_alter() using the code $form['field_tipologia_tid']['#access']=FALSE;


Insert into List(Text) Field I have a Drupal content type that includes Zip Codes (Postal Codes).  An unlimited number of Zip Codes is allowed, and the Zip Codes are defined in the "Allowed Values List" in the field definition.  I have many Zip Codes that I need to insert, and have them staged them and their relationship to nodes in a temporary database table.

I do the following insert to both "field_data_field_zip_codes" and "field_revision_field_zip_codes", but I still do not see the values in the online Content.

Has someone done this type of thing before, and know what I am missing?  I looked at using "Feeds" but that module doesn't seem to support multi-value fields, just flat tables.

INSERT INTO  field_revision_field_wp_zip_codes
SELECT c.entity_type                     AS entity_type
      ,'wp_content_component'            AS bundle
      ,0                                 AS deleted
      ,c.entity_id                       AS entity_id
      ,c.entity_id                       AS revision_id
      ,'und'                             AS language
      ,(@rownum:=@rownum+1) - 1          AS delta
      ,z.zip                             AS field_wp_zip_codes_value
FROM field_data_field_wp_cc_id c
  INNER JOIN cc_zips z
     ON z.cc = c.field_wp_cc_id_value,
     (SELECT @rownum:=0) r
 WHERE z.cc = '1039'
 AND c.entity_id = '3699';

As for any application, unless you are perfectly sure of what you are doing, are comfortable with it and have a good understanding of the inner working of the Field API and the SQL storage engine for fields, you shouldn't try to do your insert directly in SQL.

Instead, you should use the Node or Entity APIs to load your contents, update them and save them back in PHP code. This will be more expensive performance-wise, but much more easier to implement and maintain.


Restrict editing of content based on form value in content type I'm not sure of the exact way to word this. I'm "just the designer". Where I'm working we've traditionally made a role per content type to limit access to editing/creating certain kinds of content. On a new (D8) site we're working on, we'd like to have a single content type ("Room") and have different people be maintainers of those rooms depending on what's set in the "Building" field.

The idea is to avoid having a ton of mostly-similar Room content types (that would all require updating when we want a change). And also of course to avoid people from other buildings editing rooms that don't belong to them.

(I think it'd be fine to have either 1) the rooms originally created by an admin and just have the building field hidden/disabled/limited when non-admins edit, or 2) even let them create new rooms with the building field limited based on their role/permissions.)

I don't know if there's a built-in way to do this, or perhaps modules you could recommend.

The developer I'm working with seems convinced that the only way to accomplish this is to build a custom form in PHP that essentially duplicates Drupal's built-in form for the Rooms content type we've made (I'd really like to avoid this route, since it'd be a lot of hard-coded stuff that needs dev time, testing, maintenance, etc.). Thanks!

(I think it'd be fine to have either 1) the rooms originally created
  by an admin and just have the building field hidden/disabled/limited
  when non-admins edit, or 2) even let them create new rooms with the
  building field limited based on their role/permissions.)

You could do this via a custom module or in your theme's mytheme.theme

function mytheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // check form id for edit
  if($form_id == 'node_room_edit_form') {
    // Load the current loggedin user.
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    // Check if user does not have administrator role
    if(!$user->hasRole('administrator')) {
      // get current node id
      $nid = \Drupal::routeMatch()->getParameter('node');
      // load the node
      \Drupal\node\Entity\Node::load($nid);
      // check if building field is not set to something
      if($node->field_building->value != 'something') {
        // remove access to field, make field not required so when
        // they save they don't get an error.
        $form['field_name']['widget']['#access'] = FALSE;
        $form['field_name']['widget']['#required'] = FALSE;
      }
    }
  }
  // check id for create
  if($form_id == 'node_room_form') {
    // logic goes here.
  }
}


Status report says database out of date, but update.php and drush say up-to-date Drupal 7.39, all modules updated to their latest version using Drush 6.6.0. When I look at the status report it says 'database out of date'. When I do drush updb or call update.php both report that the database is up-to-date.

How can I find out where the problem is?

Here are the steps I took to solve the problem. @rooby gave the URL that helped to determine which module.

As you can read on the given URL (https://www.drupal.org/node/1263908) the problem is caused by a module having a version of -1 in the system table. The URL has instructions how to find out which one is acting up. I've followed the one in this comment: https://www.drupal.org/node/1263908#comment-9059569

This basically means:

open [drupalroot]/modules/system/system.install
find the line $requirements['update']['severity'] = REQUIREMENT_ERROR; In drupal 7.39 this is on line 412
add the watchdog line as described: watchdog('module update db', $module); // <-ADDED THIS LINE
open the status page again
now open the watchdog page. You should see a line that starts with 'module update db'. After it you can read the module that causes the problem.

In my case that was environment_indicator. I'm no PHP developer, so I solved the problem by opening the database in Sequel Pro and checking the version column of the system table of this module.

The file environment_indicator.install shows several updates, the first one creating a table. Since the table was present, I entered its version number (7200) in the system table. Now I was able to run the update.php which showed there were 2 updates. I let it update the database, which ran without problems.

When opening the status page everything was fine and I deleted the watchdog line from the system.install file.

I'm just curious why update.php doesn't find any updates, while status page does.


Programmatically Change Pager "Items to Display" value? I would like to create a custom form to allow a website admin to quickly change the number of "Items to Display" for a particular block display for a particular view, but I don't have a clue how to change this value programmatically on my own, besides the views ui?

im not sure of any 3rd party module that allows easy "override the # of items per page". I've done this task a few times for View displays using core drupal apis.

Basically:

you use hook_views_pre_build to programmatically alter the view.
Use a custom variable to store your items per page value.
Make a simple admin page to allow a site administrator alter the value.

EDIT: amended to different views hook function.


What is the best way to run HTTPS for drupal commerce I have seen the module Secure Pages, and also found Custom SSL redirect and read all the issues related to this and Commerce, but most seem out dated.

Can anyone say as of this point what is the best way to run the site on http and the checkout (anonymous users) with https?

It's hard to say what's 'best', it depends what you mean by that.

If you're just looking for a working solution, the dev version of Secure Pages along with the core patches it recommends works great.

Best thing you can do is install the various options you've identified, do your testing as normal, and ask a more specific question if the modules do something you don't expect.


Views Criteria Filter - Changes Affect Master Display I have a problem with the module Views with the FILTER CRITERIA, When I clone a block inside my view and change the FILTER CRITERIA the change also occurs on the Master Display is it a normal behavior ?

Thanks !

Yes, that's the default behaviour. But you can change it easily.

When you're editing the filters in your cloned display, look to the top of the dialog. You'll see a select list like this:

That select list determines whether the changes you're about to make are applied to the whole view, or just the display you're working on. If you choose "This xxx" (where xxx could be any number of things like page, etc), the changes you save will not apply to the other displays.


Rule to send an email on node save printing a field value of a referenced node I am using Drupal 7, and the modules References and Rules.

I created two content types: A and B.

A has a field (A:b_nodes) which is multiple node references of B which has field (B:time).

How can I configure a rule so that when A is saved, an email will be sent with body text like the following:

here are the B nodes time data contained in A

B1 : 2 januari 2013
B2 : 5 may 2013
B3 : 15 august 2013

Go to /admin/config/workflow/rules/reaction/add and create a rule. Then in rules action section under system category select Send email. Then you will be redirect to a new page, here you can define the subject,content,recipient of mail. By using Replacement Patterns you can add dynamic variable in to mail content.


How to display photo properties (ISO, Aperture, Exposure, Shutter Speed) in Drupal 7 everyone! I know that every image contains specific information about itself( ISO, Aperture, Exposure, Shutter Speed). The problem is how to display them in the article of Drupal 7? Thanks!

The exif module should get you going.

  The Exif module allows you to display Exif metadata on image nodes.
  Exif is a specification for the image file format used by digital
  cameras.


Creating a simple first module I am a total beginner with Drupal and am trying to create a very simple "Hello world" module. I've been following the guide "A Hello World custom page module", but I still get a "Page not found" message.

My directory structure looks like this:

    drupal
        modules
            custom
                mymodule
                    src
                     |- Controller
                     |     ExampleController.php
                     |- mymodule.info.yml
                     |- mymodule.routing.yml

The module shows up in the admin panel, and I have activated it.

Here's what my routing file looks like:

mymodule.content:
  path: '/example'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ExampleController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

Here's mymodule.info.yml:

name: Hello World Module
description: Creates a page showing "Hello World".
package: custom

type: module
core: 8.x

dependencies:
  - datetime
  - link
  - views

configure: hello_world.settings

hidden: false

# Note: do not add the 'version'  property yourself!
# It will be added automatically by the packager on drupal.org.
version: 1.0

And here's the controller:

/**
* @file
* Contains \Drupal\mymodule\Controller\ExampleController.
*/

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class ExampleController extends ControllerBase {

    /**
    * {@inheritdoc}
    */
    public function content() {
        $build = array(
        '#type' => 'markup',
        '#markup' => t('Hello World!'),
    );
    return $build;
    }

}

When I go to  Configuration/Development/Performance and click "Clear all caches" I get this error message:

ReflectionException: Class \Drupal\mymodule\Controller\ExampleController does not exist in ReflectionMethod->__construct() (line 128 of core/lib/Drupal/Core/Entity/EntityResolverManager.php).

I have tried experimenting with the directory structure, for example moving mymodule up directly to modules instead of custom, but to no avail. What am I doing wrong?

Well, this is embarrassing... By blindly following the guide I forgot to add <?php to the beginning of ExampleController.php. All these new .yml-files made me forget all about "normal" PHP I guess. Problem solved.


Editing a Design Suite Template File I'm using the Design Module for a Drupal 7 site and have created a simple 1-column views display using the module and I want to take that template file that it has created and edit it more.

At the bottom of the layout options I am given a location of where the template should be along with the name of it, but it's not there.

Is it possible to edit a layout (template file) that Display Suite has created? Where can I find those template files?

The source template file you are looking for should be called ds-1col.tpl.php. It is in the mentioned folder.

Copy the file to the templates folder within your theme.
Then rename the file to ds-1col--ds-views-account-wins-page.tpl.php
Make the adjustments you desire.
Flush your caches and you should see the changes.

Read more about views template files here which function really similarly.


How to eMail a file uploaded to a Webform to a sysadmin using the Rules module? I have a webform where a user can upload a file to the webform. I would like to be able to email the file via Rules to a sysadmin. I know I can send it from Webform directly, but I am also needing to attached a FillPDF file that can only be sent via Rules.

Yes it is possible to use the Rules module for sending an eMail with an attached file. To do so, make sure you have the Mail System and Mime Mail modules installed/enabled.

The Rules Event you want to use is probably when the Webform is submitted.

Then create a rule with a Rules Action to Send an HTML email. Specify the eMail body content, and then the email's attachment(s). If you have multiple attachments, make sure to specify 1 file (only) per line. The tricky part you probably run into is to correctly specify the filename of the attached files. The correct way to do so is like so:

[node:field-file-attachments:file:path]

That is also what is suggested in Comment # 25 of support issue (not bug ...) #1431572.

In your case, make sure that this path refers to the webform that is submitted and contains the attached file. Using the "Webform Rules" module, you should be able to have Rules react on an event like "Webform submitted". And if you then add a Rules Condition like "entity has field" (with the field corresponding to your attached file), you should be able to "do something" with that filename of your attachement. E.g. trigger another Rules Component that uses as a parm ... the path of your attached file. With that, your Rules Component should then take care of sending the actual eMail, with the correct value of the filename for the file to be attached.

Use Rules debugging

This question is pretty tough to answer with the limited info you provided (and without access to "your" site). Therefor I suggest you also consider 2 variations of Rules debugging, which are:

Within the rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).
(Temporary) enable the Devel module, so that you can (temorary) add a Rules Action like "Display a value" (in your case of the entire node/webform that's used to submit that attached file).

For way more details about these 2 variations, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


Add an extra delivery address I'm a Drupal novice and struggling to build a webshop with Drupal Commerce.
It's really starting to work out, but I've still have some problems regarding overriding and restyling themes.

Is it possible to add an extra delivery address form to the Drupal Commerce address field module (different billing, delivery addresses with checkbox to show delivery address)?

How can I restyle the address form? Is there a template file for it, or does it have to be done through CSS?

It would be really usefull if somebody could help me with some information or maybe some kind of guideline.

The customer information is stored as commerce_customer entity. By default it has an address field attached to it. For multiple addresses, you could either allow multiple values on the field, and use some theming to display one as billing and the other as delivery.

The other option would be to add a new address field and use that for delivery/billing. With hook_form_alter you could add custom elements to the form, like the checkbox and JavaScript effects.

You have a few options if you want to customize your address field form. You can implement AddressFieldForm, the default looks like this:

/**
 * Default address handler.
 */
class AddressFieldForm_default implements AddressFieldForm {
  public function form($address, $field, $instance, $langcode, $items, $delta, $element) {
    $required = $delta == 0 && $instance['required'];

    $form['thoroughfare'] = array(
      '#title' => t('Street'),
      '#type' => 'textfield',
      '#required' => $required,
      '#default_value' => $address['thoroughfare'],
    );
    $form['premise'] = array(
      '#title' => t('Residence, building, ...'),
      '#type' => 'textfield',
      '#default_value' => $address['premise'],
    );
    $form['sub_premise'] = array(
      '#title' => t('Floor, stairway, ...'),
      '#type' => 'textfield',
      '#default_value' => $address['sub_premise'],
    );
    $form['dependent_locality'] = array(
      '#title' => t('Suburb, post box, ...'),
      '#type' => 'textfield',
      '#default_value' => $address['dependent_locality'],
    );
    $form['postal_code'] = array(
      '#title' => t('Postal Code'),
      '#type' => 'textfield',
      '#size' => 5,
      '#required' => $required,
      '#default_value' => $address['postal_code'],
    );
    $form['locality'] = array(
      '#title' => t('City'),
      '#type' => 'textfield',
      '#size' => 30,
      '#required' => $required,
      '#default_value' => $address['locality'],
    );

    // All the other fields are unsupported by this handler.
    foreach (array('administrative_area', 'sub_administrative_area') as $field) {
      $form[$field] = array(
        '#type' => 'value',
        '#value' => '',
      );
    }
    return $form;
  }
}

This is what addressfield uses to internally handle different address types. Using addressfield_mapping_alter you would be able to overwrite the default mapping, or create a mapping for your own country:

function module_addressfield_mapping_alter(&$mapping) {
  $mapping['default'] = 'AddressFieldForm_my_custom_default_form',
  $mapping['DK'] = 'AddressFieldForm_dk', // Add for Denmark which doesn't exist yet
}

In addition to this, you have all the usual tools, like hook_form_alter and adding a custom theme function to render the form like you which. You should be aware that addressfield makes heavy use of AJAX to replace form elements when changing country.


Determine if entity type is fieldable Given an $entityTypeId as string, how can I determine if this entity type is fieldable? That is, if entities of that type implement FieldableEntityInterface?

There might be a simpler way but I think this should be pretty reliable:

// Inject the entity_type.manager service instead if possible.
$class = \Drupal::entityTypeManager()
    ->getDefinition($entity_type_id)
    ->getOriginalClass();

$interface = 'Drupal\Core\Entity\FieldableEntityInterface';

if (in_array($interface, class_implements($class))) {
    ...
}


How can I allow users to edit CSS in a WYSIWYG editor Is there a way to give the administrator of a site the ability to edit and save CSS files in a wysiwyg editor? I thought perhaps the CSS could be node therefor allowing for some type of versioning and reversion.

You might be interested in this module:

CSS Injector

  Allows administrators to inject CSS into the page output based on
  configurable rules. It's useful for adding simple CSS tweaks without
  modifying a site's official theme


Right way of data organasing and structuring I have the following structure of the site that is revealed in main menu hierarchy:

  News

  news category 1
  news category 2

  Documents

  document category 1
  document category 2

All the pages mostly will be presented with a single Content Type. But for different places in menu hierarchy page regions should consist of different blocks.

e.g., for a node from "news category 1" there will be a search block placed in the sidebar, for th enode from "document category 2" -- the login block.

I see a quite moot "solution" for this. I will have to turn nodes' urls into somewhat like "mysite.org/news/category1/..." and set visibility options to blocks through url patterns. Is it a right way to follow? But in this case the editor (not me) will have to invent and handcode url aliases when creating node and it seems to me very unreliable to entrust him with the site structure.

Another way -- create different content types for every categories and generate aliases automatically but it seems to me a bit crazy.

What do you think about that?

If your categories are pre-defined and won't change then I think your solution of using blocks regions and block visibility settings may be the best. If you need more complex visibility settings the Context module should be able to help.


Group Filter for taxonomy term in view Right now I have it so that I grouped a list of taxonomy terms with Group Filters like this:

House Pet:

Dog
Cat

Sea Creatures:

Whale
Shark

All:

Dog
Cat
Whale
Shark

My current problem is that when using group filters I keep getting No Results, however if I use a single filter and choose one of the options I get results.

I have seen a lot of videos of people using groups with taxonomy, but I have not been able to replicate what each of them have done. I have tried using the Filter Criteria with the field as well as the content taxonomy has terms with depth option as well. The content is tagged and has departments (you can see it from the the field I am showing with the view) so I know that the tags exist, but they always return with no results.

Ideas, options, patches, questions, help? I have run out of ideas.

If I remember correctly, try this.

Create a relationship to the taxonomy parent term.
Add a taxonomy term name field, add relationship to Parent.
Add another taxonomy term field.
Group by Parent term.

Hopefully that works out. You can also look into Views Tree, I've used it before and works pretty well for specific use cases.


Is it beneficial to export views and store it as a module? So in an attempt to further optimize my app, I thought it would be wise if I store the Views in a module using the export tool.

Are there any advantages to gain by doing this?

Thanks!

The biggest benefit is that you can have your views stored in a version control system like Git or SVN. I maybe mistaken but I don't think there are really performance benefits on doing this.

Some documentation to help you out: http://views-help.doc.logrus.com/help/views/api-default-views


How to redirect users after password reset from first time user I am using hook function in my module to redirect users accordingly as below.

function mymodule_user_login($account) {
 if (!$account->getLastAccessedTime()) {
  // The user has never logged in before.
   return;
 }
 $response = new RedirectResponse('MyModuleFormUrl');
 $response->send();
}

First time users coming from their corresponding emails are getting redirected to change password page able to set new password and existing users are redirected to form page after successful login. But the problem is how to redirect users after successfully setting their password to my module form. From the code above I thought it should happen automatically but it isn't. Can anyone suggest some ideas.

Edit to the Question:
So as suggested below I tried both the ways but still after the new user clicks save button on password reset page(setting his new password), he is not getting redirected to mymodule form page. Below are the codes I tried.

Method 1:

    function MyModule_form_alter(&$form, &$form_state, $form_id){
    if($_SESSION['first_time_login']==TRUE)
    {
       $_SESSION['first_time_login']==FALSE;
       $form_state->setRedirect('url');
    }

Method 2:

    function mymodule_user_form_alter(&$form,
    \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
    {
       foreach (array_keys($form['actions']) as $action) {
        if (isset($form['actions'][$action]['#type']) && $form['actions']
        [$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'mymodule_form_submit';
         }
       }
    }

    function mymodule_form_submit(array $form, FormStateInterface
     $form_state){
         $form_state['redirect'] = 'url';
     }

Final function which worked for me:

    function MyModule_form_alter(&$form, &$form_state, $form_id){
      if($form_id == 'user_form')
      {
        foreach (array_keys($form['actions']) as $action) {
           if (isset($form['actions'][$action]['#type']) && $form['actions']
           [$action]['#type'] === 'submit')
           {
            $form['actions'][$action]['#submit'][] =
               '_MyModule_user_profile_submit';
           }
       }
     }

      function _MyModule_user_profile_submit($form, &$form_state)
      {
           $response = new RedirectResponse('url');
           $response->send();
      }

It's actually pretty easy, the user module adds user_pass_reset to the form_state all you need to do is check for that value:

function MyModule_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_state->get('user_pass_reset')) {
    $form['actions']['submit']['#submit'][] = '_MyModule_user_profile_submit';
  }
}


I need to add a date to a calendar without creating a node I have a difficult use case. I am building a site for a beverage distributor. They want to put their sampling events on a calendar. The problem is the sampling events don't really have a title. They just have the beverage being sampled, the location, and the date/time. Is there a way I can add dates to a calendar without creating a node for them or create a node with no title field?

I would use the Automatic Entity Label module to hide the title field on the form, and automatically populate it with a title. It can work with tokens, so you could configure it to generate node titles like "Event on [node date]".


Install Commerce 2.x project template windows using composer and got HTTP 500 error I want to install Drupal Commerce 2.x in Drupal 8.x in Windows. I followed as in  Commerce 2.x project template in Github. I installed composer and from my cmd window, I ran command: composer create-project drupalcommerce/project-base mystore1 --stability dev --no-interaction

All was going fine. It loaded many components like phpunit 4.8.27. Then it displayed messages like commerceguys/addressing suggests installing sysfony/intl ... and like these. Then Writing lock file ,  Generating autoload file, Downloading file:100%, Downloading file:100%,

Then I got Downloading file:Failed

Composer/Downloader/TransportException
The "http://cgit.drupalcode.org/drupal/plain/.eslintignore?h-8.2.0-rc1: file could not be downloaded (HTTP/1.1 500 Internal Server Error)

I also searched if it had created some folder somerwhere in my C:\xampp\htdocs or somewhere, I could not get anywhere. Please help me install it completely and access drupal from browser.
I have attached screenshot. The errors are seen in lower section:

Retry ! It solves download issues.
Then find project location in C:\Users\current_user\project_name
Copy inside htdocs and browse localhost\project_name\web and continue installation.


How to pre-populate paragraphs when creating a page I have tried for some time to find out a way to populate a new page with a few paragraphs to save time on most of the pages (but which might change position or even get dropped for some pages) but so far haven't found a way to do.

I think I have found out how to do the paragraph adding part, but what I am missing is how to fire the code when a new node of relevant content type is created.

I have tried hook THEME_node_create and THEME_node_insert, but they seem not to be fired when a new node is requested. I read that not all hooks are implemented for a theme but how then to achieve this functionality?

I probably (as most of the times) am missing something trivial, but please, help me find the light.

wbr

hank

Actually I found a solution using a module. It was not the first time to find the solution after asking it here so it was not in vain - even if I found it myself...

To help possible otrhers, here is my solution from my module's .module file

function acme_pre_populate_node_create(\Drupal\node\NodeInterface $node) {
  $i=0;
  if ($node->getType() == 'acme_basic_page') {
    $paragraph = \Drupal::entityTypeManager()->getStorage('paragraph')->create([
        'title' => 'Paragraph ' . $i,
        'type' => 'hero_image',
      ]);
      $node->field_paragraph_list[] = $paragraph;
      $i++;
      $paragraph = \Drupal::entityTypeManager()->getStorage('paragraph')->create([
          'title' => 'Paragraph ' . $i,
          'type' => 'one_column_text',
          'field_one_column_text' => "
Change title here

And contents here
",
    ]);
        $node->field_paragraph_list[] = $paragraph;
       $i++;
  }
}