How do I get a field label in different languages?

You can load an entity's translation by using the entity repository service. The field configuration is an entity itself. So you could try this:

use Drupal\field\Entity\FieldConfig;

// Override language before loading field configuration.
$language = \Drupal::languageManager()->getLanguage('fr');
\Drupal::languageManager()->setConfigOverrideLanguage($language);

// $entity_type, $bundle, $field.
$field_info = FieldConfig::loadByName('entity_type', 'bundle', 'myField');

$label = $field_info->getLabel();

EDIT:

As stated by 4k4 within the comments, config entities don't behave like content entities. So in order to get their translations, you will need to override the language before getting their translatable strings. Adjusted the example accordingly.


How to add fields from other modules in Drupal 6 Views?

You can try out the below modules. They are meant for getting data directly from the database into views.

Table Wizard

Data Model

If both of them doesn't suit your requirement then you could use the Views Custom Field write php code directly into the view and collect the required fields using database queries.

You could also do the direct query with in the views template files.


Displaying parse errors in module development on the browser

You have to enable error displaying in PHP. There are several ways to do it, but one of the most straightforward is to enable them in the settings.php of your project.

Just add those lines to the file:

error_reporting(E_ALL);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Meaning:

Instruct PHP to notify all errors.
Instructs Drupal to show all errors (using a drupal_set_message).
Instruct PHP to display errors instead of show a blank page.
Instruct PHP to display errors even those in the startup phase.

Also, as Clive comments, if you enable XDebug error reporting is more verbose. The screenshot you show includes XDdebug error backtrace.


When configuring flag(s) (using the Flag module), you can indeed attach fields to them. However when doing so, make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.
Navigate to Administration > Structure > Flags page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.

If the above doesn't help (or if you've already configured your flag using a Confirmation Form), then you may want to look at Comment nr 1 in issue nr 2539868, which points to 2 more related issues.


Is there a function to output the tag and vocabulary?

There is taxonomy_get_tree() which can return all terms in a hierarchical array, you will however still have to display it and hardcode the vid (or use variable_get() to make it overridable).

Depending on how and where you are displaying this, one of the following alternatives could maybe work better for you:

If you are displaying this information in a block, consider using http://drupal.org/project/taxonomy_menu instead. It can create menus based on vocabularies, which you can then be displayed as a block. They will be properly cached and faster than querying them on every page.
You can also use Views to build a list, tag cloud or similar thing for all terms of a vocabulary.


To print the HTML code corresponding to your form you need to render it:

$form = drupal_get_form('weblabs_form');
print drupal_render($form);


How to remove the grid from a zone in Omega

Could you elaborate on what it means not to be gridded inside a zone? If you just make a single region inside the zone that is as wide as the zone, then you could lay out content in the region however you want. Your CSS would just have the zone or region class as a prefix to anything else in that region.

Or, are you trying to get rid of the gutters? If so, you could make a custom grid of some number of columns with zero-width gutters. Then you have to add padding and margins yourself to your content. I have a site with an Omega grid-based layout with zero-width gutters, and do some non-grid-based layout inside certain regions.. For instance, I have pairs of images side by side inside the right sidebar. They are not aligned with the grid columns.


warning: Illegal offset type in isset or empty

I have fixed the problem. I think this will help you. For me it works perfectly:

BEFORE:

// Custom strings work for English too, even if locale module is disabled.
if (isset($custom_strings[$langcode][$string])) {
  $string = $custom_strings[$langcode][$string];
}

AFTER:

// Custom strings work for English too, even if locale module is disabled.
if ($custom_strings[$langcode] && isset($custom_strings[$langcode][$string])) {
  $string = $custom_strings[$langcode][$string];
}


How can I uncheck a required checkbox on the edit page for a given content type?

Implement hook_form_FORM_ID_alter() such that it clears the #default_value property of the widget:

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node_type = 'example_type'; // TODO: change to the desired node type
  $field = 'field_example';    // TODO: change to the name of the field

  $node = $form['#node'];
  if ($node->type == $node_type) {
    $language = $form[$field]['#language'];
    $form[$field][$language]['#default_value'] = 0;
  }
}


Try this : Add this code in .info.yml

libraries:
        - 'theme/global-styling'
        - 'theme/global-scripting'

And include the CSS and JS the libraries.yml file like below.Include styles and scripts seprately.

 global-styling:
    css:
      theme:
       css/style.css: {}

 global-scripting:
    css:
      theme:
         js/script.js: {}


Getting Drush to play with MAMP and Acquia

when User°1 tries to start Acquia Drupal he just gets an alert box saying that the Apache server failed to start - nothing shows up in the Apache error logs (the MySQL server starts ok though).

Have you ensured you are only running a single apache process as OSX ships with it's own version and MAMP also has it's own. You can confirm it by running ps aux | grep apache in your shell.

Additionally, you can check which version has priority on the system (based on $PATH) by running which apachectl in a shell (example output).

$ which apachectl
/usr/sbin/apachectl

Which will help you determine that if there are conflicting version trying to run, who will be serving the requests.

  I've done everything I can to get this working, in particular by using the alias command
  like so:
  alias drush='/Applications/MAMP/bin/php/php5.3.27/bin/php
  /usr/local/Cellar/drush/6.2.0/libexec/drush.php'
  but all to no avail.

I am not sure whether you should be executing that drush.php file directly as all of the installations I have ever completed all point to an executable that I usually move the /usr/bin or /usr/local/bin for system wide availability - But then again, I haven't tried installing drush 6 yet so that could have changed.

If you do a bit of development and don't like dealing with issues like this, I recommend you look at virtualising your environments using a tool such as Vagrant. Doing this will allow you to build an isolated development environment where you can configure the environment then package it for reuse should you ever need to reset it.


You can not do it through macro's but alternatively you can set the zoom option for the map.

Go to Gmap Setting and set the Default zoom option to your requirement.

Hope it works for you!


Accessibility : Broken Skip Link Error on "Skeleton" Theme

I use the Skeleton theme. it has:

    Skip to main content

But it has no anchor tag for main-content. You should file an issue for the Project on Drupal.org.

You can fix this by supplying a patch to the theme project that alters html.tpl.php or page.tpl.php to include an  at the top of the content area. You may do this in your own subtheme as well of course simply by modifying the necessary TPL file.

EDIT:
Issue created at Drupal.org https://drupal.org/node/2211661


How to format an integer field as Date/Time using Views module

Implement hook_entity_property_info_alter() to describe your custom entity type's properties to the Entity API module, which will then automatically create Views integration based on the types of fields in your database table.

http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.api.php/function/hook_entity_property_info_alter/7

An example of this can be found in the Log module, which has three timestamps (timestamp, created, and changed). It gives each of these a "type" of "date" in the entity property info, which automatically makes them visible to Views as date fields. http://cgit.drupalcode.org/log/tree/log.module#n242


Getting the taxonomy parent term as Views argument

I believe that Views uses $view->args to store the arguments it has received from the url, or passed to it when embedded.

So in the above case, you would need a url structure where the parent term is located in the views url after the actual term. Most likely this is not the case.

If you want to get the parent term you can use the function taxonomy_get_parents


Modifying Poll Template to have big buttons for voting

What I ended up doing was overriding this theme function:

function media_preprocess_poll_vote(&$vars)
{
    $node = menu_get_object();
    $list = array();

    $vars['choice'] = '';
    $vars['vote'] = '';

    foreach ($node->choice as $i => $choice)
    {
        $vars['choice'].= '
        <div class="poll-choice-wrapper">
            <input type="button" data-choice="'.$i.'" id="choice-'.$i.'" name="choice-'.$i.'" value="'.$choice['chtext'].'" class="poll-choice" />
        </div>';
    }

    $vars['choice'].='<input type="hidden" name="choice" id="choice" value="-1" />';
}

Then adding a little js:

jQuery(document).ready(function()
{
    jQuery(".poll-choice").click(function()
    {
        jQuery("#choice").val(jQuery(this).data('choice'));
        jQuery("#poll-view-voting").submit();
    });
});


Webform - Mandatory text field depending on select option state

I found a module called Webform Validation that lets you achieve this without any custom code.

To accomplish the above, add the 'Require at least one of two fields' validator under 'form validation' and then select both components that you want to validate against.


How to conditionally book an appointment on calendar module?

I'm not aware of any way to use the Calendar module for this. However, there are some distributions and/or contributed modules for managing such bookings. More details below.

Option 1: Distributions

The Clinic Appointment distribution is a brand new distribution for D7. Some more details about it (from its project page):

  It is a doctor appointment management system. It manages patient profile, doctors profile, and appointments. It supports multiple offices. It creates all kinds of reports that help clinic's day to day operation and business growth. It is a great choice for doctors to have an excellent management system built on a free open source software.

  Appointment Management System is the quickest way to get up and to run with patient appointment management. It includes the latest version of Drupal core, FullCalendar, and the other modules it is depending on. It lets you create a fully functioning appointment book, managing system out of the box. It comes with comprehensive reports powered by views module.

  Who should use Clinic Appointment? Anyone who want to build an appointment booking system. Anyone who wish to use it to schedule an appointment with doctor and patient. Customize patient, doctor content type by adding and deleting fields to the need for your business.

According to Comment nr 2 in issue # 2646628 it "Can be used for appointments made by patients" also.

Option 2: Contributed modules

These modules have a stable release, and can be used  for either D6 or D7 (quotes are from their project pages):

Availability Calendars (D6 or D7).

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation (D6 or D7).

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependent on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

MERCI (D6 or D7).

  ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict (D6 or D7).

  ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

Deciding which module to go for

When deciding between multiple modules, a typical consideration is often about the "maintenance status" of the various modules. To illustrate some of the criteria I often use for that, please checkout the community documentation about Maintenance Scorecards. Here is the intro about it (from that page):

  ... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Disclosure: I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).


I found the solution in enabling the entity_token module. This expanded my available tokens list to include the fields within the field collection.


How can I restrict changes to certain fields in a view for a user?

You can expose only the Title filter to the user. They will be able to see all of the content, but only specify the exposed filter.

You can expose a filter while editing it by checking the box that says "Expose this filter to visitors, to allow them to change it".


Send different email response based on form options?

I experienced the same problem a while ago. I wrote a blog post on it (link below) if you need more information. Basically you can change the email that gets sent based on the input of the form by creating your own webform-mail-[node-id].tpl.php. Within this template you can change the content based on submission data in the $submission variable.

<?php
  if ($submission->data[1]['value'][0] == 'General Application'){
    print 'Thank you for submitting your resumé and covering letter'."\n\n";
  } else {
    print 'Thank you for submitting your resumé and covering letter for the position of '.$submission->data[1]['value'][0]'."\n\n";
  }
 ?>

http://bouncingorange.com/blog/201204/custom-email-templates-webform


In order to add another submit handler you have to add something to hook_form_alter(): check for your particular form ID, and then add a submit handler in one of the following ways:

OPTION 1:

To add a submit handler that is called as the next callback after processing the default submit handler callback you can use this:

function mymodule_form_alter(&$form, &$form_state) {
  if ($form_id == 'form-id-of-your-form') {
    $form['actions']['submit']['#submit'][] = 'mymodule_whatever_function';
  }
}

OPTION 2:

If OPTION 1 is not working for you, replace the third line with this:

form['#submit'][1] = 'mymodule_whatever_function';

This will add a second submit handler, or replace the second one with yours if there is already more than one.

OPTION 3:

To remove the default submit handler completely (so that "nothing will happen" on submit, or so that you can replace it with your own), use code like this:

function mymodule_form_alter(&$form, &$form_state) {
  if ($form_id == 'form-id-of-your-form') {
    unset($form["actions"]['submit']);
  }
}


Add a JOIN with a subquery into a views query

After some work this problem was solved with the Views Field View module.


change customer email address in ubercart

This is a known issue with ubercart. The only way to change it, currently, is to find the order in the uc_orders table, and to update the primary_email field in the record.


There are basicly two alternatives:

Using the Ctoosl Modal module. This module, included on the ctools project, is the most popular way to popup modal forms on Drupal, with lots of addon modules (like modal_forms). Here is a nice tutorial.
Using a custom module. You may find the following modules helpful:

popup_message - which seems well supported.
popup_announcement - this is a new module which seems closer to what you search for, with full html support, but with only a few downloads.

With option 2, you should have to create the form and inject it into the popup using the forms API, so here is a form creation tutorial, and a stackexchange discussion about the best form creation method.


how to find whether a node has more than one revision?

Have you checked node_revision_list($node) function?

  This returns a list of all the existing revision numbers.

You can pass the current node and it will return list of all revisions.


Add a limitations to anonymous user for node view

If cache is enabled hook_nodeapi() is not always executed. The first time a node is viewed Drupal renders the page and save it in the cache. During this process, hook_nodeapi() will be fired. Next time the same page is viewed, Drupal will find the rendered copy in the cache,  serve this copy, and no hook_nodeapi() will be fire fired.

You have to do it in hook_boot. This hook is fired even for cached pages. You must first check if current path is a node path (you may use arg() function). Try to add lightweight code as it will be executed in every page petition.

Remember that this protection is easily bypassed clearing the cookies for your domain.

References

hook_boot()
arg()


try to use node archive module or auto archive module, they give a lot of stuffs to do. you can also type archive in search section in drupal.org nd choose modules to display all kind of modules about archiving.


How to add 'font color' option to Buedit

You can enrich Bueditor by adding buttons to it. You can find some very well written documentation about how to add buttons to the editor in the official bueditor page.

After you have learned how to create buttons, you can use one of the already implemented buttons for text color. You can find a demo and the actual button code here.

The steps that I followed in a clean Drupal 7 installation:

Installed Bueditor
Navigated to Configuration - Content Authoring - Bueditor
Selected a random editor (e.g. Default) and hit "Edit"
Copied the 2 files from the second link in the library folder inside
modules/bueditor
Added the following lines in "Editor specific library files":

%BUEDITOR/library/bue.style.js

%BUEDITOR/library/bue.colorbox.css
I went to the bottom of the page, above the "Save Configuration" button and in the blank button I added a title (i.e. Color), in the "Content" field I added the code from the second link (the code that is marked as: "Button code" (simple copy and paste)
In the place of the icon I just wrote: Color
Now just hit: "Save configuration" and go to the bottom of the page and check in the demo editor how it works.


How to use responsive design with bootstrap views

I think your problem is in using Views grid format. That is table based and not responsive in the way you would want it. Tables can be responsive but in a table way (hiding of columns and inserting sliders etc).

You need to use 'unformatted list' as the format, and then for your 'row class' you need to set appropriate bootstrap col-* classes and you have to get a bootstrap row class in there as well. To do that your best bet is to override the views template files and preprocess functions.

There are plenty tutorials etc available for that on the web.

Bootstrap provides the framework, you just need to make sure your html conforms and that you put the classes you need in the right places. It can be done in views without any major issues.

You should also look at these modules as they definitely will help you (provided you have read the twitter bootstrap documentation and understand at least the basics)

Views Bootstrap, Display Suite Bootstrap Layouts, Panels Bootstrap Layouts


CKEditor not displaying in latest 8.0.x-dev version

Here is the correct code to create a WYSIWYG field:

$fields['title'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('Content'))
  ->setDescription(t('The content of the block'))
  ->setDisplayOptions('form', [
      'type' => 'text_textarea',
    ])
  ->setDisplayOptions('view', [
      'type' => 'text_default',
    ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);


Clearing the cache might help. I had tried to use libraries_flush_caches but that didn't seem to work. General CC did though - that will ensure libraries_load detects and loads the files you put in your files array.

Also, for this library (at least composer version "google/apiclient": "1.0.*@beta") , you want to put 'autoload.php' in your files array - it'll do what it sounds like, auto-load all the classes you want to use instead of you manually having to do it.


Is there a module that provides payment processing but not a shopping cart?

Have you tried some of those ?

lm_paypal:

  This module provides an interface to PayPal using Instant Payment
  Notifications (IPN). It currently supports paid memberships
  (subscriptions), donations (tip jar) and paid adverts (classified
  ads).

Payment API: this one need a specific module for the payment platform

  This module can be used by other modules to collect and track payments. Through this API, any module can provide a payment form and payments can be handled and tracked centrally.

How to build a paid membership site with Drupal 7 (paid module)


/**
 * hook_form_FORM_ID_alter() function implementation.
 * @param unknown_type $form
 * @param unknown_type $form_state

 */
function yourmodule_form_article_node_form_alter(&$form, &$form_state) {
    // Add your own function to the array of validation callbacks
    $form['title'] = array(
            '#type' => 'textarea',
            '#title' => 'Title1',
            '#required' => 1,
    );
    return $form;
}

I have created for article node type. You can use same for other node typw also.
I have used hook_form_FORM_ID_alter() API function.


Load form via ajax and submit by ajax not working

I had the exact same issue:

When the form was on its own page, ajax submit works.

When the form was loaded through ajax, ajax submit didn't work, submit was redirecting the form to its own page.

After unsuccessfully restarting from scratch twice, I tried to implement this ajax modal example: https://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8/

Success one.

Then removing the openModalCommand to simply display the form on the page.

Success two.

I compared both my unsuccessful attempts and the successful one.
There was one difference, in the success one, in the controller the form was built but not rendered.

// Controller to load the form through ajax
public function ajaxSupportTicket() {
    $form = \Drupal::formBuilder()->getForm('Drupal\itportal_support\Form\SupportTicketForm');
    $ajax_response = new \Drupal\Core\Ajax\AjaxResponse();

    // Append the form in the page.
    // The form is sent as is, not rendered
    $ajax_response->addCommand(new \Drupal\Core\Ajax\AppendCommand('#selector', $form));

    return $ajax_response;
}

Now that this works, the whole ajax api of D8 seems very powerful.

Also, try to get rid of your custom javascript to load the form. It can be done using render array. Place a link with use-ajax class.

$output['open_form'] = [
  '#type' => 'link',
  '#title' => $this->t('Open Form'),
  '#url' => Url::fromRoute('mymodule.ajax_form_controller'),
  '#attributes' => [
    'class' => [
      'button',
      'use-ajax',
    ],
  ],
];

// Attach the library for pop-up dialogs/modals.
// drupal.dialog.ajax might be overkill, but I didn't took time to improve
// comments about it are welcome
$output['#attached']['library'][] = 'core/drupal.dialog.ajax';

Hopefully, it can help.


How to use the gmap module withouth a API key?

As suggested in the issue someone opened for the GMap project page, head to this page and follow the steps to obtain a key (Google account required).


Sending system e-mails do not work in spite system says it sends e-mail

If the system log reports it is sent, mostly likely it was sent. Perhaps those mail went to SPAM box? If that is the case, check if you have Reverse DNS set up for your domain.

Besides, you can utilize 3rd party email service (such as Gmail) as your Drupal mail system.
Check out SMTP module.


What step am I missing installing drush with Composer?

Well, actually you installed it locally. You can find it in your project's directory under vendor/drush/drush place (maybe, it depends where the composer put it). You can call only from that place because it's not in your global path. If you want to use this method, you need to call it with an absolute or relative route. Like if your composer installed to here:
On Windows:
D:/phptest/my_project/vendor/drush/drush
On Linux:
~/my_project/vendor/drush/drush
and you are in the D:/phptest/my_project (Windows) or ~/my_project (Linux) dir, in that case, you need to call it like:
On Windows:
vendor/drush/drush --version   OR  D:/phptest/my_project/vendor/drush/drush --version
On Linux:
vendor/drush/drush --version   OR  ~/my_project/vendor/drush/drush --version
and you will get something like:
Drush Version   :  8.1.3
Of course for this, you need a PHP in the global path. (so you need to be able to call PHP from anywhere.)
If you installed it globally with composer (I think you just installed it locally), in that case maybe you need to create a (soft) symlink one place which is globally available for you (listed in the %PATH% variable on windows or in the $PATH variable on Linux), or you need to add the drush's dir to your global path variable.
I suggest you, install it globally, like here is written: https://docs.drush.org/en/8.x/install/
# Browse to https://github.com/drush-ops/drush/releases and download the drush.phar attached to the latest 8.x release.

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

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

# Optional. Enrich the bash startup file with completion and aliases.
drush init

Then you can use it in any site's dir.
TIPP: if you're installing drush launcher (https://github.com/drush-ops/drush-launcher) globally, then you can have per-site base different drush installed. In this case, you don't need to have global drush installed.


Change mailsystem used on webforms on a per email basis

I think you can do this via hook_mail_alter you'll need to write your own implementation but should be possible.

From what I can see in webform.submissions.inc inside webform_submission_send_mail()

// Build the e-mail headers.
    $email['headers'] = theme(array('webform_mail_headers_' . $node->nid, 'webform_mail_headers'), array('node' => $node, 'submission' => $submission, 'email' => $email));

It should be possible to use hook_mail_alter to choose the right submission and also the e-mail address it's being sent to.


How can hook some code before deleting a comment?

Strange enough, but there is no predelete hook present with Drupal 7 core, or even not provided by the entity module.

However the good news is Drupal 8 has this feature!


Grant permission to post a new node of content-type 2 if previous node of his content-type 1 has a state of approved

You can create two Roles.

Role 1 -> has permission to create summary (content type 1)
Role 2 -> has permission to create full article (content type 2)

you can assign Role 1 to users by default.

Next you create a rule like

  Event : Summary gets approved
  Action : Add user role

The way you create the rule depends on whether you are using Workflow Node or Workflow field

If you are using Workflow Node then the rule  will be

  Event : Workflow state has changed
  Condition : Check the state

If you are using Workflow Field then the rule will be

  Event : After updating existing node
  Condition : Do a data comparison for the workflow field with the state ID.

Action will be Add user role, that is Role 2


Just add $vars as second argument.

drupal_get_form('new_form', $vars);

and...

function new_form($form, &$form_state, $vars) {
// ...

Quote from drupal_get_form()

  ... Any additional arguments are passed on to the functions called by drupal_get_form(), including the unique form constructor function. For example, the node_edit form requires that a node object is passed in here when it is called. These are available to implementations of hook_form_alter() and hook_form_FORM_ID_alter() as the array $form_state['build_info']['args'].


Find if the drupal node is published or not published in node_save()

You are looking for $node->status. The Node module defines two constants which you can use instead of 0/1 to make your code more readable:

/**
 * Node is not published.
 */
define('NODE_NOT_PUBLISHED', 0);

/**
 * Node is published.
 */
define('NODE_PUBLISHED', 1);

Example:

if ($node->status == NODE_PUBLISHED) {
  // Node is published.
}

Note that you should not alter node_save(). Instead, implement hook_nodeapi() to do something either before ($op is "presave") or after ($op is "insert"/"update") the node is saved.


header("Location: /") redirect in template file only works if user is logged in. Why?

Output of the tpl files is cached for anonymous users. But only their text output is, that's how Output Control Functions in PHP works. That's why Drupal API functions will not work as intended, either. They may do their job, all right, by serving as cache breakers, but you do not want to break cache on a busy website, as it may be a server killer.

Most stable way of doing temporary redirections is, as far as I found, an .htaccess way. mod_rewrite is already used by Drupal, so it cost you nothing in additional binaries loaded to memory, and it acts before PHP is even started. As described in this answer on SO, you can do this like that:

RewriteRule ^example/my-stuff/$ /example/home/ [L,R=301]

Put it before Drupal redirects, but in the same section.

If you need a PHP logic to decide if redirect is needed, you can do it using hook_menu_alter() instead:

Substitute original callback with yours
Perform any logic needed
Log to watchdog if you want to

Call original callback and return it's result if you are not redirecting, or
Redirect with drupal_goto('<front>')


There is a Drupal 7 version of that module, it's just in dev at the moment.

I think it's highly unlikely someone else will be developing a competing module along side the development of this one.

I'd advise downloading and installing the dev version of the module, if you get any errors report them back to the issue queue to help push it along.

You can actually check the current issue queue to see if there are any known problems that may stop you being able to use this in your new site...at least you'll know as early as possible.


As mentioned in comments if you want it shown everywhere you should untick the Type options, then they apply anyway. And on the Seite delete everything, that should show it everywhere too without restrictions (no need for /*).

But I think your particular configuration isn't working because you have included the /de/ in your path under Seite, the language prefix is not part of the Drupal path. Remove it from there and it should work.

Instead of:

/de/tutorial/erste-schritte

it should say:

/tutorial/erste-schritte

You have the Visibility limited to the German language under the Sprache tab.


How do I disable the taxonomy term page?

A lightweight solution is to simply edit the taxonomy term view :
/admin/structure/views/view/taxonomy_term

... and restrict the access.


Check these variables:

user_mail_register_admin_created_notify
user_mail_register_no_approval_required_notify
user_mail_register_pending_approval_notify
user_mail_status_blocked_notify
user_mail_cancel_confirm_notify
user_mail_status_canceled_notify

Use drush (drush vget user_mail_register_no_approval_required_notify) or install Mail Control; This module provide only interface modifications. The underlying functionality is already there by default in Drupal 7.

You can also drop in settings.php:

$conf['user_mail_register_admin_created_notify'] = FALSE;
$conf['user_mail_register_no_approval_required_notify'] = FALSE;
$conf['user_mail_register_pending_approval_notify'] = FALSE;
$conf['user_mail_status_activated_notify'] = FALSE;
$conf['user_mail_status_blocked_notify'] = FALSE;
$conf['user_mail_cancel_confirm_notify'] = FALSE;
$conf['user_mail_status_canceled_notify'] = FALSE;


I found a neat little module the other day called Message Close which once installed, adds a simple close icon to every message, whether status or vaildation. It also resets all margins and padding so once a message is closed, the page looks exactly as it does on a fresh load.

In the js of the module, you can use jquery to make the message fade out, or slide out.

This would be perfect for closing webform validation messages without needing a page reload.


In Views, how to wrap a div around every specified number of items

In the View, there is a Theme: Information Link under the Advanced Tab. There you can theme your view with template files the way you like.


Why doesn't this Views 3 contextual filter work?

In order to play nicely with other modules, views will not override any aliases that point to something already. You're trying to make a view show up on an alias that is already pointing to a standard drupal full page node. This simply will not work.

Options:

Stop giving aliases to press release nodes so they are only available at node/nid
Use a different path for your view so it doesn't conflict with your nodes
Use Panels to override your full node page and show that view

Some other things to consider
A view is really useful for display a list of things, you should probably consider not using it as a node page in this way. You can get a lot of control over your page layout using the standard display tools Drupal 7 gives you.

Using Content: Nid as a contextual filter will not recognize a url in the form of press-releases/name-of-article. You would need to use Content: Title. You also don't need to specify the raw url value as a default value or add % in your view path. The order in which the contextual filters are configured are the order in which they are pulled from the URL.


If that's your code, transform it into Drupal custom module. If you want use PHP API delivered by external service - transform it into library (move code into  sites/all/libraries/yourLibrary) and write custom module which loads files on demand (with Libraries API).


Tutorial for creating website using existing MySQL db?

It's not too hard. Assuming Drupal 7 and a one-time import:

Create a new content type in Drupal with the fields you want
Export a CSV file of your records with a header row from your legacy database with the fields you want.
Use Feeds to import the csv file.  You will setup a mapping between the csv fields and your content types fields (from within the Drupal UI).  This is pretty straightforward and the feeds module guides you through it.
Feeds will create one node per record (line) in your csv file.

Now if you will continue to use your existing database and want to import new records as they are added, I believe Feeds has some support for this but I haven't personally used it.


Commerce multiple stores and multiple carts for B2B customers

According to the Commerce 2 documentation, stores are optimized for two use cases:

  We optimize for the two use cases:

  One business that has one or more locations or 2. The marketplace
  model (where you have sellers)

  One or more locations This is the most common eCommerce situation where we have a single person, company, or organization that is taking
  payments online.

  Marketplace model The marketplace model is where you have many sellers who are taking payment for unique products.

Each store can have a different currency, payment method, order flow, and so on.  So, each store also has a separate, unique cart.

It seems there are two ways to do what you want.

Keep two different stores, one for B2B and one for B2C.  If the configuration is mostly the same, you will have to duplicate a lot of config between the two stores.  You will also need to keep the two stores separate so that B2B customers see the B2B store and B2C customers see the B2C store.
Just have one store.  Add a select field to the products for admin to indicate whether it is a B2B product, B2C product, or both.  Then, modify the views that show the products so that B2B customers see B2B products and B2C customers see B2C products.  This way, you don't have to duplicate the config for the payment flow and so on.


drupal 7 + services 3 - inserting nodes with select fields

Eventually I figured this out:

    {
    "title": "some more tests",
    "type": "weed",
    "field_sprouts": {
        "und": [ 8,9 ]
    },
    "field_urgency": {
        "en": [
            {
                "value": "2"
            }
        ]
    },
    "field_species": {
        "und": [ 4 ]
    }
 }

species and sprouts are entity references and only need the nid of the target (no value= or target_id= or anything).
For unknown reason (as of yet), the urgency field required a language to be defined (other then und[efined]). Its the only select field here with a normal select list, not entity refernce.
Make sure your widgets are select list and not auto complete.


Calendar popup field get a default value. How to avoid this?

Edit the date field in your Content Type.  There should be a MORE SETTINGS AND VALUES accordion that drops down to reveal more options including DEFAULT VALUES.  Set the default value to No Default Value.  You probably have it set to Now.


Do purchased themes need to be fully built from the ground up?

where did you buy the theme from? Do they provide installation instructions or usage instructions? Did it ship with any additional modules to enable configuration?

A theme is basically styled blocks, views, nodes, regions. You need to place your content into Regions of the theme for it to show up like their example.


save base64 images alogside entity creation

It works after getting file mime type here is the code sample

$data = base64_decode($args[1]['avatar']);
$finfo = finfo_open();
        $mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
        finfo_close($finfo);
        // get file type png. jpg
        $ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
        $file_name = str_replace(' ', '-', $args[1]['name']);

then you we save the file using

$file = file_save_data($data, 'public://users/'.$file_name.'.'.$ext, FILE_EXISTS_REPLACE);

    $args[1]['field_field_user_picture'] = array(
        'fid' => $file->fid,
        'width' => 100,
        'height' => 100,
        'alt' => $args[1]['name'],
        'title' => $args[1]['name']
    );


What is the alternative for user_check_password in drupal 8

$uid = \Drupal::service('user.auth')->authenticate('testusername', 'testpassword');

if ($uid) {
// do stuff
 }


The media field is an entity reference type field.  You will need to add a relationship to the media entity.  This should add the URI field in media entity to the view selections.  You should then be able to select this (with the right reference relationship) and use the standard URL formatters.


Username converted to us-ascii (unix-style)

If you only want to transliterate non-ASCII European characters (like those used in Nordic, German and French names), you can use the PHP function strtr. E.g:

$name = strtr($name,
   'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ',
   'AAAAAAACEEEEIIIIDNOOOOOOUUUUYTsaaaaaaaceeeeiiiidnoooooouuuuyty');

If you want to do romanization of a wider range of non-ASCII alphabets (cyrillic, greek, etc.) take a look at the contributed project Transliteration.

While this is specifically to transliterate file names to US-ASCII, at its core is UTF-8 normalization (based on UtfNormal.php from MediaWiki) and transliteration (based upon Sean M. Burke's Text::Unidecode).  You should be able to use the same libraries for romanization of names and other strings.


The settings for the clean URLs are at admin/config/search/clean-urls.
That page shows the "Enable clean URLs" checkbox only when it is possible to enable them; when the server is not configured to support them, that page shows the following message:

  Clean URLs cannot be enabled. If you are directed to this page or to a Page not found (404) error after testing for clean URLs, see the online handbook.

On an Apache server, and with the default settings used from Drupal, clean URLs work if:

The mod_rewrite module is enabled for the server
The following directives are present in the Apache configuration file

AllowOverride All
AccessFileName .htaccess


Custom widget field only saves first letter, disappears on edit

It may help to just wrap the returned array from the _field_widget_form in yet another array

return array('anything' => $element);

Worked for me ;)


Productivity tool to help me add multiple fields at once

Just wondering about the use case for hundreds of fields - this seems a bit bizarre. Maybe consider using Field Collections to group similar fields and combine with use multiple values per field on a field collection.

As for a possible solution (although not recommended since a lot of things could go wrong) - if you have many similar fields you could export some "base" fields using features and copy-paste inside the features' files the relevant fields. Clearing cache or feature-revert would create the relevant fields.


_preprocess_views_view not getting called

Ok. Then, we have to consider the following possibilities:

The name of the function is bad typed. The structure for this case should be template_preprocess_HOOK(&$variables). The second part (_preprocces) and third part (_views_view) is well typed, but are you sure the first part is well typed? I assume that "bootstrap" is the name of your theme.
This template hasn't been called when you visit the page, for example, if the pages have been stored in cache_page table for anonymous users. Another possibility could be that a different template has been called.


How do I get the Google Analytics module settings to show up? I am unable to configure

The path is admin/config/system/googleanalytics

There is post about this on https://www.drupal.org/node/1510436

Comment number 17 states a fix

  But after uninstalling--> run cron--> clear caches--> reinstalling-->
  run cron--> clear caches the configuration page appeared, voilà!

Also don't forget to run update.php afte you install a module en clear your caches


Using modules with almost similar functionality together on production site

Yes, there's always a possibility that modules will be incompatible with other modules that do the same thing.

There's also the possibility that modules whose functionality is completely unrelated will be incompatible with one another. Such is the nature of a modularly extensible system.

The only way you'll know is if:

The documentation for one or more modules list their known issues with other modules, or
You thoroughly test the two modules while both installed on a single site


Controlling access to documents for specific users

A possible (but somewhat convoluted) solution could be to use Node access user reference module with private files setup. Basically adding a user reference to a node will allow them to see its content (including files) and having files' folder protected will prevent direct access to the file urls.


Is it possible to provide content editor ability to create sortable table?

You can use TableField module to create table that is a real html table. Sorting is currently unsupported, sadly, although it would be wonderful.

If all you need is sorting on display, you can create a patch or your own module, and implement one of the jQuery plugins for sorting. Personally I found tablesorter to work pretty OK.


How to create nodes from shell script at server?

If you are going to start scripting on the command line, you can always script a php script and run it via drush. That way, you have access to your Drupal system and data. For example, if you place the following code in a file, e.g. script_create_node.php:

<?php

// Expect title as $args[1] and body as $args[2]
if( !isset($args[1]) || trim($args[1]) == '' || !isset($args[2]) || trim($args[2]) == '') {
  print "Expecting two arguments on the command line, title and body, for the new article\n";
  exit;
}

$node = new stdClass();  // Create a new node object
$node->type = 'article';  // Content type
$node->language = LANGUAGE_NONE;  // Or e.g. 'en' if locale is enabled
node_object_prepare($node);  //Set some default values

$node->title = $args[1];
$node->body[$node->language][0]['value'] = $args[2];

$node->status = 1;   // (1 or 0): published or unpublished
$node->promote = 0;  // (1 or 0): promoted to front page or not
$node->sticky = 0;  // (1 or 0): sticky at top of lists or not
$node->comment = 1;  // 2 = comments open, 1 = comments closed, 0 = comments hidden
// Add author of the node
$node->uid = 1;

// Save the node
node_save($node);

you can always call this on the terminal like this:

drush scr script_create_node.php "Article Title" "Article Body"

You can extend such a script to include the logic you would use in your shell script, but instead of writing to a CSV file, you can write directly to the database. It's a great advantage having both PHP-CLI and a bootstrapped Drupal available at the same time.

Hope this helps some!

P.S: Lots of pages out there answering the question "programmatically creating nodes", one random pick would be http://www.group42.ca/creating_and_updating_nodes_programmatically_in_drupal_7


I use Storage API for this sort of thing with S3 and cloudfront. I think it supports custom sub domains. It handles all the replication (copying,moving, deleting) itself. I have had a couple of minor compatibility issues with other contrib modules during upgrades.

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


Wrap a single html tag around each block that's generated from a single view

The answer suggested by madhurjya is correct, but I would point out that it is possible to create a template that is applied to all block displays of a certain view. E.g. for a view Blog with Unformatted type of output you can use views-view-unformatted--blog--block.tpl.php to alter all blocks only from that view.

Explore the Theme:Information in the Advanced settings of a view to see all your options.


Just install the Views PHP module and you can now add a "Global: PHP field" to your views that can include PHP code. Quote from its project page:

This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.
Note: While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly
advisable to use regular handlers and plugins when available (or even
to create one yourself). Take note that filtering and sorting a view
using PHP always has a considerable perfomance impact.


Maybe I'm not understanding your question. You can globally change all metatag information at /admin/config/search/metatags. To change the meta information on a per-node basis, edit the node and click on the Meta Tags tab at the bottom. You can then update the meta information for that specific node:


Migrate row data into text formatted long multiple

There is a plugin named iterator which allows iterate a list of associative fields to a compound field.
Example:
field_formatted:
      plugin: iterator
      source:
        - fieldA
        - fieldB
      process:
        value: value
        format:
          plugin: default_value
          default_value: 'full_html'

In this case the fields should have this structure
    [
      'fieldA' => [
         'value' => 'Chicken',
      ],
    ]

Can you fields you adapt your source fields to use iterator plugin in this way?


Try this out

use Drupal\Core\Database\Database;

$connection = Database::getConnection();
  //- Step one get all referenced nids
  $query = $connection->select('node_field_data', 'nfd')
    ->fields('nfd', ['nid', 'created']);
   $query->innerJoin('node__field_ils_apps', 'app', 'nfd.nid = app.entity_id');
  $query->orderBy('created', 'DESC');
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);


Why theme scripts.js is not working, how to attach it

What you're trying to do is not valid jQuery code. You missed the .each part.

So use $(context).find('.block-offer42-branding').each(function () {


Your settings are messed up somehow. I'd suggest looking into the multi-site capability to keep things straight.

You would create directories for live and test under /sites. Assuming example.com and test.example.com are your site:

/sites
    /example.com
        settings.php    # connection details for your live database

    /test.example.com
        settings.php    # connection details for your test database

    /example.local
        settings.php    # (optional) details for local development environment

Under this scheme, when you browse http://example.com, Drupal will look for the database settings in /sites/example.com/settings.php. When you browse http://test.example.com, Drupal will look in /sites/test.example.com/settings.php and so on.

An alternative would be to use environment variables set in you Apache or Nginx configuration. You would then use the PHP getenv() function to access the values. This approach would be a little bit harder to set up and troubleshoot.


Display Exposed Filter value of selected exposed filter

You have a couple of options here Rituraj.

You'd need to use PHP to output the selected values in the header. See the related example here to see how to output view filter values to a template.

<?php
$view = views_get_current_view();

if(isset($view->exposed_input['field_release_date_value']['value']['year'])) {
  echo "
Press Releases for ", $view->exposed_input['field_release_date_value']['value']['year']; "
";
}
else {
  echo  "
Press Releases for ", date("Y"); "
";
}
?>

This post has an example for using an exposed filter value to override the page title as well.

My preferred method would be to use JQuery to read updates from the exposed filter and inject them into the DOM. That would have the added bonus of making it easy for you to wire up the X links to remove both the value both from the display and from the exposed filter.


Group by your Category taxonomy and select to Use rendered output to group rows, then in your Filter criteria for your taxonomy turn on autocomplete of the category terms.

Add View

View Settings: Show Content of type Course sorted by Newest first
Page Settings: Create a page selected
Page Display Settings: Display format Unformatted list of fields

note: you may not want to use the pager.

Edit new View

Advanced:

Relationships: add Relate nodes to taxonomy terms with Vocabularies {Taxonomy} selected and Require this relationship selected
Use aggregation: Selected

Fields: add content: ID, Content: Title, Content: {Taxonomy}

Content: ID: Exclude from display selected, Thousands marker: -None-
Content: ID Aggregation settings: Aggregation type: Count DISTINCT
Content: Title: Formatter Plain text and Link to the Content selected
Content: {Taxonomy}: Exclude from display selected

Format:

Format settings: Grouping field Nr.1 Content: {Taxonomy} and Use rendered output to group rows selected

Filter Criteria: add Content: Title and Content: {taxonomy}

Content: Title: Expose this filter to visitors, to allow them to change it selected and Operator Contains
Content: {Taxonomy}: Expose this filter to visitors, to allow them to change it selected and Operator Is one of
Content: {Taxonomy} settings: Vocabulary {Taxonomy} and Selection type Autocomplete

Sort Criteria: Content: {Taxonomy} (asc), Content: Title (asc), Content: Authored on (desc)

Note: the preview will not display the Grouping titles, but this dose appear on the page.


Drupal substracts 2 hours from the CCK date field when saving. Why?

In Drupal 6 at least, you would go to admin/settings/date-time to check the default timezone of Drupal. I'd check to see if that's set correctly.  If it is, then you have to check if user configurable timezones are enabled, and if so, check what you or the logged in user has set in his/her account against all of the above.


Create test and development copy of a production site

You have a problem with your settings.php file.

Check if the name is correct.
Check if the database is set correctly.
Try to access in command Line to the database.
Check rights of your files.
Try to clear the cache with drush cr.


Why isn't  the node ID available as "replacement pattern" for the title link?

You've to add the nid field and exclude it from display, after your NID must be before your title and you'll have access to it.

Even, if is not right, normally you'll have it.


Print {{ node.body.value }} in node--content-type.twig missing figure and figcaption tag of image

This is my code to corrected it:

<p>{{ content|without('body') }}</p> <!--Other fields in Full content mode-->
{{ content.body }} <!--This is body field. Don't forget config show it in Full content mode-->

If someone has a better solution please help me! Sorry my English not good.


How to add db_select condition by using two concatenated fields?

You can try something like the following. You build the name with a small sql expression and then can use it within the where clause.

$select = db_select('people_table', 'p');
$select->addField('id');
$select->addExpression("CONCAT(p.first_name, ' ', p.last_name)", 'full_name');
$select->condition('p.full_name', $some_name, 'LIKE');
$results = $select->execute();


Error - Sharing the Same URL for two different views in exposed filter

You can use Views Glossary to create a glossary that is grouped alphabetically, and then add an exposed filter to search by Keyword.

Enabling the module provides you with an example view that you can clone and modify to get the functionality you need.

Clone the view "Views Glossary Example" to create your /glossary view
Add your exposed filter for your keyword search.
Open contextual filters and change the Title filter to "Display all results for the specified field" when the filter value is not in the URL. If you don't do this, the view will only display results for 'A' when no letter is selected.

This will allow users to simultaneously search the glossary using keywords and/or filter the glossary alphabetically.


Do I need to sanitize a user input textfield used in a mail body?

There are two reasons to use Drupal's text filtering system: security and proper formatting of the information for the context.

In reverse order:

For formatting: if you use something like the markdown filter or limit with html tags can be used for simple sanity (i.e. no h1) then you want to use a filter that removes that.
For security: you want to remove malicious code if it is being displayed in an environment where that matters. In the case of email, the relevant DOM is the email client which can sometimes be a domain. However, if it is a security weakness to that email user to get javascript...that is a problem with their client. Since anyone can send any email to any address with any (malformed) contents it is not a major consideration of e-mail processing to ensure the body is "safe" (without scripts). See this discussion on g.d.o/security about sanitizing text in email bodies

That said, you don't want your system to be useful for spam.

Consider using the flood_control system.
Consider adding an introduction and closure to your email message to make it less useful for a spammer. For example "This email was sent from example.com. Your friend said: _stuff_here_. If you have questions contact your friend and not example.com"

There is more to e-mail than the body, of course. E-mail headers can be a vector for attacks, since someone can use a newline as part of the "to" address and then append new headers to send as many mails as they want to whomever they want, pretending to be from whoever they want, hurting your domain's reputation in the process.

One other side-note:

  The textfield is saved in the database, and I rely on the Form API to
  protect against SQL injection.

SQL Injection protection should come from proper use of methods and arguments in your db_insert or db_query function. It does not come from the Form API.


To alter the query itself, try hook_search_api_query_alter (for search api) or hook_search_execute for the core search


There's no such thing - cron always runs as the anonymous user.

This is forced by the drupal_cron_run() function in Drupal 7:

// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user();

and Cron::run in Drupal 8:

// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$this->accountSwitcher
  ->switchTo(new AnonymousUserSession());


The Drupal way

In Drupal we create similar form like this:

Create a custom module

Create a file sites/all/modules/own/form_test/form_test.info with this in it:

name = form_test
description = form_test
core = 7.x
package = Own
Create a file sites/all/modules/own/form_test/form_test.module

(start it with <?php tag, but don't add ending ?> tag)

Write these functions in your module:

function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Form Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => TRUE,
    );
  return $items;
}

An explanation

form_test_menu
creates a menu item in your navigation menu so we can have a place where to show our custom form. You can think that menu address referring to a page yoursite/formtest.

title

Title of the page.

page callback

Calls a function drupal_get_form which returns a render array for drupal_render().

page arguments

Here we pass our custom render array (which form_test_form returns) as an argument for drupal_get_form.

access callback

We define it TRUE so that everyone can access this page.

(Rendering means turning a structured array into HTML.)

function form_test_form($form,&$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

An explanation

So we use render arrays to describe a form in drupal.

When you use a function to return a render array for drupal_get_form, there are two default parameters that are in use:

$form   Holds the form array items we define inside the function when this function is called again.

&$form_submit   This parameter holds various data items like the values you pass when you submit the form.

(Ampersand & means that this is a reference to a variable, so if we change this variable in this function, changes will show in the parent function too.)

Form items are added as arrays to the $form variable. Hash (#) sign refers to an attribute of the item.

Enable the module in admin/modules

Flush the caches

Form can be seen in yoursite/formtest, but it doesn't do anything yet.

OR
more links are :

Drupal 7 - How to Make a Simple Module with a Form and Menu Link

Ten Step-by-Step Code Samples for Learning Form API


Restrict Menu Item from anonymous users and redirect to Login page

Create a custom module
In your_custom.module

function custom_init(){
global $user;
$current_path = request_path();
if (!in_array(array('your roles','your roles'),$user->roles) && $current_path=="node/add/yourcontent type" ) {
  // for mutiple row
  drupal_goto('/user');
}
}


Entity reference field to show translation of nodes

I am not sure if you have already taken care of this but I think you would need to add title module as well since the title is not an entity by default and wont work with the entity translation module.

Another thing would to keep the language as neutral rather than keeping it English. Internally drupal would fetch the nodes with the lan


Better exposed filters allows only one checkbox at a time

Follow the steps:

go to advanced tab.
Under exposed form section, go to exposed form style setting. (BEF settings).
Then under display option of your checkbox field, expand more options and check add select all/none option.
Uncheck autosubmit option if checked.


What's wrong with my GET request? (Commerce Services, REST)

From what I understand, querying only works on entity properties. That is why status works, commerce_price is a field and won't work. Checkout Services Entity API, it may do what you're looking for.

You may still be out of luck though. You alternatives will be to use services_views or write your own Services Resource.


Generating Main content nodes based on SQL data (associated with users)

From what i have understood about the problem you are facing, i believe its advised using the content type for profile as well as the votes. Here is the CCK field to use the vote field.
https://www.drupal.org/project/rate
It would be very easy for you to create view if all fields are part of content types.


A possible explanation for your problem might be because of your "language detection" configuration.

Check this configuration via Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.


Your page callback is drupal_get_form, and your page argument is _mymodule_confirm_offline, so the call Drupal makes is drupal_get_form('_mymodule_confirm_offline');, which doesn't at all seem to be what you want to do.

What you need is a custom callback instead.

In hook_menu:

'page callback' => '_confirmation_form_page',
'page arguments' => array(1, 3),

And then

function _confirmation_form_page($node) {
  $question = t('Take fiche offline. ');

  return confirm_form($form, $question, 'node/' . $node->nid, t('You\'re about to depublish this fiche. <br />Are you sure you want to depublish this fiche?'), t('Yes'), t('Cancel'));
}

In order to "auto-load" an object from the url, it needs to be named, otherwise Drupal can't know how to perform the load. On a url like "node/%nid", the argument is named "nid". In reality the argument would usually be called %node, but I wanted to distinguish the parts. Drupal will then look for a function called load_nid, pass the number from the URL in, and this function is responsible for returning the fully loaded object. Core has a "load_node" function, so arguments named %node will be auto-loaded without further effort from your part.

To add autoloading into your callback then, you need

$items['node/%node/revisions/%/offline'] = array(

However, this will still only give you the right node, not the right revision. node_load() supports a second argument, $vid, that we need to use to get the right revision. Telling Drupal to pass on extra arguments is used with the load arguments key, and we need to use the fourth argument from the url node/%node/revision/%/offline for this.

So in conclusion, the hook_menu implementation becomes:

$items['node/%node/revisions/%/offline'] = array(
  'title' => 'Offline',
  'description' => 'Confirm the action "Fiche offline".',
  'page callback' => '_confirmation_form_page',
  'page arguments' => array(1),
  'load arguments' => array(3),
);
return $items;


In Views, how can I use the rewrite text to include an image in HTML with some text and then translate the text?

I hit upon a very straightforward solution for doing this-- simply add each field that needs to be rewritten twice.  Place the IMG tag in one field and the string to translate in the other.  This way, no custom code need be written and everything can stay in Views.


How do you remove N/A from radio button groups?

If you make a list field mandatory, the N/A option automatically goes away

Also, if you allow multiple values, the radio dot elements automatically becomes checkboxes.


How to print uc-auction-bid-table-form seperately in product node template using ubercart?

In your module which implements hook_node_view, to accomplish this, do something along these lines:

   function module_node_view($node, $view_mode, $langcode) {
      // Do business logic here like if these node should have the form then...
      $node->content['your_from'] = array(
        '#markup' => drupal_render(drupal_get_form('uc_auction_bid_table_form')),
        '#weight' => 10,
        // you may or may not need this based on your implementation : '#theme' => 'theme_uc_auction_bid_table',
      );
    }

Drupal 6: use hook_nodeapi

function modulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'view':
      // Do business logic here like if these node should have the form then...
      $node->content['uc_auction_bid_table'] = array(
        // Try drupal_render if theme does not work
       '#value' => theme('uc_auction_bid_table', drupal_get_form('uc_auction_bid_table_form')),
        '#weight' => 10,
      );
      break;
  }
}


OK, it was me, I have not provided the specific view display, and the "default" did not work. No wonder. Sometimes asking a question in the air makes the answers come along magically.


The first thing I would say is that it sounds as if you have node references going both ways. This is generally a bad thing in terms of database structures. In this case you should only have inspections pointing at cars and use reverse references if you need to do the opposite.

Anyway here's what I would do:

A view based on inspections, filter the content type to inspections only and also filter the date. That gives you all the old inspections.

Put the Car Node Ref into the field list and then Group By that field (Group By is under View > Advanced > Use aggregation)

You could then add a relationship based on the Car Node Ref which then gives you access to the individual Car fields.

This will give you one row per car for inspections older than [whatever you choose].

My only concern then is whether you might get a car which has inspections for >2 years ago and also more recent ones. So will appear in the list even though it has more recent ones.


Commerce Kickstart Facet Displays Item Count Even With Option Disabled

You have to configure the settings under vocabulary, go to admin/structure/taxonomy/product_category/edit and then uncheck the Display number of items that's it, it will not show you the count anymore.


Linked entity references in a content type

Actually, while looking at the hierarchical_select module, I found a module which is (almost) working - the "Dynamic dependent fields" module.

It does not work yet with multiple values though.


OK, I found it myself. The trick was to turn on AJAX (for some weird reason).


How to theme PDF generated by Print module?

You should on your creation of node call a function which will generate a pdf.
Use tcpdf class for it generate pdf and download  tcpdf functions./
Check also the link

 class my_pdf extends TCPDF { //Page header public function Header() { } // Page footer public function Footer() { } }

$pdf = new my_pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, UTF-8', false);

$pdf->setPrintHeader(true);
 $pdf->setPrintFooter(true);
$pdf->SetMargins(25.0, 40, 25.0);
$pdf->SetFooterMargin(1.5);
$pdf->SetAutoPageBreak(TRUE, 50);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->lastPage();
$pdf->Output('my_document.pdf', 'D');


How can I make my site stop adding  tags in textareas?

Sounds like maybe you need to disable the "Convert line breaks into HTML (i.e.
 and
)" filter on your Full HTML text format.

This can be done by navigating to Configuration > Content authoring > Text formats and editors, then editing the Full HTML configuration and un-checking the box for "Convert line breaks into HTML (i.e.
 and
)" under "Enabled filters". Assuming this is Drupal 8 anyway. Drupal 7 has the same setting but the exact location might be different.


I needed the same thing and couldn't get Commerce Extra Login to do it.

Fortunately, there's Commerce Checkout Redirect which does the trick:

  This module redirects anonymous users to a page where they can login or create a new account when they try to checkout. After the user logs in or registers, he is redirected to the checkout in order to finalize his order.


including js through module info file is not working

The problem is with a typo in the info file. It's missing a "=" on the version line.
Correct info file here:

name = custom
description = custom module

core = 7.x
version = 7.x-0.1

scripts[] = custom.js

Also note that the version properties is discouraged


How do I properly pass taxonomy term from panels to the context filter in views?

it depends how you are trying to get the taxonomy term, but here is one solution. In my example I'm using a node as my context, and a taxonomy field of that node as the contextual argument.

There are basically two things you need to get this to work. One, you need to use view panes, so you can get the arguments from the panels context.

How can I show a view in panel with argument in drupal 7

Second, if your trying to get the taxonomy term from a field you need to convert the term to a term id using validation.

Views contextual filters taxonomy name

For instance this would work if you were trying to create a panel that diplayed a node, and a view of content related by a certain taxonomy term that that node belongs to.


How to use hook_views_query_alter to catch last DELTA of a multivalue date field?

This can be done with HOOK_views_query_alter(). Add all the fields as normal within the views UI, including filtering on the date field value. Make sure the entity ID is in there (in your case, nid is in the query) and the date's delta field.

Next, add a WHERE clause on the delta in hook_views_query_alter() using add_where_expression():

function MODULE_views_query_alter(&$view, &$query) {
  // Check for correct view
  if ($view->name == 'view_name' && $view->current_display == 'display_name') {
    $query->add_where_expression(0, 'field_data_field_period.delta = (SELECT MAX(field_data_field_period.delta) from field_data_field_period WHERE entity_id = nid)');
  }
}

This assumes the filter should be in the first filter group (0).

References:

https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7.x-3.x

https://api.drupal.org/api/views/plugins!views_plugin_query_default.inc/function/views_plugin_query_default%3A%3Aadd_where_expression/7.x-3.x


For your first question:

Redirect module integrated with views module, just navigate to admin/structure/views and you will see View called Redirects, enable it if it's not enabled, then pick the field you want, source field label is 'Source redirect' and from is redirect URL.

You can also create a new your view just be sure you using the base table or redirect

For the second question:

you need first to understand how redirect module structured.

Each redirect record you see is an entity, and it has the following fields:

rid: Primary Key: Unique redirect ID.
hash: A unique hash based on source, source_options, and language.
type: The redirect type; if the value is 'redirect' it is a normal redirect handled by the module.
uid: The {users}.uid of the user who created the redirect.
source: The source path to redirect from.
source_options: A serialized array of source options.
redirect: The destination path to redirect to.
redirect_options: A serialized array of redirect options.
language: The language this redirect is for; if blank, the alias will be used for unknown languages.
status_code: The HTTP status code to use for the redirect.
count: The number of times the redirect has been used.
access: The timestamp of when the redirect was last accessed.
status: Boolean indicating whether the redirect is enabled (visible to non-administrators).

As you see from the structure, there is no reference to the entity you added the redirect for; you have only a reference for the user who creates the redirect.

You can create a relation between the redirect and the user who creates the redirect, then get the nodes which authored by that user; Then you can adjust the views in the way you want.

Please notice this would work with nodes and with any entity store uid, but for example, in Taxonomy case it won't work because taxonomy entity doesn't store the uid.

another tip might help a bit is to add the redirect URL as a filter then make some string comparison.


Anonymous access to paid downloads using unique link

Drupal commerce has a permission to complete the checkout process, that might be your issue there, check the permissions page (admin/people/permissions) and grant anonymous users the "access checkout" permission


How to set the permission for particular role user to access the user profiles of users with a particular role?

You can make a template file for your profile content type, probably called something like node_profile.tpl.

At the top of this file, write some code that will get the user object of the node owner, and check this against user's roles in $user->roles.

It's easier if you do this with the roleID numbers (you can see these by going to user>role and hovering your mouse over the various links for the roles - the roleID appears as a number somewhere in the link).

Your code in the template then may look something like this.  You'll need to know php to understand how it executes.

$userRoles = $GLOBALS['user']->roles;
$account = user_load($node->nid);
if(!empty($userRoles[2])) {
  // user is a company user
  if(!empty($account->roles[2])) {
    // profile belongs to a company user
    print 'Company users are only allowed to see business user profiles';
    return; // this will stop execution of the template file, and return to the page template
  } elseif(!empty($account->roles[1])) {
    // profile belongs to a business user
    // do nothing - just continue code execution of this template
  }
}

For your listings of users, you'll want to make three different views, with views filters in each to determine which users you want displayed.  For this, you can create a page which chooses the name of the view based on the user's role(s) - either a "page" with the php code in the body (if you have php code as one of your input types), or else a page you create with a small custom module using hook_menu().


I use direct input parameter for right filtering, and it is working for me.

$view = Views::getView('my_view_name');
$view->setDisplay('display_name_from_my_view');
$view->setArguments([ $value1, $value2 ]);
$view->execute();

So, i can take result of $view by

$result = [];
if (empty($view->build_info['fail']) and empty($view->build_info['denied'])) {
    $result = $view->result;
}

After this I can render it or use for another goal.


how to remember results of a views query in rules

As a possible alternative to make this work (instead of using Views Rules), you may want to give it a try to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

Load the VBO list that you want to be processed.
Add a loop to perform a Rules Action, for each row contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

To actually trigger such Rules Action, you should be able to use a Rules Event like "... when the user requests it using a flag." (as in your question).


Read Drupal 7 Template (Theme Hook) Suggestions

  A theme hook suggestions is an alternate template (.tpl.php) file that
  you have created to override the base or original template file.

The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:

page--node--edit.tpl.php

page--node--1.tpl.php

page--node.tpl.php

page.tpl.php

Read Theming Drupal 6 and 7

If you still want to alter the suggestions its possible with template_preprocess_page

function template_preprocess_page(&$variables) {
  $variables['theme_hook_suggestions'][] = "page--type--" . $vars['node']->type;
  // likewise you can do
  // $variables['theme_hook_suggestions'][] = "page".GET-URL-ALIAS-HERE;
}


Used Finder module as separate input box for people to check for existing titles.


Translatable image field gets replaced when adding content

By default only the image alt and title are translatable and the file itself isn't. By the default the file is always the same in all languages. You can simply make the file to be translatable as well under https://example.com/admin/config/regional/content-language.

Note: After you've done this, all your existing translations will need to have the file re-uploaded (or a new file uploaded), as the default only gets added once when translating content through the UI.

Taken the above Hero image field this can be done manually be editing field.field.node.page.field_hero_image.yml (which translates to field.field.ENTITY_TYPE.BUNDLE.FIELD_NAME.yml):

Before file checked:

third_party_settings:
  content_translation:
    translation_sync:
      alt: alt
      title: title
      file: '0'

After file checked (alt and title are mandatory if file is checked, that's why they have '0' now):

third_party_settings:
  content_translation:
    translation_sync:
      file: file
      alt: '0'
      title: '0'


Content node migration to user profile in Drupal 6

I'm assuming you're wanting to create new user accounts with these profile nodes, not migrate existing users linked to these profiles. Since you're using a custom node type and not core profile or Content Profile, there are many pre-existing solutions not available.

If these author nodes are constantly changing and you need to maintain periodic synchronization before you're ready to launch, you can set a custom class with the Migration framework. This requires some work so it might be overkill here.

More than likely, I'd say the best solution is probably the User Import module with data fed in via Views Data Export from your existing D6 site. You can create a view of your profile nodes, export it to CSV, and use that as a base to create all your new user accounts with the User Import module.


I am adding an answer so anyone who comes across this that i was able to resolve the issue. I had to use mymodule_preprocess_eck_entity(&$vars).

When i tried to use the machine name in place of eck_entity, it did not work.


Getting latest entity data from the database

You can clear the cached entity in memory to get the latest field values:
\Drupal::entityTypeManager()->getStorage('paragraph')->resetCache([477]);

See Referenced entities show old value when changing properties


You don't want to use [field_team_image] in the src ,just put the [field_team_image] you can get the image and print $data in views custom php field to get the another image to get the url.


There is one central problem: the active class is not always added in PHP, but
for non-anonymous users its calculated using some javascript, see "active-link.js".
For anonymous users, its calculated in
\Drupal\system\Controller\SystemController::setLinkActiveClass


How do I modify the HTML of my subtheme?

A sub theme inherits its templates from the base theme. When you want to edit templates for your sub theme you simply copy over the desired template from the base theme's template folder into your sub theme's template folder, flush the cache and start editing it.

And then flush the cache again.


"File not found error" when installing using composer

Yes, it turns out it was an Nginx configuration problem. In my docker-compose.yml file i have:

web:
  volumes:
    - '/server/path/to/html:/usr/share/nginx/html'

php:
  volumes:
    - '/server/path/to/html:/var/www/html'

In my site.conf file, i had:

fastcgi_param SCRIPT_FILENAME project/$fastcgi_script_name;

Not sure why this worked for the initial php files i tested but then failed during the installation. Changing this line to the full path as follows solved the problem for me:

fastcgi_param SCRIPT_FILENAME /var/www/html/project/$fastcgi_script_name;


You can override the template file that outputs your SOLR items with a check for a set image field.

This type of check is generally ok to use in a template file:

<?php if(isset($item['image'])): ?>
  <?php print render($item); ?>
<?php endif; ?>


How can I create a collapsible block from page content using .tpl file?

i'm pretty sure all the core js and css files should handle both the collapsing and styling of the fieldset. you could simply add the fieldset into your code. however, if it is not added in by default for some reason you can use the following addition to your function code.

drupal_add_js('misc/collapse.js');
drupal_add_js('misc/form.js')

Below should be an opened fieldset example.

    <?php print $description; ?>

    <?php foreach ($albums as $key => $album) : ?>
     <fieldset class=" collapsible collapsed">
     <legend>More Info</legend>

         <?php print $album['image_link']; ?>

         <?php print $album['title_link'];  ?>

         <?php print $album['total'] . t(' Pictures'); ?>

   </fieldset>
  <?php endforeach; ?>

To have it closed simply add collapsed to your class like <fieldset class="collapsible collapsed">


How do I use variables in links.task.yml?

In your module_name.links.task.yml file you can add a route_parameters: array that lists the parameters you want to pass, in your case it would end up:

entity.node.check_backend:
  route_name: module_name.my_route
  base_route: entity.node.canonical
  title: My title
  route_parameters:
    arg1:  'value_for_arg1'

You can find this by looking at the code in \Drupal\Core\Menu\LocalTaskManager which parses this file.


Provide autocomplete field with user's Display Name

I looked at realname module, which autocompletes the real name. Since realname stores the user defined DisplayName equivalent in the database, it can issue % LIKE queries and autocomplete on both username and realname.

I posted this question to see if there were other approaches, the realname module validates the proposed method as asked in the question.


When while saving nodes do I have old and new vid available at once?

You simply can add a custom submit callback to the node form.

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  $node_forms = [
    'article_node_form',
  ];

  if (in_array($form_id, $node_forms)) {

    // Add a custom submit callback.
    $form['actions']['submit']['#submit'][] = '_MYMODULE_postsave';
  }
}

There you can access the original vid from the $form_state array. And when you load the freshly saved node you'll have the new vid available.

/**
 * Custom submit callback.
 */
function _MYMODULE_postsave($form, &$form_state) {

  $old_vid = $form_state['values']['vid'];
  $nid = $form_state['values']['nid'];
  $node = node_load($nid);
  $new_vid = $node->vid;

  // Voilà!
  dpm($old_vid, 'OLD_VID');
  dpm($new_vid, 'NEW_VID');

  // Do your stuff here
}

For reference: https://drupal.stackexchange.com/a/221041/15055


How do I configure the Services OAuth sub-module?

There is a handbook page covering testing Oauth based services at http://drupal.org/node/942866 . This does assume that you have some familiarity with both oauth and the drupal oauth module.

The basic workflow as far as implementation goes is:

Set up an oauth context.
Set your service to use oauth authorisation
Configure the authorisation for all your resource operations.
Configure one or more oauth consumers

For testing you're probably going to have to write your own client code which generates the oauth signature and then passes that with your service requests.

For learning more about Oauth itself I recommend you start by reading this guide which is fairly comprehensive -
http://hueniverse.com/2007/10/beginners-guide-to-oauth-part-i-overview/


Get the draft data in the webform hook_form_FORM_ID_alter()

As jrockowitz suggested, the best way to get the webform's data and processing it is, to create custom WebformHandler. Please refer "Creating a custom webform handler plugin for drupal 8" section here for more details.


Use One Content type's field as a reference in another content type's view?

My solutions is

1. In your Quiz content type remove book_id field , add another field with (each name you want here I named it my_book_id ) select type node reference  for it.

then in views, create a views of content type quiz, create a relation on my_book_id then you can add book title .

2. Another way is using php views field
create a views with content type quiz, select quiz desire field, then add my_book_id field ,exlude it from dispaly then create php field , in value use something like this

<?
 $node=node_load($data->mybookid); // this is not precise way, you should put nid in node_load(nid);
 print $node->title;
?>


How can I override an entity form with the same date?

When new entity created you need to implement check (if entity with certain date exists) in your FORM_ID_submit() function. If so, use entity_load() to edit existing entity, if not, create new one. Also I recommend using EntityFieldQuery and Entity Metadata Wrappers to deal with entities.


How enable Taxonomy to work with Basic Pages

You probably have your field being displayed as Plain text. To display as links:

Go to your content type and Manage Displays
Find the Tags field and make sure the Format column has the Link value

Note that I'm assuming that you added the Tags field to your Basic Page content type and it's showing up in your page.


D7 Commerce - Save rules applied to line items in cart?

I don't think there is. You will have to:

Add a Discount /admin/commerce/discounts, which will generate a discount rule. /admin/config/workflow/rules?event=0&tag=Commerce%20Discount
Edit the discount Rule and do your magic here.
Create a Coupon /admin/commerce/coupons and link it to your Discount in the "Discount Reference" field.


You can create two folder contrib and custom inside sites/all/modules. Drupal is able to look up any folders inside sites/all/modules to discover the modules.

If it is multiple site structure, you can do the same in sites/[site_name]/modules

For the custom templates and styles, if you means the theme one, you can place the theme in sites/all/themes/custom, otherwise, templates and styles can be placed inside custom module.


Node title get deleted when saving a translation of the node

Do you want to manage your content type translation at node level or field level ? You can have a mix of both on the same site if needed, for different content types, but don't mix up within a content type.

If you choose "basic" node translation for content type A, you won't need the Title module, so if it's enabled/in use for content type B, just don't "replace" (admin/structure/types/manage/content_type_A/fields/replace/title) the built in node title of A by a field.

Then when you translate a node from node/xxx/translate then node/add/content_type_A?translation=xxx&target=lang , everything should be ok.

Read also Gábor Hojtsy explanations which are still valuable about translation settings, or Randy Fay Field translation: First steps


Custom preprocess_function does not fetch translated value of the content type

You can confirm this by looking under the "Overview" tab of the translation interface:

If the percentage in the "Node types" for your second language is ("Norwegian Bokmål" in the image above) is 0%, the translated strings for the Node types has not been imported into the translation interface.  This means that even after you enable that language, the fallback English strings will be used.

However, it should now be possible to add these translation by hand.  Navigate to the translate tab of the translation interface, and limit search to Node types.

The strikethrough over the string with the two letters in the Languages column means that the translation is missing.  Click "edit" to add the missing translation.

This exact procedure fixed it for me as can be seen from the "Overview" tab below.  The percentage for "Node types" for "Norwegian Bokmål" in now 100%.


solving cors problem I just add configuration into my .conf file.

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "Content-Type, X-CSRF-Token"


Maybe it's better to use an image style and use theme_image_style($variables)


rules download module will definitely working with your requirement. This was previously discussed on drupal issue.

Rules Download:

Exposes some Rules actions to download files from the internet using HTTP and use them within rules.

This module exposes the following actions:

Download a file from the internet.

There's a possibility, if you fetches an URL from the site that triggered the rule, that, depending on your configuration, it triggers the same rule again. To prevent that, each file that is downloaded is appended with a special URL parameter (drupal_rules_download=1) that prevent the action to be run again.

Downloaded files are stored within the Drupal files system, so they can then be used to set file fields on entities and other drupal actions in which a file field item is expected. For adding it to a single File field use "Set a data value" and for a multiple File field use "Add an item to a list".

This module started of as an attempt to create PDF with the print module and use it in Rules, but because of how Print module works, it was safer to do it as a separate request and then, the module involved into something more general and flexible.


Store array of ids in a field programmatically?

Consider using hook_entity_presave() to populate any auto-generated fields.

In your case, you could do something like:

/**
 * Implements hook_entity_presave().
 */
function example_product_entity_presave($entity, $type) {
  // Set the values for our computed fields.
  switch ($type) {
    case 'commerce_line_item':
      // @todo: get the value for $foo_ids.
      foreach ($foo_ids as $foo_id) {
        $entity->field_entity_ids[LANGUAGE_NONE][] = array(
          'value' => $foo_id,
        );
      }
      break;
  }
}

If you intend to reference any existing entity, you might want to use the Entity Reference module and use an entity reference field instead of an integer field.


prevent file upload renaming for each node

Sounds like a job for:
filefield_sources

Re-use files by an auto-complete textfield
Attach server-side files uploaded via FTP
Transfer files from a remote server (cURL required)
Select existing files through the IMCE file browser


In the Block title field, use <none> to display no title. Go to     admin/structure/block/manage/system/main/configure: You will find the following description.

  Override the default title for the block. Use <none> to display no title, or leave blank to use the default block title.


How to override Page Title of View using Contextual Filter

In Drupal 8, if you are using a contextual filter to pass a taxonomy term to a View and want to change the page title to match with the term title, you can:

/**
 * Implements hook_preprocess_views_view().
 */
function HOOK_preprocess_views_view(&$variables) {

  $id = $variables['id'];

  if( $id == 'YOUR_VIEW_NAME' && $variables['view']->args[0]) {

    // Get tid from contextual argument of the view
    $tid = $variables['view']->args[0];

    // Load the Term Entity
    $term = Term::load($tid);

    // Term Title
    $new_title = $term->getName();

    // Set the new Page Title
    $request = \Drupal::request();
    if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
      $route->setDefault('_title', $new_title);
    }
  }
}


If I understand you correctly you are wanting to create a specific 'view' template file, your initial question is not clear. You also don't mention which Drupal version you are using. I will assume it's Drupal 7.
Go to your specific view and click Advanced then select Theme. There is a list of file names used for the view. The highlighted templates are current. After is a list of suggested templates that can be used. It's quite safe to use the first example. Copy the highlighted file from core and save it to your themes/templates folder rename it to the suggested file name.
Clear cache and revisit the same view > Advanced > themes section. Your new template file should now be highlighted.
That's it! You are now control of the output. Edit the file as you wish.


There is no "Drupal 8 way." Drupal 8 relies on Guzzle as its HTTP client library so it doesn't have a built-in solution for this.
While the Guzzle client library has GuzzleHttp\Client::requestAsync(), it's not a non-blocking asynchronous method; the method will block once it has initiated the network request since it needs response data for promise methods.
In order to do something akin to your linked question (using fsockopen() / fwrite() to open a socket, send HTTP headers, & close) with Guzzle, you'll need to use a different handler than the default ones Guzzle provides. Guzzle has some documentation on to do this.
It should be noted, even the linked solution isn't non-blocking in the event there are network connection issues (e.g. if the host is unreachable, fsockopen() has $timeout set to 30, so it would  block for 30s before timeout was hit). PHP being single-threaded prevents true non-blocking asynchronous execution within PHP code.


View builders only display HTML/render arrays.

Look into the serialization/rest/hal modules if you want to extract the data of your entity, as you guessed already.

Note that REST in core only supports content entities at the moment, but I assume you have one of those.

Also, I'd recommend hal+json serialization, provided by the hal.module instead of the raw json seralization, as that can't deal with things like references properly.


How to alter menu parent select list on node form?

Menu module does form alter to add the Menu Fields to the node creation form using function menu_form_node_form_alter in menu.module

Check your custom module weights to catch this data in your custom module to do form alter...

There is a new drupal 7 API called hook_module_implements_alter() which lets you alter the execution order for a given hook WIHOUT altering the module weights table.


You can try Custom Search module. This module alters the default search box in many ways. If you need to have options available like in advanced search, but directly in the search box.

The module adds options to select:

which content type(s) to search, which specific module search to use
(node, help, user or any module that implements search),
advanced criteria For all these choices, there are options to switch between a
select box, checkboxes or radio buttons,
You can also customize the selector label and the default - Any - text.


I would use this structure:

$_SESSION['mybasket'][$id] = [
  'label' => $label,
  'code' => $code,
  'price => $price,
];

Then you can delete one item

unset($_SESSION['mybasket'][$id]);

or the complete basket

unset($_SESSION['mybasket']);

You don't need the variable loop, to count the items use

$count = count($_SESSION['mybasket']);