How to remove the default "Anonymous" from comment author name? In the comment form field (core comment module) I would to leave the comment author name empty, in order to encourage commentators to come up with original epithets.

What's the easiest way to do it?

hook_form_alter()

http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_form_alter/7

Allows you to hook in to and alter any form, including setting the default text to empty. Here's some more help on what the valid elements are:

http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html

Best way to start is to determine the form ID by creating a mymodule_form_alter() function and printing out the $form_id using print so it appears at the top of the page. (Or better still, use the devel module to print it out in a Drupal status message). Once you know the form ID, you can add an if to make sure you only act on that form and then alter the array to remove the default value you don't want.

Look at pretty much any module for an example implementation. Many modules use this hook. I can't think of any specific example off the top of my head, but there are loads.

EDIT: Here's a good Lullabot blog post on the matter... there's not much different between Drupal 6 and Drupal 7 in this regard, AFAIK:
http://www.lullabot.com/articles/modifying-forms-drupal-5-and-6


Conflict with languages at home page I have enabled 2 languages on the site (Russian and English). The conflict is only happening at the home page where the URL alias is /. All the strings at sitename.ru/ are in English (the ones I would expect on sitename.co.uk), except for blocks. Language seems set to Russian, if that is the language set for the blocks.
All the other pages (sitename.ru/pagename) are working correctly.

Here are some screenshots of page configuration, modules list and language configuration from admin.

How do I make it work on / for all languages based on their TLD?

Please advise

I suppose this is happening because you set the default language as English (see: /admin/config/regional/language) and set Russian as default to have Russian language on "/" .


Insert/create user in database using login form I know its dump question, using login form and insert user in database.

Actually, I have an API that includes users of company/organization and these users already have registered on other applications. So, using such API I can get user info using username and password.

Of course, we need to logged in users directly (without registration) who already have account on other applications.

For logging in, I need to, first, insert the user info in data (before insertion, I can fetch username and password from API) so user can get in the site as logged in user.

After fetching from API, how to create user in the database with
username and password field only?
It should be done without email info.

It is not possible to create a user account in Drupal without writing an email account.

An example of how you can create a user programmatically is:

 $new_user = array(
  'name' => 'name',
  'mail' => 'name@email.com',
  'pass' => 'password', // note: do not md5 the password
  'status' => 1
 );

 //custom fields
 $new_user->field_name_lasname['und'][0]['value'] = 'Name and Last Name';
 //custom fields ( custom fields)
 $new_user->field_referenced_field_['und'][0]['target_id'] = 0;

 user_save(null, $new_user);

Please excuse me my English is not good


Is weather.com still running Drupal? There have been news items in 2013 about weather.com moving to Drupal. I have been reading How to tell if a site is using Drupal 7 and I have been unable to find out if the site is still running on Drupal.

How can I find out if weather.com is still running Drupal?

I use buildwith chrome plugin and Appspector, it does not looks like they use drupal CMS.


pass variable from custom module file to twig template in d8 How to pass variable from controller to twig template in Drupal-8?
I have tried to pass variable on module theme folder, but I want to use this variable on global theme?

First create a function that returns the variable, something like this:

function my_function() {
return $var_name;
}

Then you must create a preprocess function, for the template, like this:

function MY_MODULE_preprocess_TEMPLATE(&$variables) {
  $V_NAME = my_function();
  $variables['v-name'] = $V_NAME;
}

Remember to clear the cache.


#states does not hide #suffix in a form I am new to Drupal, so please be fair with me :)

I am trying to create a custom form using FAPI. The code is as follows :

$form['format_document'] = array(
  '#type' => 'radios',
  '#options' => array(
    'yes' => t('Yes'),
    'no' => t('No')
  ),
  '#title' => t('Should we format your document?:'),
  '#required' => TRUE,
  '#default_value' => 'no',

  '#suffix' => 'markup for the help image',

  '#states' => array(
    'visible' => array(
      ':input[name="select_service"]' => array(
        array('value' => '1'),
        array('value' => '2'),
        array('value' => '3'),
      ),
    ),
  ),
);

The #states work fine on the form element visibility; however the #suffix part is always visible. I can create a new form element with the same #states, but I have to do this on large number of elements. Is there something I am missing in the #states?

You could put your form element with the suffix into a container forms element. The container can also have states:

$form['format_document_container'] = array(
  '#type' => 'container',
  '#states' => array(
    'visible' => array(
      ':input[name="select_service"]' => array(
        array('value' => '1'),
        array('value' => '2'),
        array('value' => '3'),
      ),
    ),
  ),
);

$form['format_document_container']['format_document'] = array(
  '#type' => 'radios',
  '#options' => array(
    'yes' => t('Yes'),
    'no' => t('No')
  ),
  '#title' => t('Should we format your document?:'),
  '#required' => TRUE,
  '#default_value' => 'no',

  '#suffix' => 'markup for the help image',
);


How do I set an empty link title in a menu item? I'm using a fontawesome icon in a menu (with the tbmegamenu module) and I want to remove the text. Drupal forces me to enter something, &nbsp; doesn't work so as a temporary solution I put at dot .
How can I remove the dot without resorting to very dirty CSS tricks?

See also the actual HTML at the website.

Entering an empty string in the menu title would be the cleanest way to get to a solution now.  Maybe it's possible with a hook that lets me put <none> in the menu title?

No need to resort to "dirty CSS tricks", you can just use clean CSS:

a.class {
  display: inline-block; // Or block if it makes more sense for your layout.
  text-indent: -9999em;
}

This is the correct way to handle it, as you can include proper text as your link (e.g. "Home"), so you're not alienating users with screen readers, etc.


Get a list of all entity reference fields that reference specific entity types Is there a way to get a list of entity reference fields by field type (similar to what is produced by $all_reference_fields = $this->entityFieldManager->getFieldMapByFieldType('entity_reference');) but filtered down to just list the entity reference fields that have target entity types and bundles that match a specified list.

I'm not seeing anything in the entityFieldManager that would make it easy to filter the results of the getFieldMap() or getFieldMapByFieldType() down  to just specific reference fields I'm looking for, because the mapping doesn't contain any of the field's storage information, that contains the list of target bundles and handlers.

Looks like the entity_reference module in core doesn't provide any services that would be the logical place for something like this, so my current thinking is that I'll need to do this in two steps:

Call getFieldMapByFieldType('entity_reference');.
Work through every single entity type in the field map, and call buildFieldStorageDefinitions($entity_type); or something of that nature, to figure out the target entity_type:bundle_name combinations, and track down fields that reference 'taxonomy_term:tag'. This seems horribly inefficient, due to the sheer number of entity_reference type fields in this site, so maybe there is a better way to do this step?

In an ideal world, there'd be just a set of database calls I could make, or even a service in core for entity_reference module! (wishful thinking) ;)

Answering this myself based on the investigation I did using field_entity_bundle_delete for inspiration.  Would be great if someone could take this code and improve it.

  /**
   * Helper method gets a list of all entity reference fields that reference
   * the specified entity type.
   *
   * @param $entity_type string
   * @param $entity_bundle string (optional)
   * @return a filtered field map of entity reference fields.
   */
  protected function getEntityReferenceFieldsByEntityType($entity_type, $entity_bundle = '') {

    // Gather a list of all entity reference fields.
    $map = \Drupal::entityManager()->getFieldMapByFieldType('entity_reference');
    $ids = [];
    foreach ($map as $type => $info) {
      foreach ($info as $name => $data) {
        foreach ($data['bundles'] as $bundle_name) {
          $ids[] = "$type.$bundle_name.$name";
        }
      }
    }

    // Determine if any of the reference fields reference a specific entity type
    // and bundle type.
    foreach (FieldConfig::loadMultiple($ids) as $field_config) {
      $field_name = $field_config->getName();
      $target_type = $field_config->getSetting('target_type');
      if (!empty($target_type) && $target_type == $entity_type)) {
        if (!empty($entity_bundle) {
          $handler_settings = $field_config->getSetting('handler_settings');
          if (isset($handler_settings['target_bundles'][$entity_bundle])) {
            $filtered_map[$entity_type][$field_name] = $map[$entity_type][$field_name];
          }
        } else {
          $filtered_map[$entity_type][$field_name] = $map[$entity_type][$field_name];
        }
      }
    }

    return $filtered_map;
  }


how to load Ckeditor with IMCE file browser through javascript I have installed CKeditor and IMCE modules for Drupal7.
Now when i click on a button in my page, i want to load the ckeditor with IMCE support (File browser option).

How to achieve this with javascript?
So far, i am loading the ckeditor this way, but it is not showing a file browser button for image:

CKEDITOR.replace('text_'+id, {
    width: 630,
    height: 300
});

CKEDITOR.config.toolbar = [
    ['Bold','Italic','Underline']
];

CKEDITOR.config.extraPlugins = 'imce';

The strange thing is that, the Image dialog has "Browse Server" button for the textarea under the form that is created with Drupal Form API, but when i try to apply ckeditor for a custom textarea through javascript, i don't see the "Browse Server" button for Image dialog.

Finally i figured it myself, after referring to some of the Drupal forum posts, like this one. I removed the 'Image' button in ckeditor toolbar, and instead used the 'IMCE' button. I realized that i must

Assign a profile to the users under: admin/config/media/imce
Under admin/config/content/ckeditor/edit/Full > Editor Appearance, add 'IMCE' button in the 'Used Buttons' area and check the option "Plugin for inserting files from imce without image dialog" under Plugins. (assuming that i am using 'Full' ckeditor profile)
Under admin/config/content/ckeditor/edit/Full > File browser settings > select 'IMCE' for all File browser type options.
Include the 'IMCE' option while applying the ckeditor for the textarea, like:

CKEDITOR.config.toolbar = [['Bold','Italic','Underline',
'-','JustifyLeft','JustifyCenter','JustifyRight','-','IMCE','Undo','Redo']];

Finally this is what i achieved in the editor:


Is there a way to use grouping settings for Bootstrap Tabs in Views? Is there a way to use grouping settings for Bootstrap Tabs in Views?

There isn't a way at the moment to use the built in views group by function, but luckily there is a way to accomplish similar behavior if you install a contrib module called views field view.

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

The premise being, tabs separate a listing of entities into multiple groups based on a common term.

Not like this: https://monosnap.com/file/K4W6m63A1jsy7frYdL8P0LfcFQPj29

But like this: https://monosnap.com/file/Q8WsRSgJU7f8AYFMMomDmcIjyOAXZE

In order to make this work, you need two views, One with the tab output, and another contextually filtered as a field within the first.

View 1 (list of taxonomy terms) would look like this to create the labels for the tabs: https://monosnap.com/file/h3fDlfgy2HwlHT2Y3Lywe8IroagDyE

View 2 (Use a relationship to call the nodes that are referencing each term and a contexual filter to limit the nodes per term id): The view field here is the key: https://monosnap.com/file/NtIumKYmsws62o4kTAnU72mt1LPZZq

Once you have the two views you can set the argument on view 1
The view field here is the key: https://monosnap.com/file/EzgRlcjLgr0au7TIWnTLbWEosCHwcP


Ajax submission leads to => An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports So i'm trying to submit a form using ajax, in my form i have the following:

        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('OK'),
        '#button_type' => 'primary',
        '#prefix' => '
',
        '#suffix' => '

',
        '#attributes' => array(
            'class' => array('proximabold', 'tc', 'transition', 'no-underline', 'ph3', 'pv2', 'mb2', 'dib', 'white'),
        ),
        '#ajax' => [
            'event' => 'click',
            'callback' => '::updateTable',
            'wrapper' => 'table-wrapper',
            'progress' => [
                'type' => 'throbber',
                'message' => t('Verifying entry...'),
            ],
        ],
    );

and a simple updateTable function:

public function updateTable(array $form, FormStateInterface $form_state) {
    return "Hello World";
}

But when i click on submit i get the error:
An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports.

I knew that the error is server side (Maybe i'm wrong), so i went to php.ini (i use PHP7) and update the following lines:

post_max_size = 6144M
memory_limit = 6144M
upload_max_filesize = 6144M
max_file_uploads = 1000

but without luck, this configuration shouldn't be necessary as the request size is only 1.5KB

So after a throughout debugging i finally found the solution. the first thing i did is that i searched for the error and it was outputed from core/lib/Drupal/Core/Form/EventSubscriber/FormAjaxSubscriber.php :: wihtin we find a condition that interests us:

if ($exception instanceof BrokenPostRequestException && $request->query->has(FormBuilderInterface::AJAX_FORM_REQUEST)) {
  $this->drupalSetMessage($this->t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', ['@size' => $this->formatSize($exception->getSize())]), 'error');
  $response = new AjaxResponse();
  $status_messages = ['#type' => 'status_messages'];
  $response->addCommand(new ReplaceCommand(NULL, $status_messages));
  $response->headers->set('X-Status-Code', 200);
  $event->setResponse($response);
  return;
}

So the error is triggered if an exception instanciated of the BrokenPostRequestException class has occurred.

and now if we got to Core/lib/Drupal/Core/Form/FormBuilder.php we find that this exception is thrown if the post request is bigger than what is allowed by the server and also if the request doesn't carry the form id.

if ($ajax_form_request && !$request->request->has('form_id')) {
  throw new BrokenPostRequestException($this->getFileUploadMaxSize());
}

  It would have been better if there was another exception for this case
  rather than getting the same error for when the post request exceeds
  the configured allowed size (post_max_size)

well in my case it was not a matter of post size request but rather when I themed the form in my twig file, I did not include the form id.

So what i did is i added the lines highlited bellow:

Filtres

        <form> //Added this one
            {{ McRefund_build_data.filterform.form_build_id }} //Added this one
            {{ McRefund_build_data.filterform.form_id }} //Added this one
            {{ McRefund_build_data.filterform.RelevesMensuels }}
            {{ McRefund_build_data.filterform.from }}
            {{ McRefund_build_data.filterform.to }}
            {{ McRefund_build_data.filterform.example_select }}
            {{ McRefund_build_data.filterform.actions.submit }}
        </form> //Added this one

        {% for Num_refund,refund in McRefund_build_data.filterform.RefundsContainer['Refunds']['#Refunds_data'] %}
                   ............
                   ............
                   ............
        {% endfor %}


Drupal 8 - Stock quote cache I'm building a Drupal 8 site that has a stock quote on every page.  The data for the quote comes from a database.  The requirement is that the stock quote data be refreshed every five minutes and I've nailed down the database update portion of the process.

The other content on each page is highly static and I do not want to refresh the cache every five minutes.  Our Drupal config has cache set at one hour.  We also have Varnish to deal with.

Is it possible to exclude just this one block from cache?  I've tried using the preprocess hook to set max-age:

function mytheme_preprocess_block(&$vars) {
    if($vars['derivative_plugin_id'] == 'stocktickerblock') {
        $vars['#cache']['max-age'] = 0;
    }
}

But this doesn't seem to work.

Thank you

Put this in a custom module:

/**
 * Implements hook_block_view_alter().
 */
function MYMODULE_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  if (!empty($build['#id']) && $build['#id'] == 'stocktickerblock') {
    $build['#cache']['max-age'] = 0;
  }
}

but if the your 'stocktickerblock' block is from a custom plugin you can set the build cache directly in that plugin render array.


Programmatically changing the global site name? I'm making a multi-site setup using the same install and the same database, basing it off domains. I'm trying to programmatically alter the site_name variable so that it displays a different site name based on the domain being used.

I am using 3 different methods to achieve this at the same time, however even that is not bullet-proof. Certain instances (i.e. some administration pages, user login, or user profile edit) still display the default site name in the page title (or elsewhere).

I am doing the following:

$conf['site_name'] = $my_title; in settings.php
$vars['site_name'] = $my_title; in my theme's hook_preprocess_page
using hook_tokens_alter in a custom module to change the [site:name] token to $my_title

Despite all these measures, it seems I did not enforce the site name change in a bulletproof way. Is there a better method I have missed?

Worth mentioning: I am using the Metatag module, which seems to alter page titles on a fundamental level. I am not sure if this is related to my problem.

What is the value for the site_name variable in the variables table? (e.g. what's the output of variable_get('site_name')?)

If it's overridden from the value that you set in your settings file, reset it like so:

variable_set('site_name', $my_title)


How do you upload an image via jsonapi? The documentation is vague: https://www.drupal.org/docs/8/modules/json-api/working-with-files-post

I am trying to upload an image following the sample code given for uploading a "document" on above page.

Simplified example:
Given an admin user "bot" and a base-64 encoded qr code.

I create the json payload following the example in the documentation

{
  "data": {
      "type": "file--image",
      "attributes:": {
          "title": "QR Code",
          "uri": "public://folder/qr-code.png",
          "data": "iVBORw0KGgoAAAANSUhEUgAAAG8AAABvAQMAAADYCwwjAAAABlBMVEUAAAD///+l2Z/dAAAAAnRSTlP//8i138cAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAEsSURBVDiN1dS7jcMwDABQGirU5RYQoDXUaSV7AX8WsFdSxzUCeAGrUyGYRzuJ79KIKoIDTnCRVyj8gBTQ24H/wQ1gQNNCBrAiI+UOafRmoAqG48eSTKur2Gq4+VzJ3q/x190SKbfOLpivJAvkejs0/F3lF8hnh9yFn8YWuIEBR7tXs6ugJkIVEzSPrIqMBF94By72DFTmpteJVAxXoBI5RK9Nz4lpmbtTCx2FdGdWZRLmHuzo1/m8K5DWKeWB6001NEOg0dHrbombt9wfHu8GrcgYeEjuN00Lkky0m1eEdkoVTIa3rHfQBCuST6TzH0DmMbGBo/AukEjehSHkLtmYrExeyWNioXmWL1EDd34GW0XPneQ3h2Tym0OKh/Y5sUU+9hfcOmqZf/YCf4zfOAszBtzxUOsAAAAASUVORK5CYII="
      }
  }
}

Which translates into this curl command

curl \
--user bot:bot \
--header 'Accept: application/vnd.api+json' \
--header 'Content-type: application/vnd.api+json' \
--request POST http://drupalvm.test/jsonapi/file/image \
--data-binary '{"data": {"type": "file--image", "attributes:": {"title": "QR Code", "uri": "public://folder/qr-code.png", "data": "iVBORw0KGgoAAAANSUhEUgAAAG8AAABvAQMAAADYCwwjAAAABlBMVEUAAAD///+l2Z/dAAAAAnRSTlP//8i138cAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAEsSURBVDiN1dS7jcMwDABQGirU5RYQoDXUaSV7AX8WsFdSxzUCeAGrUyGYRzuJ79KIKoIDTnCRVyj8gBTQ24H/wQ1gQNNCBrAiI+UOafRmoAqG48eSTKur2Gq4+VzJ3q/x190SKbfOLpivJAvkejs0/F3lF8hnh9yFn8YWuIEBR7tXs6ugJkIVEzSPrIqMBF94By72DFTmpteJVAxXoBI5RK9Nz4lpmbtTCx2FdGdWZRLmHuzo1/m8K5DWKeWB6001NEOg0dHrbombt9wfHu8GrcgYeEjuN00Lkky0m1eEdkoVTIa3rHfQBCuST6TzH0DmMbGBo/AukEjehSHkLtmYrExeyWNioXmWL1EDd34GW0XPneQ3h2Tym0OKh/Y5sUU+9hfcOmqZf/YCf4zfOAszBtzxUOsAAAAASUVORK5CYII="}}}'

This results in an error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'uri' cannot be null

What am I doing wrong?

I am using a local Drupal instance generated by https://github.com/geerlingguy/drupal-vm#quick-start-guide on Mac Sierra 10.12.6

It is

Drupal core 8.5.3

Includes: Automated Cron, BigPipe, Block, Breakpoint, CKEditor, Color, Comment, Configuration Manager, Contact, Contextual Links, Custom Block, Custom Menu Links, Database Logging, Datetime, Field, Field UI, File, Filter, HTTP Basic Authentication, Help, History, Image, Internal Dynamic Page Cache, Internal Page Cache, Link, Menu UI, Node, Options, Path, Quick Edit, RDF, Search, Serialization, Shortcut, System, Taxonomy, Text, Text Editor, Toolbar, Tour, Update Manager, User, Views, Views UI

With the following Modules

File Entity (fieldable files) 8.x-2.0-beta6
JSON API 8.x-1.18
JSON API File 8.x-1.1
Token 8.x-1.3

(And with the core HTTP Basic Authentication module enabled)

Here is a javaScript version that may help after alot of trial and error I could only get "entity/file?_format=hal_json" to work aka "file_entity" module.

the following "bace64" = iVBORw0KGgoAAAANSUhEUgAAAG8AAABvA.....

uploadDrupalImage(bace64) {
  // Could only get hal_json to work.
  var dataToPost = '{"_links": {"type": {"href": ' + JSON.stringify(this.baceUrl + 'rest/type/file/image') + '}},"filename": [{"value": "' + this.state.file.name + '"}],"data":[{"value": "' + bace64 + '"}]}';
  var url = this.baceUrl + 'entity/file?_format=hal_json';
  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': this.state.csrf_token,
      'Authorization': this.state.basicAuth,
    },
    body: dataToPost
  }).then(response => response.json()).then(data => {
    if (data) {
      this.setState({uploadedFile: data});
      if (data.fid) {
        //console.log(data.fid[0].value);
        this.setState({fid: data.fid[0].value});
      }
    }
  }).catch(err => console.error(err.toString()));
  return false;
}

taken from (when i was just learning react so be kind lol) https://github.com/taggartj/Drupa_react_REST_examples/blob/master/src/components/drupal/DrupalCreateArticleWithImageBasicAuth.js


Form token wrong if logging in during rebuild I have a multi-step form using AJAX. When you submit the form it increments the step, and then sets $form['#rebuild'] to TRUE, and the entire form is replaced by AJAX.

It works fine, right up until one of the steps involved calling user_login_finalize() in the submit handler - the user can go from anonymous to logged in. Then when it tries to build the next step I get the error:

  Form errors cannot be set after form validation has finished

I puzzled over this error for a while. I thought the validation handler might be firing twice, but then I saw in the debug trace that setInvalidTokenError() is being called in FormBuilder->doBuildForm().

After looking in doBuildForm(), I think the problem is that Drupal thinks the form is being submitted in a naughty way or has the wrong token. What can I do?

The only way I could fix it was to set $form['#token'] to FALSE when building the form. This disables the token checking functionality, which isn't ideal, but I think it's my only option.


How to remove the title from a youtube video when using D7 + media module? When I add an youtube video to a "blog post" content type I automatically get youtube's title/url placed above the video (see screenshot below).

I have Drupal 7.7 + Media 7.x-2.x-dev + Media Youtube 7x-1.x-dev installed.
I have added to the "blog post" content type a new "video" field with type "multimedia asset" and widget "media file selector".

I would really appreciate any advice on how to remove or change this title.

It looks like that's the field label, which can changed on the manage display page (Structure > Content Types > Manage Display)


Override image template for field Can I modify core/image twig template only for specified entity.field?

I want to modify img tag output only for commerce_product.images custom field
but there is only 1 suggestion themes/bootstrap/templates/system/image.html.twig which override all image uses.

EDIT1:
if i'm implement hook_theme_suggestions_HOOK_alterm there is no entity or field info:

function mytheme_theme_suggestions_image_alter(array &$suggestions, array $variables) {
  $entity = $variables['item']->getEntity(); //ERROR
}

It's possible but very difficult to do.

You would have to alter to output of the image formatter to inject a theme suggestion on the image_formatter template (or create your own image formatter).

Then you would need to inject the suggestion from the formatter to the image theme function (could be done in a preprocess).

The issue is that altering the output would probably be something you would handle in each unique case, so you would basically need to create your own image formatter.

It's not a lot of work, but a bit tricky.

TL:DR;
Yes it's possible but you don't want to do that.


Drupal simplenews doesn't subscribe the users registed via social networks I'm using Simplenews module for sending newsletter to the registered users. When a user creates a new account he/she will be automatically subscribed to a newsletter which can be seen in admin/people/simplenews.

However, when user registers via social network he/she is not subscribed to newsletter. When I visit admin/people/simplenews I can see only the users registered in normal way; users registered through a social network cannot be seen.

I'm using HybridAuth for Twitter & Google+ login and Fboauth for Facebook login. In simplenews configuration, I've used silent setting. What can I do to make users sign up to a newsletter on social network registration?

The reason users aren't signed up is due to how simplenews works. It does the work of newsletter signup by modifying the Drupal core registration form to capture the newsletters (or setting them automatically in case of the silent option) then takes that data to sign users up following account creation.

For both HybridAuth & FBOauth, they subvert this process with their own forms to do authentication with a 3rd party. Both HybridAuth & FBOauth however, provide their own API hooks to take action upon user registration (hook_hybridauth_user_insert() & hook_fboauth_user_save() respectively). You can implement their hooks in a custom module to do the same work HybridAuth does to signup users automatically.


Mass Node Update (e.g., disable comments for all nodes of a given content type) Is it possible to mass update nodes from, say, "Comments Read/Write" to "Comments Disabled" for all nodes of a certain content type?

I changed the Content Type setting and that worked for all the other nodes types, except for a certain Node type that has given us problems in the past.

Thx

There's a module called Views Bulk Operations.

I never tried to do it, but I think you can write your own operations for this module pretty easily.


How can I get the checked attribute into Better Exposed Filters input type radios? i'm having a BEF exposed filter representing a taxonomy, they're radios.

It works well, but when i select a radio, it won't get in its HTML tag the property «checked».
I guess the selected value of the radios is stored somehow at $form_state, but this prevents existence of «checked» tag at HTML level. :-(

at jQuery level, i can select and play with the «checked» property, so it's working at javascript level.

the person who does the CSS needs that «checked» property at HTML level ...
is there a way to insert it in the HTML?

The person who does the CSS needs to design the dynamic property :checked, not the static attribute [checked]. The 2nd one is static in the HTML code and never updated after the intial page load, the first one is the currently selected input.


Lightweight way to check to see if another user has a role There are lots of examples of seeing if the current user has a particular role. I need lightweight function to see if another user has a particular role.

For comments, I want to highlight comments from users who have a particular role, "Guest Blogger". Using hook_preprocess_comment(&$variables) I can load up each user using:

$user_fields = user_load($variables['comment']->uid);

But this seems rather heavy. All I need to do is see if the user has a role, not load up the entire user object.

Can someone help me out with a function or a query where I pass in the uid and the function/query passes back an array of roles?

Something like:

function MYMODULE_get_user_roles($uid) {
  $roles = &drupal_static(__FUNCTION__, array());

  if (!isset($roles[$uid])) {
    $query = db_select('role', 'r')
      ->fields('r', array('rid', 'name'))
      ->condition('ur.uid', $uid);

    $query->join('users_roles', 'ur', 'ur.rid = r.rid');

    $roles[$uid] = $query->execute()->fetchAllKeyed();
  }

  return $roles[$uid];
}

You might want to add static caching to that if you plan to call it more than once for any single user during a single page build.


Migration of multi-value pictures to user fields I need to migrate from a WordPress site to a Drupal 7 site where users could upload their own images (like multiple user pictures). I have a CSV file with the User's ID and a serialized array containing the filenames of uploaded pictures (no, really).

Users have a multi-value image field 'field_user_pictures'.

After deserializing the array, drupal complains with the error "ltrim() expects parameter 1 to be string, array given". (Presumably because MigrateDestinationFile doesn't handle arrays very well.) Then I tried with just using the first image of the array, and that actually works. What doesn't work, however, is to get drupal to link this sole image to the 'field_user_pictures' user field.

I have been trying to get to something like this:

 class PictureMigration extends Migration
 {
    public function __construct ($arguments)
        {
        parent::__construct($arguments);

        $source = 'user_pictures.csv';

        $columns = array(
            1 => array('source_userid', ''),
            3 => array('source_serialized', ''),
        );

        $source_key = array('source_userid' => array('type' => 'int', 'not null' => TRUE),);

        $this->source = new MigrateSourceCSV($source, $columns);
        $this->destination = new MigrateDestinationFile('image', 'MigrateFileUri');
        $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationFile::getKeySchema());

        $this->addFieldMapping('source_dir')->defaultValue($this->remote_dir);
        $this->addFieldMapping('destination_dir')->defaultValue('public://');
        $this->addFieldMapping('value', 'source_serialized');
      }

  public function prepareRow($row) {
     // snipped
     $row->source_serialized = $this->deserializePhotos($row->source_serialized); // returns array of filenames
    }
}

public class UserMigration extends Migration {
  public class __construct ($arguments) {
    // snipped...
      $this->addFieldMapping('field_user_pictures')->sourceMigration('PictureMigration');
  }
}

The first problem is that MigrateDestinationFile doesn't seem to like multi-value values; the second problem is that even when I only use the first filename of the array, it still doesn't get linked to the 'field_user_pictures' field...

See also: Migration: Combine Profile2 and file migration -- almost exactly the same issue, but with no valid answer as well.

Something is really odd about your code $this->destination is a MigrateDestinationFile yet $this->map is trying to track a MigrateDestinationNode .... I've never done anything that way.

I would do the following:

Import Users from Wordpress to Drupal.
Use your CSV file of legacy UIDs and picture files to run an update of the (newly) created Drupal users and insert the images as needed.

I'm doing this now as we speak on a Document content type of which there are 120k entries, but only 4k have movie files associated with them so I feel a node revision is a better use the time to import stuff.

This is an example from some work in progress and will not run as-is but it should be a concrete example:

class PrezDocumentMediaMigration extends PrezMigration {

  public function __construct($arguments) {
    parent::__construct($arguments);

    $document_fields = array(
      // ... fields ...
    );
    $this->description = 'Update created Documents with audio and video from legacy DB. There are only ~5k of entries.';

    $query = Database::getConnection('default', 'legacy_migration')
      ->select('papers', 'p')
      ->fields('p', $document_fields)
      ->condition('av', 0, '<>');
    // Additional pseudo fields to move data from legacy derived data to drupal.
    $query->addExpression('NULL', 'local_video');
    $query->addExpression('NULL', 'remote_video');
    $query->addExpression('NULL', 'local_audio');
    $query->addExpression('NULL', 'remote_audio');

    $options = array('track_changes' => 1);

    $count_query = Database::getConnection('default', 'legacy_migration')
      ->select('papers', 'p')
      ->condition('av', 0, '<>');
    $count_query->addExpression('COUNT(pid)', 'cnt');

    // We are updating existing content in Drupal.
    $this->systemOfRecord = Migration::DESTINATION;

    $this->source = new MigrateSourceSQL($query, $document_fields, $count_query, $options);
    $this->destination = new MigrateDestinationNode('documents');
    $this->map = new MigrateSQLMap($this->machineName,
                                   array(
                                     'pid' => array(
                                       'type'     => 'int',
                                       'unsigned' => FALSE,
                                       'not null' => TRUE,
                                       'description' => 'Unique content reference legacy document',
                                       'alias' => 'doc',
                                     )
                                   ),
                                   MigrateDestinationNode::getKeySchema()
    );

    // Migration mappings, the documentation for these mappings can be seen at:
    // https://www.drupal.org/node/1133448

    $migrator_user = user_load_by_name('PrezMigrator');

    // Some default values for sanity.
    $this->addFieldMapping('uid')
      ->defaultValue($migrator_user->uid);
    $this->addFieldMapping('revision')
      ->defaultValue(1);
    $this->addFieldMapping('log')
      ->defaultValue('inserted related media from legacy DB on ' . date("l jS of F g:i A.", time()));
    $this->addFieldMapping('promote')->defaultValue(0);
    $this->addFieldMapping('sticky')->defaultValue(0);
    $this->addFieldMapping('revision_uid')->defaultValue($migrator_user->uid);

    // What legacy content are we talking about ?
    // also we want this legacy ID to actually lookup through 2 source migrations.
    $this->addFieldMapping('nid', 'id')->sourceMigration(array('PrezDietNonPresidents','PrezDietPresidents'));

    // Map media files these are multiple value fields. They can accept a PHP array of values.
    $this->addFieldMapping('field_docs_media_videos_local', 'local_video');
    $this->addFieldMapping('field_docs_media_videos_remote', 'remote_video');
    $this->addFieldMapping('field_docs_media_audo_local', 'local_audio');
    $this->addFieldMapping('field_docs_media_audio_remote', 'remote_audio');

    // Each of the above media fields will need the following additional subfields
    // Only 1 is provided as an example to keep this example shorter:
    $this->addFieldMapping('field_docs_media_videos_local:file_class')
      ->defaultValue('MigrateFileUri');
    $this->addFieldMapping('field_docs_media_videos_local:language')
      ->defaultValue(LANGUAGE_NONE);
    $this->addFieldMapping('field_docs_media_videos_local:preserve_files')
      ->defaultValue(FALSE);
    $this->addFieldMapping('field_docs_media_videos_local:file_replace')
      ->defaultValue(FILE_EXISTS_REPLACE);
    $this->addFieldMapping('field_docs_media_videos_local:source_dir')
      ->defaultValue('/var/www/2015/presidency/drupal7-project/build/legacy/htdocs/www/media/');
    $this->addFieldMapping('field_docs_media_videos_local:urlencode')
      ->defaultValue(FALSE);
    $this->addFieldMapping('field_docs_media_videos_local:alt')->defaultValue('');
    $this->addFieldMapping('field_docs_media_videos_local:title')
      ->defaultValue('');

    // List fields not be migrated to destination.
    $this->addUnmigratedDestinations(
      array(
        // ... massive list of fields.
      ));

  }

  public function prepareRow($row) {
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }

    $youtube_format = 3;
    $quicktime_format = 2;
    $audio_format = 1;

    switch ($row->av) {
      case $youtube_format:
        $row->remote_video = $this-> find_remote_video($row->medialink);
        break;
      case $quicktime_format:
        $row->local_video = $this->find_local_video($row->medialink);
        break;
      case $audio_format:
        $row->local_audio = $this->find_local_audio($row->av, $row->medialink);
      default:
        break;
    }
    return TRUE;
  }

  // http://stackoverflow.com/questions/5830387/how-to-find-all-youtube-video-ids-in-a-string-using-a-regex
  protected function find_remote_video($link) {
      $separator = '***';
    $text = preg_replace('~
        # Match non-linked youtube URL in the wild. (Rev:20130823)
        https?://         # Required scheme. Either http or https.
        (?:[0-9A-Z-]+\.)? # Optional subdomain.
        (?:               # Group host alternatives.
          youtu\.be/      # Either youtu.be,
        | youtube         # or youtube.com or
          (?:-nocookie)?  # youtube-nocookie.com
          \.com           # followed by
          \S*             # Allow anything up to VIDEO_ID,
          [^\w\s-]       # but char before ID is non-ID char.
        )                 # End host alternatives.
        ([\w-]{11})      # $1: VIDEO_ID is exactly 11 chars.
        (?=[^\w-]|$)     # Assert next char is non-ID or EOS.
        (?!               # Assert URL is not pre-linked.
          [?=&+%\w.-]*    # Allow URL (query) remainder.
          (?:             # Group pre-linked alternatives.
            [\'"][^<>]*>  # Either inside a start tag,
          | </a>          # or inside <a> element text contents.
          )               # End recognized pre-linked alts.
        )                 # End negative lookahead assertion.
        [?=&+%\w.-]*        # Consume any URL (query) remainder.
        ~ix',
                         '//www.youtube.com/embed/$1' . $separator,
                         $link);
    return explode($separator, $text);
  }

  // other "find" media methods that return filesystem paths and stuff depending on where the media
  // existed in the legacy system.
}


Search facet user entered date field display I've recently started working on an existing Drupal site that uses Apache Solr search & have come across a problem when configuring facets.

The search index just indexes one type of content & one of the facets it displays from this is a year field, this is set as a date select field where the user can select a month & year. If I set this to only allow one entry it works fine and the facet links have the years that are available with the number of results it'll return in brackets.

When I set the field to allow an unlimited number of values instead of getting a list of years as links I get what seems to be a random number "1414800000 (1)," timestamp maybe? It also seems to group them by the month & year entered rather than just the year as it did when only one field entry was allowed.

If anyone else has this same problem, there is a patch on drupal.org. If you've not used to patches, See this beginner's guide.


How to create a view of nodes *without* comments from currently logged in user I'm trying to create a view that lists nodes that don't have any comments from the currently logged in user. The nodes may have comments from other users, but if there is no comment from the current user then it should be listed.

I can show nodes with comments from the currently logged in user but not nodes without comments.

Almost like a "to-do" list of nodes that need to be commented on by the current user.

I'm a fairly advance views user (I've tried all I know by way of contextual filters, relationships, different content approaches like listing comments or users and connecting them through relationships... ) but all to no avail.

Anyone else come across this or have ideas where I can make more progress?

REVISED ANSWER

This can be accomplished in two step process.

Create a very plain view to only show node titles. Do not filter it except by type if you wish, and do not place any contextual filters on it. For this answer I created a view called 'not_commented' with a page display of 'page_1'.
Create a custom module. We will use it to alter the views query. For this answer I created a module called 'custom'.

Add this code to custom.module:

function custom_views_api(){
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'custom') . '/includes/views',
  );
}

Now create a folder 'includes' in the module folder, and then a folder 'views' inside the includes folder so that the folder structure is : sites/all/modules/custom/includes/views

Create a file custom.view.inc within folder views. Place this code in the file:

<?php

function custom_views_query_alter(&$view, &$query){
  if ($view->name == "not_commented" && $view->current_display == "page_1"){
    // get all nodes commented on by this author
    $sql = "SELECT n.nid, COUNT(n.nid) " .
      "FROM {node} n LEFT JOIN {comment} c ON n.nid = c.nid " .
      "WHERE (c.uid = :uid AND n.status = '1') GROUP BY n.nid";
    global $user;
    $query_2_result = db_query($sql, array(':uid' => $user->uid))->fetchAllKeyed(0,0);

    $query->where[1]['conditions'][] = array(
      'field' => 'node.nid',
      'value' => $query_2_result,
      'operator' => 'not in',
    );
  }
}

Clear you cache.

Please replace module and views/display names etc. as applicable. If there are any problems please inspect the $query object to see if you have the right where array key etc.


I cannot see the dblog of my kickstart commerce When I navigate to /admin/reports/dblog, nothing happens. It only shows me a node, and if I go to the Admin menu then I cannot see the reports link. Check the image below to better illustrate my issue:

My questions: Why I cannot see the reports menu? And how can I access the dblog info?

I found in the Commerce kickstart documentation that the dblog is disabled by default due to this functionality consumes a lot of resources.

Enable database logging module and then rebuilt the menus as suggested by Clive


Where are the field labels and descriptions stored? I have been exploring Drupal 8 and it's tables lately. The config table has the storage information serialized as blob. But it doesn't store the Label or Description of a field. Where can one find these data? Is there a core function which helps in fetching all these data for a particular content type?

You can try something like this :-

$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
$field_label = $node->field_file->getFieldDefinition()->getLabel();
$field_desc = $node->field_file->getFieldDefinition()->getDescription();
$field_settings = $node->field_file->getFieldDefinition()->getSettings();
}


Update webform field value using AJAX realtime I have a webform created using the admin panel and would like to change one of its textfield values on click of a button. I have attempted doing this from hook_form_alter. I have given the wrapper name 'changeText' for this textfield from admin panel.

function fence_quote_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_1'){
        $form['buttons']['fence_quote']  = array(
          '#type' => 'button',
          '#value' => t('Get online estimates'),
          '#ajax' => array(
              'callback' => 'fence_quote_form_callback',
              'wrapper' => 'changeText',
          ),
        );
       $form['field_meters']['#prefix'] = '
';
       $form['field_meters']['#sufix'] = '
';
    }
}

function fence_quote_form_callback($form, &$form_state) {
   $form_state['values']['field_meters']['und'][0]['value'] = '111';
   return $form['wrapper'];
}

The problem is I can't update 'meters' value using AJAX callback as it is a field created from admin panel and not from hook_form_alter. However if I place

$form['submitted']['meters']['#default_value'] = '111';

outside of the callback it works on page refresh. How can I do this?

As requested by @kamal-oberoi I'm uploading a screenshot of my full code.

add wrapper to your text field which you want to update.

 function fence_quote_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'webform_client_form_1'){
    $form['buttons']['fence_quote']  = array(
      '#type' => 'button',
      '#value' => t('Get online estimates'),
      '#ajax' => array(
          'callback' => 'fence_quote_form_callback',
          'wrapper' => 'changeText',
      ),
    );
    /* Please add Wrapper to text_field */
    $form['wrapper']['your_textfield_name']['#prefix'] = '
';
    $form['wrapper']['your_textfield_name']['#sufix'] = '
';
  }

}

function fence_quote_form_callback($form, &$form_state) {
     $form_state['values']['meters']['und'][0]['value'] = '111';
     return $form['wrapper'];
 }


How to get an image url given term_image_tid using the customfield-PHP views module I have created a view of type Term that lists all the taxonomy terms plus each term's image. This works. But now I want to wrap the images in a link that links to another view. I am trying to use the customfield: PHP Code field to build up an html string containing the image and the link. The only bit that I cant figure out is how to get the url of the image.

If i do print_r( $data); I get...

stdClass Object ( [tid] => 7
[term_data_name] => Old Edinburgh
[term_data_vid] => 2
[term_image_tid] => 7 )

And the sql query is...

SELECT DISTINCT(term_data.tid) AS tid,
   term_data.name AS term_data_name,
   term_data.vid AS term_data_vid,
   term_image.tid AS term_image_tid
 FROM term_data term_data
 LEFT JOIN term_node term_node ON term_data.tid = term_node.tid
 INNER JOIN node node_term_node ON term_node.vid = node_term_node.vid
 LEFT JOIN term_image term_image ON term_data.tid = term_image.tid
  GROUP BY tid

You shouldn't use a PHP code field, rather you can use the Image URL formatter module to create a image URL field, exclude it from display, & then use that image URL field to feed into a Global: Custom text field with your own custom img & a markup.


How do I check if a field is empty? On my views-view-field template, I would like to print out 'field_images' if 'field_cover_image' is empty.
I tried this solution here but it throws me this error message.

Notice: Undefined variable: node in include() (line 45 of /sites/all/themes/mytheme/templates/views-view-fields--incubator.tpl.php).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7539 of /includes/common.inc).

Is there any other ways to check if a field is empty or not?
Thanks!

You get that error because $node is not one of the variables passed to views-view-fields.tpl.php, which receives:

$view: The view in use.
$fields: an array of $field objects.
$row: The raw result object from the query, with all data it fetched.

Basing on the description, $row could be used to retried the node object. I cannot tell you the content of that variable, but using print_r() from your template file can help to understand its content.


A view inside another View, updated with AJAX I have a View of taxonomy terms (categories of books). This View lists all of the categories available to the user. Now I would like that, when the user clicks on the Category, a div will appear with a few books (another View, with contextual filter). By clicking on a link, I can go to the full View or to the details of the book, but if I do not click on any link, and go to another section and click on the title, I would like the earlier section to close the div, and another div with new books will appear in this new section.

The schema would be something like this:

Category 1
Category 2
Category 3

When clicking on Category 1, with AJAX there will appear:

Category 1 ---> the next part appears retrieved with AJAX

Book 1
Book 2
Book 3
See more books on Category 1 <--- END of content thrown by AJAX call.

Category 2
Category 3

I have been able to make it work without AJAX, using both modules Views Field View and Views Accordion.

However, I cannot find out how to make it work with AJAX, so no tab content is loaded it will be loaded in AJAX when clicking and opening one tab category, so the browser memory/speed/server requeriment is not impacted if I just want to see books in one category.

Views Megarow sounds like it would be ideal for this situation as it opens up a new "accordion" page in the middle of your view like you desire.

You would need to build a new view page / panel page for the parent terms which list the books. This can be done in many ways but I guess a view for /categories/%tid would be the easiest.

The benefit is that you can really do a lot of stuff inside that page.. Blocks / Comments / Multiple Views etc. along with just listing books. If you already have pages for each category, it would be a case of creating a version suitable for loading inside the megarow.

It doesn't close the last category but I guess you could get past that with some basic jQuery.


Create a Block to display Titles - even pages, view-pages, articles In my theme I need to hide the title of content, even the content-type pages and the Views page, and put it in a separate block placed in an other region than the content one.
I figured out how to pick the title from the content-type pages (plain-simple as is) but I figure some difficulties on the View Pages.

How can I hide the title of the node or the page view in the content and put in a block of another region?

Thanks for every answers!

Welcome to Drupal answers.

How hide a title? There are a lot of questions that have been answered about this topic. Here one of them.
How put the title in a block? You have different ways to achive this goal. if you only want to display the title with a content-type and the title is always in the same place, i would create a template for this content-type.

Another way to do it, you should build a module that declare a block. The content of this block(the title of the node) has to to be rebuild when a page is requested.


I want to make a news slideshow of nodes I see the module Views jQFX Nivo Slider and it's mentionned that the current slideshow is a demo of it.
I installed the module and really don't know how to make something like that with it..
Can you help me please ?

This module is a Views jQFX addon that integrates the Nivo Slider plugin with views.
The Views jQFX module is a dependency.@Anoop Joseph -- Go through modules README.txt, it explains step by step configuration


Can I add and edit a custom entity from the same URL? I am creating a custom entity called user_profile. Each logged in user will have a user profile. I want to be able to add and edit the user_profile entity from the same URL.

The example module provided at

Creating a Content Entity Type in Drupal 8

shows adding and editing with the same form but from different URLs.

I want to be able to create the profile when the profile does not exist and edit the profile when the profile does exist from the same URL like /user/3/my-profile

You can create a controller in its simplest form.

In my_module.routing.yml :

my_module.profile_controller_profile:
  path: '/user/{user}/my-profile'
  defaults:
    _controller: '\Drupal\my_module\Controller\ProfileController::profile'
    _title: 'Profile'
  requirements:
    _permission: 'edit profile'
    user: \d+

In ProfileController.php :

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\my_module\Entity\Profile;
use Drupal\user\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class ProfileController.
 */
class ProfileController extends ControllerBase {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new ProfileController object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
    EntityFormBuilderInterface $entity_form_builder
  ) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFormBuilder = $entity_form_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('entity.form_builder')
    );
  }

  /**
   * @param \Drupal\user\Entity\User $user
   *
   * @return array
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function profile(User $user) {
    $profiles = $this->entityTypeManager->getStorage('profile')->loadByProperties(
      ['user_id' => $user->id()]
    );
    if ($profiles) {
      $profile = array_pop($profiles);
      $action = 'edit';
    } else {
      $profile = Profile::create([
        'user_id' => $user->id(),
      ]);
      $action = 'add';
    }
    return $this->entityFormBuilder->getForm($profile, $action);
  }

}

You can choose to redirect after submitting the form, etc.


Site shows themeless and blockless front page I've installed a brand new Drupal 8 site (http://www.edcint.co.nz/tmp/drupal8_problem_new.PNG) with next to no configuration, default theme etc. I then ran Drupal Update against a Drupal 7 site (http://www.edcint.co.nz/tmp/drupal8_problem_existing.PNG). The content/users all came across but the front page shows without any theme or blocks, only the 3 articles/pages marked as "published to the front page" appear.

I've migrated another more simple Drupal 7 site to Drupal 8 and this did not happen.

Have I hit some limitation of the Upgrade module?
How can I make the theme and blocks reappear on the front page?

I would check your watchdog logs (/admin/reports/dblog) after refreshing your homepage a few times.

This may give you some clues to what the problem is. For example...

I ran in to a similar issue with my D7 -> D8 migration, where my nodes were imported with a 'filtered_html' input_format. I was storing my node body content as markdown.

My front page had no blocks or theme. When I looked in my logs, I was seeing Missing text format: filtered_html.

I ran the following to update the input_format of my nodes, which fixed my problem.

UPDATE `node__body` SET `body_format`='full_html' WHERE `body_format`='filtered_html';

To then get things displaying properly, I installed the markdown module (and one of the required libraries, I opted for commonmark).

drush en markdown
composer require league/commonmark

I then went to /admin/config/content/formats/manage/full_html and enabled markdown for that content type.


How to resolve notice : Undefined offset: 3 in user_node_load() I have moved my entire site and got this when I want to add content:

Notice: Undefined offset: 3 in user_node_load() (line 3604 of /storage/content/39/170239/<mysite>.se/public_html/modules/user/user.module).

Can it have to do with the fact that I have different users now on my site and that some nodes is connected to users that may not exists?
If that is the case, can I resolve this by editing my DB?

I'd guess you might be right. I think I have a different version of the user module from you (different line numbers), but user_node_load() adds stuff back in from the users table.

If you are missing a user with uid 3, you will get this error.

You probably need to update all of the nodes authored by user 3 to another user, the following SQL should do the trick (replace {new_user_uid} by the uid of the user you want to move the nodes to):

UPDATE node SET uid = {new_user_uid} WHERE uid = 3;


Is it possible to retrieve partial forms? Is it possible to retrieve only parts of a form for display, that is, only certain form elements?

I am looking at the stack for building the node form, and so far the functions I've seen work with wholesale forms, in this case the node_form.

  drupal_retrieve_form(): /.../http/includes/form.inc at line 752
  drupal_build_form(): /.../http/includes/form.inc at line 331
  drupal_get_form(): /.../http/includes/form.inc at line 123

I am interested in only retrieving (rendering) the default body field via AJAX only for a preview type of display. So far I've been successfully build and render the whole node form just using the #AJAX FAPI property and other Drupal hooks - but I was wondering if something similar was possible for just one field. Answers that point to Drupal core APIs instead of contrib modules (who may be using their own jQuery magic) are a plus.

I'm just gathering thoughts to see how I write a D7 module for this question.

This is how I might end up doing it:

When a JavaScript callback is triggered by a user editing the body field (this can be done via the #ajax property), clone current node found on form_state.
Create a render array for the whole node by using FAPI's drupal_build_form($form_id, $form_state).
Extract the body field from the render array.
Render the body field.
Return HTML to the front-end (JavaScript) so it can be placed on a preview DIV.


Form is still trying to do validation I have heavily modified an Ubercart form.

I have tried to remove the initial validation placed on this because I'm using a whole host of different fields.

For some reason, however, the validation is still getting executed.

Why would this be the case? Am I removing all sources of validation correctly?

  array_unshift($form['#submit'], 'client_mod_uc_cart_checkout_handler');
  $form['#validate'][] = 'client_mod_uc_cart_checkout_validate';

I have also tried setting $form['#validate'] to array();

However, upon submission, I get:

First name field is required.
Last name field is required.
Street address field is required.
City field is required.
Postal code field is required.
First name field is required.
Last name field is required.
Street address field is required.
City field is required.
Postal code field is required.

Why would this be the case?

$form['#validate'][] = 'client_mod_uc_cart_checkout_validate';

Will only append your function to the list of functions in the validation array.

I'm fairly certain using = array() won't work because that's how you define an array, not how you empty one.

Modified answer from Stack Overflow:

  Use unset, if you need the array later on just instantiate it again.

unset($form['#validate']);
$form['#validate'] = array();


How do I display a fixed size Views grid regardless of the number of results? I have a Views grid that can display anywhere from 0 to dozens of results. I want to display a 3 column, 2 row grid with a pager that will always show 6 cells regardless of how many results my filter gives. How do I do that? Also, I can't find the option to display the View even if there are no results. Where is that?

You can take a look at Views responsive grid.  I'd suggest using it over the built in views grid because it splits up your rows/columns in a more manageable way.

The functionality you're looking for is built into views, under pager.  You would need to set it to use a pager as well as display 6 results.

The section under Advanced -> No results behavior is what you are looking for.


Change date format "Authored on" for views with replacement pattern In Druapl 8, how can i change the date format used in a view (see screen shot)

The view uses a replacement pattern {{ created }} == Authored on

and i don’t find where to modify the format. I’ve checked :

  configuration / regional and language / date and time formats

But i don’t know how to use the custom format with {{ created }} in the view.

Could it be done in admin without modify template file ?

In Drupal 8, fields use the normal field formatters.  In your list of Fields in the View, click on Content: Authored on (Authored on).  You can change the Formatter to what you want (same choices as Manage Display on the content type configuration).  You can then configure other options, like the format.

If you already are using {{ created }} in the template, and you need it in a different format for a replacement pattern / token, then add Content: Authored on (Authored on) again to the list of Fields, but exclude it from display.  Reorder things, so this appears before the field you need it as a token.  Configure it as above.  Then, where you need the token, you should have {{ created_1 }}, which is the duplicate you just made.


I am unable to post image references I have had this module working for years. Recently, it has stopped working. I'm using Services 3 to:

Log in and get a token
Create an image file and get its file ID
Create a node, using the file ID from the previous step for the image field

The JSON I'm posting for the image field on the node is similar to the following.
   "field_image":{
      "und":[
         {
            "fid": 10279
         }
      ]
   }

Suddenly, I can't get the node I'm creating to reference an existing field via the file ID. The node and the image are created without issues, but the image field is empty.
Is there some other way I should be doing this?
This seriously worked for years, so I'm not sure what changed.
I am using the Services module 7.x-3.27.

Turns out you need a patch. Field was multi-value.
https://www.drupal.org/project/services/issues/2224803


Let custom module access private files via file_get_contents I have a custom module (Drupal 7) where I want to read the contents of a file using file_get_contents($file) in the private directory. Theres a access denied error, as the module accesses as anonymous.

I can access the file via browser via the url created with file_create_url(), but gain no access from my module.

Is there a way to grant my module the permission to open files?
Any other ideas are welcome, too.

Thanks, Marc

"Use the file system path rather than the url" - Thanks @Clive, this is the solution.


How do I attach files to nodes? I need to add files to multiple value file field using drupal rest api (restws module).
return format of restws is something like this :

"field_files": [

    {
        "file": {
            "uri": "http://drupal/file/445",
            "id": "445",
            "resource": "file"
        }
    }
],

but when I send it to http//drupal/node/<node_id> restws returns not acceptable.

Can anyone suggest which format I must use to send data to?

and second question : How can I upload files using restws module ?

For my first question:
I'm sending data with this format and it works now

{
  "field_files":[

    {
      "fid": "445"
    },

    {
      "fid":"446"
    }
  ]
}

Where fid is the id of an existing and accessible file.

For my second question, I've written module extending restws classes that user can submit data like the way user submits for services rest api.

Idea behind my module is that user submits data and module checks validation data and if data is valid saves file using drupal file_save_data function.


Problem with image width in views/ block I have a problem to set image dimension on various position. I want a 300x100px in top, 100x75px for thumbnail and other dimensions on other place. In WordPress I can just add "width" attribute to set image width, also class. Example: //img src="location" width="100" class="myclass" alt="". In drupal I can't found how to set this.

I know, I can set in image style with various dimension but too many dimensions. I think, it will increase my hosting disk.

How to set width attribute on image in Drupal block/views like [img src="location" width="value"]?

You can try hook_preprocess_image in template.php

function <THEMENAME>_preprocess_image(&$variables) {
    // If this image is of the type 'thumbnail' then assign additional classes to it:
    if ($variables['style_name'] == 'thumbnail') {
        $variables['attributes']['class'][] = 'myclass';
        $variables['attributes']['class'][] = 'yourclass';
        $variables['attributes']['width'] = 'yourclass';
    }
}

OR

function <THEMENAME>_image_style($variables) {
  $style_name = $variables['style_name'];
  //print_r($variables);
  $path = $variables['path'];
  $style_path = image_style_path($style_name, $path);
  if (!file_exists($style_path)) {
    $style_path = image_style_url($style_name, $path);
  }
  $variables['path'] = $style_path;
  if (is_file($style_path)) {
    if (list($width, $height, $type, $attributes) = @getimagesize($style_path)) {
      $variables['attributes'] = array('class' => 'fullwidth');
      $variables['width'] = '400px';
      $variables['height'] = '400px';
    }
  }
  return theme('image', $variables);
}


How to apply a distinct css class to each value of a field with multiple values? In a similar manner to views-row classes, is it possible to add a distinct css class to each value of a field where cardinality is greater than one?

Ideally I am looking for a module that does this.

A simple approach would be to use CSS :nth-child() pseudo classes.  Assuming some HTML output like:

            [CONTENT]

            [CONTENT]

            [CONTENT]

            [CONTENT]

You can target the 2nd div with css like this:

    .entity-reference-wrapper .entity-reference:nth-child(2) {
        color: green;
    }

Odd children like this:

    .entity-reference-wrapper .entity-reference:nth-child(odd) {
        color: green;
    }

There are a lot more options over at CSS tricks here:  https://css-tricks.com/useful-nth-child-recipies/


How do I Install an earlier version of Drupal 8 with composer because install fails on server with PHP 5.6? My server is using PHP version 5, therefore, I need to install Drupal 8 version 8.6.18. But when I try, composer create-project drupal-composer/drupal-project:8.x-dev my_site_name_dir --no-interaction --no-install, I get the following error.

  [InvalidArgumentException]
  Could not find package drupal-composer/drupal-project with version 8.x-dev
  in a version installable using your PHP version 5.6.40.

Is there anyway to install 8.6.18 with composer?

Drupal 8 does not support PHP version 5. It requires a minimum PHP version of 7.0. Please see here for Drupal install requirements

Drupal Installation Requirements - Drupal.org

So you will have to upgrade PHP on your machine. Also PHP 5.0 is no longer supported and is not secure. So you might want to upgrade PHP on your server any way.

PHP Supported Versions - php.net


Does hitting 'recreate' recreate the feature from the site's elements, or vice versa? Does hitting 'recreate' recreate the feature from the site's elements, or vice versa?

I tried hard looking to this in the documentation, but I couldn't find a clear explanation.

When you recreate a feature via the UI (admin/config/development/features/) or even by using drush (drush fua -y or drush fu feature_name -y) all your configuration changes regarding nodes, modules, blocks, themes etc are being extracted to the corresponding feature directory. Configurations from different modules are saved to different files. In order to apply your changes to another Drupal instance you have to do it the other way around drush fra -y or drush fr feature_name -y and your changes will be stored to the database.

In case that you want to revert some settings back to their initial state, before you move them to another Drupal instance you can do the following: edit and save the appropriate file that you want to revert and then use drush to apply the changes from your files to the database. Thus you'll have your site back to its former state.


How do I use a drush alias to connect to a docker container? I have a droplet setup on Digital Ocean with two docker containers, one for Drupal (using modified alpine-drupal8 image) and another running a simple mysql server.

I am able to run drush commands on this container by connecting over ssh into the droplet and running docker exec -it <container_name> /bin/sh
I have also set up an ssh server (listening on port 2222 on the same ip address) on the container itself with a little port forwarding:

ssh root@<droplet_ip> -p 2222 # Connects from remote dev machine to drupal container using ssh key

My sites/default/drush/aliases.drushrc.php file:

<?php

$aliases['container'] = array(
  'root' => '/usr/share/nginx/html',
  'uri' => 'http://default',
  'path-aliases' =>
  array (
    '%drush' => '/usr/local/bin/drush',
    '%site' => 'sites/default/',
    '%files' =>'sites/default/files/',
    '%modules' =>'modules/'
  ),

  'remote-host' => '<droplet_ip>',
  'remote-user' => 'root',
  'ssh-options' => '-p 2222',
);

?>

Starting an ssh session with the drush alias is working:

$ drush @container ssh
186203cca:/usr/share/nginx/html# ### Connected to ssh session in droplet
186203cca:/usr/share/nginx/html# which drush
/usr/local/bin/drush
186203cca:/usr/share/nginx/html# drush status
 Drupal version                  :  8.1.8
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  <removed>
 Database port                   :  <removed>
 Database username               :  <removed>
 Database name                   :  <removed>
 Drupal bootstrap                :  Successful
 Drupal user                     :
 Default theme                   :  <removed>
 Administration theme            :  seven
 PHP configuration               :  /etc/php7/php.ini
 PHP OS                          :  Linux
 Drush script                    :  /usr/local/bin/drush
 Drush version                   :  8.1.3
 Drush temp directory            :  /tmp
 Drush configuration             :
 Drush alias files               :
 Install profile                 :  standard
 Drupal root                     :  /usr/share/nginx/html
 Drupal Settings File            :  sites/default/settings.php
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  /tmp
 Sync config path                :  sites/default/files/config_vxs7qxuAqrfCtOXdbGYLvLAIKl1_bN4J_BvmrEn1l1EUIsn4Du_CKck2QWYSmkNDgUVfdZUZVQ/sync

However, I still can't seem to run actual drush commands:

$ drush @container status
env: can't execute 'drush': No such file or directory

My theory is that the port forwarding is not working correctly, and drush is trying to run on the container, not the droplet

This may be related to my issue: Why does drush say "command not found" when I try to execute remote commands?

Update:

A little more testing and I found out I can use drupal console without issues, so it seems this is isolated to drush only:

$ drupal @container cr all

 Rebuilding cache(s), wait a moment please.

 [OK] Done clearing cache(s).

So this one threw me for a while this evening as well.

Here's what ended working:

$aliases['docker'] = array(
  'uri' => 'http://localhost:8080',
  'php' => '/usr/bin/php',
  'root' => '/var/www',
  'remote-user' => 'root',
  'remote-host' => '0.0.0.0',
  'ssh-options' => '-p 8022 -o PasswordAuthentication=no -i ~/.ssh/id_rsa',
  'path-aliases' =>
  array (
    '%drush' => '/root/.composer/vendor/drush/drush/drush'
  )
);

The remote host of 0.0.0.0 ended up doing the trick. Seems that if you use localhost or 127.0.0.1 drush doesn't actually try to ssh in.


How to render comments at the top and the comment form at the bottom? I'm trying to display the comments on a node at the top of the page. I've edited node.tpl.php in my theme to be:

<article id="article-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print $unpublished; ?>
  <?php print render($content['comments']); ?>
  <?php print render($title_prefix); ?>
  <?php if(!empty($user_picture) || $title || (!empty($submitted) && $display_submitted)): ?>
    <header class="clearfix<?php $user_picture ? print ' with-picture' : ''; ?>">

      <?php print $user_picture; ?>

      <?php if ($title): ?>
        <h1<?php print $title_attributes; ?>>
          <?php if ($page): ?>
            <?php print $title; ?>
          <?php elseif (!$page): ?>
            <a href="<?php print $node_url; ?>" rel="bookmark"><?php print $title; ?>
          <?php endif; ?>

      <?php endif; ?>

      <?php if ($display_submitted): ?>

        <?php
            //By:   Mike Ghen
            //Date: 5/21/2012
            //Description: This Modifies the submitted user and date info.
            //             Code from: http://drupal.org/node/1072640
            if ($submitted) {
                echo "Submitted on " . date( "F j, Y",$node->created);
            }
        ?>

      <?php endif; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <div<?php print $content_attributes; ?>>
  <?php
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>

  <?php if ($links = render($content['links'])): ?>
  <?php endif; ?>

I moved <?php print render($content['comments']); ?> to the top of the page but, it makes the form to fill out a comment appear at the top of the page as well. Is there a way to render the comments at the top and the comment form at the bottom?

you attack this line in file :

<?php
    // Remove the "Add new comment" link on the teaser page or if the comment
    // form is being displayed on the same page.
    if ($teaser || !empty($content['comments']['comment_form'])) {
      unset($content['links']['comment']['#links']['comment-add']);
      unset($content['links']['comment']['#links']['comment-comments']);
            unset($content['links']['comment']['#links']['comment_forbidden']);
    }
    // Only display the wrapper div if there are links.
    $links = render($content['links']);
    if ($links):
  ?>
    <div class="link-wrapper">
      <?php
      hide($content['links']['comment']['#links']['comment-comments']);
      print $links;
      ?>
    </div>
  <?php endif; ?>


How to make node hierarchy with siblings and child pages I want to make a node hierarchy menu which will display the child pages and siblings if child pages don't exist. I want to have the following structure

parent
   child
   child
   child
or

parent
   sibling
   sibling

You will need to create a entity reference field to find the parent node. On each child select the parent it belongs with.

In Views you can then create a "menu" by using views field views and passing the parent (content ID) argument into the child view.

In your parent view filter, make sure and filter by Parent is Empty to show only parents if there are no children.

On your child view, make sure Context has the entity reference to the parent.


Drupal 7 Date - Is there a way to change field settings if there is data in it already? Currently I am using the date module for drupal 7 and I already have stored data in the existing date field. I want to make changes to the date field by adding "Repeating Dates", but obviously I cannot since I have data in there already. The options I came up with are:

Create a completely new date field for the content type with the additional "Repeating Dates" feature. Then copy all the old dates into the new field (im not sure how to do this easily)
Modify the existing Date field table via phpmyadmin or mysql console.

What is the suggested way to go about updating an existing field that already has data?

I got this working by doing the following without having to write any code. Keep in mind im only doing this for the DATE type fields:

example:

my old field: field_eventdate

my new field: field_placeholder

create the same field type with a different name and the options you want.
open up phpmyadmin
goto the table: field_config
search for the new field you created (field_placeholder)
click on the data column blob and download that.
search and edit field_eventdate and upload the file you downloaded which contains the new settings.
do the same exact thing for the table: field_config_instance
now we have to update the table structures of the field to encompass these changes. I first inspected the strucuture of the new field i created and see what the old table was missing. Once you have that down, create the missing columns in the old field that exists in the new field.
Do #8 again but this time for the revisions table. In my case it would be: field_revision_eventdate
delete the field_placeholder via the content type page as you wont need it anymore.

let me know if this worked for anyone else too.


Is there a drupal 7 equivalent to the Country Ban module? I'm wondering if anyone has a Drupal specific solution for blocking entire countries from accessing your server. My company only does business in the US so there's no point in having other countries accessing my site.

For Drupal 6, there is the Country Ban module.  Is there a Drupal 7 was to do this?

this module may help you : Smart IP ,,,,

  Overview Smart IP identify visitor's geographical location
  (longitude/latitude), country, region, city and postal code based on
  the IP address of the user. These information will be stored at
  session variable ($_SESSION) with array key 'smart_ip' and Drupal
  $user->data object with array key 'geoip_location' of the user but
  optionally it can be disabled (by role) .....


add link to edit content in admin top bar I'm theming a web site that I haven’t created and I‘ve noticed this useful link placed in admin top bar (see screen shot) :

It provides link to edit / delete content.

How can I place this link on other website ?

I use Admin Toolbar + Adminimal Admin Toolbar with Adminimal 8.

Actually, I have the native menu and it is quite disturbing when you work on theming because it is placed inside content.

That looks like the "shortcuts" menu tab which comes natively in a D8 installation but if you're looking to add your own custom shortcut menu (& menu items) you might want to look into the hook_toolbar: https://api.drupal.org/api/drupal/core!modules!toolbar!toolbar.api.php/function/hook_toolbar/8.2.x

You can build a quick custom module to establish your own links and configurations. Hope I answered your question!


Non-Members of Organic Group can still view Node links I'm on Drupal 7 with Organic Groups installed.  I've created a Private Group for my IT Team, meaning that only members of that group can see the group content.

The problem I'm seeing is that when I publish group content, Non-Members can still see the node link from the homepage, and click on it, even though the content is not displayed.

How can I make group content only visible to group members?  (Meaning, the node itself is not visible to non-members.).

Please allow me to offer helpful insights even 6 months after your posted question.  Hopefully, this will help others who are struggling with the Drupal module OG as well.

Note that in your content type, you should already have bundled Group content visibility as another field.  Go to /admin/config/group/fields to accomplish this:

In this picture as my live example, note that my Content Group is the Group content type and that the Content Group Submission is the content type FOR hosting articles that should only be visible to any particular group.  What you need to do is bundle Group content visibility as a new field for this content type as shown below.

This means that you will have Group content visibility field as an additional field to your own content type.

The Groups audience field is meant to make content authors specify the intended audience of the content they are authoring.  The Group content visibility field is meant to make content authors specify the exposition criteria of that particular content.  This is best shown in the following two pictures.  Let us now look at the field set of my content type Content Group Submission.  In my example, I went to /admin/structure/types/manage/content_group_submission/fields.

If you edit this field, you will see its values to be constrained to the following options by default:

- None -,
Use group defaults,
Public,
accessible to all site users

and Private -
accessible only to group members.

The last one appears to be what you are interested in.  You should make that as your default value for this field.

Save all of that.  And your content authors will be offered with these options.  In my case, go to /node/add/content-group-submission.

And this is how your content authors would be able to constrain your article's exposition to only his/her intended groups.  By this method, non-group members would not be able to see nor access the nodes (even titles only) that are intended for private groups where they do not belong.


Change Ubercart shipping/billing layout & logic? I'm selling some tickets for a concert online with Ubercart, and I give people the option of holding the tickets at Will Call, or mailing them out for $1.

The customer's workflow when they're checking out looks a little wonky right now. The first set of address fields is the Shipping Address, then they can click the checkbox to indicate "My billing information is the same as my delivery information." But for a Will Call person, that feels backwards. They shouldn't need to enter a shipping address at all.

Is there a way to put the Billing Information first, and only expose a Shipping Information block when it's needed?

Seems like the same question would pertain to an electronic delivery situation too - but in that case you'd also be generating download links, etc., which I wouldn't need.

Thanks.

(Note - I also posted this question yesterday on ubercart.org's forums, but it looks like traffic there is very slow, I'm wondering whether this is a better place for it.)

You can change the order here:

admin/store/settings/checkout/edit/panes

But you cannot dynamically determine whether the shipping is required. (at least not without tweaking the code.)

Do you really need to offer both anyway? (how often person A buys tickets that need to be sent to person B?)


where to find html code of a page I am using Opigno (a LMS based on drupal) and I want to edit a page. I am looking for its HTML but when I open the code for the page this is what I found.

<?php print render($page['content']);
<?php print render($page['content_bottom']); ?>

I try to use print_r function in PHP and it displays an array of stuff.

How could I change the page if it is from php.

Thanks!

I have never used Opigno but since it's based on Drupal, I'd say that you should change/edit the content of a page from its corresponding form once you're logged in.

If you want to edit the HTML, than you have to look for the page templates in your theme folders. This link may help you: https://www.drupal.org/search/site/theme%20template


Avoid sql-drop or sql-sync drush commands in a particular environment I'm syncronizing databases form stage to local environments with drush commands like:

drush @dev sql-drop
drush @stage @dev sql-sync

How can I protected that the @stage server reject to drop or sync its database like:

drush @dev @stage sql-sync
drush @dev sql-drop

I think this is a common problem, maybe there is some params that can be set in drushrc.php file. How can I manage that? Thanks!

This is best done with a policy file.  See policy.drush.inc, which has an example policy prohibiting overwriting a production server.

The example could be expanded to perhaps check for patterns in the destination parameter (any alias containing 'prod'), etc.


Inserting a select box before the search box (Drupal 7) I am pretty new to Drupal dev world. I wanted to know how to insert a select box before the search box. I used the below code to alter the search form and set the #weight to a higher value but the select box still shows up after the search box.

function mymodule_form_search_block_form_alter(&$form, &$form_state) {
  $form['my_field']= array(
    '#type' => 'select',
    '#title' => t('whatever'),
    '#options' => array(
      0 => 'option1',
      1 => 'option2',
    ),
    '#default_value' => 255,
    '#weight' => 10,
  );
}

If you need the form field to be placed before any other form field present in the form, you need to use, for the weight, a lower value than the one used from the present form fields. The default value is 0; use a negative value to be sure the form field is always shown first (e.g. −200).

search_box() doesn't use any value for the field's weight, which means the default value is used.

  $form[$form_id] = array(
    '#type' => 'textfield',
    '#title' => t('Search'),
    '#title_display' => 'invisible',
    '#size' => 15,
    '#default_value' => '',
    '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );
  $form['#submit'][] = 'search_box_form_submit';

I have used the following code in a test module.

function code_testing_form_search_block_form_alter(&$form, &$form_state) {
  $form['my_field'] = array(
    '#type' => 'select',
    '#title' => t('whatever'),
    '#options' => array(
      0 => 'option1',
      1 => 'option2',
    ),
    '#default_value' => 255,
    '#weight' => -200,
  );
}

The search form appears as in the following screenshot.


Why does "my blog" menu link disappear when I use a view with the path blog/%? When I create a view with the path blog/%, the menu link "My blog" disappear from the main menu but still exists in the database. The view works exactly as expected when I go to /blogs and click the nav link at the bottom of the article.

Already tried without success (logged in as administrator)

1) Change view access to:

none
permission: view published content
permission: blog entry:
create new content role: authenticated users

2) Add/Remove the view filter: status published

3) Create a new menu link using Menu Token module but this link disappears too (but still exists in the db).

4) Enable/disable Menu Token and Menu item visibility modules, just to check if there is a conflict somewhere but it doesn't change anything.

Versions:

Drupal 7.31
Blog 7.31
Views 7.x-3.8.
Menu Token 7.x-1.0-beta5
Menu item visibility 7.x-1.0-beta1

The path that the blog module uses is blog/%user .

If you go to blog/1 you will see all posts made by the user with uid equals 1.

So, when you create a views:view that defines the path blog/%, it overrides the default path previously defined by blog and uses the views path.


How to tell the difference between multiple image_buttons on the same form? Using FormAPI to create a simple set of three image_buttons, in the form_submit handler there is no 'op' value set in $form_state and therefore no way to tell which image_button was clicked. Is this a limitation of image_buttons?

Here's what I used to create the form, and it's bare-bones submit handler that shows no information telling me which button was clicked:

function cex_dash_top_icons_block_form( $form_state ) {
  $form = array();
  global $base_url;
  $projects_icon_path  = '/'.drupal_get_path('module','cex_dash').'/Projects-icon-med.jpg';
  $reporting_icon_path = '/'.drupal_get_path('module','cex_dash').'/Reporting-icon-med.jpg';
  $help_icon_path      = '/'.drupal_get_path('module','cex_dash').'/Help-icon-med.jpg';

  $form['projects'] = array(
    '#type'  => 'image_button',
    '#value' => 'Projects Dash',
    '#src'   => $projects_icon_path,
  );

  $form['reports']  = array(
    '#type'  => 'image_button',
    '#value' => 'Analytics Dash',
    '#src'   => $reporting_icon_path
  );

  $form['help']     = array(
    '#type'  => 'image_button',
    '#value' => 'Documentation Dash',
    '#src'   => $help_icon_path
  );

  return $form;
}

function cex_dash_top_icons_block_form_submit($form_id, &$form_state) {
  _devReport( 'cex_dash_top_icons_block_form_submit: form_state is "'.print_r($form_state,1).'"' );
}

And no matter which button is clicked, $form_state['values'] looks like this:

[values] => Array(
  [projects] => Projects Dash
  [reports] => Analytics Dash
  [help] => Documentation Dash
  [form_build_id] => form-b6c762d22d0fd2360d1804ef19043c7d
  [form_token] => 4f0ce5275cc923e8fb27c305b57bf414
  [form_id] => cex_dash_top_icons_block_form
)

Now, in the larger $form_state array there is a 'clicked_button' array, but that always only has the information for the last image_button.

Do I need to create one mini-form for each image_button?


Overriding page.tpl.php for a menu_hook page I am trying to override template for a custom page I have in hook_menu.

 $items['announce_your_new_products'] = array(
    'title' => 'Announce Your New Products',
    'description' => 'Announce New Products.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('announce_new_product_form'),
    'access arguments' => array('access content'),
    'file' => 'view_new_products.pages.inc',
    'type' => MENU_CALLBACK,   );

I have read to override a specific node's page template is page--node-[nid].tpl.php and page--announce_your_new_products.tpl.php, with and without underscores, but since this doesn't have a nid I was hoping someone could point me in the right direction on how to achieve this.  I have tried page--node-announce_your_new_prodcts.tpl.php but it doesn't seem to work. Thank you.

You wouldn't need node- at the beginning of your template file name as your path isn't a node page. Going off the Drupal 7 Theme Hook Suggestions, the file should be called:

page--announce_your_new_products.tpl.php

If that doesn't work, try:

page--announce-your-new-products.tpl.php

Unfortunately the docs aren't very clear on which way will work.


Use single values added by field-collection module in Views? I've already found this question, but it doesn't really help me out, maybe I just don't understand it (I've got the latest version of the module). How to integrate Field collection module in Views?

I have my own content type called "Gallery", for this, I created a field-collection which consists of an image and caption. Now I try to create my own view, first one, only to show the thumbs, and then one, showing the big image and the caption.

But how can I access only one field of the field-collection? I can find this field:
Content: Gallery and caption
or this one:
Content: Gallery and caption:delta (Gallery and caption (field_gallery_and_caption:delta))

but how do I access only the image field? and which type of display should I select?

I've recently done this before. It's really easy, you can create a Node type view. Then you just add the field collection field that's attached to your node as a Relationship, in your case "Content: Gallery and caption".

Then after you've added the relationship, when you click "Add" on the fields, your field collection fields will be available to select. Their names will start with "Field collection item: *".

If you're using Node reference field inside your field collection then you need to add one more relationship. See this issue and #2 comment for solution.


Content type field with term reference or users I have "People" content type that has some fields; one of those is "field1," which is a term reference, and uses an autocomplete widget.

How can I display only "Users" registered with particular roles in the term reference with the autocomplete?

I need to display it on http://example.com/sitename/admin/config/people/accounts/fields.

I am displaying any view or content here; this is where administrator users add the fields to the user accounts and in the "field1". How can I display or list only ["username" with respective to "roles"] or ["username"]?

If you install References and Views, you should be able to use a view to determine which content/terms/etc. are shown. These settings appear on the field settings page for the Term Reference.


After moving a new server, one of 2 Drupal sites, has no css loaded I moved 2 sites from a shared server to a VPS. One works just fine with a custom theme, but the second doesn't have the Bartik CSS loaded.

Both sites moved via the user root and as it seems almost all of their dirs are 755 root root.
Temporary files dir is /tmp
manual cache flush from from DB doesn't change anything.

Something wierd I noticed and don't know to solve is the fact I can't disable CSS or JS aggregation. Maybe this reflects the core problem?

This sometime happens if Apache server is not able to write files or directory.

Since you mentioned you moved using root user, Apache server may not be running on root user.

To further clarify this: If the inodes of both sites have the same permissions, ownership, grouping, but only one works, it's because it doesn't have CSS and JS aggregation on (a thing that requires an Apache user --- that is, www-data ownership and grouping, that you should apply).

You could either turn off CSS and JS aggregation for the non working site (and then it'll work), or make sure you give both sites such ownership and grouping if you want both of them to work properly with CSS JS aggeregation.

If at least for now you just want to turn off CSS JS aggregation, read here how to do so, but for troubleshooting this (and take care of the root cause), read the following (you might want to precede it with this piece of data on the aforementioned Apache user):

First check on which user apache server is running. Finding out what user Apache is running as?
Change your tmp folder and files folder ownership to that user so that it is writable by Apache.Giving ownership of the directory to the apache user?
Make sure you have tmp directory created in your files folder and is writable by Apache server. You can define it your Configuration > File System