Crop Profile Image on upload I come across different type of image crop, but the only one seems to work on the profile image is Image Javascript Crop like says this answer.

The problem so far is that i need to crop the image on upload.
I can't find any way. Is there any way?

The Imagefield Crop module allows a user to crop the image after upload.
Here is a quote about it (from the module's project page):

When the user uploads an image, the image is presented inside a cropping area. A cropping box is shown inside, and the user can resize and move it. Upon clicking 'preview' or 'submit', the image is cropped and the result is saved instead of the original image.
Features:

Seamless, intuitive cropping, almost like using a desktop photo editing app
All major browsers supported
Dynamic preview - you see how your crop will look like, in real time!
Original image is saved for recropping.
No matter what resolution the cropping area is, the original image is used for cropping (for highest quality)
The sizes of the cropping area, cropping box and resulting image can be controlled by the administrator


How to migrate Link Fields ('title' and 'url') involving local variables? I have performed the following query:

$query = db_select('sage.USER', 'USER')
  ->fields('USER', array('USER_ID', 'OFFICE_ID', 'USER_PASSWORD'))
  ->range(0, 1);
$result = $query->execute();
...
$url = '/sage/office-' . $result->office_id;
$arguments = MigrateLinkFieldHandler::arguments(array('source_field' => 'office_id'));
$this->addFieldMapping('field_office_id', $url);
  ->arguments($arguments);

However, the above is not working. I would like to manipulate the 'office_id' field to be used as the 'title' and the variable $url to be used as the URL that was linked. I have followed what's on this post

Could someone please point out my mistakes?

EDIT: Updated question to reflect jdu's answer.

The link.migrate.inc file is not included in the Migrate Extras module, it's part of the Link module.

The file doesn't exist in the stable version of Link, but it does exist in the dev release. I think you're going to have to install the dev version of Link if you want this to work.

If you install the dev version and still get the error it's most likely because the file is not being automatically included. If that's the case try adding this to the top of your code:

module_load_include('inc', 'link', 'link.migrate');

EDIT

As I mentioned in your other question there's a slight error in your code, you should change this line:

$result = $query->execute();

to:

$result = $query->execute()->fetchObject();

That will return an object representing the first result that was returned by the query.


How can I get rid of the paddings and margins that come with the webform? What I did was use position: absolute to have them the way I want, but that is probably not a good idea. I tried to put padding and margin 0 everywhere, but Drupal seems to override my CSS or something.

You can override Drupals styling rules. Just use your browsers (Chrome, Firefox) developer tools to inspect elements for whats styling rules they have. Then override them in your themes stylesheet(s).


How to re-create vanilla field configuration strings programmatically for any field? After a D7 update and migration of fields, most of our problems with converted fields result from invalid or incompatible field settings. Field settings are stored in the
field_config_instance.data column in the database as serialized php objects.

How can I, for any given field instance, generate a fresh field configuration string, as if the field was just created in D7, while leaving the already stored field data intact?

My manual approach seems to work but is very cumbersome:

create a new content type
add an existing field to the new content type, generating new settings string
search the new and old field in the database
using sql: replacing the string in the data column of the old field (with the same name) with the new data content.

There must be a way to automate this a bit.

I guess you will need a combination of field_update_field() and field_create_field().

During field_create_field(), the settings are loaded from the default field definition as each field has defined in its own hook_field_info().

$field['settings'] += field_info_field_settings($field['type']);

What you are looking for is to apply this logic to field_update_field().

Basically you will need to load all fields:

$fields = field_info_fields();

Optionally limit the fields to your selection:

foreach ($fields as $field_name => $field) {
  if ($field['type'] == 'some type') {} // Filter by type
  if ($field_name == 'some name') {} // Filter by name
}

And update the fields:

$field['settings'] = field_info_field_settings($field['type']);
field_update_field($field);

So I guess it should look something like this:

$fields = field_info_fields();
foreach ($fields as $field_name => $field) {
  if ($field['type'] == 'some type') {
    $field['settings'] = field_info_field_settings($field['type']);
    field_update_field($field);
  }
}


Render a field from an entity reference in twig template? I have a node that has an entity reference field to a Media entity. That media entity has a field on it "caption". I want to render this caption directly in my twig template, so instead of doing this:

{{ content.field_media_item }}

Which would output the entire rendered media entity, I just want to output a field from that media entity. I've tried this:

{{ content.field_media_item[0]['#media'].field_caption.value }}

Which works, but since it's already rendered output, all the HTML from that value is escaped. So <p> tags appear as literal <p>. I could tack on a |raw at the end, which actually seems safe to me since I know the output has already been rendered and passed thru the field formatter, but seems wrong?

What's a better way of doing this? Using a pre-processor to access the field data from the reference media entity and passing it through a field formatter again or something? That actually seems inefficient since the caption field data was already rendered properly, and I'd be passing it thru the formatter again.

After some more thought and research, I think the best approach to this problem is to use a theme pre-processor function to manually prepare the entity reference field.

The main issue is that the referenced entity has a formatted text field that I need to output. That means it needs to run through the formatter before it's considered safe for output.

Manually accessing the value through the entity object in Twig is not a good solution because it will just print the raw value from the database, which twig will by default escape. Tacking on |raw makes it unsafe because it still hasn't run through the text processor.

Here's a preprocessor snippet that does what I need:

/**
 * Implements hook_preprocess_node().
 */
function MY_THEME_preprocess_node(array &$variables) {
  $node = $variables['node'];
  if ($node->bundle() == 'news') {
    // Extract the caption from the cover image media entity and prepare it manually. We do this because in our template, we render the caption separately from the image.
    if (!$node->field_news_cover_image->isEmpty()) {
      $image_media_entity = $node->field_news_cover_image->entity;
      $caption_field = $image_media_entity->field_media_caption;
      // Caption is formatted text, so we must output a render array that will
      // process the text with the appropriate filter.
      $variables['cover_photo_caption'] = [
        '#type' => 'processed_text',
        '#text' => $caption_field->value,
        '#format' => $caption_field->format,
        '#langcode' => $caption_field->getLangcode(),
      ];
    }
  }
}

This allows me to simply print {{ cover_photo_caption }} in the twig template.


How to use database BETWEEN query? I need to fetch the database records for particular date using database query , i tried some queries to fetch but it showing all records in table .

controller.php

public static function load($entry = array()){
$maxDate = \Drupal::request()->query->get('set_start_date');
$minDate = \Drupal::request()->query->get('set_end_date');
 $select = db_select('pastpayments', 'x');
 $select->fields('x');
 foreach ($entry as $field => $value) {
 $select->condition('paiddate', $maxDate, "<=");
 $select->condition('paiddate', $minDate, ">=");
}
 return $select->execute()->fetchAll();
}

public function entryList() {
$content = array();

$content['message'] = array(
  '#markup' => $this->t('Generate a list of all entries in the database. There is no filter in the query.'),
);

$rows = array();
$headers = array(t('Member Id'), t('Name'), t('Paid Date'), t('Paid Date'));

foreach ($entries = $this->load() as $entry) {
  // Sanitize each entry.
  $rows[] = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', (array) $entry);
}
$content['table'] = array(
  '#type' => 'table',
  '#header' => $headers,
  '#rows' => $rows,
  '#empty' => t('No entries available.'),
);
// Don't cache this page.
$content['#cache']['max-age'] = 0;

return $content;

}

  how  i can fetch the table records for particular date ranges

database query

mysql> select * from pastpayments where paiddate >='2017/03/01' and paiddate <='2017/03/30';

You can use BETWEEN like this:

$query->condition('myfield', array(5, 10), 'BETWEEN');

In your case:

$query->condition('paiddate', array('2017/03/01', '2017/03/30'), 'BETWEEN');

For more information see the Conditional Clauses documentation.

It depends on how your dates are stored as to what min and max values you should pass in.

For example it could be a unix timestamp or it could be an actual date.
I would recommend doing a more generic select on the data to find out the format of the dates and then replicate that format in the values that you are passing in.


Adding to that list of display options that includes "Default" and "Teaser" Under structure > content types > manage fields, there are display options in the upper right. The system-defined ones are "default" and "teaser" but I have seen "tokens" and "colorbox" added by contrib modules.

What hook or function do I use to give my modules access to create these new content type displays?

You can either use the Entity View Mode module (which lets you define new view modes through the UI) or you can use hook_entity_info_alter() in a custom module to create them through code:

function MYMODULE_entity_info_alter(&$info) {
  $info['node']['view modes']['some_view_mode'] = array(
    'label' => t('Some View Mode'),
    'custom settings' => TRUE,
  );
}

The 'custom settings' bit is defined like this in the hook_entity_info() docs:

  A boolean specifying whether the view mode should by default use its own custom field display settings. If FALSE, entities displayed in this view mode will reuse the 'default' display settings by default (e.g. right after the module exposing the view mode is enabled), but administrators can later use the Field UI to apply custom display settings specific to the view mode.

Basically you want to set the to TRUE to have the view mode show up on the manage fields page.

Using either of those methods you should see your new view mode(s) pop up everywhere (the manage display form for nodes, in views, etc.)


Processing data sent from drupal 7 webform I've inserted a webform in a node's template like so:

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

and created the webform in the admin panel for that page. The form shows up fine and I've styled it correctly. I would now like to know the Drupal way of grabbing the data from the form. Most likely a preprosses function from what I've researched.

The form is very simple, just an email address and a submit button. I'm good with PHP but still getting used to drupal's backend functionality.  Any help or direction is greatly appreciated. Cheers!

I am not clear about your question. But here is the answer from what i understood.

Try creating a new module and use the hooks to process the data
http://api.drupalize.me/api/drupal/group/webform_hooks/7


What's the best infrastructure to set permissions to user roles that controls who can see which Nodes and which Views? I'm building a bsite that needs pretty stringent permissions. I have already created the (4) user roles for the site, but not sure the best way to handle viewing permissions.

I see that when creating Views it is pretty simple to assign which roles have permission to view, but what about for my content that is straight up page/nodes?

I was able to accomplish this using Permissions By Term (https://www.drupal.org/project/permissions_by_term). After I installed, I completed the following steps:

define member/student/guest roles in People > Roles
define Taxonomy structure (I named the vocabulary 'Page View Permissions')
In order to apply these permissions to Basic Pages, edit the Content Type of Basic Page to add section to set the permissions when creating a Basic Page. (Create new Entity Reference field.) Set default to Public.


webform css styling twig email Is it possible to add inline css styling to a twig email template? Not as a source file reference but by inclusion of css within the template similar to html <style>...</style>functionality.

For HTML emails, you have to use the inline style attribute.

The Mimemail module might be able to inline your external CSS.


How to return Views Field Value in Twig Template How do I return a field value from Views when using a Views Relationship?
Im using views-view-fields--pagedisplay--html.twig

fields.title.content

seems to return titles but

fields.field_movie_length.content

does not return any vales, however the field exists if I

{{ dsm(fields) }}

I have Twig Tweak & Twig Feld Value modules installed also.

Views templates don't work like field templates, so the modules you have installed won't help. Though you can use node and field templates by switching the Format of the View to Content instead of Fields or you can configure a single field to use a field template in STYLE SETTINGS.

If you want to use the views templating system you might consider switching to the format Table, because this template has the most options.

The template you have now has very limited options. The field array is exactly the output you have configured in Views UI and this is the place where you should apply your adjustments.

After all of that, if you still want to see which fields and their content are delivered to your template, then use this loop for debugging:

views-view-fields.html.twig

{% for key, field in fields %}

{{ key }}: {{ field.content }}

{% endfor %}

field.content is finally rendered html, so you can't do much with it. The array keys contain the field names of the fields you have selected and arranged in the FIELDS section of the Views UI. It doesn't matter whether the fields come from relationsships.


Webform export to CSV programmatically I'm looking to write a module that automatically uploads the submissions of a webform to an ftp server every week or so.

I'm looking for the recommended way to use the CSV export plugin that comes with the WebForm module to render a csv file to a string. I would want to set the following options:

separator (default is , but should be ; because Europe)
start date and end date of submissions (weekly export)

I see there are a lot of classes and configuration options available, but I'm not sure about the best way to string them together to achieve what I need.

After looking at the drush webform-export code I came up with the following code sample.
It appears to work, however jrockowitz advises me that using drush straight up should be the best solution. I'm sure there's something wrong with the following code. For one, it probably breaks when the export is too large.

$webform_id = 'easykit_vip_formulier';
$webform = \Drupal\webform\Entity\Webform::load($webform_id);
$submission_exporter = \Drupal::service('webform_submission.exporter');
$export_options = $submission_exporter->getDefaultExportOptions();

$export_options['delimiter'] = ';';
$export_options['multiple_delimiter'] = ',';
$export_options['range_type'] = 'date';
$export_options['range_start'] = '2018-02-18';
$export_options['range_end'] = '2018-02-26';

$submission_exporter->setWebform($webform);
$submission_exporter->setExporter($export_options);
$submission_exporter->generate();
$file_path = $submission_exporter->getExportFilePath();

print file_get_contents($file_path);

unlink($file_path);


Link module output with content type I am confused on how to output links from a content type into a list in HTML. Currently I have the following code.

<div class="lenders-block-content clearfix">
  <ul>
    <?php print render($content['field_link']) ?>
  </ul>
</div>

The output just adds the links back-to-back within an <a> tag.

Is there a way to render the links so its outputted within a <li> tag?

I am using multiple links. When adding a content type you can add up to ten links.

As you mentioned in the comments you field is multivalue field so you should loop over it and render the item inside
 tag something like the following:

      <?php foreach ($content['field_link'] as $key => $link):?>
      <?php if (is_numeric($key)): ?>

 <?php print render($link) ?>

      <?php endif;?>
      <?php endforeach;?>


conditional removal of a field in a view I'm displaying the latest 5 nodes (teaser view mode) in a sidebar region using views. The nodes have an image field but I only need to render that on the first node on the list.

So, since the teaser view mode does include the image, I'm trying to remove the image from all nodes apart the first upon rendering.

I've tried the following in my theme's template.php:

function foo_preprocess_views_view(&$vars) {
  if (isset($vars['view']) &&
      isset($vars['view']->style_plugin) &&
      isset($vars['view']->style_plugin->row_plugin->nodes)) {
    $first = true;
    foreach($vars['view']->style_plugin->row_plugin->nodes as $node) {
      if (!$first) {
        unset($node->field_image);
      }
      $first = false;
    }
  }
}

But the image is still being rendered. I think that this has to do with the fact that I'm trying to temporarily remove the image from the wrong datastructure which represents the node state.

I then tried using the hook_preprocess_node with something like:

unset($vars['field_image']);

But it still has no effect. The image was still there.

How is this solved? And at which layer is it solved best?

I know I could simply hide via CSS by using the .views-row-first class but I don't think this is optimal.

Take a look at Views Nodes Split. Module Monday: Views Nodes Split gives more information about how to use the module.

  Setting up the module is simple: just turn it on, and build your View as you normally would. Then, click on the View's Format option and select the newly available "Splited Content" row style. While the grammar is awkward, the results are great: you can specify separate build modes and display styles for the first node and all subsequent nodes from a simple config screen. In fact, you can even adjust where the cutoff happens: you might want the first three nodes to display in full, for example. No other changes are needed for your View; this module's new row style handles the rest.


Superfish Menu in 2 Columns I am using superfish menu in my website as a main horizontal navigation. on mouse over some links the drop down menu opens and it but due to lots of links its getting very long verticaly. Is there a way through CSS we can divide the first drop down menu into 2 columns. my website link is http://go2georgia.travel

Just about the time you posted your question, the new Superfish features showed up in beta.  These features include a multi-column capability. You would want to use CSS to style it, but the multi-column capability comes through the configuration panel.

There is a nice tutorial here:
http://www.digett.com/blog/02/19/2013/superfish-mega-menus

Pay special attention to the limitation: the multi-column nature of the menu is enabled for the entire menu, and you have to explicitly indicate any menu items that are to be excluded.

Presently, the dev version is the most highly recommended by the developer, but leave yourself a way to back out, in case you hit a problem.

Also, pay close attention to the instructions for upgrading to v1.9

d


Drupal 6: Allow external site to authenticate via Drupal How would I allow a simple PHP site, which already has a user db, to let Drupal handle the logging in of users? I guess I could use services (but I would need help on this) or alternatively is there some way that users are passed to the Drupal login form to log in, but the simple external PHP site knows, through some kind of cookie arrangement, that the user is logged in?

The main priorities are that the user should only have to log in once for both sites, and the existing users on the external site can be maintained and transitioned smoothly. I want Drupal as the main user db because it's more secure and I think it's easier to have the external authenticate off Drupal rather than the other way around.

Any thoughts?

If you have access to the same cookies as the Drupal site, you can pull the session ID out of the SESS* cookie. Then check the sessions drupal table for the uid.

The session cookie name is a little more challenging to predict as it is "SESS"+ an md5 hash of the session name from the host domain URL or cookie_domain setting in settings.php file. Given your full control over the site, it shouldn't be hard to work with that though.


How to consume custom fields in RSS feeds I'm sharing data between two Drupal sites using the Aggregator and Views modules (created a Feed to look at a content type).

This works, but the problem is that the source server places CCK fields within the description field, so when I try to use those fields in the destination view (e.g to filter content), the view doesn't about the CCK fields.

Is there anyway to make the CCK fields render as regular fields in the RSS? Like title or author?

For this situation I prefer using the Services module, then enable a rest server and using the index. Here is an excerpt about it from the module's project page:

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.


Load entities referenced by the user I am using Entity reference module.

In one of my content types I have added Entity references as Users of the website.  So is there any way or API function to load the entities with logged in user is associated.

For Ex: When User1 is creating an article node and will add other users such as user2 etc in one of my entity reference field. Now when user2 is logged in i would like to inform him that he was referenced by user1. Is there any API function to achieve it ?

I have created a view which will display all the entities in which current logged in user is referenced. Just Import this view and change it as per the content type you want.

Enjoy!!!!

$view = new view();
$view->name = 'users_referenced_entity';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Users Referenced Entity';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Entities in Which Logged in User is Referenced';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Referenced users (field_referenced_users) */
$handler->display->display_options['arguments']['field_referenced_users_target_id']['id'] = 'field_referenced_users_target_id';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['table'] = 'field_data_field_referenced_users';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['field'] = 'field_referenced_users_target_id';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
  'page' => 'page',
);
$handler->display->display_options['filters']['type']['group'] = 1;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'users-referenced-entity';


Custom 404 - menu disappears I have created a custom 404 page using hook_preprocess_page():

function THEME_preprocess_page(&$variables) {
  $header = drupal_get_http_header('status');
  if($header == '404 Not Found') {
    $variables['theme_hook_suggestions'][] = 'page__404';
  }
}

The contents of page--404.tpl.php is identical to the contents of page.tpl.php except that use a static text block instead of calling print render($page['content']);. When this page is displayed one of the menus disappears from the header. Everything else look just as it does when I'm on a ordinary page except for the menu.

Since I only wan't to change the actual message that is displayed when receiving a 404 page and still use the rest of the markup contained in page.tpl.php perhaps it would be a better idea to only alter the $page['content'] inside a hook or similar?

Would appreciate if anyone could help me figure out why the menu is vanishing or could give me a solution that only alters the $page['content'] in page.tpl.php in case of a 404.

If you can accept using a module for this, rather than a theme override, you should be able to use CustomError:

  This module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them.

Just to make sure I've understood the use case: You write:

  Since I only wan't to change the actual message that is displayed when receiving a 404 page

This message is by default "Page not found  The requested page "..." could not be found. ".  I think CustomError' will reproduce the standard message unless you override this - but it may something about your use case that I have not understood.


Add dividers for each year on View table I have a view listing a custom content type by year and quarter (Spring, Summer, Fall, Winter). It's currently listed in a table. I'd like there to be dividers for each year within the table. Simply a row that names the year before going on to the content that fits within that year. Below is an image of the effect I want to achieve.

I've considered creating a twig template for the view, but I'm not sure how I would be able to check whether an item is the first or last item in a year. I've also considered adding a 'custom text' field but again I'm not sure how I'd make a conditional for that, and I'm not sure how I would be able to turn that into a unique row.

Is there a way to create row dividers in a table view once the year changes, or with any field for that matter?

You can use "Grouping field" option inside view formate settings for year field. Here is example of grouping
1. https://stackoverflow.com/questions/13828952/drupal-7-views-list-group-by-field?answertab=active#tab-top
2. https://www.drupal.org/node/1578512


Drupal 7: Add markup to form during validation I have a custom validator on a webform. When a person enters an address, I validate it. When the address is not right, I set an error in the validation function. This is all going well. But now I want to give the visitor suggestions when he enter a wrong address. This should be done by giving the suggestion in a markup underneath the address input.

I allready set up an empty markup field in the webform, now I just want to put information in it during validation. How is this possible. If you need any dpm or printout let me know please.

Thanks in advance.

In your validate you can set a variable in the $form_state that tells if the validation failed or not:

function webform_validate_handler(&$form, &$form_state) {
  if ($mail_invalid) {
    $form_state['mail_invalid'] = TRUE;
  }
  else {
    $form_state['mail_invalid'] = FALSE;
  }
}

Then in your form, you can check for empty($form_state['mail_invalid']) and show the markup when the empty check returns false.

function hook_form_alter(&$form, &$form_state, $form_id) {
  ...
  if (!empty($form_state['mail_invalid']) {
    $form['markup'] = ...;
  }
}


How can I set a certain cck value to selected nodes using View Bulk Operation (VBO)? I have a text type cck filed (checkbox widget) allowing multiple values.
I need to add one of the values of this field to selected nodes using VBO.
I suppose Modify node fields (views_bulk_operations_fields_action) is the way to go but how can I exactly do it?
I need to add just one value but keeping the existing values the nodes currently have.

Create a view, and add Bulk Operation to the field.
In the configuration field: Bulk Operations: Content
  Bulk Operations -> Selected Operations,  you can choose the operations you would like to perform in bulk.
  Once you done, save the view, and go to the view page.

Select the nodes you would like to edit
Choose an operation, click Execute
Select the field you like to edit
You got the rest.


How to make 'Views' consider contextual filter value to be 'all' automatically? What I am trying achieve here(d7) is a bit cleaner URLs which is looking odd due to 8-12 contextual filters. Except 1 or 2 filters others will be /all most of the times.

Suppose I have 5 contextual filters. When only the first one has value, the URL becomes example.com/24/all/all/all/all. Is there a way we can avoid "/all/all/all/all" ?

I have also tried using query parameters through PHP CODE.

If I choose 'Provide default value' ->  'PHP code' and use

$query= $_GET['clr'];
return $query;

Is there a way we can tell views to consider "query=all" for other queries automatically if that part is omitted in URL?

For ex:
If URL is

  example.com?clr=1234

the view should assume it to be

  example.com?q1=all&q2=all&q3=all&q4=all&clr=1234

I don't know if it clashes with your configuration, but usually you use the option Display all results for the specified field under When the filter value is NOT available.

There is also the option under When the filter value IS available or a default is provided > Specify validation criteria:

Action to take if filter value does not validate

where you can choose to Display all results for the specified field. Maybe you can combine it with some Validation conditions to achieve what you want.


How can I display information about a referenced node within a content creation page? I have a content/entity type called venue. On these venue nodes, there is a link to review the venue. When users click on this link, they are taken to a content creation page for a review content type. The content creation form has an entity reference field, populated automatically with Entityreference Prepopulate, so that the review is associated with the correct venue.

I would like to display information about the venue being reviewed (including name, address, etc.) on the review content creation form, for the purposes of clarification for the user. I'm assuming that there is some way to fetch this information since both the url (/node/add/review?field_venue_reference_review=9) and the reference field contain the NID for the venue.

What would be the best way to pull information from the venue node and display it in/above/near the review form? I've tried to do it using a views block with a contextual filter, but it seems that since the NID neither has its own place in the url, or is in the standard place that an NID would be placed on the url of a node page, views cannot detect it. There may be another way to do this that I'm not realizing.

Any help would be greatly appreciated, as I've being searching for an answer for quite some time. Thanks in advance for any help.

If I was faced with this problem I would look to views to help me solve it.

Create a view for the review content type containing the fields
you want to display.
Add the entity reference relationship to that view.
Pass the correct node id as the argument using that reference.


How to create a shortcut to IMCE File Browser? The File Browser link is different for each user, e.g.:

http://example.com/user/1/imce
http://example.com/user/10/imce

How can I create a shortcut to the File Browser which is good for all users?

Use me aliases module.

It turns:

http://example.com/user/10/imce

to:

http://example.com/user/me/imce


Javascript loaded via DrupalSettings variable not executing? I have added a js library and associated code to get all Location nodes onto a Map page

This code works fine if I paste it into the map.js file but if I use the drupalSettings variable, the code is appearing in the map.js file but doesn't appear to be executing

The map.js file

(function ($, Drupal, drupalSettings) {

    'use strict';

    Drupal.behaviors.mybehavior = {
        attach: function (context, settings) {

            var map = L.map('mapid').setView([-38.037511118801255, 176.41345152203002], 13);

            var googleSat = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
                maxZoom: 20,
                subdomains:['mt0','mt1','mt2','mt3']
            }).addTo(map);

            // the data from basic.theme file, basic_page_attachments_alter function
            // console.log(settings.basic.nr_map.foo);
            settings.basic.nr_map.foo;

        }
    };

})(jQuery, Drupal, drupalSettings);

And the code from the theme function

function basic_page_attachments_alter(&$page) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if (!empty($node)) { // if empty its a view and has no bundle - causing 503
    $bundle = $node->bundle();
    if($bundle == 'map') {
      $mapid = $node->id();
      $nids = \Drupal::entityQuery('node')->condition('type','location')->execute();
      $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

      $out = '';

      foreach ($nodes as $key => $location) {
        $map_title = $location->getTitle();

        // lat, lon
        $latlong_arr = $location->get('field_mahere_location')->getValue();
        $lat = $latlong_arr[0]['lat'];
        $lon = $latlong_arr[0]['lon'];

        $out .= 'var ' . strtolower($video_title) . ' = L.popup({ closeButton: false, closeOnClick: false, autoClose: false, className: "static" }).setLatLng([' . $lat . ', ' . $lon . ']).setContent("
' . $map_title . '
").openPopup().addTo(map);' . PHP_EOL;
      }

      $page['#attached']['drupalSettings']['basic']['nr_map']['foo'] = $out;
      $page['#attached']['library'][] = 'basic/nr_map';
    }
  }
}

If I copy the code from the console i.e. console.log(settings.basic.nr_map.foo) and paste it into the map.js file it runs perfectly and creates all of the map markers I'm after, but if it comes from the variable i.e. settings.basic.nr_map.foo it doesn't execute, and doesn't create any map markers

Any ideas? It seems like it should be simple!

Apologies for the duplicate post but I haven't had any joy on drupal forum.

Thanks

EDIT:
And the libraries yml file

nr_map:
  js:
    js/map.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/drupalSettings

Use drupalSettings.basic.nr_map.foo instead of settings.basic.nr_map.foo in your JavaScript.


Comments are Posted anonymously I am using Services Module in Drupal 7. When I try to POST comments, these comments are Posted anonymously.

I am sending POST request to ?q=endpoint/comment.json

with this Body

{   "nid":"401","subject":"Comment Subject sdfsdf ",   "comment_body":{
    "und":[{
      "value":"Comments body sdfsnd fsd fds "
    }]   } }

Comments are getting posted but anonymously. I want to comments to be posted by the name of logged in user.

The default for an unprovided uid property to a comment entity is 0, so with your current code it will always be owned by an anonymous user. If you want a specific user, you have to be specific in the request.

It can just go straight in the payload though:

{
  "nid": "401",
  "uid": "123",
  "subject": "Comment Subject sdfsdf ",
  "comment_body": {
    "und": [
      {
        "value": "Comments body sdfsnd fsd fds "
      }
    ]
  }
}

You have access to uid from the return value from the login, so it's easy to get hold of.


How do I download drupal from my webhost so I can run on my home server? I have made a database for it in mysql and uploaded the file to my home phpmyadmin but I am not sure which files needed to configured. This is the error I get on the page:

 PDOException: SQLSTATE[28000] [1045] Access denied for user
'mydb_Rem412'@'localhost' (using password: YES) in lock_may_be_available()
(line 167 of /home/magpie/public_html/includes/lock.inc).

Answer courtesy of Dipen:

"You need to adjust the username/password value in settings.php. You need to put valid username/pwd applicable on home server mysql instance."


View Preview Correct , Actual Page Not I have a block view that I am placing in every page containing the content type "class". There are several "lesson" content types referencing it through entity reference "field_class".

I want the view to display all lessons referencing the class.

I set my view up like so:

When I pass the args through it, it displays correctly, as in the first image.

When I go to the same page whose node id I passed through the view preview to get a correct output, I find that the page is displaying something different:

The result showing is the "no results" default summary.

Can anyone tell me what I'm doing wrong, or suggest advice to clear up the problem?

I'm using drupal 7. To place the block in the page I'm using panelizer.
I'm not using any internationalization modules

Any help would be greatly appreciated.

EDIT:

Here is the screenshot of my contextual filter:

Change the filter to "Provide default value", and then choose the node ID from the URL.


Scheduling review of content I have a content type that includes a date field called expires.  I'd like to set up some way to monitor all nodes of this content type and if the current date is close to the expires field value, send an email.  I checked the rules module using the built in scheduler, but I didn't see a way to check a specific node, or a series of nodes.

Use hook_cron() to check the value of that field when cron runs and fire off an email with drupal_mail_system() if the value meets your criteria.


onClick attribute striped out in rendered html I have below code in my Form. But after rendering i could not see the onClick attribute in the link.

$form['step2_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
    '#prefix' => '
'.t('Back').'

',
    '#suffix' => '
',
    '#name' => 'step2',
    '#attributes' => array('class' => array('enabled-for-ajax')),
    '#ajax' => array(
                'callback' => '::myajaxmethod',
              )
);

But i got the below output, without onClick attribute and javascript: in the output.

Back

Is this restricted? If so, how to achieve this in drupal 8?

Try this code:
$form['cancel'] = [
  '#markup' => '
' . t('Back') . '
',
];
$form['step2_submit'] = [
  '#type' => 'submit',
  '#value' => t('Next'),
  '#prefix' => '
',
  '#suffix' => '
',
  '#name' => 'step2',
  '#attributes' => ['class' => ['enabled-for-ajax']],
  '#ajax' => [
    'callback' => '::myajaxmethod',
  ],
];


How to delete all revisions of given content type except the current revision? I am having a very large website which have around 400000 nodes of story content type. And these nodes have around 2000000 revisions. How can I delete all the revisions except the current revision so i can reduce the size of my database.

I have tried node node revison delete module with no success. Page is getting time out.

The time out page is happening cause the modules is not using Drupal batch operation.

Did you try to use drush command that comes with the same module? you need to install Drush Help module to do so. If it didn't work, please post it here so I can provide you with a batch code.


how to get list of field names by select its node type in drupal? I got the all node type list in a variable using get_node_type_info() and now am passing this variable to field_info_instances as:

array_keys(field_info_instances("node", $op_keys));

ps: $op_keys is the variable to get node types.
But this is giving me list of node_type "keys" and I want field "keys".

Either tell:

  (1)how to pass list of all node types as a $bundle_name in
  field_info_instances() ?

or

  (2) when selecting any of the node_type (as an option of select
  list) from select list, it's corresponding field's name will get
  rendered. I mean to say for example: node_type = "Article" and its
  field names  = "body", "title", "image". when "article" got
  clicked from select list, "body", "title", "image" should get
  rendered.

To get a list of field names for each content type,, stored in a variable "list", given an array of bundle names, you could do:

$list = array();
foreach($bundle_names as $bundle){
   $list[$bundle] = array_keys(field_info_instances('node', $bundle));
}

Hope that helps.


RNG Module wait-list feature I just took a first look on the RNG Module. In the Readme, it is called the successor of the Drupal Entity Registration Module.

Is there a wait-list functionality planned or already implemented?
Maybe I'm not getting it right and its already implemented via Rules?

Any help would be welcome...

There is no support for wait lists at this time, however the API has a tagging system not exposed via UI, which is designed to support a list systems.

I encourage you to take a look at RNG Ecosystem, and give some feedback on your requirements for wait lists.


Mini-site on Sub-Domain I'm about to start a Drupal project for a client who has a large site currently set up on Drupal. The project will be a mini-site on a subdomain and will be totally different from the main website.

The mini-site will probably be a one-page website and the client wants to be able to easily edit the test on there. The one-page website will be fairly long and will need custom HTML.

My initial thought was to just code the HTML directly into a new page via Drupal and enable 'Full HTML' as the content type - my only worry is that I don't want the client to see/edit the HTML code, I only want them to be able to edit the text content.

So my question is quite simple - what would be the best way to go about doing this?

What I would do is create a new content type "Specific page" (id: specificpage).

In the content type, put all the "fields" / content that your client can edit. You don't want your client to break your HTML structure, but he probably wants to edit the title, the content, the background color, etc. Define all the fields he could want to edit and create them in your content type.

Use this code to theme the "page.tpl.php" for this specific content type:

function phptemplate_preprocess_page(&$vars) {
  if (arg(0) == 'node') {
    $vars['theme_hook_suggestions'][]  = 'page__' . $vars['node']->type;
  }
}

Then create a page--specificpage.tpl.php based on the original page.tpl.php, put it in your theme folder, structure your HTML content and display the fields defined by your client in the back-office.

[Edited the answer bc I did a mistake in the code and template suggestion]


Views, how to show x-items from each tag? I wan't to create an view that show MAX:10 items of tags (football,basketball,tenis etc...)

I want the view to show 3 items for each tag

[football_article_1]
[football_article_2]
[football_article_3]
[basketball_article_1]
[basketball_article_2]
.....

Any idea?

A possible solution involves creating two views, one of taxonomy terms, and another one of articles, and using Views Field Fiew to embed the article view as a field in the taxonomy terms view.

Create a taxonomy term view that shows fields. Add the title (optional) and Term ID fields. We'll come back to this one in a moment.
Create a view of content - of your sport articles that contain the tags. You can use an unformatted list of teasers, or if you want to include only some fields, an unformatted list of fields. My example uses teasers. IMPORTANT: Select a limited number of items to display. In my example I'm limiting it to 3. I won't use a pager in this example.
In the Advanced fieldset of the second view, add Contextual Filters. Select Content: has taxonomy term ID. Then in When the filter is not in the URL : Display content of "no results found".
Go back to your taxonomy term view. Add field Global: View. Select the View and Display of the view of content created in step 2. IMPORTANT: in the Contextual filters textfield, add the token for the Taxonomy term ID field (usually [%tid])

That's it. Visit your taxonomy term view and you'll see a list of 3 articles per term.

This is what the Views UI for the two views look like:

View of terms

View of content


Problem changing colors in the mayo theme I have installed the mayo theme on my new site. When I try to go to "appearance" menu, and change the color combination from mayo (default) to anything else, the system saves the settings. but the website is not using the colors I chose.

What could be the cause?

I'm trying to change colors, but nothing I do works; the colors are correct only with the default color combination.

Have you installed the theme in the right location (sites/all/themes)? If so, verify that each template has a CSS file for it. If so, then the next place to check is within the template's .info file to ensure that the CSS file is indeed being used.

Perhaps this thread would help assist you:  http://drupal.org/node/1118068


How to access the external database in drupal? I want to get the values of the current drupal database and the values from an external database in to a same template file. How can I achieve this

First you need to setup your external database as a second database in settings.php.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'standard_db',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'external' =>
  array (
    'default' =>
    array (
      'database' => 'external',
      'username' => 'username',
      'password' => 'password',
      'host' => 'db.external.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Then before you do your database queries you need to set the active database. In this example, to switch to external you need to execute db_set_active('external');

When you want to switch back to the default database you execute db_set_active();

Example code to switch to and query the external database:

db_set_active('external');
$query = db_select("your_table_name", "t");
$query->addField("t", "field_name");
$result = $query->execute();
while ($row = $result->fetchAssoc()) {
  drupal_set_message($row['field_name']);
}

db_set_active();


How can I fix the "Deleted and replaced configuration entity" error during configuration import? I am currently running into a config import error and it seems like it has something to do with field collections:

Finalizing configuration synchronization.

The import failed due for the following reasons:

Deleted and replaced configuration entity "field_collection.field_collection.field_lives_around"

I just started yesterday with this project and created tons of fields and configurations, no custom code at all for now. Any idea what could go wrong?

The field collection contains an list (text) and an geolocation field (https://www.drupal.org/project/geolocation)

The error happens when entity you are trying to create already exists. Or the data changed while config import was in progress. See: ConfigImporter.php/checkOp().

  If the target already exists, use the entity storage to delete it again, if is a simple config, delete it directly.

Running import twice may help, but obviously not at the same time, otherwise, you probably need to remove that field manually and try again.

This could be a bug of the module, as normally modules should have the following condition in place, e.g.

 /**
  * Implements hook_ENTITY_TYPE_insert().
  */
 function hook_ENTITY_TYPE_insert(RoleInterface $role) {
   if (\Drupal::isConfigSyncing()) {
     // Do not change data while config import in progress.
     return;
   }
   // ...
 }

Related bug: The group_roles field gets created too early during configuration sync.

Few hints:

In case you don't need the particular import, you can use Config Ignore to ignore it.
Try exporting the config first, then import again.
Try importing config individually first, file by file by using Drupal Console, e.g.

drupal config:import:single --file=$PWD/config/sync/config_ignore.settings.yml


Theme filter for a view How can I theme filters for a view in drupal 8?
I would like to place the filters to the sidebar menu, and rather than having standard either dropdown or autocomplete field, I would like to have something like a rendered block, so that a user could see all options at a glance.

Install Better Exposed Filters and if you want to have a filter as a rendered block you can edit view and see Exposed form in block: option under EXPOSED FORM. Enable it as Yes and place block in any page as you like.


Add link to my module output I have many field for my custom module.

And output:

    if($slides->rowCount() > 0 ){
        $output .= '
';
        foreach($slides as $sld):
            $nd = node_load($sld->nid);
            if(count($nd->field_simage) >  0){
                $img_url = image_style_url('img_960x378',$nd->field_simage['und'][0]['uri']);
            }
            $output .= '
title.'" />
';
        endforeach;
        $output .= '
';
    }

    return $output;
}

Content type has url field. It's name field_surl When users insert a link to this field, must wrap this link to my output.

I tried this but not working:

$output .= '
title.'" />
';

Result of this output:

...

How can I fix it?

With the few things I know about your field field_surl and about the way you tried to solve it, I might purpose this simple answer, sorry if it sounds obvious :

You wrote :

$output .= '
title.'" />
';

Where did you initialize your $field_surl variable ? At least, assuming $field_surl is loaded within the same node, try :

$output .= '
field_surl.'">title.'" />
';

Or even better, as suggested in @Brandon comment, use url() function :

$options = array('absolute'=>TRUE); //i.e, or set whatever options you need for your url
$my_url = url($nd->field_surl, $options);
$output .= '
title.'" />
';


In drupal 7 I want to crop same image for different device ratios. How can I do this? In drupal 7 I want to crop same image for different  device ratios. How can I do this.

On uploading image and We have to crop for different ratios.

You can use picture module combined with breakpoints module. Worked perfect for me.


Set a page to be only viewed by users who are logged in I have created a page that I would like to be visible only for logged in users and admin.

It sounds like you're looking for a node access module. There are many of these modules available which approach this problem in different ways. But in the end, they all allow you to specify more fine grained access rights to nodes (and other types of content). There's a good overview of the various node access modules on drupal.org. This page explains what you should consider when choosing a node access module and describes quite a few of the popular ones. If none of these quite meet your needs and you're up for creating your own custom module check out the documentation for Node Access Rights (here's the Drupal 6 version just in case).

Edit:

In response to the comment from OP, in general you can't set access (view) permissions per content type (though you can set create/edit/delete permissions per content type). So either people can't see any content until they sign in, or they can see all content all the time. So if you have a specific content type that should only ever be visible by logged in users you'll likely need a node access module.


Apache Solr form alter add custom fields in search form I wanted to alter the apache solr search form by adding my own custom textfields, dropdowns. I tried using the regular form alter hook but it works only for the Core search i.e custom fields appear for core search. On the Apache Solr form these form elements are not getting rendered.

Is there a way to achieve this kind of functionality ? Or any other Apache solr hook perhaps.

You need to add facetsapi module and in form alter add the custom fields. On form submit you need to use

$keys = $form_state->getValue('keys');
$custom = $form_state->getValue('user_custom_field');
$form_state->setRedirectUrl(Url::fromRoute('search_api_page.en' . '.' . $form_state->getValue('search_api_page'), array('keys' => $keys), array('query' => array('facet_key' => $custom))));


how to import some content to a new site? site A powered by drupal 6 whch has a content type news. there are many articles under it.

site B is a new site. which powered by drupal 6 too. now i only want to import those articles in site A to site B. how do i do? thank you.

The deploy module can move nodes between Drupal sites.  For advanced uses there's also migrate.


Displaying Special Characters and Letters in Drupal 7 Site I have a page that lists several non-English names which contain special letters with dots and tildas above them. Currently, those are not being displayed properly. In place of the letters the site displays question marks in a small black diamond.

How can I fix this? Is there a module? Could this be an encoding issue? Having looked at the source, I found that the page is set to UTF-8.

Try installing the languages in which you display the data. To do so go first install the "Languages" module which is already part of the core and then go to admin/config/regional/language and install any language with it.

If it's not in a formal language, try changing encoding by using this article:

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

Though, they mention in that document that it's problematic to change Drupal's encoding.

If showing these letters is rare, consider displaying these as an image.


I can not change the author of the material, an error occurs. error code inside, along with a screenshot I want to change the author of the material, but the Ajax work with error

Failed to load resource: the server responded with a status of 403 (Forbidden)

The AJAX path used for autocompleting usernames (user/autocomplete) requires a user to have the access user profiles permission:

  $items['user/autocomplete'] = array(
    'title' => 'User autocomplete',
    'page callback' => 'user_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
    'file' => 'user.pages.inc',
  );

Make sure that is true for the user account that's entering the data into the autocomplete field.

If the account does have the permission then the problem is specific to your environment (e.g. a module that alters access callback / access arguments of router item) and requires further debugging that falls out of the scope here.


POST request trying to make a Session authentication in the REST SERVER return a HTML error 406 Not acceptable I have a REST server in drupal working. I get data if I go to the server endpoint.

In Navigator:

http://localhost/drupal-7.19/restserver/user/

Work fine.

I have created a PHP to make the Session authentication:

<?php
// REST Server URL

/*
* Server REST - user.login
*/

// REST Server URL
$request_url = "http://localhost/drupal-7.19/restserver/user/login";

// User data
$user_data = array(
  "username" => "test",
  "password" => "test",
);
$user_data = http_build_query($user_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: application/json")); // Accept JSON response
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Check if login was successful
if ($http_code == 200) {
  // Convert json response as array
  $logged_user = json_decode($response);
}
else {
  // Get error msg
  $http_message = curl_error($curl);
  die($http_message);
}
echo "END php \n";

?>

But I getting this error:

TestAuth.php The requested URL returned error: 406

First of all make sure you choose the appropriate Data types for request formatters and parsers for your resource. You will find it under admin/structure/services/list/your_resource_name/server. Having said that, this works for me :

// .xml asks for xml data in response, choose what you need here
$service_url = 'http://localhost/your-endpoint/user/login.xml';
$post_data = array(
    'username' => 'admin',
    'password' => 'pass',
);
// We format post data as application/x-www-form-urlencoded so make
// sure that you tick it under the rest server parser options.
$post_data = http_build_query($post_data, '', '&');
// Initialize the request
$curl = curl_init($service_url);
// We want curl to return a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Choose method POST
curl_setopt($curl, CURLOPT_POST, true);
// Feed the data to POST to curl
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
// Make it verbose for debugging.
curl_setopt($curl, CURLOPT_VERBOSE, true);
// Go!
$response = curl_exec($curl);
curl_close($curl);
print "LOGIN RESPONSE:\n";
var_dump($response);
// parse the response we get (in XML see above)...


How do I add secondary tabs to the user (profile) edit tab? In earlier versions of Drupal, there were categories of users which showed up as tabs on the user (profile) edit page, located at /user/{user}/edit. How can we define new tabs on this page in Drupal 8?

Tabs can be added to the user edit page as follows:

1) Define the route(s) for your tab(s) in [MODULE].routing.yml as normal:

[MODULE].something.user_defaults:
  path: '/user/{user}/edit/something'
  defaults:
    _controller: '\Drupal\[MODULE]\Controller\SomeController::someSettingsTab'
    _title: 'Some Settings'
  requirements:
    _permission: 'some permission'
    user: \d+
  options:
    parameters:
      user:
        type: entity:user

2) In [MODULE].links.task.yml, add your tab(s) as you would primary tabs, except rather than using base_route, use parent_id, and set it to (somewhat unintuitively) the user edit form tab key, which is defined in user.links.task.yml as entity.user.edit_form (same as the route name):

[MOUDLE].something.user_defaults:
  route_name: [MODULE].something.user_defaults
  parent_id: entity.user.edit_form
  title: Some Title
  weight: 10

3) You also need to define a tab for the user to switch back to, as tabs are only rendered if there are more than two tabs. In this case, we want to add a tab for the user edit form, using the user edit form route, again using the user edit form tab key:

[MODULE].entity.user.edit_form:
  route_name: entity.user.edit_form
  parent_id: entity.user.edit_form
  title: Profile


Add custom URL to Image on a node I'm using Drupal 7, and my nodes have an image and a weblink in seperate fields, The weblink is using the link module so not sure if that will complicate things here. (if so I could downgrade the link field to a text field)

anyway I'd like to create an <A> tag around my image whilst its being themed and I want the href or that <a> tag to point to the weblink url. Sounds like an easy thing to do hey... well I can't figure it out at all! so any help would be awesome :)

If I understand well your question, an alternative can be edit your image field ("Configure field" options) and select Rewrite results > Rewrite the output of this field. Here you can make lots of things with your image, for example add a link from other previous view field, over your image.

here one example to string included in the rewrite field:

[field_image_test]

in this example [field_test_link] is a text field with the respective web address, and [field_image_test] is the field that comes with the image.

this image comes from Drupal 7, but this steps also are possible in Drupal 6


How do I make a view block with picture of the currently logged-in user? How do I make a view block with picture of the currently logged-in user?
I am using Drupal 8.

Create a new view /admin/structure/views.

Add  a contextual filter in view: User: User ID and configure.

Add picture field.
Save.
Show block where you need.


Comments not displayed On my Drupal 8 I have a blog, which should have a comment function. I added the comment field in the content type of the blog posts and I also checked the checkbox that the comment input field is shown. But the comment section is not displayed. Even in my template file in my theme_preprocess_node function I could not find the comment field. I also tried it with the Bartik theme, but that also didn't work.

My question now is: How can I display the comments section on my blog articles?

Debugging is the art of taking away all possible causes ... in this case you want to make sure that the permissions are set correctly. so that for the user id you're using, it's allowed to post comments.

Not sure if it is "the" reason for your issue, but without appropriate permission Drupal seems to work as it should.

Another reason might be that you have "the field deactivated in the manage dispay settings of the related content type" (as per your comment below this answer seems to be your case).


Make field editable after date Is it possible to make a field either editable or appear after a date?

I have a content type with a Title, Date and 'Winning Numbers' field. The winning numbers field should only be fillable/editable AFTER the Date in the date field has passed.

You van achieve this with hook_field_access (https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook_field_access/7). You can check the date value against current date from the $entity object and then set permissions.


Taxonomy breadcrumbs I'm using the core taxonomy module for blog tags but when on a tag's page can only get the breadcrumb to appear as 'Home', whereas I'd like it ideally to be 'Home > Blog > #Tag#'. I'm using custom breadcrumb module to set breadcrumbs for content types (<- doesn't allow for taxonomy breadcrumbs) and have tried using taxonomy breadcrumb module with absolutely no result, partly due to the fact that it's not a particularly configurable module. Blog tag pages (listing all the nodes under a term) seem to be generated from the core taxonomy module and not views so I can't resolve the issue in views.

If anyone could point me in the right direction I'd be grateful :)

This can be accomplished by overriding theme_breadcrumb() in your theme's template.php
An example implementation:

function mytheme_breadcrumb($breadcrumb) {

  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $breadcrumb = array();
    $breadcrumb[] = l(t('Home'), '<front>');
    $breadcrumb[] = l(t('Blog'), 'path/to/blog');

    $tid = arg(2);

    if ($term = taxonomy_term_load($tid)) {
      $uri = entity_uri('taxonomy_term', $term);
      $breadcrumb[] = l($term->name, $uri['path'], $uri['options']);
    }
  }

  // resume normal operation
  if (!empty($breadcrumb)) {
  // uncomment the next line to enable current page in the breadcrumb trail
    $title = drupal_get_title();
    if (!empty($title)) {
      $breadcrumb[] = $title;
      unset($title);
    }

    return '
'. implode(' &gt; ', $breadcrumb) . '
';
  }
}


Redirecting doesn't work with a custom form in a block I developed a custom form with FAPI and added a block for it.

Block is included only on one specific page (basic node).

When user submits this form it should redirect user to external site (URL is a return value from another external site).
For this purpose I've used $form['redirect'] which was working when this form was used as standalone page.
In block it won't redirect and instead the same page is loaded.

I tried other methods too for redirecting such as php header location and drupal_goto but none of them work.

Perhaps there is something node level overriding that prevents the form redirect?

EDIT:

Block is a very basic implementation on code level. API based hook_info and hook_view functions accompanied with custom content function (which returns form markup:drupal_get_form('my_form')).

The redirect is defined on hook_form_submit($form, &$form_state) in which it first makes two calls to external web services and based on return values it either redirects or shows message:

// Debug shows that this evaluates true
if (!filter_var($webservice1, FILTER_VALIDATE_URL) === false) {
    $form_state['redirect'] = $webservice1;
} else if ($webservice1 == 'ok' && $webservice2 == 'ok') {
    drupal_set_message(theme_item_list($formvalues),'status');
} else {
  drupal_set_message('Error', 'error');
}

I believe the redirect should be $form_state['redirect']


How to write a module that provides its own content-type using CCK? I have to write a module that provides its own content type. In the drupal-documentation there is a guide for that; yet, I would have to deal with the CRUD logic inside of my module. I thought I could use CCK to create my new content-type with its fields inside of hook_install();. But I couldn't find any guides on how to do that.

Can anyone give a short example or provide a link to some decent guide? That would be awesome.

If you goal it to create your own content type, but don't want to deal with the hassle of CRUD, you could use features. It's designed for doing stuff like this.

CCK doesn't actually handle creating new content types, that is part of the node module (Drupal core). If you want to add a node, as if it was done through the interface and don't want to use features you should use hook_node_info:

/**
 * Implementation of hook_node_info().
 */
function module_node_info() {
  $items = array(
    'activity' => array(
      'name' => t('Name'),
      'module' => 'node',
      'description' => t('Description.'),
      'has_title' => '1',
      'title_label' => t('Title'),
      'has_body' => '1',
      'body_label' => t('Body'),
      'min_word_count' => '0',
      'help' => '',
    ),
  );
  return $items;
}

Setting node to be the owner of the node type lets it handle CRUD etc.


Troubleshoot hook_library_alter() not being called for the jQuery Update module I have the jQuery Update's development shapshot version 7.x-2.x-dev installed and enabled. The version jQuery configured in UI is not being imported. As result, it is importing version 1.4.4 instead of the version I specified. Debugging, I noticed that jquery_update_library_alter() is not being called. In meanwhile, my custom hook_library_alter() is called, and I use that as temporary solution until I figure out why the hook implemented by the jQuery Update module is not called.

function MODULE-NAME_library_alter(&$javascript, $module) {
  module_load_include('module', 'jquery_update');
  jquery_update_library_alter($javascript, $module);
}

This is first time I encounter a situation where hooks are not called. Where are hooks attached to and where are they called from? How would you approach to troubleshoot hooks? Where can I check all registered hooks?

I had this problem as well and I tracked it down to a custom module calling drupal_add_js() right at the top of the module file. This meant that drupal_get_library(system, jquery) and in turn module_implements(library_alter) were getting called before the jquery_update.module file had a chance to get loaded and hence jquery_update_library_alter wasn't defined yet.

To find this I put the following lines into drupal/include/module.inc and cleared the cache.

...
function module_implements($hook, $sort = FALSE, $reset = FALSE) {
    if ($hook == 'library_alter') { debug_print_backtrace(); exit; }
...

You might have some other problem, but a call to drupal_add_js to early in execution was my issue.


Conditional price in readonly text field I have a content type to create membership for a plan, There are around 900 kind of price based on condition. I know conditional field only make visible the text-field when criteria match but if I create text field for each price then my content type will have more than 1000 fields and that is some kind of fussy isn't it ?

So can anybody suggest me any other option to do it, like I know first 4 condition, based on which the value has to come, I can make table for it...but how to go forward to make it appear in content creation page ?

Looking at your requirements I would suggest going with the data module

You could create a table with all the possible combinations. Once that is done in your content type you would be displaying the required fields such as Apartment Type, Plan Type etc. When the content is chosen you can look up in the table and get the correct pricing.

There are some assumptions made here. The prices are fixed and known in advance and changes in price would be minimal. We only need to get the correct price defined byt the table.

As for the down payment and EMI I presume you would have a set rules for the same which can be calculated on the go.


500 internal server error while installing What is the reason for the error "500 internal server error" while trying to install drupal,

i have created database successfully
After that i have downloaded and extracted the drupal 7.22 in my desired        directory.

But when i trying to install the tables in my database its showing  the error and approximately more than 30 tables are storing and the installation process stops automatically with showing the above error . Can anybody tell me why the error is coming.

As Clive says above, it's nearly impossible to help without knowing more about your particular setup and debug info.

Common pitfalls are :

Various php.ini settings : max_execution_time as mentioned by monymirza above, but also memory_limit. This last can be raised during install and dev, then lowered for production.
Lacking .htaccess at Drupal's root. Standard unix commands often don't copy hidden files, and .htaccess is more or less mandatory for D7 to work.
Lousy DB connection, particularly on shared hosting.
Misconfigured vhost : perhaps a particular setting messes up things between domains, or subdomains. Also, you have to check the AllowOverride All directive on Drupal directory for it to function properly.

There are others, but these should get you started.


how do I change the url based on a theme? On some occasions, I've seen Drupal able to detect things like language and rewrite the url accordingly, so your actual displayed url reflects the detected value (like from http://www.mysite.com/foo/bar to http://www.mysite.com/en/foo/bar)

I want to do that based on the $theme_key. I want all the data, when displayed in the 'fancytheme' theme, rewritten from  http://www.mysite.com/foo/bar to http://fancytheme.mysite.com/foo/bar

is that possible ?
how would i go about ?
is there a module out there that already does that ?

Normally, you could accomplish this with URL rewrite rules or theme switching modules like ThemeKey but you're moving to a different sub-domain which Drupal is going to assume is a new database. The best way to do this then is to use the Domain Access module to simulate the use of a sub-domain without switching your database.

Domain Access is a little trickier to setup (read the install file carefully) but it allows separate themes for each subdomain with the "Domain Theme" module.

  Domain Theme -- Allows separate themes, theme settings and colors for
  each subdomain.


Is it possible to use a sort of constant or a custom token in the rewrite section of a views field? My use case.

I have a portion of a URL of another site (www.example1.com) under each of my nodes (let's say node type B).

Each of these nodes can be related with another node (let's say node type A).

I need a view which show informations of A nodes and get the URL portions from B nodes using the relationship section of the view.

That's ok, I get what I want but I would like to create a URL with this URL's portion adding a constant/token at the beginning (www.example1.com) so that it can changed in a simple way (let's say www.example2.com) instead of modify each field of the view.

My best bet should be probably to rewrite the template of the view and using a constant (variable_get/set should be fine) but I would like to have this field configurable with the UI.

Thanks

If I'm understanding the question properly, you can either use a hidden field on a node to create a node specific value which you can rewrite as a link if desired, or create a Global:Custom Text where you can include whatever static or variable data you desire, so long as the fields containing the information are present (visible or not).


Accessing the cell phone camera to populate the profile picture field I have a mobile website, and I thought it would be cool if there were a way for the user to take a picture with their phones camera to populate the field rather than have them go and upload a picture they have on their phone, similarly to the way used from some websites to access the computer's webcam to let you take pictures.

I'm not sure if this is even possible to do from within a web browser on a phone. I've seen Flash soultions that access the webcam of a computer via the browser, would any of those solutions work for Drupal?

Agreed this is not purely a Drupal question but not unrelated, a little searching got me a really good answer on HTML5 Rocks taking you through the history and methods.

Specifically go to the section on getUserMedia(), there are even examples on the page that let you test it on your browser.

To my knowledge and from my searching I have not seen any Drupal module making use of this, but there is a discussion thread on drupal.org looking into this.


Add .active class when certain view is executed using hook_menu I have a view that is not related with a menu but I need to add .active class to an element of this menu when the view is shown. How can I alter the element adding a class active?

You can use the Context module for this. Context is capable of adding active classes to menu items based on conditions, e.g. path, content type, etc.


How to make page.html.twig based on Vocabulary? I want to make different page.html.twig according to different Vocabulary.
 I found this code:

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

in How do I theme a taxonomy term page?.
Code does not work:

  Fatal error: Class 'Term' not found in...

Excuse me, what is the reason, I really need to customize the page.html.twig according to the vocabulary, you can help me？

Because you have not included the PHP code that contains the Class.

See Namespacing in PHP.

According to term.php the name space is Drupal\taxonomy\Entity.

So you need to add use [name space]\[class name]; at the top.

Therefore, it would be use Drupal\taxonomy\Entity\Term;.

Example:

<?php

use Drupal\taxonomy\Entity\Term;

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}


How to get value from field widget during AJAX callback loop? A select element on my form gets processed with an AJAX callback. There is a Multiselect widget on the form, and I want to see the new value of the field as if the form had been submitted. But, the $form_state['values']['my_multiselect'] is always NULL when checked in the form builder function during AJAX callback. Where does Multiselect build the value from the form state?

Looks like there's an existing answer on Multiselect issue queue: Changing multiselect options using #ajax, and it has the solution.


How to attach external js to Drupal.behaviours If we write js code in Drupal.behaviours like below

(function($) {
  Drupal.behaviors.my_module = {
    attach : function(context, settings) {

}
};
})(jQuery);

that code will be execute multiple times on a page if needed even after an ajax callback.

But in the preprocess_node I have added an external js file. The problem is on node page there is a view with an ajax pager.
When I move to next page through views ajax pager(views infinite pager) then that external js did not work.

So my question is, Is there a way to add the external js to Drupal.behaviours?

You can use .once available in Drupal.

Drupal.behaviors.Newsletter = {
    attach: function (context, settings) {
      $('#cd-sso-newsletter-form').once('form-Newsletter', function () {
        // Your Code.

        });
      });
    }
  };


How to create a packing slip? We want to be able to print a packing slip from a completed order.

I see that the line items is a view but how can I create a new page or tab on the order page to display a clean packing slip?

Check out this list of order printing and order invoicing modules.

I think Commerce Billy looks promising, but I haven't tried it out.

Commerce Order2Pdf is another promising module, but I'm not sure how customizable it is.

I am currently building a custom module to handle my own packing slip requirement.  I'm building to a template, and have found FPDF to be quite useful for this.

If you're comfortable with custom module development, I'd think that FPDF is the way to go, but you'll just need to write a lot of PHP to build a template, and then use Drupal Commerce API and/or custom database queries to load in the order data.  If you don't like the sound of that check out the aforementioned modules.

Let us know what you end up using! I'm curious about those modules but in this case I am going the custom route.


Problem with views recent comments block I have a problem with the recent comments block created with Views. I have overridden the view fields in the view template (views-view-fields--comments-recent--block.tpl.php) and printed out the fields:

print '
'. $fields['subject']->content .'
';
print '{  '.$fields['name']->content. '' .', '. ''. $fields['timestamp']->content .' }';

It displays the name of user that created that node. For example, I've created a node titled "blahblahblah" and I added a comment on my node; the block displays "blahblah - posted by heihachi." If another user (jessica) posts a comment in that node, the block still displays " blahblah - posted by heihachi," not "by jessica."
Why?

This is because the title and author being shown belongs to the node not the comment. There are some options under the comment group of a views fields or you can use a relationship to specify the node's author or the comment's author.


Creating a job portal system I want to create a job system with the following workflow:

Administrator can add the jobs.
A page for job listings.
On detail job there should a link of apply for this job.
The form will contain the fields and upload application form.
The back end must display the number of application received for respective job.
On click on number of application received for respective job the see the list of Application received list for particular job category.

I have tried it with the Views and the Webform module.

Created a view for job listing and use webform for apply form. But what should I do with the trackers in point 5?

I would implement this in the following manner:

Two content types: Job opening & Job application
Job openings to have fields like : Job description, current CTC, expected CTC, etc.
Job application to have fields like : Cover letter, experience, resume (file upload), etc.
Important: In job application content type, add an entityreference field that refers to Job openings.
Give permission to company user to create job opening; and normal user to create job application.

With this architecture, you should easily be able to build the views as entityreference module provides two very powerful relationships:

Entity reference: Referenced entity (Job opening)
Entity reference: Referencing entity (Job application)


Removing "Member for" How can I remove the Member for information from appearing on accounts?
I know I can hide the field, but the problem is that Ubercart order link appears in the history field, so I can't hide the field. I have tried using CSS to hide the details, but failed as hiding the dl tag hides the whole field.

From this comment:

  in D7 history is a field on the user entity

  goto admin/config/people/accounts/display set the format of the
  history field to 'hidden'


Use multiple email addresses on contact form I'm using the default D7 contact form to have anonymous users enter some information. I've created various categories and based on the category the message should be emailed to a single or multiple email addresses. The email addresses are valid addresses comma separated as described by D7.

This has worked fine for many years but recently emails are refused by Google due to multiple addresses in the From: header. So D7 sends the content of the contact form to both email addresses but also to the email address entered but with the entire list of email addresses in the From: header.

Is there a way to have both? i.e.

copy of the message sent to the user, with a single, preset email address
message sent to a list of email addresses based on the category.

Preferably with the standard contact form or with a separate module.

Despite being an old post, I think it warrants an answer for those sites still operating on Drupal 7 or even Drupal 8.  Rather than use the built-in Contact form, I recommend using the Webform module.  Below is a description of how it can be used for a contact form of this nature, with Drupal 7 specific screenshots.

If you setup your contact form using the Webform module, you can setup distinct emails, one for each purpose.  In both cases, the "from" setting can be set to one unique site email address, a preset/predefined email address in the configuration, or one email address from the form itself.


Unexpected class in ControllerResolver.php on line 151 I'm working with Drupal 8 for the first time, though fairly well experienced in 7.

I have a site working on a localhost environment just fine, and I am attempting to get it working on Go Daddy (I know they are not well regarded, but right now I need this to work.)

The entire code-tree on the localhost and server are identical. They both connect to the SAME mysql database, hosted on GoDaddy. The database is fine.

When I try to load the site from the GoDaddy host, I get the following error.

  Parse error: syntax error, unexpected 'class' (T_CLASS), expecting
  identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in
  /home/content/01/9224501/html/mysite/drupal8/core/lib/Drupal/Core/Controller/ControllerResolver.php
  on line 151

So far, from googling the error, it seems to result from a failed database connection. I'm not sure why the same code would connect to the same database just fine from one place and not from another.

The db connect code from settings.php is here:

$databases['default']['default'] = array (
  'database' => 'mydb',
  'username' => 'mydb',
  'password' => 'mydbpwd',
  'prefix' => '',
  'host' => 'mydb.db.9224501.hostedresource.com',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

For what it's worth, this is the code in core that generates the error.

protected function doGetArguments(Request $request, $controller, array $parameters) {
$attributes = $request->attributes->all();
$raw_parameters = $request->attributes->has('_raw_variables') ? $request->attributes->get('_raw_variables') : [];
$arguments = array();
foreach ($parameters as $param) {
  if (array_key_exists($param->name, $attributes)) {
    $arguments[] = $attributes[$param->name];
  }
  elseif (array_key_exists($param->name, $raw_parameters)) {
    $arguments[] = $attributes[$param->name];
  }
  elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
    $arguments[] = $request;
  }
  elseif ($param->getClass() && $param->getClass()->name === ServerRequestInterface::class) {
    $arguments[] = $this->httpMessageFactory->createRequest($request);
  }
  elseif ($param->getClass() && ($param->getClass()->name == RouteMatchInterface::class || is_subclass_of($param->getClass()->name, RouteMatchInterface::class))) {
    $arguments[] = RouteMatch::createFromRequest($request);
  }
  elseif ($param->isDefaultValueAvailable()) {
    $arguments[] = $param->getDefaultValue();
  }
  else {
    if (is_array($controller)) {
      $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]);
    }
    elseif (is_object($controller)) {
      $repr = get_class($controller);
    }
    else {
      $repr = $controller;
    }

    throw new \RuntimeException(sprintf('Controller "%s" requires that you provide a value for the "$%s" argument (because there is no default value or because there is a non optional argument after this one).', $repr, $param->name));
  }
}
return $arguments;

}

Line 151 is the 3rd elseif statement.

A similar error that I already solved was a result of GoDaddy defaulting to PHP 5.3, which was not supported by Drupal 8. I upped it to 5.4.19, which is the only other option they offer.

My localhost is running PHP 5.5.9. I hope this is not the problem because there won't be anything I can do about it.

My localhost is running PHP 5.5.9. I hope this is not the problem because there won't be anything I can do about it.

Well there is something you can do - change your hosting provider :)

The error is indeed caused by your version of PHP - it's too old. It doesn't understand the newer method of class name resolution, introduced in 5.5. A quick search through core reveals 350+ uses, and I think there is/was an issue around somewhere to convert any uses of static strings as class names to the new way, so it's not something you could realistically work around with patches.

The PHP requirements do list 5.5.9 as a minimum version (until Drupal 8.7.0), so trying to install on anything lower than that is doomed to failure unfortunately.


How to remove all attributes displayed for a field? We are looking for a way to remove all the attributes for one or more fields (if not all) when they are displayed. There is a way to do this using Twig template by removing {{ attributes.addClass }} in any twig template that has <article {{ attributes.addClass }}>, but that requires for us to do this with all fields and any twig templates.

The goal would be to have a settings globally to remove the attributes, but we have been unable to find a module that does this.

How would we without modifying twig templates, accomplish this situation?

We have a way to add custom attributes on a as needed basis.

We ended up creating a field.html.twig in our custom sub theme where all the attributes were removed and only added them on an as needed basis.


Display only last item in multifileld (files by media) I added one multifield - files with media widget.
Drupal rendered all items, but I need only last.
I can fix this by code below in template.php, but i don't know, it is good?

$i = 0;
while($i < $items_count - 1) {
  unset($variables['content']['field_files'][$i]);
  unset($variables['content']['field_files']['$items'][$i]);
  $i++;
}

What is the best way?

You shouldn't unset array elements in tpl files. Instead, use hide() function:

Hides an element from later rendering.
The first time render() or drupal_render() is called on an element tree, as each element in the tree is rendered, it is marked with a #printed flag and the rendered children of the element are cached. Subsequent calls to render() or drupal_render() will not traverse the child tree of this element again: they will just use the cached children. So if you want to hide an element, be sure to call hide() on the element before its parent tree is rendered for the first time, as it will have no effect on subsequent renderings of the parent tree.


How to set the value of a field when hidden from certain users/roles? I have a field which I don't want to be displayed for certain users, however I still want a value to be entered for that field, which is extrapolated from other fields they enter data in.

In order to do this, I'm setting the field as hidden in hook_form_alter:

$form['field_target']['#type'] = 'hidden';

and then setting the value of the field from within a form_validate function based on another field, such as:

$form_state['values']['field_target']['und']['0'] =
    $form_state['values']['field_source']['und']['0'];

And this works fine, unless I force a form validation error on field_source. When I correct the validation error and submit again, I get a white screen with PHP Error:

PHP Fatal error:  Cannot create references to/from string offsets
    nor overloaded objects in includes/common.inc on line 6288

This error happens even if I comment out the setting of field_target. However I can fix this error by removing the [#type'] = 'hidden' line and everything works fine, except that the field shows for all users.

Is there any way to fix my above approach, or is there a better way to achieve what I'm trying to do?

Ok it seems I can get around this error by setting:

$form['field_target']['#access'] = FALSE;

instead of ['#type'] = 'hidden'; and Drupal no longer freaks out.

If anybody has a better idea though I'll glady accept a different answer :)


Drupal 7 "The form has become outdated. Copy any unsaved work in the form below and then reload this page." I have a problem. When I put this code in my module checkboxes work great but form throws an error:

"The form has become outdated. Copy any unsaved work in the form below and then reload this page."

Alert one add node form.

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

  $form['add_phone'] = array (
    '#type' => 'fieldset',
    '#title' => t('Adauga telefon'),
    '#weight' => 6,
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

  $form['add_phone']['phone'] = array(
    '#type' => 'phone',
    '#title' => t('Phone Number'),
    '#required' => TRUE,
  );

  $form['add_phone']['phone_submit'] = array (
    '#type' => 'button',
    '#value' => 'Add',
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
      'callback' => 'automobil_add_phone_callback',
      'wrapper' => 'add-new-phone',
      'effect' => 'fade',
    ),
  );

  if(isset($form_state['values']['phone']['prefix'])) {
    $upload_users_phone = _upload_users_phone($form, $form_state, 'add');
  } else {
    $upload_users_phone = _upload_users_phone($form, $form_state, '');
  }

  $form['field_temporary_phone'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#title' => t('Telefon'),
    '#type' => 'checkboxes',
    '#weight' => 5,
    '#options' => $upload_users_phone,
  );
}

Ajax Callback

function automobil_add_phone_callback(&$form, &$form_state) {
  return $form;
}

Function that returns a list of user_phone that is stored in user profile.
If a user adds new phone it adds it and return the updated list.

    function _upload_users_phone($form, $form_state, $operation, $returns) {
  global $user;
  // load user

  $existingUser = user_load($user->uid);

  if($operation == 'add') {
    $existingUser->field_user_phone['und'][]['value'] = $form_state['values']['phone']['prefix'] . ' ' . $form_state['values']['phone']['number'];
    $user = user_save((object) array('uid'=>$user->uid), (array) $existingUser);
  }
    // edit field-data
  foreach ($existingUser->field_user_phone['und'] as $key => $value) {
    $val_list[] = $value['value'];
    $key_list[] = $key;
  }

  return $val_list;
}

What is a problem (why is the 'form outdated form' error thrown)?

The reason you get the "The form has become outdated." error is because the token fails validation (meaning the old string doesn't match the new string). The token is determined by running a hash on several things including the session_id(). When you call user_save(), the session is changed/invalidated/whatever. Hence, when the token is tested next time around, it generates a different token because you have a different session_id() and therefore fails, thinking you were using an old form.

I have the same issue after calling user_save() from within my form processing. The way I fixed it feels like a pretty big hack, but I don't know that there's a clean way around it. The form code doesn't seem to expect that you would ever change/invalidate the session whilst in the middle of handling a form (in this case, a multi-part form).

Once you call user_save you must modify the form state manually to insert the updated token. Then, when it checks tokens your new token will match since you generated it after the 'session_id()' was updated.

So the resulting code looks like this. Notice that the input element is changed for $form_state to pass by reference so that the modification gets propagated up.

function _upload_users_phone($form, &$form_state, $operation, $returns) {
  global $user;
  // load user

  $existingUser = user_load($user->uid);

  if($operation == 'add') {
    $existingUser->field_user_phone['und'][]['value'] = $form_state['values']['phone']['prefix'] . ' ' . $form_state['values']['phone']['number'];
    $user = user_save((object) array('uid'=>$user->uid), (array) $existingUser);
    $form_state['input']['form_token'] = drupal_get_token($form['#token']);
  }
    // edit field-data
  foreach ($existingUser->field_user_phone['und'] as $key => $value) {
    $val_list[] = $value['value'];
    $key_list[] = $key;
  }

  return $val_list;
}

You might also need to set $form_state['values']['form_token'], but I'm pretty sure it's unnecessary. Again, don't forget the & in front of the declaration of the function variable $form_state or the value won't make it into the real array.


composer.json for just core How do I get just Drupal 8 core using drupal-composer?

This would be very useful for core development and starting a new project without any assumption.

Sounds like you want drupal-console.  This tool can quickly create working Drupal 8 sites interactively or via command line. More info here.

Another quick alternative is to use DrupalVM and Varnish to spin up a fully working D8 site.  The DrupalVM defaults are to create a D8 sandbox site.

I believe that DrupalVM now has Docker support so you might be able to have a single VM and just spin up a new D8 box.


Problem with integer field format in Drupal 7 I just created an integer field for one of my content types. I'm using it to display a value for a year. However, when it is displayed, it is putting in a space between the 1000s column and the 100s column; so, for example, "1991" is displayed as "1 991".

I'm guessing this is something to do with the formatting of the field. Can anyone tell me how I can correct this or change the formatting?

Go to the "Manage display" tab and edit "Thousand marker".