Is there a module for adding field types for latitude, longitude, compas coordinates, etc?

The Geofield module allows you to store such data:

  Latitude and Longitude Supports entering data as both Decimal Degrees
  (122.340932) and Degrees-Minutes-Seconds (-123° 49' 55.2" W). The
  Degrees-Minutes-Seconds input is very tolerant of inconsistent input.

  Bouding Box Four textfields where lat / lon can be entered

  Well Known Text (WKT) A textarea for direct WKT input

  Draw on an OpenLayers Map Allows drawing of Points, Lines, Polygons
  and Bouding Boxes

  HTML5 Geolocation Transparently asks the browser for the user's
  current location. Works great on Chrome and smartphones with GPS.

You can encode data from another field using the Geocoder module as well.


How do I keep fields from being in the same row?

Find the class of the element/field above (using your browser's developing tool) and try this CSS:

.field_my_field:after {
  visibility: hidden;
  display: block;
  content: "";
  clear: both;
  height: 0;
}

Change the "field_my_field" with your class name. Clear Drupal cache.
It should push the next element below.


From where does variable_get() get the first parameter?

I think you're referring to the $conf variable?

It's set in sites/default/settings.php (or sites/SITENAME/settings.php if you have a multi-site installation), and that file is included in Drupal's page build.


Force redirect from HTTPS to HTTP in Drupal 7 Multitsite?

Maybe you should try and and change the object embed code code to use a protocal-relative URL such as //YOURSITENAME.COM/some/path/to/video/file.mp4 you can do this easily with a WYSIWYG editor or like hook_node_view and regexing for your domain url and an object tag and removing the http:// or https:// as needed ...

Simply google for protocol-relative url and you'll find a bunch of information.


Contextual value when the filter is not available and PHP code

I found the cause of the problem from this resource and I have to define the $node variable by:

$node = node_load(arg(1));

Then I use the $node as shown in the question above.


Submit form to 3rd party site, receive response to update original form

There are a variety of ways you can do this using the 3rd party API and the hooks provided by Webform such as

http://www.drupalcontrib.org/api/drupal/contributions%21webform%21webform.api.php/function/hook_webform_submission_presave/7


How to save the previously selected option in the selection box, the default value strays

Solved the problem yourself with the help of code. It was necessary to create a handler instead comment_form_submit and create in him the values of a variable_set of my field value, so, I create custom field.

    function comment_author_form_comment_form_alter(&$form, &$form_state, $form_id){
           if($form_id == 'comment_node_zayavka_form'){
             $query = db_select('node', 'n')
                ->fields('n', array('type', 'uid', 'title', 'nid'))
                ->condition('n.type', 'brigada_type', '=');
             $result = $query->execute();
             $brigade_list = array();
                foreach($result as $value){
                    //if($value->uid == $user->uid){
                     $brigade_list[] = $value->title;
                    //}
                }
                $form['field_select_brigade_1'] = array(
                    '#type' => 'select',
                    '#title' => t('Select brigade'),
                    '#options' => $brigade_list,
                    '#description' => t('Please select the team that was sent to you with reference to this application.'),
                    '#required' => TRUE,
                    '#default_value' => variable_get('comment_field_brigade_selection'),
                );
        $form['#submit'] = array('comment_author_comment_form_submit');
        }
function comment_author_comment_form_submit($form, &$form_state){
        if(isset($form_state['values']['field_select_brigade_1'])){
              variable_set('comment_field_brigade_selection', $form_state['values']['field_select_brigade_1']);
            }
        }


How to customize the display of a block?

You can customize the display of a block by using Block Class module.

  Block Class allows users to add classes to any block through the
  block's configuration interface. By adding a very short snippet of PHP
  to a theme's block.tpl.php file, classes can be added to the parent
   element of a block. Hooray for more powerful
  block theming!

In this case, first look at the CSS selector and then add a single line to theme's CSS file such as:

.label { display: inline }

It's about CSS.


How can I split up a massive feature module into multiple smaller modules?

I came across this solution which suggests using CTools Bulk Exporter to get the features back into the database so they can be re-exported as smaller features.

  Think I've found an alternative solution to get your exported objects
  back into the database so you can safely disable/remove your features.

  1) Export everything you want in the database using CTools Bulk
  Exporter (admin/structure/bulk-export). Put the module it generates
  into your modules folder (eg. my_exports_module) 2) Disable the
  features containing the objects you just exported 3) Enable the module
  CTools Bulk Exporter created for you 4) Download Drush CTools Export
  Bonus & enable it 5) Run the following drush command: drush cbsa
  my_exports_module 6) Disable my_exports_module

  Tested this with view modes/fields/... created in Display Suite -
  everything went better than expected :)


This the official documentation for the API change you've mentioned:

Modal/dialog/ajax is using query parameters instead of accept headers

The most important detail is to attach this library:

$build['#attached']['library'][] = 'core/drupal.dialog.ajax';

You ask about why this works on admin pages without this. The reason is, admin pages already have dependencies on most Drupal jQuery libraries, while non admin pages are loaded without any jQuery out of the box (which is a great performance improvement in D8).

Bootstrap Theme

If enabled in the theme settings of the Bootstrap theme, "jQuery Modal" is replaced by
"Bootstrap Modal", see this code snippet:

LibraryInfo::alter()

elseif ($extension === 'core') {
  // Replace core dialog/jQuery UI implementations with Bootstrap Modals.
  if ($this->theme->getSetting('modal_enabled')) {
    $libraries['drupal.dialog']['override'] = 'bootstrap/drupal.dialog';
    $libraries['drupal.dialog.ajax']['override'] = 'bootstrap/drupal.dialog.ajax';
  }

For this to work you attach the same core library as above, so that the Bootstrap theme can find these core libraries to override them.


As for fixing this - see Shawn Conn's answer.

Some more background:

The "Roboto" font is already embedded in your site.  If you look at he markup in your header, it has the following line:

<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:700italic,400|Roboto:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

This should be:

<link href='//fonts.googleapis.com/css?family=Roboto+Condensed:700italic,400|Roboto:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

to make it work with both HTTP and HTTPS (as already pointed out by Shawn Conn).

Provided this is made to work, it means that if a user don't have Roboto installed, it will be downloaded from the googleapis CDN and cached upon first visit.

The line that inserts that link to the googleapis is probably in html.tpl.php in your site's theme (but I can't be sure - Drupal allows a site developer to insert such links in the header by other means).

Also, your style sheets uses the following every time a font is mentioned:

font-family: "Roboto",sans-serif;

This means: Use "Roboto" when available, otherwise fall back on the browser's default for "sans-serif".  This should work OK in all browsers, including Firefox and Chrome - even if the HTTPS/HTTP mixup mentioned by Shawn Conn stops Roboto from being downloaded.

  Now my website design gets completely screwed up in Chrome and Firefox
  browsers.

I looked at your website in MSIE, Firefox, and Chrome.  I don't see any obvious problems with it.


Cannot Disable User Programmatically With user_cancel()

Per the docs in user_cancel():

  Since the user cancellation process needs to be run in a batch, either
  Form API will invoke it, or batch_process() needs to be invoked after
  calling this function and should define the path to redirect to.

You need to invoke the batch API in order to trigger the result.

// Set the notify and cancel type options.
user_cancel(array(
  'user_cancel_notify' => TRUE,
  'user_cancel_method' => 'user_cancel_delete',
), 5, 'user_cancel_delete');

// Invoke the Batch API, disable drupal_goto(), and execute.
$batch = &batch_get();
$batch['progressive'] = FALSE;
batch_process();


I assume you are trying to import this via phpMyAdmin and that the file is an standard DB dump.

I would recommend either doing this via drush or the mysql command line.  E.g.:

drush @mysite sql-cli < \backup\my-dump.sql

Note:  drush @mysite status should show db schema and user name.

or

mysql -u user -p d8-database-schema-name < \backup\my-dump.sql

Another alternative would be to use the MySQL Workbench Tool.  Excellent GUI tool that runs on any OS and can even access databases via SSH.  Set up a connection to your DB, then load the dump as a script.  Make sure your target database schema is selected as default.


db_query unknown column on where clause?

If you're new to Drupal or PHP coding, you've created a nice example of how not to write an sql query. What you've written is open to SQL-Injection.

Please review the Database API Examples Documentation page.

A "correct" way to write this query using the API could look like (adapting 1 of the top examples to your code) the following.

$result = db_query("SELECT id from {galleries_types} WHERE name = :name", array(':name' => $form_state['values']['id']));

You will want to make use of placeholders in PDO to write your queries.


Why do many Drupal themes markup images with typeof="foaf:Image" attribute?

Yes, it’s about semantics of your content. That way, your page/content is part of the Semantic Web.

Background

The typeof attribute is defined by RDFa.
RDFa is a syntax to embed RDF in markup languages like HTML.

The value foaf:Image (most likely) refers to the Friend of a Friend vocabulary/ontology. The namespace foaf: typically stands for the URI of that vocabulary (http://xmlns.com/foaf/0.1/), so the value is actually the URI http://xmlns.com/foaf/0.1/Image.

http://xmlns.com/foaf/0.1/Image is a class. It’s (= what it means) documented here: http://xmlns.com/foaf/spec/#term_Image.


"Create a new account for an anonymous order" Rule issue with required field

Two options:

Make the field not required at the field level but then use a Form alter hook to make it required when presenting the form.
Make the logo point to the default image by setting the data value to public://your-file-here.png inside of the rule.


This is what worked for me in the node template for any custom field:

{{ node.uid.entity.field_name.value }}

I'm using Drupal 8.3.7

EDIT:
This is what I'm doing for the profile picture.
I'm creating a rendering object so I can specify a theme and an image style:

            {% set imagestyle = {
              '#theme':      'image_style',
              '#style_name': 'user_avatar_80x80',
              '#uri':        node.uid.entity.user_picture.entity.uri.value,
              '#attributes': { class: 'authorImg' },
            } %}

{{ imagestyle }}


I think the only way you will find out is through testing this for yourself. I  speak from experience in using Entity Reference currently in a project with success. It comes down to your needs. For example I needed a way to reference commerce products - which are not node entities - so the references module is useless. Entity reference was perfect for this case and would work with any other entity type.

With the massive change in drupal 7.x moving from a common mindset of "everything can be a node" 7.x core has emphasized and shown us the benefits of "everything can be an entity". With the success of entities you can pretty much guarantee that entity reference has a strong future in d7.x

I am not sure if there is any advantage in using references since Entity Reference does all that references does, while being much more powerful.

From the project page;

  "Note :
  - As the past couple months showed, the current maintainers are not up to the task. This module accepts new maintainers.
  - References will most probably be deprecated in the near future in favor of Entity Reference, which should probably be considered first
  on fresh D7 projects."

I think this says it all.

For the extended future developers should look into Relation which is expected to replace entity reference.


How can I have multiple content types pick up the same template?

Normally you'd simply use node.html.twig and then have different node templates for other node types. But I can imagine that it can make sense to bundle certain node types differently instead of providing distinctive templates for all other node types.

So you can implement hook_theme_suggestions_alter or hook_theme_suggestions_HOOK_alter to provide an extra template suggestion. The following snippet lets nodes of a given type pick up a node--foobar.html.twig template if present.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_node_alter(array &$suggestions, array $variables) {

  $bundles = [
    'contenttype1',
    'contenttype2',
    'contenttype3',
    'contenttype4',
    'contenttype5',
  ];

  /** @var \Drupal\node\Entity\Node $node */
  $node = $variables['elements']['#node'];

  if (in_array($node->bundle(), $bundles)) {
    $suggestions[] = 'node__foobar';
    $suggestions[] = 'node__foobar__' . $variables['elements']['#view_mode'];
  }
}


Display main menu for logged in users only

If you are assigning main menu (as block) to region, you can control it's visibility by "Visibility settings". If you are rendering it in .tpl.php file then you can do it like this: Example (bartik's page.tpl.php):

<?php if ($main_menu && user_is_logged_in()): ?>
  <div id="main-menu" class="navigation">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#main-menu -->
<?php endif; ?>


Menu hook callbacks not working for anonymous users

You're doing a switch(), but with only a default for the switch and no options, it means the switch is unnecessary. Drupal also provides the drupal_goto() function, which handles both redirects, as well as cancelling killing the script so the redirect can proceed. Your code can be simplified to:

function my_customerror_page($code) {
  $dest = variable_get('my_customerror_' . $code . '_default', '');
  drupal_goto($dest);
}

Or if you're really set on using header() to set headers for whatever reason, you just need to add drupal_exit() after your call to header().


Implementing an age check using InboundPathProcessorInterface

service:

  blah.preserved_system_paths_redirect:
    class: Drupal\blah\Redirect\PreservedSystemPathsRedirect
    tags:
      - { name: event_subscriber }

--

<?php

/**
 * @file
 * Contains \Drupal\blah\Redirect\PreservedSystemPathsRedirect.
 */

namespace Drupal\blah\Redirect;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Routing\RouteMatch;

/**
 * Class PreservedSystemPathsRedirect.
 */
class PreservedSystemPathsRedirect implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST] = 'checkSystemPaths';
    return $events;
  }

  /**
   * Redirect from original system paths to their new locations.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $response
   *   The created response object that will be returned.
   * @param string $event
   *   The string representation of the event.
   * @param \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $event_dispatcher
   *   Event dispatcher that lazily loads listeners and subscribers from the dependency injection
   *   container.
   */
  public function checkSystemPaths(GetResponseEvent $response, $event, ContainerAwareEventDispatcher $event_dispatcher) {
    $routeMatch = RouteMatch::createFromRequest($response->getRequest());
    $route_name = $routeMatch->getRouteName();

    switch ($route_name) {
      // Regional settings are now available in the blah/site settings form.
      case 'system.regional_settings':
      // Maintenance mode is now available in the blah/site setting form.
      case 'system.site_maintenance_mode':
        $url = \Drupal::url('blah.settings');
        break;
    }

    if (isset($url)) {
      $returnResponse = new RedirectResponse($url, Response::HTTP_MOVED_PERMANENTLY);
      $response->setResponse($returnResponse);
    }
  }

}


Yes, you need to install Drupal locally to test the theme progress. There is a nice guide at http://drupal.org/node/307956, I hope it works for you. Please post back if you need more guidance. It is the easier way I know to get started with Drupal on your computer.


Contextual filters are just the term. So in the contextual filter input box for the Views Admin you would put mississippi-river as an example. In addition to Term name converted to Term ID you want to be sure you check the box for convert spaces to dashes further down in the specify validation criteria or else "mississippi-river" will not be found because it's expecting a space and you're providing a dash.

For the parent/child filters you're trying to achieve look at Taxonomy Edge. The -dev release contains some contextual filters for "parents" and "children" of stuff.


how to hide the main menu which is not listed in a block

It seems that you want to lock down specific areas of the site with permissions that are not readily available on the Permissions page. I would address that issue in the following way.

I would update the theme to make the region editable and make it so that the menu was not part of the theme by default.

Next I would install the Context module so that I could display specific blocks, in specific regions, when specific conditions are met.

Finally I would create a Context with the settings:

Conditions

"Sitewide: Always active"
"User Roles": "Authenticated User"

Actions

"Block": Main Menu


How to show "Log in or register to post comments" message when no comments on content?

this is my temp solution.. i copy the ds-1col template to my ds-1col--node.tpl.php and add this code at bottom.

<?php global $user;
if (!$user->uid) {
print render($content['links']['comment']['#links']['comment_forbidden']['title']);
} ?>


The solution is simple: remove the caption tag from the allowed HTML tags in "/admin/config/content/formats" :-)


It was my mistake. I forgot, that I need to enable commenting on individual nodes. Sorry for this stupid mistake. Thanks @rémy


Getting the content type in Template.php

You can put hook_preprocess_node() in your template.php.

function THEMENAME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'your_type') {
    //Add the JavaScript file.
    drupal_add_js('/path/to/jsfile.js')
  }
}


How to use the Leaflet 'maxBounds' option?

Got it working. Override the leaflet.drupal.js file as follows. See the leaflet markercluster module for how to override in an 'As You Like it kind of way.' in a custom module. Pretty useful.

// instantiate our new map
  var lMap = new L.Map(this.mapId, settings);
//note, the comma (NOT A semi-colon) at the end of the next line - this is  important.
  lMap.bounds = [],
// Now set your maxbounds, see the leaflet documentation for reference.
    lMap.setMaxBounds([
      [40.712, -74.227],
      [40.774, -74.125]
    ]);


Views 3 "no results behavior" for different languages

This is a bug which is currently being worked on.


How to use db_select and apply a condition for another table's data?

The following query should be self-explanatory.

$query=db_select('table1','t1');
$query->join('table2','t2','t1.nid = t2.nid');

$query->condition('t1.uid','1')
      ->condition('t2.uid','3')
      ->fields('t1',array('uid','nid'))
      ->fields('t2',array('date'));


Use the "in" operator:

{% if '/services/' in url %}

More information: http://twig.sensiolabs.org/doc/templates.html#containment-operator

If you didn't do it already, put this preprocess function in the file mytheme.theme in your theme directory:

function mytheme_preprocess_page_title(&$variables) {
  $variables['url'] = $_SERVER['REQUEST_URI'];
  $variables['#cache']['contexts'][] = 'url.path';
}

Edit:
By moving the code from page inside a block we need to provide a cache context.


Translate homepage meta Title and description

You need to install the variable translation module.

  The Variable translation module, part of the Internationalization
  (i18n) package, allows you to translate text and settings that are
  stored in Drupal as variables. These variables include text such as
  'site name' and 'site slogan', as well as settings like 'Default front
  page' and 'Default 404 page'.

Go to

  admin/config/regional/i18n/variable

and select the variables you would like to translate.
Then translate the string(s) at

  admin/config/system/site-information


How to add custom text settings to a custom theme?

Right now this option in your theme is in configuration setting. I think they done it using some custom module. Edit the module file, add a new text area using following code..

 $form['name']= array(
'#type' => 'textarea',
'#title' => t('Main Address'),

);

Save the

$form_state['values']['name']

using variable_set('name' , value) in form submit. Then retrieve variable in template using variable_get('name').

Another easy method is just edit your theme-settings.php. Add a new textarea field. you will get the field in your Home » Administration » Appearance » Settings.
 You can access that value using

theme_get_setting('field name');

Hope this will helps you...


How do I update Drupal Distribution (Commerce Kickstart) on shared hosting environments?

Use drush and try with this article: https://duntuk.com/how-install-drush-godaddy-cpanel-hosting
or
Update manually.

I would avoid the "update" interface in drupal. Reminder: All of the 100 or so modules are stored in the profile folder.


How to disable the number that the Email Registration module puts on peoples username on registration

I have figured out my own problem. The module has a double fail safe for there not being duplicate usernames. Every time a new account is created it adds the uid to the end of the username so that there would be no duplicates, but if there was still a duplicate it will append a 1 or 2 on the end. Since the odds of there being 2 identical usernames from emails I am just commenting out where it adds the uid and going with just the appending a number if it ever does happen. Here is the code I commented out:

/* 070715 AS commented this out so the user id is not concatenated to the end of the user name,
this is just guaranteeing that no 2 people have the same username which has odds so small
we aren't going to worry about it.
  if (!empty($uid)) {
    // Put uid on the end of the name.
    $name = $name . '_' . $uid;
  }*/


Should magic quotes be on/off for Drupal 7?

Off. Currently it's non standard to set them on, and here you have somebody with problems created by magic quotes on.


How can open add content form in modal form module

finally I found my answer, I put it here for another than want do something like this

function mymodule_menu() {
  $items = array();

  $items['mymodule/page'] = array(
    'page callback' => 'mymodule_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  $items['mymodule/%ctools_js'] = array(
    'page callback' => 'mymodule_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Helper function to make a link.
 */
function _mymodule_make_link($link_text = '') {
  // Set a default value if no text in supplied.
  if (empty($link_text)) {
    $link_text = 'Magical Modal';
  }

  return '
' . l($link_text, 'mymodule/nojs', array('attributes' => array('class' => 'ctools-use-modal'))) . '
';
}

/**
 * An example page.
 */
function mymodule_page() {
  // Load the modal library and add the modal javascript.
  ctools_include('modal');
  ctools_modal_add_js();
  return _mymodule_make_link('Magical modal');
}

/**
 * Ajax menu callback.
 */
function mymodule_callback($ajax) {
  if ($ajax) {
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('MyModule Modal Form'),
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $output = ctools_modal_form_wrapper('mymodule_form', $form_state);

    // If the form has been submitted, there may be additional instructions
    // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('mymodule_form');
  }
}

/**
 * Drupal form to be put in a modal.
 */
function mymodule_form(&$form, $form_state) {
  module_load_include('inc', 'node', 'node.pages');
$form = node_add('article');
  return $form;
}


Changing decimal field scale and precision using database

you could create a new field with the settings you need and import the data from the old field.
see: https://www.drupal.org/node/1491590#comment-9682599


How to change column chart color programmatically

Attempt to answer the last question, i.e.:

  Is there any module by which I can sort out my problem?

To create charts in Drupal, consider the comparison of charting modules as a possible place to start from, to find the module that best fits your needs. That comparison does include the modules mentioned here, but quite AbitMORE charting modules ...

Possible alternatives that should solve this specific question, are the Chart module, or the Charts module. I recently created quite a lot of new Chart documentation, and Charts documentation. Though there are other alternatives in that comparison that might be a better fit for this specific case.

The license that comes with the related charting library (engine) in each of these modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. 'Possible privacy concerns' or 'Yes or no support for saving charts in PDFs' is another typical item to consider.

Be aware: I'm a new (co-) maintainer of both module 'chart' and 'charts' (confusing names, I didn't invent those names), and the author of the comparison.

Ps: the question does not say why it has to be done programmatically. But note that the Charts module ships with out-of-the-box samples which seems to be very close to what you are trying to create. Adapting these samples to exactly fit your needs seems like cloning these samples in a new views display or a new view.


As it turns out, in the system_cron was ultimately causing the query storm. The particular bit of offending code was:

$result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE,
  ));
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {

As it turns out, there were about 200k files which matched that first query. It would then loop through them all and check to see if they had any references remaining. Since it had to do this check that may times, it was hammering the database and causing a decent amount of slowdowns. Additionally, it wouldn't find anything to prune since all of those files are still presently in use.

The solution in my case was to simply set the status field to 1 on all of the offending records, since they weren't going to change any time soon (these are product images whcih don't get updated often). The full consequences of that are unknown to me, but it seemed like a reasonable fix.


Decide which modules to enable / disable in make file

Drush make only downloads projects; if you want to enable some modules, you must do that with an installation profile.  An installation profile contains a make file, plus some code to configure your site.

If you're using Drupal 7 and would like to create a starting installation profile from an existing site, see http://drupal.org/node/1368242.  There is a patch there that will create a profile for a D7 site.  The issue is marked "needs work" because the code templates for D6 are not in place yet.


What's the difference between content type and node?

Newcomers to Drupal who aren't tech savvy often struggle with the concept of Content types and Nodes.

I find it beneficial to remind them of the real world equivalent—forms and filling in forms.

Remember in the olden days when you were given a piece of paper out of a whole stack of them, with labels and boxes and you used a pen to fill in your information by hand (name, address, DOB, etc.) when applying for a college or anything?

The Drupal equivalent to a real-life stack of blank sheets of preformatted forms is a Content type. When you're creating a Content type in Drupal, you're actually designing a form of blank fields. You're designing a structure, it holds no data.

In the digital world, we don't have to have multiple copies of Content types, one is enough because it doesn't have to be printed on paper. It is printed on the screen and we can always use the same "source". That's way we only have one “Create article” form and not thousands of them like you have to in paper form.

When you fill in one sheet of paper in ink with your specific information it is considered one form submission. The Drupal equivalent to this one filled-in sheet of paper is a Node. Node is the actual data entered into the structure defined by the Content type. You can create many Nodes (data submissions) for a Content type.

When you want to publish an Article you are first presented with a form to fill—Create Article page. This is the Content type form. Once you enter specific data into it and Save, you have created one submission of that form, one Node. You can create many nodes, with different data, as submissions to the same form.


This is a very common and very difficult to debug problem. It happens when there's an inconsistency between the cache version and the submitted version of a form; whatever the reason.

You're best bet would be to upgrade Views and Ctools (and perhaps BEF too) to the latest dev versions.

Also, one important thing to consider is wether or not you have custom code altering the form.


dreamhost VPS returns a lot of blank pages

I would check PHP error reporting on the server : usually, WSOD are caused by hidden PHP errors. A value of E_ALL & ~E_NOTICE is usually fine, at least for development.


Overlay and jQuery don't work, what should I do?

Have you seen Overlay and jQuery dont work on Win 7, but work on XP?

The last comment reported in that report is the following one:

  Problem resolved. I still don't know why this problem arise, but after Windows 7 latest updates installed (on 18 apr 2011) overlay and jquery now working.


How to import image using Feeds which doesn't have a correct file extension?

I managed to solve this by using the feeds tamper module with the following php snippet to save the image and then reference the path on my server.

$checkext = substr($field, -5);

if (strpos($checkext,'.') == false)
{
  $filename = str_replace(".","_",microtime(true)).".jpg";
  $output = "public://field/image/".$filename;
  file_put_contents($output, file_get_contents($field));
  return  $output;
}
else
{
  return $field;
}


Well to my knowledge Drupal doesn't mind the input/import data that much, as long as it's rendered in a secure way.

  So what we really have to do is make sure that, regardless the data, its content can never be interpreted as SQL. To do this, we use the escaping functions provided by the database API. We do this escaping in the database layer and not directly after receiving input as it may not be the only escaping (or filtering) we have to do. - https://www.drupal.org/node/101495

Just my 2 cents :)


Drupal 7 how can I alter page content generated with module?

You can change the variables of the page content implementing the template_preprocess_page() function in your module or theme. As of Clive's comment, I want to update that you can preferably use hook_page_alter(), which is called earlier than preprocess function.

function YOURMODULE_preprocess_page(&$variables) {
  // Do your changes here
  // If have Devel module installed
  // You can use dpm() function to print the contents of $variables array.
  // dpm($variables)
}

or

function YOURMODULE_page_alter(&$page) {
  // Do your changes here
  // If have Devel module installed
  // You can use dpm() function to print the contents of $variables array.
  // dpm($page)
}

Additional Reference:

Render Arrays in Drupal 7 See the section "Creating Content As Render Array"

  A page callback should return a render array, as should hook_block_view()'s $block['content']. This allows your module and other modules to treat the content as data for as long as possible in the page generation process.


Force authentication for specific IP range on IIS

Use the Rules module to determine if the user is from a specific IP range, or is authenticated.  If they are not from that IP range or not logged in, redirect to Login page.

Install and enable Rules module.
Create a new Rule that is triggered when Drupal is initializing.
Add a Condition of Data, Text Comparison
Add a Data field of site:current-page:path that matches user, and negate the condition so this Rule requires this Condition to be False.
Add a Condition Or group, set it to Negate, so that if neither condition are positive it will execute an action
Within the Or group, add a condition that executes PHP Code. Enter PHP code that returns True if the IP is in range (learn how to get the visitors IP).
Within the Or group, add another condition of User's role. Configure the condition to return true if the User has the Authenticated User role.
Add an Action of Page redirect, and redirect the user to user, or some other page where they can login.
Save and enable the Rule.


The page you are looking for is provided by Field UI core module. Go to /admin/modules and enable it.


WebForm images not displayed after node creation with submission handler

I would agree with cchen - you need to use the URI of the image to print it - and I'm not sure 'field_image' => $values['image'] would work in this case.


Error when creating a custom Twig filter

The problem in the code above is that your Twig extension class is extending the internal Drupal Twig extension class. That breaks the Twig extensions added by Drupal core and that's why you are getting the error.

To fix this, you should make your Twig extensions extend Twigs internal Twig extension class. Your class should be defined like this:

class MyExtension extends \Twig_Extension {

After making that change, you can also remove arguments set for that class from the MODULE.services.yml


The problem is that you're not specifying what menu your links belong to. Instead you are setting the parent, but I think the parent doesn't exist in your cast. This works for me:

custom_module/system.menu.my-custom-menu.yml:

langcode: en
status: true
dependencies: {  }
id: my-custom-menu
label: 'My Custom Menu'
description: ''
locked: true

custom_module/config/install/custom_module.links.menu.yml:

custom_module.custom_link:
  title: 'My Custom Link'
  weight: -10
  route_name: custom_module.custom_route
  menu_name: 'my-custom-menu'


You can use the PHP text filter in core. It is quick and dirty.

Add a Header of global text area to the view. Then add this PHP code using the PHP code text format:

<?php
$query_params = drupal_get_query_parameters();
if (isset($query_params['title'])) {
  print t("Results for @query", array('@query' => $query_params['title']));
}
?>

Exposed filter and sort queries in views are passed as query parameters in the form of:

?title=test

In the above code I am just looking at the parameter 'title', but you can adapt that code snippet to suit your needs. Just look at your url to see what query parameters are passed along.


Can a database be tested to see if it is inconsistent?

As I was writing up a description for a sandbox project, I ran across a sandbox project for doing this:

http://drupal.org/sandbox/anton_krechetov/1345066

It currently only works for Drupal 6, and there haven't been any commits since Nov 2011, but it looks promising.


Approach for building local/city versions of a national website?

I'd recommend the Domain Access module(s) as the easiest way to set this up with multiple sub-sites (even with sub-domains) but still having a central site to control content and access:

  The Domain Access project is a suite of modules that provide tools
  for running a group of affiliated sites from one Drupal installation
  and a single shared database. The module allows you to share users,
  content, and configurations across a group of sites

It comes with a dozen or so helper modules and a few stand-alone projects that make it easy to create and manage sophisticated site networks.


How to find operation type in validating form?

A new node will not have a node ID.

So you can check the form values or the original form for that to determine whether it is a new node or not.

For example:

if (empty($form_state['values']['nid'])) {
  // This is a new node.
}
else {
  // This is an existing node.
}


The secure alternative would be to use l() to generate the link.
In your current code, it's very likely that you've created a security problem.

l('More', $fields['path']->content) would be better.

But in answer to your original question. you are missing echo statement here

<a href="<?php echo $link ?>"> more </a>


Stop displaying content of subpaths for invalid URLs

This can be achieved through views contextual filter.

As per wesleymusgrove's asnwer on drupal.org support
"Under "WHEN THE FILTER VALUE IS NOT IN THE URL", tell it to "Display all results for the specified field".  This allowed me to still see the list of all articles at the views path: example.com/articles

And under "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" check "Specify validation criteria", Validator "Content", Content type "Blog post" or "Article" - whatever content type it is.  This allowed me to still see a valid post at example.com/articles/my-page, but invalid links like example.com/articles/mypage respond with 404


t('String') always belongs to the "Built-in interface". If you have t() texts, then you don't need to create textgroups.

They are meant for strings that are not translated with that function, usually content/configuration. The I18n modules define lots of these groups for things like variables, menus, taxonomy terms and so on.


Calling a class defined from another module

In your comment, you say the class is inside module/src/controiller/controller_name.php, but you refer to the class as Drupal\module_name\MyClassName. That is wrong.
Assuming module_name is the directory containing your module (and the short name of the module itself), and that module_name/src/Controller/controller_name.php is the file containing the class definition, you need to use the following code.

use \Drupal\module_name\Controller\MyClassName;

$instance = MyClassName::getinstance($host, $user, $pass);

That is evident in any file referring a class, for example user.routing.yml.

user.logout:
  path: '/user/logout'
  defaults:
    _controller: '\Drupal\user\Controller\UserController::logout'
  requirements:
    _user_is_logged_in: 'TRUE'

As you notice, the class is referenced as \Drupal\user\Controller\UserController, not \Drupal\user\UserController.

Also, the filename is generally the name of the class plus the php extension, so in your case the file name should be module_name/src/Controller/MyClassName.php, not module_name/src/Controller/controller_name.php.

As side note, if you are calling a static method for a controller class, you probably need to do something more than just invoking it. Normally, controllers get also the dependency injection container; without that, they would not work. See for example UserController::create().

public static function create(ContainerInterface $container) {
  return new static(
  $container->get('date.formatter'),
  $container->get('entity.manager')->getStorage('user'),
  $container->get('user.data')
  );
}

If you call controller a class that is not a controller class as Drupal defines that, then your code could work; differently, if you are calling a Drupal controller class, resolved the error about a class not found, you will get more errors to fix.


The issue was while I had imported all of the past module information, I was missing the profile files.


Hook that act on a field being inserted or updated?

Why not use a hook_entity_update()? This hook gets triggered as soon as an entity gets updated. Inside the hook you should include some logic with respect to your field.


My Drupal setup relies on some other modules, but otherwise I have the same set up. I am not an expert (critics, take note!), but have you tried creating a new input format which ONLY contains the emogrifier filter?
I have all my standard filters in one input format that gets applied to all content types, and then I have a seperate input format which applies emogrifier as the post-filtering process in HTML Mail.
Just a suggestion. Daniel.


You need to declare on what object (or class if static) to call the callback, like

'callback' => [get_called_class(), 'settingsAjax']

or

'#ajax' => [
            'callback' => [get_class($this), 'addMoreAjax'],
            'wrapper' => $wrapper_id,
            'effect' => 'fade',
          ],

or at least

'callback' => '::settingsAjax'

depending on your code.


Using the CodeMirror Syntax Highlighting plugin with CKeditor and the WYSIWYG module

You can install CodeMirror as a library, and then make a "FULL HTML" profile in WYSIWYG. In practice, you'd get a drop-down entry for it on your edit page (e.g. the ability to switch editors to CodeMirror instead of CKeditor), and a config page within the WYSIWYG module. It's not fully flushed out, but is workable enough to use in production, and TwoD has given really strong input for how we could finish it up properly.

Alternately, you could try to get it working as a CKeditor plugin. You'd get a button toggle in CKeditor, but no configurability within the WYSIWYG module (which defeats the purpose of using WYSIWYG in the first place, IMHO). Haven't tried that one, but my read is that it works.

If you're not too concerned about configurability, you might be able to just drom WYSIWYG completely, and use the original CKeditor module instead. According to one of the folks in those linked threads, CodeMirror works with it out of the box.

There's also a TinyMCE integration module, wysiwyg_codemagic, that supposedly works.


Within a view listing, how can I denote whether a node's date is upcoming, current or past?

A possible solution is to use the Views feature "rewrite result" (as explained also in Rewriting view fields), combined with the Views PHP module.

If you're not experienced in PHP, you may want to experiment with only the "rewrite result" feature, which may help to come up with an acceptable compromise for what you're looking for.;

Note: The Views PHP module only has an alfa version as of today, but it's used in about 70K sites anyway ... That many sites can't be wrong, right?


Adding 'Add to Cart' to 'Collection Products' view

In your view, can you add a relationship to the product category in your cart? It should be visible as Referenced Entity or Referenced Product... basically in views you need to join your node/product to its related store/product, once you have done that you should see an available field "% to buy" with the formatter "add to cart button"


Views Summarize Won't Sum when field is output as link (D7)

Have you seen this issue on drupal.org: http://drupal.org/node/1880450?

It looks like this is actually a bug in the module - not anything you're doing wrong.  However, there seems to be a user-submitted patch that fixes issues with decimals, currency, etc that you can try out...


I found the solution.

Editing the template.php file of my custom theme and more specifically the theme_form_element() function. In that function, simply move these 3 lines where I want :

if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . "
\n";
}


limit amount of upload images (through imagefield module) to only 1 by code/programmatically

You want to use a hook_form_alter to process this for just that form, ex.

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

    if ($form_id == 'user_register') {
        // do stuff here
    }

}

The 'stuff' is the real challenge, especially since you are allowing for unlimited uploads. There is a previous post on this with a solution for a limited set (<10):

https://stackoverflow.com/questions/5701488/change-fields-number-of-values-per-role

My suggestion for resolving this (though not ideal) would be to add a custom handler as part of your logic that would check to see if one already exists and gently prod them not to add more than one.

if ($form_id == 'user_register') {

    $form['<image field name>']['#element_validate'] => array('_mymodule_only_one_image'),

}

and then for your validation function, you could simply test whether a 2nd image exists and prod the user to only submit one. Rough psuedo-code example here, haven't tied this to an actual form.

function _mymodule_only_one_image($element, &$form_state) {

    if (!empty($element['<image_field_name>'][1])) {
        form_error($element, t('Please only upload one image');
    }

}

Another option would be to try and disable the ajax handler that initiates the 2nd upload through your own custom jquery override, which you could also add in to this custom form through the above form_alter.


How can I create a new content type based on an attached format

1)
Place each expiration field above the corresponding other field and then add the following CSS rules to your theme:

form.node-form .field-name-field-product-EXPIRATION-DATE {
position:absolute;
right:0;
width:200px;
}

On the content creation pages, this will move the expiration field to the top right of the field below.

2) Yes, users can add an unlimited amount of values to each field. To enable this go to the desired field in your content type and edit it. There look for "Number of values" near the bottom of the page. Choose the desired amount. Suppose you choose 5, the user creating the content can add up to 5 values for this one field. I hope this works out for you.


How to get the image from the url and store in the custom path?

Hope this will help you.

In Drupal 7 , system_retrieve_file function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file_managed table if you want it to be managed.

You need to create a folder beachesmigration inside sites\default\files.
By using system_retrieve_file it will be store your images inside beachesmigration folder with the filename you no need to specify the filename manually.

 $image = 'http://wordpress.ikitesurf.com/wp-content/uploads/2012/09/2032239599_fdce5e0ab0_z.jpg';
//I have used picture folder to store images using image field settings
 $file = system_retrieve_file($image, 'public://beachesmigration/', TRUE, $replace = FILE_EXISTS_REPLACE);

Source


How to check field value against same field on existing nodes of same content type

I don't know how to achieve that with rules, but you could use EntityFieldQuery, in a custom submit callback of property_node_form.
Something like that :

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_property_node_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'mymodule_property_node_form_submit';
}

function mymodule_property_node_form_submit(&$form, &$form_state) {
  $phone_number = $form_state['values']['field_phone_number'];

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'property')
    ->propertyCondition('nid', $form_state['node']->nid, '<>')
    ->fieldCondition('field_phone_number', 'value', $phone_number)
    ->range(0, 1);

  $same_phone_count = $query->count()->execute();

  if($same_phone_count > 0) {
    // send mail
  }
}


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


Recursion when reading field in hook_entity_load

Your code works just remove the $entity->save(); and it works i have tested it:

function zzzmodule_entity_load(array $entities, $entity_type_id) {
  foreach ($entities as $entity) {
    if ($entity_type_id === "node" && $entity->hasField('other_field')) {
      $t = $entity->title->value;
      $o = $entity->other_field->value;
      if (empty($o)) {
        $o2 = json_encode($t);
        $entity->set('other_field', $o2);
      }
    }
  }
}


Is there a way to insert a view in a node form?

Found it i can use Markup module to use php code in the field and use this code;

WHATEVER is the name of your view.


I know this is late, but for people like me who are still experiencing similar problems with ajax and forms in Drupal, here's how I fixed this.
In your ajax callback function, instead of returning just the render array, you need to call the form_builder() function and return its result.
Eg., my code goes like this:

function inventory_purchase_item_add_ajax(&$form, &$form_state) {
    //...

    unset($form_state['input']['line']);
    unset($form_state['values']['line']);

    //Update the form's lines array
    $lines = update_inventory_purchase_form_lines($form_state['node']->line, $purchase_item_count);
    $form['vtab1']['purchase']['items_wrapper']['line'] = $lines;
    return form_builder($form['#id'], $lines, $form_state);
}


After installing the searc api module:

1) goto: /admin/config/search/search-api/index/default_index/edit

If you want for example to search for both Users & Content at once, make sure that both entities for Content & Users under the Data sources section are checked.

2) Goto: http://site8.dd:8083/admin/config/search/search-api/index/default_index/fields

This page is used to choose which are the fields you want to be indexed for your search.

So make sure on this page that all the fields you want to search your entities by are added to your entities; If not,
add any field using the +Add Fields button.

3) On the same page: http://site8.dd:8083/admin/config/search/search-api/index/default_index/fields

Any field you add, it has its own data type which you have also the permission to change it.

As per the data type table available at the bottom of the page:

  Fulltext fields are analyzed fields which are made available for
  fulltext search.  This data type should be used for any fields
  (usually with free text input by users)  which you want to search for
  individual words.

so in your view, if you want to use the Fulltext search to search for your contents, every indexed field on this page should also be set to Fulltext data type.

4) Goto: http://site8.dd:8083/admin/config/search/search-api/index/default_index

And make sure that the index Status bar is 100% and so all your contents are indexed to be searchable.

When you have done the above, create a new view as per below:

Show: index default content index
Check Create page box
Display format Grid
Hit save and edit button.

Within the views configuration page:

Under add fields section:

add any fields you want and make sure the field title has the (indexed field) text.

Under the filter criteria section:

add the fulltext search field and exposed to visitors.

Here you go, visit your search page and enjoy.

If none of the above helped you, feel free to ask any other question in comments or update your current question.


What hook should I use to define a class?

You wouldn't use a hook to define a class, that doesn't really make sense.

If you're talking about autoloading, you have two options:

In-built - you can add a file called, for example, foo.class.inc, in your module's root, and add the following to your module's .info file

files[] = foo.class.inc

Once you've cleared the caches, any time you request a new foo(), the appropriate file will automatically be included.

See Writing module .info files for more information.
XAutoload - PSR-0 & PSR-4 style autoloading. If you're into OO this is a much better option in my opinion.


You should use the url() function to create URLs.

  Generates an internal or external URL.

This functions handles all complexity of creating an URL, including language prefix. url() handles exernal URLs too.

You can also use the l() function to create anchor tags:

  Formats an internal or external URL link as an HTML anchor tag.

  This function correctly handles aliased paths and adds an 'active'
  class attribute to links that point to the current page (for theming),
  so all internal links output by modules should be generated by this
  function if possible.

In your case you can use:

<?php print url('<front>', array('absolute' => TRUE, 'fragment' => 'project'));?>


How to add ShareThis link field into View

Please check images for how to use sharethis filed within views

RESULT PAGE:


Customize the output style of a view field

For this case, don't use Style Settings. Instead, use Rewrite results.

Click on Replacement patterns, to get the Token of your field.

Then just wrap Token inside div tag.


Disable the Drupal 7 overlay for some administrative links

Hope this will help you.

In Drupal 7 you can achive this by using hook_admin_paths_alter

Programatically

hook_admin_paths_alter : Redefine administrative paths defined by other modules.

    function HOOK_admin_paths_alter(&$paths) {
      //return FALSE to the path where you don't want to show in OVERLAY
      $paths['node/*/edit'] = FALSE;
      $paths['node/add'] = FALSE;
      $paths['node/add/*'] = FALSE;
    }

Using Module

Overlay Paths : You can enable the overlay for selected non-admin paths and also you can disable overlay for selected admin paths.


How can I create page.tpl for user’s profile page?

Try this...

page--user-profile.tpl.php

[page]--[node].tpl.php

or actually...

page--user.tpl.php

To see available templates for this page simply do the following in your themes template.php

function YOURTHEME_preprocess_page(&$variables) {
   echo '<pre>'; var_dump($variables['theme_hook_suggestions']); echo '</pre>';
}

If nothing were in there (doubtful), then just add your own...

if ($SOME_CONDITION) {
    $variables['theme_hook_suggestions'][] = 'page--user-profile.tpl.php';
}


How to create sub menu in Drupal 8 using views result for specific item of the menu?

We have implemented using the

MODULE_NAME_menu_links_discovered_alter(&$links).

In which, We have accessed the result of the block by using the following code.

 $result = views_get_view_result("view_name", "display_id");
    foreach($result as $result) {
      $title = "Entertainment"; // we have took as static
      $tid = 10;
      $slug = str_replace(' ', '_', strtolower($title));
      $links[$slug] = array(
        'title' => $title,
        'route_name' => 'view.VIEW_NAME.DISPLAY_ID'
        'route_parameters' => array('arg_0' => $tid),
        'description' => 'Dynamic',
        'provider' => 'MODULE_NAME',
        'parent' => 'menu_link_content:DATABASE_UUID_OF_SELECTED_CATEGORY',
        'id' => $slug
      );
    }

We have used route_name for assigning the url, this url should be the existing url of the drupal site.

We need route_parameters for passing the arguments.

For accessing the Video Link : reference in parent of $links. I have got it from the

SELECT uuid as DATABASE_UUID_OF_SELECTED_CATEGORY FROM `menu_link_content` where id = "TID_Video_Link_of_Main_menu"

After that, We have used that id in parent as 'menu_link_content:04c479c9-7234-4de2-a4f0-e03b0a3003b6' so all links will be added below the Video Link of the main menu.

After doing all the code and we need to clear the cache. And we are able to see the sub menu from the views of texonomy to Video Link of the main menu.

Please suggest me if there is any better way than this.

For Reference: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Menu!menu.api.php/function/hook_menu_links_discovered_alter/8.2.x


How to just show front page and message when search api search was queried with blank input

Here is a solution:

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

  if($form_id == 'search_block_form' || $form_id == 'search_form') {
    array_unshift($form['#validate'], 'custom_search_validate');
  }
}

function custom_search_validate($form, &$form_state) {
  dpm($form_state);
  if(isset($form_state['values']['search_block_form']) && $form_state['values']['search_block_form'] == FALSE) {
    drupal_set_message('please enter the terms of the search', 'error');
    drupal_goto();
  }

  if(isset($form_state['values']['keys']) && $form_state['values']['keys']
    == FALSE) {
    drupal_set_message('please enter the terms of the search', 'error');
    drupal_goto();
  }
}


Rather than "waste time" with modules, I'll spend a little time looking at how a module like https://www.drupal.org/project/views_watchdog handles something I want to do.  Turns out it's like so...

function views_watchdog_format_message($message, $variables) {
  return $variables === 'N;' ? $message : t($message, unserialize($variables));
}


Looking for informaton on Drupal core security process, audits and benchmarking

There are 2 websites you should look at, http://buytaert.net/greg-knaddison-and-drupal-security and http://crackingdrupal.com.


D7 + Views 3 - How to reproduce a teaser with fields in Views

You can use Display suite and Views to achieve the required functionality. Using Display suite, you can control what fields appear in the teaser. Also, Display suite provides views Integration, so you can use your new teaser to show up in views. This article explains more about this.


jsmin+ causes high server load in drupal 6

Give AdvAgg a try. It works around the limitations of jsmin+


You can try and change the permission of the folder 'sites/all/files' to give it 777 permission in your drupal installation and see if this works.


Displaying block only when user visits his own profile page

If you are using the php code in the block visibility option than I guess the following should work:

<?php
global $user;
$user_id = $user->uid;
if (('user' === arg(0)) && ($user_id === arg(1))) {
  return TRUE;
} else {
  return FALSE;
}
?>

If your site is multi-lingual than may be you have to change the if condition as: if (('user' === arg(1)) && ($user_id === arg(2)))


How to send mails to users with bulk operations in drupal7

You can use Rules module with VBO to extend the operations of VBO. In Rules module, you can select the action to send mails to users with whatever text you want.


When you write $node->$sku, PHP takes the value of $sku and uses it as name of a property.
In your case, $sku contains 'tshirt-11', and $node->$sku is equivalent to $node->tshirt-11. Since $node->tshirt-11 is not defined, you get the error you see.

The code you should write is the following one.

  uc_stock_set($sku, $stock_value);
  uc_stock_adjust($sku, $stock_value);

As side note, the value of a field is accessed using field_get_items(). The code you use to set $sku should be rewritten as the following.

$items = field_get_items('node', $node, 'field_sku');
$sku = $items[0];


Installing new module in Drupal 8.3.2 link is not exist in xampp

Just download zip unzip it and paste folder to xampp\htdocs\modules. It should be working then.


May I use Bootstrap-CDN on Subtheme for production site?

Yes you can use the BoostrapCDN for js and your own style.css. I'm not sure if would overwrite but if those you can create a separate file that is not style.css on the info file to add your CSS or your JavaScript.

If you are using the Bootstrap project by default it allow you to use the CDN.


You can see what page is the referer by using

$_SERVER['HTTP_REFERER'];


security report there is no .htaccess file in private:// directory

When you say sites/all/default/files/private I presume you mean sites/default/files/private.

I suggest deleting sites/default/files/private/.htaccess and setting the permissions of sites/default/files/private to 777 temporarily. Drupal should then be able to recreate the .htaccess file which should be exactly correct.

There are other reasons this can happen, I just can't remember off the top of my head sorry. I've had this same problem before.


The offending parts in your VCL are (line 53):

# Drop any cookies sent to Drupal.

 if (!(req.url ~ "install\.php|update\.php|cron\.php|admin\.php")) {
 unset req.http.cookie;
 }

and (line 81):

# Drop any cookies Drupal tries to send back to the client. This will make it unpossible to login, unless you filter it a bit better that it is made below
sub vcl_fetch {
 if (!(req.url ~ "install\.php|update\.php|cron\.php|admin\.php")) {
  unset beresp.http.set-cookie;
 }
}

Remove both of them.


function input_request($form, &$form_state) {

    $form['make'] = array(
    '#title' => t('Car make'),
    '#type' => 'textfield',
    '#required' => TRUE,
    );

return $form; //you need this here
}

On order to send it to your mailbox, you will also need a submit button and a submit handler for your form.

Read this, it has good info on how to create, validate, submit, theme drupal forms. http://drupal.org/node/751826

FOr sending email you can use the drupal_mail_send() API or drupal_mail() depending on your Drupal core

http://api.drupal.org/api/drupal/includes--mail.inc/function/drupal_mail/7. http://api.drupal.org/api/drupal/includes--mail.inc/function/drupal_mail_send/6


How do I add a script just above the closing body tag?

You can achieve this simply by using jquery. If you want to access it from all theme pages you need to add the below line in your global common js file which has access to all the theme pages in the app.

$('body').append('<script src="/name-of-your-library"></script>');


Correct analysis for "Mismatched entity and/or field definitions"

Thanks to 4k4 and Clive and following the link I think I can now write up the answer to my question.

This Drupal Change Record (and more detail) documents that
module developers should write hook_update functions for entity updates.
So if you get the "mismatched" warning after a contrib module update
then it's a bug in that module and you should not apply to update to the live site.
This question explains that entity-updates is a developer tool.
If you are a developer working on a test site you may see the
"mismatched" warning whilst making changes.  You will run
entity-updates when you are ready.

So the answer to my questions 2 and 3 is no.


Hooking in to the email verificatin process

It would make more sense to create a rule to activate on After saving new user account. You could do a Text comparison on Account:mail using your regular expression, and if the condition was TRUE, Assign a role for the  new user. It would be waiting for them when they verified their account.

If your requirements change for the site, it is easier to make an alteration through the UI than it is to track down the code that has to be changed.

The same rule can Set a data value in the custom user field if you wish.

EDIT:

Install and activate the Rules module. Then go to /admin/config/workflow/rules and create a new rule,  calling it, lets say 'Upgrade new user' and set it to react on After saving a new user account.

When the configuration screen comes up Add condition and select Text comparison (wait for the AJAX request to complete) then set the Data selector to account:mail. Under Matching Text, click the Switch to direct input button, enter your regular expression in the  Value box, and at the bottom use Regular expression for the Comparison operation. Then save the condition.

Then add two actions; First add Add user role (wait for the ajax to complete) and you should see account as your data selector. Then choose the role(s) to add and save the action.

Then add an action to Set a data value. In the Data selector, find your field, and click Continue. In the Value box using <?php ... ?> delimiters, enter the code you need to return your activation key.

Save everything and try it out.


I think you'll find details in the Watchdog if the updates were performed using the UI.

If the modules were updated using a different method, e.g. Drush or manually, then you'll need to turn to your server logs, assuming that you keep logs for such actions. Drupal won't hold any data about those actions, as it wouldn't even necessarily know they had occurred.

Just to clear things up, the "Recent log messages" report gets its data from the watchdog table, so you're looking in the same place for both.


Want to filter result by using two filters "event start day" and "event start time" in one view for showing upcomming events?

You can try this Views between dates filter module. Or you can create filter by selecting event date and time from the content.
Views Between Dates Filter:

This Views filter provides the between date functionality you've been looking for by answering the question: "What events are on this date?" It displays all content (comparing start and end dates) occurring on a specified date.
Creating this functionality with standard Date filters requires two filters: start date less than or equal (<=) to the supplied date and end date greater than or equal (>=) to the supplied date. The problem is two filters means users must enter a date range, when technically selecting "September" is a range: September 1st to the 30th.
It compares two date fields with one supplied date. Effectively it is the opposite of the standard Date Views "between" operator, which compares one date field with two supplied dates.


How can I make form_alter work with Ajax Comments?

AJAX Comments replaces the core comment form with its own version, so #comment-form is the wrong selector. It'll be something more like #ajax-comments-reply-form-751661-0-0. The numbers break down as [node-id]-[parent-comment-id]-[ajax-iterator]. The parent comment ID comes into play when you're replying to an existing comment.

Because the module uses the core AJAX API, that ID will also change for the new form that appears after a new comment is posted, so using an ID for your jQuery selector isn't a good option.

Without knowing exactly how your markup looks some of this is guess work, but the code to grab a reference to the comment form will look something like this:

var $commentForm = $('#main-body-selector').find('.ajax-comments-form-add');

EDIT:
The Ajax Comments module adds an ajax-comments-form-reply class to all reply forms and adds an ajax-comments-form-add class to all comment add forms.

So, instead of #comment-form you should use ajax-comments-form-add and/or ajax-comments-form-reply to effect the comment form.

(function ($) {
Drupal.behaviors.comment = {
  attach: function (context, settings) {
        $(".ajax-comments-form-reply").validationEngine();
        $('.ajax-comments-form-reply').find('.form-type-textfield').hide();
        $('.text-full').click(function() {
                $('.ajax-comments-form-reply').find('.form-type-textfield').slideDown();
        });

        $(".ajax-comments-form-add").validationEngine();
        $('.ajax-comments-form-add').find('.form-type-textfield').hide();
        $('.text-full').click(function() {
                $('.ajax-comments-form-add').find('.form-type-textfield').slideDown();
        });

  }
};
}(jQuery));


How to suppress composer autoload when installed as an unused dependecy?

I doubt composer manager is an unused dependency. It would make very little sense to list that module as a dependency and not using it. Are you sure there are no packages listed on yoursite.com/admin/config/system/composer-manager?

It is very likely that the module that defines the dependency requires some composer packages to function properly. Even if you managed to suppress the composer manager module, the main module would not have access to the package that composer was supposed to fetch, and likely will not work as expected. In that case you should consider two things:

Move to a host that gives you more privileges
Download the site to your own computer, install and run composer in the file directory configured on /admin/config/system/composer-manager/settings and re-upload the entire site, including the vendor directory.

If there are really really really no packages, you could try to change composer manager's status in the database system table to 0. That disabled the module without checking for dependencies. It could however break a lot of other things, so have your backups and proceed with caution.


Fatal error: Call to undefined function db_transaction()

There is no fuction db_transaction() for Drupal 6 (see Drupal 6 API search).

It is available for Drupal 7 though: db_transaction()


Need advice to get an approach to do a personalized searcher?

Why don't you try a View using exposed filters?  If your content type is made with CCK then you could achieve what you're looking for quite easily.  This video might help you out.  Eric London's Drupal Blog also has something on exposed filters.  I would thoroughly recommend this approach, I've done something very similar to what you're looking for.


You could concat only string with strings, It's php :)
What you can do is to use hook_load() something like this:

function add2basket_link($val) {
  $build = array();
  $build['add2basket_link'] = array(
    '#type' => 'link',
    '#title' => t('Bucket'),
    '#href' => 'basket/add/'. $val->lid . '/nojs/',
  );
  return render($build);
}

/**
 * Implements hook_menu().
 */
function bucket_menu(){
  $items['basket/add/%bucket_link_id'] = array(
    'page callback' => 'data_add2basket',
    'page arguments' => array(2),
    'access arguments' => array('use basket'),
    'type' => MENU_CALLBACK,
    'file' => 'data.inc',
  );
  return $items;
}

/**
 * Implements hook_load().
 */
function bucket_link_id_load($lid) {
  // 'bucket_link_id' is from hook_menu() from $items['basket/add/%bucket_link_id'].
  // lid is id that was passed from add2basket_link() to the #href.
  // link_load() is function to load your object.
  return link_load($lid);
}


Use form_alter to change description under reset password field for user_pass form

Got it!

if($form_id == 'user_pass') {
   $form['name']['#description'] = t('This is a test');
 }


Commerce Feeds: Multiple values in one field or multiple fields?

It sounds like what you need is commerce price table. There isn't a stable release for it yet, but I have seen it demoed where it worked great.


Site UUID in source storage does not match the target storage

You can fix this by changing your local site UUID using drush.

I also needed to run a mix of drush entity-updates -y and installing specific modules with drush en <module_name> -y before the configs would import on a new fresh database.

Update: you shouldn't use drush entity-updates -y anymore.  See https://www.drupal.org/node/3034742


Is it possible to use %user_uid_optional as a view path?

When declaring a views path, you can only use '%'.
This is because Menu API can't handle two loader functions in the same path, and Views already has its own (that loads the view itself).


How do I print an image field value in views-view.html.twig?

views-view.html.twig is not meant to be used for field printing.

You should use views-view-fields--[view-name].html.twig

OR

views-view-fields--[view-name]--[machine-name].html.twig if you want to be even more specific.

and there you just do

{{ fields.field_name.content }}

  For multi value fields, is there a way to print just one value within a field at a time?

{% set field_values = row._entity.get('field_name').getValue() %}
{% for field_value in field_values %}

{{ field_value['value'] }}

{% endfor %}

  By doing {{ fields.field_color_hex.content }}, I printed them all at
  once.

In your case:

{% set hexes = row._entity.get('field_color_hex').getValue() %}
{% for hex in hexes %}

{{ hex['value'] }}

{% endfor %}


"#markup" form element can't have children

Not being able to use "#tree" with a "#markup" element seems a bug of Drupal, as the reference page for the form API reports that "#tree" is supported by the "#markup" element.

As workaround, you can also use the "#prefix" property, as in the following code:

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
  '#prefix' => '
My Heading
',
);

If it is not rendered as you expect, then you can simply remove "#tree" from your code, which doesn't seem to be needed, if all you want is to render the
My Heading
 tag before the form fields. The form API renders the elements following the order they appear in the array; if you want to alter the order, you can use the "#weight" property.

$form['html'] = array(
 '#type' => 'markup',
 '#markup' => '
My Heading
',
);

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
);


What is best way to integrate external jQuery plugin?

Perhaps the simplest way is to add it to your theme.info file

e.g, in mytheme.info

scripts[] = js/jquery.cycle.min.js

That will add it globally sitewide.

For more selective control, use drupal_add_js

e.g, in template.php

/**
 * Implements hook_preprocess_html
 */
function mytheme_preprocess_html($variables){

  $valid_path = ''; // TODO, check arg(), current_path() etc.. for valid_path
  if ($valid_path){
    drupal_add_js(drupal_get_path('theme', 'mytheme'). '/js/jquery.cycle.min.js');
  }

}

An advanced method is to use the Libraries API and hook_libraries_info however any of these methods will work.


Assuming the table and field names are valid, you can run that SQL straight through db_query() and it will work fine.

It won't work if you just put the raw query into an SQL client, as Drupal uses brackets around table names to substitute in any necessary prefix. MySQL doesn't do that, so if you want to run the same query against the server proper, you need to remove the brackets from around the table names.


Using states in Drupal 7 form to provide 'select all' functionality

I don't think the "checked" property works with the "checkboxes" form control (or if I does I know how to use it!)

As a work around use the checkbox type instead:

$form['report_group']['selectall'] = array(
  '#title' => 'Check All',
  '#type' => 'checkbox',
  '#default_value' => 0,
);

$boxes = array(1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five');

foreach($boxes as $key => $val) {

  $form['report_group']['box_'.$key] = array(
    '#type' => 'checkbox',
    '#title' => $val,
    '#return_value' => $key,
    '#states' => array(
      'checked' => array(
        ':input[name="selectall"]' => array('checked' => TRUE),
      ),
    ),
  );
}

Your selector was also wrong. This is a jQuery selector so I find it easiest to use firebug to figure out what it should be and test if it's working.


filter fields of type date with the view module filters

You need to enable the Date Views module (part of the Date project) to be able to filter using interval operators such as "Is between":

Take a look at the upvoted answer to this question for details: How do I add a date field that can be filtered by a relative value?


I found a way to do this using Drush and Localization Update.

Install Localization Update  drush en l10n_update
Configure a local path for po-files (admin/config/regional/language/update)
Configure automatic updates from remote servers or just local sources

Now you can put your own po-files in a local path (for example sites/all/translations). If you have translations for your own module then you name it according to this naming convention:

modulename-version.language.po

So a Swedish po-file for 'my_module', version 7.x-1.1 would be named:

my_module-7.x-1.1.sv.po

Now you have everything setup and you can start updating your sites translation with Drush:

drush l10n-update-refresh # Looks for new po-files
drush l10n-update # Updates translations


Or try using Ajax Login/Register, a complete solution. Here is a quote about it (from the module's project page):

... provides a smooth way for the user to login, register and request new password via AJAX at any Drupal site.
Features:

This module provides a block with 2 links (Login, Register) for the anonymous user.
When the user clicks on Login or register the requested form appears in a nice ajax popup.
The login and register forms can validate using ajax and not redirect on error.
On success the module redirects to the user page.
When user is logged in, the block provides a Welcome !username message and a link to the user page and a logout link.
This module integrates the thickbox plugin with the Ajax module and provides a simple, easy to use and cool login and register block.


Allow authenticated users to fill out fields in nodes that only they can see

you can use field permission to set limit to each field
https://www.drupal.org/project/field_permissions

In field permission,
You can set fields that can edit by an authenticated user and can only edit by an admin role, etc.


How to create a views page of discounted products list?

I'm affraid there's no working solution right now.

you can see and follow List all discounted products in commerce discount issue list for further information and workarounds.


Import CSS stylesheet only for specific content type?

You can add your css only on Blog node pages so it does not impact site wide. Sample code

function MYTHEME_preprocess_node($vars) {
  if ($vars['#node']->type == 'blog') {
    drupal_add_css(drupal_get_path('module', 'mymodulename') . "/css/materializeCSS.css");
  }
}


Adding the category for a custom entity reference field add other fields to the same category

I fixed the problem by adding the following code to the class
  /**
   * {@inheritdoc}
   */
  public static function getPreconfiguredOptions() {
    return [];
  }


Filter by text of a field of an entity displayed in a view

Entity Reference Fields only store the entity ID. To pull other information about the referenced entity into the Views you need to add the Relationship for the ER field.
It will be called something like Content referenced from field_person.
Once you add that Relationship you unlock new Fields and Filters inside Views that relate to the Person entity.
You can now add (Content) Title Filter that uses the Relationship and it will filter text within the Title Field of the Person Content Type.
Without the Relationship the Title Field/Filter will show information about the Publication, the base type chosen for that particular View.
The same goes for other Fields/Filters. If you make them use the Relationship they will pull information from People CT.
Fields/Filters that only exist on People CT will have the Relationship prefilled, as a requirement (because that data isn't accessible in that View without the Relationship).


How to convert the Title field on Image type to multi-line text box

Using the Media module, you can add fields to images, such as description or caption.

OR
Alternatively, you could use the Field collection module to create a 'Gallery image' field type, which has the extra fields that you need.


How can I loop through a multivalue field's values?

The solution is:

  foreach($node->field_author[LANGUAGE_NONE] as $key => $value){
    $nid = $value['target_id'];
    //$key is the index 0, 1 ....
  }


Email notifcations based on specific dates i.e. employee anniversarries

You should be able to configure a rule that will run with cron. Then it will check the employee start date field as the condition and send an email as the action.


How to add value in to multiple value field (entity reference)?

I think this line is wrong:

$user->field_profile_access['und'][]['target_id'] = 34;

You could try with:

$user->field_profile_access['und'][] = array('target_id' => 34);

or this:

$next = count($user->field_profile_access[LANGUAGE_NONE]);
$user->field_profile_access[LANGUAGE_NONE][$next]['target_id'] = 34;

I used LANGUAGE_NONE instead of 'und' here, but that's not the problem.

Or even better, using the Entity API. That example is for a field collection, but the idea should be useful for any entity, including nodes.


What is the best way to add my custom PHP functionality to a Drupal homepage?

The best way forward is to go ahead and create a new module. You can find the steps from this link .It also shows you how to create a block from code.

You can add your files in the module and then make a function call which returns the table and add it as your block content. You can then include your block in the home page from admin interface in any region that you want it to be.

Hope it helps.


Generally speaking, only the form builds with system_settings_form() automatically saves the form field content of all the form fields present in the form. This is because its form submission handler (system_settings_form_submit()) contains the following code.

  foreach ($form_state['values'] as $key => $value) {
    if (is_array($value) && isset($form_state['values']['array_filter'])) {
      $value = array_keys(array_filter($value));
    }
    variable_set($key, $value);
  }

The form you are altering has a different form submission handler, menu_edit_item_submit(), which doesn't contain similar code. The function that is called for saving the menu item, menu_link_save() saves the fields it knows of, and which are defined in the database schema for the table used for this purpose.

  if (!$existing_item) {
    $item['mlid'] = db_insert('menu_links')
      ->fields(array(
      'menu_name' => $item['menu_name'],
      'plid' => $item['plid'],
      'link_path' => $item['link_path'],
      'hidden' => $item['hidden'],
      'external' => $item['external'],
      'has_children' => $item['has_children'],
      'expanded' => $item['expanded'],
      'weight' => $item['weight'],
      'module' => $item['module'],
      'link_title' => $item['link_title'],
      'options' => serialize($item['options']),
      'customized' => $item['customized'],
      'updated' => $item['updated'],
    ))
      ->execute();
  }

db_update('menu_links')
  ->fields(array(
  'menu_name' => $item['menu_name'],
  'plid' => $item['plid'],
  'link_path' => $item['link_path'],
  'router_path' => $item['router_path'],
  'hidden' => $item['hidden'],
  'external' => $item['external'],
  'has_children' => $item['has_children'],
  'expanded' => $item['expanded'],
  'weight' => $item['weight'],
  'depth' => $item['depth'],
  'p1' => $item['p1'],
  'p2' => $item['p2'],
  'p3' => $item['p3'],
  'p4' => $item['p4'],
  'p5' => $item['p5'],
  'p6' => $item['p6'],
  'p7' => $item['p7'],
  'p8' => $item['p8'],
  'p9' => $item['p9'],
  'module' => $item['module'],
  'link_title' => $item['link_title'],
  'options' => serialize($item['options']),
  'customized' => $item['customized'],
))
  ->condition('mlid', $item['mlid'])
  ->execute();

In your case, you need to alter the form, adding the form field, and a form submission handler that saves your data in your own database table.
As there are more than one button on that form, I prefer associate a new form submission handler to the specific button, such as with the following code.

$form['actions']['submit']['#submit'][] = 'mymodule_menu_edit_save_submit';

You could also be interested in doing something when the menu item is deleted (in which case, you should delete the data from your database table); the delete button is $form['actions']['delete'].


Changing a menu's target nodes for each page

I found an answer to my question: the best is to use a programmatic approach by using the l() function that is available anywhere within a Drupal installation. It accepts three arguments:

$text: The text that will be visible to users for your link
$path: The URL that the link will go to when clicked.
$options: An associative array which allows to set additional parameters to further customize the link with CSS classes etc…

A good introduction is found here: http://www.pixelclever.com/how-and-why-use-l-function-create-links-drupal-programming.
This function can be used in the template files, or directly from a node body.


Calling form validation function from new button

See below example which works perfectly...

function drup_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "page_node_form" && arg(2) == "edit") {
    $form['buttons']['process'] = array(
            '#type' => 'submit',
            '#value' => 'Process',
            '#validate' => array('disavow_process_validate'),
    );
  }
}

function disavow_process_validate($form, &$form_state) {
  form_set_error('title', 'Something wrong here !');
}

Please update what you are trying to do inside validate function..


How to deal with files with %20 in name in Nginx

Think outside the box of web server configuration.

Install the Transliteration module:

  Provides one-way string transliteration (romanization) and cleans file
  names during upload by replacing unwanted characters.

And install the File Field Paths module:

  In simple terms, File (Field) Paths allows you to automatically sort
  and rename your uploaded files using token based replacement patterns
  to maintain a nice clean filesystem.

  Features ...

  Retroactive updates - rename and/or move previously uploaded files
  (Use with caution)

With both enabled you can goto the Content Type's Manage Field page and edit the field with the file(s) and enable Transliteration on the file name to be retroactively assigned to all uploaded files.

This will change the space character ' ' to '_' for all uploaded files.

Then you don't need to worry about difficult server configuration issues. I've used File Field Paths to rename thousands of files successfully on production systems.


Disable reaching a node by its internal path

You can do this if speed is important in a middleware, checking if the request has no session and then block right away or in a request event subscriber after authentication checking for the path. Or a bit slower after routing if you want to include if the route matched is the canonical node route and use the node entity in your logic.

The easist but slowest is in a page preprocess hook. You can even do this in a theme. The cached page is varied by path and user permission by default and so the not found exception:

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    if (isset($variables['node'])) {
      $node = $variables['node'];
      if ($node instanceof \Drupal\node\NodeInterface) {
        if ($node->getType() == 'article') {
          $path = \Drupal::request()->getRequestUri();
          if (preg_match('#/node/\d+/*$#', $path)) {
            throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
          }
        }
      }
    }
  }
}

Because the 404 response is cached by the page cache the performance should be OK for most cases.


For Drupal 7, check out http://drupal.org/project/field_permissions.

  The Field Permissions module is a drop-in replacement for the Content
  Permissions module shipped with CCK.

So for Drupal 6, use the Content Permissions module shipped with CCK


Post method trow an Preflight not successful response

This is the right cors.config configuration:

 cors.config:
        enabled: true
        # Specify allowed headers, like 'x-allowed-header'.
        allowedHeaders: ['*']
        # Specify allowed request methods, specify ['*'] to allow all possible ones.
        allowedMethods: ['*']
        # Configure requests allowed from specific origins.
        allowedOrigins: ['*']


How can I bulk update the language for all content?

Load the nodes entities and set its langcode column

For example:

$w_node = entity_load('node', $nid);
$w_node->set('langcode', $data_langcode);
$w_node->save();

To do it in bulk, i guesing that you should create a new action to be available in the defaults bluk operations for the admin/content view


How to open a link of node in custom region?

You can create your block programmatically as explained in this post, and then in the block_view function, add the content of your node as the block's content, for example:

$imported_node = node_load($imported_nid);
$block['title'] = $imported_node->title;
$block['content'] = $imported_node->body;

You will have to tweak the values to fit your node content, structure you want to output


How to display search results within the same Panels page

Do you use Content pane with Views? If so, under Pane settings make sure Use Panel path: Yes.


Thanks to @Clive giving me an indication that is something to do with memchache I followed these steps to resolve my issue.

Disabled the memcache module.
Commented out the memchache configuation settings in the settings.php of the copy site.

This resolves the issue.


I don't have the exact answers for you, but I do have some directions to point you. Try something like this:

In template.php, in a THEMENAME_preprocess_page() function, construct a query to get the node ID of the most recently created node. Look up Drupal's Database API to see how to do this. (A more permanent solution would be to use a custom module for the query, but let's start at the theme layer to get this working.)
Do a node_load() to get the entire contents of that node, which will contain your three fields, and more.
Create variables (inside the $variables[] array) to hold the rendered content of your custom fields.
Use those new variables in page.tpl.php, or page-article.tpl.php


Make a database backup.
Make a Drupal code source backup.
I had to know which drush I use:

$ drush version
Drush Version   :  8.1.9

which isn't good for me.
I had to find out whether it is a local or a global installation

$ locate drush
/usr/local/bin/drush
$ dpkg -l | grep drush
rc  drush    5.10.0-2ubuntu1

it looks like the ubuntu package was removed before
and it wasn't installed by pear:

$ pear list

Installed packages, channel pear.php.net:
=========================================
Package          Version State
Archive_Tar      1.4.0   stable
Console_Getopt   1.4.1   stable
HTTP_Request2    2.2.1   stable
Net_URL2         2.2.0   stable
PEAR             1.10.1  stable
PEAR_Manpages    1.10.0  stable
PHP_CodeSniffer  2.5.1   stable
Structures_Graph 1.1.1   stable
XML_Util         1.3.0   stable

So, it can be only a global phar installation.

I chose the WRONG WAY of the installation in the beginning which resulted a lot of more issues (I don't list them here) and finally a drush installation which I wasn't able to update my drupal
Just for the record here is the wrong way: I decided I install drush by composer and if the global version confuses its functionality I will remove the old one from the file system manually
I ran this command from the root directory of my drupal project
$ composer require drush/drush
This installed a lot of other packages and updated my drush from 8.1.9 to 8.1.12. Everything looked good at this point.
$ drush version

Drush Version   :  8.1.12

$ drush up drupal
resulted

Unable to load class \Drush\VersionControl\Backup.

I removed the drush 8.1.12 and installed the drush 9.x version.
I wasn't able to update my drupal site, so I removed the local drush package and its dependencies.

the WORKING WAY
remove the composer version if that exists and install drush globally by phar

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# Test your install.
php drush.phar core-status

# Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH.
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

I updated my drupal from 8.3.4 to 8.3.5
$ drush up drupal
I got the package name of the drupal 8.4 by this command
$ drush dl drupal-8 --select

 [0]  :  Cancel
 [1]  :  8.4.x-dev  -  2017-Jul-22  -  Development
 [2]  :  8.3.5      -  2017-Jul-05  -  Supported, Recommended
 [3]  :  8.3.4      -  2017-Jun-21  -  Security

I chosed 0

I updated my drupal from 8.3.5 to 8.4
$ drush pm-update drupal-8.4.x-dev

Update information last refreshed: Mon, 06/26/2017 - 18:31
 Name    Installed Version  Proposed version  Message
 Drupal  8.3.5              8.4.x-dev         Specified version available

Do you really want to continue? (y/n): y

At the end I got 3 errors, but the update was successful.
Unfortunately the drupal 8.4.x-dev version didn't fix any of my issues.


I'm not sure that you need to dive into any theming. The Google js API uses an empty div and javascript to fill it. Your could create a custom module with a block hook to create your block. It would also load the necessary js to engage the Google API. This assumes that you are going to access the geographic information for the map independently - i.e. via accessing the database or whatever on your own. I think it makes most sense to use something like Openlayers if the data is stored in nodes and you want to use a View to access it.

If you need to theme the block outside of the map, you could use a straightforward theming function, also in your custom module. Creating or using a template makes most sense if somebody else who is more of a html/css person with less php/js experience is going to be doing the theming. If the theming is simple, you could just create the needed id and class tags in your module and then theme it via a css file.


I've just been encountering a similar problem. And solved it like following.

In my MYMODULE.module file:

function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'mythemename' => [
      'render element' => 'form',
      'template' => 'my-template-name',
    ],
  ];
}

In the $form:

$form['#theme'] = 'mythemename';

And finally in the my-template-name.html.twig template:

<div class="someclass">
  {{ form }}
</div>


On the view that you have the files upload, under Advanced, add a relationship of comments of the node, then add Comment:Comment as a field.


Programmatically creating a node doesn't save custom fields

If you're using Rules anyway why don't you use the Create new entity action which should take care of everything? You will need to use the Set a data value action multiple times and possibly the Save entity action too.

In answer to your question I think you need to set the language before node_object_prepare so your code would become:

$nodo = new stdClass(); // Create a new node object
$nodo->type = "capitoli"; // Or page, or whatever content type you like
$nodo->language = 'it'; // Or e.g. 'en' if locale is enabled
node_object_prepare($nodo); // Set some default values

Also you don't need the node_submit($nodo) line


How do I create a static block programmatically?

The important hooks in the Block example module are hook_block_info() and hook_block_view(). The info hook defines your block in the system and the view hook creates the output (html) for your block.

Every module, including yours, will have at least a .info file and a .module file. Drupal.org has some more documentation about .info files that you may find helpful when getting started with modules. Yours really just needs the name and core entries.

The .module file is where you'll implement your hooks. First, implement hook_block_info(), replacing 'hook' in the function name with the name of your module, e.g., my_module_block_info(). It should look something like the following.

function my_module_block_info() {
  $blocks['your_block'] = array(
    // info: The name of the block.
    'info' => t('Your Block Name'),
  );

  return $blocks;
}

Then, implement your hook_block_view() hook to define the static content.

function my_module_block_view($delta = '') {
  // The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'your_block':
      // Create your block content here
      $block['subject'] = t('Title of first block (example_configurable_text)');
      $block['content'] = 'Your block content, or the result of a function that returns the content';
      break;
  }

  return $block;
}

Once you have that in place, you can put your block in any region as you would any other block in Drupal.


zero distance in views geofield proximity problem

I just posted a new documentation page for geofield that shows how to setup a basic proximity search: http://drupal.org/node/1944648


Image field: Force at least/exactly two images per field

This question has already answer here

You can do it by using Field validation Module.

The following validators are listed:

  Regular expression
  Numeric values (optionally specify min and / or max value)
  length (optionally specify min and / or max length)
  number of words (optionally specify min and / or max words )
  Plain text (disallow tags)
  Must be empty (Anti-Spam: Hide with CSS)
  Words blacklist
  number of selections (optionally specify min and / or max selections
  )
  Unique
  Match against a field
  Match against a property
  Specific value(s)
  Require at least one of several fields
  Equal values on multiple fields
  Unique values on multiple fields
  PHP Code (powerfull but dangerous)
  URL (support internal path and external url validation)
  Email
  Pattern (Regular expression lite)
  Date range2

Hope this will help you