How to set the default values of "Included Export Components" for a Drupal Webform I'm trying to figure out how to set the default values of the Webform Results > Download > Included Export Components Field to exclude certain fields.

The webform module defaults to a state for that field in which all the webform's fields are checked.  They can be manually unchecked before each download but we've run into a business requirement by which we would require 3 fields (IP Address, Draft, and UID) to be unchecked on the page load.

I've looked through the configuration pages for the webform module and for the specific webform node and have come up empty handed.  I've considered writing an additional module which will override the module which sets the checkboxes.  Before I went that route though, I was wondering if anyone has dealt with this requirement before and/or can share some insight/point me in the right direction.

Thanks!

I remember having to do that once, and though I looked at how the values were initially set, I still ended up using hook_form_alter to change them.
I don't remember why exactly, but presumably due to fact I couldn't reach them as easily.

Just use a hook_form_alter in a custom module to get to the form, and unset the defaults you don't want.

This should pretty much do it in a hook_form_alter or hook_form_ID_alter ( example is for hook_form_alter ) :

if ($form_id == 'webform_results_download_form') {
  /**
  * default ( and named ) components are :
  * - serial: Submission nr
  * - sid: Submission ID
  * - time: Time
  * - draft: Draft
  * - ip_address: IP Address
  * - uid: User ID
  * - username: User Name
  */
  $excludes = array('serial', 'sid');

  foreach ($form['components']['#default_value'] as $cid => $component) {
    if (in_array($component, $excludes)) {
      unset($form['components']['#default_value'][$cid]);
    }
  }
}

This will uncheck both the Submission Nr & Submission ID checkbox. Adjust the $excludes array accordingly to your needs


Code running in one theme but not the other I am using the Mobile Theme module to switch between my themes, in my primary theme's page-front template I have some PHP code including a select statement, it queries tables created by a contributed module. The code works fine in my primary theme but in the mobile theme, the PHP returns nothing. What could cause this change from one Theme's page-front to another? None of this code relies on template.php, but I copied that over in case.

Themes are highly cached. That's a reason why you should avoid logic in them if only you can. And if you have to, put it in template.php, not .tpl files. Probable reason of query not executed is that template got cached and Drupal sees no reason to evaluate files again. You could force it to, probably, but it would be a huge performance killer.

Move your queries to contrib module, and query-based logic to template.php and you'll be good.


Drupal block-level form submit URL? I have a form:

function form_search_products($form, &$form_state) {
  $form = array();

  $form['keyword'] = array(
    '#type' => 'textfield',
    '#description' => 'Enter keywords (ie: Fat free milk)'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Add item to my shopping list'
  );

  return $form;
}

Simple and its loaded into a block region above product listings via:

function products_block_view($delta = '') {
 $block = array();

  switch ($delta) {
    case 'search_form':
    {
      $block['content'] = drupal_get_form('form_search_products');
      break;
    }
  }
  return $block;
}

I am trying to figure out how to map a submit handler now as there is no menu...

My current menu looks like this:

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

  $items['products/mycity'] = array(
    'type' => MENU_CALLBACK,

    'title' => 'Enjoy shopping in MyCity',

    'page callback' => 'html_list_products',
    'access arguments' => array('access products')
  );

  $items['products/autocomplete.json/%'] = array(
    'type' => MENU_CALLBACK,

    'page callback' => 'json_list_products',
    'page arguments' => array(2),
    'access arguments' => array('access products')
  );

  return $items;
}

What or how do I add to the menu_hook above so that I can process form submissions done through the above block code???

Alex

Form submissions aren't dependent on there being a path to view/submit the form at, all you need to do is one of the following:

Name the submit function as FORMNAME_submit() and Drupal will pick it up automatically
Add the handler manually in the form function itself, e.g.

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


Panels vs. Entity View Attachments (EVA) Just digging into view, panels, contextual filters, etc. do build and render related entities. In this context I got the EVA module and now asking myself if I need EVA when using Panels? In a panel (page) I can include a pane to insert the result of a view - at least that is what I understood so far. Isn't EVA about the same thing? If I don't use Panels I see the point of EVA but if I use Panels anyway do I need EVA?

Thx for help,
Marc

Whether you need a module or not depends on your use case; you certainly don't want to install and enable a bunch of modules that you don't need, as this will slow down your site and can cause other problems.

In this context, if Panels does what you need alone, then you don't need any other modules (and Panels can do so many things that it generally is sufficient by itself).

If you're committed to Panels, there's probably no need to use EVA-- and certainly if you're asking whether there's a need, you should try doing everything in Panels first, as that will be easier to maintain long-term.

EVA would be better if you wanted something more lightweight and just want to make changes for a few things; Panels is more useful if you want to take full control over the layout.  EVA can also be used in circumstances where Panels integration isn't finished (e.g., Revisioning module and Panels' node add/edit forms).

That said, these two modules really aren't all that similar.  Usually the layout modules are considered to be Panels and Context.  Entity View Attachments is really just an extension of the attachment feature provided by the Views module.  In that way, you could think of it as competing with content panes, another type of display provided by Views specifically for Panels (for reference, this question relates to the differences between attachments and content panes).


I edited the database but the site's showing old content no longer in it I needed to find-and-replace text across several nodes in my database, so I exported it via PHPMyAdmin and then ran the find-and-replace on the resultant .sql file. I then dropped all tables in my database and imported the edited .sql file. Now when I inspect my database with PHPMyAdmin I see that the text I removed with the find-and-replace is no longer there; however when I view or edit a node with the text I've replaced I see the replaced text still there. This is despite the fact that if I search for that text in the .sql file I imported (or a fresh .sql export after the import) I don't find it anywhere.

Why is this? How can I fix it, and successfully find-and-replace text in my site with the method above (or some better method, though that's slightly changing the question)?

Example

If you view source on http://gwwc2.centreforeffectivealtruism.org/node/546 you'll see at the start of the node content:

<style type="text/css"> <!--        @page { margin: 2cm }       P { margin-bottom: 0.21cm }         A:link { color: #2198a6; text-decoration: none }    -->     </style>

However when I run SELECT body_value FROM field_revision_body WHERE entity_id=546 (which seems to be the right query as I'm using D7) I don't see this anywhere in what's returned, which instead starts:

<p>A perennial criticism

Have you refreshed your caches?
Configuration -> Development -> Performance -> Clear all caches


List field with 'Select All' option? I have a Product content type with a list field of Groups (another content type). I would like to be able to have a 'Select All' item in the Groups list that allows the user to relate the product to all groups.

Note: This isn't the same as using javascript or ctrl+a to select all items in the list, because that approach would mean that when a new group is added it would not automatically be selected.

There are two workarounds that hit my mind, depending on the logic your UI could have.
1. If having no Group assigned could mean "assigned to all" - go for it.
2. Else: consider adding additional checkbox (boolean) field labeled "Fits all" (or whatever you like).


Mink failing to run JavascriptTestBase tests I suspect this is more a config issue than anything but struggling to run JavascriptTestBase tests. The error I'm getting is as below:

  wodby@php.container:/var/www/html $ ./bin/phpunit -v -c ./web/core
  ./web/core/tests/Drupal/FunctionalJavascriptTests/Tests/JSWebWithWebDriverAssertTest.php
  PHPUnit 6.5.8 by Sebastian Bergmann and contributors.

  Runtime:       PHP 7.1.17 Configuration:
  /var/www/html/web/core/phpunit.xml

  Testing
  Drupal\FunctionalJavascriptTests\Tests\JSWebWithWebDriverAssertTest S
  1 / 1 (100%)

  Time: 21.2 seconds, Memory: 6.00MB

  There was 1 skipped test:

  1)
  Drupal\FunctionalJavascriptTests\Tests\JSWebWithWebDriverAssertTest::testJsWebAssert
  An unexpected error occurred while starting Mink: Could not open
  connection: Error forwarding the new session cannot find :
  Capabilities {browser: firefox, browserName: chrome, browserVersion:
  9, deviceOrientation: portrait, deviceType: tablet, name: Behat Test,
  selenium-version: 2.31.0, version: 9}

  /var/www/html/web/core/tests/Drupal/FunctionalJavascriptTests/JavascriptTestBase.php:50
  /var/www/html/web/core/tests/Drupal/Tests/BrowserTestBase.php:484

  OK, but incomplete, skipped, or risky tests! Tests: 1, Assertions: 1,
  Skipped: 1.

I'm running this directly within a docker container. Selenium is also running in a docker container and I know I can connect from my PHP/Apache container to the Selenium container as running

wget http://selenium:4444/grid/console

Returns the selenium Grid Console homepage.

My phpunit.xml file looks as follows:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true">
  <php>
    <ini name="error_reporting" value="32767"/>
    <ini name="memory_limit" value="-1"/>
    <env name="SIMPLETEST_BASE_URL" value="http://apache"/>
    <env name="SIMPLETEST_DB" value="mysql://drupal:drupal@mariadb/drupal"/>
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value=""/>
    <env name="SYMFONY_DEPRECATIONS_HELPER" value="weak_vendors"/>
    <env name="MINK_DRIVER_ARGS_WEBDRIVER" value='["chrome", null, "http://selenium:4444/wd/hub"]'/>
  </php>
  <testsuites>
    <testsuite name="unit">
      <file>./tests/TestSuites/UnitTestSuite.php</file>
    </testsuite>
    <testsuite name="kernel">
      <file>./tests/TestSuites/KernelTestSuite.php</file>
    </testsuite>
    <testsuite name="functional">
      <file>./tests/TestSuites/FunctionalTestSuite.php</file>
    </testsuite>
    <testsuite name="functional-javascript">
      <file>./tests/TestSuites/FunctionalJavascriptTestSuite.php</file>
    </testsuite>
  </testsuites>
  <listeners>
    <listener class="\Drupal\Tests\Listeners\DrupalListener">
    </listener>
    <listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener">
    </listener>
  </listeners>
  <filter>
    <whitelist>
      <directory>./includes</directory>
      <directory>./lib</directory>
      <directory>./modules</directory>
      <directory>../modules</directory>
      <directory>../sites</directory>
      <exclude>
        <directory suffix="Test.php">./</directory>
        <directory suffix="TestBase.php">./</directory>
      </exclude>
     </whitelist>
  </filter>
</phpunit>

Could anyone give me any pointers in the right direction?

There's an annoying bug with the Selenium2Driver code with regards to specifying the correct browser. If no capabilities are specified, it uses the defaults:

    public function setDesiredCapabilities($desiredCapabilities = null)
    {
        if (null === $desiredCapabilities) {
            $desiredCapabilities = self::getDefaultCapabilities();
        }

Note in the error it hase browser defaulted to firefox while the browserName is correctly set to chrome:

Capabilities {browser: firefox, browserName: chrome,

In order to workaround this issue, change your capabilities to also specify browser:

<env name="MINK_DRIVER_ARGS_WEBDRIVER" value='["chrome", {"browser": "chrome"}, "http://selenium:4444/wd/hub"]'/>


Set lightbox effect for the link I have a gallery, created as a view:

http://hotelcentralpark.ro/gallery/2

Now the titles are links to the pages. And  images have lightbox effect.

I want the links to activate lightbox of the appropriate image. But there are no settings for that in the admin panel.

Here are the settings for the image field:

Settings for the header field in the control panel:

How can I set the link to act as lightbox?

Here is the image content type structure:

In Views Use this code in "Rewrite the output of this field"

[title]

You can also set the width and height of the popup window, see the read-me file in Lightbox2  module folder.

hope you will get idea from the above!!


Trying to keep facets visible even when the terms restrict facets I believe the setting I am looking for is minimum facet count, so that I can set it to 0.

I'm going based on this:

https://drupal.org/node/1669600#comment-6190924

I don't have search API installed, however I do have Apache Solr installed.

When I'm searching for something, say tech, whenever there are results that don't have that keyword, the facets are disappearing - the client doesn't want the facets to disappear.

I tried to disable this disappearance in the template.php above, but it didn't work.

How do I keep facets visible in Apache Solr even when there are 0 results?

How do I keep facets visible in Apache Solr even when there are 0 results?

As I know, it's not possible. You can make separate query for display facets, but they cannot be displayed if solr return no data.


Empty Field Notification View? My website has a content type with about 15 fields. Now I don't have all the data to fill the fields all the time. I've got close to 1000 entries in this content type.

Is there any module that can work as a Notifier. Ex: I've chosen to have Content Type A selected and the module tells me how many Entries that are not 100% filled and what fields are missing. ?

Try any one of the module as per your requirement.
Content Complete

Content Complete is a CCK extension module that allows to tag CCK fields needed for completion (CCK Complete). The module checks the tagged fields against the content provided for those content types, and computes a complete percentage that can be shown to the user.

Field Complete

In some situations you want to mark an entity field to indicate it should be completed but not enforce its completion at that time. This module extends the choice between Required and Not required to "desirable" completion.
This module overcomes the problems with the (otherwise excellent) Content Complete module which cannot cope with field collections or fields that link to other entities.

Hope the following links give you clear ideas on how to use Content Complete module.
Measure node completion in Drupal, part 1
Measure node completion in Drupal, part 2


How to unfocus button after ajax form was rebuilt? I have a form that is completely ajaxified and when I submit the form the submit button stays focused.

I have styling in place and it results in bad UX. How should I unfocus the button? Do I have to implement ajax response and some custom JS for this? Seems like a hacky solution :(

You can solve this by setting focus to another element on rebuild.

I don't know how to do it in Drupal 8, but here's Drupal 7 code to focus an element:

In the form_alter:

  // Focus the first element on rebuild.
  if ($form_state['rebuild']) {
    $first_element = array_keys($form['entry_fieldset']['entry_ids'])[0];
    $form_state['focus_id'] = $first_element;
  }

  // Allow a form element to be focused.
  if (isset($form_state['focus_id'])) {
    // Pass the element ID as a variable to the JS.
    $settings = array('focus_id' => $form_state['focus_id']);
    $form['#attached']['js'][] = array(
      'data' => array('example' => $settings),
      'type' => 'setting',
    );
  }

JS:

  /**
   * Focus a form element.
   */
  Drupal.behaviors.exampleFocusElement = {
    attach: function(context, settings) {
      if (settings.example && settings.example.focus_id) {
        // Focus the element having the ID passed in.
        $('#' + settings.example.focus_id, context).focus();
      }
    }
  };


How do I relocate the "Reset password" form? Is there a way to hide and relocate the Reset password form from standard location? The login form needs to be shown as is.

I wasn't able to do what the answer on How to print the local task bar different places depending on the base route? says to do.

I found the No Request New Password module. However, I'd like to still access this form on a special link.

How do I print the local task bar in different places depending on the base route? is about changing where the tabs for local tasks are rendered in the page. It's different from what you want to achieve.

The module you found (No Request New Password) is for removing the Request new password link from block and user page. This is probably part of the task you want to achieve, but you cannot use that module because it has not been completely ported to Drupal 8, and it would not work. If you look at the content of the noreqnewpass.module file, you will notice it is using functions that don't exist anymore in Drupal 8, as in the following hook implementation.

function noreqnewpass_form_alter(&$form, $form_state, $form_id) {
  if (($form_id == 'user_login_block' || $form_id == 'user_login') && variable_get('noreqnewpass_disabled', true)) {
    $key = array_search('user_login_final_validate', $form['#validate']);
    $form['#validate'][$key] = 'noreqnewpass_user_login_final_validate';
  }
}

The task you want to achieve requires to:

Remove the Reset your password local task from the /user/login page
Change the path associated with the user.pass route
(Eventually) remove the Reset your password link that appears in the login block

The fist step requires a module implementing the following hook.

function custom_menu_local_tasks_alter(&$data, $route_name) {
  // Remove the "Reset your password" tab only from the login page.
  if ($route_name == 'user.login') {
    unset($data['tabs']['0']['user.pass']);
  }
}

The second step requires altering a route another module defines. There isn't any hook to do the task, which requires writing code for an event subscriber. Fortunately, Drupal 8 has a class that can be extended to do the task.

class CustomSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change path '/user/password' to '/hidden/user/reset'.
    if ($route = $collection->get('user.pass')) {
      $route->setPath('/hidden/user/reset');
    }
  }

}

An event subscriber is a service using the event_subscriber tag. This means it needs to be defined in the .services.yml file of the module.

For the last step, it's sufficient to alter the login block.

function custom_block_view_user_login_block_alter(array &$build, BlockPluginInterface $block) {
 unset($build['user_links']['#items']['request_password']);
}


Create a Form in a Block using API that sends captured data to email Possible Duplicate:
  Send email of form data?

So I have a simple three field form which I've created in HTML/CSS, see here:

Now I want to put this into a block module, generate the form fields using Drupal Form API (is this appropriate or should I just stick with my existing HTML markup?). And on submission of the form I want it to email the details to a designated email. Is Drupal Triggers appropriate for this, if not, what is?

Any guidance on where to go with this would be amazing. Thanks so much for your time :)

Use simple news module which will give you lots of e-newsletter features out of the box.

For new features you can extend above module to suit your specific requirements.


Commerce Dynamic Address Field Issue I've got a problem with the dynamic address field. Maybe it is a problem with the feed-importer, not quite sure about that.

I've imported customers to my database, in the view, name and address are displayed correctly but when i click on edit, those fields are empty. Seems like they are correct in the database.

Addressfield module depends on the country for displaying the right structure of the form that is configured by the plugin, I'm afraid country is mandatory so you can just select one in the field settings so you don't have the selector, then you'll need to do some theming magic for hiding it when it's displayed


How to call AJAX on check-box of form API? I need to get radio buttons in a form, whenever a checkbox gets enabled/clicked.
Say, I have 5 items listed in a checkbox, named orange, apple, .....When I enable orange checkbox, a set of radio button comes that will ask color of the corresponding fruit. Any working example regarding this will be highlyy appreciated.

EDIT:

$form['toggle_me'] = array(
  '#type' => 'checkboxes',
  '#title' => t('Tick this box to type'),
   '#options' => array(0 => t('Orange'), 1 => t('Apple')),
);
$form['settings'] = array(
  '#type' => 'radios',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"][#options][0]' => array(0 => t('red'), 1 => t('yellow')),
    ),
  ),
);

Try This, may be helpful for you

$form['checkbox'] = array(
    '#title' => 'Select',
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('Orange'), t('Apple'))),
    '#ajax' => array(
      'callback' => 'fruits_callback_form',
      'wrapper' => 'fruit-check',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
  $checkbox = !empty($form_state['values']['checkbox']) ? $form_state['values']['checkbox'] : 0;
  $form['slots']['#prefix'] = '
';
  if ($checkbox == 'Orange') {
    $color = array(0 => t('Red'), 1 => t('Blue'));
  }
  $form['color'] = array(
    '#type' => 'radios',
    '#title' => t('Select Color'),
    '#options' => $color,
  );
  $form['slots']['#suffix'] = '
';

  //Callback function

  function fruits_callback_form($form, &$form_state) {
    return $form['color'];
  }


Using attachFileToField in a Functional test doesn't allow entering the alt text for an image In a Functional test, I am doing:
    $this->drupalGet('node/add/article');

    $page->fillField('title[0][value]', 'Page 1 EN');

    $page->pressButton('Add image');
    // Using TestFileCreationTrait::getTestFiles().
    $image = current($this->getTestFiles('image'));
    $page->attachFileToField('field_image', $this->container->get('file_system')->realpath($image->uri));

This appears to work, in that if I then do:
    $page->pressButton('Save');

I get a form error because the image alt text is required.
But this doesn't work:
    $page->fillField('field_image[0][alt]', 'Image alt text EN');

and in the browser output, I don't see the subfields for the image.
In FunctionalJavascript tests that use attachFileToField(), there's typically a waitForFoo() call which waits for the form AJAX to update and show the image subfields.
But that's not available in Functional tests, and besides, there's no AJAX since there's no JS.
How can I get this to work?
(I'd really rather not use drupalPost() to send a massive edit array; using Mink to fill fields one by one is much better DX I find.)

Ah, it looks like this might do it:
    $page->fillField('field_image[0][alt]', 'Image alt text EN');
    $page->pressButton('Upload');
    // This reloads the page and the alt text field is now present.


CKEditor add custom class to table I want to add a class to a table inserted in CKEditor.

I have tried to add a custom style using the styles dropdown and add this line, table.my-custom-class|Table, but when clicking on the table the styles dropdown is not activated and I'm not able to add the class.

Is this possible to do with the styles dropdown?

I do use the ckeditor_tabletoolstoolbar module, so alternativaly I can add a custom button to the toolbar, but I don't know how to do that either?

I have seen this thread, but it's for CKEditor 3, I'm using CKEditor 4.

I want to be able to toggle the class, so it's removed when clicking the button again.

How can I solve this problem?

I solved the problem by creating a custom CKEditor plugin.

This is the JS code, in case anyone find it helpful:

CKEDITOR.plugins.add('tableclass', {
  beforeInit: function (editor) {
    editor.ui.addButton('addtableclass', {
      label: 'Add table class.',
      command: 'addTableClass',
      icon: '/modules/custom/mymodule/icons/add.png'
    });
  },
  init: function (editor) {
    editor.addCommand('addTableClass', {
      canUndo: true,
      exec: function (editor, data) {
        const className = 'custom-class';
        var selection = editor.getSelection();
        var selectedElement = selection.getStartElement().$;

        if (selectedElement.localName === 'table') {
          selectedElement.classList.toggle(className);
        }
        else {
          selectedElement = selectedElement.parentNode;
          while (selectedElement && selectedElement.localName !== 'table') {
            selectedElement = selectedElement.parentNode;
          }
          if (selectedElement.localName === 'table') {
            selectedElement.classList.toggle(className);
          }
        }
      }
    });
  }
});


How to reset form page after it has been successfully submitted? User is allowed to submit answers from the question node view page.

The form is redirected to the same question node view page after submission. But the form displayed still displays the older values. How can I reset these values?

function answers_custom_node_view($node, $view_mode, $langcode) {

  if (arg(0) == 'node' && is_numeric(arg(1)) && $node->type == 'question') {
    global $user;
        if(node_access("create", "answer", $user)) {
        $node1 = (object) array(
            'uid' => $user->uid,
            'name' => (isset($user->name) ? $user->name : ''),
            'type' => "answer",
            'language' => LANGUAGE_NONE,
        );
        $form_state['build_info']['args'] = array($node1);
        form_load_include($form_state, 'inc', 'node', 'node.pages');
        $form = drupal_build_form('answer_node_form', $form_state);
        $output = drupal_render($form);
        $node->content['answer_form'] = array(
            "#type" => "markup",
            "#markup" => $output,
        );
      }
   }
}

function answers_custom_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == "answer_node_form") {
       if (arg(0) == 'node' && is_numeric(arg(1))) {
        $nid = arg(1);
        $node = node_load($nid);
        if($node->type == "question") {
             $form['#submit'][] = "answers_custom_destination";
        }
       }
   }
}

function answers_custom_destination($form, &$form_state){
   if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load($nid);
    if($node->type == "question") {
        $form_state['rebuild'] = TRUE;
        $form_state['redirect'] = drupal_get_path_alias('node/'. $node->nid);
     }
   }
}

That happens because you are using $form_state['rebuild'] = TRUE; which is telling Drupal to rebuild the same form, which also mean the form will be repopulated with the last values the users entered. When you then set $form_state['rebuild'] to TRUE, $form_state['redirect'] is ignored, since the user is already redirected to the page containing the form.

The code I would use is the following one.

function answers_custom_form_answer_node_form_alter(&$form, &$form_state) {
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    // See https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_get_object/7.
    $node = menu_get_object();

    if ($node->type == "question") {
      $form['#submit'][] = "answers_custom_destination";
    }
  }
}

function answers_custom_destination($form, &$form_state) {
  // Since the form submission handler is added only when the user is seeing node/%node,
  // there is no need to verify that again.
  $form_state['redirect'] = FALSE;
}

As side note, since the form alter hooks and the form submission handlers share $form_state, which is passed by reference, if something needs to be shared between those functions, it can be added to $form_state. As long as the added array index doesn't conflict with an array index used by Drupal or third-party modules, all is fine.

For example, this code would use $form_state to share a value between the hook altering the form, and the form submission handler.

function answers_custom_form_answer_node_form_alter(&$form, &$form_state) {
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    // See https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_get_object/7.
    $node = menu_get_object();

    if ($node->type == "question") {
      $form_state['answers_custom_question'] = $node;
      $form['#submit'][] = "answers_custom_destination";
    }
  }
}

function answers_custom_destination($form, &$form_state) {
  // Since the form submission handler is added only when the user is seeing node/%node,
  // there is no need to verify that again.
  $form_state['redirect'] = drupal_get_path_alias('node/' . $form_state['answers_custom_question']->nid);
}

Reference

drupal_build_form()
drupal_redirect_form()


Stop node being edited programatically I have written a module that puts a "generate pdf" link on a node when it is viewed. What I now want to do is lock the original node after the pdf is generated.

I know I could just add a "locked" field to the content type I want to lock, and then programatically set that etc. But I'd prefer it to work with any content type.

How can I programatically disable the editing of a node? I'd prefer to install as few additional modules as possible.

For this you should have to implement hook_node_grants and hook_node_access_records. It look something like that -

 /**
  * Implement @hook_node_grants
  */
 function MODULENAME_node_grants($account, $op) {

  $grants =array();
  $grants['Node_Edit_Permission'][]=array($account->uid);
 return $grants;
}

/**
 * Implement @hook_node_access_records
 */
function MODULENAME_node_access_records($node) {

  $grants = array();

  if ($node->type == 'node_type') {
    $user_id = /* list of user id which you want to block */;

     // Revoke Permissions from these Users
    if (!empty($user_id) {
      foreach ($user_id as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }
  }

  return $grants;
}


Grouping Content Panes in Views For Theming I've created a view for a specific content type. This view has a number of Content Panes associated with it.

I need to apply a row template file to about half these panes but the only tpl name suggestions the "Theme: Information" section gives are shared across all panes.

Is there a way to delineate certain panes for templating purposes? Machine name kind of works but I don't want to end up with views-view-fields--machine-name-1.tpl.php, views-view-fields--machine-name-2.tpl.php, ....

Thank you!

In Views you can change this by giving the View a name, which will change the display name from views-view--view_id--page_1 to views-view--view_id--my_display_name. You can do this in the Advanced section of a view display config, and changing the 'Machine Name' value.


Modal windows module for Drupal 7 content? I have looked at a bunch of modal window modules but they all seem to only apply to media such as images or videos.

Do any of the modal window modules (lightbox, shadowbox etc) for drupal 7 allow drupal content to be displayed within, for example blocks / webforms etc?

I've used the colorbox module for this purpose for a couple of recent D7 projects.  It works well and seems to fit your use case.

You might also want to checkout the overlay module in D7 core, but it generally involves more effort to make it work for the non core use cases.


How to drush enable a module only if is not installed I would like to drush enable a bunch of modules in a certain environment via a shell script that runs EVERY TIME the environment rebuilds when new code is committed. (This saves me from having to have access to a drush terminal when I want to first install a module in an environment, but means I don't know if module is being enabled for the first time or if it was enabled long ago)

I'm concerned there might be consequences of repeatedly enabling already enabled modules. Is this true?

If yes, I'm trying to find a drush command to enable a module only if it's not already enabled.

For example, I have seen this page:

drush en `drush pm-list --status="disabled,not installed" --pipe`

which enables all disabled modules.

and

drush dis `cat tmp.txt` --yes

which disables all modules listed in tmp.txt

I want something like:

drush en `magicfunction(tmp.txt, `drush pm-list --status="disabled" --pipe`)`

where magicfunction is some linux command line magic that returns the names of modules listed in tmp.txt that are also in the list of not enabled modules.

Any ideas?

You can use grep command to filter out the modules from disabled list to only which are appearing to your list, e.g.

drush -y en $(drush pm-list --status="disabled" --pipe | grep -f tmp.txt)

Other way is to use SQL query:

drush -y en $(drush sqlq "SELECT name FROM system WHERE name IN ('$(cat tmp.txt | paste -sd, | sed "s/,/','/")');")

which may be more complex, but quicker (especially when you replace drush sqlq with mysql -e command.


Commerce editing content for products i have a project that is based on a normal drupal, and i have added commerce modules to it,
but i can't find the module or setting that changes the way of editing the product from:

to:

can anyone point me to the right direction?

I believe that functionality is provided by the Inline Entity Form module

Provides a widget for inline management (creation, modification, removal) of referenced entities.
The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.

Edit: In fact it definitely is, this is an image from the module page:


Arrange fields in a drupal form by multiple columns/rows I'm trying to create forms that I can customize to display multiple elements in a column or row, instead of the current one field per line that seems to be the default.

I've been searching around for a few modules and so far have only come across one that would be able to do what I need which is Form Panel.

How do I edit or create forms where I have control of the layout? I would like to avoid code as much as possible.

I did use the https://drupal.org/project/webform_layout Module which does create a div container around one or more fields.

You may choose between Horizontal, Equal Width and Vertical Orientation.
Further you can nest divs of Layout Boxes.

It is simple and does the job.


OG subscribe link rewrite How can I remove or rewrite "group/node" and "og_user_node" from url when user click on OG subscribe link ?

siteURL/group/node/63/subscribe/og_user_node

Is there any module like pathauto where I can use to make this url a custom look?

Thanks.

Well you know that all these requests are made using hook_menu.

Yes, you should use hook_menu_alter Create new module and add hook_menu_alter

function my_module_menu_alter(&$items) {
    // Unset core path
    unset($items['The_actual_menu_request']);
    $items['your_new_menu_request'] = array(
        'title' => 'OG subscribe',
        ...
      );
}

Just pass the same page callback and arguments as the menu request for og subscribe

EDIT

Well try this snippet and see if it works, for OG subscribe menu request

Create a custom module. If you do not know how to create a custom module read This

then in your .module file add this code. It should work, I do not know if the 'file' argument needs an absolute path to the file, but if it does not work you just have to change it for the real path in og '../og/og_ui/og_ui.pages.inc'

function my_module_menu_alter(&$items){
  //unset core path
  unset($items['group/%/%/subscribe']);
  //as an example (taking the example url you provided) I will call the new menu request community/node/63/sign-in
  $items['community/%/%/sign-in'] = array(
    'type' => MENU_CALLBACK,
    'file' => 'og_ui.pages.inc',
    'page callback' => 'og_ui_subscribe',
    'page arguments' => array(1, 2),
    'access callback' => 'user_is_logged_in',
    'title' => 'Join group'
  );
}

Greetings hope it helps you, do not forget to mark the answer.


How to choose what tables to skip for drush sql-sync @dev @staging? Following my previous question
How to set Drush sql-sync not to clone users between @dev and @staging?
I have manually preselected over 80 tables that should not be automatically synced (content, roles and permissions, users, temporary, cache). I am not fully satisfied with this solution. Why? Because my filter decisions is based on experience, intuition and guess when I would like to use the best practice method.

How to properly choose what tables to skip for drush sql-sync @dev @tst and drush sql-sync @production @staging?

My setup:
git.drupal.org ==> local drupal git repository ==>  @dev -> @tst -> @staging -> @production (configuration, static content, roles and permissions)

@staging <- @production (content, production scenarios to be tested)

The Definitive Guide to Drupal 7 by Benjamin Melançon and others says:

  Here is the list of tables that appears in example.drushrc.php:

$options['structure-tables'] = array(  'common' => array('cache',
  'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions',
  'watchdog'),
);

  You may need to add some more tables to this list. A good place to
  start would be to consider the list of tables that contain cache in
  their name via drush sql-query 'show tables;' | grep cache

  Remove from this list tables such as imagecache_action and so on, and
  add the remainder to your structure tables list.

  After you do an sql-sync with skipped tables, you will need to clear
  the cache on the target site to make sure that things work right.

What are the other tables to consider? Why?

Drush sql-sync does not support shared databases that use prefixes.  You might have some luck if you wrote a wrapper script that used drush sqlq 'show tables;' to get a list of available tables, filter them manually by prefix, and then pass them back to sql-sync via the --tables-list option.


Set value for new field automatically based on another field I want to add a new date field to an existing content type, and set the new field automatically for existing nodes to be equal to another date field from that content type.

For example, if the new field is called 'Event date', and there is an existing field 'Publication Date', I want the 'Event date' field to contain the date from the 'Publication date' field for all existing nodes, without assigning each one manually.

Is this possible?

It is possible and the best way to do it is in a custom module. Here's how:

Assume you have a module called mymodule.
Inside mymodule.install create a function called mymodule_update_N where N is a number starting at 7100. See the API documentation for hook_update_N for details but this is what runs when you run update.php
Inside your mymodule_update_7100, load the nodes you want to act on and then iterate over them, setting your newly created field to the value from Event Date.

If you have a lot of nodes, you'll want to look to the Batch API system to batch the nodes one by one so you don't run out of PHP memory or run up against the timeout. If it's not a ton of nodes, you don't need to worry about that usually.

And last, but not least, you should use an EntityFieldQuery to get the nodes you want to act on.

Hope that helps. Good luck!


How to act on paramters being passed to the homepage? We have external sites direct users to our homepage. These external sites add information to the url which add additional information. This is an internal academic site so these parameters look like, for example, http://www.example.edu/?dept=classics
How can I get our homepage to detect and act on these parameters?

I think my approach would be to use $_SERVER['REQUEST_URI'] in a hook_preprocess_HOOK (see this) on template.php in a theme folder if all I needed to do is theming based on it.  For example:

function example_preprocess_page(&$variables) {
  $current_path = $_SERVER['REQUEST_URI'];
  // and so on
}

And then you could explode() it, modify stuff in the page array or the node array, etc.


Inside TWIG Template, how to determine if a paraph is empty or not I have a paragraph called "Square cta" that I'm using like an old field collection.  It has 2 fields in it - a text field (field_cta_text), and an Image (field_square_cta_image).

I have a content type called "Show Page" in which I will upload an image and put in the cta text for.

I then have a view that shows all of the show pages and I reference the square_cta in my template - node--view--seasons.html.twig - like so

{{ content.field_square_cta }}

This works great for displaying the image inside the field_square_cta for the show and it acting as a link back to the Show Page node it's in.

Where I am having trouble, is not all shows have the field_square_cta populated.  For those show pages, I want to just display the of the node instead.  I have been unable to figure out how to write my if logic to determine if the field_square_cta is undefined.

Here is what I was trying to do:

{%  if content.field_square_cta %}
  {{ content.field_square_cta }}
{%  else %}

{{ label }}

{% endif %}

The conditional is always going with the if, never the else, even when I don't have any data inside the content.field_square_cta.  I have been unable to determine the proper syntax for checking if that is empty or not.

Any help would be greatly appreciated.

Better use the node object to check whether the field is not empty:

{% if not node.field_example.isempty %}


Exposed filters in Block for Page View do not filter results I have below content types with following related fields setup in a Drupal7 setup.

Activity
    Fields: Name, Body and Image.

Event Fields:

Date
Location: Term Reference for Taxonomy Location
Activity : Term Reference for Taxonomy Location
Organiser: Entity Reference for Organizer node (as 1 event will have only 1 organizer)

Organiser
    Fields:

Location: Term reference for Location taxonomy
Activity: Entity  Reference for node Activity.

I have setup a Page View named Experience, with Listing of Events on right sidebar and on left sidebar i want to display the Filters.

I have managed to Expose the filter with BEF, however these filters don't give any result after changing value. Though they are set to Use Ajax.

Also other filters like Organiser and Location are autocomplete fields, these fields do not show-up any value on entering text.

Kindly help

UPDATE: Here's the SQL Query

SELECT node.nid AS nid, node.title AS node_title, node.created AS node_created, 'node' AS field_data_field_event_date_node_entity_type, 'node' AS field_data_field_event_image_node_entity_type, 'node' AS field_data_field_event_location_node_entity_type, 'node' AS field_data_field_event_amount_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_event_club} field_data_field_event_club ON node.nid = field_data_field_event_club.entity_id AND (field_data_field_event_club.entity_type = 'node' AND field_data_field_event_club.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('event')) AND (field_data_field_event_club.field_event_club_target_id IS NOT NULL ) ))
ORDER BY node_created DESC
LIMIT 12 OFFSET 0

Is your views filter is working when you disable ajax submit?

if No then enable -> Show the SQL query

from URL www.yourdomain.com/admin/structure/views/settings

then check query which is generating on submit of the form, you will get solution there only

try and let know status.


where does $data come from in hook_tokens? In a custom module i have hook_tokens() implemented in order to create some custom tokens. What i realized is that some data is being declared as null but i don't know where this is happening. These values are coming from user input in a submitted web form. input from traditional web form fields do appear but input added through payment method fields are the ones appearing as null.

this is a small snip of what var_dump($data) shows:

$data['webform-submission']->payments[34]->contextObj->submission->data[47][0]"August"
$data['webform-submission']->payments[34]->contextObj->submission->data[46]array[1]
$data['webform-submission']->payments[34]->contextObj->submission->data[46][0]"1"
$data['webform-submission']->payments[34]->contextObj->submission->data[16]array[1]
$data['webform-submission']->payments[34]->contextObj->submission->data[16][0]null
$data['webform-submission']->payments[34]->contextObj->submission->data[35]array[1]

EDIT:

Thanks for the clarification on where $data comes from. I also realized that the hook i created (hook_token_info) is not being utilized. When i create a token i do not see it listed under Browse available tokens when i edit emails templates under the web form tab. Oddly hook_tokens is being called when i pass token_alter('[submission:custom:card_type]', array('submission'=>$card_type)) however the token is empty.

The $data is whatever is originally passed to the token_replace function by the process that's doing the token replacement.

The var itself is:

  An array of keyed objects. For simple replacement scenarios 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.

It's essentially just an array that's used to pass extra context to the token replacement, and it can contain anything at all.

For example if you were writing a module that introduced a custom entity type, you could use this feature to pass an instance of that type in to be used in your own tokens.

In your specific case, it's presumably the Webform module that prepares that data array, so that would be where to look if something's missing. Or it could be a submodule if that's what you've used to provide the payment fields themselves.


How do I get the global user object? How do I get the global user object in hook_preprocess_page()?

<?php
public function behave() {
  $account = \Drupal::currentUser();
  if ($account->id() == 1) {
    return "Hi, boss!";
  }
  else {
    return "You are not the site administrator.";
  }
}
?>

Note that in neither case is the value an actual User object. Rather, as of Drupal 8 it is a UserSession object, which duplicates some, but not all, of the information of a user. It may also represent the Anonymous User rather than a saved User entity. See link for more information.


image field - how to overwrite existing image? How to set up the image field in a content type so that it always overwrites images with the same name instead of creating new images with name suffix _0, _1 etc. Currently, while editing a node and uploading image with the same name as existing one, it won't overwrite.

If it is impossible, then how to achieve it programmatically (hook, hack?) without help of any additional modules, just using the core image field.

Its not there -- this functionality has been discussed on Drupal.org and ruled out by the maintainer of the filefield module before because it could cause the original file to be deleted before the node is saved. You can follow their argument here:

http://drupal.org/node/427212

Fortunately, if you do want the file to be replaced when you upload a new one with the same name there is an alternate module you can add for 6x/7x called Upload File Replace that does this and avoids the issue above:

http://drupal.org/project/upload_replace


want to make user-login before view contain i am making a online tutorial site where a user can view can different contain but i want then to go through login.

For example: you have a home page. after login, user get redirected to the video page. but i dont want to display video page at the homepage.

you can go for LoginToboggan module .

 The LoginToboggan module offers several modifications of the Drupal login system
 in an external module.

    Allow users to login using either their username OR their e-mail address.

    Allow users to login immediately.

    Provide a login form on Access Denied pages for non-logged-in (anonymous) users.

    Customize the registration form with two e-mail fields to ensure accuracy.

    Optionally redirect the user to a specific page when using the 'immediate login' feature.

    Optionally redirect the user to a specific page upon validation of their e-mail address.

    Optionally display a user message indicating a successful login.

    Optionally combine both the login and registration form on one page.


Creating multiple node references I have the following content types - Efforts, Objectives, Groups and the user.

Efforts and Objectives can be shared by both users and groups. A user/group can have multiple objectives and efforts and can also share the same objectives/efforts.

Is it possible by using node references ? or Is there any other way where I can implement this functionality in drupal ?

sure you have to use node reference
I think you need a node reference in efforts and objectives to select users or group so you need a node reference to a view (you can reference to a view it should not be node)

the same user/Group make a view reference to objects and efforts

If you have any problem make a comment


Problem installing Drush 7 due to missing ext-pcntl PHP extension - any workarounds? I attempted to install Drush 7 using the "manual install" instructions, and the "composer install" step failed with the error that the ext-pcntl PHP extension was not found.  The hosting company (which I don't have control over choosing) says they are unwilling to install ext-pcntl in a production environment due to security concerns.  Are such security concerns justified?  Is there any workaround for installing Drush 7 without the ext-pcntl dependency?  If not, I might try to install an older Drush version that doesn't have the dependency.

Are such security concerns justified?

Given the description on extension's introduction page, yes:

  Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

Emphasis mine.

But also no, because, as greg_1_anderson stated in his answer, it can be enabled (or even compiled) into CLI only.

Then again, it might be yes. With functions like pcntl_fork it might be possible to make a fork bomb. Other bad things may also be possible. Personally, I wouldn't allow it on shared server.

Is there any workaround for installing Drush 7 without the ext-pcntl dependency?

Not really*, but if you can mount webserver's filesystem on your local machine and tunnel SQL port, you can install drush locally and still use it on remote website. From Drush's point of view there will be no difference.

* Correct me if I'm wrong here.


Get views exposed filter values I have a view in which I want to have a link that passes the current exposed filters values through to another custom page (not a view).

For example if the "Day One" checkbox is checked I want my link to be able to reflect this checkboxes value.

Link

Is there some form of array where all exposed values are stored when a view is shown? I can't seem to find one

I got what I needed after reading a couple of views docs.

 $view = views_get_current_view();
 $view->exposed_input['filter_name']


How to add template suggestions for entities? I need to add a template suggestion for entities in a custom module, similar to how you can add one for nodes. I've seen the ones implemented in the Entity API module, but how do I hook into entity preprocessing so I can add my own?

I found a solution. The Entity API module defines template_preprocess_entity() such that you can add template suggestions during your own preprocessing in a custom module, like for example:

function mymodule_preprocess_entity(&$variables) {
    if($variables['elements']['#entity_type'] = "myentity") {
        $variables['theme_hook_suggestions'][] = "myentity";
    }
}

This runs preprocessing for custom entities built off the Entity API, but not for not nodes or entities built into Drupal core. In order to add template suggestions for Drupal core entities, you need to add it while using the various entity-specific preprocessing hooks provided in Drupal core. For example:

// Preprocessing for taxonomy terms
function mymodule_preprocess_taxonomy_term(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for user profiles
function mymodule_preprocess_user_profile(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for comments
function mymodule_preprocess_comment(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for nodes
function mymodule_preprocess_node(&$variables) {
  // Add template suggestion code here.
}


Alter views exposed form drupal 8 I have a view that in that view I set up 3 exposed filter, all working fine.

I need to set a condition to show the third filter option to a specific user, it can be checked according to the user role, but how I should do that?

Can anyone provide a hook to help me?

Previously I tried the following but it does not change anything:

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

  if ($form_id == 'views_exposed_form') {

    //unset($form['average']);

    var_dump($form);

    die();
  }
}

My view looks like this

Following example unsets the filter average when user is NOT administrator, you can modify it to your specific case.

use Drupal\Core\Form\FormStateInterface;
function my_modulename_form_alter(&$form, FormStateInterface $form_state, $form_id){

  $roles = \Drupal::currentUser()->getRoles();
  $is_user_admin = in_array("administrator", $roles);
  $is_exposed = $form_id == 'views_exposed_form';
  $is_filter_set = isset($form['average']);

  if ( $is_exposed && $is_filter_set && !$is_user_admin ) {
    unset($form['average']);
  }
}

If you want to unset only on a specific view exposed form use this condition

$is_our_view = $form["#id"] == "views-exposed-form-article-page-1";


Add JavaScript 'effects' to be used with AJAX form submissions Consider the following code:

        $form['actions']['submit']['#ajax'] = array(
            'wrapper' => 'apple-node-form',
            'callback' => 'node_add_callback',
            'method' => 'replace',
            'effect' => 'fade'
        );

This will produce a JavaScript fade animation. But how can I define my own animations? For example, 'effect' => 'myCustomAnimation'.

I'm really just looking for a way to be able to define my own JavaScript function, and have that function handle the AJAX request. I could just call .ajaxComplete() on the document and have a series of switch statements in there that figure out what to do with the response. But that's a bit hacky, and the switch statements (as well as the initial response parsing) would be additional logic. If I can just define right there in the $form array PHP code the JS function to be used, no ugly switch statement would be necessary.

It appears you need to install the interface elements library to add custom effects.
As indicated in the forms api.
http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7
ajax['effect']
Description: Specifies the effect used when adding the content from an AJAX request.
Values: String. Possible values: 'none' (default), 'fade', 'slide'. If the interface elements library is installed, any effect with the name effectToggle may also be used.
I hope this helps :)


Can't call hook index document build I have installed the apachesolr module and it all works fine.
To display more details about results, Ivs decided to add indexes.

But Im stucked, because the
hook_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) is not called.

Im using the last version of both solr and Drupal module.

I finally resolved it.
The hook is called during the indexing not during the search.


How can I connect drupal 6 and activemq? I would like to use publish subscribe technique to send updates to drupal as they happen in an external database. This database has middleware that publishes changes using a messaging system (apache camel).

If you're willing to upgrade to Drupal 7, Services version 3 should interface to (for instance) JSON or SOAP.

Feature of version 3:

  Response format API allows you to define response Formats for CONTENT-TYPE ie. application/json or application/xml.

Edit: I didn't know about STOMP, which the OP mentions in a comment. I add it here for searches/future reference:

  STOMP is the Simple (or Streaming) Text Orientated Messaging Protocol. The Stomp module implements an alternative Drupal Queue backend for queues supporting the STOMP protocol - such as ActiveMQ, RabbitMQ.

For Drupal 6, there is JSON server.  I am not familiar with it, but you may be able to use that instead.


Securing Admin on separate port I am attempting to secure the admin pages (/admin/*) and login page (/user/login) to port 8443. I have successfully done that with the following in apache 2.4:

<VirtualHost _default_:443>
    ServerName example.com:443
    ServerAlias drupal
    DocumentRoot "/opt/rh/httpd24/root/var/www/html/example.com/current"
    <LocationMatch /(user|admin)>
            Require all denied
    </LocationMatch>
</VirtualHost>

<VirtualHost *:8443>
    ServerName example.com:8443
    ServerAlias drupal
    DocumentRoot "/opt/rh/httpd24/root/var/www/html/example.com/current"
</VirtualHost>

The problem I am having is when I go to https://www.example.com:8443/user/login and login, I am redirected to http://www.example.com:8443/user/1.

This creates a 400 error - Bad request. Trying to serve http content over a SSL port.

How do I tell drupal to stay on https protocol and remain on port 8443?

So I wasn't able to do this on a separate port, but for anyone who needs to secure the login page from public eye, this is what I did.

<VirtualHost _default_:443>
  ServerName example.com:443
  ServerAlias drupal
  DocumentRoot "/opt/rh/httpd24/root/var/www/html/example.com/current"
  <LocationMatch /(user|admin)>
        Require all denied
        Require ip 10
  </LocationMatch>
</VirtualHost>

This will require the user to be on a local IP. (I am in-housing the site, so when I access the site I'm on a local IP.)


HTML5 web app: How do I create a dynamic manifest file with drupal? I hope this is the right place to talk about this...

I'm planning to create an HTML5 web application which basically download new contents, something like the financial times app.
I want to use drupal such as base where I can upload contents and the export it such as json view.
In the web app I would like to create a local database where i will add the contents.
To keep it update I will compare the last content creation date in the app with the last content creation date on drupal, if they are not the same it will download the latest contents and add it into the db.
This is "quite simple", let's move to my problem now...
I've got one image per each content and, to see the images offline, I need to add it to the manifest file every time a new content is added.

How can I get this? Or if you think I should use another method, let me know.

Thanks in advance.

images should be attached to content via image field(if not I know another way, just ask), so you can create a new views and fetch only these images

add page display to that views and use it to create manifest, in this way you have dynamic manifest. if you want write it to file, small module is needed.

in this case you need have more than one manifest (multiple manifest), one of them is for your images

steps to create images manifest:

create views to fetch images: named manifest_1
create page display in that views: named page_1
create a small module to create your manifest, dirty sample:

function mymodule_menu() {
  return array(
      'manifest/images' => array(
          'page callback' => 'mymodule_manifest',
          'access arguments' => array('access content'),
          'type' => MENU_CALLBACK,
      )
  );
}

function mymodule_manifest() {
  $images = views_get_view_result('manifest_1', 'page_1');
  //sent header text/manifest
  //output image paths
  die();
}


Two views one page (sorting, etc) I am sure this is just by design and not much can be done, but I figured i would ask anyway...

I have a couple views on a dashboard. Each can be sorted, but when I sort one by "Date Submitted" all the others follow suit, which is expected, but not desired.

Is there a way to disconnect the Views, so that query parameters bind to a single view instead of all on screen?

Just curious,
Alex

Yes, when you configure your view, if you edit the pager settings, there's a Pager ID that if you change it you'll get a different pagination for each view, you can sync some but others not and so on.


Increase upload file size by content type I have worked with our host to increase our upload file size to 2GB.  However, on one page it still states that the files must be less than 3MB.  How do I change that?  I am a Drupal novice so please bear that in mind.

The following is on a content type on our website (classified as a 'story'):

  Files must be less than 3 MB. Allowed file types: jpg jpeg gif png txt
  doc xls pdf ppt pps odt ods odp.

So I am trying to increase the size to be 2GB as per what our host is allowing. How do I increase the file size to upload?

It sounds like the content type "story" has a 3MB limit set on that file field.

You can increase that limit by browsing to "example.com/admin/structure/types" and select the "Manage fields" tab (for the "story" content type). Find the field in question (the file upload field) and edit it. You should find a setting for the maximum upload size there.

If you'd like to learn more about fields, and specifically file fields, check out this Drupal.org resource and and this one as well.

Now, the other thing you will need to review is your .htaccess file. There are a couple of php flags you will want to review:

php_value post_max_size
php_value upload_max_filesize

Review the .htaccess file first because no matter what setting you set for your file field on the content type "story", it will be overridden by the setting in the .htaccess file.


How to exclude the result of one view from another one? I would like to implement a discussion overview page which displays the hot topics  and latest topics, excluding the hot topics from the latest ones.

I have two displays in the same view, each of those operates on the same dataset (listing the same content type).
The difference between the two displays is the sort criteria only.

Is it possible to set up the display which generates the latest topics list to exclude hot topics? More generally: is it possible to exclude the results of one view from another without making a custom module?

I would like to get a general answer not involving offsets, because we'll probably face a situation where the sort criterias have to change. Most likely offsetting won't solve my issue there.

[Drupal 7 with Views 3.]

One thing that pops to mind, albeit dirty, is to use php in the argument and do:

views_get_view_result($name, $display_id = NULL)
Loop over resulting nids of your hot topics then explode them out separated by +
set the argument to exclude these nids.

Not the cleanest solution as it leaves you with php in the DB but it would work.


How do I give the following responsive information in the .info file? I have the below lines in the info file for a Drupal 7 theme.

stylesheets[all and (min-width: 980px)][] = css/960.css
stylesheets[all and (min-width: 760px) and (max-width: 980px)][] = css/720.css
stylesheets[all and (max-width: 760px)][] = css/mobile.css
stylesheets[all][] = style.css
stylesheets[all][] = color/colors.css

How do I map these in Drupal 8?

Your D7 declarations have the effect of placing the media query in the markup, and I think you want to replicate that method. You can do this in the library declarations, e.g.

stylesheets[all and (max-width: 760px)][] = css/mobile.css

Becomes:

mobile:
  version: 8.x-1.0
  css:
    layout:
      css/mobile.css: { media: all and (max-width: 760px) }

Note I am assuming this is for layout, hence my use of the "layout" SMACCS category for this library.

Personally I don't really bother with such things and write the media queries in the CSS, if you have many media queries you're going to have a lot of extra http requests if you're always splitting files based solely on breakpoint.


How should I prevent second page of site's front page from being indexed? My website's second page has the URL http://example.com/node?page=1

I've got the marinelli theme installed.

For SEO purposes, what should be done for the second page node?page=1 of blog listings? Should I disallow it from robots.txt or do something else?

Since view?page=1 will almost always be the same as view, you should add these lines to your robots.txt

Disallow: /*sort=
Disallow: /*order=
Disallow: /*page=1

More at: http://larsolesen.dk/content/struggling-duplicate-content-drupal-7


Create a view based on node reference field There are two content types Gallery and Image. Image has node reference field (node reference from url). Gallery doesn't have any node reference fields.

By using views I can show all related images on a gallery page (I use node reference field "field_pers_gallery" as a contextual filter).

At the same time I need to create a view to show all images related to one gallery (all images have the same value in field field_pers_gallery) on a page of every image. I would like to create a view that looks like Flickr  image page with related images. I have the problem with it because I cannot choose the right contextual filter to create the view as I want.

I tried the following examples but nothing helped me, I cannot understand why.

http://drupal.org/node/370227#comment-4364810
http://drupal.org/node/370227#comment-5699610
How can I build a view that shows other nodes that reference the same node the current node references?

Could anybody help me with any advices?

I think here is a simple solution just add that the node reference field (field_pers_gallery) to contextual filter then all nodes (Images) which have same value in that field can be displayed on a page.


Views Grouping by Field I'm looking to display a list of staff grouped by department.  I've figured out how to do this just fine with one exception.

I have a few staff who's time is split between 2 departments.  However, when I edit their department field and enter more than one department, they show up in a new section.  For example.

  Outreach

    Joe Smith

    jane Smith

  Technical Services

    Joe Johnson

  Outreach, Technical Services

    Jane Johnson

Instead of having this separate display, I want Jane Johnson to be listed twice, under both Outreach and Technical Services.

Any ideas?

I'm not sure if you've had this answered yet, but in Drupal 7 and the latest version of Views, this is possible by doing the following:

Under Fields, click the one you want to configure, in your case it probably looks something like:
Content: Departments

Select Multiple Field Settings and it will drop-down to where you see a check mark in the box labelled:
Display all values in the same row

Uncheck this box and it should list your members twice, once in each department they are specified under.


Is it possible to use civicrm stand alone profile page to edit existing contacts? Is it possible to use civicrm stand alone profile page to edit existing contacts? Is it also possible to alter or override civicrm stand alone profile page via Drupal hook apis?

Generally agree with the previous commenters -- you can do an edit screen using "civicrm/profile/edit", and "webform_civicrm" is generally the next level to go if you want the effect of a standalone profile managed in a Drupal-way. There are hooks for manipulating Civi's profile screens, but they're different from the hooks of typical Drupal forms.

For completeness, we should add some links about Civi's profile hooks. The most concise reference I can think of is:

https://github.com/civicrm/civicrm-core/pull/1144/

It's a bit dense, so let's drill down on an example section:

civicrm/profile/edit:
    CSS: form#Edit .crm-profile-name-{NAME}
    Region: profile-form-{NAME}
    Hooks: buildProfile($name), validateProfile($name), processProfile($name)

What this says: If you're dealing with the page "/civicrm/profile/edit?gid=X", then there are three ways to precisely customize that profile (and no other profiles). All three require that you know the {NAME} of the profile. (This is internal name that corresponds to the DB field "civicrm_uf_group.name".)

To customize with CSS or jQuery, use a selector like "form#Edit .crm-profile-name-{NAME}". (As always, it's helpful to "View Source" and see the precise tags on your form.)
To append/prepend content programmatically, use a region named "profile-name-{NAME}".
To execute code while processing the profile, you can use hook_civicrm_buildProfile($name), hook_civicrm_validateProfile($name), or hook_civicrm_processProfile($name).

For information about other Civi hooks, see wiki.civicrm.org/confluence/display/CRMDOC/Hook+Reference .

(NOTE: I left some links as plain-text because stackexchange limits the #links from new users.)


How to correctly handle date formats that needs i18n Suppose you have a date format that looks like this: "Some text Y-m-d other text H:i". Please ignore that the text needs some escaping.

What is the correct way of outputting this in a i18n friendly way?
I see that format_date attempts to do some sort of translation work, but I don't understand entirely what.

My best guess:

implode(' ', array(
  t('Some text'),
  format_date($timestamp, NULL, 'Y-m-d'),
  t('other text'),
  format_date($timestamp, NULL, 'H:i'),
);`

Is this the correct/best way?

Try something like:

$text = t("Some text @date more text @time", array(
  '@date' => format_date($timestamp, NULL, 'Y-m-d'),
  '@time' => format_date($timestamp, NULL, 'H:i'),
));

More info at:

http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/t/7
http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/format_string/7


hook_user_insert not being called I've got a custom module weekly_digest and I want to make it so each new user is added to a table with info on their subscription preferences.

I've been using the admin UI to add the users to test, unsure if that effects things but I don't see why it would.

As some context, in my .module I currently have weekly_digest_node_insert and that works just fine.

And here is the function which does not get executed and I can't get Xdebug to catch it either:

function weekly_digest_user_insert(UserInterface $entity) {

  $query = Drupal::database()->insert('weekly_digest_user_preferences');
  $query->fields([
    'uid',
  ])->useDefaults([
    'new_posts',
    'digests',
  ])->values([
    $entity->id(),
  ])->execute();

}

Most search results returned "Can't in theme" or "Drupal 7" so I was unable to figure this out.

It could be that you are using the incorrect argument. hook_ENTITY_TYPE_insert is a generic hook, it's not opinionated about what entity you are "inserting" (E.g. it could be a node, taxonomy, user...)

Try:

function weekly_digest_user_insert(\Drupal\Core\Entity\EntityInterface $entity) {
  // Do stuff.
}


drupal moving from local host to live server - error Error
The website encountered an unexpected error. Please try again later.
Error message

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1231 Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER' in lock_may_be_available() (line 167 of /httpdocs/includes/lock.inc).

I am getting the above error after deploying a website on server.

Basically, I created a Drupal website on local server. After finishing it, I generate the database script and run it on live server using phpmyadmin. and then I upload and files on server and change the setting file for database connectivity.

Once I tried to access the website, I am getting the above error like I said before.

I find this solution. but because I am running a dedicated server and don't want to update phpmyadmin. So, I am looking for way around.

clue

When creating database exports, the tables are usually locked to ensure that there are no attempts to access or change data within the tables while they are being exported and imported. Those locks will usually be released at the end of the import process. That obviously did not happen for your database.

Most likely your database import in phpmyadmin timed out and did not complete the import process. Check the tables available in phpmyadmin and see if there are the same number of tables as on your local server. If the data appears to be properly intact on the production server, then you will need to manually unlock the tables.


Collapsible items in menu administration In sites with a lot of nested menu items on a menu (e.g the main-menu) administration becomes painful. Is there a module which will add expand/collapse capabilities to the admin/structure/menu/manage screens?

This has also been discussed in http://drupal.org/node/521546 but doesn't seem to be resolved.

The Big Menu module seems to do the job. Here is a quote about it (from the module's project page):

An alternative to core menu management - adds scalability to the admin menu management screen, by loading subtrees via AJAX (not related to megamenu & similar display modules - this is an admin-only content management utility).
When dealing with a site menu that contains thousands of links, the Drupal Menu UI admin interface becomes so unwieldy as to be impossible to use. When the drag & drop functions for tree management are running, a page can take minutes to render.
This module attempts to replace the all-in-one global tree view with a similar interface, but sub-trees are "collapsed" below a certain level, and can be expanded as needed.


"Output this field as a custom link" set here link to the content How to set in "Output this field as a custom link" a link to the content.

In drupal 7 it looks like this:

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

Tried this, but this doesn't work:

Replacement patterns in image field:

And in link to content field:

Found a solution:

Add a Link to Content field, outer fields hide from display and remove links.

then setup Link to Content like this:

Link to Content haven't link path input - it always link to content.  This what I needed!


Views: Using Pager With Single Node, Multiple Fields I created a node, that has multiple images on it. I want to use this node as the "source" for a views page showing a gallery of images.

I am having a few problems, the first and most major, is that the pager does not work.

I presume that is because all of the images are coming from a single node.

The second problem is more aesthetic; the images are not spaced correctly, and are not distributed across the width. I am not sure how to fix this problem either.

Any help would be greatly appreciated.

You can use Nivo Formatter to make your image field to a slider. There is no need to build this with views.


ckeditor underline not allowed on filtered HTML I have a problem whereby I cant underline text using ckeditor whilst in Filter HTML, it works fine with Full HTML. I can also use Bold and Italic with Filter HTML but not Underline. Is there a configuration setting for this, so a User set up with just permission for Filter HTML can add underline?

You have to allow <u> HTML tags in 'Filtered HTML' filter (/admin/config/content/formats/filtered_html).


Views data export user role field value missing from exported csv file I'm using views_data_export to export data from the views displays. I added a Data Export option to the user account list views. When I use the batch in export settings, user role field is missing in the exported CSV file. While not using batch, role field is there.

Thanks

I found this is a bug in the module itself, and the following patch will solve the issue.

Discussion: https://www.drupal.org/project/views_data_export/issues/2789531#comment-13345278

Patch: https://www.drupal.org/files/issues/2019-11-08/views_data_export_batch_empty_fields.patch


How to avoid losing custom CSS/JS on a form using Ctools Modal when Validation Errors Occur I have a regular content type form that has been customized quite a bit with a form alter. I am wanting to see about getting that form in to a ctools modal window for the creation of that content. I am able to do so, and I am able to create content. However, my form_alter customizes this form with some JS and CSS which is being added by specifying an #after_build on the form.

/**
* implements hook_form_alter to add in some custom submit and validation callbacks
*
* @form
* the activity form at node/add/activity-log
*/
function activity_log_form_alter(&$form, &$form_state, $form_id) {
 global $user;
 //activity log form
 if($form_id == 'activity_log_node_form') {
  //specify an after build function where i can add JS and CSS files
  $form['#after_build'][] = 'activity_log_entry_form_after_build';

  //change the submit buttons text value
  $form['actions']['submit']['#value'] = t('Save this task');
  $form['actions']['submit']['#weight'] = 30;
  unset($form['actions']['preview']);

  if(isset($form['actions']['delete'])) {
    $form['actions']['delete']['#value'] = t('Delete this task entry');
    $form['actions']['delete']['#weight'] = 35;
  }

  //submit handler and validation handler
  $form['#submit'][] = 'activity_log_form_submit';
  $form['#validate'][] = 'activity_log_form_validate';

  } //end check for activity log form
}

/**
 * This function is ran after the node/add/activity-log form is built. The css and js files are added here
 * because if they are added in the form alter, they won't get included when the form throws validation errors.
 *
 * @form
 * the activiyt log form at node/add/activity-log
 */
 function activity_log_entry_form_after_build($form, &$form_state) {
    //add the chosen library in there
    drupal_add_js(libraries_get_path('chosen') . '/chosen.jquery.min.js');
    drupal_add_js(libraries_get_path('chosen') . '/chosen.proto.min.js');
    drupal_add_css(libraries_get_path('chosen') . '/chosen.min.css');

    //activity log js and css
    drupal_add_css(drupal_get_path('module', 'activity_log') . '/css/activity_log.css');
    drupal_add_js(drupal_get_path('module', 'activity_log') . '/js/activity_log.js');

   return $form;
}

This works great when I browse to the normal forms create content url, and if there are validation errors, all is well. However, when using the form in the modal window, if there are validation errors, I lose my JS/CSS on form rebuild even though the form_alter and after_build are still being called. Any ideas why?

Turns out that the JS and CSS files were not being dropped, but since the modal window uses ajax, all the ID's were being incremented when the form was rebuilt after a validation error.

So JS and CSS selectors such as edit-field-act-property-ref

would become

which is a problem if you have CSS/JS targeting the original. I thought I would share in case this helps out somebody else in the future.


How to create HTML Tooltips using the Charts module's API with Google Charts? I'm using the Charts module and I've been trying to set up a simple pie chart that has HTML in the tooltips.  We would like the HTML to be menu links, but they can just be manually coded into the chart code.  However, I have not been able to get this working.  Looking at the API (http://cgit.drupalcode.org/charts/tree/charts.module#n46) it seems there is an option to set: '#tooltips_use_html' => TRUE

But I haven't been able to get it to work.  I've tried the following code in the body of a node:

$chart = array(
    '#type' => 'chart',
    '#title' => t('Pie Chart with tooltips (no data labels)'),
    '#chart_type' => 'pie',
    '#chart_library' => 'google', // Allowed values: 'google' or 'highcharts'
    '#legend_position' => 'right',
    '#data_labels' => FALSE,
     '#tooltips' => TRUE,
     '#tooltips_use_html' => TRUE
  );
  $chart['pie_data'] = array(
    '#type' => 'chart_data',
    '#title' => t('Gender'),
    '#labels' => array('Male', 'Female'),
    '#data' => array(10, 20),
  );

/*
$chart['pie_data_item'] = array(
    '#data' => 10,
    '#color' => 'NULL',
    '#title' =>'Male',
  );

$chart['pie_data_item'] = array(
    '#data' => 20,
    '#color' => 'NULL',
    '#title' =>'Female',
  );
*/

  $example['chart'] = $chart;

In place of $chart['pie_data'] I've also tried the commented out code $chart['pie_data_item'].  With the first approach I do get a result, but the HTML is not rendered correctly, and labels are being treated as the tooltips?  Is there anyway to tell what HTML goes into each tooltip?

EDIT: Using the patch in https://www.drupal.org/files/issues/2209467-9--raw_options.patch as recommended by Pierre.Vriens I was able to enable the #raw_options array.  I've looked around and haven't found any clear documentation what that array is supposed to look like though.  How would I use #raw_options to generate HTML tooltips?

The most recent Charts version does not yet support "tooltips" as such. However, have a look at Pass library-specific options via existing #raw_options, which provides an alternative (using #raw_options) to what you're trying to get to work. For charting engine Highcharts it's already supported (and committed to the most recent dev version), while for charting engine Google Charts you'd need to apply the RTBC-patch attached to comment nr 9 (from about 6 months ago). Obviously, after that patch is committed, my recommendation here to use the #raw_options will continue to work (for either charting engine). And rest assured, this patch will make it (so it's not a patch that might make it).

With this #raw_options solution, we have a solution for using options that are specific for either of the supported charting engines (Google Charts or Highcharts). While still not deviating from a key design concept of the Charts module, which is that all supported charting options should work for either charting engines (you should be able to easily swap from one to the other charting engine, without your charts being affected).

Disclosure: I'm a co-maintainer of the Charts module.


Need filter on value of a field in a specific node of different content type in Views I have content type pick_topic, containing an entity ref taxonomy field topic. There is one node of this type. It defines the topic of the month. Several views blocks and pages need to only display content nodes with this topic value. Example: taxonomy topics: dogs, cats, rabbits.

The user (site manager) edits this node and selects a topic from dropdown. Say it is dogs. My view of another content type, articles, contains topic field. How can I filter the view based on the pick_topic topic value equal to the article topic field value, in this case dogs?

I don't know of a way to do this all in the interface, but if you add a contextual filter in the view for the topic field on the article content type, you can programmatically set the contextual argument in hook_views_pre_view.

First, load your pick_topic node like:

\Drupal::service('entity_type.manager')->getStorage('node')->load(PICK_TOPIC_NID);

Then load the field value. See How do I access a field value for an entity (e.g. node) object?

Then set the view argument.

function MY_MODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'MY_VIEW_ID' && $view->current_display == 'MY_VIEW_DISPLAY_ID') {
    // Load your pick topic node.
    // Load your pick topic field value.
    // Set the view argument, term id.
    args[] = $my_pick_topic_field_value_tid;
  }
}


How to get url of Product image field of Entity Reference field Trying to create a view (a block) with associated products on product pages. Products have a field "Related products" (Entity Reference) and in my view (show products' fields) I can get images and titles of them using contextual filter (Content: Nid) and relationship (Entity Reference: Related products). But there's a problem with the url of titles and images, they're leading to editing pages (like admin/commerce/products/1), but not to content.
I tried to add a field Content:Path, but I get a link to a product itself, not to related with it products.

As you're creating your view, you need one more relationship. Look for this relationship:

  Commerce Product: Referencing Node

  (Relate a product to the Node referencing it through field_product.)

This will allow you to harness the "reverse-relationship" going from the product to the reverse-node. Add this relationship, require it, and then use this to generate your links.


Make Backup & Migrate backups smaller in size I have a 2MB upload cap on my school's server and get an error from backup and migrate that it cannot restore the file.

Is there any way the backups from backup and migrate module be compressed in some way and upload them when are needed?

I often take a backup before making new changes on the site and revert to the last one if I make a mistake or get an error, so ideally all files(DB and Directory) need to still be backed up...

Backup & Migrate module by default backs up all the data that is in your database. That includes cache_%, watchdog, and other tables data that is not essential for a backup. By excluding data that lives in those tables from your backup (Advanced Backup settings) you can save a great deal of MB.
Read more about tables recommended for exclusion here -Backup and Migrate exclusion recommendations?.


The responsive menu (Sidr menu) is not working with anchors I'm using the responsive menus, specifically the Sidr menu, the menu is not working when the paths have anchors.  When I do click in a item with anchor the menu is still opened.  The toogle in the menu is not working.

Thanks in advance for your help.

The solution to this question is here: https://www.drupal.org/node/2697767


Pictures are not responsive on Firefox & Internet Explorer, Using grid on views I am building a site with a lot of pictures.
On Google Chrome Everything is working fine.

On FF & IE, If I am just viewing the content & picture not through a view - everything is fine.
But, the pictures are not responsive when I am presenting the picture using views.
I read & saw many tutorials regarding breakpoints Module, Picture Module, and more.
On the picture field on views, I chose the right Formatter, picture group and Fallback image style.

I am using zen sub-theme, but the problem also occur on other themes I tried.

If there are other modules that can fix this issue, or you can help me solve the situation currently, it will be great.
Any Ideas?

Thanks!

I use the Adaptive Image module. It gives you an adaptive behavior you can select when on Admin>Configuration>Image Styles. In other words, you'll need to create an image style with the new adaptive behavior (it should appear in the pick list after you install the module), or alternately, add the adaptive behavior to existing image styles. Once you've done that, you just need to use the adaptive image style in the view, either by adjusting the image field settings, or by changing the settings on the display type fields if you're using content or rendered entities. For the most part, I found that doing the above steps gives me responsive images, but I sometimes have to tweak my CSS also.


Preserve nids script add in migrate d2d What is the file name I have to add the following script in it?

  This is actually easy to do. In the prepare() function of the node
  migration class, just set the nid and is_new to true:

public function prepare($node, $row) {
  // Preserve old nid so that old links to nodes using /node/nid still work
  $node->is_new = TRUE;
  $node->nid = $row->nid;
}

  Source link:
  How can I preserve nids during a migration?

Unfortunately, sometimes answers on stackexchange are misleading.  It doesn't look like ANY classes within migrate_d2d extend MigrateDestinationEntity, that invokes a "prepare" hook.  So I think the question itself is misguided.

Looking in the migrate code, it looks like any class that extends abstract class MigrateDestinationEntity can call this process function see
/migrate/plugins/destinations/entity.inc,

on line 140:

// Then call any entity-specific handlers
migrate_handler_invoke_all($this->entityType, 'prepare', $entity, $source_row);

Rather than trying to find a place to call this from DrupalNodeMigration, which will never call this function, what you need to do is add a mapping for nid, and a mapping for "is_new".

In your class that extends the DrupalNodeMigration class, in the __contruct() function, just make sure to add a mapping for nid and is_new.

$this->addFieldMapping('nid', 'nid');
$this->addFieldMapping('is_new')->defaultValue(TRUE);

Otherwise, nid will be automatically assigned.


If you update a routes file in Drupal 8 how do you clear the cache? Having worked with Drupal 7 since its launch, I'm learning Drupal 8. At the moment I'm finding that whenever I change anything I have to do drush cache-rebuild to get things working again.

On my VPS this takes 15 seconds (and then the next page load also is slow). I have a feeling this may be a sledge hammer to crack a nut situation.

Is there a more efficient way to get Drupal to recompile the (changed) routes from {module}.routing.yml files?

You can use

drush ev '\Drupal::service("router.builder")->rebuild();'

to rebuild the routing information without clearing all the caches.


How to let users mark ( like) other users? In my project I'd like to let users to mark (kinda like) other users.

What solution should I use? Appreciate any feedback.

You can use Flag module. It does have integration with Views module. So you can configure and customize.

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.

  Flags may be per-user, meaning that each user can mark an item
  individually, or global, meaning that the item is either marked or it
  is not marked, and any user who changes that changes it for everyone.

  In this way, additional flags (similar to published and sticky) can be
  put on nodes, or other items, and dealt with by the system however the
  administration likes.


500 Server Error after deployment I apologized as I'm not well versed specifically with drupal. But anyway, I was migrating an existing installation on a Windows Server to a Linux Server (debian).

I went ahead and moved all the files, setup the database, updated settings.php in /sites/default

I also chown'd with correct user, and set /sites/default/files to 777 permissions with all other directories set to 755 and files set to 644.

I have errors with some images, css, and js. I checked the files, and they exist. When attempting to access via GET request (http protocol) I get 500 Internal Server error.

Looking at PHP's error logs I see these alerts (no errors):

/sites/default/files/.htaccess: Option FollowSymLinks not allowed here

When I edit said .htaccess files to:

#Options None
#Options +FollowSymLinks

The images load, but the CSS and JS does not (it exists but tries pulling from incorrect directory). I am also worried about security in this folder.

ie:

Actual Request: GET site.com/css/css_49249400b301b59bd86200648ba96215.css

Correct Request: GET site.com/sites/default/files/css/css_49249400b301b59bd86200648ba96215.css

Anything I could be doing wrong?

Help is appreciated!

UPDATE:
Rewrites are enabled and working.

Did you have "Clean URLs" enabled on the Windows install?  You may need mod_rewrite enabled in Apache (a2enmod rewrite)

I'm not sure how your server is configured (os/php version/etc), but I had a similar issue that required me to change the following in .htaccess

# RewriteBase /
to
RewriteBase /

Another thing to check would be that overrides are allowed at all.  Apache needs to be set to something like "AllowOverride All"

More info regarding AllowOverride:

How can I enable clean URLs?

How to enable Clean URLs?

Regarding permissions, there is a bunch of information available including a script that can help repair permissions (obviously use extreme caution when running and verify before you do.)

Source for the script below.

#!/bin/bash

# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:

  1) Path to your Drupal installation.
  2) Username of the user that you want to give files/directories ownership.
  3) HTTPD group name (defaults to www-data for Apache).

Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}

if [ $(id -u) != 0 ]; then
  printf "**************************************\n"
  printf "* Error: You must run this with sudo or root*\n"
  printf "**************************************\n"
  print_help
  exit 1
fi

drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"

# Parse Command Line Arguments
while [ "$#" -gt 0 ]; do
  case "$1" in
    --drupal_path=*)
        drupal_path="${1#*=}"
        ;;
    --drupal_user=*)
        drupal_user="${1#*=}"
        ;;
    --httpd_group=*)
        httpd_group="${1#*=}"
        ;;
    --help) print_help;;
    *)
      printf "***********************************************************\n"
      printf "* Error: Invalid argument, run --help for valid arguments. *\n"
      printf "***********************************************************\n"
      exit 1
  esac
  shift
done

if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
  printf "*********************************************\n"
  printf "* Error: Please provide a valid Drupal path. *\n"
  printf "*********************************************\n"
  print_help
  exit 1
fi

if [ -z "${drupal_user}" ] || [[ $(id -un "${drupal_user}" 2> /dev/null) != "${drupal_user}" ]]; then
  printf "*************************************\n"
  printf "* Error: Please provide a valid user. *\n"
  printf "*************************************\n"
  print_help
  exit 1
fi

cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .

printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;

printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;

printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;

printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
  find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
  find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done setting proper permissions on files and directories"