To extend and clarify Saud Alfadhli's answer for others (I'm not allowed to comment yet), hook_preprocess_views_view_field (hook_preprocess_views_view_fields with the "s" exists as well) works great for this. Both the view ID, display ID, and field ID can be easily inferred from this hook, and the field output can easily get overwritten (as both a string or render array). Here's a quick example replacing all occurrences of my second custom text field with a simple string:

/**
 * Implements hook_preprocess_views_view_field().
 */
function hook_preprocess_views_view_field(&$variables) {
  if ($variables['view']->id() === 'my_view_id' && $variables['field']->options['id'] === 'nothing_2') {
    $variables['output'] = 'Hi Mom!';
  }
}

Hope this helps!


How to enable Google analytics while site is in maintenance mode?

You'll have to do it manually unfortunately, the normal page building handler isn't called for the maintenance page so the analytics module never actually builds up the necessary javascript.

You can follow the instructions here to set up a custom maintenance page template, from there you'll just need to add the tracking code manually to the bottom of the site. It should start working instantly.


what security measures should be taken when creating/updating/retrieving entities with data from users' form submissions?

Designers need to worry about two things, making sure that user-supplied data can go into the database successfully, and also that data pulled from the database can be written to the page successfully.

When adding data to the database, Drupal will use prepared statements to ensure the SQL injection does not occur. What this means is, Drupal will tell the database, "Expect to see an INSERT command that looks like {statement}." and then sends all the data. If the resulting statements does not match, there will be an error.

Drupal Fields are defined such that the system knows how the data in that field should be displayed. The database schema guarantees that only a certain data format is available. For example, if the field is a number, we know we won't get a string because the database is designed to only record numbers. Drupal can just worry about formatting it properly. Same if it's text, it will make sure that it is not displaying a URL by passing the text through check_plain() after retrieving the data from the database.

In your case, you are going to be inserting this user-supplied data into the database. The Drupal Field API should be ensuring that the data is of the correct type for the database, and that it is not too long, or improperly formatted before inserting the record. It will insert it using the prepared statement to prevent SQL injection. So, you should be fine.

Make sure you read the CiviCRM secure coding guide:
https://docs.civicrm.org/dev/en/latest/security/


Adding extra fields to Site Contact Form

Expecting forms fields to be configured like content types is an over-generalization. Content types are for content (text, image, etc.) of the website, and more specifically, in Drupal, for nodes (the main piece of content in Drupal). Using the Field and Field UI module, one can easily adds fields to content type using a Web UI. Except for some specific cases, a form is not part of the content of a website but rather a way for users to add and edit information, sometimes content and sometimes not.

To customize (i.e. alter) a form in Drupal, the usual way is to create a custom module that implements the hook_form_FORM_ID_alter hook. This way, you can add form elements to existing forms provided by other modules. To use the information for fields added to the contact form this way, you will also need to alter the sent mail using an implementation of hook_mail_alter(). The following guide walks you through both steps in Drupal 7. (Note also this comment)

A non-code solution is to use the Webform module that provides a form content type and let you add forms as content to your website. These forms are configurable through a Web UI. Various processing steps can be configured for the information submitted through these forms. One of them is email sending. Using it for a custom contact form is a common use case. Webform comes with its own concepts and extension points. While it may prove to be a easier and faster solution for a one time simple forms, it may also reveal to be over-sized and complex to customize once a certain features threshold has been reached. The cost to add extra-features to a webform can then outperform the gain of avoiding writing a custom module in the first place.


Why are there "updates" to dev versions of modules that do not include any changes to the code?

Strange, I selected some modules at random and I see dev versions consistently packed 2013-Oct-01. I can't find any one with another date now.

Examples I've tested:

https://drupal.org/project/views_data_export
https://drupal.org/project/views
https://drupal.org/project/prepopulate
https://drupal.org/project/imagecache_actions
https://drupal.org/project/file_entity_revisions
https://drupal.org/project/file_download_count
https://drupal.org/project/scald_file

and many more.

Edit: Some of them, closer to the beginning of alphabet, was packaged one day earlier:

https://drupal.org/project/elysia_cron
https://drupal.org/project/blocktheme

but operation big as this surely needed to take considerable time and it still looks like one long rebuild queue.

With so many unrelated projects repackaged at the same day, and without any correlation to their GIT log, it must be something on the Drupal.org side that triggered mass repackaging.

It's simply impossible that all maintainers decided to rebuild at the same day, plus as far as I remember only way to trigger for them rebuild is via GIT anyway.

GOT IT

https://drupal.org/node/2101175#comment-7919049

  -dev releases are currently being rebuilt ... working alphabetically, and there are a lot of packages, so it will take a while. :)

So it was a manual rebuild triggered to fix an issue with infrastructure, not something planned as regular action.


How to remove all nodes authored by users when their role changes?

You could use the Rules API to define a custom action that gets triggered whenever your users upgrade their accounts. In your custom action you could have a SQL query that searches all that users' content and deletes it.

For how to invoke a Rule programatically see this other DA answer: programmatically-execute-an-action-set-rules-module


Points-based tasks: pledging and tracking

There's a way to use Rules, Webform and Webform Rules together, by adding a number field with initial value 0 in your user fields. Every time user completes a task, validating a form submission, a value will be added to your field. That's the points field, which would be, in this case, unique. There is no sum in this case, but the field value will be automatically calculated by Rules.

Number field, your points field, should be available in your display, not in your user register form, with the right permissions.

That's what I'm thinking as a solution right now, if tasks are webforms. Not sure about awards or how to keep track of each completed task.

I hope that would get you started.


Call AJAX function in the beginning not just after change

Rather than calling the AJAX function at the beginning I simply built the form as it should be in buildForm. Like so

    for ($i = 0; $i < $this->configuration['test']; $i += 1) {
        $columns[$i] = [
            '#type'  => 'textfield',
            '#title' => t('Column Title'),
            '#value' => $this->configuration['test'],
        ];
    }
    $form['column_wrapper'] = [
        '#type'        => 'container',
        '#attributes'  => ['id'  => 'column_wrapper'],
        'columnTitles' => $columns,

    ];


Views hook query alter, change the DatabaseCondition Object

The conditions may be altered by getting them by reference:

function custom_views_query_alter(&$view, &$query) {
   $conditions = &$query->conditions();
   foreach($conditions as $idx => $condition) {
     if ($condition['field'] == 'node.type') {
       $conditions[$idx]['value'] = array("Some other type");
     }
   }
}

Don't forget to modify the object/arrays by reference with the & character.


An entity reference field is implemented from the \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem class. If you look at the code for EntityReferenceItem::preSave(), you will notice it is setting its target_id property to $this->entity->id().

public function preSave() {
  if ($this->hasNewEntity()) {
    // Save the entity if it has not already been saved by some other code.
    if ($this->entity->isNew()) {
      $this->entity->save();
    }
    // Make sure the parent knows we are updating this property so it can
    // react properly.
    $this->target_id = $this->entity->id();
  }
  if (!$this->isEmpty() && $this->target_id === NULL) {
    $this->target_id = $this->entity->id();
  }
}

I take your code should be changed to the following one.

$entity_ids = $query
    ->condition('type', 'user')
    ->condition('status', 1)
    ->condition('field_product_document', $node->id());

The change makes also sense: A node title cannot be used to uniquely identify a node, since there could be more nodes with the same title; the node ID uniquely identify a node on a Drupal site.


Couldn't create range_filter for search index(commerce price)

There is an opened issue for the module contextual_range_filter with search_api and the patch patch-contextual-range-filter-search-api.txt will make the range filter work with views based on search api though you could use it for a resource for services.

Another way of achieving that scenario is to use search_api_ranges but it won't be controlled by services module.

Hope that helps with your case.


How to enable users to add content only from some pages (and only once) in  Drupal 7

Content Profile module usually bounds the users to create exactly one node of some content type that has been marked as Content Profile.

May this help you in this regard.


Use this code, your missing $return $form in the second form

    /**
     * Implements hook_menu().
     */
    function listings_menu() {
        $items = array();
        $items['site/listings'] = array(
            'title' => 'State Listings',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('listings_form'),
            'access arguments' => array('access content'),
        );

        $items['site/listings/%/%'] = array(
            'title' => 'Business Listings',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('listings_mini_form'),
            'access arguments' => array('access content')
        );

        return $items;
    }

    /*
     *  FIRST FORM
     */

    function listings_form($form, &$form_state) {

        $form['zipcode'] = array(
            '#title' => t('Zipcode'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

        $form['form-wrapper']['form-wrapper-zip']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit')
        );

        return $form;
    }

    /*
     *  FIRST FORM SUBMIT FUNCTION
     */

    function listings_form_submit($form, &$form_state) {

        $zipcode = $form_state['values']['zipcode'];

        $form_state['redirect'] = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
    }

    /*
     *  2ND FORM ON PAGE IM CALLING
     */

    function listings_mini_form($form, &$form_state) {

        $form['mini-form'] = array(
            '#title' => t('Enter your Zip Code for more listings.'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit')
        );

        if (isset($form_state['values'])) {
            $form['page_output'] = array(
                '#markup' => listings_list_view($form, $form_state)
            );
        }
        return $form;
    }

    /*
     *  2ND FORM SUBMIT FUNCTION
     */

    function listings_mini_form_submit($form, &$form_state) {
        $zipcode = $form_state['values']['zipcode'];
        $form_state['redirect'] = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
    }

    /*
     *  FUNCTION WITH LISTINGS INSIDE OF IT
     */

    function listings_list_view($form, &$form_state) {
        global $base_url;
        $zipcode = isset($form_state['values']['zipcode']);
        dpr($zipcode);
        #blah blah blah
    }

I got output using this code

    /*
     *  FIRST FORM
     */

    function listings_form($form, &$form_state) {
        $form['zipcode'] = array(
            '#title' => t('Zipcode'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

        $form['form-wrapper']['form-wrapper-zip']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit')
        );

        return $form;
    }

    /*
     *  FIRST FORM SUBMIT FUNCTION
     */

    function listings_form_submit($form, &$form_state) {
        $zipcode = $form_state['values']['zipcode'];
        $form_state['redirect'] = 'site/listings/' . $zipcode . '/' . $zipcode;
    }

    /*
     *  2ND FORM ON PAGE IM CALLING
     */

    function listings_mini_form($form, &$form_state) {
        $form = array();
        $form['mini-form'] = array(
            '#title' => t('Enter your Zip Code for more listings.'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit')
        );

        if (isset($form_state['values'])) {
            $form['page_output'] = array(
                '#markup' => listings_list_view($form, $form_state)
            );
        }
        return $form;
    }

    /*
     *  2ND FORM SUBMIT FUNCTION
     */

    function listings_mini_form_submit($form, &$form_state) {
        $zipcode = $form_state['values']['zipcode'];
        $form_state['redirect'] = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
    }

    /*
     *  FUNCTION WITH LISTINGS INSIDE OF IT
     */

    function listings_list_view($form, &$form_state) {
        $zipcode = isset($form_state['values']['zipcode']);
    }


Views Contextual Filters: Using node's URL alias as a conditional filter

Maybe the View Url Path Arguments module. I am seeing it recommended in this thread, but I'm really not sure if that's your issue or not.

Alternatively, you can implement hook_views_pre_view and alter the argument passed to the view based on the value in the url, i.e. do the conversion from alias to id manually. If you have an issue when your alias contains a /, an alternative may be to use a query string for the contextual argument.


Send email to specific users using webforms

Why not activate individual user contact forms, add a User: Link to contact page field to your view, and put your 'Click to connect' in the Text to display?

This will allow users to control whether or not they wish to receive such emails. They will be able to opt out in their account page and the link will not appear in the view.


How to debug #states mecanism - trying to get #states to work with inner fieldsets & webform

Can you add the full code for both form items?

If the element needs to be collapsed at start-up you need to add '#collapsed' => TRUE,

It also looks like there's an error in you're selector as pointed out in comments


Can I turn a regular content type into a Commerce product display?

All you need is a product reference on a node for that node to be a "Display Node." A simple solution would be to just add that and any other fields you think necessary to the "selling" part of the node's function. You might need an alternative View Mode for the content type if there are items you need displayed or not dependent on circumstances.


Trying to alter SKU field on ubercart product that is also a course

The ID for a node form is built up in node_forms():

$forms[$type . '_node_form']['callback'] = 'node_form';

Where $type is the name of each type retrieved from node_type_get_types().

So generally speaking, if the content type is product, the form ID will be product_node_form, if the type is course the form ID will be course_node_form, and so on.


If you check core.services.yml you can see the service which sends mail (plugin.manager.mail).  It looks for  overrides for default mail plugin starting from message_id to module name. You can create simple new mail plugin which sends HTML mail and set this in configuration "system.mail".

 drush cset system.mail interface.contact your_mail_plugin  // this will change mail plugin for contact module

Creating a mail plugin is easy and you can find example here Drupal\Core\Mail\Plugin\Mail

MailSystem  module does this and it supports advanced options https://www.drupal.org/project/mailsystem


Add new user via Commerce or Add User account

You can add all necessary profile fields to user register form, and disallow checkout to anonymous users. This way every time new user proceeds to checkout' they are redirected to register form where they fill in the info and then proceed with checkout as usual.

A good helper module for this is Commerce Checkout Redirect

  This module redirects anonymous users to a page where they can login or create a new account when they try to checkout.


@Oswald: thanks for pointing in the right direction. This snippet does exactly what I need:

$front_url = variable_get('site_frontpage', 'node');
$front_url = trim($front_url, '/');
$front = explode('/', $front_url);
if( $front[0]=='node' && ctype_digit($front[1]) ) {
  $front_nid = $front[1];
}
echo $front_nid;


Is it better to hard code everything or use the ui?

If you use code you can:

Version control the field settings.
Lock the field, so it can't be deleted or altered in the UI.

It's always a good idea to keep as much as possible in code, for when you need to roll out changes etc. This is why i prefer the above method, even though it is more time consuming during development. Depending on your use case, you may save a lot of time doing this however.


Why is the page content always rendered after blocks displayed on the same page?

You need to adjust the display order of the blocks through configuration. Navigate to Manage >> Structure >> Block layout (relative path: /admin/structure/block), click the handle icon next to the "Main page content" block and use it to drag the block to the top of the "Content" region.


Create a new region in your theme's .info file.

regions[RegionName] = Region Name

Insert following code in your
views-view-unformatted--viewsname--attachment.tpl.php template file
to insert region between views rows:

print render(block_get_blocks_by_region('RegionName'));

And then put your block into this region.

For more reference go to this.


Filter view results by day of the week instead of the date - Date Module

I think you have to use the Views Day of Week module to filter the result by day of week. Here is a quote from it's project page:

... Views Day of Week provides a simple filter plugin for Views 3 to enable filtering content that should be visible based on the current day of the week.
Example: With this module you can select that some content should be visible only on Mondays, some on Tuesdays and Thursdays and some only on Fridays.


How do I prevent an entity to be saved on update depending on conditions?

Could you not instead implement a hook_form_alter and do your condition checks, and hide/remove the submit button if it is the same user trying to review?

You could set the same message at the top of the form and not have to do any redirects.


How to enable ckeditor in the emails templates at admin/config/people/accounts?

Create custom module for Drupal 7;
Add below code to your module;
replace all MODULENAME in code to your module name;
clear cache;
refresh /admin/config/people/accounts page

For all textarea fields there's text selector appear - you should select format, where ckeditor attached:

/**
 * Implements hook_form_FORM_ID_alter() for user settings page.
 */
function MODULENAME_form_user_admin_settings_alter(&$form, &$form_state, $form_id) {
  _MODULENAME_form_user_admin_settings_elements($form);
}

/**
 * Scan through elements.
 */
function _MODULENAME_form_user_admin_settings_elements(&$elements) {
  // Recurse through all children.
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      if (isset($elements[$key]['#type']) && ($elements[$key]['#type'] == 'textarea')) {
        $elements[$key]['#type'] = 'text_format';
      }
      else {
        _MODULENAME_form_user_admin_settings_elements($elements[$key]);
      }
    }
  }
}

be warn, that placeholders signs [bla-bla:something] can be replaced by unicode symbols (&XXXX;), check before to show your client.
if you want add text format only for certain textarea use Devel module dpm function for seeking that element and setting next code $elements[CERTAIN_ARRAY_PATH2ELEMENT]['#type'] = 'text_format'; without scanning through all elements.


How can I install a specific core version?

Now Drupal recommended project supports version as command line option. If you want to install version 8.8.5 via Composer then command will like as shown below.
composer create-project drupal/recommended-project:8.8.5 <INSTALL_DIR>


use different layouts for different pages

Custom content types are should be themed at the node level.  Add a node template file to the theme/templates directory according to your content type.  For example, I have a "Trip" content type.  This gets themed with a node--trip.tpl.php file.

You don't need to do anything special to redirect.


Go to your nodes which you want to disable from viewing.

Go to node edit and find 'Published options' and uncheck published option.

So now you want to display them at view's page. So go to your View Filter criteria and select Published 'No'

That's it. Now you can see the unpublished nodes at view's output but not at node output.

There is another way you can do it.

If those nodes (which you want to disable at node output) are all belongs to same content type, you can manage them under content type display settings. You can manage view modes there.


How can I display information about a referenced node within a content creation page?

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

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


Error: Argument 2 passed to drupal_array_get_nested_value() must be of the type array, string given

The error:

  Argument 2 passed to drupal_array_get_nested_value() must be an array, string or null given

means there is a problem with the structure of your form you're trying to submit. So string/NULL were given instead of array for the second parameter.

The function:

&drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL)

retrieves a value from a nested array with variable depth, for example:

$value = drupal_array_get_nested_value($form, $parents);

Here are the example calls from Drupal core (see the 2nd argument):

./common.inc:  drupal_array_get_nested_value($array, $parents, $key_exists);
./form.inc:      $input = drupal_array_get_nested_value($form_state['input'], $element['#parents'], $input_exists);
./form.inc:  $source = drupal_array_get_nested_value($form_state['complete form'], $element['#machine_name']['source'], $key_exists);

If you don't know which field is causing it, the easiest way to find out is by doing this simple hack (which should be reverted after that of course):

function &drupal_array_get_nested_value(array &$array, $parents, &$key_exists = NULL) {
  if (!is_array($parents)) { var_dump($parents, debug_backtrace()); exit; }

Which would display value of $parents which should be an array and the backtrace.

Usually this could happen during the validation and it can caused by invalid #parents or #limit_validation_errors structure of form array.

If there is no any custom coding involved, then it's a bug of the contrib module which cause that (e.g. Conditional Fields, Email Field, Entity Translation, etc.), so it should be reported against the right module.

In my specific case, I've to fix #limit_validation_errors by wrapping it into array() where it contained list of $group['children']:

  $form['actions']['continue'] = array(
    '#type' => 'submit',
    '#value' => t('Continue'),
    '#limit_validation_errors' => array($validate_fields),
    '#submit' => array('foo_form_submit'),
    '#validate' => array('foo_form_validate'),
  );


Rules - New events inside code not shown in interface

The problem is the function name. Since the module name is nodeaccess (and not node_access), function name should be nodeaccess_rules_event_info

However, it is not recommended to add anything to a contributed module (unless you are going to contribute back to the module's issue queue).

If this rule is specific your project, you can add it in your own custom module.


How to show the body field in a custom template?

Your code should be:

    <?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
//$original_image = file_create_url($node->field_portfolio_images['und'][0]['uri']);
$lightboxrel = 'portfolio_' . $nid;
$portfolio_images = field_get_items('node', $node, 'field_image');
$first_image = '';
if ($portfolio_images) {
  foreach ($portfolio_images as $k => $portfolio_image) {
    if ($k == 0) {
      $first_image = file_create_url($portfolio_image['uri']);
    } else {
      $image_path = file_create_url($portfolio_image['uri']);
      print '&nbsp;';
    }
  }
}
?>
<div id="node-<?php print $node->nid; ?>" class="portfolio-text <?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php print render($title_suffix); ?>
<div class="ImageWrapper content"<?php print $content_attributes; ?>>

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

                   <a href="<?php print $first_image;?>" rel="prettyPhoto[<?php print $lightboxrel;?>]" data-toggle="tooltip" data-original-title="<?php print t('View Image');?>" data-placement="bottom" class="zoom dtooltip">

<?php print $title; ?>

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

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


Commerce customer profile uses an address field, whose columns are defined by the addressfield module.

It's not possible to alter those columns without writing code, so you're out of luck.

Also, I'd imagine that removing the state field would incur quite a bit of extra work, as existing validation/submission functionality would need to be overridden.

The easiest thing you can do is add the telephone number field to the profile type entity itself, and use a form alter or CSS to remove/hide the state field.


Required field set via hook_form_alter not fully working in Commerce Checkout form

Using required along with #states will add the required indicator to the element, But there will be no client or server side validation involved. So to make the field as required you would have to add the custom validation to the form and there you can validate the field something like below:

/**
 * Implements hook_form_alter().
 */
function MODULE-NAME_form_alter(&$form, &$form_state, $form_id) {
  // Check if the form is commerce checkout form.
  if ($form_id == 'commerce_checkout_form_checkout') {
    // Add the custom validation function to the form.
    $form['buttons']['continue']['#validate'][] = 'mymodule_custom_validate_required_field';
  }
}

/**
 * Callback handling the custom validation.
 */
function mymodule_custom_validate_required_field($form, &$form_state) {
  // Check if the field you want to validate exists in the form.
  // replace 'field_dispongo_de_' with the name of field you want to validate.
  if ((isset($form_state['values']['field_dispongo_de_'])) && (empty($form_state['values']['field_dispongo_de_']))) {
    form_set_error('field_dispongo_de_', 'Field cannot be left blank');
  }
}

Alternate way:

Since its a commerce checkout form so we can add the custom validation using hook_commerce_checkout_pane_info and commerce_checkout_form_validate as discussed here: Adding validation to commerce pane form


token is a contributed module and not part of Drupal 8 or webform installation.  You have to install and enable before you can use it.

composer require drupal/token
drush en token

NOTE: Webform is not aware of token directly and does not complain because it thinks are you just inputting text


Think you are looking for the form alter hook here: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.2.x


how to use a submit handler which is in an .inc file

You want form_load_include() instead:

Ensures an include file is loaded whenever the form is processed.
...
Use this function instead of module_load_include() from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using module_load_include() directly, form_load_include() makes sure the include file is correctly loaded also if the form is cached.


What is error: "Base table or view not found: 1146"

Found the fix!!! (Yes, i am user96758)

After 3 hours of investigation, internet and uncle Google wasn't helpfull at all.

The problem was that field was created via Drupal UI in Content Type -> Manage fields.
And it was deleted programatically by using UPDATE (code example below), not by using UI.

function hook_update_N(&$sandbox){
    $update_manager = Drupal::service('entity.definition_update_manager');
    $definition = $update_manager->getFieldStorageDefinition('field_name', 'entity_id');
    $update_manager->uninstallFieldStorageDefinition($definition);
    return t('Entity: field was uninstalled');
}

I have installed module named "Devel", which is pretty good damn module and every developer should have it.

I was finding anything that contains name of my problematic field.

Thanks to Devel module i was able to find config of this field.
Usually you can see all configs at url (your_site)/devel/config

Well, i was desperate, so the last chance was to delete the config i found.
Usually the fields are named: field.field.(entity).(entity).(field_name)

I removed the config with this code below

Drupal::configFactory()
    ->getEditable('field.field.(entity).(entity).(field_name)')
    ->delete();

Then i CLEARED CACHE and IT WORKS AGAIN!


How to redefine default theme_image() function?

If your purpose is overriding theme_image(), and make Drupal (or third-party modules) use your theme function when calling theme('image'), then you need to implement hook_theme_registry_alter().

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['image'])) {
    $theme_registry['image']['function'] = 'theme_cus_image';
  }
}

Implementing that code, when a module uses code similar to the following one, it will call your function, and not theme_image().

$form['enable'] = array(
  '#markup' => theme('image', array('path' => 'misc/watchdog-error.png', 'alt' => $status_short, 'title' => $status_short)),
);

If you need to override theme_image(), and use your code when the image class is a specific one, and theme_image() in the other cases, then you should use code similar to the following one.

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['image'])) {
    $theme_registry['image']['function'] = 'theme_cus_image';
  }
}

function theme_cus_image($variables) {
  if (!empty($variables['attributes']['class']) && $variables['attributes']['class'] == 'the class you are looking for') {
    // Add your code.
  }
  else {
    return theme_image($variables);
  }
}

The problem with that code is that it is assuming no other module overridden the same theme function. If another module with a lower weight (or for which its hook_theme_registry_alter() is executed first) overrides theme_image(), the new theme function would not be called from the code I shown, as it explicitly calls theme_image().
It is also not possible to call the original theme function with theme('image') as that would cause an infinite loop: theme('image') would call theme_cus_image(), which would call theme('image'), which would call theme_cus_image(), which would call theme('image'), which would call […].

Keep in mind that, with Drupal 7, preprocess functions are invoked also for theme functions that don't use template files. If you want to replace theme_image() just to alter one of the variables it gets, then you can use code similar to the following one, which unsets the width, and the weight of the image.

function mymodule_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    unset($variables[$key]);
    unset($variables['attributes'][$key];
  }
}

Similarly, if you would want to alter the class assigned to the image, you could use the following code.

function mymodule_preprocess_image(&$variables) {
  if (!empty($variables['attributes']['class']) && $variables['attributes']['class'] == 'the class you want to alter') {
    $variables['attributes']['class'] = 'your class';
  }
}

If your purpose is defining a new theme function that is used from your module, then you simply need to implement hook_theme().

function mymodule_theme() {
  return array(
    'cus_image' => array(
      'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
    ),
  );
}

In this case, theme_cus_image() will be used from code that calls theme('cus_image'). The code that calls theme('image') will still be using theme_image().


Fatal error: Call to undefined function media_filter

Prior to newer version of Media, media_wysiwyg_filter should be used instead which will perform media markup filter. This can be found in modules/media_wysiwyg/includes/media_wysiwyg.filter.inc.

The code is:

/**
 * Filter callback for media markup filter.
 */
function media_wysiwyg_filter($text) {
  $text = preg_replace_callback(MEDIA_WYSIWYG_TOKEN_REGEX, 'media_wysiwyg_token_to_markup', $text);
  return $text;
}


view of unformatted list invalidating cache issues

The cache tag node_list only works for database changes in the node table, but this is not happening when the user selects a filter value.

This is from the point of the View a cache context. So if you don't find a way to configure the View to handle this correctly, you could assign a custom cache context for the filter value.

The whole picture, which the View can't know because you provide only the filter value to it, is a mix of tag and context. You would need a cache tag for the private tempstore and a context for the current user to get the caching right:

function modulename_views_pre_view($view, $display_id, array &$args) {
  ...
  $uid = \Drupal::currentUser()->id();
  $view->element['#cache']['tags'][] = 'users_in_class.' . $uid;
  $view->element['#cache']['contexts'][] = 'user';
}

and then invalidate the tag when changing the private tempstore of a user $uid:

Cache::invalidateTags(['users_in_class.' . $uid']);


Login menu which I added in main menu still displaying even after logged-in

You need two have two menu items, login and logout.

For the login link the path is: user/login
and for logout the path is: user/logout

Make sure you don't enter a absolute URL to the links, just user/login and user/logout.

I have just tested this by adding two menu items to the primary menu.


In your settings.php change/add this line

ini_set('session.cookie_lifetime', desired time in seconds);

it will increase your timeout length in desired way.


The real problem with such maps is that, the PDF gets generated before the map appears.
I'm assuming your map provider is JavaScript based - that means the map appears on the user browser and your server just sets the javascript parameters.

I had to do a similar thing a long time ago, and the only solution that seemed easier was to use Google Maps with static maps. You can embed an image with parameters such as pointer options and geocodes and the maps server will return a static image. Worked in dompdf.


One solution would be to create two roles, one for A and one for B - then you can restrict access to different profiles in permissions under admin/people/permissions .

You could use Rules to assign the appropriate role based on selections during registration, and use the 'After Saving a new user account' trigger.


Taking node map from /map/node and using it on home page

Just create an appropriate view, give that view some path that you like, and set that path as your homepage. To actually create such view with the kind of data your question is about,  have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.


update user data without a form from a module

$edit = array(
    'basic_webmail_username' => $full_username,
    'basic_webmail_password' => $password,
  );

user_save($user, $edit);

echo('lol that was easier than i thought');

user_save();


What's better to do when we create a new site project?

It depends on your site and the needs of your client, but it is probably best to start with an easy base theme and then start theming on top of that.

Some good basic base themes are:
Omega - Best used for responsive HTML5 designs
Zen - Good basic starter theme
960gs - Good if you need to use a grid format.

Also, you might want to grab some other themes for administration.

Recommended administration themes:
Rubik - Clean administrative interface
Admin - Adds a toolbar at the top of the site, which makes Drupal easier to manage


How to add replicate fields when adding content?

You could use Field Collection to set up a field that contains both a category and a date as one unit.

Then all you would need to do is set the field collection to allow multiple values.


How do I prepopulate the value of a taxonomy term reference field on the node creation form?

Try the following code.

function MYMODULE_form_MYFORM_node_form_alter(&$form, &$form_state, $form_id) {
  // Check if the node has a node ID. If not, then populate the fields with the default data.
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))) {
    global $user;
    $user_fields = user_load($user->uid);
    // Set age.
    if (isset($user_fields->field_acc_age['und'][0]['tid'])) {
      $form['field_ad_age']['und'][0]['value']['#default_value'] = $user_fields->field_acc_age['und'][0]['tid'];
    }
  }
}


If I delete openenterprise module from drupal module folder site is collapse

You will need to rebuild the registry. The simplest solution is to use Drush and Registry Rebuild. There's also instructions on that page in case you can't use Drush or the command line.


For your contextual filter use Provide default value, User ID From URL. (this automatically extracts the uid from the url (page) and the uid does not need to be in the url).


How can I post webform block values to another form?

You should be able to use one of the webform hooks to pass $_GET values via redirect.

function YOURMODULE_webform_submission_insert($node, $submission) {
  if ($node->nid == XXX){
    // Grab the values we need and create our get url parameter string.
    $queryString = 'f1=' . $submission['value']['myfield'] . '&f2=' . $submission['value']['myfield2'] . '&f3=' . $submission['value']['myfield2'];
    drupal_goto('PATH/TO/FORM', $queryString);
  }
}

Or you can use a hook_form_alter for that form, add a new submit callback, and in the new function set the form's #redirect with the same syntax.

$queryString = $form_state['value']['myfield'] . '&f2=' . $form_state['value']['myfield2'] . '&f3=' . $form_state['value']['myfield2'];
$form['#redirect'] = array('PATH/TO/FORM', $queryString);

Then in your custom form, check for the $_GET values, and set them as the defaults to the appropriate fields, if they exist.


How do I alter the order used to load JavaScript files?

I'd set it up like this:

highcharts:
  css:
    theme:
      highcharts/css/highcharts.css: {}
  js:
    highcharts/highcharts.js: {weight: -400}
    highcharts/modules/exporting.js: {weight: -29}
    highcharts/modules/data.js: {weight: -28}
    highcharts/modules/drilldown.js: {weight: -27}
  dependencies:
    - core/drupal
    - core/jquery

charts:
  js:
    js/hc.js: {}
  dependencies:
  - mymodule/highcharts

Then add the library mymodule/charts.


How to set node creation limit by user type in Drupal

Another new module for Drupal 8: https://www.drupal.org/project/entity_limit

Some details about it, from its project page:

  Entity Limit allows administrators to restrict the creation of the number of entities that users may create. Basically, this module provides options to define a creation limit based on user and role.


display custom order fields in a checkout pane of drupal commerce

Try Commerce Fieldgroup Panes module.

  This enables an easy way to collect information in the checkout
  process... The collected information is auto added to the order... You
  can watch a demo usage in Commerce module Tuesday videocast:
  http://www.commerceguys.com/resources/articles/257


Here is some boilerplate Apache rules I came up with for this question based off of the rules found in the advagg readme. The inverted files match is untested but based off this post: https://stackoverflow.com/questions/12926604/inverted-filesmatch; got what needed to be excluded by looking at core's .htaccess

<FilesMatch "(?<!\.php)$">
  # No mod_headers
  <IfModule !mod_headers.c>
    # No mod_expires
    <IfModule !mod_expires.c>
      # Use ETags.
      FileETag MTime Size
    </IfModule>
  </IfModule>

  # Use Expires Directive.
  <IfModule mod_expires.c>
    # Do not use ETags.
    FileETag None
    # Enable expirations.
    ExpiresActive On
    # Cache all files for 2 weeks after access (A).
    ExpiresDefault A1209600
  </IfModule>

  <IfModule mod_headers.c>
    # Do not use etags for cache validation.
    Header unset ETag
    <IfModule !mod_expires.c>
      # Set a Cache-Control header to 2 weeks.
      Header set Cache-Control "max-age=1209600, no-transform, public"
    </IfModule>
    <IfModule mod_expires.c>
      Header append Cache-Control "no-transform, public"
    </IfModule>
  </IfModule>
</FilesMatch>

In your case the best you can do is to use ETags.

Note: If you happen to be serving all you static file assets from a CDN then you could enable far-future headers in the CDN module. Doing it this way will route almost all static file traffic through PHP (on a origin request) so it can be extremely damaging to the sites performance if you are not using a CDN.


Disabling block is pointless. You need to truly disable registration itself. Go to Administration » Configuration » People and under Who can register accounts? select Administrators only. If that's not enough, make sure you have all security updates installed.

Note: exact path to this setting may be a bit different in Drupal 6 or 8, but you should be able to find it easily enough.


Change some charachter in All field before saving node

You're probably looking for hook_entity_presave():

  Act on an entity before it is about to be created or updated.

It's equivalent to hook_node_presave(), but as the name suggests is run for all entity types.

From there you can use the Field Info API functions to get a list of fields that should be attached to that entity, then loop through them and do the character replacement.


Which entity to check in Rules to disallow taking a Quiz after passing it?

Even though the Quiz 7.x-5.x release comes with lots of new Rules capabilities, I've not found any entity to check if a user already passed some quiz. However, using the Flag module you can implement an appropriate flag, and then just check if the quiz node (an entity ...) was flagged by the current user. Read on for how to do so ...

Step 1 - Create a flag for tracking Passed Quizes

Use the Flag module to create a flag labeled (e.g) Passed Quizes. Here is an export of the flag I used for this (you should be able to import it in your own site also):

$flags = array();
// Exported flag: "Passed Quizes".
$flags['passed_quizes'] = array (
  'entity_type' => 'node',
  'title' => 'Passed Quizes',
  'global' => '0',
  'types' =>
  array (
    0 => 'quiz',
  ),
  'flag_short' => 'Flag this item',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Unflag this item',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'answers_full_node' => 0,
    'print' => 0,
    'question' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;

This flag will be used in the custom rule, detailed in the next step.

Step 2 - Flag a Quiz node after passing the quiz

Create a custom rule to flag the quiz node (using the flag from Step 1) after a user passed the quiz and which looks like so (in Rules export format):

{ "rules_flag_a_quiz_when_passed_the_very_first_time" : {
    "LABEL" : "Flag a quiz when passed the very first time",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "flag", "entity" ],
    "ON" : { "quiz_result_update" : [], "quiz_result_insert" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } },
      { "NOT data_is" : {
          "data" : [ "quiz-result:score" ],
          "op" : "\u003C",
          "value" : [ "quiz-result:nid:quiz:pass-rate" ]
        }
      },
      { "NOT flag_flagged_node" : {
          "flag" : "passed_quizes",
          "node" : [ "quiz-result:nid" ],
          "flagging_user" : [ "site:current-user" ]
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Congratulations, this is the FIRST time you passed this quiz (with a score of [quiz-result:score] %, whereas the pass rate is [quiz-result:nid:quiz:pass-rate] %)." } },
      { "flag_flagnode" : {
          "flag" : "passed_quizes",
          "node" : [ "quiz-result:nid" ],
          "flagging_user" : [ "site:current-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Step 3 - Create a rule to disallow taking a passed quiz again

Here is a rule which illustrates how to resolve the challenge in your question:

{ "rules_disallow_taking_a_passed_quiz_again" : {
    "LABEL" : "Disallow taking a passed quiz again",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag", "entity" ],
    "ON" : { "quiz_result_insert" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "flag_flagged_node" : {
          "flag" : "passed_quizes",
          "node" : [ "quiz-result:nid" ],
          "flagging_user" : [ "site:current-user" ]
        }
      }
    ],
    "DO" : [
      { "entity_delete" : { "data" : [ "quiz-result" ] } },
      { "drupal_message" : {
          "message" : "You already took (and passed) this quiz. Your new attempt to take it again has been disregarded and you have been redirected to your results summary ...",
          "type" : "warning"
        }
      },
      { "redirect" : { "url" : "[quiz-result:nid:url]\/quiz-results" } }
    ]
  }
}

Here are the critical pieces of this rule to make Rules-magic happen:

The Rules Event "After saving a new Quiz result" is what gets triggered right after a user attempts to start taking a quiz (a first time, or another time), so even before the first question of a quiz is shown.
The first Rules Condition, which is "the" way to get access to all sorts of data about the quiz node itself (starting from "a" quiz result).
The last Rules Condition, which verifies if the quiz node (to which this quiz result relates) is already flagged (by the flag from Step 1), which indicates this user already passed this quiz.

If all Rules Conditions are satisfied, then these Rules Actions will be executed:

Delete the newly created "quiz result" entity (this is needed, otherwise if the user would try another time to take the quiz, it would be considered as an attempt to resume taking the quiz, starting from the very first question, and the used Rules Event would NOT (repeat: NOT) be triggered ...).
Show an appropriate message.
Perform a redirect (to show the result summary of the quiz for the current user), to relative path node/nid/quiz-results (using nid as the node id of the quiz).

Use the Rules UI to import the above 2 rules in your own site, after you completed Step 1.

Showtime

Here is a sample of a warning message I received after passing a quiz, and trying to take the quiz again:

  You already took (and passed) this quiz. Your new attempt to take it again has been disregarded and you have been redirected to your results summary ...


User Registration to provide password on registration pg administrator approval and verification email

With the settings you are currently using, the user creating the account should receive an e-mail. On the admin/config/people/accounts page, near the bottom, look for the vertical tab labelled "Welcome (awaiting approval)". This is the e-mail the user should receive while waiting for the account to receive administrator approval. Check the Recent log messages page (admin/reports/dblog) to see if the e-mail is being sent by Drupal. If it is, check the spam filter on the e-mail account receiving the e-mail.

You will need to set up a trigger so that administrators receive e-mails when new accounts are created. I believe that the superuser account (the user created when installing Drupal) should automatically receive e-mails about new accounts. To notify additional e-mail addresses when accounts are created, see the directions listed at Administrator notification on user registration. You'll need to enable the Trigger module if it's not already enabled. If you want to e-mail all users having a certain role when an account is created (for example, e-mail all administrators), check out the Rules module.

I would also look into the LoginToboggan module. This module also allows the user to enter their password on account creation, but has several other great options. It allows you to set an additional role applied to users when they first create the account but before they verify the account. With this role, you can allow users to create an account and log in immediately, but not perform actions until they verify the account. The LoginToboggan module also allows users to log in using their e-mail address, and display two e-mail address fields on the registration page. I would recommend looking into this module as a replacement for the "User registration password" module you're currently using.


Check, anywhere during a session, if a logged in user has previously logged in

A cookie would work. Another way is to add a field to the user entity that you can check that field first to see if it's empty, and then modify it with a Rule, triggered by the log in action


Set your max_execution_time 300 to -1 which is unlimited or can increase according to your need.
And memory_limit to 1024M or more.


I'm not sure what template you're using, and I'm not sure how your site is setup. But if you have a template that is looping through and displaying these paragraphs, you can add a check in your twig file that checks if the paragraph is even or odd.

{% for paragraph in paragraphs %}
    {% if loop.index is divisibleby(2) %}

{{ paragraph.field_text }}

{{ paragraph.field_image }}

    {% else %}

{{ paragraph.field_image }}

{{ paragraph.field_text }}

    {% endif %}
{% endfor %}


How can I create a Views field template per display?

views-view-fields--myviewsname--display-1.tpl.php will do it, eg, views-view-fields--VIEWNAME--DISPLAYNAME.tpl.php.  (Along with changing any underscores in the names to single dashes)

On the api page you reference, you can see this in their example as the display mentioned there is called page.

These and other template names can be easily discerned from clicking on the Theme Information link in the Style Settings in the Views UI.


You have to put your code into an custom module. Creating Drupal 7.x modules should get you going. You should never change code of core. This will be lost (or at least causes tidious manual work) the next time you update drupal.


User 1 bypass access controls, so that wont work. You could have 2 menus as blocks and use the block system to control which to use.

You could also use theming/CSS to hide the menu.


Use the string overrides module - anything passed through t() will be caught by this and it provides an admin interface similar to the localization functionality to make it easy to look up these strings and translate or change them as you like. It also recognizes variables so you can still use the context of the function. From the module:

  Easily replace anything that's passed through t()
  Locale support, allowing you to override strings in any language
  ...
  Note that this is not a replacement to Locale as having thousands of overrides
  can cause more pain then benefit. Use this only if you need a few easy text
  changes.

You can also do this in your settings.php file with a simple array, ex:

$conf['locale_custom_strings_en'][''] = array(
   'Performed %operation on @items.'      => 'Your Changes',
);

This handbook page covers both of these methods in much more detail.


First back up the live site in its current state.

On your local site running your backup database enable the database administration module

And use that to export the tables labeled 'views_views' and 'views_display' in format 'mysqldump'

On your live site, import your sql files

Then run:

mysql -u root -p drupaldb < views-views.sql
mysql -u root -p drupaldb < views-display.sql

I used this issue thread for reference.

It's worth noting that because your errors also seem to be coming from blocks (and assuming no one else has worked on them in the meantime) you might also want to do the same as above with your 'block' 'block_current_search' 'block_custom' 'block_node_type' 'block_role' tables.


How can I manage site translations in code?

I had the same problem and had a look at the module Features Translation. However, there were some downsides to it. Don't know exactly what is was. From what I can remember is that when I import a feature, for example the menu link labels are imported in the built in interface. So it doesn't help to import the translations for Menu Items because the source labels are not available there but in the Built In interface. But maybe I am wrong, tried so many things I can really recall what I did.

But you can have a look at it, maybe it works for you.

Tell us when you have found a suitable solution. I am curious.


Why is drupal not changing the value when renderd after value change in preprocessor?

You need to pass $vars in by reference:

function mytheme_preprocess_views_view__myviewname(&$vars) {


Assuming that you have set up your contextual filters properly, all you need to do is change the format of the date you pass.

/events-calendar/20130904--20130930

That above format should do the trick.


How to create a block with views filter form available on each page of the site?

Views support "Exposed form in block", see in views editing page. Set it to "Yes", and it will appear in blocks.


How to override "Create @bundlename" text?

You can try using Node Add title module ...

  Above module allows you to configure the title of the Node Add pages
  and the Node Editing pages.

  The default title of the page where users create new nodes is
  constructed by Drupal in a dynamic way that not always looks good. By
  default Drupal concatenates the word Create and the name of the
  content type. The result could be something like "Create Basic page"
  or "Create article". This is not always acceptable.

  With this little module you can replace Drupal's default concatenated
  Node Add page title and the Node Editing page title with a title of
  your choice for every content type.

  After installing this module you will see the following two new fields
  at the bottom of the content type configuration form:

  Node Add page title Node Edit page title Use these two new fields for
  overriding the titles of the new node creation pages and the node
  editing pages.

PS : Module is in Dev Version.... Test before you use..

If you are interested to change same using code you can use drupal_set_title

function mymodule_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'mynodetype_node_form'){
         drupal_set_title('My new title');
    }
}


Calling render($content[...]); renders the field—but you need to change how the field is being rendered. To do this, you'll need to modify it's display widget.

Go to Admin→Store→Configuration→Product types→Product type→Manage Display. Then, on the price field, change the the formatter (the first arrow):

This can be further configured by clicking on the gear icon (right arrow) to get access to more configuration.

If this still does not suffice, try these:

Add a HOOK_commerce_price_savings_formatter_formatter to your theme to override the theme provided by the module.
Create a new formatter (the price saving formatter modules can be used as an example) and then use that formatter to display your prices.


Problems rendering radio buttons after an ajax call

A common mistake with AJAX is presuming that an AJAX callback is "aware" of the form's state. In reality, the form definition that AJAX works with is the original form instance. You will have to set the form values accordingly in your AJAX callback prior to returning the re-rendered markup. The $form argument that you receive in your callback function is always a cached copy of the original form.

So, to track what is going on in your form across AJAX callbacks, need to stash data server-side (e.g. in \Drupal::state()) or use the values stored in the $form_state argument. A good explanation of Drupal's form handling can be found here (thanks Jaypan!): https://www.drupal.org/forum/support/module-development-and-code-questions/2012-02-24/update-form-state-in-ajax-callback#comment-5648474


How to make weights continous with db_update?

Adding the expression is no problem, but neither UpdateQuery nor MergeQuery implement an orderBy() method. Neither will support setting a local variable first either, as far as I can tell (I'm not even sure a standard query will let you do that actually).

So I think it's safe to say that the answer is no, unless you subclass either UpdateQuery or MergeQuery, and add the sorting and variable declaration functionality yourself.


Content: tags contextual filter seems to only match the first tag

It usually work better when you add a relationship to the view, where you relate the content to the taxonomy term.
Then you unlock a whole new collection of fields and filters.

Choose to filter by taxonomy - name instead of content - tags.


Unable to find out how a content type node is getting themed

I have run into this before; it's the result of some bad practices commonly used by the commercial Wordpress—ehem, wait, I mean, Drupal—themers.

The culprit code is probably in a function in template.php or similar. Try searching the entire theme codebase for "team" - if you are on a Unix system you can use the grep command like this

grep -r "team" /path/to/theme

This might help you find the dirty function.


Adding values to referential entity using REST API POST

You can see the article about create Custom Rest Resources for POST

You can reference below code below

$node_actor = Node::create(
      ['type' => 'actor',// the content type
        'title' => 'Actor Name',
      ]
    );
   $actor_id = $node_actor->save();

After you can use $actor_id had node reference to movie

$node_movie = Node::create(
   ['type' => 'movie',// the content type
    'title' => 'Movie Name',
   ]
  );
  $node_movie->set('field_actor_ref',['target_id'=>$actor_id])
  $node_movie->save();


Script for collecting all translatable strings in the codebase?

By default, every string you wrap in the t() function is going to be added to the localization database by the core Drupal locale module as soon as Drupal encounters the occurrence. You can then use the translation interface to search for these new strings and update them manually or export a Gettext Portable Object Template file

http://example.com/admin/config/regional/translate/export

These files are in text format and easily editable by non-technical users, ex:

#: misc/tabledrag.js
msgid "Hide row weights"
msgstr ""

There are a number of tools available for working with gettext files, I would recommend the Localization client module for doing this work within the Drupal interface. There is also an option to convert these files to excel and back using csv2po but I haven't used this:

http://docs.translatehouse.org/projects/translate-toolkit/en/latest/guides/using_csv2po.html


View listing element by date, exception for the first one

Add two sort criteria, the first one on that ID and the second on the date.
Please note that the "ID" must have the same value for all other nodes except the first to make this works.
So probably it will be necessary to use an extra field - boolean, or integer, depending how many nodes you want to fine control.
If you don't have a lot of content to order in that view you otherwise may consider Entityqueue or DraggableViews.


How to redirect programmatically inside a module to an external url?

Well if you want to redirect to an external page this can be your code:

<?php

namespace Drupal\achva_sso\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;

class SsoController extends ControllerBase{
    public function ssoLogout(){
        unset($_SESSION['name']);

        // Redirect.
        return new TrustedRedirectResponse('http://www.bbc.com/');

    }
}

In this case, the redirection will happen when your ssoLogout() method will be called.


Views multi field exposed free-text filter/search

You could do that without the help of the search filters.

On my Drupal instance I have Views 7.x-3.7 there is a filter Global: Combine fields filter (exposed) This lets me add multiple fields and then enables users to search on selected fields using a single filter.


What are all the directories for in the new Drupal 8 structure?

/core - All files provided by core, that doesn't have an explicit reason to be in the / directory. More details futher down.
/libraries - 3rd party libraries, eg. a wysiwyg editor. Not included by core, but common enough to warrant inclusion here.
/modules - The directory into which all custom and contrib modules go.

Splitting this up into the sub-directories contrib and custom can make it easier to keep track of the modules.
enough to warrant mention here.

/profiles - contributed and custom profiles.
/themes - contributed and custom (sub)themes
sites/[domain OR default]/{modules,themes} - Site specific modules and themes can be moved into these directories to avoid them showing up on every site.
sites/[domain OR default]/files - Site specific files tend to go here. This could be files uploaded by users, such as images, but also includes the configuration, active as well as staged config. The configuration is read and written by Drupal, and should have the minimal amount of privileges required for the webserver, and the only the webserver, to read and modify them.
/vendor - Backend libraries that Drupal Core depends on. (Symfony, Twig, etc)

Details on the /core directory, primarily useful to know for new core hackers:

/core/assets - Various external libraries used by Core. jQuery, underscore, modernizer etc.
/core/misc - Frontend code that Drupal Core depends on.
/core/includes - Functionality that is to low level to be modular. Such as the module system itself.
/core/lib - Drupal Core classes.
/core/modules - Drupal Core modules.
/core/profiles - Drupal Core installation profiles. Minimal, Standard, Testing and Testing multilingual installation profiles by default.
/core/scripts - Various CLI scripts, mostly used by developers.
/core/tests - Drupal Core tests.
/core/themes - Drupal Core themes.


Comment approval permission to non-admin user

I take that "moderator2" is a username name used for a user account. In that case, if you want to give to moderator2 the permission to administer comments, then you have to associate the user account with a role you only give to those users you want to be able to administer comments, then you visit the page on admin/user/permissions, and select "administer comments" for that role.

In this case, I called the role "comments moderator" but I could have chosen another name.

If "moderator2" is a role name, then on the page at admin/user/permissions you see something similar to what shown in the following screenshot.

The permission is the same as before.

P.S. The only permission for which you are interested is "administer comments." The other permissions don't influence that one, and users with a specific role would be able to approve comments, even without to have (for example) the permission to access comments.
The only permission associated with the page at admin/content/comment is "administer comments."

  $items['admin/content/comment'] = array(
    'title' => 'Comments',
    'description' => 'List and edit site comments and the comment moderation queue.',
    'page callback' => 'comment_admin',
    'access arguments' => array('administer comments'),
    'file' => 'comment.admin.inc',
  );


Translate configuration values in custom webform handler

I did provide the wrong type. It should be label and not string
webform.handler.newsletter2go:
  type: mapping
  label: 'Newsletter2go'
  mapping:
    newsletter2go_formcode:
      label: Formcode
      type: label


Using Theme() to output html/javascript in user edit

If you just want to add some markup and Javascript, you don't need a submit callback because that's for handling form submissions.

Requirement 1: Add html

Options:

#prefix and/or #suffix form element attributes. (If just simple short html this will do)
#theme to use you custom theme function declared hook_theme and place your markup in your tpl.php file. (If too much markup and want your module/theme to be clean)

Requirement 2: Add javascript

You can use #attached form/form element attribute

In the links, there are example codes that you can follow.


Views: attachment inherits exposed filters when set to No

You can't do that by default with views settings. Filters are meant to stay upon adding / removing one of them, because otherwise you can't search items combining them. You can add a "Reset" button form the "Advanced" block of the view UI (see screenshot).

If you want this behavior to be exactly as you describe, I think you'll need write up a plugin for the filters yourself, or alter the default ones.


Have a look at Limit allowed HTML tags in the setting for your text filter. Make sure img is among the allowed HTML tags.

The settings are found under admin/config/content/formats.


That isn't the right way to save a line item. All that second line does is remove the item from the entity controller's static cache.

As CommerceLineItemEntityController::save() already manipulates the static cache directly to ensure the updated entity is in it, the second line is redundant. All it does is force unnecessary database usage if/when the same line item is loaded again in the same request.

This is all you need to create or update a line item:

commerce_line_item_save($item);

Remember that $item is an object, so doesn't need to be passed by reference as you mentioned in the comments.


How do I limit webform submissions based on the email address?

Edit the email field in the webform and check both the "mandatory" and "unique" options. That way, it will not except more than 1 submission with the same email address.


OH, just realized now, maybe I misunderstood the question 100%

This is the code which basically generates the output:

$serializer = \Drupal::service('serializer'):
$output = $serializer->serialize($entity, $format);

with $format for example being 'json'.

Luckily the serializer is symetric, so you can do the same the other way round.

$client = \Drupal::service('http_client');
$result = $client->get('http://example.com/entity/node/1', ['Accept' => 'application/json']);
$output = $result->getBody();

$serializer = \Drupal::service('serializer'):
$entity = $serializer->deserialize($output, 'Drupal\node\Entity\Node', $format);


How to generate url with language code in drupal7?

You can get the URL by using following code

global $language ;
$lang_name = $language->language ;

$url_current = $GLOBALS['base_url']/$lang_name;


You need to enable the Profile2 Page module in the modules list page.

Then you go to modules/profile2 and copy profile2.tpl.php, paste it into your template folder and there you can customize as you want using...

print render($content['YOUR_FIELD']);

...or other variables you want.


Real-time workflow scheduled transitions?

You can use Elysia Cron to let the workflow cron hook run every minute, without sacrifing performance by having other cron hooks run that often.

See Multiple (and differents) crons?


I don't understand most of this.. "publishing a content type?" You sure you don't mean "creating a node"?

Anyways, in conditions for the rule, choose "entity has field" for each field you need. This will allow you to use them in actions.


As you are using subdirectory structure at localhost and previous drupal installation was at root directory, the base url will not change for database entries.

Use Pathologic module to change base url of urls coming from database

or

search n replace them in .sql file, then import the database.

search: src="/sites/default/files/images

replace: src="/repliconwebsite/sites/default/files/images


How to create a block with taxonomy terms and their corresponding nodes?

Well you need to use views_field_view module. In you views :

Create a view of Taxonomy type
Add a filter of Taxonomy Vocabulary = Categories
Add filed Term: tid (exclude) and Term: Name
Add Global View field pass argument tid (Another view in which contextual filter of tid is added and 3 items are displayed in views configuration)

Done.


Change Views BETWEEN min/max filter to a cleaner URL format?

You can always create redirects with rewrite rules outside of Drupal, in your server configuration. You can add them in Drupal settings too.
There is a module that did this for Views in D7 but it needs more help with D8, help if you can:
Query Parameters To URL


Perhaps you can use the Conditional Fields module to check whether the field has a value (sort of a 'not empty' check).

Conditional Fields is described as follows:

Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.


Drupal7 | Time shows differently in Frontend and Backend

Problem solved:

Just in case someone else got the same problem over this.
Here is what I was doing wrong (Thanks to Jay from Princeton University for pointing it out):

I set up the Date & Time for the administrator account under "/admin/people", but not the system-wide setting, which is at "/admin/config/regional/settings"

'Administration -> Regional & Language -> Date And Time' will show the date/time formats I have set up while respecting the user-chosen timezone (not the system-wide default time zone) so everything looks deceptively like it's how I want it until I log out.

So in short there is another time setting in .../admin/config/regional/settings
that I wasn't aware off.


For those of you interested -- the only way I could figure out how to solve this was with writing a custom cTools plugin (See: What are Ctools plugin (content type, access, etc), and how does one create them?).

In that plugin I created a block and placed it in the panel.

I used Magpie RSS for the parsing/fetching of the feed.


Complete checkout for all orders Drupal commerce

I fixed this issue by adding this PHP code:

$orders = commerce_order_load_multiple(array(), array('status'=>'cart'), TRUE);
foreach($orders as $order){
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    foreach($order_wrapper->commerce_line_items as $line_item_wrapper){
        $product = $line_item_wrapper->commerce_product;
        $node_product = $node_wrapper->field_product;
            $order_wrapper->status = 'invoiced';
            $line_item_wrapper->save();
            $order_wrapper->save();
    }
}


The Plus One Module (in conjunction with the Voting API) should do what you're looking for.

  [This module provides] a simple digg-like voting widget for content that uses Ajax.

Here is a demo I put together for another question.


Using Views sounds like a way to go. You could have separate employee and company profiles (where employee profile references company), and then add a view to each company profile listing all its employees.


How to grant permission directly to a user other than a role?

Use the user permissions module.  Contrary to your objections to using this module, it is not the grantee who needs the  "administer permissions", but the grantor


Inspecting the differences in the node table, I noticed that the node created by my code had an empty language field. Updating this to "und" fixed the node alias.

This makes sense, because path_save() defaults to LANGUAGE_NONE (i.e. "und").

I had assumed that node_prepare would do likewise, but it does not.

So the solution is to set $node->language = LANGUAGE_NONE; at the point of creation.

Also, this is an easier way to create the alias...

$node->path = array('alias' => $path, 'pathauto' => FALSE);


views_get_current_view() seems to be from the early days of procedural code and I don't know how this can be used in connection with form building in D8.

You can get the current view from the current route, if this is what you are looking for:

use Drupal\views\Entity\View;

  $view_id = \Drupal::routeMatch()->getParameter('view_id');
  if ($view_id) {
    $view = View::load($view_id);
  }


How do I apply patch in vendor directory using composer?

You will need cweagans vendor to make composer able to parse the extra->patches lines.

This line is wrong I think: "vendor/behat/web-api-extension"
You always need the package name (without version) and not the relative path.
In your case it should be "behat/behat"


How to create a $navigation main menu with target="_blank" on specific page.tpl.php pages

There are many ways to do this

A quick way would be to use jQuery to rewrite the anchor tags in the menu with the target attribute

$( '.page--landing [menu link selector] ).attr( 'target','_blank' );

Using the Drupal API

function MODULE/THEMENAME_menu_link_alter(&$item)
{
   if (some logic that sets it only for the desired paths/context)
   {
     $item['options']['attributes']['target'] = '_blank';
   }
}

an example from the documentation for function hook_menu_link_alter

function MODULE/THEMENAME_menu_link_alter(&$item)
{
  if($item['link_path']=="admin/tutorial14333")
  {
  $item['options']['attributes']['target'] = '_blank';
  }
}


How can I get the content type name inside the hook_form_BASE_FORM_ID_alter() hook?

You can get the node from the form object.

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function yourmodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  /* @var \Drupal\node\NodeInterface $node */
  $node = $form_state->getFormObject()->getEntity();

  if (!$node->getType() == 'article') {
    // ....
  }
}

Note that getEntity() doesn't exist on \Drupal\Core\Form\FormInterface, which is why it doesn't show up as a method in an IDE. It only exists on \Drupal\Core\Entity\EntityFormInterface, you can add an explicit instance of for that.


Can I use sites.php to resolve subdomain on my multi-site installation?

This assumes your multi-site structure is as follows:

sites/site.edu
sites/cyber.site.edu

Let's start at the top by addressing a few key things:
1. Is there a DNS entry for your subdomain?
When working locally, you should add the subdomain to your hosts file.
Hint: If browsing to cyber1.site.edu generates "This webpage is not available", the answer is no.
Help: (AskUbuntu) Setting up subdomain on Ubuntu server
2. Have your Virtual Hosts been properly configured?
You need to inform Apache how to pass the correct domains to Drupal.
Hint: If browsing to cyber1.site.edu generates a Drupal site installation page, the answer is no.
Help: How To Enable Multiple Sites on a Drupal Installation On Ubuntu 12.04
3. Do you have a folder in sites/ bearing the actual hostname, including the subdomain?
In this case, we already know the answer is no. If the answer were yes and you had a folder in sites/ named cyber1.site.edu then Drupal would be able to auto-discover it in the usual way. Since you do not, we need to tell Drupal what to do.
This is where sites.php comes in handy:

Setting up sites.php
From the docs in sites/example.sites.php:

This file allows you to define a set of aliases that map hostnames and
pathnames to configuration directories. These aliases are loaded prior
to scanning for directories, and they are exempt from the normal
discovery rules. (...)
To use this file, copy and rename it such that its path plus filename is 'sites/sites.php'.

Add this line to the end of the file and save.
$sites['cyber1.site.edu'] = 'cyber.site.edu';


Is there an option to somehow display all nodes that that doesn't have a menu link?

I think the best approach to handle this would be to get all of the menu items, and the nodes associated to them.  Then perform a EntityFieldQuery on nodes.  Making sure that your query includes a 'NOT IN' condition, and use the ids from the nodes you discovered in the menu as the values.

This would return all nodes not in your menus.


if scripts[] variable additions are added before drupal_add_js() calls, etc

The JavaScript files used by a theme, and defined with scripts[] directives are added in _drupal_theme_initialize(), using the following code.

  // Do basically the same as the above for scripts
  $final_scripts = array();

  // Grab scripts from base theme
  foreach ($base_theme as $base) {
    if (!empty($base->scripts)) {
      foreach ($base->scripts as $name => $script) {
        $final_scripts[$name] = $script;
      }
    }
  }

  // Add scripts used by this theme.
  if (!empty($theme->scripts)) {
    foreach ($theme->scripts as $name => $script) {
      $final_scripts[$name] = $script;
    }
  }

  // Add scripts used by this theme.
  foreach ($final_scripts as $script) {
    drupal_add_js($script, array('group' => JS_THEME, 'every_page' => TRUE));
  }

_drupal_theme_initialize() is indirectly called from theme(), l(), contextual_preprocess(), and ThemeRegistry::initializeRegistry().

As each JavaScript file added to a page has its own group, with its own weight, it doesn't generally have importance which file is added first. If you really need to be sure a file is included before another one, you should define its group, and its weight, consider that files are included following this order:

First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by the theme
Then by group
Then by the 'every_page' flag, with TRUE coming before FALSE
Then by weight
Then by the order in which the JavaScript was added


"Content entity" types like nodes (content) are field-able, so you can choose what data are attached to them.

The "basic page" content type only comes with a body field out of the box, but it's a cinch to add new ones:

Visit /admin/structure/types
Click "Manage fields" for the "basic page" type
You'll see a list of the fields currently attached to the content type. Click "Add field"
Select a field type; "Image" would probably make most sense for your needs
Follow the rest of the wizard and choose suitable values (should all make sense)

When you visit the node add/edit page for a "basic page", you'll see the new field, and you'll be able to upload your images.

Next you'll probably want to visit the "Manage display" tab to choose how the images are rendered, and the "Manage form display" tab to choose which widget is used.


How to register or track the views of a node per user?

I think You've  missed something from the Node View Count module.

  Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

Note: Make sure to give permission for users to see their node view count.


Showing a list of content that only authorised users can see

You can use use Nodeqeue and views module to create a nodeqeue and assign permission using views module.


How can I act on a taxonomy term in my twig template?

content.field_taxonomy_resource_type is a render array, which you're comparing against a string. Instead, you need to get access to the label, and extract the term name.

Try this instead (if in a node template):

{% if node.field_taxonomy_resource_type.entity.label == "Topic Page" %}

Or, as we know it's a paragraph template:

{% if paragraph.field_taxonomy_resource_type.entity.label == "Topic Page" %}


Drupal 7 hook_fom_alter not working for custom fields

Set default value in field setting and try this after that :

print $form['field_your_email']; //check where default value is

$form['field_your_email']['und'][0]['value']['#default_value'] = 'sam@gmail.com';


How to display references entities in single field?

You might need to use something like Views Field View and pass your node number as an argument, then use the reverse relationship to list members.


Your problem is don't delete image style when uninstall module. So when you reinstall image style already exist. Use can use hook_uninstall to delete
image style to finish uninstall: write code in file module_name.install

<?php
use Drupal\image\Entity\ImageStyle;

function module_name_uninstall() {

  ImageStyle::load('image_style_name')->delete();

}


Drush returns "sh: php: command not found, code: 127"

Exit code 127 means "command not found", just as the error message says. https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html

If php is in your PATH, then this should not happen.  If you want to explicitly tell Drush which php to run, then set the DRUSH_PHP environment variable as explained in the Drush README.  This should help out in the case of Drush commands such as the ones you mention before, that run a Drush subcommand in a new process.

Update:

To make things work correctly, you need to understand how bash initializes itself.  For example, did you know that .bash_profile is sourced if you run ssh user@host, but it is not sourced if you run ssh user@host pwd?  Drush uses the later form to re-launch Drush subprocesses, so if you initialize your PATH in .bash_profile, then it will be fine when you test it in the shell, but it will be broken for Drush subprocesses.

To get around this problem, you should also export your PATH in your .bashrc file, as bash will source this file for non-login shells.  Be sure to set up your PATH at the TOP of the file, as there is a line near the top that reads: [ -z "$PS1" ] && return.  This causes the script to exit if ssh did not create a tty (run ssh -t to create a tty; Drush adds this flag for interactive commands only.)


Node gallery: display image count in a template file

One answer:

<?php
  $results = db_select('field_data_node_gallery_ref_1')
  ->fields(NULL, array('entity_id'))
  ->condition('node_gallery_ref_1_target_id', $node->nid)
  ->execute()->fetchAll();

  $pcount = count($results);
?>

Explanation:

The field_data_node_gallery_ref_1 table contains one row for each picture in the gallery. I filter it by the nid of the gallery (node_gallery_ref_1_target_id) in order to get only pictures in that gallery, then count how many pictures exist on the gallery by counting the results of the query array.


Count items in nested field array for if/then in template

You can use field_get_items api function to read values.

<?php

$images = field_get_items('node', $node, 'field_media');
if (count($images) > 1) {
  // Print Carousel
}
?>


How do I get items of a field of type list?

Better create a vocabulary of taxonomy terms populated with your items.Then you can use taxonomy_get_tree() function to retrieve all those items


How do I create a folder structure inside a view

The feature "Group by field" provides a hierarchy, but you don't have the path components out of the box.

Are you using a module that is controlling the paths that is also integrated with views, maybe File field paths? If you can get a field to display a path component you will be able to group by them, effectively getting a folder structure.

Views tree also helps, if you have the path components.

This comparison list might help: File Uploading and Managing.

If no module provides this already you'll have to create your own Views Field formatter for the file URL link field and use with some hierarchy mentioned above, or create a completely new Views Format for the File Views type that displays results in a hierarchy.


I ended up:

Creating a Content Pane for each question.

Added a duplicate set for each field result in the that pane.

For instance one, I set aggregation to "Group results together", which gave me the labels.

For instance two of that same field, I set the aggregation to "Count", which gave me the number of times that value has been selected.

Excluded the above fields from display.

Added a Global Text field for styling, using the tokens from the above fields for Label: (Value)


How can I programmatically restrict node access?

I use a function to build the database rows in node_access and nodeaccess:

  private function set_node_access($nid, $id, $realm='nodeaccess_uid', $view=1, $update=0, $delete=0)
  {
    // ksm("nid: $nid uid: $uid");
    $connection = \Drupal::database();
    $sql = "INSERT INTO nodeaccess (nid, gid, realm, grant_view, grant_update, grant_delete)
            VALUES($nid,$id,'$realm',$view,$update,$delete)
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete)";
    $connection->query($sql);
    $sql = "INSERT INTO node_access(nid, langcode, fallback, gid, realm, grant_view, grant_update, grant_delete)
            VALUES($nid,'de', 1, $id,'$realm',$view,$update,$delete)
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete);";
    $connection->query($sql);
  }

That's not the nice way, but it works for me.


How to force migrations to not copy files

Well if thats not working do a scan for the file on the destination location to set or unset the field value (so it's not updated on save). You can do this in the prepare function of your migration class. See the commonly implemented migration methods page for example implementations.

Also have you tried setting the preserved_files key:

    $this->addFieldMapping('field_images:preserve_files')
  ->defaultValue(TRUE);

I haven't done any file migrations myself lately, but I stumbled across that in this thread: https://www.drupal.org/node/1886404  it looks like you got the field ordering correct (well from the issue the source field primary and sub-field ordering now no longer matters).


Use aggregate and set the option for distinct results. Aggregate is similar to GROUP BY in SQL so be careful what fields you include. If you really need to do it with custom code set a tag for your view's query in advanced settings and then use this tag to alter your query by implementing hook_query_alter or hook_query_TAG_alter in a custom module
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_query_TAG_alter/7


Adding a table with items and prices to a drupal site

Your question consists of 2 questions ... I'll use the same numbers to answer them.
1. Alternatives to using Custom Content types
a) Use Drupal Entities (Option 1)
Use the Entity Construction Kit (ECK) module to create 'entities' (= fieldable things ...) like Products and Prices. For each of those entities use "fields" for each of the columns you mentioned. Should you run into fields such as dates, you would have to add modules such as date also.
For the "foreign keys" use the Entity reference module (possibly some related modules of it also, extending its functionality, as mentioned on the ECK project page) and/or the References module (cfr. 'node_reference' and 'user_reference' as contained in CCK for D6).
Maybe modules like Display Suite or Panels could help to enhance the look and feel of it all also?
b) Use custom tables and/or an external database (Option 2)
Custom tables are tables you create yourself, in the same Drupal database. External Databases are databases that are different from the Drupal database, which are typically in formats such as Oracle, PostGress, MS Sql, MySQL, SQLite, some PDO compliant DBMS.
Using this alternative, you can use the Forena module for reporting about the data from within a Drupal site (as further explaining within "reporting" below also). To perform updates (delets, inserts, etc), you'd use your own tools that you'd prefer for the DBMS of your choice. Same for creating the tables, etc.
2. Reporting
Consider using modules such as (either one, or both, depending on your requirements):

Views, combined with Views Calc also probably. Have a look at How to calculate the sum for each option of all webform results in a Drupal webform grid? to get an idea of using Views Calc.

Maybe you want to consider the Forena module as a supplement / alternative. E.g. if you'd need to also create charts or so, or if you have a need to access data in some external database such as MS SQL, Oracle, etc. Here is a quote about it:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Disclosure: I'm a (co-)maintainer of some of the modules mentioned,
I hope this does not violate the site's policy on self-promotion.


Try http://timonweb.com/how-create-ajax-autocomplete-textfield-drupal-7

ALSO:
http://qandeelaslam.com/blogs/cck/converting-texfield-autocomplete-using-drupals-form-api
http://www.elevatedthird.com/blog/enable-ajax-autocomplete-drupal-7-webform-textfield

(Looking for a module,  now.)


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

    if($form_id=='user_profile_form') {

       $form['linkb'] = array(
            '#type' => 'image_button',
            '#href' => '',
            '#title' => t('something'),

            '#name' => 'linkb',
            '#ajax' => array(
                'method' => 'html', // this is important without this if else condition for ajax will not work.
                'effect' => 'fade',
                 'prevent' => 'mousedown',
                'callback' => 'clicktell_verification',
                'wrapper' => 'replace_textfield_div',),
        );
        $form['cardnresp'] = array(
            '#type' => 'hidden',
            //'#default_value' => '',
            '#title' => t('This is where msg comes'),
            '#prefix' => '
',
            '#suffix' => '
',
        );
        $form['#validate'][]='clicktell_error';

    }
    return $form;
}

This will run ajax but you may feel form is submitting but there is no actual submitting of form


Based on your responses in the comments, it sounds like you want anonymous users to be sent to the login page on any access and for authenticated users to be able to access the site as normal.  You can achieve this with a custom module that checks for logged-in status and redirect to the login page, or via the Require Login Module which does essentially the same thing.


Hope this will help you.

Create a new view content type

add field Content: All taxonomy terms (checked Exclude from display )
add field Content: Title

add filter Content: Type (= Member)

go to format select HTML list on settings Grouping field Nr.1  select Content: All taxonomy terms unchecked "Use rendered output to group rows"

from add create a block you will get a new block in your block page.


I am doing it.  The only problem I found was with Panels, but this post fixed it.  Also, I had to turn down the default error reporting, but I've not had the site crash.


Redirecting to external validation page using oauth with drupal_http_request()

In the case the request is redirect to a different URL, $response->code is 301, and $response->redirect_url is the redirection URL. If the request is redirect, you can call drupal_http_request() using $response->redirect_url as new URL.

See aggregator_aggregator_fetch() as example of Drupal function that verifies the request is being redirected.

  // Process HTTP response code.
  switch ($result->code) {
    case 304:
      break;
    case 301:
      $feed->url = $result->redirect_url;
      // Do not break here.
    case 200:
    case 302:
    case 307:
      if (!isset($result->data)) {
        $result->data = '';
      }
      if (!isset($result->headers)) {
        $result->headers = array();
      }
      $feed->source_string = $result->data;
      $feed->http_headers = $result->headers;
      break;
    default:
      watchdog('aggregator', 'The feed from %site seems to be broken, due to "%error".', array('%site' => $feed->title, '%error' => $result->code . ' ' . $result->error), WATCHDOG_WARNING);
      drupal_set_message(t('The feed from %site seems to be broken, because of error "%error".', array('%site' => $feed->title, '%error' => $result->code . ' ' . $result->error)));
  }

If you want to redirect the users to $result->redirect_url, and not requesting that URL with drupal_http_request(), you use the following code.

drupal_goto($response->redirect_url, array('absolute' => TRUE));


How to find image style URL from within twig template?

The first part is already answered in the linked question, where there is the code how to do this. To answer the second part of the question, you can access the original image in the node object:

{{ file_url(node.field_image.entity.uri.value) }}

One remark about content:

In a node template the image field in content is not ready to be rendered. The field contains the configuration how it should be displayed and the field object which contains all raw data. Later this will be put together in the field, image-formatter and image templates. That is the reason you don't find the url you are looking for in content at this point.

In the node template you can use the fields on the top level of the content array, for example display the image field

{{ content.field_image }}

as configured in the view mode.

Edit:

There is a new filter in the module Twig Tweak. Now you can generate the image style url in twig directly from an uri or url of the original image:

{{ node.field_image.entity.uri.value | image_style('thumbnail') }}


Is the mail_logger module safe for production?

No, it doesn't enable any developer backdoor features (e.g. arbitrary PHP execution, code/stack dumps, etc.) if that's your concern.

For the most part, its code base is Views integration & an admin interface wrapped around its core function; intercepting outgoing mail through hook_mail_alter() and storing in the mail_logger table.

I'd say the only concern there is privacy for your users.


How to manage text on my site that's not node content?

Consider using the Bean module for this. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

If you'd grant content editors the appropriate Bean permissions, it appears to me that you might be close to a possible solution to what you're looking for.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

PS: This module only started as of D7, and is already integrated in core in D8 ...