can i use entity id instead of node id to load node with node_load() function can i use entity id instead of node id to load node with node_load() function coz
i don't find any difference between entity id and node id . both node id and entity id return same result

$e_id = node_load($entity_id);
dpm($e_id);
$n_id = node_load($node_id);
dpm($n_id);

both $e_id and $n_id return exactly same result

The node ID is the entity ID for the node entity type.

As they're the same thing, the answer to your specific question can only be "yes".


hook_node_insert and FileField Paths I'm using hook_node_insert to process some data from node.

This code returns image URL, BUT i'm using FileField Paths and i can't manage to get the final image URL. Is there any way to solve this issue?

$fid = $node->field_imagen['und'][0]['fid'];
$imgpath = file_load($fid)->uri;
$url = file_create_url($imgpath);

Thanks

Filefield Path uses hook_entity_insert() to operate with file directory. The hook_node_insert is called before hook_entity_insert, so the file isn't processed yet there.
See: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_save/7

module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

You should use that hook as well. Just make sure, your module have higher weight than ffp. (Check (and increase if necessary) the weight field of your module in the system table.)


Upgrading a simple drupal 7 module to drupal 8? I am new to drupal and currently using version 8. I am trying to convert cricket feed widget module in drupal 7 to drupal 8 based on Community instructions.. But I am unable to understand the routing.yml files. I don't understand the parameters used in the routing.yml file to connect with the controllers. I checked out some of their examples..

I don't understand

what they mean by sub_name and
Path: Path to the page on site.How do I know that?
Is it that much difficult to convert a simple drupal 7 module to drupal 8?

I've spent the past few months doing a lot of D7 -> D8 upgrades. I haven't used sub_name (or even seen it), so I cannot comment on that, but as for the path, it's the same path you declared as the array key in your hook_menu definition - however note that with D8 you need to include the preceeding forward slash.

So if your D7 hook_menu() definition for a path was:

$menu['path/to/something']

In D8 your path in the routing file would be:

path: /path/to/something


Update manager fails to move files from tmp I've this configuration:

Fedora Core 21 (64bit)
vsftpd: version 3.0.2
Drupal 7.41

I have a unix user called user1 who has home dir /home/user1
and Drupal root is at /home/user1/www

The Drupal temporary directory is at /home/user1/tmp

I'm trying to install the Corporate Clean theme using the update manager but it fails giving this message:

  corporateclean Error installing / updating File Transfer failed,
  reason: Cannot move
  /home/user1/tmp/update-extraction-5345b836/corporateclean/comment-wrapper.tpl.php
  to /www/sites/all/themes/corporateclean/comment-wrapper.tpl.php

I checked ownership and permissions of /home/user1/tmp/update-extraction-5345b836/corporateclean and it's owned by apache and permissions are like so:

  755
  drwxr-xr-x 7    755 apache 4096 Dec  9 07:05 corporateclean

Is this the right permissions / user for the extracted directory by the update manager? The owner / permissions is causing the issue and not allowing the move.

After reading Enable FTP on your server i applied the changes as mentioned in the /etc/vsftpd/vsftpd.conf file.

The changes applied are

Linux Instructions (UNSECURED):

Step 1:  sudo  yum  install  vsftpd

Step 2:  sudo emacs /etc/vsftpd.conf
Uncomment these settings:
listen=YES
local_enable=YES
write_enable=YES
local_umask=022
anon_upload_enable=YES
anon_mkdir_write_enable=YES

Step 3:  sudo service vsftpd restart

i then changed the ownership of the drupal root to apache user

chown -R apache:apache /home/user1/www

and this fixed the problems for me. am able to install themes via FTP method.

Please note - the method i've used is potentially insecure. Don't use on production server.

Thanks.

Yashesh


How to change node field label for some specific conditions? In preprocess_node I wrote this and when I do kint($variables['node']) I can see that label is set to "test", however on display it appears with the old label. How can I change the label name? Should it be in preprocess_node or some other hook? Or what else I should update, so it is actually displayed with label replacement?
    $node = &$variables['node'];
    if ($node->getType()=='training') {
      $term = reset($node->get('field_training_type')->referencedEntities());
    }
    if($term instanceof \Drupal\taxonomy\TermInterface && $term->id() == 9) {
      $node->get('field_section_09')->getFieldDefinition()->setLabel('test');
      $variables['node'] = $node;
    }

This doesn't work for two reasons. First, you shouldn't change objects unless you want to save the changes  because they are shared across the entire Drupal application. Second, preprocess is for preparing variables printed in templates. Changing other variables has no effect.
So in hook_preprocess_node you can change only $variables['content'].
For most fields the label is stored in #title unless the field is built in a special way by callbacks:
$variables['content']['field_bar']['#title'] = 'Foo';

More straightforward, though, would be changing the label directly in hook_preprocess_field:
$variables['label'] = 'Foo';

which is then printed in the template as {{ label }}.

By the way, if you want to rewrite your code for field preprocess you find the node in this variable:
$node = $variables['element']['#object'];


Display custom variables We have a twig template, node--page.html.twig where we want to display the custom variable ns-custom-template. The variable is created from a custom module, mymodule with the following code below.

How can I create a variable, populate it using the ns-custom-template variable, and display it in the node--page.html.twig template?

Here is what I tried, but when using kint(test_var) I get NULL returned.

mymodule.module

function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'ns_custom_template' => [
      'variables' => [
        'test_var' => NULL,
      ],
    ],
  ];
}

Inside mymodule's template folder is ns-custom-template.html.twig

<p> Testing my variable {{ test_var }} </p>

MyModuleController class

class MyModuleController extends ControllerBase {
  public function content() {
    $config = $this->config('mymodule.settings');
    $config_value = $config->get('my_config_value');
    return [
      '#theme' => 'ns_custom_template',
      '#test_var' => $config_value,
    ]
  }
}

mymodule's routing file:

mymodule.module_controller_content:
  path: '/mymodule/content'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController:content'
    _title: 'content'
  requirements:
    _permission: 'access content'

MyModuleForm

class MyModuleForm extends ConfigFormBase {
  protected function getEditableConfigName() {
    return [
      'mymodule.setting',
    ],
  }

  public function getFormId() {
    return 'mymodule_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('mymodule.setting');
    $form['my_config_value'] = [
      '#type' => 'textarea',
      '#title' => $this->t('My config value'),
      '#description' => $this->t('Enter some value'),
      '#default_value' => $config->get('my_config_value'),
    ];
    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    $this->config('mymodule.setting')
      ->set('my_config_value', $form_state->getValue('my_config_value'))
      ->save();
  }
}

node--page.html.twig

<article>
  {{ ns_custom_template }} {# returns null #}
  {{ kint(ns_custom_template }} {# returns null #}
</article>

For reference, I am trying to emulate the steps on Define a custom template for module output page.

The variable you are looking for is not ns_custom_template but test_var

To get all variables in your twig file, you can try {{ kint() }}

To get the variable you have previously declared in mymodule_theme, you can try {{ kint(test_var) }}

BUT there is another mistake:

The twig file in which you will find test_var is not node--page.html.twig but only ns-custom-template.html.twig

if you want to have test_var inside node--page.html.twig, you can use a preprocess function : function template_preprocess_node with a code like:

$var['test_var']='my value';

EDIT:It seems that you would like to use the template ns_custom_template in a node template: to achieve this, you need to populate your variable test_var with a render array having the name defined in mymodule_theme as a value of the #theme key.

function mymodule_preprocess_node(&$var) {
  $var['my_free_var_name'] = ['#theme' => 'ns_custom_template', '#test_var' => 'your value'];
}

After doing this, you can display your template inside node--page.html.twig bu using the following code:

{{ my_free_var_name }}


Get term name for page title from term id passed in the contextual filter? What is the correct method of getting term name in the page title field if I have passed the term id in contextual filter.
I have added the Content: Has taxonomy term ID contextual filter in views, I have tried to overwrite the page title be provide "%1" but that also provides term id as the "filter value type" contains term ID.

One way to achieve this using the "global php" field in the header and getting the term ID from the argument as "arg(1)", and getting the term name from the term ID and than setting page title using "drupal_set_title($term_name)".

Answers Updated:
try this hook, hook_view_pre_render()

  This hook is called right before the render process. The query has
  been executed, and the pre_render() phase has already happened for
  handlers, so all data should be available.

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
     $term = taxonomy_term_load(arg('arg_position_in_url'));
     $title = $term->name;
     $view->build_info['title'] = $title;
  }
}


Unable to rebuild a form in submit handler I don't have much experience in drupal development. So for the purpose of learning, i have made a custom module and trying to implement various functionalities in drupal 8 module development.
I want to rebuild a form on submission of the form. I took help from here and here and drupal.org's this node. How can i rebuild the form on clicking on the button 'Click Me'. It is not throwing any error but the form is not getting rebuild in the following piece of code :

function say_hello_submit(&$form, &$form_state) {

    $form_state->setRebuild();
  }
public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('hugs.settings');

    $form['default_count'] = [
        '#type' => 'number',
        '#title' => $this->t('Default_hug_count'),
        '#default_value' => $config->get('default_count'),
    ];
    $form['mytable'] = [
        '#type' => 'table',
        '#header' => [t('Name'), t('Value')],
        '#rows' => array(),
    ];
    for ($i=1; $i<=2; $i++) {
        $form['mytable'][$i]['name'] = array(
            '#type' => 'textfield',
            '#size' => 40,
            '#maxlength' => 40,
            '#title' => t('Name'),
             '#title_display' => 'invisible',
     );

        $form['mytable'][$i]['value'] = array(
            '#type' => 'textfield',
            '#size' => 40,
            '#maxlength' => 40,
            '#title' => t('Value'),
            '#title_display' => 'invisible',
     );
    }
    $form['submit'] = array('#type' => 'submit', '#value' => 'Click Me');
    $form['#submit'][] = 'say_hello_submit' ;

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

}

What exactly do you expect to happen when it's "rebuilding"?

I should simply call buildForm() again, but that will build the same form, so visually, you won't see a difference. The only ondication would be that it's doing only a POST request, while a non-rebuilding form submission does a redirect to the same page after submitting.

If you e.g. want to see additional rows in your list, you need to store the desired max with $form_state->set('max_rows, 5) and then in your buildForm() method, read it again from there with get()


Dual operating system setup I need advice regarding my plans for a Linux/Windows web development project.

My employers have 2 windows servers - one hosts their non-drupal CMS and the other hosts the website database.
My job is to transition their website to Drupal - that's the easy part. So, I will be shutting down the server hosting the current website.

The hard part is using two separate servers for the site and the database - something I've never done before.

I plan on using a Linux server for the Drupal development but I need to know how to do the following:

use a remote database
use SQL Server on a Windows IIS machine

Remote database

To use a remote database, you just have to supply the IP/URL of your remote server instead of 'localhost' during install or in sites/default/settings.php file.

SQL Server

There's a module for SQL Server : Drupal 7 driver for SQL Server and SQL Azure.

And installation instructions are available on the module page.


Showing a message (perhaps using a redirect) after a Fileds form is submitted in Drupal 7 I am using Drupal 7 + Rules. I have this form (creates a new node of some content type , dunno the correct jargon here) that users can fill to apply for a job. I want to show them a static message after the form submission. Apparently Rules is the way to go. How to do I achieve this ?

You can setup Rules to display a message when ever a node of the specific type is created. There is an interface for creating Rules you want

Event: Creating a new node
Condition: The node is of the chosen type
Action: Display a message

Alternatively you can use code with hook_form_alter, and add a submit handler to the node submit of the specific type, where you use drupal_set_message to display the message. This can be done faster (if you know how to create modules for drupal, and it requires less resources (is faster in execution) than the Rules solution.


How to decide to create a content type or two if there are both common and uncommon fields? I have a content type that has about 80 fields.
It has a select list field at top and there are two options: Yes or No.
If Yes is selected all the 80 fields are used and if the No is selected, the last 30 fields are not used. For both two options, 50 fields are common.
I wonder, if I should go for creating two content types for this structure, or if continuing  with "one" (only) is better. If I continue with this "one" content type, 30 fields will be empty for the "No" options and can it be a "bad" thing for the database (waste of space etc.)?
(If I continue with one content type I will use some modules such as Conditional Fields etc).
Is there anybody faced with a similar situation and is there a "better" way?
(Additional information: this content type is used for an academic resource. If the resource is in English I will only fill the 50 fields. If the resource is in another language I will fill the 50 fields and also fill the other 30 fields.)

I would use only 1 content type, and use the Conditional Fields module to hide those 30 extra fields for your select list field with value No.

This excerpt from this module's project page seems to perfectly fit as a possible solution for this approach:

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.

  When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.

  You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

Possible alternative

True, you might also go for 2 content types instead. But in that case you're using an approach as described in the (illuminating, I think) article "Relativity model for Drupal". For more details on that, and the typical modules involved in that approach, refer to my answer to "How do I model content (types) from a database-centric point of view?".

In the long run, I bet the overall implementation of your entire site would be much better (eg: you'd need way less contributed modules). But that also implies you're willing to do a way higher effort/investment then just adding the Conditional Fields module.


Just list one product variation I'm developing a videogame store with Commerce (I'm n00b in Drupal), so for example I'm adding a new game "GTA V", GTA has versions to XBOX360 and PS3, so I'm trying to create the product and add two variations for PS and XBOX with different prices and some stuff, but I don't need a product page where the user selects PS or XBOX version, because I'm splitting my site by consoles, so if the user is in XBOX section, I need to list only the XBOX variation and not the PS variation.

I'm trying to achieve this because I don't wanna repeat myself with description, videos, etc of video games, so in the "GTA V" example I will write just one description and not two (for PS and XBOX) that will be the same.

You can just use views to filter on the catalog pages for product variations if they are set. You should take a look at http://www.drupalcommerce.org/user-guide/products the guide will help you create product variations, you can then create a view for the catalog, you can then create a exposed filter (lets the users change the filter value) for product variation so they user can select PS3 or XBOX and get only those products on the filter. But if you went to that page, you would still need to select "PS3" or "XBOX" to place a order.


Filter by multiple taxonomies in URL I need to display nodes in a view, based on a combination of multiple taxonomy terms, in multiple vocabularies. For example, for car sales, one vocabulary lets the visitor select one model, and another selects the color.

My custom path looks like this:

/sales/cars/models/%            // taxonomy view
/sales/cars/colors/%            // taxonomy view

/sales/cars/model/%/color/%     // taxonomy filter

URL:

mydomain.tld/sales/cars/model/land-rover/color/red

I assume I can do this by exposing filters but how?

When you create your views page you set the path to /sales/cars/model/%/color/%

Add contextual filters:

You need to create 2 Contextual Filters, both of them are: Content: Has taxonomy term id so repeat the process below twice.

On configuration of first contextual filter, you need to set:

  "WHEN THE FILTER VALUE IS NOT AVAILABLE" -> Provide default value ->
  Raw value from URL -> Path component

Also check "Use path alias" if the URL is an alias rather than a system path.

Now you need to validate it, on same configuration overlay screen under

  "WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED"

tick "Specify validation criteria"

and select "Taxonomy Term" for Validator. Check the appropriate Vocabulary for each contextual filter, and finally set "Filter value type" to "Term name converted to term id" and check the checkbox "Transform dashes in URL to spaces in term name filter values".

Set "Action to take if filter value does not validate" to whatever your needs.


Webform Mail not arriving at gmail address I'm having problems with the mailing of the Webform Module.

I have an online website where you can fill in a form. The results will be sent to the email-address the user gave in and the user of the site.

When the user fills in an email like myname@hotmail.com or myname@mycompany.com there are no problems. They receive the results perfectly. But when they use a gmail address like myname@gmail.com they DON'T receive the email. So it never works with a Gmail address.

The user of the site (who normally also receives the results) then gets an error like this:

  Subject: Undelivered Mail Returned to Sender

This is the mail system at host myhost.com.

I'm sorry to have to inform you that your message could not
be delivered to one or more recipients. It's attached below.

For further assistance, please send mail to postmaster.

If you do so, please include this problem report. You can
delete your own text from the attached returned message.

                 The mail system

  : host gmail-smtp-in.l.google.com[ip-adres]
    said: 550-5.7.1 [ip-adres      12] Our system has detected that this
    message is 550-5.7.1 likely unsolicited mail. To reduce the amount of spam
    sent to Gmail, 550-5.7.1 this message has been blocked. Please visit
    550-5.7.1 http://support.google.com/mail/bin/answer.py?hl=en&answer=188131
    for 550 5.7.1 more information. 44si1984154eef.10 - gsmtp (in reply to end
    of DATA command)

What could be the problem with this?

From the link in your bounceback message:

"A message might be blocked if it contains suspicious-looking or spammy text or if the sending IP has had a history of sending unsolicited messages."

Either one of these possibilities might be the issue.  To rule out "suspicious-looking or spammy text" you should look at the emails your webform generates.  Is there any text they have in common that might be triggering gmail's spam rules?  If you send such a message to a gmail address manually, do you get the same bounceback?

The more likely explanation is that the sending IP has had a history of sending unsolicited messages.  This is especially likely if you're running in a shared web hosting environment.  If this is the problem, there's likely little you can do about it, other than asking your host to move your account to a different server.


Drupal reuses its hash salt The instructions in default.settings.php say

  This variable will be set to a random value by the installer. All one-time
   login links will be invalidated if the value is changed. Note that if your
   site is deployed on a cluster of web servers, you must ensure that this
   variable has the same value on each server. If this variable is empty, a hash
   of the serialized database credentials will be used as a fallback salt.

but this explanation of salting says

  A new random salt must be generated each time a user creates an account or changes their password.

and goes on to clarify that each salted hash (eg password) should have its unique salt stored along with the hashed+salted password in the database.

Am I misunderstanding the article I read on salting, or is Drupal using a faulty practice for the sake of convenience, or is the article wrong, or is there something else going on?

I have migrated other CMS's to Drupal and had experience moving user accounts.  Drupal's password algorithm is extremely good.

The salt you are referring to in the settings.php is not used for passwords. The drupal_hash_salt salt is used for generation of things like cookies.  Hence why it says you must keep it the same across all web servers if you are in a load balanced setup.

Generation of passwords uses the SHA512 algorithm with randomly generated salts using openssl php libraries (not mt_rand or other weak random number generators).

If you want to learn more about password generation you can start here reading the API documentation for Drupal

You see that in the function to generate it calls a "private" function to generate a new password salt (_password_generate_salt()). Which in turn calls a lot of other private, custom Drupal functions (it is a long rabit hole).

So in general the password scheme used for Drupal is extremely deep and nested, it does not use PHP functions considered to be "weak".


Move Menu minipanels DOM location I am trying to create a Menu-minipanel which will appear directly below the horizontal header menu, and push the content below down.

I have set the menu positioning to static so that it sits within the page structure, but that renders it at the bottom of the page when triggered (which is where it is put by default, and usually repositioned from there outside of the page structure).

Among the Menu mini-panels options there is a field labelled:

  "Allows control over where within the page's DOM structure the
  minipanel will be inserted. This defaults to $(document.body), i.e. at
  the end of the page's content."

but I have absolutely no idea how to manipulate this, and cannot find any documentation which makes this clear.

DOM is something I simply don't have a clue about, and I feel like I am so close to the answer, but my own knowledge seems to have run out!

Any guidance would be so appreciated!

So, though a bit of experimentation I found that the language

  "Allows control over where within the page's DOM structure the
  minipanel will be inserted. This defaults to $(document.body), i.e. at
  the end of the page's content."

Was what confused me - it turns out that just by adding a standard css selector to that field moved the menu.


Problems with moving my site to another server - WSOD with unfamiliar errors I've transferred a site from one server to another (both using Webmin's backup and restore facility).

Everything appears to have transferred across fine, except for when I try to access my site, I get the WSOD. I enabled error reporting and get the following error. Unfortunately, I'm unable to comprehend what it's telling me.

  Warning: Table 'id0063_BTG.users' doesn't exist query: SELECT u., s.
  FROM users u INNER JOIN sessions s ON u.uid = s.uid WHERE s.sid =
  'dc0n9e93lvckbmskv5frobirn2' in
  /home/id0063/public_html/includes/database.mysqli.inc on line 128

  Warning: Table 'id0063_BTG.system' doesn't exist query: SELECT name,
  filename, throttle FROM system WHERE type = 'module' AND status = 1
  AND bootstrap = 1 ORDER BY weight ASC, filename ASC in
  /home/id0063/public_html/includes/database.mysqli.inc on line 128

  Warning: Table 'id0063_BTG.url_alias' doesn't exist query: SELECT
  COUNT(pid) FROM url_alias in
  /home/id0063/public_html/includes/database.mysqli.inc on line 128

I checked the Apache error log and found this:

  [Tue Jul 19 16:40:24 2011] [notice] mod_fcgid: call
  /home/id0063/public_html/index.php with wrapper
  /home/id0063/fcgi-bin/php5.fcgi PHP Warning:  PHP Startup: Unable to
  load dynamic library '/usr/lib/php/modules/intl.so' -
  /usr/lib/php/modules/intl.so: cannot open shared object file: No such
  file or directory in Unknown on line 0

Any ideas where I can start?

When I'm migrating websites I use the Backup & Migrate module. You should give it a try.

If the problem persists, look for differences between the two servers: PHP version, Apache version, MySQL version, etc.
Also check your user permissions on the new server.


A way to determine where a URL is being generated? I'm a drupal noob, and one of the most frustrating things for me is finding where a specific page is being generated from. The fact that it could be a block, or created via a module, or through a view, I so far can not figure out how I can easily determine where the page is being created.

Is there an easy way of finding the 'culprit' that is generating any given url?

For example: www.example.com/catalog/something

How can I quickly tell what is generating /catalog/something?

In Drupal 6 many different things use the PathAuto module to quickly create URL Aliases for your content.

Automatic generation of aliases, the code that controls the administration and application of patterns, the database schema definitions & more can be found within the module.

To answer your original question, it depends on what is creating that alias, a node or view or taxonomy page or whatever, but more times than not pathauto will be involved.

To see the automatic alias settings go to : admin/build/path/pathauto


Drupal 8 - how to run multisite using one database I setup Drupal 8 in my localhost, i want to run multisite using one database and one instance (under one drupal installation)
How do i achieve this?

Also, i want the url will work like this :
site1 : http://localhost/site1
site2 : http://localhost/site2

Thank you.

First, read this page on Drupal 8 multisite, https://www.drupal.org/node/2297419.

It should give you a good idea of what you have to do in order to get multisite working and also explain some of the things you should consider. Following are generic steps, there are many things you can customize using settings.php.

The documentation inside the settings.php file is also very helpful, read that too by viewing the source of the file here https://api.drupal.org/api/drupal/sites!default!default.settings.php/8.

Briefly, the steps are,

Multi-site requires the existence of the sites.php file in the sites directory. This file does not exist by default.
Add your sites to a $sites array in this file, instructions are mentioned here https://www.drupal.org/node/2297419
Create a site directory inside sites/, the path should be sites/site1.
Each new site directory must have a settings.php file in order for Drupal to recognize it.
Visit the URL of site1, site1.yourdomain.com to install it.


Location map in colorbox I am using 'Location map module' and I have made a block of it displaying my required map.
My requirement is to view that map in colorbox when some user clicks on 'Map' link.

I need to use Location map module only. I tried to achieve above using views but didn't worked.

Can anyone help ?

Found this module Colorbox Node which allowed me to view Location Map Block in colorbox.

Follow this simple steps (to show only map block).

Enable Colorbox Node module. (Make sure colorbox module is already installed)
Create a Basic page and render Location Map Block in content region.
In this page display only Location Map Block.
Create a Global:Custom text or any custom link and add below code as a
text in it.

Map

By this you can render any block which you want to.


custom search in drupal for custom content type page I am trying to implement following functionality in drupal:

From the admin interface add, edit, list multiple stores for a company. The store record would be: Store name, address, image and zip code. This will be like how its done in simple lists - a list of stores shows up with edit and delete links and a link to add a new store, thats all.
Provide a search box in the homepage (separate from the standard site search) which will allow users to enter a zip code and view the image, title and address of stores in that zip code ( No need for proximity search or anything)

What I have done so far:

For adding store information:
created a new content type called 'Store Locator'' and added custom fields for required data. I unchecked promote to front page, so the added records do not show up in the homepage. This works pretty much how I want so that is fine.

The main challenge is to give a search facility for the stores. I created a view called store locator with rule set to show only 'Store Locator' content types. Added 'Table' as the format for display, and added the fields I want to see in the table. This view was created as a 'Page'

Now when I got to the view's URL, I can see a list of stores in the defined table format. My problem is that I need to add a search box in the front page where the user can enter a zip code and it will show this same view page, but with only matching records. Basically the custom search result page should be in the same table format and not like how the results gets displayed when a standard site search is done. I am at a loss on how to add a new search box in the home page, and how to link it to the view page with filtered results..

I am not looking for a complete answer to this problem, just some pointers on what area I should be looking at..I am pretty new to drupal and its pretty daunting to figure out which way I should explore more. I installed/uninstalled a lot of modules to see if they can do it, but they did not really help. Any pointers on which direction to explore would be highly appreciated!

As far as I understand you made 80% of the way.
I think you can do the following:

Add contextual filter to your view so you will be able to filter to results according to the zip code
Use your custom module (if you don't have one, this will be a good time to create one) to define a custom block (use the following hooks - hook_block_info and hook_block_view)
Create a custom form that will contain the search box and the submit button
Make a custom submit handler that takes the field value (the zip code inserted by the user) and loads the views page with the inserted zip code (the contextual filter we defined in step 1 will allow it)
Place the form in your custom block and place that sweet block in your homepage

References:
Create custom form

Edit:
By the way, the first comment is exactly what you need.

   function my_module_my_form_submit($form, &$form_state) {
    $first_name = $form_state['values']['first'];
    $last_name = $form_state['values']['last'];
    drupal_goto("/my_view/".$first_name."/".$last_name);
}

Hope that helps..
Rotem


Alter an existing view definition I have an existing view to which I would like to add some contextual filters if my module gets enabled. In D7 this was possible using hook_views_default_views, but I can't seem to find the equivalent in D8. Is this possible in D8?

Providing a view by using hook_views_default_views() is no longer possible. In D8 views are configuration entities. This means when a module wants to provide a view, it puts a yml file in /config/install.

If you want to change a view in code, load the view, change it and save it.

$view = View::load('test_filter_taxonomy_index_tid');
$display =& $view->getDisplay('default');
$display['display_options']['filters']['tid']['type'] = 'textfield';
$view->save();

A third alternative is to change the view directly in configuration, for example replace it with the content of a yml file:

$config_path = drupal_get_path('module', 'mymodule') . '/config/optional/views.view.myview.yml';
$data = \Symfony\Component\Yaml::parse(file_get_contents($config_path));
\Drupal::configFactory()->getEditable('views.view.myview')->setData($data)->save(TRUE);

The last option might be the easiest for your use case. You can configure the view in ui, export it to a yml file and use this file to overwrite the configuration of an existing view in hook_install().


Customizing user module output I am using Drupal 7 to develop a REST API to create an iPhone app. The basic feature for this app user login and logout process. I am using the User module. The authentication process involved is session authentication. JSON is the output format used for the API.

How do I customize the JSON output from the login service? I am getting a bunch of other information which I don't require. I am not sure how to add more tags to the JSON format. Can anyone point me to the files where the information is?

For example, for a wrong username and password I get the following output:

  Status 401 Unauthorized - Wrong username or password

  ["Wrong username or password."]

I would like to change the output to have something like {status: 0, message: 'Wrong username and passowrd'}.

Can anyone help me?

Use this for errors:

/**
 * Implements hook_rest_server_execute_errors_alter().
 *
 * Reformat error output.
 */
function up_coaching_rest_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {
  $error_alter_array['body_data'] = array(
    'success' => FALSE,
    'error' => $error_alter_array['body_data'],
  );
}

For success output you need clone needed resources from user resource definition.


Getting "--> ;" on front page after editing custom html.tpl file I am newbie and using Drupal - 7.

I have added script tags into my customized html.tpl file.

And now I am getting this "--> ;" into front page of my website.

This is the code for my customized html.tpl. file with script tags.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>
<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>

<body<?php print $attributes;?>>
<?php print $scripts; ?>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

Can anyone please help me?

Thanks!

it is probably stemming from this line:

 is a commenting system for HTML, but the item you are trying to comment out is php, which uses a different method for commenting.

you would use the html commenting around html elements:

whereas for php:

<?php //print $scripts; ?>

or

<?php /*print $scripts;*/ ?>

would be appropriate.


Why required form field has #required=FALSE on theme level? I have a form with managed file field. Form has single field. I have declared this field as required and indeed after submit without file I have an error: Field is required.

I wanted to add HTML5 validation to this field, but in my custom theme_file implementation $variables array has #required => FALSE for this field...

I have even red asterisk above this input field so I truly don't know what is wrong..

My custom theme_file:

function custom_file($variables) {
    if (! _custom_isMyTheme()) {
        return theme_file($variables);
    }

    $tpl = <<<HTML

%s

        %s

HTML;
    dpm($variables);//devel shows #required property as FALSE
    return sprintf($tpl, t('Select'), theme_file($variables));
}

In short, the hidden input field that stores the file ID (fid) is what is required, but the displayed file upload element isn't. The actual "displayed" element is added to that form element in file_managed_file_process() in file.module. Specifically, check out line 440 of that file:

  // The file upload field itself.
  $element['upload'] = array(
    '#name' => 'files[' . implode('_', $element['#parents']) . ']',
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#title_display' => 'invisible',
    '#size' => $element['#size'],
    '#theme_wrappers' => array(),
    '#weight' => -10,
  );

This has no #required property, and so therefore defaults to FALSE. If you dpm() your element earlier in the process (before it's expanded to include more hidden elements and attach the necessary javascript and CSS to be a full-fledged "managed file" element) you'll see your #required => TRUE.

I would add an additional function to the #process property of your form element, which will run after file_managed_file_process(). In it, you can check if the original element had #required => TRUE and then also set that on the $element['upload'] item. I haven't tried it, but I think that would get you what you want.

Edit: It would be wiser to do this in #after_build and not just append to #process. Here's an example:

<?php

function my_form_builder($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'managed_file',
    '#title' => 'Upload a File',
    '#required' => TRUE,
    '#after_build' => array('my_file_element_after_build')
  );

  return $form;
}

function my_file_element_after_build($element, &$form_state) {
  // Set the 'file' element to have the same #required property as its original form element.
  $element['upload']['#required'] = $element['#required'];
  return $element;
}

?>


How do I alter the page title after a controller sets the title? Is it possible to modify a page title after a controller sets #title in the main element?

Normally you can modify the page title by setting _title or _title_callback in the route. However it seems that you cannot alter the page title if a controller sets #title.

(A correct answer would affect both the HTML <title> and the system title block.)

Yes, #title from the controller overrides the title set in the route. There doesn't seem to be another override to override #title.

Though you could try to alter the controller output in a KernelEvents::VIEW with a priority higher than 0 like this:

$result = $event->getControllerResult();
// change the controller output
$event->setControllerResult($result);

Metatag

Working on a project I found out, that the metatag module in default configuration gets the title with the token [current-page:title], which retrieves the title from the route, ignoring #title set in the controller. Most times this would be considered as an unwanted side effect, but in your case you get the title you want from the route title callback in HTML <title> and only have to take care of the page title block, which should be no problem in a preprocess hook.


How do I get a form element to display in a lightbox? I'm currently using Drupal 7 and I'm using the Form API to generate the form.  What I'd like is for certain fields to be represented by a link, which when clicked on, opens the field in some kind of lightbox.  This is what I tried, but it doesn't seem to work:

  $form['snvisdt_note']=array(
  '#prefix' => "note\
",
  '#type' => 'textarea',
  '#title' => 'Add More Information',
  '#suffix' => "
",
  );

"screen" is the name of the page the form is on.  I am trying to do this in Lightbox 2, but would be happy to use some other solution, if it works.  Can someone please give me an example of what would work?

If you want to display form element into popup, then I would suggest you to use ctools api. It will provide you functionality to create a custom popup to render content.

  Ctools provide Modal dialog functionality to display element in modal.

You need to follow below step for the same:

Create a custom module and create Menu item which will interact with ctools modal.
Define ajax callback for the menu item and return HTML of the modal
using ajax.

You can check working example  (http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7)


limit view result to only commented nodes I created a view that gets the logged in user posts, But I need to alter that view a little bit to only show the posts that has a comment by a different user "not the OP".

Do I have to create a template and add PHP to it? or this can be done with views?

You don't need to code something here with powerful Views module.

First, add relationship “Comment: Comments of the node” to current View.
Then in “Query settings” check “Distinct” option. Now you have list of nodes which have comments.
Add contextual filter “Comment: Author uid”, set default value to “User ID from logged in user” and don't forget to check option “Exclude” in MORE fieldset.

Note that this solution works only for current logged in user.


How do I make #cols work in textarea? According to the Form API, you control the number of columns in a textarea with the #cols attribute. However, setting this seems to have no effect when I use it inside a $form array (the companion #rows attribute works as expected).

This is question is already on stack overflow however the answer utilizes css instead of the cols attribute which seems like a cheat.

    $form['message'] = array(
        '#type' => 'textarea',
        '#title' => t('Message'),
        '#resizable' => FALSE,
        '#cols' => 20,
        '#rows' => 10,
    );

Drupal will add the cols attribute to the textarea, however its CSS which controls it. i.e Width of the textarea or its container is controlling it.

Here is the fiddle example explaining this scenario

In the above example first textarea didn't affected by any CSS so it has 100 cols, however the second one is bounded with another container and its width is restricted, so textarea is rendered within the available width that's why cols value didnt affected the textarea.

The same is applicable for rows attribute when you set height attribute.


Form_set_error for array of fields I got below code in form_validation

$form_state['values']['field_address'][LANGUAGE_NONE][0][postal_code];

I've tried below tricks but it didn't make red color in textbox.

form_set_error('field_address][postal_code', 'error');
form_set_error('field_address[und][0][postal_code', 'error');
form_set_error("field_address[und][0]['postal_code']", 'error');
form_set_error('field_address[LANGUAGE_NONE][0][postal_code', 'error');

Your form_set_error like that

form_set_error('field_address][postal_code', t('enter postal code'.));


Pathauto tokens for taxonomy terms except root Thanks to pathauto and tokens it is very easy to generate URLs with [node:field_product_category:entity:parents:join-path]/[node:field_product_category:entity]/[node:title] \o/

But … I would like to start at the 2nd level, so is it possible to exclude the root level from [node:field_product_category:entity:parents:join-path]?

Example

What I have got: http://www.example.com/redundant_root_category/category_from_level_2/category_from_level_3/super_product

What I want: http://www.example.com/category_from_level_2/category_from_level_3/super_product

The default tokens won't allow you to do this, but the only thing you're missing I think is an array token that removes the first element, I'd call it "tail". See token_token_info(), which defines for example a 'reversed and other array tokens:

$info['tokens']['array']['reversed'] = array(
  'name' => t('Reversed'),
  'description' => t('The array reversed.'),
'type' => 'array',
);

And the implementation for that is in token_tokens():

// [array:reversed:*] chained tokens.
if ($reversed_tokens = \Drupal::token()->findWithPrefix($tokens, 'reversed')) {
  $replacements += \Drupal::token()->generate('array', $reversed_tokens, array('array' => array_reverse($array, TRUE)), array('array sort' => FALSE) + $options, $bubbleable_metadata);
}

Instead of array_reverse(), you'd call array_shift() on the array first and then pass that along.

Might also be a useful standard token to have in the token.module, if someone wants to provide a patch.

Your token would then look like this:

[node:field_product_category:entity:parents:tail:join-path]


Redirect user after registration I am trying to redirect new users after registration depending on values saved in $_SESSION. I use ajax for registration form submission and hook_user_insert fro redirect

function MYMODULE_user_insert(&$edit, $account, $category){
global $user;
if(isset($_SESSION['VAR']) && !$user->uid){
    drupal_goto('path/to/somewhere');

}

Once form is submitted I receive alert AJAX HTTP request terminated abnormally and page html code. What should I change to make redirect working?

You should alter the register form and set new redirect value.

function MYMODULE_user_register_form($form, &$form_state) {
  $form_state['redirect'] = 'path/to/somewhere';
}


Display all nodes posted on a certain month and day between 1990 and 2014 I want to display all nodes created on lets say, March 30 (between 1990 to 2014). Views contextual filters seems to display nodes posted on March 30 this year, how do i make the contextual filters include content posted on March 30 between lets say 1990 till 2014?

The custom module method is:

$nodes = node_load_multiple(db_query("SELECT nid
    FROM node
    WHERE MONTH(FROM_UNIXTIME(created)) = 3 AND DAY(FROM_UNIXTIME(created)) = 30 AND
    YEAR(FROM_UNIXTIME(created)) BETWEEN 1990 AND 2014")->fetchCol());

As far as I'm aware this isn't possible using the views UI so you would have to use hook_views_query_alter to get this working using views.


Get all content in all language using query I tired to get the content from db using query with some conditions and I need to fetch content in all languages. I have tried two methods, only english language content were fetched, but it doesn't work for all other languages...

Method 1:

    $langcd = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'page');
      ->condition('langcode', $langcd);
    $nids = $query->execute();

Method 2:

    $db = \Drupal::database();
    $query = $db->select('node', 'n');
    $query->fields('n');
    $query->condition('type', "page", "=");
    $query->condition('langcode', $langcd);
    $result = $query->execute()->fetchCol();

Every time I am getting only the English version of that content, but other language for that particular content was available in db. Please somebody help me to get the content in all other languages.

Following code should work:

$langcd = \Drupal::languageManager()->getLanguages();
$langcd = array_keys($langcd);
$query = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', 'page');
$query->condition('langcode', $langcd, 'IN');
$nids = $query->execute();

Get list of active languages first, then change condition for langcode to IN.


Redirect to profile2 page after adding user based on roles? I'm using rules and trying to get this workflow.

Site administrator adds new user -> redirected to the user's profile page to fill out information about the user.

I'm using the page redirect action to redirect to the profile2 edit page for the newly created user which works great. But I can't get this rule to trigger only for site administrators.

I've tried using data comparison [ roles= site administrator ] and user roles equals site administrator but neither work.

The idea is that the site administrators can add new users and fill out their profiles immediately.

Here's how to fix the problem I was having and a little more context on how to do it.

First you need the Rules module. http://drupal.org/project/rules

Go to the rules configuration page, usually located at example.com/admin/config/workflow/rules

Add a new rule
Add condition

User has role(s)
Parameters should be   User: [site:current-user], Roles: roles for condition
in my case
Parameter: User: [site:current-user], Roles: developer, site administrator

add an action

Page redirect to new user profile
Parameter: URL: user/[account:uid]/edit/'profilename'
replace 'profilename' with whatever your profile2 profile is called

Before I was using the default 'account' parameter, changing it to the User: [site:current-user] fixed my problem.


List child terms according to parent term page I created a view listing all parent terms  and child terms in my site. Following those suggestions:
Tiered HTML lists using Views and Taxonomy?

Now, I need to make the list of child terms change automatically according to the parent term page. For example:
In the parent term page: Fruits,
This view will show a only a list of those terms:

Bananas
     Apple
     ….

In the parent term  page: Colors,
This view will show only a list of Colors child terms:

Red
     Green
     Yellow

Any Idea how to do this?

In Drupal 7, I accomplished this by creating a view (for a block) that uses the contextual filter, "Taxonomy term: Parent term" - Under "When the Filter is Not Available" choose "Provide default value", then select "Taxonomy term ID from URL", and check "Load default filter from term page". I then displayed the block on the taxonomy pages where I want the child term lists to appear.

I'm just starting to work with Drupal and I suspect that there's a more robust solution - this works with pathauto but has trouble with terms that use a URL alias - but the instructions I've found for other approaches either don't work or require considerable coding. If you devise a better way, or somebody else has ideas, I'm all ears.


Tax calculation Drupal Commerce I've set-up a Drupal Commerce website. Clients add products in the backend and give each product a price INCLUDING taxes (in this case €160,00). The product fiches on the product page should show the products with taxes. In the shopping-cart block (in the sidebar) as well.

However, on the check-out pages, the line items should be shown WITHOUT taxes (€126,40 in this case). The taxes should only be added in the block on the bottom...

I hope I make myself clear with this picture:

Does anyone have an idea on how to do this? Because I don't :)

The Commerce Price Components module allows you to change what elements of a price are included when displaying it, including whether tax is included in the amount.  With that module, you can get the result you are looking for by editing the view behind your Checkout screen (from your screenshot).

Go to the Checkout screen so it looks like your screenshot.  In other words, be sure you have a VAT tax set up, and a product in your shopping cart, and go to Checkout.  The screen will look as you show above, ie the line item price will INCLUDE VAT.
There is a gear icon in the upper right of the screen (above the word TOTAL).  Hover over this and click EDIT VIEW.
You will be in the Commerce Cart Summary View.  In the FIELDS list, click on the Commerce Line Item Unit Price.
Change the Formatter to Price By Components, and be sure only Base Price is ticked.
Click APPLY
Do the same for the Commerce Line Item Total.
Click SAVE to save the View


function in inc file not being found I put this function in my inc file

function getLanguage(){
  $url=url() ;
  $language="";
  $pos=strpos($url,"/es");
  if ($pos===false){
    $language="en";
  }else{
    $language="es";
  }
  return $language;
}

And then I try to call that function from the module, but the module says Fatal error: Call to undefined function getLanguage()

What am I doing wrong? thanks

thank you pobtastic, this is the answer:

within the .module file you put your hooks and shared functions. Usually in the callbacks, you get to declare 'file' to point to an include for your functions to reside in a nice separate place. See api.drupal.org/api/drupal/modules%21system%21system.api.php/… and api.drupal.org/api/drupal/modules%21system%21system.api.php/… –  Pobtastic 1 hour ago


JOIN subquery as right table in Views I have a node field named event_date which contains multiple values of dates.

The table for the field looks like this:

node__field_event_date
+----------------+------------+
| entity_id(nid) | event_date |
+----------------+------------+
|              1 | 2019-1-1   |
|              1 | 2019-1-2   |
|              2 | 2019-1-3   |
|              2 | 2019-1-4   |
+----------------+------------+

I would like to join only earliest event_date for each node to the node base table(node_field_data).

node_field_data(short version)
+-----+--------+
| nid | title  |
+-----+--------+
|   1 | event1 |
|   2 | event2 |
+-----+--------+

The ideal result is:

+-----+--------+----------------+-------------------+
| nid | title  | entity_id(nid) | EarliestEventDate |
+-----+--------+----------------+-------------------+
|   1 | event1 |              1 | 2019-1-1          |
|   2 | event2 |              2 | 2019-1-3          |
+-----+--------+----------------+-------------------+

In raw sql, it can be written like this:

SELECT * FROM `node_field_data`
INNER JOIN (
  SELECT entity_id, MIN(field_event_date) AS EarliestEventDate
  FROM node__field_event_date
  GROUP BY entity_id
) AS event_date
ON node_field_data.nid = event_date.entity_id

But the problem is, the join should be done as a part of query for a View.

I tried the code below, but the Views didn't parse the subquery at all.

// in MY_MODULE.module

/**
 * Implements hook_views_query_alter().
 */
function MY_MODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() === 'events') {

    $subquery = "(SELECT entity_id, MIN(field_event_date_value) AS EarliestEventDate FROM node__field_event_date GROUP BY entity_id) AS node__field_event_date";

    $definition = [
      'table' => $subquery,
      'field' => 'entity_id',
      'left_table' => 'node_field_data',
      'left_field' => 'nid',
    ];

    $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
    $query->addRelationship('event_date', $join, 'node_field_data');
  }
}

What appeared on SQL preview in the view editing page:

LEFT JOIN {SELECTentity_idMINfield_event_date_valueASEarliestEventDateFROMnode__field_event_dateGROUPBYentity_idASnode__field_event_date} event_date ON node_field_data.nid = event_date.entity_id

Maybe I should try Views Plugin? But I don't have much experience making it and have no idea plugins can accept subquery like this.

If anyone have thoughts or ideas please give me advice...

It worked (in views plugin).

// create subquery using database api
$sub_query = \Drupal::database()->select('node__field_event_date', 'n');
    $sub_query->addField('n', 'entity_id');
    $sub_query->addExpression("MIN(n.field_event_date_value)", 'EarliestEventDate');
    $sub_query->groupBy("n.entity_id");

// create join
$join_definition = [
      'table formula' => $sub_query,
      'field' => 'entity_id',
      'left_table' => 'node_field_data',
      'left_field' => 'nid',
      'adjust' => TRUE,
    ];
$join = $this->joinManager->createInstance('standard', $join_definition);
$this->query->addRelationship('event_date', $join, 'node_field_data');

Edit:
If you do the same thing in hook_query_alter, change the last two lines like this.

$join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $join_definition);
$query->addRelationship('event_date', $join, 'node_field_data');


Private file (video) timeout? I'm wondering if the private file system has a timeout.
Because after many tries of watching a video uploaded by the file system both in public and private mode, with a low speed connection, the video from private always stops loading at around 20 minutes of playing. The same video, from public, works perfect ( it keeps loading after 20 minutes, until the end ).

I've tried on many computers, with different videos, always the same.

Can someone explain me how the private files works, so i can try to find a workaround.

Sorry for my english.

Thanks !

There is an issue with streaming video from the private folder because Drupal handles the permissions rather than apache. Use the resumable download module to overcome this. You should be able to enable the module and you are good to go.


How can I get all related entities of a node programmatically? I am writing some drush scripts and find myself needing to get related entities (nodes) of the current node. However I can only find info for constructing views that do this.

Can anyone tell me is there a programmatic way to pull all entities that relate to the current nid with a filter on the entity type?

Ultimately I need to get a list of node ids that relate to the current node id.

The relationship depend on the relation module.

Like this, you will get all the referenced items of the node being displayed.

  $current_path = explode('/', $_GET['q']);
  if ($current_path[0] == 'node' && is_numeric($nid = $current_path[1])) {
    $field = 'my_field';
    $bundle = 'my_bundle';
    $query = db_query("SELECT {$field}_target_id FROM field_data_{$field} WHERE entity_id = :nid AND bundle = :bundle",
      array(
        ':nid' => $nid,
        ':bundle' => $bundle,
      )
    );
    foreach($query as $row) {
      $target_ids[] = $row->{$field . "_target_id"};
    }
    $nodes = node_load_multiple($target_ids);
  }

If you have more entity reference fields, you have to expand the query (with more joins) according to your fields.


Adding an Image Style I'm new to Drupal, and I'm attempting to add an image style to a Basic Page in the "Manage Displays" area. After savings, there is no effect with the images on my basic pages (i.e. the image style was not applied) What would cause this, and how can I fix it?

Thanks! (PS - I'm sure this is probably a novice question.)

I think (if i did understand you correctly) you need to add a new image style first and then you apply it to your image in the manage display area.

you can add a new style by going to admin/config/media/image-styles and then click on "Add Style"


How can I conditionally reference an entity? I would like to have an inline entity reference form that will optionally provide a write-in text form if the entity doesn't already exist. Here's the use case: I want to reference a faculty profile that is associated with a particular research project; but I want the option to also associate another person who does not have a profile on the site. In a corresponding view, if the associated person has a profile on the site, their name will link to their profile, otherwise it will simply appear without a link.

Use Entity reference module to insert the references of the existing users to the content type.

  This project provides D7 versions of the 'node_reference' and
  'user_reference' field types, that were part of the CCK package in D6,
  at functional parity with the D6 counterparts.

For the rest of the users, you could use a textfield.


system_cron() eats all ram and runs forever Client doesn't ran Cron for >6 months. So in database, we had large tables. I have cleared  tables accesslog, cache_*, watchdog, flood manually in MySQL.

After that, running Cron runs forever. Especially system_cron(). What part of that function can cause this? It seems that probably mysql is eating RAM, but I'm not sure.

system_cron() touches following tables - cache_* (empty), flood(empty), batch(1 row), queue(159 rows), file_managed(18,163 rows).

Maybe something is wrong with file_managed?

Try Elysia Cron, it provides a lot of fine tuning and control over standard cron.

Khalid Bahey from 2bits.com wrote an extensive article regarding this module: Improving the performance of Drupal's cron by using the Elysia cron module


How to change taxonomy term path I am using taxonomy menu module but I want to change the taxonomy path from
 taxonomy/term/tid to subject/term title.

You need to use Path auto module .. Alias taxonomy term paths...

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.


Video Embed in FieldFormatter I want to embed the video as follows. I have written a FieldFormatter for this.

public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
      // Render each element as markup.
        $target_id = $item->getValue()['target_id'];

        $file = \Drupal\file\Entity\File::load($target_id); //load the file and its attribute.
        $parts = pathinfo($file->getFileUri());
        $new_filename = $parts['filename'] . '_' . $file->getCreatedTime() .'_selfhelpvideofid_' . $target_id . '.' . $parts['extension'];

        $video = '<video width="480" height="320" controls="controls">
                    <source src="movie.mp4"  type="video/mp4">
                  </video>';

      $element[$delta] = [
        '#type' => 'markup',
        '#markup' => $video,
      ];
    }

    return $element;
  }

The above is not working. Please help.

Instead of #markup, which is filtered, use inline template:

$file_path = 'movie.mp4'

$video = '<video width="480" height="320" controls="controls">
  <source src="{{ file_path }}"  type="video/mp4">
</video>';

$element[$delta] = array(
  '#type' => 'inline_template',
  '#template' => $video,
  '#context' => array(
    'file_path' => $file_path,
  ),
);


Development without pulling production DB to your local machine When you push configuration to production, any configuration that has changed in production that has not been exported into code will either be reset to the values in code or be wiped out entirely if they never existed in code. One out of many examples is changing the site name. If that change didn't go into code (i.e. if a content admin changed it, not a developer), the next deploy would reset that change.

Now the solution we have in place is to pull the production DB down and export the configuration against production code. Any differences appearing in the export are configs that have changed on production since last deploy. It's a process that you can easily wrap your head around (prod config - deployed config = changed config -> you check this in) and works pretty well so far.

But there are issues with this approach, one in particular is pulling the production database down. The DB may be huge, well into the hundred megabytes. It may contain sensitive info you don't want on your machines. Or it can only be retrieved indirectly (e.g. last night's cron job) and could already be stale by the time you work on it.

I know D8 config management is not perfect, and some things can't be avoided due to the current design of things. But I still would like to ask:

Is there a better way to do the process of resolving configs on deploy?
Is there any way to do this without pulling down the production database down?
Is there a Drupal/Drush/third-party module feature that already does what I am describing?
Is this more of a content workflow issue? i.e. never let content admins touch config?

Install Config Ignore and configure it to ignore those config objects from which you think they are going to be changed in production.

  Ever experienced that your site's configuration was overridden, by the
  configuration on the filesystem, when doing a drush cim?

  Not anymore!

  This module is a tool to let you keep the configuration you want, in
  place.

  Lets say that you do would like the system.site configuration (which
  contains that sites name, slogan, email, etc) to remain untouched, on
  your live site, no matter what the configuration, in the config
  folder, says.

  Or maybe you are getting tired of having the devel.settings changed
  every time you import configuration?

  Then this module is what you are looking for.


Formatting with Views So I'm using the Views module to list inventory items that include:

Name
Photo
Description
Sales document

I noticed that each item in the view is formatted differently because of size of text, image, etc.

Can I force a specific width/height with CSS, or is there an option within views? Here is an example of the situation.

If you're looking for uniformity across the view, I'd go with a teaser view mode on the nodes.  It's under display settings.  In view mode, you can control the length of the text that is trimmed, the size of the image,or whether or not you want field labels, or taxonomy terms showing, etc. In fact you can show a completely different set of fields that weren't visible on the default view mode. The upshot of this is the content will display exactly the same across the entire site without having to re-theme it in a block, in a different view, & so on.


AddThis Icons Being Blocked on SSL/HTTPS Site I've installed and configured the AddThis module to show sharing buttons to my users. It works great on my local machine. When I put the site on my SSL/HTTPS enabled site however the buttons do not show up (although I see the  they are in in the page inspector) and Chrome gives me JavaScript errors that the script being used to get those icons is calling from http://s7.addthis.com/js/300/addthis_widget.js...a not-secure link and is being blocked).

Does anyone know how to change the link the addthis module is calling to make it SSL/HTTPS compatible?

I ended up contacting AddThis and they told me the Drupal module is outdated, and to instead use this code:

So I put the first line (the  tag) in my html.tpl.php file and put the rest of the code in a block in my footer. I had to make sure to put all the  tags on the same line otherwise Drupal was forcing  tags between them making it impossible to style the toolbox correctly. Making sure the block content was set to 'Full HTML' and I was good to go.

The negative of this approach is that it requires another call to an external script. The positive is it negates the need for another module - you can safely remove 'addthis'.


Which menu should a third-party module choose, between "Structure" and "Configuration"? I noticed that some module prefers to add their menu items under "Structure," while other modules prefer to add them under "Configuration."

I thought that the reason of choosing "Structure" was because the menu items were related to some kind of "entities," but I then noticed that Rules is adding its menu items under "Configuration."
Vice versa, Views and Flags put their menu items in "Structure."

What is then the criteria to use when deciding under which menu a module put its menu items? Does the "Structure" menu contains only menu items that are related to content?

This and many other D7UX related things are best explained in the UI Patterns session from yoroy and Bohjan: Drupal 7: Interface patterns.

In short, Structure is meant for structural things which are used regularly (mostly during site building). If those modules add their stuff their and are not Views, Panels or similar, chances are that they are doing it wrong. :)

Not everyone exactly agrees on the IA (Information Architecture) of Drupal 7 yet or simply doesn't know about it. Not even Drupal 7 core is very consistent IMHO; I don't think the contact.module settings belong to Structure, for example, when not even those from path.module are, which are most likely way more often used.


Can I make Text Field accept filtered_html? I have a content type where a field is the common name for a USA president. In examing a legacy database I'm importing some presidents have (simple) HTML in their name. For example Dwight Eisenhower <i>Ike</i>.

I would like to support this on a content type field field_people_common_name which is a textfield created in the Field UI.

Following these directions:

https://www.drupal.org/update/modules/6/7#text_format
https://www.drupal.org/node/1087468

I've created a simple form alter hook to allow the input format of filtered_html on this form element:

function prez_people_form_people_node_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
  $form['field_people_common_name']['und'][0]['value']['#type'] = 'text_format';
  $form['field_people_common_name']['und'][0]['value']['#base_type'] = 'textfield';
  $form['field_people_common_name']['und'][0]['value']['#format'] = 'filtered_html';
  $form['field_people_common_name']['und'][0]['value']['#settings'] = array('text_processing ' => '1');
}

This appears to well, work or function:

But upon previewing the edit I get these errors:

Warning: mb_strlen() expects parameter 1 to be string, array given in drupal_strlen() (line 482 of ../htdocs/includes/unicode.inc).

Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1583 of ../htdocs/includes/bootstrap.inc).

Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1583 of ../htdocs/includes/bootstrap.inc).

Any idea how to get this to work. I'm trying to avoid embedding a text_area for simple textfield value (a name will never require a massive textarea .... yes I know I could make the textarea 1 row tall ....)

You shouldn't need to use hook_form_alter to allow the user to specify an input format for a textfield. On the content type page, you can edit a fields settings and there is an option titled "Text Processing" that you will want to use instead.

Then when I look at my node form I see the following:


Straightforward method to get related items view from Solr I have a Drupal 6 site with an Apache Solr search index.
I'm trying to create a block that displays 'related content', much like Stack Exchange sites have 'related' in the sidebar of questions.
The modules Apachesolr_views seems like a good candidate, but it's current development status and issue queue is less than inviting.
Does anyone have suggestions of a straightforward way to implement this?

The feature is actually built in to apachesolr.module. It is called 'mlt' (short for More Like This).

You can add differently configured MLT blocks via ?q=admin/settings/apachesolr/mlt/add_block and then configure their visibility in ?q=admin/build/block or whatever block visibility mechanism you are using (context etc).


How to display only  certain values  otherwise display empty field in Views I would like to display only certain values of CCK value in a views field. In another words, I don't want to display certain values of CCK in the views field. Is this possible?

For example I have a CCK field called "fruits" with multi selections of "orange", "apple", "banana". I have also a table view with a "fruits" field and then I would like to display only "orange" value but keep this field empty when the field have the value other than "orange"(when the value is "apple" or "banana" ).

You can make use of a computed field (fruits_computed) which takes the input value of the fruit field (fruits) and filters values via php, sth. like this:

$allowed_values = array('orange');
if ( array_in($fruits_value, $allowed_value) ) {
$output = $fruits_value;
} else {
$output = '';
}

Then in views, you do not use the fruits field, but fruits_computed.


Views with node references result redundant records I have three content types - Leg, Transport and Ticket. Transport has a node reference to Leg. Ticket has a node reference to Transport.
Thus, Leg and Ticket have an indirect way of relationship. But,Transport and Ticket have optional relationship.

I'm creating a view which lists transports of the given leg ( contextual filter ).
In the list, ticket is needed to join to show ticket price. Here is my views settings :

The view result is not what I expected. It lists unnecessary and duplicate records as shown in the screen shot.
The first two records ( in the red box ) should not be listed here. They are redundant of the last two records ( in the red circle ). You can see prices are not showing for the first two.

Aggregation did not help me in this case.

I have found the most possible answer. It may need to update the query from hook_views_query_alter(). The generated query from views is here :

SELECT node.nid AS nid,
    field_transport_node.nid AS field_transport_node_nid,
    field_transport_node__field_data_field_price.field_price_value AS field_transport_node__field_data_field_price_field_price_val,
    node.created AS node_created,
    'node' AS field_data_field_dept_time_node_entity_type,
    'node' AS field_data_field_travel_time_node_entity_type,
    'node' AS field_data_field_transport_type_node_entity_type,
    'node' AS field_data_field_price_node_entity_type,
    'node' AS field_data_field_travel_optr_node_entity_type,
    'node' AS field_data_field_ticket_office_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_transport} field_data_field_transport ON node.nid = field_data_field_transport.field_transport_nid
LEFT JOIN {node} field_transport_node ON field_data_field_transport.entity_id = field_transport_node.nid
LEFT JOIN {field_data_field_leg} field_data_field_leg ON node.nid = field_data_field_leg.entity_id AND (field_data_field_leg.entity_type = 'node' AND field_data_field_leg.deleted = '0')
LEFT JOIN {field_data_field_price} field_transport_node__field_data_field_price ON field_transport_node.nid = field_transport_node__field_data_field_price.entity_id AND (field_transport_node__field_data_field_price.entity_type = 'node' AND field_transport_node__field_data_field_price.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('transport')) AND (field_data_field_leg.field_leg_nid = '2' ) ))
ORDER BY field_transport_node__field_data_field_price_field_price_val ASC, node_created DESC
LIMIT 20 OFFSET 0

I just need to add a condition with "OR". It gives me the correct result.

AND ( ( field_transport_node.nid IS NOT NULL AND field_price_value IS NOT NULL ) OR ( field_transport_node.nid IS NULL AND field_price_value IS  NULL ) )

How can I add this kind of OR condition from views UI ?
How can I do it with query object of the views ?

function mymodule_views_query_alter(&$view, &$query){
    switch($view->name){
        case 'my_view_name' :
            $query->where[0]['conditions'][] = array(
                'field' => '',
                'value' => '',
                'operator' => ''
            );
            break;
    }
}


How can I send Newsletter in HTML format? I have  installed the following modules simplenews, mailsystem, html mail to send HTML news letter from a Drupal 7 site. Right now, I am just able to send plain text email from send test option. How can I send an HTML email from my site? How can I send a newsletter to registered emails of my site?

You can use Mime mail along with your newsletter module to enable HTML in your emails. This module will work on the message mime so it should work with almost any mail module


Set entity reference target_id in migration yml I migrate Drupal 6 to Drupal 8. In Drupal 8 I have content type that has field with type Entity reference that reference specific taxonomy dictionary. I can't find out how to set Entity reference field target_id in yml migration file. I have tried:

field_my_field:
  plugin: iterator
  source: field_my_field
  process:
    target_id:
      plugin: default_value
      default_value: 19

I would expect that code above set Entity reference (field_my_field) to reference term with id 19 (that already exists). There is no error (or message) and default_value plugin is called correctly a returns 19. But in migrated content is not reference set.

I tried to set reference manually and then dump it and result was:

[field_my_field] => Array
  (
    [x-default] => Array
      (
        [0] => Array
          (
            [target_id] => 19
          )
      )
  )

I have tried lot of other ways how to set entity reference target_id but nothing actually work. Do anybody know how to set entity reference target_id in migration yml file?

Old question, but I'm guessing you need to add the array for the item list. I was successful with:

field_something/0/target_id: YOUR_VALUE_HERE

I haven't found documentation on the slash in the field id, but it is an array notation. The above is equivalent to something like:

$destination_values['field_something'][0]['target_id'] = YOUR_VALUE_HERE


I could not access a page as administrator user I just had a problem where a page created with a custom module caused an access denied error even when logged in as administrator user.

function cmis_play_menu() {
  $items['cmis_play'] = array(
    'title' => 'cmis_play',
    'page callback' => 'cmis_play_page',
  );

  return $items;
}

function cmis_play_page() {
  return 'boot';
}

I checked the following.

The administrator user has all the privileges
Cookies are disabled in settings.php
The database username and password are correct

I tried the following (without success):

Drush CC all
Truncating the session table
Accessing the page as a guest and as non administrator (but authenticated) user

I solved the problem by adding the following line:

$items['cmis_play'] = array(
  'access arguments' => array('administer news feeds'),
);

Why did I need to do this?
How do I configure Drupal so that expressly setting access permissions for a page is not needed?

From hook_menu():

  "access callback": Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments'

Emphasis mine.

So if you don't provide an access callback explicitly, user_access() is used, which, unless you're logged in as user 1 which is a special case, returns FALSE if you don't provide it with any access arguments. That's why passing in access arguments fixed it.

You can't change this default behaviour without changing core Drupal files. Being explicit about your access is better than being implicit anyway - default should always be to deny.


Fatal error: Class 'SelectQuery' not found in /*/includes/database/database.inc on line 813 My site works fine in local system, Upload code and database in server show Error.

Fatal error: Class 'SelectQuery' not found in /*/includes/database/database.inc on line 813

Check database setting in settings.php file. If database configuration is right then just clear the cache and rebuild registery.


How to retroactively apply Mollom spam filtering? I've been asked to clean up a site that's been running for a few years, and has accumulated some spam in addition to a lot of valid content.

I've just installed Mollom on the site to help reduce future spam postings; but is there some way I can have Mollom process what's already been posted to the site, and flag potentially-spammy content for my review (rather than having to review all of the mostly-valid content individually)?

Not currently. See http://drupal.org/node/734476 for the feature request in the Mollom issue queue.


Rules - Send mail to all addresses in email field of specific content type I have a content type (school) with an unlimited email field (field_email).
Now on creation of another node (page), I would like to send to all emails stored in the "field_email" of all school nodes an email.

I started by created a rule with the "rules" module but i cannot figure out how to pull the data from a separated node (school).

Could someone point me in the right direction?

You can use Views Rules module. For achieve this goal first you have to create a view to get all mail values of content type (school) and than its result provide to rules using this module. For more information go through the documentation of Views Rules module.


Pre and Post event on AJAX call In a form, using #ajax to add a callback when a button is pressed. When the button on my form is pressed, I wish to call some JavaScript when the button is pressed and once again when the AJAX call is complete. can anyone suggest?

The "duplicate" I linked to above gives you almost all of your answer, but this adds the "complete" function that you asked for.

In a custom js file in your module (this assumes that your module is named ajax_example and that the ID of the element being clicked is #edit-submit):

Drupal.behaviors.ajax_example = {
  attach: function (context, settings) {
    // Overwrite beforeSubmit
    Drupal.ajax['edit-submit'].options.beforeSubmit = function (form_values, element, options) {
      console.log('before');
      // Add your on click code here
    }
    // Overwrite complete
    Drupal.ajax['edit-submit'].options.complete = function (form_values, element, options) {
      console.log('after');
      // Add your on complete code here
    }
  }
}


Exit pop up with registration form I want to have anonymous users to have a pop up displayed after they visit first page and moving to second page. The pop up should have a Name and email and after submission user gets registered to our website. I'm confused which existing module can achieve it. I tried using popup module.  Or do I have to custom code to achieve it?

If you're looking for a module, try Splashify. Splashify is although not available for Drupal 6. Tinybox can help too but I haven't tried it myself.

You can also create this yourself, simplest way would be to change your front-page in configuration in toolbar, create that page, in drupal template, write something like this:

<?php
if (drupal_is_front_page()) {
    ?>
/*Your Splash Screen Code*/
<?php
    }
?>

Your Splash Screen Code can be a simple HTML Model, see this Simple Tutorial.


Checkboxes options with class in form api I need something like a filter on checkboxes #options in my form built via Form API.
Is there a way to group checkboxes or add a class to filter them via js front side?

In the documentation options are simply 'value' => 'label'. Can I filter or group them?

To modify how drupal outputs checkboxes, override the default theme_checkbox function found in includes/form.inc. This allow to you add classes and all other stuff. I simply copied the function and changed the last 8 lines:

/* Override theme_checkbox to display titles as facebook-style beautytips  */
function MYTHEME_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  if (substr($element['#name'],0, 13) == "field_MYFIELD") :
    $element['#attributes']['class'][] = 'beautytips';
    return
      '<input title="' . $element['#title'] .'" ' .
      drupal_attributes($element['#attributes']) . ' />';
  else: // Return the regular value
    return '<input ' . drupal_attributes($element['#attributes']) . ' />';
  endif;
}

Thanks @clive for the inspirtation.


How to create twig files content type specific in Drupal8? I have created a content type in Drupal 8. How should I write content type specific twig file?

you can use this file for specific content type "node--{content type machine name}.html.twig".
Please check this url for Twig Template naming conventions.


Affect a theme to a view page So, I create a view page that list the webform results, and I want to affect the administration theme to this page, How ?

Thank you.

Check admin_theme module. This will allow you to set custom pages in admin theme.


How to replace the title of the profile in the breadcrumb, by the name of the user? I installed the "Profile" module. I have rewritten the url with the username instead of the profile title.

When I visit a profi, the url is corect but the breadcrumb is still indicating the title of the prodil.

How to replace the title of the profile in the breadcrumb, by the name of the user ?

you can implements this hook in a custom module or in your theme.

hook_preprocess_breadcrumb()

Then you can access $variables and manage it easily (like put the username in the last element of the array).
Regards,


Field collection with condition node tpl I've been researching this for the last few days and I cant find a clear explanation of this issue im facing.  I'm receiving an error when a node has an empty collection with no values.

The collection field: field_window_shade
The fields within the collection: field_question, field_answer

Here is my code that is only looping thru the collection array within my node.tpl:

            $wrapper  = entity_metadata_wrapper('node', $node);
            $formtype = field_get_items('node', $node, 'field_window_shade');

            foreach($formtype as $itemid) {
                 $item = field_collection_field_get_entity($itemid);
                 print $item->field_question['und'][0]['value'];
                 print $item->field_answer['und'][0]['value'];
            }

I am after something like this:

            $wrapper  = entity_metadata_wrapper('node', $node);
            $formtype = field_get_items('node', $node, 'field_window_shade');

            if (isset($wrapper->field_question)) {
              foreach($formtype as $itemid) {
                 $item = field_collection_field_get_entity($itemid);
                 print $item->field_question['und'][0]['value'];
                 print $item->field_answer['und'][0]['value'];
              }
            }

I've seen this question asked about 5 different times with 10 different solutions and I can't seem to reach a solution here.

Thank you !

Did you try field_collection_item in entity_metadata_wrapper? I mean this

$wrapper  = entity_metadata_wrapper('node', $node);
$raw_collection = $wrapper->field_window_shade->value();
$fwrapper = entity_metadata_wrapper('field_collection_item', $raw_collection);

Now use $fwrapper to extract the items (This code is not completely accurate a few modification may be needed)

Visit Extracting a specific data part of a Field Collection Item for more details. Also Programmatically create and update field collection with Entity API and Understanding Field Collection Values can be helpful.


Create node from JSON I'm looking to write the following module, any help, guidance, and advice would be greatly appreciated.

User is logged into site.
Site has two content types: page & note.
Logged in user can create content type note only.
User is viewing a node: /node/5.
User selects some text in the body.
Link/icon is shown above selected text.
User clicks clicks and is taken to /node/add/note
Some fields are pre-populated on Node edit page, including:

title, field_source_quote, field_entity_reference_nid

User adds his "note" to field_user_note and saves note

From my basic understanding of JSON, I should be able to create a JSON of the user selected text with something like:

var selectedText = "";
selectedText = window.getSelection().toString();

var noteData={
    "sourcePath": "/node/being/viewed",
    "selectedText": selectedText
};

How do I get noteData to a module? Better yet, how do I get nodeData to the node/add/note page and pre-populate the correct fields?

Any help would be greatly appreciated.

======= Updates Below =============

Passing data through local storage (Andrew's Approach)

I can confirm this approach is viable. There are a number of issues, however that this presents:

I'm sure this is not the most "drupal-ized" way to perform this.
If the node admin pages use a different theme, the js to retrieve and apply the data must be within the other them.
Need to have a persistent marker placed for the user ui (i.e. highlighting the text they have added a "note" to).

I've come across a library that might be helpful for #3: Rangy (https://github.com/timdown/rangy).

Here is a little working piece of code for you. You may extend it according to your needs

document.onselectionchange = function() {
    var selectedText = "";
    $('div').mouseup(function() {
      //Save selected text in localStorage.
      selectedText = window.getSelection().toString();
      if (selectedText.length > 10) {
        var noteData={
          "sourcePath": window.location.href,
          "selectedText": selectedText
        };
        localStorage.setItem('noteData', JSON.stringify(noteData));
        window.location.href = '/node/add/page';
      }
    });
  };

  // Get saved data from localStorage and insert in the form.
  var savedNoteData = JSON.parse(localStorage.getItem('noteData'));
  if (savedNoteData && savedNoteData.selectedText) {
    $('.form-item-title input').val(savedNoteData.selectedText);
    localStorage.setItem('noteData', '');
  }


Get the parent menu of the node I've a node, which is linked to a sub menu in the main navigation. I would like to get the url and title for the parent menu of the sub menu selected.

I've used it, but it is not working.
I'm trying to use it in hook_node_view()

$node_id = $entity->id();
      $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
      $result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
      $build['result'] = $result;
      kint($result);

In twig, I'm calling it as

{{ content.result }}

But it is not working..

If you want to get the parent of the menu link use getParent():

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
if ($link = reset($links)) {
  if ($parent = $link->getParent()) {
    $parent = $menu_link_manager->createInstance($parent);
    $parent_title = $parent->getTitle();
    $parent_url = $parent->getUrlObject()->toString();
  }
}


How to create an Achive with views I want to create an archive from my news with views and filter it by post date.
How can I do it?
Thank you

There's a default view that comes with the Views module that will provide the block, it's called Archive and that'd be your best start point, enable it in admin/structure/views and  you'll get both the block with the items grouped by date and a page.

Find an advanced customization of this in http://www.webbykat.com/2012/02/creating-monthly-archive-block-drupal-7-views


How to access the value of a Drupal\Core\StringTranslation\TranslatableMarkup object within a form? I tried this : dpm($button['#value']->string
but got this error:
 access protected property Drupal\Core\StringTranslation\TranslatableMarkup::$string

Within a form object I need to be able to read that value and also change it.  how can I access it?
thanks

You can get the string value by calling the magic function ->__tostring() or casting the object to a (string). But most time you don't need to do this, because if you use the translation object in a string context it will return the translated string automatically.

You can't change the original string in the translation object. You have to generate a new one with the t-function:

$button['#value'] = $this->t('new text');


How to make the File Attach option available? When attaching a file to an instance of a content type, there is an option to use ‘file attach’.
This is an alternative to uploading a file to the server from one’s local computer. Instead, when creating the content, you click on File attach option and it shows the contents of the folder sites/default/files/file_attach.

but i don’t remember how to get this option to be available! does anyone know?

this is much more efficient than uploading files from my laptop to the server

thank you,

On the edit page of the content type that contains the file field, there is a  closed pane labelled 'File Attach Setting'. Inside of that is a checkbox that reads 'File attach from server directory'. It needs to be checked.

Also note, regardless of where you've specified that the file be stored, the module will create a dir named file_attach. This confused me earlier. I thought it was looking only for files in the default directory ie
sites/default/files/file_attach


User with permission can't add an event to calendar by clicking I have a working calendar (from the module calendar).

As administrator, i can click on a date and a popup allows me to add an event.

But users, who are allowed to add an event, can't do it. They can add an event by navigation and clicking on"add content", but they can't do it, like me, the administrator.

Can someone help me? I guess, it's somewhere in configuration but I don't find anything.

Thanks for any advice!

Can you clarify? You said:

  users, who are allowed to add an event, can't do it. They can add an
  event by navigation and clicking on"add content", but they can't do it

what do you mean they can't do it? Can they navigate to /node/add/[event] (I'm not sure what your event node type is called)? Or when they do go to /node/add/[event] does something happen when they try to save the new event?

Are you sure you have the permissions set correctly for their role? Check out the permissions at admin/people/permissions. Double check the permissions under Node.


Feed import of CSV file only in imports the title and nothing else. It also has paragraph fields I'm trying to import a small subset of my data to test out how well it would go first before importing 20k records. I'm using the latest feeds module with the paragraphs feeds importer (https://www.drupal.org/sandbox/shaney/2862236). For now I'm only importing:

guid
title
field_client
field_award_status (paragraph field under"award")
field_award_name (paragraph field under "award")

The only successful import is the title, but nothing else shows up. Below is a preview of my csv data and my feed mapping settings. What could I be missing?

I checked the csv file in an editor it found the culprit was because I deleted a bunch of records using excel and it left alot of empty commas everywhere. You have to go into the csv file and edit it manually.

Also it wasn't importing because the values need to be in quotes.


Views field: & content: different What is the difference between the 2 fields as follows:

Content: Abbreviation
This is an alias of Field: Abbreviation.

Field: Abbreviation

And if they are the exactly the same, why is Drupal listing them twice?
Check the attached screen shots for more details.

This is something that Views does when a particular field is used in more than one Entity type. In your case, the "Abbreviation" field is used both by node entities (the "Content" views group) and by taxonomy term entities.

It represents the field in both the "Content" and the "Taxonomy Term" group, so that if you were filtering the list by group, you wouldn't be missing it in the list.  But it also represents itself canonically in the "Field" group, to correctly inform the user that the field is available in multiple entity type contexts. This would be important knowledge if you had both entity types available in your View because of a relationship.


View that Shows Result Links I have a view that prints the titles of my 10 most recent news item content.  I also want to print the URL to these news items.   How do I do this?  When I edit the view, under Fields, I see a Link field, but the problem is that it prints the word "view" instead of http://mysites.com/my-first-news-item

I almost got it....the field i'm looking for is called Content:Path.  Right now, it prints /my-first-news-item.  All I need to do now is have it print the domain name as well.....almost there.

EDIT
Figured out the last part.  To print out the absolute path, make sure the field also has the setting Use absolute link (begins with "http://") checked