How to create dynamic link in views? I have created a page in Views, and the path is node/%/images. Now I want to put a dynamic link in the header. I want to link to http://www.example.com/node/add/album/[nid], where "[nid]" is the node ID of the node being viewed. How can I do this?

How do I add HTML tags to it? I want to make it as a image button.

arg(1) would be your friend here. In your view header definition (PHP format) put something like:

print l(t('Add album'), 'node/add/album/' . arg(1));


Drupal 8 : Get a config settings value being stored in blocs I have create a block with a form and stored something i called 'submit_action_amu_dud_form_block_settings'

 public function blockSubmit($form, FormStateInterface $form_state) {

    $this->configuration['submit_action_amu_dud_form_block_settings'] = $form_state->getValue('submit_action_amu_dud_form_block_settings');

 }

in a method of the same class i can retrieve the value

      $config = $this->getConfiguration();
      $my_stored value=$config['submit_action_amu_dud_form_block_settings']

how can i get it from . module hook_form_alter callback ?

    function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

if ($form_id == 'amu_dud_form') {
    $form['actions']['submit']['#submit'][] = 'my_submit_method';
}
}

 function my_submit_method(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

//$my_stored_value=??

You need to load the block if your outside of the class, for that you need it's id.

$block = \Drupal\block\Entity\Block::load($bid);
$my_stored_value = $block->get('settings')['submit_action_amu_dud_form_block_settings'];

The id can be found in it's annotation if it's custom: @Block( * id = "my_fancy_block_id". If there are several instances of the block this may be altered and can be looked up in the DB, or the block config admin section - check the urls there.


Views theming, using raw data I am using views to get results which can be filtered (exposed) by the user. So far so good. Now I have to (heavily) modify the end result and while I have figured out which template I need to use, I can not find a way to fetch the actual (raw) data from the view in my template so to theme it as the client likes.

What do I have to do to get the raw data in my template? If I will have to create a module for it which steps do I have to follow to do so?

Side question, is there any other way to expose filters in a page?

Theming info on each views is located under 3-rd col - Advanced on the view. Last row say "Theme:Information". Click on Information. According to your needs select template name, and create file in your current theme. Then click on "Style output" for example if you choose this kind of filename, and get code for the file (copy/paste) in above created file. Type dpm($variables); after opened php tag (install devel module ofcource) This will output available data for this template. After creating file, go agayn on theme Info and click Rescan template files. Your new file will be bolded. If not, there is something wrong - start again this process.
There is too many name suggestions - get the last (longest) for your type.

Example:
If we have views "Latest content" with all default options, for example we can create a file views-view-unformatted--latest-content--page.tpl.php in the theme folder. Code must be (with our dpm()):

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */

dpm($variables);
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

Also we may create separate view mode for node and use them in this views. This way we may theming node views in separate file according to node view. We can get entity_view_mode module for this from DO. This is not alternative to above views theming, but as addition.

There is too many variants how to theming views - this depends what we set on the current views.


Redirect not obeying front page URL We are using this module for our redirection for 404's and manually created redirects.
The site has a number of pages translated for the American audience. We added a redirect today for a page and simply pointed the redirect url to <front>. The referring URL is http://www.example.com/when-to-go/october. In the General site settings, the front page is set to /homepage. (A Basic page for this exists.)

Now when going to http://www.example.com/when-to-go/october, the users are redirected to http://www.example.com/en-us which gives a The page isn't redirecting properly error.

There are two issues:

It should simply send users to /homepage, which is what is set to
If we wanted the American version, then it should use en-US not en-us; Drupal seems to be treating this as case sensitive

A circular redirect was been caused which stopped the redirect to front working. Checking the redirects already created and removing the offending ones fixed the issue.


How to check if code is running inside simpletest? Here's the best I've come up with so far:

/**
 * Returns TRUE if our code is running via a simpletest.
 *
 * We don't check for the database prefix so that this can be used by Unit
 * Tests also.
 *
 * We could set a variable in the test setUp method and check that variable,
 * but then some dummy could misuse that variable in code intended for
 * production.
 */
function check_is_simpletest() {
    return class_exists('DrupalTestCase', FALSE) || strpos($_SERVER['HTTP_USER_AGENT'], 'simpletest') === 0;
}

Is this crazy? I'd expect it to break in the Testing UI pages of the site, but I'm only concerned with testing custom code which will not affect those pages, and I usually test via drush.

In Drupal 7, drupal_http_request() use the following code to add an extra header, when tests are running.

  // If the database prefix is being used by SimpleTest to run the tests in a copied
  // database then set the user-agent header to the database prefix so that any
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
  // user-agent is used to ensure that multiple testing sessions running at the
  // same time won't interfere with each other as they would if the database
  // prefix were stored statically in a file or database variable.
  $test_info = &$GLOBALS['drupal_test_info'];
  if (!empty($test_info['test_run_id'])) {
    $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
  }

In your module, similar code should work.

  $test_info = $GLOBALS['drupal_test_info'];
  if (!empty($test_info['test_run_id'])) {
    // Drupal is running tests.
  }

In Drupal 6, the following code is present in drupal_http_request().

  // If the database prefix is being used by SimpleTest to run the tests in a copied
  // database then set the user-agent header to the database prefix so that any
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
  // user-agent is used to ensure that multiple testing sessions running at the
  // same time won't interfere with each other as they would if the database
  // prefix were stored statically in a file or database variable.
  if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix, $matches)) {
    $defaults['User-Agent'] = 'User-Agent: ' . $matches[0];
  }

The following code should work for a Drupal 6 module.

  global $db_prefix;

  if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix)) {
    // Drupal is running tests.
  }


View Field Display placing table label on top of the description So I have this table created with display suit and table group.

How am I going to make it look like this?

The label is already set to be above, but that doesn't seem to work.

I'm not really good in CSS nor Drupal. Consider me a newbie and willing to learn.


Pull all articles from my Drupal Site as JSON I am trying to pull all articles from my site in form of JSON.

I know it can be done by either Services, RESTful Web Services or Views Datasource but I don't know how to do it. I am a complete n00b in Drupal.

Could you specify me, with an example hopefully, that how can I pull all articles in a JSON and show that JSON through a URL?

Many Many Thanks.

Judging by its description Views Datasource might be the way to go, but it seems to be still not ready for production. There is no even beta version as far as I can tell. But your task can be easily achieved by creating your own custom module.

Create your own module (you can read more about this process here).

And in your module do the following:

//Your implementation of hook_menu, create url endpoints here
function YOURMODULENAME_menu() {
    $items = array();
    $items['path/where/i/want/your/json/to/be'] = array(
        'title' => t('list of articles'), // can actually be arbitrary text here
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name',
        'access callback' => TRUE,
    );
    return $items;
}

//Page callback function that renders the json endpoint
function your_function_name() {
    $query = "SELECT * FROM {node} n WHERE n.type = :type";
    $result = db_query($query, array(':type' => 'article'));
    $json_data = array();
    foreach ($result as $record) {
        $node = node_load($record->nid);
        $json_data[] = array('nid' => $node->nid, 'title' => $node->title, 'body' -> $node->body['und'][0]['value']);
    }
    print drupal_json_encode($json_data);
    exit;
}

I didn't test this code and you might have more fields in article datatype, but I think you should get the idea how this can be done. Just query the database for the list of nodes of specific type, compose an array of data and output json.


ckeditor in not showing up on one of my drupal site content type I have installed ckeditor in my Drupal 7 site. It works well on all content types except one.
Actually, on one of my content type it doesn't show on Body field when I write content. But when I open that field in structure then I can see ck editor here.

I googled it but didn't find any helpful thing. So anyone of you who knows please help to resolve this issue.

I would click on "Configure" for CKEditor in Modules and make sure "Any content type" is selected. In these settings you can specify which content types CKEditor will be available for, so it's possible that that content type is not selected.


How to change Views field settings programmatically? I would like to change some field settings in a given view created with Views programmatically.

For example, I would like to change the "Formatter" and "Image style" settings of an Image field. This is what the settings of this field look like when I export this view:

/* Field: Taxonomy term: Natural images */
$handler->display->display_options['fields']['field_gallery_natural_images']['id'] = 'field_gallery_natural_images';
$handler->display->display_options['fields']['field_gallery_natural_images']['table'] = 'field_data_field_gallery_natural_images';
$handler->display->display_options['fields']['field_gallery_natural_images']['field'] = 'field_gallery_natural_images';
$handler->display->display_options['fields']['field_gallery_natural_images']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_gallery_natural_images']['type'] = 'colorbox';
$handler->display->display_options['fields']['field_gallery_natural_images']['settings'] = array(
  'colorbox_node_style' => '',
  'colorbox_image_style' => '',
  'colorbox_gallery' => 'post',
  'colorbox_gallery_custom' => '',
  'colorbox_caption' => 'auto',
  'colorbox_caption_custom' => '',
  'display_empty' => '',
  'custom_text' => '',
  'empty_callback' => 'mymodule_empty_fields_no_data',
);

I would like to change the "Image style" of the Colorbox formatter somehow like this:

$handler->display->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail';

and save that. How should I do that?

Like here:

EDIT 1.

Maybe I should use views_save_view():
http://api.drupal.org/api/views/views.module/function/views_save_view/7

It saves a view - so maybe I should query the whole view, change that, and use this function. But how exactly?

EDIT 2.

I found in views/includes/admin.inc that the given view gets saved like this: $form_state['view']->save(); in views_ui_edit_view_form_submit().

I already know how to change "Image style" of an Image field in a given view mode programmatically (as on "Manage display" tab after clicking the gear), but now I would be happy if I could do something similar with a given view.

UPDATED:

You can use this code snippet to change a view without views_alter:

$view = views_get_view($view_name, TRUE);
$view->display['default']->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail';
views_save_view($view);

Change default display ID if you want to use display other than the default.

If you have exported the view to code using hook_views_default_views() or the Features module, there is a hook to alter the views programmatically:

/**
 * Alter default views defined by other modules.
 *
 * This hook is called right before all default views are cached to the
 * database. It takes a keyed array of views by reference.
 *
 * Example usage to add a field to a view:
 * @code
 *   $handler =& $view->display['DISPLAY_ID']->handler;
 *   // Add the user name field to the view.
 *   $handler->display->display_options['fields']['name']['id'] = 'name';
 *   $handler->display->display_options['fields']['name']['table'] = 'users';
 *   $handler->display->display_options['fields']['name']['field'] = 'name';
 *   $handler->display->display_options['fields']['name']['label'] = 'Author';
 *   $handler->display->display_options['fields']['name']['link_to_user'] = 1;
 * @endcode
 */
function hook_views_default_views_alter(&$views) {
  if (isset($views['taxonomy_term'])) {
    $views['taxonomy_term']->display['default']->display_options['title'] = 'Categories';
  }
}

For example:

/**
 * Implements hook_views_default_views_alter()
 */
function MYMODULE_views_default_views_alter(&$views) {
  if (isset($views['VIEW_NAME'])) {
    $views['VIEW_NAME']->display['default']->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail';
  }
}

Remember to clear the cache and do revert of the view to apply changes.


How do I execute stored procedures? I have a website which does lot of work on financial data. It involves operations on large volumes of data most of the time. Hence I find it useful to do those operations in MySQL stored procedures. I have stored procedures in my database. I want to know how can I execute stored procedures in Drupal? Is there any good method to execute stored procedures in Drupal? How does Drupal handle stored procedures in general? Or we just have to use the PHP to execute stored procedures?

Assuming you're using Drupal 7 you can use code like the following:

// Get the Drupal database connection and change the statement class to PDOStatement.
// Save the current class for cleanup later.
$conn = Database::getConnection();
$saved_class = $conn->getAttribute(PDO::ATTR_STATEMENT_CLASS);
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement'));

// Prepare the statement and bind params
$statement = $conn->prepare("Call GetNodeList(?,?)");

$op_status = $statement->bindParam(1, $node_type, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 25);
$op_status = $statement->bindParam(2, $publish_state, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT);

// Execute the statement and reset the connection's statement class to the original.
$exec_result = $statement->execute();
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, $saved_class);

// Get your data
while ($row = $statement->fetchColumn(0)) {
  // ...
}

That method is completely culled from this article and has worked for me well in the past.


Drupal 6 - How to check which module is caused high loading(high CPU usage) I am running a Drupal 6 site on my server, when I use Linux command top to check the CPU usage, I always get a high figure 80-90% of CPU loading, so my server down frequently.

I have installed over 50 modules,I am going to check which module was caused high CPU usage, could someone suggest how can I check which module was caused high CPU usage(by code or module)?

Thanks

I'd also try a PHP profiler which gives you a lot of metrics. Take a look at the XHProf module. Here is an excerpt about it from the module's project page:

... allows you to profile your Drupal application using the XHProf profiler from facebook.
It also provides a native Drupal UI (as opposed to facebook's original php front end) to view the profiling data. Having this in Drupal provides several advantages:

Simpler setup
No need to setup extra vhosts
Limit access via roles and permissions
Use alternative storage backends such as MongoDb


A car dealer website with Drupal Soon I will be starting to develop a car dealer website using Drupal.
I want users to be able to select make, modal and other stuffs.
The main thing is the search; I will be using the Views module, with exposed filters, and taxonomy terms.

Is there any module which can do this?

There is no specific module to do this but using as you mentioned Views, views exposed filters and taxonomy will give you what you want.


How to add Open Graph Tags in Custom Module detail page? For Node I already used https://www.drupal.org/project/metatag

For my custom module's detail page would like to add Open Graph tags for FB share.

So in my_test.module

function template_preprocess_my_detail_page(&$variables) {

  $items = $variables['item'];

  $title =  $items->title;

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => $title,
        ],
      ];

  $variables['page']['#attached']['html_head'][] = [$og_title, 'og_title'];
}

Above one suppose to work but NOT WORKING.

function MY_MODULE_page_attachments_alter(array &$page) {

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => '',
        ],
      ];

  $page['#attached']['html_head'][] = [$og_title, 'og_title'];
}

Above one is working, But I'm not able to get Page Variables. How will I get $variables in above function?

This one called in all pages of module, but I want to call only on detail page as mentioned in proprocess function

I think that you need this.

    /**
 * Alter the metatags for pages that are not of content entities.
 *
 * @param array $metatags
 *   The special metatags to be added to the page.
 * @param array $context
 *   The context, containing the entity used for token replacements.
 */
function hook_metatags_alter(array &$metatags, array $context) {
  // Exclude metatags on frontpage.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $metatags = NULL;
  }
}


How do I add a cachebreaker to a specific image style in drupal 7? I have one image style on my site that I need to add a cache breaker to.

Ideally I just want to add . '#' . time() to the end of the src URL.

For instance everywhere the large style is shown the src url is currently something like:

/sites/default/files/styles/large/public/image.jpg?itok=kdkdFf

With cachebreaker:

/sites/default/files/styles/large/public/image.jpg?itok=kdkdFf#1398670388

How do I go about doing this? hook_node_alter?

More info:

I set up a test image editor at http://blakedesign.co.nz/editor/ via Chrome uploading an image and then editing it works fine the modified image shows up in the preview.

On Firefox or IE it actually does work but the old unedited image gets redisplayed from memory.

This can be circumvented if a unique cachebreaker is appended to the source url every time the image is viewed.

Use template_preprocess_field() to set a flag with drupal_static() when a particular style is being used. This function needs to sit in your themes template.php:

function MYTHEME_preprocess_field(&$variables) {
  // Check field type is an image.
  if($variables['element']['#field_type'] == 'image') {
    // Loop over each image.
    foreach($variables['items'] as $k => $item) {
      // Check the image style is the one we want to append a timestamp to.
      if($variables['element'][$k]['#image_style'] == 'timestamp') {
        // Set a flag to say to modify this URL.
        $append_ts = &drupal_static('append_ts', TRUE);
        $append_ts = TRUE;
      }
    }
  }
}

Then we can use hook_file_url_alter() to modify the URL if the flag is set. This function can live in your themes template.php or a custom module.

function MYMODULE_OR_MYTHEME_file_url_alter(&$uri) {
  // Fetch our flag we set in bartik_preprocess_field.
  $append_ts = &drupal_static('append_ts', FALSE);
  // Fetch an array of URI's that this function has already processed.
  $processed_uris = &drupal_static(__FUNCTION__, array());
  // If the flag is true and we've not already processed this URI...
  if ($append_ts && !in_array($uri, $processed_uris)) {
    // Add this URI to our processed list.
    $processed_uris[] = $uri;
    // Set flag to false so we only edit this URL.
    $append_ts = FALSE;
    // And finally create the new URL with a timestamp.
    $uri = file_create_url($uri) . '?t=' . time();
  }
}

The use of the flag in this instance is necessary as we can't check what style the image is using in hook_file_url_alter(), but it is possible in template_preprocess_field().

To append a timestamp to the image on the edit node page

Use hook_theme_registry_alter() to add a preprocess function to the image_widget:

function MYMODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['image_widget']['preprocess functions'][] = 'image_widget_preproccess';
}

In the preprocess load the field instance config settings, and then check them to see which image style is being used. If the correct one then make changes to the markup to add a timestamp:

function image_widget_preproccess(&$element) {

  $entity_type = $element['element']['#entity_type'];
  $field_name = $element['element']['#field_name'];
  $bundle_name = $element['element']['#bundle'];

  $field_instance_info = field_info_instance($entity_type, $field_name, $bundle_name);

  if($field_instance_info['display']['default']['settings']['image_style'] == 'timestamp' && isset($element['element']['preview']['#markup'])) {
    $element['element']['preview']['#markup'] = str_replace('?itok', '?t='.time().'&itok', $element['element']['preview']['#markup']);
  }

}


Print selected fields in page tpl Drupal 7 For some reasons, I have to customize the display of the content node programmaticaly, mixing content from other sources.

Instead of making a print(render($page['content'] which outputs all the content, I need to access to selected parts of the content (for instance, value of a text field, url of a PDF file, etc.). I am using this approach:

print render( $page['content']['system_main']['nodes'][$nid]['body']['#object']->field_subtitle_product["und"][0]["value"]);

Would it be correct or is there a more straighforward method? ( I don't want to low to node.tpl.php anyway).

Thanks!!

First, If you want to print selected field then you should to do it in node.tpl.php and not in page. There are many ways to do this :

If you just need to render the fields in default way, you can go to Admin > Content Type > Your Content Type > Manage Display and hide the fields you want.

If you want to do it through template files then you can use it using :

hide($content['field_name']);
print render($content['field_name']);

You can just remove print render($content); and write :

print render($content['field_name']);
print render($content['field_name2']);


Form inputs being disabed during the Ajax request I'm working on a module where I have a form inside of a block, I'm using Ajax to submit the form, but I noticed that the form's inputs are disabled when sending a request with Ajax. Well in my case I want to keep using the form's input (keyup event) and displaying the result for each request.

// my current code
$form['combine'] = array(
    '#type'       => 'textfield',
    '#size'       => 255,
    '#maxlength'  => 128,
    '#attributes' => array('placeholder' => 'Search'),
    '#ajax'     => array(
        'callback'  => 'ajax_filter_callback',
        'effect'    => 'fade',
        'wrapper'   => 'result-content',
        'event'     => 'keyup',
    ),
);

That functionality is built-in so you'll need to monkey-patch Drupal.ajax.prototype.beforeSend (found in misc/ajax.js).

Copy the entire code, but remove/modify this line:

$(this.element).addClass('progress-disabled').attr('disabled', true);

So in your module or theme's JS file:

Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
  // Place all code from the original function here, except the line above.
}

YMMV, you may unwittingly introduce unexpected behaviour by not waiting for each request to complete.


Can node_url be accessed in page.tpl.php? Calling debug($node) in page.tpl.php seems to show that the node object is not fully populated at this stage.

I would like to access node_url in my page template so that I can add certain CSS classes for some nodes without having to use the nid.  Is there maybe a way to access a more fully populated node object in template_preprocess_page()?

You could use the drupal_get_path_alias() function along with the node's nid to get the URL alias of the node without having to load the object:

$url = drupal_get_path_alias("node/$node->nid");

If you want the fully loaded node object though use node_load():

$node = node_load($node->nid);

Memory fails me as to whether node_url is added to the node object in a hook_node_load() implementation or as part of a theme preprocess so I'm not 100% sure it's implicitly available after you call node_load()...if it's not just use the first example which will work.

UPDATE

On inspecting the node module the node_url member comes from template_preprocess_node so while node_load() will give you the fully loaded node, I don't think it's going to be useful in this case.

In fact looking at node.tpl.php and template_preprocess_node, node_url isn't added to the node object at any point so you wouldn't normally access it with $node->node_url but instead $node_url. That variable is available by default in node.tpl.php but not page.tpl.php so you'll have to get it another way (i.e. first example above).


Can we remove template.php from active theme folder? If we remove template.php file from active theme folder will it work ? Will it follow default theme's template.php ?

Please help with this question.

Here is explained the template.php function:

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

If you remove the template.php many things on the theme will stop working, specially all the things that make the template different (or useful).

But if you're using a subtheme you can remove the template.php in it since your subtheme will use the original theme template.php (As long as you don't have your own hooks and functions in that subtheme template.php).


Commerce Paypal Payment Standard Currency Conversion I have integrated paypal payment standard using commerce paypal module in my website. I have 2 currencies my default currency is AED. Now I have 1500 AED in a cart When I am proceeding to checkout on paypal its showing 1500 USD. Isn't it possible that the amount converts in equivalent USD automatically ??

The PayPal Payments Standard module only supports the currencies PayPal specifically identifies in its API documentation as supported currencies. When it encounters an unsupported currency, it converts it to whatever currency you have set as the default currency in the configuration of the related payment method rule. Since the default conversion rate is 1:1, that's why this is being passed to PayPal as 1500 USD.

I don't know to what extent PayPal supports the Dirham. If your account does, then it could be you need to patch the PayPal module to support payment transactions in AED. Otherwise you're going to need to use the Commerce Multicurrency module to set an actual conversion rate between the AED and the PayPal supported currency you want to receive payment / maintain a balance in.


How to set default form values based on query string, if the form uses AJAX file upload I have a Book content type with a file upload field.
I'm using Filefield Sources module with Plupload integration for getting the file upload widget.

I need to set a default value based on the query string passed on node/add/book page.

However, the files are uploaded via AJAX, calling the file/ajax page, and losing all default values I set. Obviously, custom query string is not present in that call, and when the form is re-generated, I get an error.

Any ideas on how can I make sure that default values stay in the form?

Thanks!

I forgot to post the answer.

To keep the data persistent between AJAX calls, you should store it in the $form_state variable. This is how it worked in my case:

Check if I already have the data in $form_state.
If not and if there is query string, get the data, sanitize/validate it and store in $form_state.

This way it works even for AJAX calls where query string parameters are not available.


Contact form - leaving the form and resuming it later Is it possible to have a contact form in drupal, which you can save, and resume later?

Yes, you can build a contact form with the Webform module and use its "Save Draft" feature.


How to limit the display of a field on the front end, based on a Form API state Following on from a previous question.

I have a slideshow field, an image field and a video field, but I only want editors to choose one of these.

Using Form API states I have created a form_alter in a custom module which reveals one input field at a time based based on a choice from a select list. This is working fine. Code below.

    <?php

    /**
     * Implements hook_form_alter().
     */
    function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
      $form['field_slideshow_image']['#states'] = [
        'visible' => [
          'select[name="field_selection_display"]' => ['value' => 'slideshow']
        ]
      ];
      $form['field_image']['#states'] = [
        'visible' => [
          'select[name="field_selection_display"]' => ['value' => 'image']
        ]
      ];
      $form['field_video_embed']['#states'] = [
        'visible' => [
          'select[name="field_selection_display"]' => ['value' => 'videoembed']
        ]
      ];
    }

This method makes for a good UI, but it does not prevent more than one field being populated. Therefore I need to extend the module to;

1). Prevent an editor populating more than one field, perhaps by displaying an inline error message.
OR
2). Limit the display on the front end, to the field which has a visible state (based on the selection list choice).

My feeling is that number 2 would make for the best UX, but it would be good to try both.

How would I go about this?

For option #1 you would have to create a custom validation.

For option #2 which is the better solution you would have to load the fields via AJAX.


Fetch views using a ajax request I worked in printing out a view using php. Is it possible to fetch views using ajax and load in the page? For suppose I have three links each one will fetch a view using ajax and load in the current page. (Am I talking sense?)

Yes it is very much possible, but probably you can do it only by creating custom module.

send Ajax request to the Drupal
load selected view form database by views_get_view
execute selected display by $view->execute_display('display')
send HTML created on executing display back to the client.
on client side put this html wherever you want

Check ajax load module (which is D6 only) too, maybe it can help you.

There is a even quicker way and more robust to render a view: views_embed_view


Dependency Injection while Unit Testing Normally with Drupal 8 I can use dependency injection like this:

<?php

class ExampleController extends ControllerBase {

  private $http_client;

  public function __construct(HttpClient $http_client) {
    $this->http_client = $http_client;
  }

  public function create(ContainerInterface $container) {
    $http_client = $container->get('http_client');
  }

  public function getResource() {
     $response = $this->http_client->get('http://biebertunes.com?q=selena');
     return $response->getBody();
  }

}

I can then use the $http_client property's methods.

Now in my testing class I'm already extending the UnitTestCase class, so I don't have access to the create method for dependency injection.

<?php

class ExampleTest extends UnitTestCase {
  public function testGetResource() {
    $mock = $this->getMock('\Drupal\Example\ExampleController');
  }
}

Now when I run my unit tests it complains that I don't have the $http_client parameter. So how can I inject $http_client into the unit test without the create method?

I have few thoughts about this situation:

Controllers should not contain business logic, services should. Therefor unit testing a controller is not a good idea in the first place.
If you are unit testing your controllers "getResource" method, why do mock the controller itself? You should mock the HttpClient. (that's the strong part of DI)
First you mock the classes which your constructor needs as arguments. Then you just create your object, which will you test like this: $example_controller = new ExampleController($http_client_mock); And that's it.


How can I pass an array from a controller to a template? I want to render array to twig file I am able to render variables but not array.

My php file :

  public function build() {

    $vid = 'Sectors';
    $terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')-
 >loadTree($vid);
    foreach ($terms as $term) {
     $term_data[] = array(
      'id' => $term->tid,
      'name' => $term->name
     );
    }
    // echo "<pre>";
    //  print_r($term_data);
    //  die;
    // return $vid;

  // do something
    return array(
      '#theme' => 'mdoner_custom_block',
      'title' => 'MDoNER custom Block',
      //'#test' => array('key'=>$term_data),
       'testmenu' => $term_data,
    );

  }

My array:

Array (
       [0] =>
          Array (
               [id] => 1
               [name] => Climate Change
           )
        [1] =>
           Array (
                [id] => 5
                [name] => Ecotourism
          )
    )

.module file:

function mdoner_custom_theme($existing, $type, $theme, $path) {
  return [
    'mdoner_custom_block' => [
      'variables' => ['title' => NULL],
      'test' => array(),
    ],
  ];
}

Twig file:

<!-- dump(content) --> // get array of all the content
{% for key, value in testmenu %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}

How can I pass the testmenu variable to twig.

You have to add the testmenu variable to the hook_theme implementation, like this:

function mdoner_custom_theme($existing, $type, $theme, $path) {
  return [
    'mdoner_custom_block' => [
      'variables' => [
        'title' => NULL,
        'testmenu' => [],
      ],
    ],
  ];
}

Then you have to pass it to the render array in your build() function like this:

return array(
  '#theme' => 'mdoner_custom_block',
  '#title' => 'MDoNER custom Block',
  '#testmenu' => $term_data, // #testmenu refers to the testmenu variable you set in hook_theme().
);

Now you should be able to iterate over the items in the testmenu variable like this:

{% for key, value in testmenu %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}


how to get previous step values in next step in drupal multi step form? How to get previous step values in drupal in the next step in a multiform. I want to display the values other than drupal_set_message(). I want to use these previous values in other function in the next step.

function form_example_wizard_previous_submit($form, &$form_state) {
  $current_step = &$form_state['step'];
  $form_state['step_information'][$current_step]['stored_values'] = $form_state['values'];
  if ($current_step > 1) {
    $current_step--;
    $form_state['values'] = $form_state['step_information'][$current_step]['stored_values'];
  }
  $form_state['rebuild'] = TRUE;
}

function form_example_wizard_next_submit($form, &$form_state) {

  $current_step = &$form_state['step'];

  $form_state['step_information'][$current_step]['stored_values'] = $form_state['values'];

  if ($current_step < count($form_state['step_information'])) {
    $current_step++;
    if (!empty($form_state['step_information'][$current_step]['stored_values'])) {
      $form_state['values'] = $form_state['step_information'][$current_step]['stored_values'];
    }
    else {
      $form_state['values'] = array();
    }

    // Force rebuild with next step.
    $form_state['rebuild'] = TRUE;
    return;
  }
}

function form_example_wizard_personal_info($form, &$form_state) {
   $form = array();
  $form['pagenumber']= array(
      '#title' =>t('Page Number'),
      '#type' => 'textfield',
      '#required' => TRUE
      );
  $form['wordscount']= array(
      '#title' =>t('Words count'),
      '#type' => 'textfield',
      '#required' => TRUE
      );
  $form['calcvalue'] = array('#type' => 'hidden',
  '#value'=>'test' );
  return $form;
}

function form_example_wizard_location_info($form, &$form_state) {
  $form = array();
  $form['quoteprice'] = array(
    '#type' => 'textfield',
    '#title' => t('Editing Your Document Will Cost'),
    '#value'=>$quoteval,
    '#required' => TRUE,
  );
  return $form;
}

There are so many ways to send data from one from to other.

You can use session
You can also pass value in url

Example of pass by value

function register_form_submit($form, &$form_state){
$name = $form_state['values']['name'];
$age = $form_state['values']['age'];

$data = array(
    'query' => array(
         'name' => $name,
         'age' => $age,
        )
    );

$form_state['redirect'] = array('/success', $data);
}

here is a link you can refer for send data

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


How to enable revisioning for user photo (user/profile field)? I want to moderate pictures, uploaded as user avatars. So, I need:

History for user field “Photo” to see all previous photoes.
UI for accepting or declining new photo.

How can I implement it?

The User Revision module would probably be your best bet

Add revision support to users and fields like there is for nodes.
For the moment all field from {users} have revisions, except for password

The picture property is contained in the users table so this module should do exactly what you're looking for.
The issue of a UI for accepting or declining a photo should go in another question otherwise this one will become too localised.


How to override certain function in a module to disable the return value Not sure how to explain this clearly but let me try.

/**
 * Implementation of hook_footer()  to insert Javascript at the end of the page
 */
function omniture_footer($main = 0) {

  global $user;

    $header = "\n";
    $header .= "\n";
    $header .= "'."\n";
    $footer .= ''."\n";
    $footer .= ''."\n";

$script  = $header;
$script .= $extra_variables_formatted;
$script .= $footer;

return $script;
}

Now my task is to disable the $script to not show in unpublished articles. Is there any way to do this in template.php preprocess?

Note: The below solved my question. Its 100% working in my end. Thanks

//Remove omniture tags in unpublish node
  if(arg(0) == 'node' && $vars['node']->status == 0) {
    $vars['closure'] = theme('closure');
    $omnitureTags = preg_replace( "/\

The value returned from the implementations of hook_footer() is used from theme('closure').

function theme_closure($main = 0) {
  $footer = module_invoke_all('footer', $main);
  return implode("\n", $footer) . drupal_get_js('footer');
}

That function is called from template_preprocess_page(), which uses the following code:

  // Closure should be filled last.
  $variables['closure']           = theme('closure');

  if ($node = menu_get_object()) {
    $variables['node'] = $node;
  }

If you want not to print the value returned by hook_footer(), you have the following options. As you are talking of articles, I get you mean nodes whose content type is "article"; if you used the word articles to mean nodes, then remove the part that checks the value of the type property.

Empty $variables['closure'] inside a preprocess function, which can be implemented in a module, or a theme (inside template.php). The following code is the code I would write for a theme.

function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'article' && !$variables['node']->status) {
    $variables['closure'] = '';
  }
}

If you are not interested in the content type of the node, then the code becomes the following one:

function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node']) && !$variables['node']->status) {
    $variables['closure'] = '';
  }
}

In the page.tpl.php file you normally find the following code to print the value returned from hook_footer():

<?php print $closure; ?>

Replace that line with the following one:

<?php if (!empty($node) && $node->type != 'article' && $node->status): ?>
  <?php print $closure; ?>
<?php endif; ?>

If you just need not to print the value of $closure when a node is not published, independently from the content type of the node, then the code simply becomes:

<?php if (!empty($node) && $node->status): ?>
  <?php print $closure; ?>
<?php endif; ?>

In this way, you can remove the value added to $closure from all the implementations of hook_footer(). You can also remove the part added from a specific module, if the module always adds the same string.

If you want to change the value returned from your implementation of hook_footer(), you can use menu_get_object() to get the node object associated to the page, if there is one.

function mymodule_footer() {
  $node = menu_get_object();

  if (!empty($node) && $node->type == 'article' && !$node->status) {
    return '';
  }

  // Return the value you would return when the node is published.
}


How to create checkbox instead of radio for just 1 allowed value? Because of this major Drupal 7 bug (http://drupal.org/node/811542), I cannot use radio options in my form.

I have three options in my form and I want them to be checkboxes, but the user can only select one checkbox.  By Drupal 7's auto form design, it converts single value items to become radios.  How can I get the below to become checkboxes that users can only select one without having to write my own module to override the form?

beef|I prefer beef

chicken|I prefer chicken

veggie|I am a vegetarian

Since checkboxes are multi-value options by nature. It would be detrimental to usability to override this default and expected behavior. You could change the validation as jimajamma suggests, but this would definitely lead to mass confusion amongst your users, as checkboxes are specifically intended for use for multi-value selections.

A slightly better, but still sub-optimal, option would be to use javascript to make sure that only one checkbox option is selected. Using javascript would at least mean that  users have immediate feedback rather than finding out after submitting the form (and it failing validation) that the completely expected behavior of multiple values for checkbox form items is no acceptable in this situation.

Since the Drupal core issue that you linked to specifically refers to sets of radio options that are not set as required, why not re-phrase the radio options so that you can make the form item be required?

For example, instead of the three options

beef|I prefer beef
chicken|I prefer chicken
veggie|I am a vegetarian

create a forth option,

none|No preference
beef|I prefer beef
chicken|I prefer chicken
veggie|I am a vegetarian

and set that fourth option as the default. In this way, you can successfully work-around the existing Drupal bug without confusing your users with non-standard behavior of form items and without creating any additional work for them. Not only is this better for users, but it requires no code customizations and is more easily maintainable (and easier to change once the bug is fixed).

In a situation with a yes/no question, you could use checkboxes and only provide one option, "Yes." Then you could evaluate "Yes" in its unchecked state the same way you would have evaluated "No" in its checked state.


Commerce Kickstart won't install Running latest versions of Drupal, modules and Commerce Kickstart
with Ubuntu, 4 GB RAM
Low Free Hard Drive Space, Swap file 2installs50 MB

I have read the posted how to installs but it still won't install.  I have only 1 GB of free space but I'm not sure that is the problem.   I suspect Kickstart unpacks itself and installs all at once, but I do not know.  Any suggestions?

Commerce Kickstart is a profile of Drupal and so you just have to select commerce kickstart radio button during your installation of Drupal. After selecting this, Drupal will start installing default products and all.
Download Commerce Kickstart and install it same as you install Drupal.


how to add field_image widget (imagefield crop) to a custom form api How can i add to my custom form api in my custom module the default widget from field_image?
I am using imagefield_crop module widget and it works in node/add form, but i cannot replicate it in my custom form api.

Problem is, Field API and Form API are separate things. You can add form elements to custom forms created with Form API, and you can add fields to custom entities created with Field API, but you can't really cross the border. Well, you can wrap form element into a field, but not the other way around.


I need to group a view by first initial (A,B,C) but both A and a are considered separate groups How can I get views to group upper and lowercase together?
I have the title field added twice in the view and the second instance under REWRITE RESULTS I have "Trim this field to a maximum length" of 1.  My view is grouped by this second field (so the first letter of the title.)
I have tried glossary mode with a contextual filter and that also didn't yield results.
Do I have to convert the field with strtoupper in a view template to achieve this?

In Drupal 8, a workaround is with twig. Choose the option to Override the output of this field with custom text and then use twig to capitalize.
{{ my_field|upper }}


How to use metatag:image_src to share images on Facebook using the Service links module? Image shared on Facebook via the Service links module is not showing up correctly when shared. I'm using Views with custom template to view this specific content.

Based on the Views configuration I can specify the image to be [metatag:image_src] in the metatag section. I have no idea where this syntax is going to get the image from, because I don't define this anywhere else, in the Views nor the Content type itself.

Another workaround I am looking at is to add a metatag tag in the head section via the hook_html_head_alter(). But I need more guidance on how and where to add this specifically, in detail.

The question about "How to change facebook og:image to post image link?" is not enough information for me.
The issue about Support for facebook "title" and "image_src" meta tags discusses the above.
I don't know how to patch using Allow Views meta tags to "Use replacement tokens from the first row".

I'm still digging through Drupal and no experience in module creation.

Anyone can point me to a more detailed solution regarding this issue?

I also created support request Image not showing on facebook share in the Service links module issue queue.

Try the approach suggested in Comment nr 1 of Issue nr 2387519, which is like so:

Install module Metatag (easy to understand module). Use the module and make your configurations.
Clear the cache.
Go to https://developers.facebook.com/tools/debug/og/object and click the "Fetch new scrape information" button to ping/update your meta tags to Facebook server.


hook_init for node redirect I need to check if the http_referrer var is a specific page in Drupal and redirect otherwise.

I was trying the Rules module but I need something flexible enough to add PHP code.

Can I use hook_init() in my template.php function to check for the referrer and the destination node and redirect if certain conditions are in place?

You can implement hook_init in a custom module.

function my_module_init() {
  // Since this file should only be loaded on the front page, it cannot be
  // declared in the info file.
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  }
}

But note that this WILL NOT work if the page is cached or if you are using a revers proxy cache. If you need to do this on cached pages look into using hook_boot

That being said, there is often better ways to accomplish a redirect based on certain conditions. Update your question with more details and perhaps we can find more suitable solutions.


View mode tabs no longer visible in Drupal 8 I have added custom display settings on quite a few content types, see image below:

The view mode tabs have now all of a sudden disappeared. I tried to uninstall third party modules and rebuilt cache multiple times but without any luck:

What can I try from here? I'm on 8.0.0-beta15.

The block showing the secondary tab menu was disabled. In order to activate it, I had to pay /admin/structure/block/list/seven a visit and manually re-add the Tabs block to the Pre-content region.


Can one feature module make additions to another feature module? I would like to have two feature modules for users to enable. One basic and one advanced. For example, the basic feature creates a blog content type, with only title and body fields. The advanced module, once enabled adds additional fields to that original content type, such as tagging or imagefield. Is this possible or will one override the other? Or will my site blow up? or?

It's definitely possible, I had to do something similar yesterday and I'm happy to say features can handle it perfectly.

The trick is that your 'advanced' feature will not contain the content type at all, but simply a list of the extra fields that are attached to the content type defined by the original rule.

When you install/enable the second feature module, the extra fields will be added to the existing content type as if by magic. I was pleasantly surprised at how well this works.

There is an example of a well established Drupal distribution using this same method (it's where I got the idea if I'm being honest); OpenPublish contains the openpublish_article feature, which defines a content type, and the openpublish_atricle_extra_media feature, whose sole job is to add a couple of extra fields to the article.

Just as a side note, it would probably be a good idea to make your main feature module a dependancy of the second, so the content type is definitely defined by the time the second feature is trying to add the extra fields to it.


How to add extra tab in common browsing widget in drupal commons Here i working in Drupal Commons.7.x and i need to add extra tab in that common browsing widget (Common Browsing Widget) section in common drupal.How to achieve to add extra tab in common browsing widget in common drupal.Here my need to in that image
Here i tried to change using

  structure => View => Common browsing Widget (Poll,Q&A,Event and etc.,)

. Need to add extra tab with content.how to achieve it.Kindly guide me.!

It uses Quick Tabs.

You can either goto admin/structure/quicktabs and edit the quicktab.

Or you can visit admin/structure/quicktabs/manage/commons_bw/edit which is the default quicktab for browsing widget directly add any block that you want.


How to create a "wall" with Drupal Commons? Does anyone know a way to show a sort of "wall" for any users, under the profile sections, like facebook with drupal commons? I think i'll have to add a block under the bio section right? My goal is that when a user will go to the profile of a trusted contact (friend) he/she can see all it's activities under the bio section.
However, if the user is not marked as trusted contact (friend) the activity will not be published.

I've found this answer but it's a little incomprehensible: https://forums.acquia.com/acquia-products-and-services/drupal-commons/drupal-commons-wall-facebook-wall ...

Flag
To implement "a trusted contact"? you could use the Flag module, whereas a user can "flag" another user as "I trust that user".
Views
Create some view using the Views module, in the format of a block, whereas you use the userid as a filter for such view. The actual content of such view should match with the "activities" you have in mind.
Rules block visibility
Use the Rules block visibility module to control the visibility of such block. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?

Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to creating a Rules Component to verify if the "current user" has flagged the user of the profile being viewed as a trusted contact. As per the great integration of the Flag module with Rules, that should really be like a "Getting started with Rules" exercise.


Check if the entity is new from the entity insert hook I have a custom content type, when I create a new content of this type via the admin ui I want be redirect to the edit page of the new node (not to the view page by default)

So, from an alter form hook, it's not possible because I don't know yet the node ID of the future node. From hook_entity_presave() it's the same: I don't know yet the node ID of the future node. From hook_entity_insert() hook, I have the node ID, but I don't know how can I check the entity is just created.

From hook_entity_insert(), is it possible to know if the entity is just created?

hook_entity_insert() is invoked only when an entity is created, not updated. That is evident from the method invoking it, EntityStorageBase::doPostSave().

  // Allow code to run after saving.
  $entity->postSave($this, $update);
  $this->invokeHook($update ? 'update' : 'insert', $entity);

hook_entity_update() is invoked for an entity being updated; otherwise hook_entity_insert() is invoked.

See also the description for the $update parameter passed to EntityStorageBase::doPostSave().

  bool $update: Specifies whether the entity is being updated or created.


How to extend link field type in D8? It's good to see the Link field type in D8. It takes a URL and (optionally) link text.

I'm adding a multiple links field to a content type and would like users to be able to provide some styling clues as well: e.g. this link is the primary one, this one needs a download icon. Basically let the user add CSS classes to each of the links in the same way they can add urls, text to each link they enter.

Is there a way to adding a new part to the field type?

(EDIT: I've put the answer into a custom module)

If you check \Drupal\link\Plugin\Field\FieldType\LinkItem, you see that it supports an array of options.

LinkFormatter then passes those to the URL.

So the only thing that you need is a custom widget that allows you to select/configure classes within the options somehow.


Add static images to bottom of view page I have a view called Courses, which outputs an table of college courses. I'd like to add two standalone images to the bottom of the page. Fairly simple really, but I'm not sure how to implement this layout. How can I achieve this?

In your view edit form, find 'FOOTER' (under Page Settins), click 'Add' and select 'Global: Text area'

In the content textarea, add your images markup (e.g. <img src="http://example.com/some_image.png" alt="This is my image!"/>), change text format to "Full HTML" and save.


How do I let users unpublish and publish their own content? I want to let users unpublish and publish their own content. By default, you have to give "administer nodes" permission for users to be able to unpublish or publish content. That is way to broad though. I want to let users unpublish or publish a node if and only if they created it. This also means they should be able to view unpublished nodes if and only if they created it.

A UI approach which I have used on some sites is the Override Node Options module, adds permissions similar to those that my other answer provides, plus a bunch extra.


Why aren't my local tasks shown? I have the module.routing.yml as

entity.node.ssl_check:
  path: '/node/{node}/check-ssl'
  defaults:
  _form: '\Drupal\ssl_check\Form\SslCheck'
  _title: 'Check SSL Cert'
  requirements:
  _permission: 'access check ssl tab'

and module.links.task.yml as

 entity.node.ssl_check:
  route_name: entity.node.ssl_check
  title: 'Ssl check'
  base_route: entity.node.canonical
  weight: 15

Here when I access node/1104/check-ssl/ the form defined in the form controller is loading. But my other need that is to show a 'Ssl check' tab when I visit path /node/1104/ is not there. I have done the tab thing while dealing with Controller but not working with form controller. Please help. I have checked 'Add tab / local task to a node' this but there was nothing dealing with form controller.

Since everything looked just fine in your code, I tried the following in a custom module:

#test.links.task.yml
test.node_test:
   title: 'Wooorking'
   route_name: entity.node.canonical
   base_route: entity.node.canonical

And this is working like a charm. Also when I added a custom routing, which was pointing to a form controller, it showed up! (although not worked, because I didn't handled the node parameter in the routing configuration)

So the problem lies another where.

So I suggest you to do it step by step way (building your routing and task yml) to understand your problem. Clearing the cache each time when you change something in your YML files. If you found the problem, please post the solution, so also we can learn from this.


Add programmatically exposed filter to view without removing the existing ones I want to add an exposed filter to a view which contains already exposed filters but without altering them.
When I add the following code it messes up  the exposed filters from the view and only the programmatically coded exposed filter works correctly.

I use the following code:

function music_m_views_pre_view(&$view, &$display_id = null , &$args = null)
{
$filter = $view->display['default']->handler->options['filters'];
$current_latter = arg(1);
$filter['field_last_name_value']['value'] = $current_latter;

$view->display_handler->override_option('filters', $filter);
}

The hook function used was wrong. I had to use hook_views_pre_build(&$view)
so I have now the following (and the other exposed filters don't get messed up):

 function music_m_views_pre_build(&$view) {

$view_filters = $view->display['default']->handler->options['filters'];

 $current_latter = arg(1);

 if($current_latter)
 {
    $view_filters['title']['value'] = $current_latter;

 }
$view->display[$view->current_display]->handler->handlers['filter']['title']->value = $current_latter;

}


I was wondering how to make "custom fields" in Drupal 7? I want to have a extra input field, called "URL" when adding content in drupal admin,
and then print that out in the template if something was inserted there.

My guess is that custom module is needed, but that's how far I got, as I have no idea what hook I need to use and how.
Or am I trying to solve this the wrong way?

No custom module is needed for this in Drupal 7.

Go to Admin > Structure > Content Types, click on "Manage Fields" by the content type you want to add the field to (e.g. admin/structure/types/manage/page/fields), select a type (e.g. "Text"), give it a name, and you're done. (There are some field settings you can change, but you don't need to.)

If you want something that does validation on the URLs, I'd recommend installing the link module, then choosing "Link" as the field widget type in the instructions above.


Form element title is not displaying translation I have got my own module providing a form and there is one element called "Estimated time" defined like this:

$form['informacie_o_incidente']['field_incident_doba'] = array(
  '#title' => t('Estimated time'),
  '#markup' => '
Estimated time:
'.$doba.'

',
);

I have translated the text "Estimated field" via translation interface, cleared cache several times (both GUI and with drush cc all command). However, when I run this drush command:

drush ev "print t('Estimated time');"

I am getting correctly translated string. So why not on the form?

I think you need  add t() in #markup and translate the string 'Estimated time:'

$form['informacie_o_incidente']['field_incident_doba'] = array(
  '#title' => t('Estimated time'),
  '#markup' => '
'.t('Estimated time:').'
'.$doba.'

',
);


How do I avoid the text on my site is selectable? I am wondering how to avoid the text on a Drupal 6 site is selectable, ideally only for certain node types.

It should help to make life a bit harder for content thieves. Apparently there is a module in Wordpress that does exactly this, but I could not find such thing for Drupal.

Try adding this code into your template.php file

/**
 * Implementation of hook_preprocess_page().
 */
function <THEMENAME>_preprocess_page(&$vars){

    drupal_add_js("(function($){
        $.fn.disableSelection = function() {
            return this
                     .attr('unselectable', 'on')
                     .css('user-select', 'none')
                     .on('selectstart', false);
        };
    })(jQuery);", 'inline');
}

You can try css methods also

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

A JavaScript solution for IE is

onselectstart="return false;"

See 826782


Get Exposed Filter Value How does one get the actual value for an exposed filter?

I can get the 'id' for a filter value using the following code and pulling the data out of the array, but this just returns integer values of 1,2,3,etc.:

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

using $view->get_exposed_input() results in the exact same issue.

How do I get the actual text string that is applied for the filter?

Specifically I'm trying to do this with a Global PHP field.

The simplest way to do this is by using a Taxonomy to define your filter. By default, the 'IDs' returned in the array will be TIDs, which you can link back to Term name.

This post provides some easy instructions on how to use a Taxonomy as your filter (you possibly need to add it as a relationship in your view)

Get your IDs (values) the same way previously:

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

Then simply step through the array to pick up and match the IDs to the term name:

$view = views_get_current_view();
foreach ($view->exposed_input['filter_name'] as $tid) {
  $term = taxonomy_term_load($tid);
  $name = $term->name;
  print $name;
}

Boom!


call_user_func_array() expects parameter 1 to be a valid callback, function 'access_denied_node_form' not found I am unable to edit a page content on my site even with the admin account.I have a page with the profile informations of the committee, I can see that page on the site but when i click the edit button it shows nothing.

I have seen the log and it is showing a error message as:

  call_user_func_array() expects parameter 1 to be a valid callback, function 'access_denied_node_form' not found or invalid function name in /var/www/includes/form.inc on line 377.

We have had this problem before in Drupal 6. It can happen if a content type is deleted, but, for whatever reason, nodes of that type still exist.

In this case, it would suggest that you have (or had) a content type called "access_denied" and this is no longer there.

First, note down the node ID of the node you're trying to edit. Then, find the node ID in the {node} table in the database, and find what node type it is.

Then, look in {node_type} in the database to see if your node type is listed there.

If you're missing a node type, you will need to restore the node type before you can edit that node. For example, if you uninstalled a contrib module that provided a particular content type, and that module didn't uninstall cleanly, you might have this issue, so you'd need to reinstall that module to fix things up.

There isn't any way that I know of to find the base module associated with a particular node type, unless it's obvious (the book module provides a node type of book, or similar), but if you are really stuck, you can always delete the node by visiting /node/123/delete - after all, if the base module is no longer present, the node itself probably isn't very useful to you.


Why does Drupal need list (integer, float AND text) and what is the difference? Could somebody explain why Drupal needs list (integer), list (float) AND list (text). What is the difference?

Values are set in key | value pairs. So:

list integer - saves key in database in integer format
list float - saves key in database in float format
list text - save key in database in varchar format

Why do we need list (float) and list (text), if we have list(integer)?

An explanation with examples would be great.

Occasionally you want to access a dropdown with Jquery - in this case it can be useful to have keys which are more than just integers.

Nothing I ever did, but you could use a dropdown to apply different classes to an element:

style-red|Red Layout
style-blue|Blue Layout

The value is the human readable label and the key is the class to switch around with jQuery. If you had used '1|Red Layout' and '2|Blue Layout' you need to tell JQuery that is has to translate key 1 into class style-red and key 2 into style-blue before applying them. So whenever you would add a new key|value pair you would not only need to edit your css but also your jQuery code, while using text keys you only need to edit the css file.

It is not a real world example, but you get the point.

For the float it is similar. Imagine you have a list with prices each with a human readable label plus a float you can instantly use for calculation in jQuery.


Rewrite empty Fields on Feeds periodic Import I have set up a periodic feed importer in drupal which imports nodes and updates existing nodes.

Lets assume the imported xml consits of two fields: the title and a long text field.

I import the nodes in the morning with the following content:

title   long text field
1       long text 1
2       long text 2
3       long text 3

So three nodes were correctly created with the two fields. But if I import later and the content of the xml has changed to the following:

title   long text field
1       long text 1
2
3       long text 3

As you can see the long text field of the second node is empty, but feeds doesn't update the field. The value after reimport is still 'long text 2'.

I haven't found an option or a module to achieve this. I have tried to manipulate the input data via

hook_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  // replace empty results with ' ' (one space), so they gets replaced
  for ($i=0; $i < sizeof($result->items); $i++) {
    for ($o=0; $o < sizeof($result->items[$i]); $o++) {
      if (empty($result->items[$i]['xpathparser:'.$o])) {
        $result->items[$i]['xpathparser:'.$o] = ' ';
      }
    }
  }
}

But feeds only jumps into the function if it detects changes in the xml, but i think empty fields don't get considered.

Yes, this is a known problem of feeds. However, there is a patch for it and will be included in the next release as I know. You can already apply the patch now yourself:https: www.drupal.org/node/1107522
It is #161 in the link above.

I am using it for a while and tested it too, it works for your scenario above.
There is one problem with email and URL fields: Feeds still creates the field when the import is empty and this results in empty fields shown.


Adding an Image field in webform module I am a newbie to drupal 7 and just started working with it a couple of months ago. My problem is I am making a "webform" where the user filling the form should upload his image. But as there is no such field I am not able to understand how to do it.....

I also tried the "entityform"  but as I install it and enable it, the edit links all over my website starts throwing an exception...

So please help me. Any help will be appreciated.

Thanks in advance.

To add an image field to a webform:

To go the webform tab where you manage the fields.
Add a new field of type file:
On the new field configuration page it's a good idea to set an Upload directory for your images. This means all the images upload from this field will sit in a particular folder in your files directly and help prevent too many files from sitting in one folder. You can also choose what types of files you want to allow users to upload. For an image field I would suggest only gif, jpg, and png.
Set any other settings such a label or display settings as required.
Finally save the component.
Now when you visit the frontend of your webform you should see your new field:


Management of priorities with node_access I do not understand how priorities are set for the node_grants... I have a module node_grants function that provides 4 grant ids for the user, but some nodes only have 2 gids... how do I know which one allows the user to view the node or not?

Thanks,

If you install the Devel module, there is a sub-module called Devel Node Access (DNA) that you can also enabled.

When you do this, two new blocks will become available.  One shows node access by users.  The other shows the access records for the node you are viewing (or the nodes that happen to be on that page), both hook_node_access() and grants.

Typically, I will install both blocks at he bottom of the Content region, as they can be big/wide, and only give their view permission to a few users.  If I am having grant weirdness, then I give the permission to all on a test site, and use user masquerading to see what is happening.

And as for priorities, this is described fairly well in the documentation on node access rights.  In short:

Deny by default
Check for bypass access permission
Call hook_node_access() per Drupal module ordering.  First denier wins, then first allower wins.
If there isn't a winner, hook_node_grants() is run per Drupal module ordering to build the list of grants.  Then tirst denier wins, then first allower wins.
Otherwise deny.

Try to read through node_access(), after the node access rights page, for the finer details.


Creating a field that has node values using FAPI I would like to use the Form API to create a form that uses a textfield that references all the current nodes as an autocomplete. Is there a way to added field using the FAPI that allows a user to type the node's title or ID and the field is validated by whether the node exists.

If it is for a custom module, Drupal makes it quite easy to do an autocomplete field.

See a tutorial here... http://timonweb.com/posts/how-to-create-an-ajax-autocomplete-textfield-in-drupal-7/

You would then do a validation function to determine whether the entity exists, or you would only provide a list of existing entities in the first place.

If you are using the core fields, then try the entity reference module.


Add a class to the first teaser on /blog page On a site I'm developing the first blog teaser on the blog index page /blog is displayed bigger than the other teasers. I do this with a class 'featured', can I add a function in template.php to add this class to the first blog teaser on the /blog page?

Thanks for your time

In the template_preprocess_node hook you can use $vars['id'] to get the array index in the order that the nodes are printed.

You'll need to replace COND_FOR_BLOG with whatever logic you have for checking that.

Example to get you started:

function THEME_OR_MODULE_preprocess_node(&$vars) {
  if (COND_FOR_BLOG && $vars['id'] == 1) {
    $vars['classes_array'][] = 'featured';
  }
}

Edit: Note that $vars['id'] is not zero-based so $vars['id'] == 1 actually gives the first post.


How to make a user choose male or female and keep a default image on a specific content? How can I make a user choose male or female and keep a default image on a specific content?

I mean I want two defaults pictures (for male and female), but only for default image in case user want to upload a different image this should be accept as normal.

And all this for one specific type of content.

I want this, just because this field must captures a photo but for the ones who don't want to upload a photo show a default profile image.

You can do this on the display level via

hook_preprocess_field() (thx Clive in the comments, give him a thumbs up!), OR
a custom formatter, OR
a custom Display suite field

hook_preprocess_field() on the image field is the easiest.

You have the full user entity available and can use information from other fields to alter the image.

The hook is fired every time theme('field', ..) is fired, so you need to figure out if this is the correct field.

EDIT: Instead of a detailed tutorial, here is what I usually do:

Install devel
Create your custom module with an implementation of hook_preprocess_field(&$variables).
Do dpm($variables) inside that hook implementation to show the function argument (sometimes you need to refresh the page twice to see the result).
Manipulate the part of $variables that you are interested in.

With a custom formatter, you can define your own way to display e.g. the image field, while having the data from other node fields available.

Then on the user display configuration, you can choose this formatter to display the image.

With the custom DS field, you can introduce a "field" - that is, a positionable element on the entity display. This field can use data from multiple data fields on the node entity. E.g. you first check if there is an explicitly uploaded image, and if not, you show an image depending on the gender (male, female, transgender / don't say).

You can also define a form to configure display options. E.g. you could make the image style configurable.

Steps:

Enable Display suite
Implement hook_ds_fields_info() in a custom module, using e.g. DS_FIELD_TYPE_FUNCTION.
Provide the function to generate the html or render array (some examples)
Configure your user to display with a Display suite layout.
Enable your custom field.

There are more details to this. But I the main purpose of this answer is to point you in a direction.

The weakness of all these options is that you have to hardcode the field names, or at least one of them. If you want to reuse this on another site with other field names, you have to change the field names in the code.


Migrating a Content Types and its Nodes into another site I have 2 Drupal 7 sites and I want to migrate data from one into the other. One of the D7 sites has a bunch of content types that the other doesn't have, along with a bunch of nodes associated with it (about 1000+ nodes). It's something I can't migrate manually or else it would take forever.

I know everyone points to the Migrate module to do something like this, but are there other similar methods that are just a streamlined. FYI, I never used the migrate module, as it seems like its more for migrating foreign data from other DB sources into drupal.

I remember there was another module that lets you copy data from another Drupal site, but it has to be the same version. Which one was this called?

Now the question is, what is the fastest approach in migrating data + content types between same version Drupal 7 sites? And what are some other caveats I might need to know?

migrate_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed

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

Using this module you can easly migrate your content types to other d7 instance.
Here You Just need to give database link form which you want to migrating content types.


Theming individual menus Let me fully describe the problem I am trying to solve as there may be a better way of doing what I am trying to do.

On my Drupal 7 install, when a user is logged out, the Main menu shows Home / Log In and a few other links I've added. This is $primary_nav in the theme.

When a user is logged in, a Log Out link is added.

What is confusing however, is that there is still a login link in the Main menu.

My solution was to create a second menu that would replace the Log in link with a link to the user's account page when they are logged in. All other links would remain the same.

In the template, I am doing the following:

<?php // show different menus depending on if the user is logged in ?>
<?php if ($user->uid): ?>
<?php $menu = menu_navigation_links('user-menu'); ?>
<?php print theme('links__menu_user_menu', array('links' => $menu)); ?>
<?php else: print $primary_nav; ?>
<?php endif; ?>

And this correctly shows the right menu depending on whether the use is logged in or not.

However, the styles are completely different. $primary_nav is a horizontal menu and user-menu is a vertical menu.

According to http://drupal.org/node/254940#theme-suggestions-for-menus, I should be able to create a function in my theme's template.php file and style it. However, I tried doing the following:

function MYTHEME_menu_tree__user_menu(&$variables) {
  echo 'Success'; exit;
}

But that code is not run.

So my questions are these:

1) Is this the best approach to replace Log In with a link to the user account page when the user is logged in?

2a) If so, what's the best way to get the menu styled the way I want it?

2b) If not, how can I achieve the effect listed in 1)?

Thanks!

If you use user as login path, it will visible after login.

You should replace user with user/login it will gone after login.

Also user's profile link is available in User menu, just edit it and change its parent menu to your primary nav.


How to Associate Page Title with Author as Variable or Token or Relationship I have created a custom content type for each of several contributing users for multi-blog purposes. I then used Views to create a page for each content type and thus a "blog home page" for each user.  I have also modified my theme's node.tpl.php file to reflect the custom look I want for displaying the teasers for all the custom content that is created.

The current header portion of my node.tpl.php file:

<?php if (!$page): ?>

<?php endif; ?>

  <? print " | "; ?><? print render($date); ?>

<?php print render($title_prefix); ?>
<?php if (!$page): ?>
  <h2 class="title" <?php print $title_attributes; ?>>
    <a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>
<?php print render($title_suffix); ?>
<?php if ($display_submitted): ?>
  By
    <?php print $submitted; ?>

<?php endif; ?>
<?php if (!$page): ?>

<?php endif; ?>

I can display the custom content title with $title, the date it was submitted by $date and the author by $submitted.  What I would like to include is the title/link to the page (that was created by the view of the custom content type associated with the author).

Is this something I can use relationships for to somehow generate a token and/or variable?

I don't really have any idea about how to approach this; any ideas or advice are much appreciate... thanks!

In your theme template.php file add preprocess_node as below.
The below code will grab the author of current node for your custom content type.
And $node_author will be available to user on node.tpl.php
With the help of $node_author you can make the link

//
//Override or insert variables into the node template.
//
function MYTHEME_preprocess_node(&$variables) {
  //dpm($variables);
  if($variables['type'] == 'my_custom_content_type') {
    $node_author = $variables['uid'];
    $variables['home_page'] = $node_author;
  }
}

In your views add contextual filter for author uid to grab from url.
This should work for you.


Autocomplete term widget (tagging) I was using the "autocomplete term widget (tagging)" as widget type for a term reference field. I found out that the when I set the maximum number of allowed values to more than one (i.e multiple choices), the auto complete does not work after you have added one option.

Do you have any idea on how to work around this?

I too am using autocomplete for a term reference field and multiples are working fine - are you sure you're putting commas between terms? e.g. I type "one, t" and as I type "t", "two" will come up as a suggestion if the term is in the vocabulary.


Taxonomy term pages with multiple views I currently use only one view with path taxonomy/term/% and without any vocabulary verification.

However, I would like to create two views: news and products (to implement different themes) linked to two vocabularies (1 per 1): news_categories and product_categories.

news_categories looks like:

  category 1
  category 2

product_categories

  category 1

  subcategory 1

  category 2
  category 3

  subcategory 1

I don't want to allow displaying terms which are not from this vocabularies.
In addition I use pathauto to generating path, which sometimes are a few level dept.

I found a module called Taxonomy Views Integrator, but I'm not sure it's in 100% stable, so my question is that you are any other ways to handle many taxonomy term pages by views?

Required modules: Views, Pathauto, Simple hierarchical select, Taxonomy Views Integrator.

Create content type "food".

Create vocabulary "food" add some example terms:

+ fruits
  - apples
  - orranges

+ vegetables
  - carrots
  - potatoes

Pathauto settings

go to: admin/config/search/path/patterns and set the taxonomy term paths:

pattern for all food paths -> [term:vocabulary]/[term:parents:join-path]/[term:name]

Thanks to this pattern our food paths will look like: food/fruits/apples and may contain more than one parent, for example: food/parent1/parent2/parent3/child

Go to: admin/structure/taxonomy/food and check if all paths are setted up correctly. If not, edit them and check Generate automatic URL alias.

Views

Create view showing taxonomy terms from food vocabulary and add these three displays:

Page: Title: "`All food content`"

Path: /food

Relatonship:  Taxonomy term: Content using Food terms.

Page: Title: `Food category`

Path: /food/%

Relatonship:  Taxonomy term: Content using Food terms.

Contextual filter:  (field_food_terms) Content: Has taxonomy term ID (with depth)

contextual filter settings: depth = 1 (use: this page override)

Override title: Food category - %1 This means, if we go to food/fruits, all items one level below fruits will be shown (all fruits)

Page: Title: `Food subcategory`

Path: /food/%

Relatonship:  Taxonomy term: Content using Food terms.

Contextual filter:  (field_food_terms) Content: Has taxonomy term ID (with depth)

contextual filter settings: depth = 0 (use: this page override)

Override title: Food subcategory - %1

There is no terms below, if we go to food/fruits/apples, all items with term name apples will be shown (only apples)

Use Views to override term paths

At the end you need to go back to: admin/structure/taxonomy/food edit each term and choose Use view override.

For each term you need to specify which view will be used to override, it's the main disadvantage of this solution.

Results

An example of article and blocks with relationship to the taxonomy.


Image getting delete away by the cronjob later in drupal 7 using theme settings i`m using system theme settings alter to add 4 images for theme, images are getting deleted /swept away by the cronjob later .trying using  FILE_STATUS_PERMANENT images are not getting set as permanent

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

  $form['themeA_settings']['header-page']['header_background_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Header Background'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://themebackrounds/',
    '#default_value' => theme_get_setting('header_background_file'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
  '#submit' => array('themeA_submit_handler'),
  );

  $form['themeA_settings']['block1']['block1_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('block1 image'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://themebackrounds/',
    '#default_value' => theme_get_setting('block1_file'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
  '#submit' => array('themeA_submit_handler'),
  );

 $form['themeA_settings']['block2']['block2_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('block2 image'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://themebackrounds/',
    '#default_value' => theme_get_setting('block2_file'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
'#submit' => array('themeA_submit_handler'),
);

$form['themeA_settings']['footer']['background_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Footer Background'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://themebackrounds/',
    '#default_value' => theme_get_setting('background_file'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
 '#submit' => array('themeA_submit_handler'),
  );

  }
   function themeA_submit_handler($form, &$form_state) {
        // Load the file via file.fid.
     if (isset($form_state ['values']['header_background_file'])) {
     $file = file_load($form_state['values']['header_background_file']);
          }
     if (isset($form_state ['values']['block1_file'])) {
       $file = file_load($form_state['values']['block1_file']);
           }
       if (isset($form_state ['values']['block2_file'])) {
          $file = file_load($form_state['values']['block2_file']);
        }
      if (isset($form_state ['values']['background_file'])) {
       $file = file_load($form_state['values']['background_file']);
     }
           // Change status to permanent.
           $file->status = FILE_STATUS_PERMANENT;
          // Save.
        file_save($file);
          // Record that the module (in this example, user module) is using the file.
        file_usage_add($file, 'user', 'user', $account->uid);
     }

A quote from the docs:

  Note: New files are uploaded with a status of 0 and are treated as temporary files which are removed after 6 hours via cron. Your module is responsible for changing the $file objects status to FILE_STATUS_PERMANENT and saving the new status to the database. Something like the following within your submit handler should do the trick ...

You would need to put the example code that follows in the docs, into a function that you add as a submit handler:

$form['themeA_settings']['header-page']['header_background_file'] = array(
  '#type' => 'managed_file',
  ...
  '#submit' => array('your_custom_submit_handler'), // <-- This line is new
);

The function itself could look like this then:

function your_custom_submit_handler($form, &$form_state) {
  // Load the file via file.fid.
  $file = file_load($form_state['values']['my_file_field']);
  // Change status to permanent.
  $file->status = FILE_STATUS_PERMANENT;
  // Save.
  file_save($file);
  // Record that the module (in this example, user module) is using the file.
  file_usage_add($file, 'user', 'user', $account->uid);
}

You can of course reuse that function for all your files.


block->subject set when using one theme, but not when using identical copy of the theme? I have a theme (based on zen). I made a copy of the theme, replacing all the references to the theme's name in the files. I switched to the new theme and copied all theme settings in drupal (drupal 6).

As far as I can tell everything looks just the same, except that on some blocks (notably the footer menu) the name ("Footer Menu") appears. From the theme files i see this is because $block->subject suddenly is set.

What's up with this - if the themes are identical and the configuration is the same, why does one have a block->subject set and not the other?

Looks to be a known issue. I see blocks display emptry string for $block->subject. in this thread someone mentions that they had to modify system.module for this to work. you can check it out in this thread here. Looks like a patch is out there for it.


How can I sum up fields that reside in multiple nodes? I am using Drupal as an inventory management system and wanted to know how can I sum up fields to get a net total?

Say I purchased 10,000 widgets over 2012, and I want to be able to sum up all the fields in those nodes to get a final total then have it displayed in a block giving me a summary of how much I spent during 2012. I want to be able to archive this data into a type of report.

I know I should use the Views module, but I want to know how others would accomplish this situation.

What kind of performance roadblocks could I run into, if I had 1 million nodes? Would my site crash? can this be lazy loaded. if needed?

The SUM functionality is actually built into Views for D7.

If you go to your Advanced settings and enable Aggregation, you will see the Aggregation settings applied to each field.

Click on 'Aggregation settings' for the field you'd like to do the SUM functions for and you can select 'SUM' from the 'Aggregation type' dropdown as shown in this screenshot

Taken from Source Sum a field


How may I curtail or minimize the text below CKEditor (while keeping it available for screen readers)? In the add/edit form of a node, is there a way to reduce, hide, or minimize the Text Format block information contained inside of <div class="form-item form-type-textarea form-item-body-und-0-value">?

Would it be best to do an accessible hide as mentioned in Drupal 7, two new system classes to improve accessibility by using the classes .element-invisible and .element-invisible.element-focusable? Or should I edit a template file?

I'm using the Autoform Block module and placing this block inside the main page of an Organic Group. The rich text editor is managed by using the CKEditor module.

if you want something interactive, you can do this - this example assumes a field called body working on a node of type article, adjust as necessary:

in css, for .page-node-add-article .field-name-body .filter-wrapper .fieldset-wrapper { display:none; } - this will initially hide the text format
add this JS either in a custom module or in html.tpl.php before , so long as it runs after ckeditor, or the classes won't exist and throw an error:


D8 - Cannot make Custom EntityType translatable When I am trying to make a custom entity translatable I get the following error message:

The Redirect entity entity type cannot be translatable as it does not define a translatable "langcode" field. in <em class="placeholder">Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions

After checking other modules and the drupal docs I have to define 2 things:

1.) I need to create a translatable "langcode" field
2.) I need to set the entityType annotation to translatable

Still I receive this error.

My annotation of the entityType:

@ContentEntityType(
 *   id = "email_confirm_redirect",
 *   label = @Translation("Redirect entity"),
 *   admin_permission = "administer email confirm redirect entity",
 *   base_table = "email_confirm_redirect",
 *   revision_table = "email_confirm_redirect_revision",
 *   data_table = "email_confirm_redirect_field_data",
 *   translatable = TRUE,
 *   handlers = {
 *     "list_builder" = "Drupal\email_confirm_redirect\Entity\Controller\RedirectListBuilder",
 *     "form" = {
 *       "add" = "Drupal\email_confirm_redirect\Form\RedirectForm",
 *       "edit" = "Drupal\email_confirm_redirect\Form\RedirectForm",
 *       "delete" = "Drupal\email_confirm_redirect\Form\RedirectDeleteForm",
 *     },
 *     "access" = "Drupal\email_confirm_redirect\RedirectAccessControlHandler",
 *   },
 *   list_cache_contexts = { "user" },
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "title",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "edit-form" = "/admin/email_confirm_redirect/{email_confirm_redirect_entity}/edit",
 *     "delete-form" = "/admin/email_confirm_redirect/{email_confirm_redirect_entity}/delete",
 *     "collection" = "/admin/structure/email_confirm_redirect/list"
 *   },
 * )

The field declaration in my baseFieldDefinition() function:

//langcode
        $fields['langcode'] = BaseFieldDefinition::create('language')
            ->setLabel(t('Language'))
            ->setTranslatable(true)
            ->setDescription(t('The redirect language code.'))
            ->setDisplayOptions('form', array(
                'type' => 'language_select',
                'weight' => 2,
            ));

I think you also need to add it to the entity keys:

entity_keys = {
  "id" = "id",
  "label" = "title",
  "uuid" = "uuid",
  "langcode" = "langcode"
}

Also make sure you're running drush entity-updates and clearing cache when making changes to base fields/annotations.


Computed Twig solution not showing in preview? I'm trying to understand Twig.

This is what I have got

{{ (data.number_1) * (data.number_2) }}

Why doesn't the preview page calculate the solution?

I figured it out. You need to create a "Preview Page" as per Computed Twig example.

webform 5.x has an inbuilt preview page which does not recalculate when viewed.


How to add a condition based on a line-item's product type in a rules tax component? In Drupal Commerce, when you create a tax rate of a particular type, let's say a "VAT low" of type VAT, a rule "Calculate taxes: VAT" is created, as well as a rule component "Calculate VAT Low".

Now I want to make the "Calculate VAT Low" component conditional on the product type of the product referenced in the line item. The examples for conditions in the tax component that I found, however, use data selectors of the order like address, not a line item.
Other examples of using conditions based on the product type referenced by the line item are configured at the level of the rule, not the component (e.g. here). The commerce-line-item:commerce-product:type does not seem to be available when adding conditions to a component.

Is it possible to make tax components conditional on the product type of the line item? Or should I create a separate rule for each tax rate component rather than use the default "Calculate taxes: VAT"?

I found out how to use product type as a condition - it actually does work the same for rules and rules components.

When I tested this, I was adding the condition "Entity has field": field_product, but in order for the commerce-line-item:commerce-product:type data selector to appear under the Data comparison condition, you have to use the field commerce_product, which is the product reference field used on the line-item entity.


My images paths contains NULL I have this content type called "Product" that contains a "Multimedia asset" field (Media module), called Images.
Everything is working (I can access the image), except all my upload images have "null" in their path,e.g. "mydomain.com/sites/all/files/null/product-928.jpg."

The same happens when the image is rendered with a image style; in that case the path is "mydomain.com/sites/all/files/styles/table_icon/public/null/product-928.jpg."

("table_icon" is the name of my image style.)

I am using Drupal 7.10 and the Media module 7.x-1.0-rc2.

Do you have any idea on how to solve this problem?

Thanks!

This is a known bug with the media module. See Issue #1351890: Wrong upload destination folder "null" and Issue #1364676: Upload path. The latter of the two contains a patch to fix this.


Access licensed files only after admin changes order status to completed I watched the Commerce File screencast which shows how to create a downloadable file as a product. It appears to be for version 7.x-1.x but currently the recommended version is 7.x-2.x which has since changed significantly.

I'm trying to achieve the same outcome as the screencast whereby the user can only see his licensed files after the order has been changed to completed by an admin. Currently, the moment the user submits his order, he can already see his files. I tried checking the checkout rules, however, the only event option closest to what I want to achieve is "After updating an existing commerce order", and that did not work either.

How can I prevent users from accessing the licensed file until the order has been processed?

Sorry I don't have time to watch the screencast.

You could create two rules, the first which trigger when an order is payed in full, this rule could change the order status to pending.

Then you could make another rule which triggers when an order is saved, with the condition that it is in the pending state, it is changed to completed (which allows access to the files).

This could cause complications if you actually use the 'pending' order status for other workflows, in which case you might need to make a custom status you can use as an in between for your review process (using this module https://drupal.org/project/commerce_custom_order_status).


All visited urls ending with _900 in cache_page tables I came across strange problem with drupal 7 and caching for anonymous users. After clearing cache, newly visited pages by anonymous users are stored in cache_page with _900 at the end of url like this www.example.com/examplepage_900. Anybody know what can cause this behavior?

This issue was caused by module http://drupal.org/project/resp_img after installing the latest version, everything is ok.