Multisite domain path access control E.g. My site have two subdomains : domain_a and domain_b.

I create a path: "custom/a".

I hope:

domain_a can visit the path.

domain_b visit the path, get 404.

Except according to the golbal $domain in the code, does anyone have other solution?

There's a few ways to do that, but an easy one is to use the Panels module to define the page, coupled with domain_ctools

Then you can just add a selection rule or access control rule to specify the valid domains via the user interface.

Alternatively, you could do something with hook_menu access callbacks.


Add combined fields to Content type I'm creating a website with a Project content type. In that content type there are common fields and a few group fields. Group fields are fields that need to stay together and can be added multiple times. So in my Group fields there will be a date field and a text field that can be added multiple times.

Do I need to create a new content type or taxanomy type for this or is there a module for Drupal 8 that provides this behaviour.

Try the module field_collection.

Add a field of type field_collection to your content type and allow multiple values. Then go to structure => Field collections and choose your field to add your date and text field.

Update: field_collection is on its way to be deprecated

Use paragraphs module instead.

Notice these meta data issues for paragraphs.


Changing exposed filter doesn't rebuild SQL query I created 5 fields for filters. 3 of them are exposed to site visitor. Problem is that if I even change this exposed filter values while editing View it doesn't rebuild SQL query.
Views version: 7.x-3.3
exposed_filter_problems
Other 2 exposed to visitors filter have the same settings but different names.

After 4 hours of fight with exposed filter I found my problem. I used drupal administration in Opera. After moving to Chrome everything works great.


Why do I get this error when I save my custom field? I created a custom field and this is its formElement() method.

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $value = isset($items[$delta]->value) ? $items[$delta]->value : '';
  $client = \Drupal::httpClient();
  $request = $client->get('http://localhost:8083/regionilist');
  $response = json_decode($request->getBody());

  $element += [
    '#type' => 'select',
    '#title' => $this->t('Select element'),
    '#options' => $response,
    //'#options' => [
    //  'Abruzzo' => $this->t('Abruzzo label'),
    //  'Lazio' => $this->t('Lazio label'),
    //  'Sicilia' => $this->t('Sicilia label'),
    //],
    '#suffix' => '

',
    '#attributes' => ['class' => ['edit-custom-field-widget']],
    '#attached' => [
      'library' => [
        'custom_field/my_js_custom_field',
      ],
    ],
  ];

  return ['value' => $element];
}

The Rest service output is this.

{
  "Abruzzo": "Abruzzo label",
  "Lazio": "Lazio label"
}

The output of json_decode() is the following one.

array (
  'Abruzzo' => 'Abruzzo label',
  'Lazio' => 'Lazio label',
)

When I add the field to a content type I get the following error.

  TypeError: Argument 1 passed to Drupal\Core\Form\OptGroup::flattenOptions() must be of the type array, object given, called in C:\xampp\htdocs\drupal8DPC\core\lib\Drupal\Core\Form\FormValidator.php on line 340 in Drupal\Core\Form\OptGroup::flattenOptions() (line 23 of core\lib\Drupal\Core\Form\OptGroup.php).
  Drupal\Core\Form\OptGroup::flattenOptions(Object) (Line: 340)
  Drupal\Core\Form\FormValidator->performRequiredValidation(Array, Object) (Line: 247)
   Drupal\Core\Form\FormValidator->doValidateForm(Array, Object) (Line: 239)
   Drupal\Core\Form\FormValidator->doValidateForm(Array, Object) (Line: 239)
   Drupal\Core\Form\FormValidator->doValidateForm(Array, Object) (Line: 239)
   Drupal\Core\Form\FormValidator->doValidateForm(Array, Object) (Line: 239)
   Drupal\Core\Form\FormValidator->doValidateForm(Array, Object, 'field_config_edit_form') (Line: 119)
  Drupal\Core\Form\FormValidator->validateForm('field_config_edit_form', Array, Object) (Line: 571)
  Drupal\Core\Form\FormBuilder->processForm('field_config_edit_form', Array, Object) (Line: 314)
  Drupal\Core\Form\FormBuilder->buildForm('field_config_edit_form', Object) (Line: 74)
  Drupal\Core\Controller\FormController->getContentResult(Object, Object) call_user_func_array(Array, Array) (Line: 123)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 582)
  Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 151)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
  Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
  Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
  Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 38)
  Drupal\webprofiler\StackMiddleware\WebprofilerMiddleware->handle(Object, 1, 1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
  Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 664)
  Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Error does not occur when I use the fixed code (commented in the code above) instead of the REST service.

Use the Json class in core, it’s set up to use associative arrays (rather than the default object from json_decode, which is causing your current issue):

$decoded = \Drupal\Component\Serialization\Json::decode(...);


Access forbidden 403 to homepage but the rest of website working Drupal 7 I have Drupal 7 installed in localhost, with XAMPP, and it is a replica of a complete working site. I think I have configured everything ok as I can see all the site working nice, with its friendly urls, multilanguage, multidomain, dozens of modules. But still the home page is not rendered, with an Apache error of forbidden. When I try to put site_name/index.php, it gives a 404 error, and the same trick in remote works rendering homepage!!

Any idea or suggestion on what could be happening? Thanks.

For reasons of module SiteMap, I needed to have folders called en, es, fr, which coincides with the suffixes of the language switcher. This was causing some problem in XAMPP while not causing any problem in Linux version. I have renamed the folders and everything is ok now.

I suspect that having an URL as example.com/fr/ which renders the homepage in french is not a good idea if you have a directory, that, if Drupal were switched off, would point to a folder example.com/fr.


Block caching when access-restricted modules are enabled We have a module that creates a custom navigation block. It runs a metric ton of queries, and it's really affecting performance. (Note that I inherited this site; I did not write this code!)

We want to cache the block, but the built-in block caching (admin/settings/performance) is greyed-out, with a message below that says block caching is inactive when modules defining content access restrictions are enabled. We do have several modules that have access restrictions, and cannot disable those.

Is there any other way to cache the navigation block? I know about the BLOCK_CACHE_* constants, but am assuming that the built-in block caching needs to be turned on, and that those constants modify the default behavior. If we can't turn on the built-in caching, what (if anything) can we do?

Assuming that the module that creates the block and is this performance heavy is a custom module, a simple solution would be to cache the output of the block from within the block. Take a look at the cache_set and cache_get functions on http://api.drupal.org


Create a wrapper around specified number of fields in views I like to wrap 3 elements of a view in a div.
I got this code, but it doesn't seem to work. It keeps printing the div but never the /div which makes everything nested in the previous row.

<?php if($i % 3 == 0){ print '
'; } ?>
<?php print $row; ?>
<?php if($i % 3 == 2){ print '
'; } ?>

Any suggestions?

Semantic Views module will let you configure HTML output easily.


How to get webform to reply to sender? For some reason I'm stuck on this!

Is there a setting in webform so that I can simply click on reply when I receive and email from contact form?

Been out of the loop for a while for health reasons!

Set the from of the e-mail that is send to the e-mail that is used by the person submitting the webform. This is a token that you can use in the settings of your webform.


Pass a variable from a node to a block module that uses a custom template I have a custom module "jsblock." When the page renders, the module should get the title of the page, pass it to drupal_add_js() and ultimately render an output in a block.

I tested the module with the template name suggested by the system. The output rendered in the block as expected. Now, I'm trying to add a custom template to the module but the variable appears to no longer be passed to the block.

Directory structure

I have been playing around with hook_block_view() and a helper function to handle the drupal_add_js() function, but I think I am not attaching it to the block correctly.

jsblock.module file

// Helper

function get_the_page_title() {
  if ($node = menu_get_object('node')) {
    $title = drupal_get_title();
    drupal_add_js(array('jsblock' => array('test' => $title)), 'setting');
  }
}

// Theme
function jsblock_theme($existing, $type, $theme, $path){
  return array(
      'jsblock_custom_theme' => array(
          'variables' => array('content' => NULL),
          'template' => 'jsblock_custom_theme',
          'path' => drupal_get_path('module', 'jsblock') .'/theme/',
      )
  );
}

// Print
function jsblock_block_view($delta = 'jsblock') {
  if($delta == 'jsblock')
    {
      $block = array();
      $block['content'] = get_the_page_title();
      $block['content']['#attached']['css'][] = drupal_get_path("module", "jsblock")."/css/styles.css";
      $block['content'] = theme('jsblock_custom_theme');
      return $block;
  }
}

I checked the console for Drupal.settings.jsblock.test and it is returning the expected value. I can see the block is printing based on an expected outline, but the data is not rendered.

How can I pass the JS variable from the page to the block that uses a custom template?

When using a custom theme wrapper for your block output, you actually theme the content parts, before the block will be rendered using the actual block theme wrappers.

If you like to pass in variables to your custom template, you need to provide them via the second parameter of the theme() function:

/**
 * Implements hook_theme().
 */
function jsblock_theme($existing, $type, $theme, $path){
  return array(
    'jsblock_custom_theme' => array(
      'variables' => array('my_title' => NULL),
      'template' => 'jsblock_custom_theme',
      'path' => drupal_get_path('module', 'jsblock') .'/theme/',
    )
  );
}

/**
 * Implements hook_block_view().
 */
function jsblock_block_view($delta) {
  $block = array();

  if($delta == 'jsblock') {
    $variables = array();
    $variables['my_title'] = get_the_page_title();
    $block['content']['#markup'] = theme('jsblock_custom_theme', $variables);
    $block['content']['#attached']['css'][] = drupal_get_path('module', 'jsblock') . '/css/styles.css';
  }

  return $block;
}

Note the difference between the $variables and the $block array.

To also cover your second question (which surely should go into a separate question on Drupal Answers):

Keep in mind, that blocks are cached by default for performance reasons, until you clear the caches. So with your current implementation the block view will be generated only once and hence the JavaScript only attached to the first page you render after a cache clear.

Therefore you should attach your JS to the block output as you did with your CSS (attach it to the content part of the block output) and make sure to have a distinct cached version of the block for every page by using appropriate cache tags in your hook_block_info():

/**
 * Implements hook_block_info().
 */
function jsblock_block_info() {
  $blocks = array();

  $blocks['jsblock'] = array(
    'info' => t('My JS block'),
    // Use DRUPAL_NO_CACHE for no caching, or
    // DRUPAL_CACHE_PER_PAGE if you are fine with
    // cached versions per page.
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}


Drupal exposed filter theming Is there a way to show views exposed filter with in betweeen operator for integer type as a select list(0-10, 10-20, etc)?

You can alter your exposed form and print needle select list.
Than you hide your exposed filter with betweeen operator. E.g. display:none.
Than you write js that fills your hidden filter when user change select value.


I need a Drupal workflow solution where I can edit live/published nodes and save without the edits going live until commited I need a module or method that can allow a PUBLISHED node to be edited in the admin and saved without the changes being made live until it is committed.

Site Example: http://bit.ly/p70f7E

1. User with EDIT permission logs in and edits this page/node - They make a copy edit such as changing the title "Litman Gregory Launches Alternative Strategies Fund" to "Litman Gregory Has Launched the Alternative Strategies Fund" or some kind of edit.
2. The user cannot publish the change but can save the revision or checkout/checking the file.
3. User with PUBLISH permission logs in and checks the edits for accuracy and then hits publish.
4. The page/node never gets unpublished, but the edits are made in the back-end without updating the live copy.

Any ideas?

Try the Workbench module. If I'm not mistaken you can make draft versions of nodes that have been published.

From the module page:

  Workbench provides overall improvements for managing content that
  Drupal does not provide out of the box. Workbench gives us three
  important solutions:

  a unified and simplified user interface for users who ONLY have to
  work with content. This decreases training and support time. the
  ability to control who has access to edit any content based on an
  organization's structure not the web site structure a customizable
  editorial workflow that integrates with the access control feature
  described above or works independently on its own.


how to automatically retrieve selected value is there a way to automatically retrieve selected value from dropdown or radio to form below? example in the image below, if i select radio button "randy", then the value "randy" automatically fill in the form Nama below

$header1 = array('Name'); // Prepare table header
$query = db_select("homo", "r"); // Select table
$query->fields("r", array("nama")); // Select fields
$result = $query->execute(); // Execute query
$rows = array();
while($data = $result->fetchObject()){ // Looping for filling the table rows
$rows[] = array( // Fill the table rows
  $data->nama,
  );
}
$form['table'] = array (
 '#type' => 'tableselect',
 '#header' => $header1,
 '#options' => $rows,
 '#multiple' => FALSE,
);
$form['f1'] = array(
 '#title' => t('Detail Anggota'),
 '#type' => 'fieldset',
);
$form['f1']['namaa'] = array(
 '#title' => t('Nama'),
 '#type' => 'textfield',
 '#required' => TRUE,
);

You need to use Form API Ajax. There you can see how to use it, Examples for developers include good ajax forms too.

Just remember, to set value to display, use $form_state['input'], not $form_state['values'].


How to manage multiple drupal 7/8 sites with multiple drush versions We manage a bunch of Drupal 7 sites and a few Drupal 8 sites. I have been trying to workout the change to Drush 9 on the Drupal 8 sites and I have hit a roadblock.

For some reason when I try to use a local drush alias to contact the site it fails. If fails slightly differently for all the different contexts.

Locally, I have Drush 8.1.15 installed globally with composer, Drush 9.2.1 in my drupal site. I have a yaml alias and a php alias both local and remote.

On the dev server Drush 8.1.10 was installed with the phar download.

$ ./vendor/drush/drush/drush @project-client.dev st
Missing argument 2 for Drush\Sql\SqlBase::__construct() SqlBase.php:34                                                                            [warning]
#0  Drush\Drush::getContainer() called at [/mnt/www/project-client.dev.example.net/repo/vendor/drush/drush/src/Drush.php:193]
#1  Drush\Drush::service(config) called at [/mnt/www/project-client.dev.example.net/repo/vendor/drush/drush/src/Drush.php:238]
#2  Drush\Drush::config() called at [/mnt/www/project-client.dev.example.net/repo/vendor/drush/drush/src/Drush.php:274]
#3  Drush\Drush::simulate() called at [/mnt/www/project-client.dev.example.net/repo/vendor/drush/drush/src/Sql/SqlBase.php:221]
#4  Drush\Sql\SqlBase->query(SELECT 1;) called at [phar:///usr/local/bin/drush/includes/environment.inc:393]
#5  drush_valid_db_credentials() called at [phar:///usr/local/bin/drush/lib/Drush/Boot/DrupalBoot.php:462]
#6  Drush\Boot\DrupalBoot->bootstrap_drupal_database_validate() called at [phar:///usr/local/bin/drush/lib/Drush/Boot/DrupalBoot8.php:111]
#7  Drush\Boot\DrupalBoot8->bootstrap_drupal_database_validate() called at [phar:///usr/local/bin/drush/includes/bootstrap.inc:430]
#8  drush_bootstrap_validate(4) called at [phar:///usr/local/bin/drush/includes/bootstrap.inc:507]
#9  drush_bootstrap_max() called at [phar:///usr/local/bin/drush/includes/bootstrap.inc:456]
#10 drush_bootstrap_to_phase(-2) called at [phar:///usr/local/bin/drush/lib/Drush/Boot/BaseBoot.php:59]
#11 Drush\Boot\BaseBoot->bootstrap_and_dispatch() called at [phar:///usr/local/bin/drush/includes/preflight.inc:66]
#12 drush_main() called at [phar:///usr/local/bin/drush/includes/startup.inc:458]
#13 drush_run_main(, /, Phar detected. Proceeding to drush_main().) called at [phar:///usr/local/bin/drush/includes/startup.inc:365]
#14 drush_startup(Array ([0] => /usr/local/bin/drush,[1] => --alias-path=/Users/fanderson/.drush/sites,[2] => --root=/var/www/project-client.dev.example.net/current/web/public,[3] => --uri=project-client.dev.example.net,[4] => st)) called at [phar:///usr/local/bin/drush/drush:114]
#15 require(phar:///usr/local/bin/drush/drush) called at [/usr/local/bin/drush:10]
PHP Fatal error:  Declaration of Drush\Command\DrushInputAdapter::hasParameterOption() must be compatible with Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in phar:///usr/local/bin/drush/lib/Drush/Command/DrushInputAdapter.php on line 27
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Declaration of Drush\Command\DrushInputAdapter::hasParameterOption() must be compatible with
Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in
phar:///usr/local/bin/drush/lib/Drush/Command/DrushInputAdapter.php, line 27
Connection to project-client.dev.example.net closed.

It looks to me as though it is attempting to run the global drush. How do I stop that? There are Drupal 7 sites on this dev server as well.

I assume the command above is run locally and it connects to the dev server? On the dev server you have the phar-installed global Drush 8 and the site-local Drush 9. From the debug backtrace you see that it starts with launching the global Drush 8 and then at the end it uses some functions from the site-local Drush since those are included when Drupal 8 bootstraps. Not strange that it doesn't work. And to make it even worse the: The phar-installed global Drush is too old - Drush 8.14 is clearly needed.

It might work to upgrade the phar-installed Drush 8 to 8.15, but why not use Drush Launcher (which is recommended) and install in globally instead of Drush. It even supports a fallback to a globally installed Drush of your liking.


How can I set up an a SQLite memory database to improve PHPUnit test speeds? I'm trying to speed up a functional Drupal test.
Given a test...
...
  public function the_front_page_loads_for_anonymous_users() {
    $this->config('system.site')
      ->set('page.front', '/node')
      ->save(TRUE);

    $this->drupalGet('<front>');

    $assert = $this->assertSession();
    $assert->pageTextContains('Welcome to Drupal');
    $assert->pageTextContains('No front page content has been created yet.');
  }

This test runs really slow against my database ... 2+ mins.
If I use a test sqlite database, it drops to around 1.6 mins
<env name="SIMPLETEST_DB" value="sqlite://localhost/logs/test.sqlite"/>
If I use a in-memory database, <env name="SIMPLETEST_DB" value="sqlite://localhost/:memory:"/>, Drupal detects no database and runs install.php
How can I set up an sqlite memory database to improve test speeds?

On Linux, we use sqlite://localhost/dev/shm/test.sqlite where /dev/shm is memory mapped


How to remove ":" (colon) when displaying field name? I created a custom content type with some text fields. In the view settings of that content type I defined both to appear and as well their titles (names of the fields) to be displayed above the content of the fields respectively.

But how can I remove the trailing colon of the titles? Is there a way of modifying the way field names are display just for certain content types? I do not want this altered site wide (e.g. for all fields of all content types).

PS: I'm already using the "views" module to define a special layout for this custom content type. Probably there is a way to carry out these changes with the help of the "views" module and a custom layout template?

/edit/
I did not create a view (as with the "views" module) to display that content but used Drupal's own content type view configuration (maybe called "display"). I'm working with a localized Drupal and retranslating the different words.

Remark: Using Drupal 7.10 with Views 7.x-3.0-rc3

Note: The OP is not talking about Views. (In Views you can uncheck a box that says Place a colon after the label).

The accepted Drupal method is by copying the core field.tpl.php file into your theme directory and manually removing the colon from the file.

modules/field/theme/field.tpl.php
sites/all/themes/[mytheme]/field.tpl.php

In Drupal 7 this is on line 55:

from:

<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

to:

<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>&nbsp;

In order to do this in a specific content type you first copy field.tpl.php to your theme, then duplicate it, adding the machine name of your content type, and remove the colon from the content type specific version.

sites/all/themes/[mytheme]/field.tpl.php
sites/all/themes/[mytheme]/field--[content-type].tpl.php

Note: the double hyphen (--) is not a typ-oh.

Read up on theme suggestions for more. Using suggestions you can target just a specific field in this content type, just the field globally, all fields in the content type, or all fields in all content types. Or handle every combination differently.


Drupal 8 upload and embed a video to WYSIWYG So what I am searching for is a module that gives us the exactly same functionality that we already have with the image tool in Drupal 8 in the WYSIWYG editor.
And that should be working with just uploaded videos.
I found that this module should be doing it for D7 - https://www.drupal.org/project/video

And also this module https://www.drupal.org/project/video_embed_field is doing it for D8, but only for videos from per say YouTube, Vimeo etc.

So please let me know if you found a way to add a similar to the image (see  attached screenshot) but for video

Cheers and thanks in advance!

For simple solution Just get video_embed_field which includes module  Video Embed WYSIWYG Enable both of them. You will get options to configure your WYSIWYG here admin/config/content/formats/manage/full_html. Just add the Video button in toolbar and checked the option Video Embed WYSIWYG. I hope you get what you want.
Thanks


create date type in install profile I want the german date format in my install profile.

I tried in my setup script:

drush en l10n_update -y
drush vset site_default_country de
drush language-add de
drush language-default de
drush vset date_format_short "d.m.Y"

but it is not sufficient. It would not show up in the UI->configuration.regionalsettings as custom date format

manually I have to create a custom date format ("d.m.Y") first and then I can set is as wanted "date type",

I would do it via drush php-eval or better in profile-install function

update: clarified a bit

update2 meanhile I discovered hook_date_format_types :-)  trying...

If you want to use a custom date format, you should write this as a record in the database. In your profile-install function, you can use following code to accomplish this:

system_date_format_save(array(
    'format' => 'd.m.Y',
    'type' => 'custom',
    'locked' => 0,
    'is_new' => true,
));


Set a different home page for each role? The Front Page module only appears to work with anon\auth users and I need it for other roles. Any ideas on how to accomplish this?

I haven't tried this exact scenario, but I just did a quick check user roles and permissions are options in the selection rule when making pages with the Panels module.


Rule to send an e-mail with the URL of an uploaded attachment after node change I have a Drupal 7 site with a custom node type with a custom attachment field. After a (kind of this custom) node has been published, I got an e-mail with the help of Rules module. I would like to set up an another rule, which sends me an another e-mail, when somebody edits this node and uploads an attachment. Inside the mail, I want to see the full url to the uploaded file.

After a several test, I'm not able to insert the full path to the uploaded file. The [node:field-attachment:file] doesn't work at all. I'm able to insert (manually) the url where this file resides, but after I can not insert the file name (so even the filename would be enough for me).

So with the [node:field-attachment:file] I got an error: *Fatal error: Call to a member function value() on a non-object in /home/xxx/sites/all/modules/entity/entity_token.tokens.inc on line 297.*

Which is exactly this:

/**
 * Gets the token replacement by correctly obeying the options.
 */
function _entity_token_get_token($wrapper, $options) {

   if ($wrapper->value() === NULL) {
// Do not provide a replacement if there is no value.
return NULL;
}

With the [node:field-attachment], I'm getting the e-mail, but it contains this: You can download the file from here: Property 0

Which token should I use to get the url (or the filename) of the actually uploaded file when I edit the node?

You can use these to get file name and file url respectively (Drupal 7.67 Entity API 1.9):

[node:field-document:0:file]
[node:field-document:0:file:url]


How to emulate all the AJAX functionality when the form is rendered after an AJAX callback? I have a Drupal form, but I am adding it to the page as the result of an AJAX callback.

I need this form to trigger a new callback. My code below:

      $form['#suffix'] = '
this is the return box
';
  $form['#attached']['js'] = array('misc/ajax.js');

  $form['markup'] = array(
    '#type' => 'markup',
    '#markup' => '
This is a form
'
  );

  $form['button'] = array(
    '#type' => 'button',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'module_myform_callback',
      'wrapper' => 'form-return-message-box',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $replace_layer = '#somelayer';

  $commands = array();
  $commands[] = ajax_command_replace($replace_layer, drupal_render($form));
  $page = array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );

  ajax_deliver($page);

So this is what happens: this form is being added into a container called 'somelayer' that already exists on the page (I didn't add that part of the code because I thought it would be unnecessary). It was called from a link with the class 'use-ajax'.

So the form renders on the page as desired after an AJAX callback triggered by the link.  This part works allright.

But here is the (very) tricky part: I would also like to preserve the new form AJAX functionality (check the '#ajax' part of the array), which doesn't occur. After the form is rendered, the button won't trigger any AJAX code. By clicking on it, the page will refresh, not triggering the callback function (not added here to preserve space).

By looking into source code of a regular form page with AJAX, you will see code like this that enables the AJAX functionality:

"ajax":{"edit-something":{"callback":"module_formname_callback","wrapper":"wrapper-name","method":"replaceWith","effect":"fade","event":"change","url":"\/spabear\/system\/ajax" ...

By looking at the source code of the form added into my page, I can see there is no piece of  code that would trigger the AJAX callback in my dynamically loaded form. How can I emulate all the AJAX functionality when the form is rendered after an AJAX callback?

The #ajax['wrapper'] property includes the HTML ID of a page section that should be replaced (or altered in some other way).
The #ajax['callback'] tells the Form system what callback should be called after the Ajax call happens and the form is rebuilt.

https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7


Fuzzy Search in Drupal 7 gives no results I have setup Fuzzy Search in our website to provide 'intelligent' search functionality. I believe that the setup is all proper but despite the fact, I always get back 0 results. This is my search page for Fuzzy Search:

http://indiansnakes.org/search-fuzzy

I have exposed "Fulltext search" and I have indexed few key fields of the snake nodes from the website which has to be searched upon (like Common name, scientific name, snake description etc.)

I have setup Search Server for Fuzzy search as shown below:

Minimum word length = 3.

I would also like to know if there is a way to provide a dedicated database for Search server and it's indexed data?

Next, I have setup Fuzzy Search index which shows that the items have been indexed and it looks like this:

I have setup the Views for Fuzzy Search page like this:

Despite all this, my Fuzzy Search does not give back any results. Any idea what might be going wrong here?

In the Fuzzy Search index, make sure the Fuzzy Search processors are enabled, and that they are processed last. The Fuzzy Search except processor should be last, with the settings processor immediately before it. You may need to enable the Tokenizer processor as well, and that should be before the Fuzzy processors.

Reindex after saving the changes.


Different Theme for Current URL - Using Javascript? I know that you can have different themes for different parts of the site, assigning specific URLs to different themes by using hook_custom_theme() or the themekey module - I've used both solutions to do this at one time or another.

However, is there a way to modify/update what theme is being used on the current page by using Javascript?

I'm asking because I want to A/B test an upcoming UI fix. In my test, 50% of visitors in the control group would see "old pages using theme A" (without fix) and the other 50% would see "new pages with theme B" (with fix). Then I can see whether the fix improves performance/conversion and by how much.

The thing is the testing tool I use needs to have a way to change the theme for that latter group only. That tool (Optimizely) doesn't have access to the PHP hooks and functions, but it can alter the on-page JS code for the control/treatment groups.

Any advice would be much appreciated. If this is a bit confusing, I can clarify any questions ...

You couldn't select a Drupal theme through JS, unless you reloaded the entire page using JS after the initial load.

The better way to do this would be to use hook_custom_theme() to set the theme. Since you need to track the theme with Optimizely, you can send a JS variable from PHP and then pass that to Optimizely in order to track which theme is being viewed.

You could do this in hook_custom_theme() to have 50% of the users use one theme, 50% use the other:

function hook_custom_theme()
{
  $theme = variable_get('switch_custom_theme', 'theme_1');
  $new_theme = $theme == 'theme_1' ? 'theme_2' : 'theme_1';
  variable_set('switch_custom_theme', $new_theme);
  return $new_theme;
}

Then you can get the theme in JS at Drupal.settings.ajaxPageState.theme (Drupal 7). I can't help you with the Optimizely side of things as I don't use it, you'd have to look at their documentation.


How to remove a taxonomy term with an empty required field without having to fill it? I'm having a problem while trying to delete a taxonomy term that has an empty required field. To proceed and delete it, I have to fill the empty field to be able to delete it.

How can I remove the taxonomy term without having to fill the empty required field?

For me there is no problem by adding a letter to the field and then delete the taxonomy, but my client is getting crazy with this issue and he is getting me crazy.

Any solution?

Thank you in advance.

I usually write out code when I need to bypass validation for deletion. You can use taxonomy_term_delete to remove the items and bypass validation:

$tids = array(); //Add your term ids that you need deleted in the array
foreach($tids as $tid) {
  taxonomy_term_delete($tid);
}


Open jump menu selection in new window I have a views jump-menu of PDFs. I'd like the PDF to open in a new window when the user clicks the "go" button on the view.

I've tried using javascript to set the form's target attribute to _blank. It is showing in the markup, but it has no effect on the behavior of the form submission.

Any ideas on how to do this?

The only way I've found to do this so far is to alter the ctools jumpMenu behaviour with the following JS. This is probably a lot more code than I need, but it seems to do the job. Better answers are appreciated.

JS

// place this outside your .ready() function
Drupal.behaviors.CToolsJumpMenu = {
   attach: function(context) {
     $('.ctools-jump-menu-hide:not(.ctools-jump-menu-processed)')
       .addClass('ctools-jump-menu-processed')
       .hide();

     $('.ctools-jump-menu-change:not(.ctools-jump-menu-processed)')
       .addClass('ctools-jump-menu-processed')
       .change(function() {
         var loc = $(this).val();
         if (loc) {
           location.href = loc;
         }
         return false;
       });

     $('.ctools-jump-menu-button:not(.ctools-jump-menu-processed)')
       .addClass('ctools-jump-menu-processed')
       .click(function() {
         // Instead of submitting the form, just perform the redirect.

         // Find our sibling value.
         var $select = $(this).parents('form').find('.ctools-jump-menu-select');
         var loc = $select.val();
         if (loc) {
          // console.log(loc.slice(loc.indexOf('::') +2) );
           // location.href = loc.slice(loc.indexOf('::') +2);
           window.open(loc));
         }
         return false;
       });
   }
 }

Source


Add config forms to existing admin page Instead of creating a new route and menu:

  amustatuscode.config:
  path: '/admin/config/statuscode/config'
  defaults:
    _form: '\Drupal\amu_http_status_code_display\Form\AmuHttpStatusCodeDisplayConfigForm'
    _title: 'HTTP status code error messages'
  requirements:
    _permission: 'administer http status code'

amustatuscode.config:
  title: 'AMU HTTP status code'
  description: 'Customize HTTP status code error messages'
  parent: system.admin_config
  route_name: amustatuscode.config
  weight: 100

How can I add this form to the existing basic site settings?

  /admin/config/system/site-information

You could extend the default form by using a Route subscriber.
To do so, create a file named RouteSubscriber.php whithin your module in a src/Routing folder.

the file should look like this:

<?php
namespace Drupal\YOUR_MODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.site_information_settings'))
      $route->setDefault('_form', 'Drupal\YOUR_MODULE\Form\ExtendedSiteInformationForm');
  }

}

You should then create a ExtendedSiteInformationForm.php file within your module src/Form folder like that:

<?php

namespace Drupal\YOUR_MODULE\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\system\Form\SiteInformationForm;

class ExtendedSiteInformationForm extends SiteInformationForm {

   /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
   $form=  parent::buildForm($form, $form_state);
   //update your $form...
   return $form;
}
}

This way you won't need your routing.yml file anymore.


How add Placeholder to login form I need to add Placeholder property to Drupal 7 login form from template.php. Not to use a module. and also want to know how to add other attributes like Required etc.

I think it cannot be done unless using the module. You can try like this

1) Adding the hook_form_FORM_ID_alter in the module to add placeholders, required and some other form attributes.

2) In the template file you can call that form using drupal_get_form('form-id', args1, args2, etc..)

3) Finally, pass the form to the tpl file.

Example:

1) In .module

function yourModule_form_user_login_alter(&$form, $form_state) {
  $form['name']['#attributes'] = array(
    'placeholder' => array (
       t('Username')
     )
  );
  $form['name']['#required'] = TRUE;
  /* Add other attributes like this*/
}

2) In template.php

$variables['login_form'] = drupal_get_form('user_login');

3) In .tpl.php

<?php print render($login_form); ?>

I hope this will work !!


Where are the Page Manager "Caching options"? In D7 I'm using Ctools, Panels (3), Views, Page Manager etc., but in Page Manager when gear-icon-clicking the content panes I don't find any "Caching options" as I have seen described. What reasons can there be for this.
It's probably something really simple, I just can't find it...

Although the language is german in this screenshot, location of the menu/options should be the same.


Is drupal able to handle technical data sheets? I already posted a similar question on webapps.stackexchange.com and was redirected here, since I mentioned Drupal. Here is the slightly updated question:

I am a php developer and didn't have the chance to work with a CMS for ages, and I couldn't find any decent solution for my problems throughout my internet searches.

For a new project I am working on, I need to provide an application which can allow a few users to create and handle numerous technical datasheets (around 1-2k). The application should be able to handle a few different kind of sheets, whose structure and contents are known and static: few lines of text, some geographical data, numeric coefficients and pictures. It should also be possible to attach files to one sheet (let's say a .zip, a .doc, or whatever).

Users should be able to:

Create and edit sheets.
Search through them
Export them to various formats (pdf, doc, xls, etc.)

Administrators should be able to:

Create and manage users.
Create new types of datasheet.

One important feature is the non-concurrent editing (i.e. a sheet should be locked if someone is editing it).

At first glance, I was willing to create all that from scratch, with my little hands and a decent php framework. But then I started to think (it happens...), and was wondering if a CMS wouldn't to the trick, since this is what I'm searching for: a (specific) content management system.

I had some little experience with drupal, which allowed to create custom nodes. Wouldn't that answer my problems? A node would then be a specific type of datasheet. The different possible actions of users and administrators (create, update, search, export, etc.) being handled by drupal core functionalities. Am I right?

If so, is there any specific module I should look into?

Thanks in advance for your help!

According to me you have half answered your question, yes node is what your data holder for the datasheets.
consider nodes as container for your data so to change the way you to present them you can use views module.views module will allow you to present your nodes the way you like also you have option to export your views in different formats.

Here are some modules which can be helpful for exporting your views in different formats

Views PDF
Views data export
Views Excel Export

Update:

For content locking for concurrent content edit
 you can  check Content locking (anti-concurrent editing) contributed module.

Update:

About having different types of datasheets,

If you are looking are categorizing your nodes/sheets, core shipped taxonomy is there.
If you need to have separate types of sheets in structure, permissions to create/edit/view them, having separate content types will be the solution.


How to configure wysiwyg_tools_plus module? Has anyone used this module (wysiwyg_tools_plus)?  It give ckeditor the ability to create tabs & accordion effects via a wysiwyg (sample video).  The docs on usage look good, but I'm having a hell of a time figuring out how to actually get the icons to show up in ckeditor.

I've done this:

installed ckeditor module & verified usage
installed/enabled wysiwyg_tools_plus
set ckeditor as the editor for my text formats
tried to edit profiles (/admin/config/content/wysiwyg/profile/full_html/edit), but haven't found a way to add the Tab or Accordion buttons

Any idea what I need to configure?

There's two ways of running CKEditor in Drupal, as a straight module install, and as a component of the WYSIWYG Tools module. It's the latter that you need.

So, install the normal WYSIWYG Tools module and then follow the instructions to install an editor (CKEditor) within. I've found only < v4 seems to work for this unfortunately, but there is an update to v3 from 2013 which seems to work ok.

Once you've got that working you will get a WYSIWYG editor that has no buttons, it's not broken, it just doesn't tell you that you have to configure it for each view (full HTML / filtered HTML etc) and select the buttons you want to appear.

When choosing the buttons, near the bottom there's a few for accordion & tabs, so just make sure these are selected for the content types you want to use.

It's not exactly intuitive, but it's actually fairly easy when you know how!

Hope that helps.


Drupal Bulk Update Nodes using button I have view that displays a table of node for the current user.

I am confused as to how i can provide the functionality to bulk update certain values.

For example:

I have table of nodes (custom content type=List) and that content type has a custom field called list_status.

I want to update the value of the list_status for all the selected nodes.

I looked at VBO (Views Bulk Operation) to do this, i managed to do it with "Modify Entity Value" setting but the UI/UX i get with this is not what i desire. It takes me to a new page to select the value.

What i need to do is is run this action on a button click. I would really appreciate if some one can please help me figure this out?

I felt, i would only be able to accomplish this by doing something custom with my own module but if i am right, then a starting point for this would also be just as much appreciated.

I seem to have solved my issue, i will try to elaborate for future reference and also for any one who may need this.

First, it seems i missed the "Bulk operations settings" section as it was collapsed by default. But one of the options under it is "Display operations as" which provides two choices (1) Dropdown selectbox with Submit button and (2) Each action as a separate button

The second option was what i needed to get the buttons i wanted.

Then for bulk updating a custom field of my content type, i added hook_action_info() into my custom module and created a custom action that would become visible where the "Modify Entity Value" option was.


Can a Calendar, based on two different content types, output different html based on content type I built a calendar based on two different content type, let's call them A and B. For each type I output the Title field and, along with it, I'd like to have a link to the node if the Title field belongs to type A and just plain text if it belongs to type B. Is there a way to do this?

You could use the Views PHP module.

Then add the content type to the view. You can exclude both content type and title from the the view only display the title through the Global PHP field. With in that you can place a condition to display the complete link if it is of Type A and only the Title if it is of Type B. You could also add the path to the node as a views fields if you prefer so that it can be used in the as href for the link in php field.


How to display the calculated priced of commerce products? I have some product pricing rules that adjust the price a customer will pay.  How can I display this adjusted/calculated price to the customer?  I want to display the calculated price like a field the way the base price is displayed.

Is there a field display setting (for example at /admin/structure/types/manage/product/display) that will do this?
Does it have to be done through rules (if so what event and actions should be used)?

When a price field is rendered using the "Formatted price" display formatter, it has a setting for you to choose between displaying the original price as loaded or the calculated sell price for the current user. That second one is the default, so as long as you are using product pricing rules properly (as indicated in the comments), this should just work for you.

If for some reason it isn't you'll need to find and review your display settings for the price field on your various product types. Because the price field that appears on a product display comes from the product entity directly, you have to adjust its field display settings there instead of on the relevant node type. You should find them under Administration > Store > Products > Product types. Click the manage display link beside your product type and see what it says.

If you get stuck, feel free to join us in the #commerce channel in the Drupal Slack!


Custom content entity field widget. This value should not be null I've created a custom content entity in Drupal 8 and all is well in those regards. I have an issue when I go to create a new record for my entity using the entity form. "This value should not be null.".

The error comes from a widget plugin that I've created that only replicates the functionality of a list of checkboxes that represent taxonomy terms. The field that uses this widget is not a base field, it's added through the UI.
I've looked at the plugin documentation on drupal.org and haven't found much help in regards to my issue.

Below, is my code for the widget form element.

namespace Drupal\my_entity\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\taxonomy\Entity\Term;
use Drupal\user\Entity\User;

/**
 * A widget for displaying terms and supplying an AJAX request when a checkbox is clicked
 *
 * @FieldWidget(
 *   id = "my_entity_programme_areas_lookup_directors",
 *   module = "my_entity",
 *   label = @Translation("Programme Areas Lookup Directors Widget"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class ProgrammeAreasLookupDirectorsWidget extends OptionsWidgetBase
{

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : NULL;

    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element += [
      '#type'          => 'checkboxes',
      '#default_value' => $this->getSelectedOptions($items),
      '#options'       => $this->getOptions($items->getEntity()),
      '#multiple'      => TRUE,
      '#element_validate' => [
        [static::class, 'validate'],
      ],
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    unset($element['#options']['_none']);
    return ['value' => $element];
  }

  /**
    * @inheritdoc
    */
  public static function validate($element, FormStateInterface $form_state) {

    $value = $element['#value'];
    return true;
  }

For the moment, I just want it to pass validation so then I can work on from there, but right now, it can't seem to retrieve a value, even though I can see it has the expected values in the $form_state object (field_programme_areas field).

Any help and tips would be greatly appreciated.
Thanks!

I managed to get it working by extending the OptionsButtonsWidget class instead of OptionsWidgetBase. I've also added the multiple_values annotation which I was missing and also removed the validation callback I was supplying, so now the validateElement method from OptionsWidgetBase is the validation handler used. My widget class just extends OptionsButtonsWidget and works fine. I think the missing annotation was the main reason it wouldn't validate.


How to get a list of all displays of every view? I'm doing some test and I'm trying to get a list of all the displays of every view to do the test things in every display of every view, but I don't have any idea how to do it.
When using views_get_all_views() I only get the first display of every view, but what I want is every view and everything inside that view.

Please find the following drush one-liner to list all the views including all display names:

drush eval 'foreach (views_get_all_views() as $view) { foreach ($view->display as $display => $data) { print "$view->name: $display\n"; }; }'

Modify the code as required.


Couldn't get setErrorByName to apply error class I have created a form following structure:

my_module
    |__
       src
         |__Form
                |__myform.php

I want to get the form_state in some() function in controller located at:

my_module
    |__
       src
         |__Controller
                     |__mycontroller.php

So that I can set error on one of my form element (say) - upload_container. And I will call function some():

static function some() {
$form_state->setErrorByName('upload_container', 'throw error while validating form');
}

here shown below as (in myform.php):

public function validateForm(array &$form, FormStateInterface $form_state) {
   mycontroller::some();
}

In D7, we do the same thing in a separate file example: common.inc

static function some() {
    form_set_error('upload_container', 'throw error while validating form');
    }

But in D8, How to set error on a form element via function located somewhere in controller file? I can't even get form_state in any third function which is located at controller.

Setting errors outside of validation isn't supported any more. From a related change record:

  In Drupal 7, form validation functions could use either form_set_error() or form_error() to set errors for an element, and form_get_errors() to retrieve the errors for a given form.
  These were global functions, which just set or retrieved errors from the current form being processed. This worked fine for form validation functions, but could produce unexpected results when called from non-form functions (like a theme function).

  In order to ensure that errors are associated with the correct form, you must now call the form error functions on $form_state.

Even if you got a reference to the form state in your controller, setting errors on it wouldn't do anything as the form wouldn't be validating (see this change record)

The best alternative is probably to use hook_form_alter and a validation method to the form which contains your logic.


How to override default meta tags? The meta tags module sets default meta tags that are rendering. However, I have a page with a panel and I am trying to override the default meta tags. I went into the panel and replaced the default meta tag tokens with custom text, but nothing changes. Any thoughts on why this might be happening? I'm using Drupal 7, and I'm hoping that we can do this through the admin UI.

In Drupal 8, there is a [module-name].module file inside your module. You can use "Hook attachments alter".

Code to alter your meta tags -

// For adding description in meta tag .

function hook_page_attachments_alter(array &$attachments) {
   $attachments['#attached']['html_head'][] = array(
        array(
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'description',
            'content' => 'Any thing in meta description',
          ),
        ),
        'description',
      );

// For adding title in meta tag.

$attachments['#attached']['html_head'][] = array(
        array(
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'title',
            'content' => 'Any thing in meta title you want',
          ),
        ),
        'title',
      );

// For adding noindex in meta tag-robots .

$attachments['#attached']['html_head'][] = array(
        array(
          '#tag' => 'meta',
          '#attributes' => array(
            'rel' => 'robots',
            'href' => 'noindex',
          ),
        ),
        'noindex',
      );

You can add more meta tags for different pages and can validate them too.


Create a View that redirects to node content based on contextual filter? I've created a view with a contextual filter for 'field_object_id' -> this is a field that the content type has which is unique but it's not the Node ID, these field_object_id's are brought in from a JSON feed.

So I can go to my view page like this:

drupal-site.com/my-view

Which would display a page not found. Then going to:

drupal-site.com/my-view/230

Would load up the content node that has '230' set for 'field_object_id' -> however that content node ID is not 230, I have no idea what it is. It could be 8509.

What I need to do, is set my view to automatically redirect the page to the node that it finds (I would set it to redirect to the first result it finds).

I have Panels installed too, would this be easier to do with Panels or should I look to creating a module?

One way I think of is to to this in a custom menu callback. So you could have an URL /mycallback/[OBJECT_ID] which would redirect to the first node that has the given [OBJECT_ID].

Something like this:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['mycallback/%'] = array(
    'page callback' => 'fieldvalue_redirect_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Custom callback given a object id.
 */
function fieldvalue_redirect_callback($id) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_object_id', 'value', $id, '=')
  ->addMetaData('account', user_load(1));
  $result = $query->execute();

  if (isset($result['node'])) {
    drupal_goto(url('node/' . key($result['node'])));
  } else {
    drupal_set_message(t('Page not found'), 'error');
    drupal_goto('<front>');
  }
}

First comes the definition of the menu callback, MYMODULE_menu().

The argument after mycallback/ is being passed on the the page callback function by defining it here 'page arguments' => array(1),.

fieldvalue_redirect_callback() will get the id entered by the user after /mycallback as argument. In the function we use EntityFieldQuery to fetch the node that matches the given ID.

And last we redirect if we get a result, otherwise we show an error message and the front page.

Hope this can help you or someone else.


Remove Parent Theme Settings From Child Theme I'm in the middle of creating a custom theme using the Bootstrap theme as it's parent. As you may, or may not be aware, the Bootstrap theme comes with lots of useful theme settings. These are great, but as this custom theme will be used for a client, most of these settings could be dangerous for them to be able to change.

I'd like to remove all of these theme settings, so only the ones I add in my custom theme will appear.

I know these theme settings would still be available to change in the Bootstrap theme, but that's not a problem.

Thanks

This definitely isn't the nicest solution, but it does work. If you find a better one, do post it here.

function THEMENAME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
  unset($form['global']);
  unset($form['bootstrap']);
  unset($form['general']);
  unset($form['theme_settings']);
  unset($form['logo']);
  unset($form['favicon']);
  unset($form['components']);
  unset($form['update']);
  unset($form['javascript']);
  unset($form['advanced']);
}


Can filter by file upload description but not sort by it? I have a simple page/content type where a user can upload files and give them a description.

I then hide that field on the page and display the files using a view in a block.

I can get it to show the files no problem and display them with a custom output, however I just can't seem to be able to sort by the text description, rather than the filename - the field just isn't there to sort by.

The description field does however show up in Filter Criteria where I've exposed it to allow users to search for files using the file description rather than the file name.

I'm not really sure how/where to look as I've tried all sorts of combos of the fields I have and none of them seem to be what I need.

Any help appreciated!

to sort by a field you should have that field in the result of view, in your example you can sort by the field "Resource Upload" because it figure in FIELDS section.. so to sort by "Description" field you have to add it first to FIELDS section and you can hide it later.


Is it possible to POST more than one article at once? How do I POST two or more articles at once?

Something like follows:

{
"_links":{ "type":{ "href":"http://drupal8/rest/type/node/article" } },
"title":[{"value":"Title 1"} ],
"title":[{"value":"Title 2"} ]
}
Result: Status Code: 400 Bad Request "Syntax error"

It is even possible for a single request to add more than one article?

As far as I know there is now way to create multiple nodes in one request. You can send multiple requests instead.

The JSON format need not to to be that much complex(as you mentioned in your POST).

You can use the following JSON format to create a node.

  URL : http://www.example.com/d8/entity/node

  Method: POST

  Headers:

  Name: X-CSRF-Token

  Value: TPlhcaO_KESksKPye805T86j0-ja9rhyfaaqi6zpA8

You can get user session token by requesting the following URL

URL: http://www.exmaple.com/rest/session/token

JSON format to create a node  (Article) for D8

{
  "type":[{"target_id":"article"}],
  "title":[{"value":"Hi World"}],
}

I've tested this on my D8 instance. It's working fine. Hope it helps


How to setup a rule to redirect to shopping cart? I am trying to create a rule that after a user creates an account they are sent to a Checkout page that will eventually have them pay via PayPal ( I am using the Commerce Module ).

My steps so far have
1.  Created an event "After saving a new user account"
2.  Leave Condition blank.
3.  Select Action of Complete Checkout For an Order

At step three it asks for a Data Selector: "Select data of the type Commerce Order." and I have no idea where to go from here.

I think you're probably missing a step, if I was integrating this I would create a product called Subscription (or something similar)

Your rule actions should be something like:

Add product Subscription to cart
Go to checkout


Views show weird SQL query I am using Views to display some comment for specify node.

The SQL query on Views pane:

SELECT comment.uid AS comment_uid, comment.cid AS cid, comment.created AS comment_created, 'comment' AS field_data_comment_body_comment_entity_type
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
WHERE (( (node_comment.nid = '1330' ) )AND(( (comment.status <> '0') AND (node_comment.status = '1') )))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0

I try to copy above sql to phpmyadmin:

SELECT comment.uid AS comment_uid, comment.cid AS cid, comment.created AS comment_created, 'comment' AS field_data_comment_body_comment_entity_type
FROM
comment
INNER JOIN node_comment ON comment.nid = node_comment.nid
WHERE (( (node_comment.nid = '1330' ) )AND(( (comment.status <> '0') AND (node_comment.status = '1') )))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0

But phpmyadmin throw an error to me:

Error Code: 1146. Table 'daxuebao.node_comment' doesn't exist

I try to search drupal node_comment table at google, But I get nothing.

There is no table named node_comment. You must do the inner join to the node table, in the same way as the Views query.

SELECT comment.uid AS comment_uid, comment.cid AS cid, comment.created AS comment_created, 'comment' AS field_data_comment_body_comment_entity_type
FROM
comment
INNER JOIN node node_comment ON comment.nid = node_comment.nid
WHERE (( (node_comment.nid = '1330' ) )AND(( (comment.status <> '0') AND (node_comment.status = '1') )))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0


How to add tags to my sandbox module? I 'm working on a sandbox module, which is text_or_user_reference field.

To release the module, I have to create a branch of the module i.e 7.x-1.0

Since beginning of the module development I was not aware with this thing, so I was working on master branch.

Now I have to add the tags to create the branch. To create the tags I followed this guide on drupal.org

These are the commands to push and create the tags:

  git tag 7.x-1.0

  git push --tags

  git push origin tag 7.x-1.0

I have applied all the commands, but I am not able to see whether tags are created or not.

My problems:

How to check whether tags are created or not ?
Do I have to seperately assign to tags to each file like .module file, .install file etc.
When I go to Edit of the project and select the dropdown version to work from it doesn't show the tags/version I created i.e. 7.x-1.0

Consider this command:

  git branch -v

What should I expect as a result after I run it? The list of all the files of current branch?

In git, the terms "branch" and "tag" always applies to the whole repository, not to the individual files.  A branch denote is a series of commits (so you always use an "x" instead of specific version number for a branch). A tag is a label for a specific version, so you specify the version number (e.g. 1.0 for the first released version, 1.1 for the next, and so on.)

The command git branch -v will give a verbose listing of the current head.  It should, in the case of Drupal 7, start with a line * 7.x-1.x.  If it says master on the first line, you've not set things up right.

Before adding tags, you need to get your project on a 7.x-1.x branch.  In your local repository, do the following to checkout branch 7.x-1.x and delete branch master, and push those changes to the remote:

git checkout -b 7.x-1.x
git branch -d master
git branch -v
git push origin 7.x-1.x
git push origin :master

After you've made sure the branch is 7.x-1.x, you can go ahead and add a tag to your release.

You can use the commands you refer to, to tag.  To see all the tag(s) in the local repository:

git tag

After pushing to the remote, if you've done this correctly, you should be able to click on the Version control tab and find the 7.x-1-x branch in the Version to work from: pull-down menu.  If you retain the master branch, make sure that you make the 7.x-1.x branch the default.


Batch redirect to http instead of https i'm working on a project and all batch callbacks in http not https so instead of redirecting to https://example.com/batch?id=844&op=start redirect to http://example.com/batch?id=844&op=start, and as result query params get lost and redirect me after to https://example.com/batch which gives me a 403 forbidden page:

i have checked htaccess file and also the server i don't have any redirection.
anyone has experienced this, any help ?
EDIT:
I have checked the result of \Drupal\Core\Url::fromRoute('<front>')->setAbsolute()->toString() i get the url correct with the right protocol and also i have added:
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = array($_SERVER['REMOTE_ADDR']);

to my settings.php and again no luck.
Note: all redirections in the site works perfectly with https only this one!

For debugging try to output the result of:
\Drupal\Core\Url::fromRoute('<front>')->setAbsolute()->toString()

Is this the wrong protocol, too? Then your browser terminates with a different protocol than the CDN to your web server.
Symfony is able to detect the correct protocol, but you need to configure the CDN (reverse proxy) in settings.php.


Assign different weights for different displays I am already guessing the answer is that it can't be done but any input on this would be much appreciated.

So I have my Content Type, say... Cakes! Now, I have a view named ALL Cakes! and they are sorted alphabetically on that.

I also have a view called Popular Cakes. Those can be sorted by weight and the awesome weight changer view integration.

Now, for some bizarre reason I also need a Recent Cakes view which is sorted in it's own way as the name reveals.

Now my question is, is there any way to add another weight for that view's use?

I know I can sort by date created but that would require going to every single node and manually changing the date; in short I am losing the drag and drop functionality Weight offers.

Poking around in the Weight module, it seems they only allow you one weight per node.

However, you can just keep adding Sort Criteria to the View, based on fields you've added to the content type. So you could add a How Many Layers? numeric field and also sort by layers, in addition to weight and/or popularity and/or whatever.


Programmatically render an imagefield in Drupal 6 as defined in content-field.tpl.php What sounds like simple task in the first place, has taken me hours without getting a solution: All I want is to render single values of an imagefield just as in the normal node, i.e. as defined in content-field.tpl.php. This is important for me, because there I add captions from the Imagefield Extended module

I tried with content_format(), but with the "default" formatter it gives me just an icon and a link and with the "image_imagelink" formatter from the imagefield.module I get an image, but not as defined in content-field.tpl.php and in the node type's display settings:

print content_format('field_image', $vars['node']->field_image[1], 'default', $vars['node']);
print content_format('field_image', $vars['node']->field_image[1], 'image_imagelink', $vars['node'])

I have tried a couple of other things and searched for hours, but I cannot find an answer. Any ideas how I can render the image "just the normal way"?

The HTML out I want is a defined in the template something like this:

Caption Text

            Source:
            Source text

            Licence:
            Licence text

Do you have more than one image?

print content_format('field_image', $vars['node']->field_image[0], 'default', $vars['node']);
print content_format('field_image', $vars['node']->field_image[0], 'image_imagelink', $vars['node']);

Try again with [0] instead of [1]. I use those all the time and it works fine like that.


How to remove "There is currently no content classified with this term." phrase? I have multiple terms created and for each I have created direct links. However under the content this message is displayed (because there are no content linked to the node) :

  There is currently no content classified with this term.

How to get rid of it ?

I don't like the CSS solution display:none.

Using mytheme_preprocess(&$variables, $hook) to override the $variables['page']['content']['system_main']['no_content'] variable.

function mytheme_preprocess(&$variables, $hook) {
  if(isset($variables['page']['content']['system_main']['no_content'])) {
    unset($variables['page']['content']['system_main']['no_content']);
  }
}


Entity Browser Widget for Video Embed Media Entity I have a few different Entity Browsers setup for uploading or selecting Media Entities on my Drupal 8.3.x site.

I have Image, Document & Video media bundles setup on the site.

The Image & Document providers include widgets to add to an Entity Browser.

Video bundle is setup via the video_embed module through media_entity module.

I can not find any documentation or method of adding an 'Add New Video' type of widget for Entity Browser – ie. A simple text field in which you paste in the URL of a Vimeo/Youtube video to create an entity for it.

My Video Entity is working fine on the standalone creation form.

I also have a View (Entity browser widget plugin) I'm using for selecting Existing videos on the site, and that works fine.

Are there any existing methods for an 'Add Video'

I could not find any way to implement an 'Add New Video' widget to an Entity Browser.

There is a solution using Inline Entity Form. https://www.drupal.org/project/inline_entity_form

With Inline Entity Form, you can have an entity creation option, or add existing entity option.  You can then use an Entity Browser for selecting existing entities, and leave the adding of new entities up to Inline Entity Form.

It's quite a clean User Interface / User Experience once implemented:


node_data_field not working on 6 I have this structure:

: '.$data->node_data_field_story_text_html_field_kampanya_adi_value.'

Ajans

: '.$data->node_data_field_story_text_html_field_ajans_value.'

Reklamveren

: '.$data->node_data_field_story_text_html_field_reklamveren_value.'

Ödül

: '.$data->node_data_field_story_text_html_field_odul_value.'

It's working.
And 4 other field:

field_one
field_two
field_three
field_four

When I change this field to other, not working. Like this:

: '.$data->node_data_field_story_text_html_field_one_value.'

And not working on my page.

How can I fix it?

I imagine $data->node_data_field_story_text_html_field_one_value is not being set.

Try running dpm($data) if you have the devel module enabled which will show you all the object members set.

Also you should check your php error logs and Drupal watchdog for any errors to see if they provide a clue as to why it doesn't work


How do I get a javascript library to work inside the CKEditor module? My content administrators want to be able to toggle back and forth between bootstrap nav-pills inside of the CKEditor instance. Out of the box, CKEditor doesn't seem to allow javascript to function in the editor. An example is below - I need to be able to click on the different pills to edit the associated content:

I have found an associated question that seem to answer this issue but I cannot get it to work in Drupal - I don't know how to implement the code. I would add a comment to that question but I do not have sufficient reputation points.

Using the code supplied in this associated question, I was able to get the javascript nav-pills to work in the CKEditor instance for Drupal 7. Unfortunately, it will only function in Firefox for PC. In addition, I had to add the following code to the ckeditor.config.js file as well as manually add the script to the admin theme's html.tpl.php file - this seems redundant but it will only work if both files have it.

CKEDITOR.on('instanceReady', function(ev) {
var jqScript = document.createElement('script');
var bsScript = document.createElement('script');

jqScript.src = 'http://code.jquery.com/jquery-2.0.2.js';
bsScript.src = 'http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js';

var editorHead = ev.editor.document.$.head;
editorHead.appendChild(jqScript);
editorHead.appendChild(bsScript);

jqScript.onload = function() { editorHead.appendChild(bsScript); };
});


Include content on module install of a custom block I'm using Features for creating a custom module that installs and places blocks on my site, but Features doesn't export content and in this case the block contents will be needed.

I'm trying figure out how to include custom block's content somewhere in my module to my custom blocks appear with some content (to allow editing in 'custom library page') or somehow populate my custom blocks after module install with a automate tool.

PS: From now, I've putting content after module install using mysqldump (export site A, insert site B), but its not safe procedure.

Any hints are appreciated.

Use https://drupal.org/project/default_content for install time content. For ongoing content, there is Entity Pilot (disclaimer: my product) https://drupal.org/project/entity_pilot.


Call a custom module's function from template file In the same context that this question, I want to add a link to a function in my custom module from a template file.

Something like this:

In my template file: Action

In my custom module

function my_function($id){
//update data base
}

a function doesn't have a url unless you set up a callback url for it first with hook_menu. Then you can point your link to it and process the data. So in your case it'd look something roughly like that:

In your custom module:

function mymodule_menu() {
  $items['some_url/%'] = array(
    'page callback' => 'mymodule_myfunction',
    'page arguments' => array(
      1,
    ),
  );
  return $items;
}

function mymodule_myfunction($id) {
 // update database
}

Then in your template use l() as Kevin mentioned (you should adjust to fit your variables etc):

print l('Action', 'abc/20');

This is very simplified. You'd want to probably enable some access limitations on that new url (abc/%) etc and you can read more about that in the hook_menu docs I linked to above.


Showing all results of custom content type in every page Essentially we have a custom content type called "Slideshow" with "title", "content", and "image" as the three fields.  We want our admins to be able to add new elements to the slideshow by simply adding new content with the slideshow content type.

Everything we have tried has failed miserably. All research indicates that we need to create a custom node template named node--slideshow.tpl.php and lay it out how we want (IE place the slideshow divs around our render($content['field_slider_image']), etc... but how do we then insert that into our page template?

I apologize if this is a stupid question or if we're going about this in an odd way.  The template has already been coded, so we need to be able let our admins add slideshow elements easily and have them show up on the front-end without them editing a "slideshow" block.

I hope someone can help us figure this out.

Edit - Just stumbled upon "views" and that looks very promising because it allows us to set up a 'slideshow' view which automatically pulls in the content of our slideshow content type.  If we go that route, how do we format the output?

Edit 2 - This slideshow will be at the top of the homepage only. Any other page will have the page title in that spot.

The simplest solution would be to to call views_embed_view in the page--front.tpl.php file (page-front.tpl.php in D6).

The more complex solution I would go with, is using Panels everywhere, and expose the View as a content pane.


How do I check if a node is an organic group in an access callback of a custom module? In Drupal 7 with Drupalgap, I have created a custom module in order to make a block. I have defined hook_block_info() and hook_block_view() as it is necessary.
What I want is making this block visible only in organic group nodes. So I need an access callback inside my groups_menu_module_block.js
Below you can see the function but it doesn't seem to work.

    function groups_menu_module_block_access_callback(options) {
        return og_is_group('node', Drupal.node.nid);
    }

You've stumbled across an early design flaw on my part, I didn't realize how important it would be to be able to make async calls when determining access to elements (pages, blocks, etc). To get around this (and other related issues), I added some helper functions to DrupalGap core.

The idea behind it is that the built in pages in DrupalGap are there for very simple applications, and more complex applications should build their own pages.

More info: http://docs.drupalgap.org/7/Entities/Rendering_Entities

The general idea is that you build a custom page(s), which will have a fully loaded entity delivered to its page_callback (which under the hood is actually a pageshow callback masquerading as a page_callback: http://docs.drupalgap.org/7/Pages/Page_Events).

Then in your page_callback when you are building the content object you already have access to the fully loaded entity, so you can make intelligent decisions about what is displayed.

With your example (and using the first link above), I'd recommend making a page with a path of group/%, and in your page_callback you can use custom widgets to simulate the block you are looking to render:

function my_module_group_page(node) {
  var content = {};
  content['my_nav_block'] = {
    theme: 'my_module_nav_block',
    node: node
  };
  content['foo'] = { /* ... */ };
  content['bar'] = { /* ... */ };
  content['etc'] = { /* ... */ };
  return content;
}

function theme_my_module_nav_block(variables) {
  var html = '';
  var node = variables.node;
  html += node.title;
  return html;
}

In hindsight it was silly of me to try and replicate Drupal's built in pages within DrupalGap (besides the user login/registration pages, etc) because every application should be unique. I now stricly use this approach and no longer use the vast majority of the built-in pages within DrupalGap.

So to answer your actual question, I would recommend building a Views JSON page display which only returns Group nodes, then your app can feed off of that and display a list of Group nodes, that when clicked go to your custom Group page.


How to use ConfirmFormBase to confirm the action of another form? I have a form that allows users to upload a CSV file. Upon submit, I would like to show a confirmation form ("Are you sure you want to import this file?").

However, the Drupal 8 examples for ConfirmFormBase seem to only focus on building the confirmation form without actually showing how one gets to that form from another form.

Can someone provide an example of a regular form that then works in conjunction with a confirmation form?

As you've already discovered, ConfigFormBase just provides some buttons, handling for messages, and submit/cancel logic. On its own, it's not designed to be used as the sort of multistep form you're looking for.

Getting that functionality is pretty easy though; you could use the logic in Drupal\config\Form\ConfigSingleImportForm as a rough example. Basically you just handle the multistep part of it yourself. For example:

protected $step = 1;

public function buildForm(array $form, FormStateInterface $form_state) {
  // When this is the confirmation step fall through to the confirmation form.
  if ($this->step === 2) {
    return parent::buildForm($form, $form_state);
  }

  // Build and return your upload form as normal, but don't call the parent method.
}

public function validateForm(array &$form, FormStateInterface $form_state) {
  // The confirmation step needs no additional validation.
  if ($this->step === 2) {
    return;
  }

  // Perform any additional validation
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  if ($this->step === 1) {
    $form_state->setRebuild();
    $this->step = 2;
    return;
  }

  // Extract rows from CSV and set batch to import here
}


Update webform without composer I need to update webform from 8.x-5.0-beta18 to 8.x-5.1  but unfortunately, I cannot use Composer because it is not possible to install it on my server due to server restrictions.

This also apply to:

Clientside Validation 8.x-1.0-rc3 to 8.x-1.0
Poll  8.x-1.1 to 8.x-1.2
SMTP Authentication Support   8.x-1.0-beta3 to 8.x-1.0-beta4

as they all appear in the admin/reports/updates/update

Is there anyway to do it manually?

Before doing any updates, make sure that you've backed up your production site to avoid loss of data. Also make sure that you have an easy way to restore the backups (:

Solution 1

You can replicate the site on your local dev environment. Then, apply the updates using composer and upload the relevant files to the prod site.

Solution 2

You can use drush up MODULENAME to update specific modules. However, make sure you've tested the updates on a dev site. However, some modules have dependencies which need to updated separately. It is for these dependencies that people recommend using composer for updating Drupal packages.


How can I create a recommended project in the root directory? My server consists only one Drupal site and therefore I would like to install it directly under D:\home\site\wwwroot
However this seems impossible as the new command composer create-project drupal/recommended-project:~8.8.0 mysite requires some sort of a folder name like 'mysite'.
All I want is Drupal composer.json stuff to be installed in D:\home\site\wwwroot and 'web' folder to be installed in D:\home\site\wwwroot\web
Is this possible at all?

If wwwroot is empty you can simply run the following command from inside this directory.
composer create-project drupal/recommended-project .

The . at the end says: current directory.


Can a module install a content type optionally or conditionally? I have a module which installs a number of different custom content types, each defined in a .yml file in config/install/.

I install my module, and the content type appears and works normally, and I used them to create content.

I was doing some other development that required me to uninstall and reinstall this module. It uninstalled with no problem, and I did not lose any of the content built on the module's content types.

However, the module could not be reinstalled. When I tried, I got the error message:

  Unable to install CustomModule, node.type.custom_node_type_one, node.type.custom_node_type_two already exist in active configuration.

where custom_node_type_one and custom_node_type_two are the content types installed by my theme.

This seems like a potentially serious problem. My module defines blocks that appear on nodes using these custom content types, but they also may contain independent content. If the module is uninstalled for any reason, I don't want to force the site admin to wipe all of that content--but I also don't want the site to be blocked from reinstalling the module.

Is there a way in Drupal 8 to make the installation of a content type conditional, so that the module can be uninstalled and reinstalled without having to first delete all of the site's custom content?

Don't install a module when its default configuration has unmet dependencies adds a config/optional folder, which silently ignores configuration that already exists.

config/optional can contain configuration that will only be installed if the required dependencies of those config entities are met, for example a default view that would only be installed if views is enabled and is not required for the module.


access a text field by php I created a text field in my "content type". as I do with php to access this value?
I would print it in a similar way:

 <?php print $submitted; ?>

in node.tpl.php and prevent it from being printed in an automatic way.

EDIT

I put this command in the file node.tpl.php:

<?php print $field_nazionalita_1; ?>

the result is:

Array([und] => Array(
   [0] => Array(
      [value] => francia
      [format] =>
      [safe_value] => francia
   )
  )
)

the result that I want is:
francia

but only if I inserted a value in the field.

I know little php, you can help me?

You should read about the field_view_field(), something like this should work for you:

print render(field_view_field('node', $node, 'field_nazionalita_1'));


How do I integrate queries to legacy databases? I'd like to totally move to Drupal and was hoping for information.  I have an old classic asp site with webpages everywhere, not in a framework or cms or anything like that.  They're just set up like the "old way" of doing things.  Mixed code and presentation and so on.

I wanted to move to Drupal, but I need to know how to handle the legacy or new non-Mysql datasources.

For example, I have an asp page that hits a sql server database.  If I rewrite that in PHP, how do I get it into Drupal?  Do I create a module for each page I want to port over?  What do I do?  Should I not use Drupal if this is my need?

Welcome to Drupal (and also Drupal answers) :) Glad to hear that you've chosen Drupal.

Although the scope of this question is pretty big, I'll try my best to answer. Feel free to ask more questions.

You might want to first check out whether Drupal fits in your requirements. You can check Case Studies of different sites which were built (from scratch or migrated) on Drupal. See if it gives you any idea.

If Drupal does fit into your requirement (mostly it does), you can check if there is any Drupal distribution present which is closer to your requirement (e.g. Commerce Kickstart distribution is a customized Drupal installation which is modified to provide features for a typical e-commerce site; while OpenPublish distribution is for news/articles publishing).

You don't need to develop a module per page. If you come across any requirement, there is a popular saying which goes "There's a module for that", which just means that there is a possibility that someone else who faced the same problem came up with the solution in the form of a module. You can search the list of modules on the official Drupal.org site, or drupalmodules.com, or just google it ;-)

You might also check for the Migrate module, which provides out of the box support to migrate sites powered by other technologies to Drupal (with some customization).

If you get any queries in your Journey to Drupal Land, you're always welcomed here on StackExchange's Drupal site :)


Drupal 7 Teaser Image Block - no titles or other data I am setting up a pretty straightforward Durpal 7 site, so I am trying to keep things simple. I have an image gallery set up just fine. On the home page, I am trying to set up a block that simply displays 4 random thumbnails from the gallery. I only want the thumbnail images, but I currently also have the image titles, date posted, and posted by data. Is there a simple way to post only the thumbnails and not the other associated data? I have tried to strip down the teaser view to the bare bones, but still the other data are viewable.

Instead of showing the content with a view mode of Teaser, rather show fields, and only the image field.

If you want to continue using content with a view mode, install and use Display Suite


Template suggestion being ignored I have a parent theme as a basis for a multisite installation. Right now, I'm working on a child theme which has to have some custom templates. Here's my preprocess function in my child theme:

$orig = $vars['theme_hook_suggestions'];
$manual = array('page__node', 'page__node__%', 'page__node__96', 'page__gallery', 'page__drisco_gallery');

dpm(array_diff($manual, $orig));
dpm($manual);
dpm($orig);
$vars['theme_hook_suggestions'] = $manual; // Loads my page--gallery.tpl.php template and works as expected.
$vars['theme_hook_suggestions'] = $orig; // Ignores my template, just uses page.tpl.php

The template only loads if I create the array by hand, even though it's apparently identical to the one already there. Here is what dpm() outputs:

... (Array, 0 elements)

... (Array, 5 elements)
    0 (String, 10 characters ) page__node
    1 (String, 13 characters ) page__node__%
    2 (String, 14 characters ) page__node__96
    3 (String, 13 characters ) page__gallery
    4 (String, 20 characters ) page__drisco_gallery

... (Array, 5 elements)
    0 (String, 10 characters ) page__node
    1 (String, 13 characters ) page__node__%
    2 (String, 14 characters ) page__node__96
    3 (String, 13 characters ) page__gallery
    4 (String, 20 characters ) page__drisco_gallery

Does anyone have a clue of what I'm doing wrong?

In order to load the template based on the content type, inside the template.php file of your theme you need the following code:

function your_theme_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

if the content type is "mycontent," create the page--mycontent.tpl.php file.

For template files that are based on the page path, create the page--front.tpl.php, page--node--7.tpl.php, page--node--58.tpl.php or page--node--nodeid.tpl.php files. Please note that between the page and node templates are different from what they used to be in drupal 6.


Drupal Gardens: is it possible to install a new theme? I need to create a site into Drupal Gardens, but my client needs a custom responsive theme. I have searched in the FAQ and internal page of Drupal Gardens, but I have not found anything about this possibility.

Is there a way to install a theme for my site into Drupal Gardens?
Can I install some modules from drupal.org?

Drupal Gardens is really limited and you cannot install a theme from drupal.org but what you can do is to customize the possible "layouts" that Gardens give to you.

If you click on the layout button on the panel you will see different layouts (columns and sidebars) and from this basic structure you can start applying custom CSS. Check more here http://www.drupalgardens.com/documentation/themebuilder/layout-tab and http://www.drupalgardens.com/documentation/themebuilder/advanced-tab


Is having 150+ user fields too heavy? Our user entities have about 5 fields for the public profile, and 5 fields with settings that determine the content of 60 other fields we need for our implementation (I've thought of making this 60 "computed fields"). The last ones can be overridden by the user, so we need another 60 to store the user entered values (without loosing the defaults) and 30 fields to act as a flag that indicates if the default or custom version is used (30 flags are enough because the 60 fields go in pairs, they are 30 pairs).

Let's say that we attach the 150+ fields to user entities: Wouldn't that be too heavy, especially when viewing the user profile page (where all the other fields are not necessary)?

Should we define a custom field that would integrate a pair of the default values, a pair of the custom values, and the flag, so we would only need 30 of those within a user object? Apart from having to define the custom field, we lose the computed field module, I think.

Should we offload user entities by creating a content type to attach the total 60 + 60 +30 fields, and link the user with the content type using the Relation module?

thats right, consider creating a new entity and relate it through a user reference field, for these types of references, the "references module" is better than the "relations module".


Import LinkedIn data (profile information) to user profile in drupal I want to authenticate via LinkedIn and, after successful login, import basic user profile data into the Drupal user profile. We're currently looking into LinkedIn Integration Module.  Unfortunately this module doesn't have a strong support or new developments going. Are there alternatives?

That module is the only LinkedIn-specific module that does that; LinkedIn Company API Suite is for company (not individual) accounts and flux LinkedIn API integrates with LinkedIn, but it does not provide any other functionality.

For quick Drupal profile creation, you're better off using one of the many social media login modules that supports LinkedIn (e.g. HybridAuth, Janrain, etc.)


Bootstrap Subtheme undefined variable error for custom node type template I am using the Bootstrap theme, I created a subtheme and duplicated page.tpl.php into my subtheme: /subtheme/templates/system/page.tpl.php

I then duplicated page.tpl.php and renamed to node--[mytype].tpl.php. The template is registering but it is filled with "undefined variable" errors. The errors don't happen /subtheme/templates/system/page.tpl.php  but happen when I add node--[mytype].tpl.php despite having the same code.

I've tried putting in node--[mytype].tpl.php in different directories including subtheme root and /templates/ but errors persists.

Duplicating node.tpl.php (instead of page.tpl.php) and putting it in /subtheme/templates/node/node--[type].tpl.php fixed my undefined variable error.


Generate slideshow of images present in a folder I want a module which gives user just a screen to upload images to a folder and it will generate a slideshow of the images and place it on a certain block in my website. Is there any module to do this or any custom code to do this?

You could try something along the lines of the following:

function mymodule_get_folder_images() {
$directory = "path/to/your/images";
//Check this...my regex is crap
$mask = "(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)";
$options = array(
'recursive' => TRUE
);

//This should return an array of images
$images = file_scan_directory($directory, $mask, $options);

//Loop through the array once to get an array of paths.
foreach ($images as $k => $v) {
$imagearray[] = $v->uri;
}

//This should probably be passed to a theme function to be more Drupally.

$output = '
';

foreach ($imagearray as $k => $imagepath) {
if ($k == '0') {
$output .= '';
}
else {
$output .= '';
}

$output .= '
';

return $output;
}

This will give you an unordered list of images that you can use to create your slideshow.  Then just hook the jQuery Cycle plugin (or any other slideshow plugin) into your site and you're off.  I can't really help with the slideshow integration as it's going to be pretty custom for your needs, but it becomes much easier when you already have the image urls formatted nicely.  Obviously, if you need a list instead then you just re-format the last foreach loop.


How do I change the text of a link? How do I change the text of a link in Views?

Under 'Fields' I have Content:Title (the default)...and that's what I want. It links to the piece of content with the link being the Title of that document. But I want to change the link text to something else.

I tried clicking that field. It opens up a dialog. Under 'Rewrite Results' I selected 'Override the output of this field with custom text' and put in my custom text. But now instead of it being a link it's just static text. That's useless.

Replacement patterns don't have any links listed just {{title}} and {{ title__value }} == Raw value

'Link to this content' is still checked at the top btw.

In Fields add Path and _Exclude from display. In your title, uncheckmark Link to the Content.

In rewrite results, checkmark Override the output of this field with custom text and put Custom Text. Alternatively, in rewrite results, checkmark Output this field as a custom link, for the path put {{ path }} and scroll down a bit to Title text and write your title here.


How to create a confirmation page linking to the content just created by a user I would like to create a page that that user sees once it has submitted a new piece of content. That page will provide a link to the page that the user has just created, allowing them to share that link through various social networks.

What is the best way to implement something like this? I am not using a webform. The user is allowed to submit an unlimited number of content.

Thanks, Lauren

use Rules module http://drupal.org/project/rules, you can build a new rule to redirect (to a new page) the user when create, for example, a node. see examples to Drupal 6 http://drupal.org/node/298483 or Drupal 7 http://drupal.org/node/878712

specifically, I suggest that you review events like 'After saving new content' or/and 'After updating existing content' , then you can launch  task (or add conditions to the task and lauch the task) according your needs. Seems that 'Page redirect' Action can be useful.


Taxonomy autocomplete is empty because of access control for anonymous users I am using Finder, a great module for autocomplete searches. I am using it for autocompleting results from a taxonomy vocabulary. The way Finder works is it uses views for the autocomplete results. My view is a simple HTML list of all the terms from the vocabulary.

The taxonomy vocabulary is restricted only to logged in users. This causes the autocomplete to return empty results. I changed access settings in the view, but that didn't help.

Can anyone suggest a way around this?

I could simply redirect from the vocabulary path, but I'm not sure it's a good solution, since the data really needs to be private. How safe is it to just redirect?

Changing the access settings didn't help because Drupal filters out items that are not accessible by the user currently viewing the view.  There are a number of ways you can deal with this:

Use Vocabulary Permissions Per Role which gives finer grained control of taxonomies
Use Page Manager (part of ctools) to override the taxonomy page either by redirecting somewhere else or making your own page in Page Manager using Panels.
As you suggest, use a redirection module (or Rules perhaps) to redirect users away from the page.  The data will be safe as long as the rule or redirection fires before anything is rendered.