Drupal Error : The website encountered an unexpected error. Please try again later I made a site locally and when I uploaded it to the hosting server, it worked fine except when I went to edit some content type. It showed this error:

The website encountered an unexpected error. Please try again later.

It was showing nothing except the above error. To get more error output, I added a few lines to my index.php file (these lines were added right after the first line):

error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE);

The error output was now showing this error:

  Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in
  /home/a2682242/public_html/includes/database/database.inc:2171 Stack
  trace: #0
  /home/a2682242/public_html/includes/database/database.inc(2171):
  PDOStatement->execute(Array) #1
  /home/a2682242/public_html/includes/database/database.inc(683):
  DatabaseStatementBase->execute(Array, Array) #2
  /home/a2682242/public_html/includes/database/database.inc(2350):
  DatabaseConnection->query('SELECT expire, ...', Array, Array) #3
  /home/a2682242/public_html/includes/lock.inc(167): db_query('SELECT
  expire, ...', Array) #4
  /home/a2682242/public_html/includes/lock.inc(146):
  lock_may_be_available('theme_registry:...') #5
  /home/a2682242/public_html/includes/theme.inc(449):
  lock_acquire('theme_registry:...') #6
  /home/a2682242/public_html/includes/bootstrap.inc(446):
  ThemeRegistry->set(Array) #7 [internal function]:
  DrupalCacheArray->__destruct() #8 {main} thrown in
  /home/a2682242/public_html/includes/database/database.inc on line 2171

The site was working fine locally. I am not having much clue as to where the problem is. Is it some problem with the mysql server setting of my hosting provider? Or something else?

Please try increasing your max_allowed_packet setting in MySQL.

Open my.cnf file & update max_allowed_packet = 16M or more


Maisystem module not saving my custom class on production server I have an issue with Mailsystem.
I want to use the Mailjet module to send my emails, and the HTMLmail module to format them.
I did it on my development server and it worked fine. I did the following :
On Mailjet administration page : admin/config/system/mailsystem
New class :
Class to use for the format() method >> Htmlmail
Class to use for the mail() method >> MailjetSmtpMailSystem
Then i saved the configuration, and in "Site-wde default MailSystemInterface", the new class showed up : HTMLMailSystem__MailjetSmtpMailSystem.

Then i tried to do it on my production server. It doesn't work. When i try to create a new class and hit "save" the new class is not saved.
I found the following error in my logs :
The specified file temporary://files5RLHj could not be copied to sites/default/files/mailsystem/HTMLMailSystem__MailjetSmtpMailSystem.mail.inc.

So of course i checked the rights.
I do have all the rights on the files folder and on the mailsystem folder.
I also have the rights on the tmp folder.

I checked with my ISP and he said he tried everything too and doesn't know what he can do.

I tried to copy manually the temporary file to its destination, but Mailsystem doesn't seem to realize it's there.

Please, tell me you have an idea where this problem comes from.

Thank you

http://php.net/manual/en/features.safe-mode.php
notes

  This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

So in general it is not very useful feature and turns out to be causing issues with some applications when they try to write to the file system.


how to check messages exists I want to check is there any messages in my template
in drupal 7 there was a global variable in page template variables messages

now in drupal 8 I want to check  is there any message  but messages variable in page--front.html.twig is always empty, alternative way is check  region highlightes( because  status messages block is in highlighted region)
but below  statement always return TRUE,

    {% if page.highlighted %}
      {% block highlighted %}

{{ page.highlighted }}

      {% endblock %}
    {% endif %}

is there any way to check that messages exists in page in drupal 8?

While the page.highlighted variable contains the block data (mytheme_messages) for message display, the block rendering data doesn't contain the messages themselves, so there's no way to check for message existance there.

However, you can inject a custom variable based on the current message queue from drupal_get_messages().

For example, in your MYTHEME.theme:

/**
 * Implements hook_preprocess_page() for page.html.twig.
 */
function MYTHEME_preprocess_page(array &$variables) {
  // Inject a flag based on the current message queue.
  $variables['available_messages'] = !empty(drupal_get_messages(NULL, FALSE));
}

And within your page.html.twig:

{% if available_messages == true %}
   <!-- TODO: Add custom markup when there are messages -->
{% endif %}


How to alter an existing Views display? I know in order to create views displays you simply declare it as:

  $view = views_get_view('AN_EXISING_VIEW', TRUE);

  $handler = $view->new_display('page', 'YOUR_DISPLAY_NAME', 'YOUR_DISPLAY_MACHINE_NAME');
  $handler->display->display_options['title'] = 'TITLE';
  ...
  views_save_view($view);

You can do this in hook_enable in your install file or using hook_views_default_views

All I need is however to programatically alter an existing view display of a Workbench Moderation module (workbench_moderation): 'YOUR_DISPLAY_NAME' and 'DEFAULT' in order add other fields and permissions on those fields.

My questions are:

How do I effectivelly get the specific display: e.g. $views->get_display?
How do I save it so that will not mess the views caches?

Views provided by a module are defined using hook_views_default_views - and as almost anything, they can be modified using "alter" version of this hook, namely hook_views_default_views_alter:
Alter default views defined by other modules.

This hook is called right before all default views are cached to the database. It takes a keyed array of views by reference.
Example usage to add a field to a view:

$handler =& $view->display['DISPLAY_ID']->handler;
// Add the user name field to the view.
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = 'Author';
$handler->display->display_options['fields']['name']['link_to_user'] = 1;

Source code from API help page linked above.


How to gather user opinions via a survey based on tagging? I'm completely new to Drupal, and am hoping it can help me with this job without me having to do too much tweaking.

I'm looking to gather user opinions on different subjects, but would rather not do it with a regular questionnaire type survey. I'm looking for something which would allow users to select topics and simply tag them with whichever words they find appropriate.

Does anyone know of a feature like this?

You can easily do this with taxonomy free tagging

Step 1 : Create a vocab, going at admin/structure/taxonomy/add
check the screen shot after adding a vocabulary named as survey.

Step 2: Create custom content type,going at admin/structure/types/add

Step 3: Add taxonomy term reference field to it.Check the settings in screen shot

once you click on save it will take you to next config page,where you will be choosing the vocab you created in step 1

Clicking field settings will take you now to last configuration page as in screen shot


Upgraded to 8.8.3 and now all of my modules say "No available releases found" I just recently updated to 8.8.3 and for some reason, all of my modules now say "No available releases found". Also the one module I had that did report "No available releases found" (Video Embed for google drive), is now saying that that module is up to date. It is like they switched somehow when I updated. I might roll back but the site is currently working just fine. Any ideas?

Clicking "Check manually" once on the Available Updates page will resolve this issue.

Please see https://www.drupal.org/project/drupal/issues/3120168 for more info.


Single page Drupal apps with custom theme I have a static HTML page which contains navigation that links to different sections on the same page. Just like this one http://www.cedricvella.com/#node-3 .

What I would like to know is how can this functionality be built with Drupal when creating a custom theme. I don't want to use Panels.

Is there a way you can pull each page node into one single page?

you could do it using the single page module. Each menu item can be a single page which can be mapped to a node.


How to use views to display a list of views pages? I currently have a view that outputs all the current nodes on a site in a table format to display things like:

Title
Nid
Path
Metatag Title
Metatag Description
Metatag Keywords
Post Date
Updated Date
and an edit link.

We mainly use this view to review our SEO optimisation in terms of the meta tags and the path constructions for each "page" on the site.

It's a nice system, but it has one major failing - it does not include any views pages - things like event listings or news listing pages. These views pages are just as important for SEO optimisation but I cannot get them to be included in this review list.

The metatag information is provided by the D7 Metatag module. With that module, we can add tag information to views pages, which is great, but to complete this admin view, it would be good to be able to include the views pages on the site in the above list as well.

It would be fine for this to be displayed in a standalone output (ie not included in the full table page above) but I cannot for the life of me find a way to get this done.

Is there any way to create a view that will list all view pages on a site with their associated meta information?

Thanks!

What you're asking is not possible. De data that the views stores is not provided back to the views module. As you've noticed, you're not able to create a list of views using a view.

I can think of two options to make this possible:

Create a (complete) custom module that selects and outputs the values you desire
or, provide the views module with the data you need to create the list you want

Both options require custom code to make it possible. At this moment, both views and metatags don't allow you to do what you want.


Commerce: Hide "Save and Add Another" button when saving new product I'm trying to hide the "Save and Add Another" button on the form used to save new products.

I can access the "Save" button in the $form array at $form['actions']['submit']. However, I'm not seeing the "Save and Continue" button in $form.

I looked in commerce_product_ui.module and found the place where this form element is being added. It's called $form['actions']['save_continue']. I would expect to see it in the $form array, but again - it just doesn't seem to be there.

Thanks for your help.

implement hook_form_alter

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_product_ui_product_form') {
    unset($form['actions']['save_continue']);
  }
}


How to render a form in custom template? I'm looking to add a form inside a custom template. The form, if I open the path registered inside the file cmodule.routing.yml, works but if i try to use it inside a custom template it doesn't work: with a dump(form) or dump(form.anyfield) i get NULL.

cmodule.routing.yml:

cmodule.manageform:
  path: '/cmodule/manageform'
  defaults:
    _title: 'Documents'
    _form: '\Drupal\cmodule\Forms\RequestForm'
  requirements:
    _permission: 'access content'
cmodule.manage:
  path: '/cmodule/manage'
  defaults:
    _controller: '\Drupal\cmodule\Controller\CmoduleController::manageAction'
    _title: 'Custom Documents'
  requirements:
    _permission: 'access content'

RequestForm.php:

/**
 * {@inheritdoc}
 *
 */
public function buildForm(array $form, FormStateInterface $form_state) {

    $form['type'] = array(
        '#type' => 'radios',
        '#options' => array(
            '0' =>t('DOC'),
            '1' =>t('PDF')
        ),
    );
    $form['pid'] = array(
        '#type' => 'textfield',
        '#title' => t('ID:'),
        '#required' => FALSE
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
        '#attributes'=> ['class'=>['glyphicon', 'glyphicon-search']],
    );

    return $form;
}

cmodule.module:

/**
 * Implements hook_theme().
 */
function cmodule_theme(){

    $templates = array(
        'manage_cmodule_page' => array(
            'variables' =>
                [
                    'id' => NULL,
                    'form' => NULL
                ],
            'template' =>'manage_cmodule',
            'render element' => 'form'
        )
    );

    return $templates;
}

the controller contains:

public function manageAction() {

        $id = 1;

        $form = \Drupal::formBuilder()->getForm('Drupal\cmodule\Forms\RequestForm');

        $form['type']['#title_display'] = 'invisible';

        return [ '#theme' => 'manage_cmodule_page',
            '#form' => $form,
            '#id' => $id,
        ];
    }

and then the template/view (contains):

<div>
 {{ form.form_token }}
{{ form.form_build_id }}
{{ form.form_id }}
{{form.type}}
{{form.submit}}
</div>
etc..

But as I said above the template doesn't show the form, but show (if i print it) the #id value passed through the controller.
Do you have any suggestions?!

UPDATE #1
I tried also to follow the suggestion of Beebee, and then this and this so the code is:

controller:

controller contains:

public function manageAction() {

        $form = \Drupal::formBuilder()->getForm('Drupal\cmodule\Forms\RequestForm');

        $render['#form'] = $form;
        $render['theme'] = 'manage_cmodule_page';
        return $render;;
    }

and the implementation of hook_theme in .module file is:

return [
    'manage_cmodule_page' => [
        'template' =>'manage_cmodule',
        'render element' => 'form',
    ]
];

The result is an empty page with an error inside the apache log:

  [php7:error] [pid 12660:tid 1592] [client ::1:59521] PHP Fatal error:
  Out of memory (allocated 270532608) (tried to allocate 266354688
  bytes) in
  C:\drupal\vendor\twig\twig\lib\Twig\Extension\Debug.php on
  line 60, referer: http://localhost/drupal/

if I remove the following row from the controller

$render['theme'] = 'manage_atps_page';

the page loads, but it is empty (without any form).

UPDATE #2

I fixed my issue following also the idea of Alex Kuzava. Thus I used the code of UPDATE 1, with the new directory of the form, and then I added these 3 lines inside the  part of my template (otherwise the submit button doesn't work).

{{ form.form.form_build_id }}
{{ form.form.form_id }}
{{ form.form.form_token }}

'render element' => 'form'

Your render element is form which means all provided variables will be passed there.

In your twig template you can render your form like here

<div>{{ form.form }}</div>

UPDATE #1

Wow man, you have wrong namespace Drupal\cmodule\Forms\RequestForm

Should be Drupal\cmodule\Form\RequestForm

Please rename Forms to Form (the same for directory) and clear cache. It should help you.


how to create regions on zen I would create regions on my zen theme, reflecting the narrow columns side by side.

I want a layout that does not provide the content by default, but it plans to create 3 sidebar facing the same width.How can I do?

EDIT

Also, I want the page layout different from the initial layout of other pages, so I can have different layout templates with different regions?

In the file your_theme.info you should add

regions[new_region] = New Region

regions[new_region] this is the machine name so the variable will be $new_region

Then on page.tpl.php you should add the html and the php like

<?php
if ($new_region) :?>
<div id="new-region">
<?php print $new_region; ?>
</div>
<?php endif; ?>

Remember to flush the cache and do the performance after you modify page.tpl.php


Mimic webform date field in custom form In one instance we are using a webform to create a form and it uses field type 'date'. The end result looks like this:

I would like to mimic this, but in a custom form. Currently what I have is:

Code:

 $form['date_starting'] = array(
  '#type' => 'date_select',
  '#title' => t('Starting'),
  '#date_label_position' => 'within',
  '#date_format' => 'm d Y',
  );

If you have date_popup enabled you can achieve the calendar part by using this:

$form['date_starting'] = array(
  '#type' => 'date_popup',
  '#title' => t('Starting'),
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-3:+3',
);

Then you can style the input field as a calendar button and use javascript to copy the date value to your date select.


Move my project from public_html/web to public_html I have a Drupal site installed via composer, creating a structure like

vendor/
config/
composer.json
etc/
web/core
web/themes
web/index.php
web/etc

Is there a way to change the web folder to a public_html folder so I can use it on my hosting? So the structure needs to be:

vendor/
config/
composer.json
etc/
public_html/core
public_html/themes
public_html/index.php
public_html/etc

I got it working now by using .htaccess but I started using this method with the config outside of my root folder because of the security advantages. With this method, the config is still in my root but via htaccess I point everybody to the web folder. Is this still secure enough?

So how can I change this and is it necessary?

You should be able to change the installer paths in composer.json, which defines where the files are placed:

"installer-paths": {
  "web/core": ["type:drupal-core"],
  "web/modules/contrib/{$name}": ["type:drupal-module"],
  "web/profiles/contrib/{$name}": ["type:drupal-profile"],
  "web/themes/contrib/{$name}": ["type:drupal-theme"],
  "drush/contrib/{$name}": ["type:drupal-drush"]
},

to:

"installer-paths": {
  "public_html/core": ["type:drupal-core"],
  "public_html/modules/contrib/{$name}": ["type:drupal-module"],
  "public_html/profiles/contrib/{$name}": ["type:drupal-profile"],
  "public_html/themes/contrib/{$name}": ["type:drupal-theme"],
  "drush/contrib/{$name}": ["type:drupal-drush"]
},

You can then rename the web folder to public_html and everything should work.


How to add in-line styles to addressfield field? How can I add an inline style to an addressfield field without having to modify the template files?

I'm using the addressfield as a field in my user object and am trying to load the full user object in the commerce order display page.

This page is being rendered using the admin theme which is the default Seven theme.  I'm trying to avoid having to modify that default theme for this purpose.

Here's the relevant code:

function MYMODULE_entity_view($entity, $type, $view_mode, $langcode){
  if ($type == 'commerce_order') {
    $uid = $entity->uid;
    $user = user_load($uid);
    $renderable_user = user_view($user, 'default');  //<-- Can I modify this array to add an inline style?
    $entity->content['customer_info'] = array(
      '#weight' => -2,
      '#markup' => render($renderable_user),
      );
    }
}

Or perhaps I'm going about this the wrong way and there's another way to modify the output of this page?

Check out the CSS Injector module. It won't do inline styles, but you could always write a selector (which is the best practice anyway).


Memory Exhausted after Drush install I've made a drush install of drupal 7.28 on my AWS server. I can confirm that the memory is set to 128M, all green on the reports -> site status page. The website will function normally and sporadically return no data, looking at the logs a tremendous amount of memory is trying to be allocated (assuming an infinite loop somewhere). Given that this is a basic install, no modules have yet been added what might be causing this?

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 140008587493184 bytes) in Unknown on line 0

Note that Drush and Drupal use different php.ini files.  This behavior is inherited from php, which allows for different configuration for commandline tools vs. web servers, so that your web server can be more locked down than your dev tools.

Use the drush status command to see the path to the php.ini file that Drush is using.

Use the drush status-report command to see the commandline equivalent of the reports -> site status page.  This will show you the real memory limit that is set for Drush.

Odds are, all you will need to do is change the memory limit setting in the php.ini file that Drush is using, and all will be well.


Setting up catalog taxonomy I'm fighting with pathauto patterns for a particular content type. The content type is bound to a taxonomy (a product catalog). I thought that the taxonomy tree should only hold container items (categories, subcategories, subsubcategories, etc) but not the end-nodes (products), and that it'll be possible to have the following URL pattern, consisting of the container node url + product alias + extension, as in [taxonomy-alias]/[node-alias].html.

This appears to be a wrong assumption though and causing trouble and bogus aliases.
I'm closer to an approach that the taxonomy should descend down to the very product node, and product pages should be tagged with the final taxonomy node.

This however brings up a question: Is this a way to go if a product can fit in more than 1 category? This smells like more maintenance issues later, because if a product were to be removed, we would have to remove it in X places; my intuition tells me it's not the right way.

Above this all there is a goal to have the URLs and breadcrumb consistent, in sync.

I'm curious to know your opinion and experience in organizing a catalog taxonomy.

Your first assumption was right. The taxonomy items should be for categories and the products should be nodes to type product.

It looks like this is not as simple to setup for D6 where you could use

[term-raw]/[title-raw]

This comment on drupal.org has some helpful suggestions

Download Entity API
enable entity and entity tokens
Setup a path something like [node:field-category:name]/[node:title]


Override Another module's Template file using my Custom Module (Drupal 7) I'm willing to change the user-profile-item.tpl.php template provided by the user module.

I've created a new template file. Now my  question is:

Where do I put the new template user-profile-item.tpl.php template
file? I've created a custom module, should I place it right in the
custom module's directory?
Do I need anything to do so that Drupal
picks up my template file instead of the default template file?

PS I got this link did not understand. Sorry I'm a newbie :(

EDIT:

I solved this using preprocessors, I figured out that I can use preprocessors easily without changing template file. I wrote following preprocessor in my module to achieve what I was looking for.

function MYMODULE_preprocess_user_profile(&$vars){
//    dsm($vars); // prints nice debugging information
    $vars['user_profile']['charity_link'] = array(
    '#markup' => l('Add Charity!', 'my/custom/link' . arg(1)),
    '#weight' => 10
    );
}

I had to use the following snippet to get it to work. I think it may be due to the way I set up the original template.

<?php
//  unset the original template to set yours.

// Implement hook_theme_registry_alter
function MODULENAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['TEMPLATE_TO_OVERRIDE']['template'] = drupal_get_path('module', 'MODULENAME') . '/TEMPLATE_TO_OVERRIDE';
  $theme_registry['TEMPLATE_TO_OVERRIDE']['theme path'] = drupal_get_path('module', 'MODULENAME');

}


Theme folder in drupal 8 In Drupal 8, the theme folder for contributed themes seemed to have moved.

Where do themes go in drupal 8?

The theme location moved to /themes, while the core themes moved to /core/themes.

This is how the directory structure looks like in Drupal 8.


Recommend a slideshow module that can create a display from a view? We have a design comp that looks like this:

We have a content type called speaker, which contains a file field that the headshot image is uploaded to. There are also several other fields, including an entity reference to another content type. What we'd like to do is be able to create a view that contains all the info we need and then have it formatted as a slideshow (where mousing over a single image brings up a div or something containing speaker name, company, etc.)
I've found several slideshow modules that are integrated with Views, but none of them seems to do quite what we need. Any suggestions?

To be honest, I have never been satisfied with any of the existing slideshow modules.

Typically, I use Views to render out the HTML I want.  Sometimes I use field output, but lately I have been using node output with a custom view mode.

The I use some custom CSS and JS to make the slideshow do exactly what I want.

Normally, I wrap all of this up in a custom block.

It may sound complicated, but it usually only takes a few hours to do all of this.


What is the best practice to exchange variables between page calls I am trying to display a list of objects related to my custom node, by showing one node on the node's page and also giving a "next" button which will call the same page but with the id/index of the next objects to display.

Is there a custom/better way to do it than with a GET parameter added to the url of the page call and then the reading of this parameter in the template file via $_GET[]?

You should never read the value of the $_GET param in a template file directly, that logic should be separated out into a process/preprocess function.

Other than that, no...there isn't really anywhere 'better' for page parameters to go. The alternatives are to use something session based, or to set something up to POST variables to the second page. Or use temporary database storage which seems like overkill for this.

Your use case sounds like the archetypal situation where URL parameters would be acceptable. For example, it's the same way Drupal core handles paging (the page parameter is added to URLs).

If you're worried about separating these pages up for SEO benefit, that's a different matter, and you should look at creating unique paths for each piece of content (provided of course that the page changes enough to not be seen as a duplicate with the URL parameter available).


One user with multiple profiles I'm setting up a webshop were clients can have multiple profiles. For example a customer and supplier profile.

Whenever the user logges in, he gets a choice which profile he wants to sign in. Depending on which profile the user has selected, he gets to see different views.
Above this, the user should be able to change from profile within the site... Much like the Masquerade-module, but in this case, it should be for all users.

I hope I make myself clear on this one...
Some advise on how to tackle this issue would be most welcome!

Discussion about one user - multiple personas started and ended at drupal.org in 2007. I think your best bet is to use masquerade as a code example and implement it yourself.


Why I'm getting MySQL error that server has gone away? I'm running:
Drupal 7.34,
PHP 5.4.16,
MySQL 15.1 Distrib 5.5.41-MariaDB, for Linux

I am getting a WSOD on just the module page after a move of server, everything else seems to be running ok.

I've added:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

to index.php and see the below errors:

  Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /public_html/includes/database/database.inc:2171 Stack trace:

  #0 /public_html/includes/database/database.inc(2171): PDOStatement->execute(Array)

  #1 /public_html/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)

  #2 /public_html/includes/database/database.inc(2350): DatabaseConnection->query('SELECT expire, ...', Array, Array)

  #3 /public_html/includes/lock.inc(167): db_query('SELECT expire, ...', Array)

  #4 /public_html/includes/lock.inc(146): lock_may_be_available('theme_registry:...')

  #5 /public_html/includes/theme.inc(449): lock_acquire('theme_registry:...')

  #6 /public_html/includes/bootstrap.inc(455): ThemeRegistry->set(Array) #7 [internal function]:

  DrupalCacheArray->__destruct()
    #8 {main} thrown in /public_html/includes/database/database.inc on line 2171

  Fatal error: Access to undeclared static property: Database::$activeKey in /public_html/includes/database/database.inc on line 1466

A couple of things to try:

First, it's potentially one of your contrib modules causing the problem, so option 1 would be to use Drush to disable all non core modules:

drush pml --no-core --type=module --status=enabled --pipe | xargs drush -y dis

After running this, there is a good chance that you can access your modules page again and be able to start enabling modules one by one to pinpoint the culprit.

Option 2 would be to check mysql's MAX_ALLOWED_PACKET.  You can check this by running SHOW VARIABLES LIKE 'max_allowed_packet' in your mysql console.  If it is set at 1MB, you can try raising it to 16M by running SET GLOBAL max_allowed_packet=16777216;. Try loading your page again to see if that was the issue.


Javascript file is being included but console.log wont work So I THINK I have configured my javascript right in that i want to inlude two files. leaflet.js and mappingsource.js and currently on the page source there exists this:

Whih both have settings? for the files that i want however the file mapping source looks like this

$( document ).ready(function() {
    console.log( "ready!" );
});

window.onload = "test()";

function test() {
    console.log('123');
}
console.log('test');
var map = L.map('map', {
    center: [51.505, -0.09],
    zoom: 13
});

Which should be console logging SOMETHING surely? Is there something I'm missing?
Additional files look like this
helloworld.libraries.yml
helloworld:
  version: 1.x
  js:
    js/leaflet.js: {}
    js/mappingsource.js: {}

<?php

/**
 * @file
 * Contains helloworld.module.
 */

helloworld.module
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function helloworld_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the helloworld module.
    case 'help.page.helloworld':
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('Hello World example module') . '
';
      return $output;

    default:
  }
}

function helloworld_page_attachments(array &$attachments) {

  // Unconditionally attach an asset to the page.
  $attachments['#attached']['library'][] = 'helloworld/leaflet';
    $attachments['#attached']['library'][] = 'helloworld/mappingsource';

}

/**
 * Implements hook_theme().
 */
function helloworld_theme() {
  return [
    'helloworld' => [
      'render element' => 'children',
    ],
  ];
}

You need to attach complete libraries, not single library files. Your module has the name helloworld, this is the first part before the slash. In your libraries.yml you have defined the top key helloworld, this is the library name and the second part after the slash:
$attachments['#attached']['library'][] = 'helloworld/helloworld';

This line will attach all JS and all CSS listed under that specific library.
Sidenote: Try to use Drupal.behaviors instead of $(document).ready, this is the Drupal-way to do stuff like this. Otherwise you might run into problems with Ajax-calls or lazy-rendered blocks rendered with BigPipe module.


Conditionally increment a case ID I have a table {cases} which has in part, upload_id, case_id case_name etc etc.
With a custom form, users, depending on role(4 custom roles), will upload a file upload_id. This  has been serialized. If it is a new case, case_name is NOT present then get max(case_id) add one and save to DB. Also users can add a file to existing cases, so the upload_id would auto-increase, and the case_id stays the same.
I've been working on this one area for 2 weeks and have come to the end of my rope.

I have written all of this into a custom PHP web app a few years ago, but now I have to rewrite it all in Drupal 7.  Any pointers in the right direction would be appreciated.

**********EDIT**************

I didn't think you could have 2 Serial Fields in the same table schema. I already have upload_id as a serial. I just can not figure out how to insert the case_id in Drupal.

Real scenario:

User uploads the file, upload_id =3796, case_id = 2916, case_name = 'xxx Macy'.

User forgot to include something needs to upload additional file. upload_id = 3797, case_id = 2916 where case_name = 'xxx Macy'. And still forgot a file, upload_id = 3798, case_id = 2916.

New user uploads file, upload_id = 3799, case_id = 2917, case_name = 'Jane Deer'.

They way you describe your case_id it sounds like the primary key of your table (a number which increases by 1 for each new entry). Rather than increasing this number in the form (and spare your self the trouble of assure atomic results when more than one person are entering cases at once) you can just set the column as primary key in your schema and let the db manage it. That way you don't need the field in your form at all.

$schema['case'] = array(
  'fields' => array(
    'case_id'       => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
   //your other fields
  ),

  'primary key' => array('case_id'),
);

That said I would consider not using a custom table to start with and instead leverage the functionality Drupal is shipped with and use a node to represent your cases.

There is a contrib module called Serial Field which allows you to add a field to your content type which increases by 1 for each case you create. There is a file field in core which allows you to upload a file to the site as well. The name field is a little tricky as Drupal doesn't allow empty titles but you can easily work around it by adding a simple text field for the name and generate the actual title with Automatic Entity Label.

In this case you need to download the two contrib modules, install them, create a case node type, add and configure the fields and you are done. The advantage is you can still leverage a great number of existing modules working with nodes/fields and entities which is much harder/impossible with custom tables. And you can display the results using Views.


Setting site name in installation profile I'm creating an installation profile. Currently, hook_install() contains only this:

/**
 * Implements hook_install().
 */
function myprofile_install() {
  \Drupal::service('config.factory')->getEditable('system.site')->set('name', 'My Site')->save();
}

Still, after installation is completed (using Drush) the site name is always "Drupal".

The code works if I paste it into Devel's Execute PHP after the site is installed.

Another option I tried is overriding system.site.yml within my profile, which won't load because I wrote uuid: ''. (I don't know how to leave the already-generated UUID.)

How can I set the site name during installation in my custom profile?

EDIT: I found out the following:

The site name gets overwritten when the install configuration form is submitted by Drush, using the values provided by Drush (including site name)
The installation profile must provide a translation of the site information for each enabled language (I have more than one). I assume I'll do this with the core module Configuration Translate.

The solution was to use hook_install_tasks.

The source of the issue was that Drush was filling in the install configuration form during the installation process. Because the form comes after the profile's hook_install, it will override whatever configuration we write in hook_install.

Using hook_install_tasks will work by defining a new install task for setting our preferred configuration, which Drupal will run after submitting the configuration form. See function install_tasks() in core/includes/install.core.inc, line 716.


How do I add a class to a section in omega? Here is the original source:

I want to add some class to it:

I've tried a hook_page_alter() but either I haven't been able to zero in on the specific element or I'm attaching the classes incorrectly.

This is untested, but I am pretty sure you just need to put this in mytheme/preprocess/preprocess-section.inc:

function mytheme_alpha_preprocess_section (&$variables)
{
  $variables['attributes_array']['class'][] = 'my-custom-class';
}

If you look at section.tpl.php, just $attributes gets printed out.  alpha_process() flattens $variables['attributes_array'] into $attributes.

Though, given that the header, content, and footer sections are unique, you probably don't need to explicitly add a class.  You can also add classes to the zone and zone wrappers inside each section directy with the UI at admin/appearance/settings/mytheme, or just replace "section" with "zone" in the code above.


Override default node form submit handler I retrieve a node form and replace it's submit callback like this:

$node = entity_create('node', array('type' => 'my_type', 'title' => ''));
$node = entity_metadata_wrapper('node', $node);
$node = my_node_handler($node, 'some_operation') // It's an object factory
  ->ekran()
  ->getEntity() // It returns a DrupalEntityWrapper
  ->value() // Node's stdClass from wrapper;

form_load_include($form_state, 'inc', 'node', 'node.pages');
$form_state = array();
$form_state['build_info']['args'] = array($node);
$form = drupal_build_form('my_type_node_form', $form_state);

// Remove save, preview, delete, ....
remove_default_actions_from_form($form);
$form['actions']['send'] = array(
  '#type' => 'button',
  '#value' => t('My Button'),
  '#submit' => array('my_callback'),
  '#executes_submit_callback' => FALSE,
  '#name' => 'name_here',
);

But Form API does not care what my submit callback is or even, #executes_submit_callback, It always sends the node form to node_form_submit and the node is saved.

Even changing the callback like this:

$form['actions']['send'] = array(
  '#type' => 'button',
  '#value' => t('My Button'),
  '#submit' => array('some_non_existing_function_hahaha_hohoho'),
  '#executes_submit_callback' => FALSE,
  '#name' => 'name_here',
);

Will not produce an error. What's wrong here? I used entity_form(args...) for retrieving the form and this thing happened, And changed it to drupal_build_form, Still the same thing.

Also along all these, I have added:

  $form['#submit'] = 'die';

Which wont happen (not even an error about die not being callable from call_user_func...);

Wow, The magic was using form alter along side the menu callback which created and handled the node like this:

function my_module_form_node_form_alter(&$f, &$fs) {
  $f['actions']['my_action'] = array(
    '#type' => 'submit',
    '#value' => t('My Button'),
    '#submit' => array('the_submit_func_here'),
  );

dpm($f);
}

Notice it's not a button type but is of type "submit". I have no idea how Form API handles submits, I thought I was having issues because of FORM_ID_submit but now I have no idea what is happening?


Entity error on add new user I am using Drupal 8.05

I am unable to add a new user. I get the following error when I press "Add User" button:

Drupal\Core\Entity\Query\QueryException: 'field_housing_coop_ref' not found in Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 252 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

'field_housing_coop_ref' was an entity reference field (pointing to Content Type A) on Content Type B. I deleted the 'field_housing_coop_ref' field and get the error.

If I recreate the field then I can add a new user. When I delete the field I get the error again.

I put this on the Drupal core issues list as support request but it got closed as not a reproducible error. So it seems to be something particular to my site.

Currently I have the field existing but unused and hidden on the form/display modes. Any idea about what I have done and how I might better resolve this much appreciated.

NOTE:Make sure to take backup of database before doing below changes to avoid any issues.

Search for "field_housing_coop_ref" field in entire database including cache tables, mostly cache_* and key_value tables. Once you've all matching records with you, delete one by one very carefully by reading there names properly to make sure nothing else get deleted.

Once you've deleted matching records for "field_housing_coop_ref" field, rebuild cache by navigating to "Admin => Configuration => Development => Performance" or using Drush command "drush cr".

Updates:

If there are any other references for this field inside other fields in key_value table, make sure to delete those field from Field UI and then cross verify again.


Which module for responsive images without Apache? Possible Duplicate:
  Handling Mobile Images in Responsive Drupal 7 Theme

I'm searching a good module to manage responsive images.

My site is build with Omega theme and the site will be published on a server that doesn't use Apache, so I can use modules that use .htaccess.

Which module do you suggest for my case?

try to use these modules. also suggest to use Adaptive theme.

http://drupal.org/project/responsive_images
http://drupal.org/project/resp_img


How to create a Gmap view that can be filtered? I have a taxonomy vocabulary that has a multiple terms.

I can create a view that shows the location of all terms in a map, but I want to filter these locations by term. I mean the user first chooses which term and then the map only shows the location of this specific term.

I don't know how to set up filter criteria correctly to achieve this, any suggestions?

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
Specific to the "filter" part of your question, here is a quote (also from the project page):

For those using the Commerce module a ready-to-use Order Locations map is provided (3rd screenshot). For each order placed at your store it outputs a marker on the map with its location details retrieved by IPGV&M. The view comes with filters to zoom in on country, time frame and order status. Each order location marker, when clicked, reveals in a text balloon details of the order, e.g number, date placed and order status as well as street address.

Note: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.
PS: I'm assuming this question is about D7 ...


How to group results by multiple fields? I have values in database like:

x submits file 1

x submits file 2

y submits file 1

y submits file 3

x submits file 1(again)

I had my output with aggregation settings as group results together as

x submits file 1

x submits file 2

y submits file 1

y submits file 3

it just grouped file 1 submissions of x

i want it to be :

x submits file 1,2

y submits file 1,3

Can anyone please help?

In D7 - you can achieve your grouping structure in Views with the help of the Views Merge Rows module.

You'd use the option "Use values of this field as a filter" for the field that produces x & y. And for the file name field you'd use the option "Merge unique values of this field".


How to get fields of certain content type in template file without writing iteration loops in tpls? Here I'm getting all fields of certain content type in my .tpl.php file with the help of hook_theme.

return theme('carousal', array('carousal' => $fields));

And my template file is something like this:

<?php
global $fields;
foreach($fields as $key => $value){
echo $value['title'];
print render ($value['fields']['body']);
}
?>

Now, what I want is, I don't wanna use foreach loop in my template file. And if possible, not even any php tags.

How far is it possible to render fields in template file without using any loop?

Can't we write only "BODY" and we get "body" field rendered itself automatically?

I don't know whether it's possible or not. If it's possible, kindly let me know the way out of this.

You can pass your $fields to a custom function. Run your logic or foreach loop in the custom function and pass the title,body values back. Thus you would not need to use the foreach loop in template file.

Here is some sample code if it helps.

$field_data = _my_function($fields);
$data = theme('carousal', array('carousal' => $field_data));
return $data;


Is there a way to add non indexed fields to a search api view? I’m wondering if it’s possible to add non-indexed fields to a search API indexed view?

I want the standard flags fields to be available on the indexed search view. And I was thinking I could do this with relationships but nothing shows up as an option.

EDIT: I was using a taxonomy view until my needs required a more robust filtering system, hence the switch to search API. With facets, it gives me robust filtering options so I can segment my content better than taxonomy alone.

I am building a flashcard website and using Views to display the flashcards and Flags to allow users to mark the flashcards as complete once they memorize the card. This way it can be removed from the main view depending on the status of the flag. So if it isn't flagged it's in the flashcard View, and if they flag it, then it gets removed from the view and I have an attached view, where it will then be listed as memorized.

I will need all of the standard Flags Views integration options to replicate what I was doing before with my taxonomy view. Otherwise, I will have to patch the Flags module or find an alternative to flags.

If you were using Drupal 7 and Apache Solr, you could get something like this with the Apache Solr Display module:

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

The advantage here is that you can store rendered entity or entity json encoded object inside the Solr index, which allows you to access non-indexed fields. Otherwise you would need to load the node to access those fields.

I'm not sure if there is any analogous module for Drupal 8, but a similar approach might work.


How to access a parent paragraph twig file from a child node twig file? In my bootstrap theme, I am trying to make the id of the paragraph the same as an attribute for each of the child nodes, so an accordion will work properly. I have tried looking at doing it through hooks, but I can't seem to access the paragraph data from my node hook.

You can use hook_preprocess_paragraph hook to set the same id to all child nodes, in the below code snippet example all child nodes will have paragraph-PARAGRAPH-ID as id.

use Drupal\Component\Utility\Html;
/**
 * Implements hook_preprocess_HOOK().
 */
function myModule_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  $identifier = Html::cleanCssIdentifier('paragraph-' . $paragraph->id());
  $variables['attributes']['id'] = $identifier;
}


How to display google map field in hidden div? I have a Google Map Field in my form. I'm editing the theme of the form and I'm using a jquery but the map is broken.

The map is inside a div and the code of the template is this:

And here is the Jquery:

$("#show-block-3").click(function () {
         if ($('#hidden-block-3').is(":visible")) {
             $(this).html($(this).html().replace(/Hide/, 'Show'));
                var center = map.getCenter();
                google.maps.event.trigger(map, "resize");
                map.setCenter(center);

         } else {
              $('div#hidden-block-1').hide();
              $('div#hidden-block-2').hide();
              $('div#hidden-block-4').hide();
              $('div#hidden-block-5').hide();
              $('div#hidden-block-6').hide();
              $('div#hidden-location-block').hide();
         }
         // Do it afterwards as the operation is async
         $("#hidden-block-3").slideToggle("slow");

});(jQuery);

I just tried this:

var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);

But the result is still the same. I don't know where else to put that code.

Am I missing something? Does anybody know how to fix this? I'm not using vertical tabs or any tabs that group field module has in the template and in the form. I would to stick with the custom code that I already have. Just need to fix the map.

Thank you!

If anyone is still interested in this answer, I managed to achieve this by making a css class:

.hide-map {
    opacity: 0;
}

I did mine in angularjs, but in JQuery I'm sure you could use some sort of toggle to enable/ disable the css class when it has loaded.


How can I use REST API to create a node with status/tags/data Follow the Services module document, I can only create nodes using REST API with type, title and body. But I am not able to create nodes with more parameters such as tags, status and date.

Need help.

You should have look at drupal docs but for understanding that first install Devel module - it really helps you to discover field names.


Show progress of code executed on form submit I have a form in my site (custom module) where the user chooses some options and depending on those options, some code is executed.

The code basically executes shell commands on a remote server and at the moment, all the drupal_set_message commands are only shown after all commands are executed.

Is there any way that I can show those messages as soon as each part of the code is executed?

function mymodule_connect() {
    $host = '<my ip address>';
    $username = '<my username>';
    $password = '<my password>';

    $connection = ssh2_connect($host, 22);
    ssh2_auth_password($connection, $username, $password);

    return $connection;
}

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

    $delete_load = $form_state['values']['delete_load'];
    $change_load = $form_state['values']['change_load'];
    $load_number = $form_state['values']['check_load'];

    if($change_load == 1) {
        # DELETE
        # perform some command

        # LOAD
        # perform other command

        drupal_set_message('Deleting. Please wait...', 'error');
        drupal_set_message('Changing load. Please wait...', 'warning');
    } elseif ($delete_load == 1 && $change_load == 0) {
        # DELETE
        drupal_set_message('Deleting. Please wait...', 'error');

        $command = "<some shell script command to send>";

        $connection = mymodule_connect();

        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);

        ssh2_exec($connection, 'exit');
        unset($connection);

    } else {
        # do nothing
    }

    # OTHER DIFFERENT SET OF COMMANDS TO SEND
    drupal_set_message('Configuring. Please wait...', 'status');

    $commands = array(
        "<some shell script command to send>",
        "<some shell script command to send>",
        "<some shell script command to send>",
    );

    $connection = mymodule_connect();

    foreach ($commands as $command) {
        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);
    };

    ssh2_exec($connection, 'exit');
    unset($connection);

    return t('Success');
}

Surely you need to implement Batch API to achieve what you need, and keep the user notified for what's happening in the background.

Very similar question that will help you more. Read it carefully.

These modules will help you:

Progerss This is an attempt to implement a generic framework for keeping track of any progress
Background progress takes over the existing Batch API and runs batch jobs in a background process


How to tell if node has been updated via UI form as oppose to programmatically? I am importing/updating nodes from a web service using node_save.  One feature that I want to achieve is when the imported node is changed locally, it should not receive any further updates from the web service.

So, what I want to achieve is:

Detect when a node has been updated
If the update was carried out by a user submitting a form (as oppose to programmatically)
Then flag that this node should receive no further updates form the web service (I don't need any assistance with this part)

I wanted to use hook_node_update but I'm not sure how to tell whether the update was carried out by a user submitting a form.

Any suggestions?

Create an additional field in the content type - for example update_source - and set the value programmatically.

If the user is editing the node on node/[nid]/edit page, set the value to UI and otherwise set it to programmatic.

You can do this with simple hook_form_alter() and URL checks to make sure the user is on node/[nid]/edit page. Something like this would work:

if (arg(0) == 'node' && arg(1) && arg(2) == 'edit') {
  // Your code
}


Read field value and pass it to section style atributes only for node page I have a color field in content type -> page fields. And i want to read the values of this field and pass this value as a background color(bootstrap subtheme) to element  for main content ( - from page,tlp.php). And only for node type -> page.

In my template.php i tried to use function theme_preprocess_page. My code:

function theme_preprocess_page(&$vars) {

    if (isset($vars['node'])) {

        $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type . 'page';

        // check the node type and specific field in not empty
        if (($vars['node']->type = 'page') && (!empty($content['field_color']['#items'][0]['value']))) {

            //read the value of color field
            $bg_color = $content['field_color']['#items'][0]['rgb'];

        }
    }
}

but i dont know how to pass the value of color field ($content['field_color']) to section style attributes. Should i use $vars['attributes_array']['style'] ? and how to pass it to section element style.

Help please.

$color = preg_replace("/#/i", "", $bg_color);
$vars['classes_array'][] = $color;
 $vars['style'] = "style='background-color:$bg_color'";


Force Drush8 to Download Drupal 8 Module on a Remote D7 Anyone happen to know, how to force download d8 module to remote d7? I tried doing the following and still letting me to choose 7s.

$ drush @remote.dev dl --default-major=8 composer
There are no stable releases for project composer.                     [warning]
Choose one of the available releases for composer:
 [0]  :  Cancel
 [1]  :  7.x-1.x-dev  -  2013-Sep-30  -  Development, Recommended

$ drush @remote.dev dl composer-8
There are no stable releases for project composer.                     [warning]
Choose one of the available releases for composer:
 [0]  :  Cancel
 [1]  :  7.x-1.x-dev  -  2013-Sep-30  -  Development, Recommended

How does drush detect the version of the remote drupal, where maybe i can edit that real quick an put it back after the download?
Maybe some drush override parameters to forcefully show all realeases?

Any help please. TIA

I was going to suggest --default-major. Since that does not seem to work, I can only recommend to download the module outside of a Drupal site and then move it into place.

drush dl composer-7 --destination=/tmp && drush rsync @self:/tmp/composer @remote-dev:sites/all/modules


Where is source code of advanced search form? I can't find where in Drupal 7 search module is the source code of advanced search form that appears on search result site.

Below is code of search_form. You can see there is basic key in renderable array. In output of dpm is even advanced key, but i can't find from where it comes.

It should be probably somewhere in search module, but it is not big module and i checked it last 4 hours and can't find it.

function search_form($form, &$form_state, $action = '', $keys = '', $module = NULL, $prompt = NULL) {
  $module_info = FALSE;
  if (!$module) {
    $module_info = search_get_default_module_info();
  }
  else {
    $info = search_get_info();
    $module_info = isset($info[$module]) ? $info[$module] : FALSE;
  }

  // Sanity check.
  if (!$module_info) {
    form_set_error(NULL, t('Search is currently disabled.'), 'error');
    return $form;
  }

  if (!$action) {
    $action = 'search/' . $module_info['path'];
  }
  if (!isset($prompt)) {
    $prompt = t('Enter your keywords');
  }

  $form['#action'] = url($action);
  // Record the $action for later use in redirecting.
  $form_state['action'] = $action;
  $form['#attributes']['class'][] = 'search-form';
  $form['module'] = array('#type' => 'value', '#value' => $module);
  $form['basic'] = array('#type' => 'container', '#attributes' => array('class' => array('container-inline')));
  $form['basic']['keys'] = array(
    '#type' => 'textfield',
    '#title' => $prompt,
    '#default_value' => $keys,
    '#size' => $prompt ? 40 : 20,
    '#maxlength' => 255,
  );
  // processed_keys is used to coordinate keyword passing between other forms
  // that hook into the basic search form.
  $form['basic']['processed_keys'] = array('#type' => 'value', '#value' => '');
  $form['basic']['submit'] = array('#type' => 'submit', '#value' => t('Search'));

  return $form;
}

The advanced form is altered in node.module and not in search.module. you can find the below function for advance search in node.module, Please have a look in the below hook:
 function node_form_search_form_alter(&$form, $form_state)


Is it possible to set the sitemap option programmatically using the module Simple XML Sitemap? On my drupal instance I have enabled the module called Simple XML Sitemap. The problem now is I want to toggle the option to index certain pages programmatically. I can't find out how. Can this be done?

There are API methods to alter stored inclusion settings and generate the sitemap programmatically. There is no documentation other than the documentation page and code documentation which is pretty complete. Here are the service methods which can be used to accomplish what you need:

getSetting()
saveSetting()
getSitemap()
generateSitemap()
getGeneratedAgo()
enableEntityType()
disableEntityType()
setBundleSettings()
getBundleSettings()
setEntityInstanceSettings()
getEntityInstanceSettings()
removeEntityInstanceSettings()
bundleIsIndexed()
entityTypeIsEnabled()
addCustomLink()
getCustomLinks()
getCustomLink()
removeCustomLink()
removeCustomLinks()

You can chain these methods like so:

\Drupal::service('simple_sitemap.generator')
  ->saveSetting('remove_duplicates', TRUE)
  ->enableEntityType('node')
  ->setBundleSettings('node', 'page', ['index' => TRUE, 'priority' = 0.5])
  ->removeCustomLinks()
  ->addCustomLink('/some/view/page', ['priority' = 0.5])
  ->generateSitemap();

I have just added the above information to the documentation page, we would appreciate anyone further contributing to it.


Custom warning on when viewing cart (anonymous users) I am wondering with what mechanisms it would be possible to add a warning message to anonymous users viewing their cart saying: "Please log in with any of the listed services in order to proceed to checkout".

If possible I'd like to avoid changing the module's code in order to avoid future update problems.

Thanks for any help,
Best

The easiest way is overriding a default cart page template (cart page has been created with Views module, name - 'commerce_cart_form', display - 'default');

Create a template for Style Output
Copy the content of it
Views module provides logged_in variable in template_preprocess_views_view(&$vars) function, so you can check with that variable and display a text;

example (views-view-table--commerce-cart-form--default.tpl.php):

<?php if (!$logged_in): ?>
  MY MESSAGE FOR THE ANONYMOUS
<?php endif; ?>

<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>
  // Rest of code from Style Output
</table>


Can you temporary grant a user permission to avoid captchas in drupal 7? I have a module which alters a webform's form. Depending on the user agent, I want to grant the current user the permission to skip captchas, so that the captcha block wont appear at the end of my webform. The problem is, within the init function of my module, if I enable the following line:

if (functionWhichChecksStuff()) {
        user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('skip CAPTCHA'));
    }

the permission is being granted for ALL anons, every time since it actually grants the permission to that user role permanently.

Is there a way or function which does that dynamically and temporary?

There are basic problems with your approach:

All anon users are one user for Drupal. They share common UID 0, so they are one user. And HTTP is a stateless protocol, so you can't decide "it's the same user" basing on connection. In Drupal 7 sessions are not guaranteed for anonymous users, so you can't use them reliably for that purpose either.
If you will try to modify $user->roles, it will add a role for current http call all right, but it will not regenerate caches, like admin/reports/status/rebuild or views caches based on roles.
hook_init docs says: This hook is not run on cached pages.

So, this is no-go by design, and if you need to give some privileges or options by browser session, you need to implement your own solutions, like cookies. There is a list of modules that works that way, you can use their code for reference.


How do I delete all the relations on my site? I want to remove all the relations (created with the Relation module) on my site because I have replaced them with an entityreference field.

At /admin/structure/relation, I can delete the Relation Types, but this does not delete the relations belonging to each type.

At /admin/content/relation, I can delete the relations individually, but there are 100K relations on this site.

At /admin/structure/views/view/relations/edit/page, with the Views Bulk Operations module enabled, I can change the contextual filter Relation: relation type to "Display all results for the specified field" for When the filter value is NOT in the URL and then add a bulk operation to delete item under Fields.  This allows me to go to /relations and trigger a bulk operation to delete all the relations.

Is there a faster way that doesn't involve customizing views?

There are many ways to delete relations on a site. Relations are Entities in Drupal.

The Delete All module can help with this process.
The Drush Entity command set has a delete function which takes a content type I believe.
With care you could by hand TRUNCATE the relation table, and destroy and drupal Fields that use relations. (I've done this on a few sites).


Additional Configuration to disable anonymous session cookies? I am running a clean install of Pressflow 6.28. I have set the following configurations:

Cache Mode: Normal;
Min Cache Lifetime: 5 minutes;
Page Cache Max Age: 1 day;

I have installed no contributed modules and have disabled all optional modules that ship with Pressflow.

I am seeing inconsistent behavior with setting session cookies with anonymous users. Sometimes a session is not set, but most of the time it is. When I login and logout, session remains set. If session is not being set and I run 'drush cc all' it begins to be set. I am wondering if there is perhaps some additional configuration I may be missing.

Make sure the $cookie_domain is set properly in settings.php, often if it's not set to the correct domain, particularly in proxy situations, you'll see inconsistent login behaviour.


Contextual filters help I have a page and a view. I have placed the view as a block on the page and there is a contextual filter defined as shown in the image

Basically when i print the arg(1) in header and see i get like 42 which is like the node id on which the view is placed. Can you please tell me what its is trying to do when its placed in the contextual filters as it was was done earlier by another person. I mean to ask how does it filter out the data based on the node id ?

I am not certain if I understand what you are asking here, but  this question is bound to come up on searches for anyone trying to figure out contextual filters.  The information you present leads to several questions and comments:

It is unclear what your contextual filter will due without knowing more about the view fields, setting and path definition you have given it.   Also, is this the contextual filter screen for the page or block?

To define the location for the argument in the path for a page view you place a % character at the location in the path definition for the view. eg. in Example.com/content/%/items, any URL value matching the path pattern will generate a view with the value of the % passed on to the contextual filter. IN this way you have a view definition performing generalized filters as defined in the first column of the view definition form page and additional filtering as defined in the third column under the 'Advanced' option.  For a page view you complete the requirements for the contextual filter under the heading "When the filter value IS available or a default is provided"

For a block you must complete the section "When the filter value is NOT available" and select "Provide default value".  IN the drop down list you can tell the filter whether it is intercepting a content, taxonomy or user id node number or you can tell it to select a raw value from the URL and which position in the string it is.  In the example I gave above the context value we are looking for (the % sign) is in the second position.

However the value is passed, the context filter will further filter the view as defined on the view form for that page or block.


Show Webform Confirmation message in popup window In my drupal7 site i have buit a contact form using Webform.

I like to do two things.

I want to show webform confirmation message in popup window.I have searched net found some popup module but the problem is they all belongs to drupal 6
When i submit the webform i am getting this error message

  Notice: Undefined index: #webform_component in theme_webform_display_select()
  (line 522 of /var/www/www.example.com/www/example/sites/all/modules/webform/components/select.inc).

Can you help me to solve this two things.Thank you friends

Without doing any coding to achieve this you could use a module like Purr Messages and then adjust the style of it's output with CSS, this would apply to all system messages though..

Otherwise like zerocoolhotone mentioned, the simple dialog is an effective way of achieving this too.

Regarding your second question, it's a bug/issue with webform, if memory serves me right you can use the development snapshot to overcome it temporarily until they roll it out.


PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'env_id' in 'field list': INSERT INTO {apachesolr_stats} I get this error a lot in the drupal logs. Several times an hour.  Anyone know why, what the impact is, and how to fix it?

My config:

Acquia Drupal 7.36
Running in IIS 7.5 / Windows Server 2008
Solr 4.6
PHP 5.3

Error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'env_id' in 'field list': INSERT INTO {apachesolr_stats}
  (timestamp, uid, sid, numfound, showed_suggestions, total_time,
  prepare_time, process_time, page, keywords, filters, sort, env_id,
  page_id) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5,
  :db_insert_placeholder_6, :db_insert_placeholder_7,
  :db_insert_placeholder_8, :db_insert_placeholder_9,
  :db_insert_placeholder_10, :db_insert_placeholder_11,
  :db_insert_placeholder_12, :db_insert_placeholder_13); Array (
  [:db_insert_placeholder_0] => 1423845337 [:db_insert_placeholder_1] =>
  697523 [:db_insert_placeholder_2] =>
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX [:db_insert_placeholder_3]
  => 35 [:db_insert_placeholder_4] => 1 [:db_insert_placeholder_5] => 15 [:db_insert_placeholder_6] => 15 [:db_insert_placeholder_7] => 0
  [:db_insert_placeholder_8] => [:db_insert_placeholder_9] => question
  about bill [:db_insert_placeholder_10] => a:0:{}
  [:db_insert_placeholder_11] =>
  a:2:{s:5:"#name";s:5:"score";s:10:"#direction";s:4:"desc";}
  [:db_insert_placeholder_12] => solr [:db_insert_placeholder_13] =>
  core_search ) in apachesolr_stats_exit() (line 191 of
  D:\Inetpub\wwwroot\sites\all\modules\apachesolr_stats\apachesolr_stats.module).

UPDATE:

I am running apachesolr_stats v. 7.x-1.0-beta1

Running update.php produces this error:

  Warning: Invalid argument supplied for foreach() in apachesolr_stats_block_info() (line 961 of D:\inetpub\wwwroot\sites\all\modules\apachesolr_stats\apachesolr_stats.module)

Check your drupal database, table apachesolr_stats if it has a field env_id.

If not check installation of module apachesolr_stats, maybe uninstall and reinstall. It should create that table apachesolr_stats with the field env_id.


What is stopping my theme from using a file that uses a suggested file name? I needed to modify a module's .tpl file and so copied it, renamed it to something suggested by Theme Debug's file suggestions.

Eg when I run drush theme_debug I see:

<!-- FILE NAME SUGGESTIONS:
   * image-resp-item--f6.tpl.php
   x image-resp-item.tpl.php
-->

So I rename my new file image-resp-item--f6.tpl.php and place it in my site's theme.

I clear cache and rebuild the theme registry but to no affect - the site still uses the original .tpl.

To experiment, I change my new .tpl's name to match the old one (remove --f6). This works - I see my new code appear on the site.

Why is my site (or theme?) not wanting to use the suggested file name?

Your can either use hook_preprocess_page or if you don't want to code use something like context module. You can add a new context to select theme template based on your requirement.


Preview is not showing after upload When i am trying to upload image as a Authenticate user, After upload i am not able to see preview. fields got disappear fully.

If i try to do as a admin, i am able to see that.

Any suggestions?

Could be that you have private file setting turned on and have not given permission to authenticated users to see an uploaded field.

But the commenters above are correct, there are literally a dozen or more ways a field may not display an image. A few that come to mind:

Images styles aren't writeable
A preprocess function has a weird permission it's checking
.htaccess or server settings is screwing up the image headers
the path is getting rewritten because of a path alias
Some access module is being wonky
The access permissions are out of date and need to be flushed
You have a field-level access module preventing authenticated users from seeing the image field
You are using some display module that is tweaking your template or display mode based on permissions
The views module is tweaking your field availability
etc


How do I get an image path from field preprocess function After 3 hours of searching the web for this I gave up...

I have added a "banner image" field to the basic page. I want to use the image as a background. I wanted to capture the image path in a preprocess_field function but I tried every possible methods on the \Drupal\image\Plugin\Field\FieldType\ImageItem object and can't seem to find the way to get the path.

mytheme.theme:

function mytheme_preprocess_field(&$variables){
  if($variables['field_name'] == 'field_banner_image'){
    /** @var \Drupal\image\Plugin\Field\FieldType\ImageItem $field */
    $field = $variables['element']['#items'][0];
    $variables['banner_url'] = $field->getValue(); // not working, tried everything...
  }
}

Then in my field--field-banner-image.html.twig:

You can do this more simply

$uri = \Drupal\file\Entity\File::load($variables['items'][0]['content']['#item']->getValue()['target_id'])->getFileUri()

Or for a field with multiple items

foreach ($variables['items'] as $delta => $item) {
  $uri = \Drupal\file\Entity\File::load($variables['items'][$delta]['content']['#item']->getValue()['target_id'])->getFileUri()
}

And then apply an image style to get the url

$variables['banner_url'] = ImageStyle::load('image_style_name')->buildUrl($uri);


Search multiple databases Running a website on Drupal 6.

I'm currently using Faceted Search to search the default database for the website.

I've installed a separate Knowledgebase application (KB Publisher) which has it's own database and search, but I would like to use one search box (the default website search box) to index/search BOTH the default website database & the Knowledgebase database.

I'm not really a hard core programmer and am looking for some ideas/assistance in doing this?

Thanks,

John

I don't think any easy solution exits. But you can connect to another database by adding below lines into your settings.php file.

$db_url['mydb'] = 'mysql://user:pwd@localhost/anotherdb';

and use db_set_active() function in appropriate places to query other database while your existing database index. You may need to have a deep look in to the Search module for that.


Multiupload widget - create more items inside single node I am looking for a solution - I want to upload multiple images (media module) into one node, so each image would be separate item. Is there any module out there? I found multiupload module that creates multiple nodes but that is not what I need. Thank you for any ideas.

You can try out the Plup Upload module https://www.drupal.org/project/plup which gives a Plup upload widget for images where you can upload multiple images at once to a content.

You can follow the tutorial here:
https://www.ostraining.com/blog/drupal/multiple-image-uploads/

NB: To fix the missing thumbnail bug add $conf['image_allow_insecure_derivatives'] = TRUE; to your settings.php


Encoding problem with node.tpl.php I am new in Drupal theming and I would like to control the "submitted by" part of a node. I want to remove the name of the author and stylize the created_date of the node. The problem is that I also echo some greek characters that show up in weird symbols in my site. I tried changing the encoding to utf-8 but it won't work. I am not even sure what the original encoding of node.tpl.php is. How would I go inserting my own custom text inside node.tpl.php and printing it correctly?

<?php if ($display_submitted): ?>
  <footer class="submitted"><?php $posted="Δημοσιεύτηκε στις "; echo mb_convert_encoding($posted, "UTF-8", "Windows-1252") . date( "d F, Y",$node->created); ?></footer>
<?php endif; ?>

The code above returns:

  Äçìïóéåýôçêå óôéò 12 January, 2012

I also tried utf8_encode function but that was a long shot since it converts ISO-8859-1 strings to UTF-8.

If the file is correctly saved as UTF-8, it should correctly handle Unicode characters. So far, I have had a problem with the saved file just because the editor I was using added the BOM ("Byte Order Mark") used to identify the encoding of the file, but the error was a different one.

Generally speaking, the Drupal way to have a translatable site is to use t() in your code, which requires the English string that will then be translated to the language set as default, basing on the translation provided to the Language module.

The code should be rather be similar to the following one:

<?php if ($display_submitted): ?>
  <footer class="submitted"><?php t('Submitted by !username on !datetime', array('!username' => $name, '!datetime' => $date)););</footer>
<?php endif; ?>

The alternative is implementing hook_preprocess_node(&$variables) (template_preprocess_page() in a theme), and initialize the variable $variables['submitted'] to the string you want to appear ("Submitted by !username on !datetime" in the code I shown before).


edit users of assigned domain i need to one role like 'domainAdmin' in a domain can edit only users of the assigned domain not another domains. is this possible with domain access itself or another modules?

A good start would be here: http://drupal.org/project/domain_roles - This allows you to segment roles by domain. So you could create different roles, then assign those roles to users and by way of other access modules (Content Access could be useful but I'm not certain how it handles user entities) you could then limit the users to only their domains.

FWIW, this used to be done in Drupal 6 by way of the unstable module: http://drupal.org/project/domain_user_edit - Could be worth contacting the maintainer and seeing what you can do to take it over for Drupal 7 and on.


How to you add a table of contents in a pdf for a book that is exported using views_pdf? I am using the book module in Drupal 7 and have successfully exported the whole book as a pdf using views_pdf. However, I would like to add a table of contents on the first page to list all the node/page headers that are in the pdf. It would be nice if the table of contents could then link to each of the page titles in the pdf, but this is not absolutely necessary. Does anyone know how to do this?

I've looked at the code for views_pdf_template.php and think it can be modified to keep track of all the page headers and associated numbers, and then render it in the close() function. But I'm not sure if this is the right way to do it. Does anyone have any ideas? Or has done this before?

Thanks in advance.

You could write a new view that only contains the table of contents (no idea how hacky this is) and include it into your PDF view as a header. (Header -> Add -> Global -> View)


Is it possible to implement theme preprocessor on specific template in drupal 8? What I am here trying to achieve is simple. I want to change the default drupal "submitted by" field to only render day and date but not the time when the node was created. To do so I want to preprocess the field which is being evoked by field.html.twig. But apparently, I don't want to run the preprocess on every field by using hook suggestion "field". Hence i created the specific template "field--default--node--node-submitted-by--blogs.html.twig". Now I want to implement theme preprocessor on this specific template. Can achieve on based on template suggestions or not?If so how?

If you implemented your own template suggestion then it's as easy as writing a function with the following name:

function THEME_OR_MODULE_NAME_preprocess_field__default__node__node_submitted_by__blogs(&$variables) {
}

The main thing to take care of is to convert the hyphen characters (-) to underscores (_).

Good luck!


Users with no roles are getting onto my system I am having an issue with my site, there are users accessing it and creating accounts without having a role.

Here we can see user roles is blank. From my understanding someone has found a weakness in our system and has exploited it to create accounts with no roles.

since the account has no role does this mean its not subjected to the rules of any role? Do these accounts have admin access to our site or would it be closer to anon users.

Is there any basic thing that I could do to stop people with no roles getting in? Or is there a way to see how a user with no role is created (understanding the process would help me fix the problem)?

Edit 1

Version: Drupal 7

Module: User 7.32

Module: LoginToboggan 7.x-1.4

Users with no roles are how the default "Authenticated user" role is listed.  I.e. these have the access level that the system gives the role ""Authenticated user".

This by itself is nothing to be concerned about.

If you don't want to allow bots and fly-by users to create accounts, navigate to Home » Administration » Configuration » People » Account settings and under Registration and cancellation, click that only admins can create new accounts.

If you want people to able to create accounts, but not bots, you need to let the registration process tell bots and humans apart.  One of these modules may help:

CAPTCHA - See also: How to add CAPTCHA to registration
In particular; CAPTCHA Riddler
Mother May I

However, in 2015, bots like XRumer knows how to do most CAPTCHAs including math and "warped" letters - you may need to experiment a bit to find a CAPTCHA configuration that works.

But preventing spam registrations are actually the topic of this question: Unknown User Registered into my system


How to limit Entity Reference to only allow referencing of nodes with the same (or undefined) language? I know I can simply add language to displayed title of a node in Entity Reference field based on views. What I failed to discover is how to limit possible values to only show and allow matching ones.

When current node is language independent, all nodes should be listed as possible in reference field.
When node has language defined, only nodes of the same language, or undefined language, should be available.

I don't really mind wrong selection to be saved in database if language of node will be changed, as it shouldn't happen often enough to be a problem. I simply don't want "wrong" nodes on the list of available reference choices. On-save validation would be nice, but isn't a must-have.

I tried to use view to populate entityreference field's dropdown on node edit form:

My big block is how to access a language of a current node in view that provides list of available entities. I can't find a way other than to guess using current UI language, but that may be wrong for edits and usually is wrong on new node creation. Ideally, the entity reference field should repopulate via AJAX according to the language selected in the node edit from.

For the sake of future visitors I would appreciate complete answer. Of course answer not based on views will be appreciated, too.

Reference field option limit module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

  It currently supports taxonomy term and entity reference fields.


How to get JSON data from exception in httpClient() public function myLogin() {
    try {
      $client = \Drupal::httpClient();
      $request = $client->post('https://targetApi.com/auth/login?fx=1', [
             'json' => [
                 'login' => 'demo',
                 'password' => 'demo1234567',
                 'locale' => 'en'
              ]
      ]);
      $response = json_decode($request->getBody());
      return $respone;
    } catch (\Exception $e) {
      \Drupal::logger('autoapp')->error($e->getMessage());
    }
  }

When I set wrong password I can catch this in $e->getMessage(). The message is:

Client error: `POST https://targetApi.com/auth/login?fx=1` resulted in a `404 Not Found` response:
{"error":"auth.user.notfound"}

So I can catch error, this is fine. But I'd like to get JSON data from It. And if in the try part I have it in $request->getBody(), how can I get it from $e ?

This should work

if ($e->hasResponse()) {
    $response = $e->getResponse()->getBody()->getContents();
}


How to copy view modes between content types in Drupal 8? I've been doing my first Drupal 8 project, and a major pain point, when you have a site with 10 or more content types, is to copy a view mode to all the other content types after you set it up on one type, such as "article".

The question is, how do speed-up the process within Drupal 8 of copying a change to a view mode on multiple content types?  It can be a real pain point for developers on larger sites.

I had an ah ah moment when I found this page: https://api.drupal.org/api/drupal/core!includes!entity.inc/function/entity_get_display/8.2.x

You can write little scripts to update a field across many content types.  This can potentially save you hours on your Drupal 8 development!  We have a site with nearly 20 content types and let's say you want all of them be able to display with your new view mode, "card".  You've set it up on the article content type and now you need to copy it over.

I created this helper function as an example:

**
 * Utility function to copy a display mode from one entity bundle to another.
 *
 * @param $entity_type
 *   string Entity type to update.
 * @param $source
 *    string Source node bundle.
 * @param $target
 *    string Target node bundle.
 *  @param $view_mode
 *    string view mode to use.
 */
function my_module_copy_display_mode($entity_type, $source, $target, $view_mode) {

    $entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $source . '.' . $view_mode);

    if (empty($entity_view_display)) {
      return;
    }

    $items_to_copy = $entity_view_display->get('content');

    $new_entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $target . '.' . $view_mode);

    if (empty($new_entity_view_display)) {
      // If it can't load view mode on target type, create it.
      $values = array(
        'targetEntityType' => $entity_type,
        'bundle' => $target,
        'mode' => $view_mode,
        'status' => TRUE,
      );
      $new_entity_view_display = \Drupal::entityTypeManager()
        ->getStorage('entity_view_display')
        ->create($values);
    }

    $arr = $new_entity_view_display->toArray();

    foreach($arr['content'] as $field_name => $field_data) {
      $new_entity_view_display->removeComponent($field_name);
    }

    $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $target);

    foreach($items_to_copy as $key => $value) {
      // Check if they are in the entity field definition array.
      // This prevents adding fields that aren't on this content type.
      if (!empty($definitions[$key])) {
        $new_entity_view_display->setComponent($key, $value);
      }
    }

    $new_entity_view_display->save();
}

To use this, I wrote a secondary function with our site's content types:

/**
 * Copy a given view mode from article bundle to all other node types.
 *
 * @param $view_mode
 *   string View Mode to copy.
 */
function my_module_copy_view_mode_from_article_to_other_types($view_mode) {
  $source = 'article';

  $targets = [
    'car',
    'gallery',
    'video',
    'listicle',
    // etc.  put all the content types you want to copy to.
  ];

  foreach ($targets as $target) {
    my_module_copy_display_mode('node', $source, $target, $view_mode);
  }

}

Then, I just ran this second function from /devel/php, with a handful of view modes I wanted to make sure were consistent across all node bundles.

It's very fast, and what used to take half-an-hour of drudgery, dragging and dropping, is now very fast!

Update: Here's a drush version you can add to a custom module, it also allows you to just copy one field from a display mode to another display mode.

    <?php
/**
 * Implements hook_drush_command().
 */
function mymodule_drush_command() {
  $items = array();
  $items['copy_display_mode'] = [
    'description' => 'Copy display mode to another display mode. Example: "drush cdm node article clinical_trial three_up_item three_up_item"',
    'arguments' => [
      'entity_type' => 'Entity type to update',
      'source' => 'Bundle to copy from',
      'target' => 'Bundle to copy to',
      'source_view_mode' => 'View mode to copy from',
      'target_view_mode' => 'View mode to copy to',
      'field_to_copy' => 'Optionally, copy just one field',
    ],
    'callback' => 'mymodule_copy_display_mode',
    'aliases' => ['cdm'],
  ];
  return $items;
}

/**
 * Utility function to copy a display mode from one node bundle to another.
 *
 * @param $entity_type
 *   string Entity type to update.
 * @param $source
 *    string Source bundle.
 * @param $target
 *    string Target bundle.
 * @param $source_view_mode
 *    string view mode to copy.
 * @param $target_view_mode
 *    string view mode to copy to.
 */
function mymodule_copy_display_mode($entity_type = "", $source = "", $target = "", $source_view_mode = "", $target_view_mode = "", $field_to_copy = "") {

  if (empty($entity_type)) {
    drush_print('Missing entity_type. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($source)) {
    drush_print('Missing source. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($target)) {
    drush_print('Missing target. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($source_view_mode)) {
    drush_print('Missing sourced_view_mode. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($target_view_mode)) {
    drush_print('Missing target_view_mode. Type "drush help cdm" for arguments.');
    return;
  }

  $entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $source . '.' . $source_view_mode);

  if (empty($entity_view_display)) {
    return;
  }

  $items_to_copy = $entity_view_display->get('content');

  $new_entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $target . '.' . $target_view_mode);

  $updated = "updated";

  if (empty($new_entity_view_display)) {
    // If it can't load view mode on target type, create it.
    $values = array(
      'targetEntityType' => $entity_type,
      'bundle' => $target,
      'mode' => $target_view_mode,
      'status' => TRUE,
    );
    $new_entity_view_display = \Drupal::entityTypeManager()
        ->getStorage('entity_view_display')
        ->create($values);
    // Change verb for output to user.
    $updated = "created";
  }

  $arr = $new_entity_view_display->toArray();

  if ($field_to_copy == "") {
    foreach ($arr['content'] as $field_name => $field_data) {
      $new_entity_view_display->removeComponent($field_name);
    }

    $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $target);

    $output = [];
    foreach ($items_to_copy as $key => $value) {
      // Check if they are in the entity field definition array.
      // This prevents adding fields that aren't on this content type.
      if (!empty($definitions[$key])) {
        $new_entity_view_display->setComponent($key, $value);
        $output[] = ' -- ' . $key;
      }
    }

    $new_entity_view_display->save();
    drush_print("$entity_type.$target.$target_view_mode $updated from $entity_type.$source.$source_view_mode");
  }
  else {

    $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $target);

    if (!empty($definitions[$field_to_copy])) {
      $new_entity_view_display->setComponent($field_to_copy, $items_to_copy[$field_to_copy]);
      $output = [' -- ' . $field_to_copy];
    }

    $new_entity_view_display->save();

    drush_print("copied field $field_to_copy to $entity_type.$target.$target_view_mode from $entity_type.$source.$source_view_mode");
  }

  if (!empty($output)) {
    foreach ($output as $item) {
      drush_print($item);
    }
  }
}


Architecture advice for site with lessons that belong to courses I need to build out a site that features courses and lessons, each defined as a content type. I currently have the site running with lessons linked to courses using entity reference (entity reference field is in lessons) and use EVA to attach a view of lessons to each course. (see screen below for reference)

This works fine, however I now have a new requirement to allow lessons to be re-used across multiple courses. This means:

Courses can contain multiple lessons
Lessons can appear in more than one course
Lessons appear in "sections" which are custom per course
Lesson and section sort order is custom per course
Courses need to be able to handle up about 150 lessons per course

Since lessons need to appear in sections, the link requires both a reference and a section. I've experimented building this out with field collections embedded in the course entity. This works pretty well, but performance degrades significantly after about 30 lessons are added to a course.

To avoid the performance problem, another approach I'm considering is to code a compound field (entity reference with a text field) that would be added as an unlimited value field to the course content type.

Before I try the compound field approach, I'm seeking input/advice on the architecture for this solution. Given the requirements, and available D7 functionality, what approach makes most sense?

How about this unproven setup.

Create a third content type, Sections. Courses reference sections with a mutli-value entity reference field, which you can drag/drop the order of this field from the node edit form. You can use inline entity form to assist with content creation.

Then, reference Lessons from Sections with a multi-value entity reference field, also allowing you to drag/drop the order of the field values. Not sure if you can use the inline entity form within an inline entity form...maybe.

Then, you can continue to use EVA on both the courses and sections to display view results, using a node id contextual filter...I assume.

Or, you could just render the referenced entity, selecting a custom display mode, which you theme accordingly. This may offer better performance.


Would like to remove welcome message from frontpage Possible Duplicate:
  Removing the “No front page content has been created yet.” message from the front page

I am using the Zen theme and don't wan't any "nodes" on my homepage. I've got menus and blocks, but not nodes as such. I don't want the "No front page content has been created yet" text to appear. What is the best way to get rid of it?

I've currently only got one template that I'm using. page.tpl.php

drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);

$default_message = '<p>' . t('No front page content has been created yet.') . '</p>';

If you add a node, publish and check "promote to front page" the "No front page content" message will disappear, even if the node isn't shown at all.

See node_page_default for the logic there.

Alternatively, you could look into use hook_page_alter to remove the $build['default_message']


View: How to make a list of article(in a block) related to the taxonomy term of my main article I would like to display a list of link in a block that are related to the taxonomy term of my main article.

I read others subjects like article-view-with-links-to-other-articles

but it doesn't work for me. My URL is like that : example.com/product/[node:id] (Maybe it doesn't work because i don't have the term id in my url)

My article has a vocabulary call "tendance", this article is tag with the term, for instance "tendance one". I would like to have all the article tag with "tendance one"

I have this configuration:

Contextual filter: Content nid
WHEN THE FILTER VALUE IS NOT AVAILABLE : raw value from URL
I add validation etc.
And in More section, i click on exclude

So i had a list of all my article in my block thanks to the exclude but there are not related to the term "tendance one" of my main article.

I tried to add relationship :

Content: Taxonomy terms on node (and i select my vocabulary "tendance" and required relationship)
Taxonomy term: Content using tendance

And it doesn't work, i always have the same list of article linked to the good vacabulary but not to the good term.

Do i have to pass in my url the taxonomy term to make it work?
Thanks,

i've just found the perfect solution for me.

I tried a lot of solution with some php code but without success.

The problem was : I had one view which display an article (with a taxonomy vocabulary) and i wanted to add a block with a list of link of another content type who are linked with the same taxonomy term.

URL: www.example/product/[nid]/[title]

Contextual filter

Contextual filter: Content nid
WHEN THE FILTER VALUE IS NOT AVAILABLE :  raw value from URL (path -> 2 to retrieve the node id)

RELATIONSHIPS

Content: Taxonomy terms on node (with Require this relationship)
(term) Taxonomy term: Content with term  (with Require this relationship) -> Relationship -> Taxonomy terms on node

And after you have to come back to the contextual filters:

And add a Relationship to Taxonomy term: Content with term

Now it works great, i have all my other content type with the same term of taxonomy linker to the term of the main article display by view on my page.