page-new.tpl.php shows page not found in browser title The page displays fine, however; the browser tile shows Page Not Found | main title of site.

How can I apply a proper title to this custom page when another page controls the header ?

This will set the title in the actual browser window:

function MYTHEME_preprocess_page(&$variables) {
  drupal_set_title(t('Custom title'));
}


Creating new content/node I want to do something very simple - create a content of a specific type when a user joins a group.

Unfortunately I can not find a simple way of how it should be done.

It can be done with rules so I've been thinking about triggering one, but the details would be awfully complicated.
I thought about having a template node that I would clone and edit, but how should I go for it? There are number of modules that do that in a strange way, while saying "it might sometimes not work properly", some people use things like drupal_execute(), I have found that node_save() has an option $node->is_new = TRUE.
I found someone suggesting a use of forms, but they were always very simple and were not working with complicated/custom fields. I figured that maybe something like this could work:

$form = drupal_get_form('my_content_node_form');
$form_state = array();
do_some_edits($form,$form_state);
drupal_form_submit($form->id, $form_state);

What is a proper/simple way of dealing with this issue? What I would expect see is something like $node = node_create($content_type) but for some reason I can not find it.

Provided you have a rule that triggers when a user joins a group, and a condition that checks that the group is the group you want, then add a execute PHP action to that rule that runs this code :

// Build a new node object
$node = new StdClass();
// set the type
$node->type = 'your_content_type';
// set the language
$node->language = LANGUAGE_NONE; // or whatever language you use.
// this fills the node with the default data
node_object_prepare($node);
// set a custom title
$node->title = 'Nice title';
// set whatever you want, for example body
$node->body[LANGUAGE_NONE][0]['value'] = 'This is some text for the body';
// Set the formatting for the text
$node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';
// Save the node to the DB
node_save($node);
// If you need the node ID
$nid = $node->nid;
// Just for debugging
watchdog('your_module','Just inserted the node with nid = '.$nid);

The key here is that node_object_prepare sets some default values for your content type.


Link field to views pages and nodes On my content type I want to allow a content administrator to insert a hyperlink to a page and allow them to define a list of related pages. This works fine for linking to nodes, but I am unable to get Views Pages to list.

I have tried the following options:

references module - only allows you to reference nodes
View reference - Not an interface I want to give to a non-techie
entityreference - also does not allow you to reference views pages
viewfield - only allows you to insert views and the interface is not end user friendly
linkit with linkit views - could not get "views pages" to list, documentation seemed to imply it was possible

The items are all in my main menu, is there not a module or picker out there that allows you to pick menu items?

Maybe View Reference ?
Please refer to this page


Updating a field programmatically, hook_node_update Currently trying to update a field every time a node is created or updated. However the value is not being populated within the node, do I have access to the node object with this particular hook? What could I be missing?

  function vbtoken_node_update($node) {

      entity_get_controller('node')->resetCache(array($node->nid));

      $types = node_type_get_types(); //What are the current Node Content Types?
      $yes = ($types['volunteer_project']->type);

      if($node->type === $yes){

        $hash = md5($node->title . $node->nid . $node->nid);
        $hashed = substr($hash, 0, 6);
        $node = node_load($node->nid);
        $node->tcode[$node->language][0]['value'] = $hashed;
        node_save($node);

        watchdog('vbtoken', 'Added a new Token code to %nid', array('%nid' => $node->nid));

        }
        else
        {
          dpm('not working dude');
        }

    }

Entity metadata wrappers

The entity API provides some wrapper classes you may use to easily deal with entities and to leverage the entity property information modules provided. With the help of the wrappers you can access the property information, loop over known properties, or just get/set the described data values, etc.

These are some simple usage examples as found in the README:

For making use of this information (metadata) the module provides some
wrapper classes which ease getting and setting values. The wrapper supports
chained usage for retrieving wrappers of entity properties, e.g. to get a
node author's mail address one could use:

$wrapper = entity_metadata_wrapper('node', $node);
$wrapper->author->mail->value();

To update the user's mail address one could use

$wrapper->author->mail->set('sepp@example.com');

or

$wrapper->author->mail = 'sepp@example.com';

The wrappers always return the data as described in the property
information, which may be retrieved directly via entity_get_property_info()
or from the wrapper:

$mail_info = $wrapper->author->mail->info();

In order to force getting a textual value sanitized for output one can use,
    e.g.

$wrapper->title->value(array('sanitize' => TRUE));

to get the sanitized node title. When a property is already returned
sanitized by default, like the node body, one possibly wants to get the
not-sanitized data as it would appear in a browser for other use-cases.
To do so one can enable the 'decode' option, which ensures for any sanitized
data the tags are stripped and HTML entities are decoded before the property
is returned:

$wrapper->body->value->value(array('decode' => TRUE));

That way one always gets the data as shown to the user. However if you
really want to get the raw, unprocessed value, even for sanitized textual
data, you can do so via:

$wrapper->body->value->raw();

More examples:

$wrapper->body->set(array('value' => "content"));
$wrapper->field_text[0] = 'the text';
$wrapper->field_text[0]->set(array('value' => "content"));
$wrapper->field_text2->summary = 'the summary';
$wrapper->field_text2->value = 'the text';

$wrapper->save();
$wrapper->delete();

More docs: http://drupal.org/node/1021556


Get fid from file path I've to create a custom function to display images because I've to add values from custom fields.

I've added a function to template php, like this:

function mytheme_image($variables) {
}

The problem is that in $variables I haven't the fid of the file, but only the path. I have to load the file to get values from field, how should I do?

I'm looking for functions to get fid from path but I haven't found something..

@pvorb, you can also use EntityFieldQuery.  See the first comment on https://api.drupal.org/api/drupal/includes%21file.inc/function/file_load_multiple/7 for an example.  Something along the lines of:

$filename = 'myfirstpony.png';
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'file')
  ->propertyCondition('filename', $filename)
  ->execute();
// if you are guaranteed there is exactly one result, then:
$file_object = reset($result['file']);
$fid = $file_object->fid;
// but beware you might get 0 or many results

If you have more information -- such as the path (from which you can generate a URI) -- then change the query condition to something like ->propertyCondition('uri', 'public://path/to/myfirstpony.png').


Loading in iframe on ajax form submit I've a form with couple of buttons, on submit it redirect to third party site for authentication.
On the submit I want to load that inside iframe on same page. How I can do that?

I think that you can do it with jQuery.

Add this code in your template: <iframe id="frame-id" src="" frameborder="0"></iframe>
Add this jQuery:

$("#SUBMIT-ID").click(function(e) {
  e.preventDefault();//This prevents the site from being redirected.
  var a_href = $('.A-THAT-HAS-REDIRECT-CLASS').attr('href');
  $("#frame-id").attr("src", a_href);
});


How to theme a menu in drupal 7 with this html

Home
The card of flight

News
The actual & promo

Compagnies
More details

Airports
Prepare your travel

Forum
The community

Use theme_menu_tree() theme function overrides

https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_tree/7

Copy the contents of 'Code' on these pages to your theme's template.php and change the 'theme' in the function names to the name of your theme, for example:

function yourcustomtheme_menu_tree($variables) {
  return '
' . $variables['tree'] . '
';
}

Make the changes to the HTML tags, save the template.php and clear caches.

Also if you just want to customize HTML for a specific menu, you can name your functions like this: THEMENAME_menu_tree__MENU_NAME()


How know if user is visitor or logged member? How can I determine programatically whether the current user is anonymous or authenticated?

For the sake of more robust and descriptive code, you can make use of the handy User::isAnonymous() method, e.g.

if (\Drupal::currentUser()->isAnonymous()) {
  // Anonymous user...
}


EntityStructureWrapper for file field is not being inflated properly while iterating While trying to interate over file filed values, EMW cannot being created properly. using isset() for not iniated fields and then trying to set them is not helping.

I get the error:

  EntityMetadataWrapperException: Unknown data property
  field_discipline. in EntityStructureWrapper->getPropertyInfo() (line
  335 of
  /var/www/siradisisporlar.com/sites/all/modules/ssbasic/entity/includes/entity.wrapper.inc).

Note that file wrapper here is EntityStructureWrapper and node wrapper is EntityDrupalWrapper.

All properties of other entity reference fields, etc are being reached properly.

$filew::data is array and it has fid where $nodew::data is a proper node object.

mymodule_node_insert($node) {
  //.... ..... $nodew is node wrapper
  foreach ($nodew->field_media as $delta => $filew) {
    $a = $filew->field_taxonomy_entity_reference->value(); //error here
    $b = $nodew->field_taxonomy_entity_reference->value();
    $c = array_unique(array_merge($a, $b));
    $filew->field_taxonomy_entity_reference = $c; //error here
    $filew->save();
  }
}

Sadly, I am posting a very bad workaround for future reference. Anybody who can improve this is welcome:

function mymodule_node_insert($node) {
  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //@todo this is not cool, figure it out
  foreach ($nodew->field_media->value() as $delta => $files) {
    $filew = entity_metadata_wrapper('file', $files['fid']);
    $filew->field_taxonomy_entity_reference = array_unique(array_merge($filew->field_taxonomy_entity_reference, $nodew->field_taxonomy_entity_reference));
    $filew->save();

  }
}


Drupal Panels/Views conflict I'm using Drupal 7 along with the Panels and Views modules. I've got a view with a page display, but I want to place it in a panel/page. I need the view's display to be that of a page because it has exposed filters, and I can't rely solely on AJAX for the filters because of 508 standards compliance concerns.

However, because the paths of the panel and the view are the same, the view takes precedence, and the panel never shows up. How do I get the view working inside the panel?

Create your view as a content pane instead of a page. Then on your panel insert the content pane. You can also look at something like http://drupal.org/project/panels_everywhere as a more general solution.


How to change text on Drupal WorldPay button? I'm using the Drupal WorldPay module (for Commerce 7.x-1.11).

On the checkout page it says "Pay via WorldPay". I want to change this. I've traced it back to a line in the module:

function commerce_worldpay_bg_commerce_payment_method_info() {
  $payment_methods = array();

  $payment_methods['commerce_worldpay_bg'] = array(
     'title' => t('Payment via Worldpay'),
     'description' => t('Integration with Worldpay\'s Business Gateway method.'),
     'active' => TRUE,
     'offsite' => TRUE,
     'offsite_autoredirect' => TRUE,
     'callbacks' => array(),
   );

  return $payment_methods;
}

Specifically:

'title' => t('Payment via Worldpay'),

I think I can override this in the theme template.php but have no idea how, and there seems to be very few instructions on how one might go about it.

In this specific case, you can implement hook_commerce_payment_method_info_alter(&$payment_methods) in a custom module, and alter $payment_methods['commerce_worldpay_bg']['title'].

If you see other instances of the strings, which aren't changed, then you can use the String Overrides module, as already suggested, or use the $conf global variable in settings.php as follows.

$conf['locale_custom_strings_en'][''] = array(
  'Payment via Worldpay' => 'Your string',
);

Keep in mind that the latter two methods change the string wherever it is used; they don't provide a context to understand where the string is being used. This could be something you want, or not.


Social Media Managament - Feed Scheduling I am wondering if there is a module that allows you to set up a schedule and auto post to social networks?(FB and Twitter)

You can create a Feed that aggregates any data you need at the rate/schedule you want.

Once you have your feed set up, you could use a service like twitterfeed.com to automatically post your data to the social networks of your choice.

Basically you'd just create an RSS feed and plug it into twitterfeed.


jquery.js from CDN sources I hope use a CDN source as default, which doesn't load the local jquery.js while the CDN is OK. If the CDN doesn't reply, load the local jquery.js.

I have writted this in my template.php.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="<?php echo base_path().path_to_theme(); ?>/js/jquery.min.js"><\/script>');</script>

It worked well until I used the Flag module, which loads the flag.js file. I think this file just work with the version of jQuery that comes with Drupa, as it doesn't work with the jQuery library from Google CDN.

Did Drupal developers rewrite the whole jquery.js? I cant believe that.

What should I do to solve this problem? Can I fix it by rewriting flag.js?
If it's possible I really don't want use other module such as the jQuery Update module; it is too huge.

No, Drupal devs didn't rewrite jQuery, a standard version is included (1.3.2). I can vouch for flag.js working fine with that version of jQuery.

It's not compatible with the version of jQuery that you're including though. You're probably also introducing a conflict between the two versions of the library that are included in the page.

jquery_update isn't a huge module at all, and it gives you several versions of jQuery plus the CDN option out of the box. It was written specifically to solve the problem you're trying to get round.

There's no good reason not to install it; if you don't, you'll just be reproducing functionality it already provides, which is time you could spend doing something productive.


Show/hide views on content-type based on taxonomy-terms I have an activity-content-type with a taxonomy field, where I can choose from different taxonomy terms related to the activity. Now I have different views and I want to show the specific view on every activity-page, which is related to the chosen taxonomy-fields.

Lets say I have different bike-tours and diff. hikes (activities). Some are for beginners and some are for pros - some are for families and some are for couples and so on. Now I want to cross-link between the different activities and give more inspiration regarding suitable activities. If someone clicks on a bike-tour that is tagged with "beginners" and "families", drupal should show a view that offers other activities (bike-tours and hikes) that suit that criteria - also tagged with "beginners" and "families". Something like "Other familyfriendly beginner activities".

The machine names of the views don't relate with the chosen option at the moment. I would need to build a view for every combination at the moment - this is fine now (few combinations) but not scalable. I thought about combining all in one view (ideal), but couldn't find a solution yet.

Emanuel

The general idea is the following:

You create a custom block (via custom module).
You place it through the interace to be visible only on nodes of type "A".

The code checks the value of field_tags.

if it is "tag1" -> views_embed_view('test_view_1', 'block_1');
if it is "tag2" -> views_embed_view('test_view_2', 'block_1);

You can see code below:

namespace Drupal\form_overwrite\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Default block"),
 * )
 */
class DefaultBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    // Gets current node.
    $node = \Drupal::routeMatch()->getParameter('node');

    // Assuming only 1 value here.
    $tid = $node->get('field_tags')->getString();

    // If there are more values you have to loop through them. The format is.
    // $tid = $tag[0]['target_id'];

    // Loads the taxonomy term.
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

    // Gets the label.
    $name = $term->label();

    // TODO: probably a better idea would be to use uuid of those terms, since
    // the names tend to change overtime.
    // TODO: Didn't test a case with translations.
    if ($name == 'tag1') {
      // Using the old but gold function views_embed_view() to get renderable array.
      // The render function spits the html, based on views_embed_view output.
      $content = render(views_embed_view('test_view_1', 'block_1'));
    }
    elseif ($name == 'tag2') {
      $content = render(views_embed_view('test_view_1', 'block_1'));
    }
    else {
      // Case where there is not tag.
      $content = '.....';
    }
    $build = [];
    $build['default_block']['#markup'] = render($content);
    // TODO: Remove it after development. It is used only to invalidate the cache.
    $build['#cache']['max-age'] = 0;

    return $build;

  }

}


How to determine if Varnish/Pressflow is caching content in a useful way? I recently converted one of my D6 sites to Varnish/Pressflow and saw a very modest improvement in average load speed (from ~550ms before to ~450ms now). But, I also noticed that the initial load time for the first load in a round of tests were consistently much higher --- around 1000ms. They quickly fall down to ~450ms during subsequent reloads during the same test.

This makes me think that I've configured something incorrectly, and Varnish isn't serving from the cache until after the (anonymous) user has already visited the page in question. Perhaps the session IDs are causing each session to be cached independently from eachother (though I understand that shouldn't happen for anonymous users under Pressflow).

The X-Varnish headers appear in both the initial page load, and subsequent loads, so I know the content is at least getting passed through Varnish.

Is there a way to get details about part of the Varnish cache is serving a particular page (e.g. when the cached page was created)? I've tried looking at the logs generated by varnishlog, but apart from various apearances of "X-Drupal-Cache: HIT" I'm not sure what to look for.

Below is the text that can been seen when using Google Chrome and under Network inspecting the response for you webpage. Observe the very last line. There you should get two numbers X-Varnish:1125490268 1125489929.

I've had problems before setting up Varnish and everything seemed to be going fine, then I noticed that only one number was present in X-Varnish. When fixed the two numbers appeared with a decrease in response time form 500ms to 45ms :)

Hope it can help you on the way.

Request URL:http://www.somepage.com/
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:www.somepage.com
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.52 Chrome/28.0.1500.52 Safari/537.36
Response Headersview source
Accept-Ranges:bytes
Age:230
Cache-Control:public, max-age=900
Connection:keep-alive
Content-Encoding:gzip
Content-Language:en
Content-Length:6411
Content-Type:text/html; charset=utf-8
Date:Tue, 30 Jul 2013 08:03:13 GMT
Etag:"1375164849-1"
Expires:Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:Tue, 30 Jul 2013 06:14:09 +0000
Server:Apache
Vary:Cookie,Accept-Encoding
Via:1.1 varnish
X-Drupal-Cache:HIT
X-Generator:Drupal 7 (http://drupal.org)
X-Powered-By:PHP/5.3.10-1ubuntu3.6
X-Varnish:1125490268 1125489929


why not redirect to another page after form submit I do this in my form submit

    $form_state['redirect']='checkout/' . $order->order_id;

but it not redirect to checkout page ( I test with another urls but it not work),
I take screen shot after set redirect ,

also I get $from_state by ref in function function pre_register_node_form_submit($form, &$form_state) {  , what do you think? where is the problem?

another note is when I am use drupal_goto form not saved !!!, it redirect to my page with out anything saved.

Do you suggest me declare another submit function and add it to submit array of my content type and in it set redirect?

Update

also I test below

 if ($form_id == "pre_register_node_form") {
       $form['#submit'][] = 'mysite_submit_redirect';
}

function mysite_submit_redirect(&$form, &$form_state) {
  $form_state['redirect'] = 'home';
   // ym($form_state);

}

but not redirected :(

If that's a node form, the problem is the node submit handler sets the redirect already in node_form_submit

If you want to redirect to checkout after a node form submit, you can do it by adding a submit handler to the $form['actions']:

/**
 * Implements hook_form_alter
 */
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'NODE_TYPE_node_form') {
    $form['actions']['submit']['#submit'][] = 'MODULE_NODE_TYPE_submit';
  }
}

/**
 * NODE_TYPE submit handler
 */
function MODULE_NODE_TYPE_submit($form, &$form_state) {
  // You don't need order_id as /checkout will route to the correct location for user
  $form_state['redirect'] = 'checkout';
}

Note: You could also do it with Rules.


Display multiple values of a field in separated rows I'm using drupal 7, and in my node views, I have a field named field_phone to display phone numbers. It is possible for a company to have more than a phone number, so I add some more rows in form edit to add more phone numbers. Instead of displaying all numbers in multiple rows, Drupal automatically puts them all inline inside a <span> tag. There are so many people on google trying to the opposite thing: make them display inline.

So I think that, by default, it displays multiple values in separated lines. How can I get over this stuff?

P.S.: I know I can edit the template file, and make it display the way I want, but it's not cool at all, when I have to edit all the field template files, as all my multiple-values-fields are displaying that way.

1) If you are using a view with field you can click on your field and have a look at

"MULTIPLE FIELD SETTINGS"

the checkbox "Display all values in the same row" is checked by default. If you uncheck it it's going to show your field in different rows.

2) If you are using a view with content (teaser, full etc..) you can modify the output in different way:

Have a look at Field API
The one you may need is template_preprocess_field()

function templatename_preprocess_field(&$variables) {
    if($variables['element']['#field_name'] == 'field_name') {
        if($variables['items']['0']['#markup'] == 'your_value') {
            $variables['items']['0']['#markup'] = '';
        }
    }
}

If you have Devel Module you can use the dsm() function to see how to manupulate it.

function templatename_preprocess_field(&$variables) {
        if($variables['element']['#field_name'] == 'field_name') {
            dsm($variables['element']);
        }
    }

It will show what's inside $variables['element'] as a drupal message.

3) You can use field.tpl.php and use field-name-[field_name].tpl.php to target only your field. Have a look at theme_field() .

If you want to change all your multiple value field in that way, use the second method without the if statement that targets your field.

Find out the method better fits your needs.


Placing the comment form on a separate page Is it possible to place the comment form for a content type on a separate page? I have some teasers on the home page and since I did them using Views, I need to find a way for people to add comments to it. If I can place a link which opens another page with just the comment form then that would be great.

Drupal has this built in, the link you are after is comment/reply/[nid].


Add unlimited fields to block module I'm creating a module which adds a block.
In that block, I want users to be able to add as many (text) fields as they need. I know you can set up content-types to allow users to add as many fields as they need, but how can I implement this into a block module?

Long story short: is it possible to add a text field with an unlimited amount of fields to a block (module) the same way it can be done in content types?

You might be looking for Node Block module.

With this module you can make your block fieldable, like your content-types.

  This module allows you to specify content type(s) as being a block.
  This allows the content managers of the site to edit the block text
  and title without having to access the block administration page.
  Users only need edit access to that node in order to edit it.

Check out this quick Demo Video


Modify the display of one field by the value of another field We have a content type with a date range element on our D8 site. I got a request to hide the display of the end date if the content editor decided so.

From testing, the content editor can't delete the end date-- the field fails validation if an end date has already been specified. And anyways, they don't want to delete the end date-- they want to maintain that information-- they only want it not to display to the public audience, in certain circumstances.

I started to approach this by adding a second field to the content type, a boolean checkbox "Hide End Date". I wrote a hook_preprocess_field in our .theme file in order to change the display of the date range value. But after debugging the variables, I realized that the date range field doesn't have any information about the value of the "hide end date" field, of course.

I'm not sure how best to proceed. Is hook_preprocess_node the place where I can look at both field values, and alter the value of the date range field? Will that affect display of the field throughout the site, including views?

Add a boolean field as a condition to hide the end-date is a fine solution. For hiding the field you can either check for the boolean in the template:

{% if $node->field_hide_end_date->value %}
    {{ $node->field_range->value|format_date('my_custom_date_format') }}
{% else %}
    {# Original version of the field #}
    {{ $content['field_range'] }}
{% endif %}

Or change the value in a preprocess method

function custom_module_preprocess_node(&$variables) {
  if (array_key_exists('field_period', $variables['elements'])) {
    $node = $variables['elements']['#node'];

    if ($node->field_hide_end_date->value) {
      $variables['elements']['field_period'] = [
        '#markup' => (new DrupalDateTime($node->field_period->value))->format('d-m-Y'),
      ];
    }
    // else: business as usual.
  }
}


How to make a new field type visible to the Rules module? I have installed the Examples for Developers module, and enabled the Field Example submodule. It creates a new field type called field_example_rgb.

I've added this field to a new content type. I'm trying to set and/or display the value of the field using Rules - to no avail. Rules does not "see" the field in the node.

I've tried adding a file called field_example.rules.inc that implements hook_rules_data_info(), still without luck. Can someone please help me figure out how to make the field visible to Rules?

This is the code of the hook_rules_data_info()

   function field_example_rules_data_info() {
  return array(
    'field_example_rgb' => array (
      'label' => t('example color rgb'),
      'wrap' => TRUE,
      'property info' => array(
        'rgb' => array(
            'type' => 'text',
            'label' => 'RGB',
        ),
    ),
    ),
  );
}

Just add the property_type key to the array you already have, like so:

'property_type' => 'text',

With that added line, the Entity API knows how to handle that field.

For a more complex field, such as fields with more than one database column, it is not enough to simply declare the property type. You need to specify further callbacks that may alter the generated property info. To do so, you need to use the key property_callbacks to add a custom callback function that will provide the extra metadata required. For example:

'property_type' => 'field_example_rgb',
'property_callbacks' => array('field_example_rgb_property_info_callback'),

Source:
Describe field properties to make custom fields work with Entity Metadata Wrappers, which includes some more info about this topic also.


How to change timezone format for user/site settings? I want to change the user configurable timezone format on the regional settings and user settings form.

For example, it displays as Asia/Kolkata: Friday, October 9, 2015 - 17:24 +0530 I want to display it as Asia/Kolkata. I have used following code but not working.

function my_modue_form_system_regional_settings_alter(&$form, &$form_state, $form_id) {
dpm(timezone_identifiers_list());
dpm($form);
$form['timezone']['date_default_timezone']['#options'] = timezone_identifiers_list();
}

Is it possible to do this?

Yes, you're close. The problem with the above code is that it doesn't set the correct key values in #options; thus upon saving, the date_default_timezone variable will be set to some numeric key instead of an accepted PHP timezone string that is expected for the variable.

Do something like this to set the correct key:

function token_form_system_regional_settings_alter(&$form, &$form_state, $form_id) {
  $options = array();
  foreach(timezone_identifiers_list() as $timezone) {
    //$options[$timezone] sets the value for date_default_timezone select
    //$timezone set the display for select
    $options[$timezone] = $timezone;
  }
  $form['timezone']['date_default_timezone']['#options'] = $options;
}


How to display the user's preferred language in a User profile page In a Drupal 8/9 site, I can select the User's preferred language.
In the "Manage form display" page (for user's fields), there are two rows which are about language:

Language settings (settings = --no settings available--)
Language code (settings = "language select" as the only option)

Question 1 : What do these two options produce?
In the "Manage display" page, I can display only one item about the language : Language code
As a result, if I visit my user profile page, I can see:

Language code: French

But if I change my preferred language in my user edit profile page into Dutch, there is no effect in my "User view" page: it is always "French"
ok, I can preprocess something and adapt the twig template to display my preferred language but this is not the answer I would like to have.
Question 2: I would like to understand this behavior because, as always in Drupal, I am sure there is a good reason for that.

I think I could answer myself to most of my questions:
1-The Language code field store the initial language of a user... it looks like it can't be changed after all. For my use case, it is an useless field.
2-The Language settings options display the Preferred language widget and the Administration pages language widget. I think that this last widget is there only if you check Account administration pages language setting. in admin/config/regional/language/detection
3-The most important part: How to display the preferred language of a user in the the display user page (/user/xxx)
You can do it with this hook:
function mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == "user") {
    $fields['preferred_langcode']->setDisplayConfigurable('view', TRUE);
  }
}

I really don't know why it is not a default... (don't hesitate to add any information on this point)


How to change bean's block view mode programmatically? I have created a block entity using bean module.

It has three image fields. Image1, Image2 and Image3.

I want to show only one image depending upon current time. I have three time values.
For this I have created 3 view modes each for one time value.

Now I'm stuck that how will change the view mode based on time value programmatically.

I have used the following code.

function glue_site_block_view_alter(&$data, $block) {
  if ($timevalue1 == $value1) {
    $data['content']['bean']['block_delta']['#view_mode'] = 'view_mode1'
}

You can use hook_entity_view_mode_alter()

function MYMODULE_entity_view_mode_alter(&$view_mode, $context) {
    if ($timevalue1 == $value1) {
      $view_mode = 'view_mode1';
    } elseif {
      .......
    }
}


How load only some node fields? entity.query service is very handy when it comes to finding nodes with specific field values. Unfortunately all it returns are entity IDs and revision IDs.

In case in which result set is big it's really inefficient to load whole nodes if only data from specific fields is needed.

In D7 it was possible for example to use field_attach_load() function which (thankfully) has been removed in D8, as detailed in Fields are no longer handled individually and are bound to an entity type. The problem is that Drupal change log references loadFieldItems() and doLoadFieldItems() of FieldableEntityStorageControllerBase class neither of which exists in current release of D8.

What is the Drupal 8 way of loading data for specific node fields only?

I did some profiling with a query of 100,000 nodes, fetching the field myfield from all nodes of type mybundle.

Good: A dynamic query with addField()

$connection = \Drupal::database();
$query = $connection->select('node__field_myfield');
$query->condition('node__field_myfield.bundle', 'mybundle');
$query->addField('node__field_myfield', 'field_myfield_value');
$result = $query->execute();
$values = $result->fetchAll();

This runs in about 250 milliseconds.

Bad: An entity query with loadMultiple()

$query = \Drupal::entityQuery('node');
$query->condition('type', 'mybundle');
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$values = [];
$nids = $query->execute();
$nodes = $node_storage->loadMultiple($nids);
foreach($nodes as $node) {
  $values[] = $node->get('field_myfield')->getValue();
}

This took 3 minutes after a few repeated attempts when the cache was fully built. After a cache rebuild, it took more than half an hour.


Remove only admin info in nodes I'm using Drupal 7 and Clean theme. And i want remove only submitted by admin, dont remove date info.

Looked node.tpl.php and node.module files but not seen this fields. How can i remove this info?

Remove $submitted from your template and use below code

$timestamp = $node->created;
print format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL);


How to display a image and some text instead of unset a field using form_alter hook? In D7 I have a field photo on the user account page (user edit form).

I have a conflict between the modules conditional state and simplecrop therefore I like to disable the conditional state module for this field and replaced it by some code in the form_alter hook..

When another field has a value of ok/not oke I can e.g. use the function like

if( set my check here) {
        unset($form['field_photo']);
}

But I do not want to unset the field. I would like to display the image and put some text here.

How to achieve this?

Using unset() with form elements is always wrong.

To avoid the form element is shown, just set its #access property to FALSE or to the value returned from a function, and that form element will not appear in the form, or it will appear basing on what returned from that function.
Once you make it not accessible from the currently logged-in user, you can add the form elements you need, not forgetting to add the form submission handler to handle the input given from the users for those form elements you add.


How to filter a view by the value of a global variable (as with the variable module)? I have a global variable, which is the id of a node representing a current organic group that changes every year. I'd like to have a rules view that filters on members of that group. I've added the right relationships and a filter on the group id of the membership entity. But I can't enter a token or a variable value in the filter dialog. What can I do?

Use contextual filter and Provide default value = PHP Code


How do you redirect anonymous users to another page without rules? Right now i want to restrict  all anonymous users to a specific page. I know you can do this with rules by setting the condition if they are anonymous have them redirected to another page. But how can this be done via code? Also I need to add exceptions to the redirect as I dont want users redirected out of user/login page, but everywhere else.

I think something like below should work.

function modulename_init() {
  global $user;
  $args = arg();
  if(!user->uid && ($args[0] == 'user' && $args[1] == 'login')) {
    drupal_goto('page_you_want_anony_to_redirect_to');
  }
}


How to choose to which group new content will be visible? I have a content type: Event. I put instances of Event inside the Calendar(everything works great). I also have Organic Groups installed and set up(I have a group called: employees).

Now, the problem is that when I create an Event I can't find dropdown list where I can choose to whom this content will be visible(to which group).

How to make it show up?

This is Drupal 7.

One have to add a field to content type: og_group_ref.


Create content types containing other content-types I've created a custom content-type called "Books."

I need to create another content type named "Catalogs" which may contain one/many "Books" as its fields.

How would I achieve that? I'd prefer some GUI tool to construct my custom content type, from admin panel, or doing some coding, if necessary.

PS: I found this question asked here but the solution did not help. Can someone provide a detailed answer, please?

EDIT:

MohammadAliAkbari's answer works perfectly :) One problem - When adding "Books" a user can add Books not created by him - he can add any Book to his "Catalog" - How can I add constraints such that a user can add Books only created by him to his Catalog?

Solution:

Using Tenken's answer, I figured out that I can write this code in my module to solve the scenario just mentioned above:

function myModule_form_alter(&$form, &$form_state, $form_id) {
//    dsm($form_id); // Use this line to find YOUR-DESIRED-FORM-ID
    switch ($form_id) {
        case 'YOUR-DESIRED-FORM-ID':
            $form['#validate'][] = 'stylesku_add_sku_form_validate';
//            dsm($form); // Use this to find out form's elements
            global $user;
            $currentUser = $user->uid;
            $fieldSku = $form['FIELD-ID-OF-BOOK'];
            $lang = $fieldSku['#language'];
            $fieldOptions = $fieldSku[$lang]['#options'];
            foreach($fieldOptions as $nid=>$nodeTitle){
                if(!is_int($nid))
                    continue; // Needed as the first option in select box is not really any book
                $nid = (int) $nid;
                $n = node_load($nid);
                if($n->uid != $currentUser){
                    // Remove this BOOK, this book was not created by current user
                    unset($form['FIELD-ID-OF-BOOK'][$lang]['#options'][$nid]);
                }
            }
            break;
    }
}

Ok, you should be familiar with

entity
view mode
entityreference

after install entityreference create a reference to books in your catelogs content-type, then go to catelogs > manage display and for books reference select Rendered entity formatter and in its options set something like teaser

after this go to books > manage display and configure teaser as you need.

also you can add more view modes by Display Suite or via simple module:

function mymodule_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['render_in_catelogs'] = array(
      'label' => t('render in catelogs'),
      'custom settings' => FALSE,
  );
}


How to get the value of a datetime when form submitted I am writing a custom module in which i am declaring a $form element as #type=> 'datetime'

The code for the buildForm method is

 $form['timesave'] = array(
    '#type' => 'datetime',
    '#title' => $this->t('Select Date and time'),
  );

Now my question is how do we get the value of the field on form Submit as i have to store the value in a configuration

I have tried with

$form_state->getValue('timesave');

This is giving an array some protected methods.

You can use the method getTimeStamp() to store the timestamp like this :

$form_state->getValue('timesave')->getTimeStamp();

Or you can use the format() function to store a formatting date.

$form_state->getValue('timesave')->format("Y-m-d H:i:s");


Override html.tpl.php per node type does not work I saw that this was asked few times before, and I tried the answers, and I tried modifying the answers, yet nothing.

Case:
I have Advanced Forum installed, and I am using HTML5 Application Cache (appcache) (don't you dear to run away now!).

Obviously I need to turn appcache off when surffing forums, and I managed to make custom html.tpl.html for /forum and /forums, so when I am looking forum list and topic list I won't get cached.

But then:
When I am looking at forum topic, it is a post ofc, and post type (machine type is forum) and I have defined in template.php:

$node = menu_get_object();

if ($node && $node->nid) {
    $vars['theme_hook_suggestion'][] = 'html__' . $node->type;
}

and it won't make change.

So I am able to change html.tpl.php for path but not for node type.

Help me please and correct my knowledge for making such things.

Thanks for all!!!
(btw i dont need a lesson of appcache, sincerely if you have manifest = x.appcache" in your html tag it will cache it, even if it's in network section)

you don't need different template for this.
you can set variable in preprocess function and print it.

function MYTHEME_preprocess_html (&$variables, $hook)
  $node = menu_get_object();
  $dont_cache = array('some_type');
  if (!empty($node->nid) && in_array($node->type, $dont_cache)) {//check if it is node and if it shouldnt be cached
    $variables['appcache'] = '';
  }
  else {
    $variables['appcache'] = 'manifest = x.appcache';//put your value here
  }
 }

and then print $appcache in you html.tpl.php


Fork currect Drupal installation Is it possible to fork current Drupal installation for experiments and have two versions of Drupal with one installation of Apache, PHP and MySQL on Ubuntu?

thank you

Yes; See the handbook page on drupal.org: Installing virtual hosts for Drupal sites and subsites.


How to change Contact Form sendto from admin dynamically In D7 I have a hook_form_alter to make changes to the Contact Form (Core). How can I  change the sendto address from the admin to another email addres that is determined when the user requests the form?

The core contact form is pretty limited in functionality. If you need more features, I recommend building your own form using the Webform module.


What is the difference between Referenced Entity and Referencing entity in views I just wanted to know what is major difference between

Entity Reference: Referenced Entity
A bridge to the Content entity that is referenced via field_FIELD_NAME

AND

Entity Reference: Referencing entity
A bridge to the Content entity that is referencing Content via field_FIELD_NAME

While using relationship in views or when I prefer to Entity Reference: Referencing entity

Say you have a content type called course that has a entity reference field that targets a content type called school.

In views you could now add a relationship using "Entity Reference: Referenced Entity" and fetch values from the school that the course belongs to.

You list of courses could now show something like:
Course X - School X

So far so good.

Now let's say you want to list schools and which courses they provide.
Since the entity reference field points from course to school you need to fetch the reference the other way. Now you can instead use "Entity Reference: Referencing entity". This way you could list schools and courses:

School X - Course X.

You will end up with duplicate rows in some cases if several courses points to the same school, but that's another story :)

Hope this made the relationship bit clearer.


Load a user object via login form name field I'm trying to check if a user account has been disabled for LDAP before the user completes the login process using a custom form validator.

What has me stuck is how I would use user_load to load the user object of the person logging in via the login form. I'm not sure how I would structure the form array within the user_load function.

What I currently have is:

$account = user_load($form_state['values']->name);

Thank you for your time.

For user_load function in D6 you have to use pass the $user_info array like ,

 $account = user_load(array('name' => $form_state['values']->name))


Organic Groups Custom theme/layout Hi I would like to give all organic group pages a custom theme and layout. How would I go about doing this? For example, I want the main site pages to follow a certain theme/layout, but when you go to any group page the theme and look is entirely different. Is this possible?

The Delta module allows you, via the Context module to make duplicates of your theme settings for any context on your site. This gives you the ability for alternative layouts as a reaction in Context. The Delta module was originally created to compliment the powerful Omega base theme, but now works with ANY theme (3.x Version)


Remove module folder when uninstalling is there any method/module that allow removing module folder when uninstalling the module
or delete the files via dashboard

To take a different angle:

It's very possible to do this, but you shouldn't. Your web server user should not have the capacity to write to the web root (except for designated folders like the public files folder). You should therefore not be able to delete module folders from code. Doing so presents a security risk to your server.

This is one of the checks the Security Review module performs, and throws up a nice big red error if it find the web server can write to such files:

I understand this might be unavoidable if you're on shared hosting, but I think it's a good piece of information to have either way.


Drupal Signup: how to signup to multiple events at once? I've been looking all over the internet for this, but couldn't find anything about it. The thing is like this:

I am creating a Drupal 7 website for a training institute. On the website I am showing the trainings in a calendar with the Calendar, Views and Date modules (see also http://drupal.org/node/998334#part1 )

With the Signup module users can signup for a single training by leaving their name, address, etc. But I would like to make it possible to signup for multiple events at once. The available events should be listed on the signup page and can individually be checked. The user will then be signed up for all the selected events with only once filling in the form.

Does anybody know if there is a workaround for this?

Thanks in advance!

Someone put together a hacky solution for "Signup" module (which is apparently similar to "CCK Signup"). Maybe it's a good starting point: http://drupal.org/node/151898.


How to add js in view created by interface I want to create a new button control in my ip_geoloc leaflet map. So, i created a view by using the drupal interface -> /admin/structure/views/view/markers_admin/edit

And now i want to set a custom JS wich execute only in this view. I've create a module to create custom form. And my goals are when the user click on the button control in the map, a modal pop with a form with lat/lng field to add dynamically the marker on the map.

I searched everything (how to create a modal -> colorbox, how to create a custom button, how to add the marker...) but i don't know how to attach the javascript to this page.

I've tried to implements these hooks (4th comments) in my custom module but this not work : https://www.drupal.org/node/1993228

Can you help me ?

If you are following that 4th comment exactly the problem is probably that it is a hook for viewing a node, not for a 'view'. Ambiguous to be sure.

The accepted answer here should be helpful: How do I add JavaScript specific for a view?.

EDIT

Okay, this may be more helpful. The trick here is finding a place to hook in to check to the page before it is rendered to add the javascript to the render array. The assumption this code makes (which may not be accurate) is that you are looking at a views page. If the view is nested in a block or a panels pane this may not work as well.  Here goes:

/**
 * Implements hook_page_alter().
 */
function food_truck_form_page_alter(&$page) {
  $views_page = views_get_page_view();

  if ($views_page->name == 'marqueurs_admin') {
    $path = drupal_get_path('module', 'food_truck_form' );
    $page['#attached']['js'][] = array(
      'type'=>'file',
      'data' => $path . 'js/food_truck_form.js'
    );
  }
}

This also assumes that you are implementing it in a module called food_truck_form and your view is named 'marqueurs_admin'.

Also, as a side-note, it often works better formatting-wise to edit your post to add the additional info there rather than in the comments.


Why does my site still use URLs containing the "q" query parameter? I have pathauto, transliteration and automatic node titles enabled.

In the settings, my content path pattern is content/[node:title]. I expect the URLs to be in the format site/content/page-name, whereas what I have is site/?q=content/page-name.

I cannot figure out why. Do you have any idea?

The initial ?q= has nothing to do with pathauto, that is handled by Clean URLs. You should start by verifying that you have those enabled on admin/config/search/clean-urls

If clean URLs are enabled but don't work, or fail to become enabled, the most common cause is that the .htaccess file from the Drupal root directory is missing. This is unfortunately somewhat common since the leading dot in the filename makes the file hidden.

Occasionally, the clean URLs test gives a false negative result.

This assumes you are running a Apache web server; otherwise, you will need to seek URL rewriting help for your particular webserver. You will be able to find Drupal specific instructions to the vast majority of webservers with Google.


JavaScript dependencies for a specific block or page I am migrating a Drupal 7 site to Drupal 8.  I have a custom block (visible only on the home page) that has some tabs on it.  Currently, the tabs are implemented using jQuery UI tabs and it would be nice (but not necessary) to keep them using that.

In order to get this to work, I need to use the jQuery and jQuery UI JavaScript files.  However, everything I have seen online talks about module and theme dependencies.  There doesn't seem to be any way to tell Drupal 8 that a specific block (or page, etc.) needs specific JavaScript files loaded in order to work correctly.

I know that I can just import the javascript files directly with script tags, but that doesn't seem to be the preferred method, especially considering all of the various optimizations that are part of Drupal (to make sure that a file is only included once, for example).

How do I include the required JavaScript files (available in core) on a specific page or as part of a specific block?

I don't really want to create a custom module for every time that I need to do this, but all of the references I have found online talk about dependencies for themes or modules, nothing for specific content.

EDIT: Multiple suggested answers involve PHP, custom modules, YML, etc.  These are not what I am looking for.  I am looking for a solution for front-end content creation (pages, nodes, blocks for the "custom block library", and so on), not requiring back-end coding and development.  Modules on Drupal.org that allow this to be done generically are perfectly acceptable.  Maybe I need to create one and put it up there, but I would think there should be an existing solution by now.  It seems strange to me that there isn't, but maybe I'm missing something.

Define an asset library in mymodule.libraries.yml. An asset library can declare either CSS assets or JavaScript assets, or both. It can also declare dependencies on other asset libraries. For example on jQuery (core/jquery) or perhaps your JavaScript defines a "Drupal behavior", in which case you depend on the supporting infrastructure for that (core/drupal). Ex:

example_library:
  js: path/to/some/file.js: {}
  dependencies:
    - core/drupal
    - core/jquery

Use #attached in your block's render array to attach the asset library:

// Assuming the variable containing your render array is called $build.
$build['#attached']['library'][] = 'mymodule/example_library';

Extensive documentation can be found at https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module.


Alias / to /lang_code I got a multilanguage configuration with language detection based on URL(/en /fr). Drupal behavior redirects everything to so it would have those two prefixes or, if setup, it will ignore the prefix for a language while keeping for the other.

In my situation I need to keep the prefix for both language except for root page.

Ex:

example.com/en -> will load english homepage
example.com/fr -> will load french homepage
example.com/ -> has to load english homepage but without redirect to /en

So, how can this be achieved?

Drupal core doesn't redirect everything. Do you have the Redirect module installed? Then disable the route normalizer in the module settings, which is by default enabled:
/admin/config/search/redirect/settings

GLOBAL REDIRECTS
[x] Enforce clean and canonical URLs

If you want to keep the global redirect try this module specifically for the language prefix Disable Route Normalizer.


Finding nodes that have not been indexed On a Drupal 8 website I'm administering the ratio of paged indexed by search_cron stays at a value far below 100%.

New pages are indexed, but it looks as if updated pages are not indexed again. I suspect that there is some problem that keeps nodes from being (re-)indexed. However, I see no error in the log. Search_cron takes very long - several minutes even when indexing only 20 pages per cron run.

There is a page Troubleshooting cron which contains an SQL query (under "Check for problems with modules") to find nodes that haven't been indexed so one can inspect them for bad content. Unfortunately, this works only with Drupal 7, and I couldn't find a similar page for Drupal 8.

How can I find non-indexed nodes on Drupal 8?

Any other idea on how to track down the problem?

Update: I now found a way to log the nodes being indexed by adding a call to the logger to NodeSearch.php. Which admittedly is a hack.

I can now see that Drupal tries to index the same nodes again and again, without success and without error messages. However, I haven't found out the reason yet.

The status of node indexing is based on the search_dataset. This table stores content keyword blobs and their associated sid, the primary key for the content's keyword (i.e. the nid). When compared/joined against the node table, it should let you see which nodes aren't index.

From what it sounds like, you've already spotted problem node(s) so it's just a matter of confirmation. Removing the node(s) from being indexed (e.g. hacking
NodeSearch::indexNode()) to confirm it's the problem, then finding out what content in the node is blocking indexer.


Need help creating a Commerce Order from Commerce Customer shipping profile I am looking for a way for our admin users on a Drupal Commerce site to look up customer profiles from previous orders, and upon looking at a specific customer profile, provide a button that allows then to create an order for that customer. This use case is for a call center.

So far, I have tried using Button Field to call a rule component but I have having problems writing the rule.

Looking up previous orders and creating a new order with information for the shipping profile attached would also be a viable alternative.

Any suggestions regarding approach or use of modules would be welcome.

Thanks!

Things like this, is much easier to accomplish with a bit of custom code. You could add a form on the order view page, with the order as the context. This can be done by using hook_commerce_order_view.

All you really need to do, in the submit handler would be something like this.

$old_order //
$new_order = commerce_order_new();
$new_order->uid = $old_order->uid;
$new_order->commerce_shipping_profile = $old_order->commerce_shipping_profile;
commerce_order_save($new_order);
$form_state['redirect'] = 'admin/commerce/order/' . $new_order->order_id . '/edit';

The code above is from memory, should be in a form submit handler and is written from memory, but should work, if I remembered correctly. As you can see, it's pretty simple to accomplish.


How to reuse query conditions? I have a semi-new Drupal 7 site in which admins approve the accounts of managers, and managers approve accounts of their employees. That's all working great. I've been asked to make it so that managers can delete the employee accounts that are no longer needed.

Using our old CMS, when all of our SQL was hand written I could build a "where" statement like :

$cWhere = "WHERE e.department = 'HR' and e.manager = 12345"

These items are not user entered, but based on the logged in person. To show a list of employees I could run :

"SELECT * FROM users " . $cWhere

Then to delete I could run :

"DELETE FROM users " . $cWhere . " AND uid = " . $deleteUser

This would ensure that the person who is logged in and trying to delete a user had the permission to do it, because the additional conditions of manager and department were checked. Furthermore, if the conditions for the employee list are changed, the delete code is automatically updated to take the new conditions in to account with no additional work needed. For the record, the query is considerably more complex than that, but no reason to make the question harder than it needs to be.

Now I'm doing everything with db_select. So I build the query to show the list of users. I need an additional query to check that the logged in user has permission to delete the target user. Then I would call the user_delete() function. Is there any way to do this, or do I have to rebuild the query completely a second time?

Non-working code, but something like this :

if (isset($deleteUser))
{
   $chkUser = $query; //$query is an existing db_select that hasn't been ran yet
   $chkUser->condition('u.uid', $deleteUser, '=');
   $rowsUser = $chkUser->execute();
   if ($rowsUser->rowCount() == 1)
   {
       user_delete($deleteUser); //user has permission
   }
}

$result = $query->extend('PagerDefault')->limit(20)->execute();

//... loop results, output list ...

Note, I have tried the above with the user_delete() commented out... but $chkUser is obviously a pointer to $query, as the list printed ends up being just the user in question. So everything works the way I need, except I've mangled my user listing query doing it this way.

You can use the function db_and() an db_or() to compile condition sets that you can the add to an existing query like this:

$query = db_select('Exhibitors', 'e');
$db_and = db_and();
$db_and->condition('ProductCategory', array(1,2,3), 'IN');
$db_and->condition('status', 'active');
$query->condition($db_and);

Example taken form here: https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_and/7

Other than that, there is the DatabaseCondition Class that might be interesting for you too.


Adding a line of code to all pages I have recently taken over the final stages of construction of 3 websites that were built in Drupal 7. I have never used drupal before and have run into a problem. My footer in one of the websites is not visible. This was due to the color style sheet not being pointed to in the page code. I copied the existing code into dreamweaver and resolved the issue, but cannot upload to the server as I cannot find the pages on the server, so i have no file i can replace.

The code looks like this:

@import url("themes/bartik/css/layoutb3ea.css?mry7g9");

@import url("themes/bartik/css/styleb3ea.css?mry7g9");

It needs to look tike this:

@import url("themes/bartik/css/layoutb3ea.css?mry7g9");

@import url("themes/bartik/css/styleb3ea.css?mry7g9");

@import url("sites/default/files/color/bartik-23dc1686/colors.css?m9ub8w");

You can see that the last line of code is missing.  I am used to working in dreamweaver and I am not familiar with the how the file system works in Drupal.

How do I add that line in to all the pages?

You should familiarize yourself with Drupal theming. Check out the Theming Guide.

Basically, you want to edit the CSS in the theme that's currently being used on your site.


export views data to text file in the background I am using views data export module to generate a text file and that works perfectly. but instead of asking me to save it to my local computer.

What I want to do is save it directly on the server, I would like to run this is the background if possible as large amounts of data take time to generate.
Ideally I would like to run this for each user in the background on cron run so I presume I will need to setup some batch job to run.

Well, I think you can set a cron job on server. You just need to add a drush command in crontab file. Drush command :

drush views-data-export [view-name] [display-id] [output-file]

Views data export provides this drush command.

Edit :

If you don't have drush installed on your server then you can take the idea from code of views_data_export.drush.inc.

Or :

In simple way you can run the code following in hook_cron :

$output = views_embed_view('ViewName', 'views_data_export_1');
file_unmanaged_save_data($Output , 'private://output.xls', FILE_EXISTS_REPLACE);

As per https://www.drupal.org/node/1875456#comment-7524421.


views exposed filter select list users with specific role I created a content type coty1.

I have 2 user roles that can create that content type. role1 and role2.

1.How can I create view that one of the filter field is expose that allow me to choose just users that have role1 or role2 (not all the users of the site).

2.How can I create view that one of the filter field is expose that I can choose just users that realy created one or more from coty1 content type?

Thanks a lot.

You need some custom code in order to do something like this.

You can put #access on any form element, and along with hook_form_alter you are able to alter the views exposed form and require a permission that the two roles have, making it so that only users with those roles can see and use the exposed filter.

The same technique can be used for the 2nd field you want alter.

In code this could look something like this:

module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['exposed_filter_1']['#access'] = user_permission('special permission role 1 and 2 have');
  }
}

This is example code. You need to find out the form id, and maybe do other checks. Also You need to do a SQL query to figure out if the user has created a node of that type.


How to move whole Drupal website on USB for localhost use using XAMPP? My cPanel subscription will come to an end soon and I want to move my site to a USB stick or CD and still be 'runnable' / executed. It is currently on a cPanel server...

I have seen these options but they all seem outdated and might not be ideal as my website is nearly 300MB in size.

Static Module
uniform server
CD deploy

I want to keep the site static and lose the editing features that come with the modules - essentially I want to freeze what I have done up to now and keep a record of it that will always work locally on a medium.

If you are married to the idea of running your website via a USB Drive, you can always just download a lamp stack to your computer and configure it to look at usb drive as it's default home directory.

There are several options for this.

Xampp: General one size fits all lamp stack
DEV Desktop: A Drupal specific lamp stack
Mamp
Wamp

This is great for doing dev work on a duplicate copy of a site for testing in order to not screw up the production. The only problem with this is if you are trying to plug the usb to multiple computers you will have download the software each time and configure it look at the usb for it's root directory.

On the plus side using a local lamp stack you won't lose you ability to edit the site. It'll operate exactly the same way. With the exception that ftp ability will vary. Also it's good practice for doing standard Drupal Migrations.

NOTE: I would suggest if you try these options you operate from a desktop and not a USB. The USB could be for just keeping backups.

If this is something you deem acceptable I can expand on this idea.


How to make use of the render placeholder system for cacheablejsonresponse? I have custom controllers which provide CacheableJsonResponse responses. Those responses are quite heavy to build (couple of seconds), so I want to build them better. I build those responses by getting the entity object(s), normalizing its content—referenced entities included—and putting the data directly into the response object.

My JSON responses varies by user, checks the role access, and includes some user related content (e.g. flags). I have tried to put a cache context on user (and url) on the CacheableJsonResponse, but this is not a viable way to handle cache, from my perspective; it would create a cache entry for each user and url request and would be ineffective (the cache will HIT only when the same request is asked twice or more by the same user).

Standard Drupal renderer seems to include a placeholder system which makes the majority of the page cached with proper cache context+tags, and the little parts with high-cardinality/invalidation rate rendered last out of the cache system (from my understanding) and then would be useful for my needs.

How can I easily reproduce the same system for my controllers? Is there any standard mechanism/pattern out there?

Reference: https://www.drupal.org/docs/8/api/render-api/auto-placeholdering

The only trade-off I have found is to implement custom tags (per user) and put the response data array in cache so I have control over the conditions of cacheability at the controller level. I build the cacheability metadata (context + tags) with the help of a service which registers the metadata of the content which is currently normalized. And when the normalization ends, I merge the metadata onto the response and put the response in a cache backend.

And when the controller is called again, I try to retrieve the cached response and returns it if not invalidated.

Internal and dynamic page cache still works for the other controllers (i.e. standard rendered pages) without removing the high invalidation tags from the services.yml file.

Feel free to add better answers than this one.

Tested on Drupal 8.6.7.

Side note

Because I was using flag, I have had to implement cache tags pairs: userid+flaggingid. This way, we will not invalidate the caches of all users whenever a single user flags or unflags a content. This does not answer this question, but I thought it could be useful to include in your reflections for your own cache system.


Availability Calendars - change amount of months shown to visitor I need to make some changes to a website that is using the 'Availability Calendars' module(available on https://drupal.org/project/availability_calendars ).

On the website a calender is shown to the visiting person that highlights any available date for 2014. I now need to have the months for 2015 to show up in the calender too.

But I can't find the option to make 2015 visible for the visitors. Using google I found this: http://drupalcode.org/project/availability_calendars.git/blob/273d12c0ad811341615197a8601797f3003f52e9:/README.txt

It says "Choose the global settings for the availability calendars under Administer -> Site configuration -> Availability calendars. You can choose how many months will be shown for each node and whether or not to display the calendars on the node page itself".

But when I go to "nl/admin/config/content/availability-calendar" I only can set the 'labels' and add a css-class to those labels. There is a link to "nl/admin/config/content/availability-calendar/styling" but that only has options to set the font-weight,color, font-size, etc...

I then went to look in the content types ( under 'Structure --> content types') but the option isn't showing up there either.

So the problem is I need to change the amount of months shown to the user (who is not logged it) on the front-end of the site for 2014 and 2015. But I can't find any option to change the amount of months shown. Can anyone point me in the correct direction? Or do I need a different module to do this? If so what module would I need for this?

It turns out I just needed to enable the 'Field UI' module. So basicly I did this to solve my problem:

Enable to 'Field UI'  module
Go through to "Structure --> content types"
Go to the 'Manage display' tab


How can I add 'text/jsx' type to a script tag via libraries.yml? I want to add some react js files to a theme's libraries.yml and I don't know how I can do this in drupal 8.

<script type="text/babel" src="scripts/example.js"></script>
or
<script type="text/jsx" src="scripts/example.js"></script>

I can't figure it out hot to make the type="text/jsx" appear when the file is added to the page.

Any ideas on how I can achieve this in Drupal 8?

I took a wild guess because I couldn't find absolutely nothing. Apparently this works:

my-libary:
  version: 1.x
  js:
    js/node.js: { attributes: {type: text/babel} }


How to print the value of an array instead of the key? I have the code below in a form builder for Drupal 7:

$form['color'] = array(
  '#type' => 'select',
  '#required' => TRUE,
  '#title' => t('Color:'),
  '#options' => array(
    0 => t('Blue'),
    1 => t('Yellow'),
  )
);

I need to print the selected value in hook_mail but I only get the key when I write:

function color_mail($key, &$message, $params) {
  global $user;
  $message['subject'] = 'Selected color is: ' . $params['color']
}

While what would make sense here would be to print the value, not the key. I tried $params['color']['#options']; too but it didn't work.

Any tip on how to make this work? I'm sure it's something simple I don't yet know about.

The form submission process will only actually keep hold of the array key (which is the value for the select element), so it won't be available to you in $params.

The usual method to handle this sort of thing is to provide a function to return the options:

function MYMODULE_colour_options() {
  return array(
    0 => t('Blue'),
    1 => t('Yellow'),
  );
}

Then in your form function you would use:

$form['color'] = array(
  '#type' => 'select',
  '#required' => TRUE,
  '#title' => t('Color:'),
  '#options' => MYMODULE_colour_options()
);

And in the message hook:

$colour_options = MYMODULE_colour_options();

$colour_string = 'Unknown';
if (isset($colour_options[$params['color']])) {
  $colour_string = $colour_options[$params['color']];
}

$message['subject'] = 'Selected color is: ' . $colour_string;


How to add twig code in View 'global custom text' field? I want to add if condition in my "global custom text" field saying if node is published, print some link. I tried below steps , but it is not working:
1.I have added "Content: Publishing status" field and hidden it from display
2.In 'global custom text' field added below code:
Replacement pattern for published status is {{ status }} and is returning 0 or 1.
Code I added is:

  {% if  status  ==0 %}

 APPLY

    {% endif %}

Drupal Version:8.2.0

Can anybody help me to make this working?
Thank you In Advance

I try that right now and worked for me.

Note: just make sure set Output format to 0/1

{% if  status  %}

 APPLY

{% endif %}


Is it possible to add custom stylesheets while using a core theme? I'm trying to add a custom stylesheet although I'm using the Garland theme but so far I wasn't able to do it.

I've tried the following:

function mymodule_init(){
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_js ( $path . '/extra/script.js' ); // script is loaded and works
    drupal_add_css( $path . '/extra/style.css' ); // css isn't.
}

I also have a form that I will display when accessing /myform, so I tried to add the CSS there:

function mymodule_formname($form_state){
    drupal_add_css( drupal_get_path('module', 'mymodule') . '/extra/style.css' );
    // $form definition here
    return $form;
}

No success. Finally also tried to include the CSS using the #attached form parameter but still no results. I flush the cache for each of the attempts just to be sure...

Am I missing something? Shouldn't this be possible?

You can use context and context add assets to get the job done. If you are not familiar with context it's a way to set reaction blocks, theme HTML, theme pages, menus, etc based on conditions on menu items, paths, node types, taxonomy terms, etc. You can include a custom css file on your form with context add assets.


Hook_menu() and its page callback: how to redirect users on a condition? I'm trying to redirect users from an existing path in Drupal 7 to another existing path. I want to implement the following rule:

comment/reply/123 should redirect to node/123#comment-form

But

comment/reply/123/456 should NOT redirect anywhere and just go where it goes.

I've tried to implement this behavior with hook_menu(), but here's the problem. When I register an item with the path 'comment/reply/%' that corresponds to comment/reply/123, it automatically includes paths like comment/reply/123/456. I know that's intended and changed my code to include this case, but can't figure out how to redirect users only when they hit comment/reply/123. Here's my code:

function mymodule_menu()
{
    $items = array();
    $items['comment/reply/%/%'] = array(
        'title' => 'bla',
        'page callback' => '_mymodule_redirect',
        'page arguments' => array(2, 3),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function _mymodule_redirect($node_id, $comment_id)
{
    if(isset($comment_id))
    {
        return; //I want to just go to comment/reply/123/456 here, but it gives me a blank page
    }
    else
    {
        drupal_goto('node/' . $node_id . '#comment-form');
    }
}

So how do I go where I want to go?

Update: This is my final solution: I now use hook_menu_alter() to rewrite an already defined link and comment_reply() to serve standard comment form.

function mymodule_menu_alter(&$items)
{
  $items['comment/reply/%node']['page callback'] = '_mymodule_redirect';
}

function _mymodule_redirect($node, $pid = NULL)
{
    if(isset($pid))
    {
         return comment_reply($node, $pid);
    }
    else
    {
        drupal_goto(drupal_get_path_alias('node/' . $node->nid), array('fragment' => 'comment-form'), 301);
    }
}

If you are altering a hook_menu item that an existing module defines, use hook_menu_alter. You will receive all menu items by reference, and you can alter the necessary menu items as necessary.

In a hook_menu() implementation, if you define example path, http://example.com/example, http://example.com/example/foo, http://example.com/example/foo/bar... and so on will have the same page callback and other properties. However, if you define http://example.com/example/foo/mine, that page will use the explicit definition of example/foo/mine. There is a negotiation with MENU_DEFAULT_LOCAL_TASK too.

PS: If you are trying to redirect comment pages to their node paths, try this module.


Upload images in custom modules I work on D7, and create form from custom modules. Create a field upload images by
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['image'] = array(

'#type' => 'file',

'#title' => t('Upload picture'),

'#description' => t('Select a picture of at least @dimensionspx and maximum @filesize.', array(

  '@dimensions' => '1000x1000',

  '@filesize' => format_size(file_upload_max_size()),

)),

);

Show form correct.

and submit form by hook_form_submit();
print $form_state, upload images not find.
How to get values of upload image.

Write Also

$file = file_save_upload('image', array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array('500x500', '100x100'),
  ), 'public://uploaded_images/', FILE_EXISTS_RENAME);

Not find of upload image.

Drupal makes a distinction between regular files and managed files. The first are only stored on the filesystem, the second are stored in the database (managed) as well.

If you use a manged file (type = 'managed_file') the $form_state will contain a file id (fid) of the newly stored image.

Also note that file_save_upload takes the file path as the first parameter, so 'image' means nothing there. And that you still have to store your image as a permanent file after file_save_upload():

$file = file_load($logo);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'your_module', 'using_entity_type', $entity_id);


How to dynamically populate select options? I'm trying to build an admin form for a module, using system_settings_form().

I want the users to be able to select sub-options, from a list that is dynamically generated depending on the main option.

For example

$main_options = array('foo','bar');
$sub_options['foo'] = array('foolish','football','foodstuff');
$sub_options['bar'] = array('barley','baroque','barbarian');

$form = array();

$form['main_option'] = array(
    '#type' => 'select',
    '#options' => $main_options,
);

$form['sub_option'] = array(
    '#type'  => 'select',
    '#options' => $sub_options[SOMEHOW USE THE SELECTED VALUE OF main_option AS INDEX],
);

return system_settings_form($form);

So I would expect sub_option to be unpopulated the first time the form is called, and then populated as soon as the user populates main_option.

Is this possible?

Update

Thanks for the advice re Ajax. I looked up https://www.drupal.org/node/752056 and this is what I've built: here the values in olt_test need to change based on the value selected for olt_provider.

  $form['olt_provider'] = array(
    '#type' => 'select',
    '#title' => t('Provider'),
    '#options' => variable_get('providers'),
    '#ajax' => array(
      'callback' => 'olt_provider_select_callback',
      'wrapper' => 'tests-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $form['olt_test'] = array(
    '#type' => 'select',
    '#title' => t('Test'),
    '#prefix' => '
',
    '#options' => array(''),
  );

and in olt_provider_select_callback() I have

  function olt_provider_select_callback($form, $form_state) {

  $new_options_value = [new value calculation snipped]

  $form['olt_test'] = array(
    '#type' => 'select',
    '#title' => t('Test'),
    '#prefix' => '
',
    '#options' => $new_options_value,
  );

  return $form['olt_test'];
}

The problem I'm now seeing is that the Ajax only fires on the first time the olt_provider select box is clicked - subsequent clicks don't fire. Any thoughts?

The problem I'm now seeing is that although the olt_test dropdown is correctly updated via Ajax, this replacement value is not saved on form submission. Any thoughts?

Final Update - My form is working correctly now. The data was being saved on form submission, but I needed to add some more code to retrieve the saved data and display the default values when the form was loaded.

As said before you could make use of Form APIs #states to display one element only after a certain input to another form element has been made. In your case you'd maybe go with two additional select lists, both initially hidden. Check form_examples_states_form() for more information.

$form['main'] = array(
  '#type' => 'select',
  // ...
);
$form['sub_a'] = array(
  '#type' => 'select',
  // ...
  '#states' => array(
    'visible' => array(
      ':input[name="main"]' => array('value' => 'foo'),
    ),
  ),
);
$form['sub_b'] = array(
  '#type' => 'select',
  // ...
  '#states' => array(
    'visible' => array(
      ':input[name="main"]' => array('value' => 'bar'),
    ),
  ),
);


Why are non-required fields still showing up in my node_edit template using Page Manager I am stumped. Certain fields are NOT required and yet they still show up if I add the base form to a node_edit variant in Page Manager (Node add/edit form).

And I finally found out why:

If the user who's accessing this node_edit form variant has the right to update this field even if it's not required and you didn't add it to the form, it will show up as part of the base form in Node add/edit form (Home » Administration » Structure » Pages)

Hope that helps someone else too.


How to use tags for filtering images to be displayed using views? I'm pretty new to Drupal (version 7). I'm trying to create multiple image galleries. I've created a content type called "Images" and use a view to display it like a gallery.

However, I wonder if there is some way to "tag" the images so that they go to different views. Ex.: I have an image tagged so that it will only appear in the "events view" and not the "projects view".

I can almost guarantee that this question has been asked before, but still ...

If you did a standard Drupal 7 install, then you should already have a Tags taxonomy. Add that taxonomy to your content type.

In the view, you could do a couple of things.

Create more than one variation of the view. In each variation, filter the view to only contain the tag that you want.

OR

Use a Contextual Filter to grab the specific term from the URL. That way, you will have as many different views as taxonomy terms. This is more complicated, but it will help you learn a lot, and it is almost always the better way to do this sort of thing.


How to translate plural strings with Drush? If we want to translate a plural string in Drupal we can use the format_plural() function.

If you are programming drush commands you can use the dt() function to translate strings, but if you want to translate plural strings in drush wich is the function to accomplish this?

Between the Drush functions that process text, there isn't such a function, but you can implement one using the code from format_plural(), replacing any call to t() with calls to dt().

function drush_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
  $args['@count'] = $count;
  if ($count == 1) {
    return dt($singular, $args, $options);
  }

  // Get the plural index through the gettext formula.
  $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
  // If the index cannot be computed, use the plural as a fallback (which
  // allows for most flexiblity with the replaceable @count value).
  if ($index < 0) {
    return dt($plural, $args, $options);
  }
  else {
    switch ($index) {
      case "0":
        return dt($singular, $args, $options);
      case "1":
        return dt($plural, $args, $options);
      default:
        unset($args['@count']);
        $args['@count[' . $index . ']'] = $count;
        return dt(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
    }
  }
}


Using ColorBox to popup "iFrame" shows original page content after the "iFrame" data? I have a basic module that parses a JSON feed, stores it in cache, then shows a "gallery" of the objects - I know I should have maybe stored these as Nodes but it was supposed to be a quick simple module...

Anyway, it works well except, when I click on one of the objects in the gallery, I have it linked to an "iFrame" (which I cached too, but it's not really a real page) found at:
the_page?iFrame-id="theDataID" - these all popup in ColorBox and the HTML from the cache for the "iFrame" is displayed.

This worked well on the dev site, however for the production site - it uses different modules and templates (which I didn't have access to for setting up the dev site).

Now when you click on an object, the ColorBox popup shows the data, except it then shows the original pages' content and I haven't been able to figure out why it does that. I assume the prod site must try to always load the "original content" based on the URL and therefore "ignores" the ?iFrame-id part?

So basically, in my code for the iFrame, I do:

echo $data;
return;

Which causes the data to be printed above the normal pages' content in the popup. So I changed it to:

return $data;

But that caused the data to show up as the pages' content, and I still had the header/footer for Drupal.

Anyone have any ideas?

Another way I could do this is by using ColorBox's inline option instead of the iframe option, however I assume that would require all the data for the objects to be on the page? As right now, the content is loaded dynamically on popup (it doesn't exist anywhere in the DOM before hand).

OK, so originally I had tried echo $data; then return;

I then tried: return $data; but that kept showing the header/footer.

I've found that this works well:

echo $data;
die;

Though it's probably not the best way to do it, but it works for the way the module was wrote... should really use the Node/Entity API next time :)


How do I collect daily login statistics I am trying to add a contest to my website which will be based on how frequently they login into my website. Each user will be assigned one point per day irrespective of how many times the login in a day. A winner will be picked every month, at random, based on the number of times they have logged in. Hence the more times you login, the more odds you have of winning.

Any ideas on what would be the best approach? Would I have to build a module from scratch? Modify a current module? Any help would be appreciated.

Thanks,
G

I would say use the User Points module along with the User Points Login add-on module to handle to recording of points for users logging in.

Then you can use the Views module to build reports for yourself to see which users have the most points for a given period.

It would also be possible to use the Rules module to automatically email you a report of the winners at the end of every month and then reset all user points to zero (I'm making an assumption that there is a rules action you could use to remove existing user points).


Sync local dev site to live best practice What is best practice for syncing a local dev site with a live production site when your live database is  constantly changing?

From what I have read there are two possibilities:

Replicate changes made in dev manually on your production site. This seems like something you would only want to do with fairly limited changes that I can make while the site is down for maintenance and users are unable to make any changes to the production database. I can imagine that it can make it tough to make more complex updates/changes. I have done this in the past with simple changes/updates to modules and so on.
Migrate the test site into production, with the site in maintenance, and synchronize the databases. This option seems more like the way to go for bigger jobs, as long as I can synchronize the databases somehow.

That seems to assume that your production site is basically static and the database will not change much at all when you are making changes on your test site.

However, I am working on a batch of improvements for site that has daily activity (new content, users, transactions, comments etc.). These changes are taking time to set up and test.

I found this comment on Drupal.org https://drupal.org/comment/4511654#comment-4511654

It addresses my situation, but is there any better way to go about this or a more detailed guide/how-to? Or should I be breaking things up into smaller and more manageable chunks -- that way seems time consuming.

Here are some good ideas to use:

1.) Backup and Migrate module.  Before doing any local changes migrate the production database down to your local environment

2.) Features.  Make all your content type into specific features.  Include content types, views, context, and any other thing that can be put into features.  This will allow you to make content type changes and almost ANYTHING on the site and simply roll it as a feature.  When its uploaded to the production environment you simply revert the features, and bam they are there.

3.) Stongarm and Diff are additional modules to use with features.  They allow to see whats different from the site and the feature, and strongarm allows variable exports into features.

3.) GIT or SVN.  Use git or svn to roll to production and keep your code base on track.  With major features differences use a branch to complete work and merge it into the trunk.  This will allow you to development bigger features, but also give you the ability to make bug fixes that can be sent up in a roll.

4.) RSYNC.  Most of the time sites/default/files or CMS uploaded files are not in your repository.  Use rsync to sync the production files to your local.  Or simply use FTP

5.) Use drush up to update your modules it will keep your subversion or git in tact.  It will also attempt to update your database.


After programmatically creating a token, it does not get overridden I have the function below in a module. After it runs once, the token never changes again. I have to disable the module, and re-enable it, to get the token to run. Do you have any idea why this happens?

function my_token_values($type, $object = NULL, $options = array()) {
    global $user;

   $rand = rand();
   if ($type == 'global') {
        $tokens['random-number-replace'] = $rand;
   }
   return $tokens;
}

Where are you using the token? Drupal may be caching information at a higher level (like the filtered output of a node, for example) and only calling the token generation code once.


Uploading pdf newsletters How would I upload a pdf and link it to a post on my homepage? Basically the PDF is a newsletter and every week I want to upload a pdf (newsletter) and have a link as a story on the home page. I'm using Drupal 7, is this possible? does a module exist for it?

You don't need a new module as this functionality is built into core.  Go to (yoursite)/admin/structure/types and click "manage fields" for the content type you want to add your pdf's to.  Add a new field whose field type is "File".

Working with files in Drupal 7


extraneous css file request generated Something within my site is generating a request to a css file called "none". It is using the path of our theme. Our theme does not have any such style sheet called as part of our stylesheets array.

Our definition:

stylesheets[all][] = css/mods.css

stylesheets[all][] = css/main.css

request on page load:

/sites/all/themes/our_bootstrap/css/none

Since there is no such file, a 404 is served for that file. Where can I look to track down what is generating the request?

You may have something like url('none'); specified for a background (or list image, etc.) in your stylesheets.


How can i use MATCH and AGAINST with db_select? I have a query like:

$query = db_query("
    SELECT *, MATCH(field1,field2) AGAINST ('$s' IN BOOLEAN MODE) AS Relevance
    FROM {my_table}
    ORDER BY Relevance DESC, created DESC
    ");

That is working well with db_query.
How can i use same query with db_select function for drupal 7?

Adding an expression should work:

 $query = db_select('foo');
 ...
 $expression = 'MATCH(field1,field2) AGAINST (:search IN BOOLEAN MODE)';
 $query->addExpression($expression, 'Relevance', [':search' => '$s']);
 ...

See SelectQuery::addExpression for more info.


How to properly program AJAX links? I have a custom module that uses AJAX. Everything works fine the way it is. I'm just wondering if it's the proper way to do it in Drupal. I'm new to Drupal 8 and 9 programming
This is a line from my code
$link ='Test AJAX';

Is this ok to do or should I be building my link? If so, why and how?
EDIT
I currently build non-ajax links like
  $url = Url::fromRoute('entity.node.canonical', array('node' => $record->nid));
  $title_link = Link::fromTextAndUrl($record->title, $url);
  $title_link =$title_link->toRenderable();
  $title_link=render($title_link);

If you just need to add the classes I believe it can be done like so
$url = Url::fromRoute(
  'entity.node.canonical',
  ['node' => $record->nid],
  ['#attributes' => ['class' => ['btn', 'btn-default', 'use-ajax']]]
);

 $title_link = Link::fromTextAndUrl($record->title, $url);

At that point $title_link should be able to be rendered in the template as is!
// php
$variables['title_link'] = $title_link;

// twig
{{ title_link }}


Entity translation: views with and without language fallback I need views with entity language fallback and others without.

if "Enable language fallback" is activated, is there a way to disable this for a specific view

Thanks
Rainer

There doesn't seem to be a solution with "Enable language fallback" activated. I guess it has to be made the other way around. Disabling it and add a fallback on views level using the "No results behavior".


Block View for specific form I have two forms on my site. I want to create a Block View for only one of them but as I choose "Webform: Webform form body (Form)" for the Fields in the View, I get both forms showing. I'm trying to only show one of the forms.

I tried adding a css class to a field and then using that as a means of filtering out the fields of just the one form but either I did it wrong or that isn't the way to complete the task.

How can I limit a Block View to show a specific Webform?

In your view, add a filter criteria of 'Content: Nid', then specify the node id of the webform in question. To locate the node id you can edit the webform and look at the url. The url will be /node/xxx/edit where xxx is the nid.


Drupal views custom filter, check if row exist I need help with a query. I am having a really hard time going in the right direction.

I have a custom multi-value field, containing one 'name' and one 'id'.
I want to filter on contents that:

None of the delta has a name 'test' ('test' is a name example).
OR, the name is 'test' and the id is equal to 0.

I was planning on having the logic in the customer filter, like so:

class my_module_handler_filter_field_name extends views_handler_filter_boolean_operator {
  function query() {
      // My custom code here
  }
}

But I don't have much success for now. I managed to filter rows where 'name' = 'test' using:

$this->query->add_where($this->options['group'], 'field_name', 'test', 'LIKE');

But if I do the opposite with 'NOT LIKE', it just shows me every row not equal to 'test' (also including rows from an item that has one name = 'test'). This behaviour is normal, I know it is simply not the right way.

A table example:

    entity_id    delta    store_name  id_in_store
    ---------------------------------------------
    1            0        Amazon      0
    1            1        BestBuy     123442111
    2            0        Apple       123442123
    2            1        Microsoft   124423459
    2            2        Google      112559002

Entity_id is a node ID for a 'product' content type. I want to be able to know which products are sold at Amazon. And there are 2 ways to know it:

The field have a delta where store_name is 'Amazon', but id = 0.
Or the the field doesn't have any delta where store name is 'Amazon'.

I guess you are looking for something like this, but you might need to tweak it a bit. You can group db_or and db_and, then combine them like this. Basically create two 'and' groups where all conditions need to match. Then combine those in an 'or' group, where one of the conditions needs to match.

function query() {
  $and1 = db_and();
    $and1->condition('field_name', 'test', 'LIKE');
    $and1->condition('field_id', 0);

  $and2 = db_and();
    $and2->condition('field_name', 'test', '<>');

  $combine = db_or();
    $combine->condition($and1);
    $combine->condition($and2);

  $this->query->add_where(
    $this->options['group'],
    $combine
  );
}


How do I install Commerce Kickstart as a Aegir installation profile I have been trying to get the most recent version of Commerce Kickstart to install as a profile in Aegir, but I have had no luck. I found the following note on the Aegir project site, and this note in the Commerce Kickstart issue queue. Has anyone gotten this to work?

If you download the .tar.gz from http://ftp.drupal.org/files/projects/commerce_kickstart-7.x-2.0-rc4-core.tar.gz into your platforms directory on aegir, untar it, and then create a platform with the same name you can build sites using the commerce kickstart profile with aegir.  Here are the commands I used:

cd /var/aegir/platforms
curl -O http://ftp.drupal.org/files/projects/commerce_kickstart-7.x-2.0-rc4-core.tar.gz
tar xzf commerce_kickstart_7.x-2.0-rc4-core.tar.gz
mv commerce_kickstart_7.x-2.0-rc4 commerce-kickstart
chown -Rf aegir\: commerce-kickstart

Then go into Aegir and create a platform.  Set the platform directory to this commerce-kickstart directory and don't include a build file.  It'll verify the platform and then you'll be able to create sites on there using the Commerce Kickstart installation profile.

Cheers,
Diwant