Drupal 7: Menu item being accessed even with false access callback?

user_is_anonymous() returns TRUE if the user is a menu administrator: see function user_is_anonymous

Try user_is_logged_in() instead, e.g.:

function the_permissions_function {
    $isLoggedIn = user_is_logged_in();
    if ($isLoggedIn) {
        return FALSE;
    }
    return TRUE;
}


DeployAuthenticationException: Authentication error when try to push the content

I was having the same issue and I solving applying this patch: https://www.drupal.org/node/2017767#comment-7773329

Hope it helps!


Add a message to messages array using theme process or preprocess function

$messages isn't an array of messages; it's the rendered output of theme_status_messages(). From the point at which you're looking to add messages (template_process_page()), Drupal has already processed all the messages it's going to render.

If you're looking to print some debugging messages you can do something like this:

function MYTHEME_process_page(&$variables) {
  drupal_set_message('new test message');

  //This will overwrite any previous messages that were to be rendered
  $variables['messages'] = theme_status_messages(array('display' => null));
}


How does POST action work on a drupal login form?

Drupal uses the Form API to handle this. It doesn't need a specific page to handle the POST data because of the way its structured. Also see user_login to get an idea of how it's implemented. You can see that it sets specific validation functions to be called when the form is submitted, and then it moves on to user_login_submit (this part happens due to the default naming conventions of the Form API). There's other magic in there that makes this all work, but it usually isn't necessary to understand it in order to develop with Drupal.


Where does Commerce Stripe store the plans that are created on my stripe account?

While I'm not familiar with Stripe, it looks like the commerce_stripe stores the details in the remote Stripe system via the stripe-php library

e.g, in commerce_stripe_submit_form_submit

Stripe_Customer::create
...
Stripe_Customer::retrieve

The other place for payment gateway settings will be on the individual payment method configuration form under Rules.


How to restrict access to a non-drupal url on a site's domain?

Nope. It sounds like your web server has the mailman web interface alias to that path. If that's the case, Drupal is never evoked so it wouldn't have any say on how that request is handled (i.e. index.php?q=mailmain/listinfo isn't executed for page handling).

You'll need look at configuring your web server to remove your alias, or remove it for your hostname.


How can I get the full content of a PHPUnit test truncated response?

My problem stemmed from trying to use GuzzleHttp to make my request, instead of BrowserTestBase::drupalGet().  I still don't know about getting to that truncated output, but using drupalGet() returns the output without truncating.


Taxomony menu - show all, vocabulary link are disabled

I am currently working on an ecomerce project and faced same issue. This helped https://www.youtube.com/watch?v=iBdVW7fC2Tg me so I recommend watching it, For the listing I have used drupal nice menus module. You can use it from https://drupal.org/project/nice_menus. In my project, listing is now working fine and I have 4 different menu items with their respective sub-categories.

If you still face any issues I will be available to help!


This may not be what you're looking for but here is what we do to deploy on several production sites.

Store as much in Features as possible
Write update scripts when needed (as you've done). However, we enable modules via drush, never in code.
then run: drush en feature_module_name -y && drush updb

If multiple modules need to be enabled, we normal setup a chain of dependencies in the *.info files.


Uncaught TypeError: Cannot call method 'extend' of undefined

You are attempting to use jQuery before it's loaded.

You should place that code inside your ready function:

$(document).ready(function () {
    // place code here
});

Although to be really Drupal-friendly, you should use Drupal's behaviors.


Maybe something like this in a js file included on the page.

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      $('.ajax_messages').delay(3000).fadeOut();
    }
  };
})(jQuery);


How to sort a view using values not stored in the database

I used a view pre render hook to alter the order of the returned rows (I had to disable pagination and create my own pagination system). Here's an example of the function:

function your_theme_or_module_views_pre_render(&$view) {
  if ('your_view' == $view->name && 'your_display' == $view->current_display ) {
    if(isset($_GET['sort_order'])){
      if($_GET['sort_order'] == 'ASC'){
        $sortorder = SORT_ASC;
      }else{
        $sortorder = SORT_DESC;
      }
      if($_GET['sort_by'] == 'field_price_value'){
        $byprice = true;
      }else{
        $byprice = false;
      }
    }else{
      $byprice = true;
      $sortorder = SORT_ASC;
    }
    $order = array();
    foreach ($view->result as $key => $row){
    /* Here you can modify the values you want to show
    and put them in an order array */
      $row->field_field_price[0]['rendered']['#markup'] = $thenewprice[$index]."€";
      $row->field_field_price[0]['raw']['value'] = $thenewprice[$index];
      $order[$key] = $thenewprice[$index]; // we will use this array for multisorting
    }

    //this will be used for pagination In my case I'll show 8 results per page
    $numpages = ceil(count($view->result)/8);
    if($byprice){
      /* we only change the rows order if we are sorting by the
      modified field, otherwise the order returned by the view is fine */
      array_multisort($order, $sortorder, $view->result);
    }

Now we create the pagination system you can use this as an example

    if(!isset($_GET['page'])){
      $view->result = array_slice($view->result, 0, 8);
    }else{
      $sumando = ((int)$_GET['page']*8);
      $view->result = array_slice($view->result, $sumando, 8);
    }
    $links = array();
    if(isset($_GET['page'])){
      $page = $_GET['page'];
      $absolute_url = full_url( $_SERVER );
      for($i=0;$i<$numpages;$i++){
        if($page == $i){
          $active = " active";
        }else{
          $active = "";
        }
        $urlconpage = str_replace("page=".$page,"page=".$i,$absolute_url);
        $links[] = "".$i."";
      }
    }else{
      $absolute_url = full_url( $_SERVER );
      $countarray = explode("?",$absolute_url);
      if(count($countarray)>1){
        for($i=0;$i<$numpages;$i++){
          if(0 == $i){
            $active = " active";
          }else{
            $active = "";
          }
          $urlconpage = $absolute_url."&page=".$i;
          $links[] = "".$i."";
        }
      }else{
        for($i=0;$i<$numpages;$i++){
          if(0 == $i){
            $active = " active";
          }else{
            $active = "";
          }
          $urlconpage = $absolute_url."?page=".$i;
          $links[] = "".$i."";
        }
      }
    }
    $_SESSION['links'] = $links;
  }

Most of the code in the paginator is just to keep unchanged the parameters in the url, essentials for the view returning the right results. The function full_url that I call in the code is an adaptation of the function described in:

https://stackoverflow.com/questions/6768793/get-the-full-url-in-php

Using the SESSION variable You can print the links where you prefere, For example in a global textarea in the view footer, inside an

 structure.


By what you can see in this var dump the field can hold any paragraph type, so you don't know which fields it may contain.

When you have restricted the field to one paragraph type, then load the field defintions for this type:

$fields_paragraph = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions('paragraph', 'my_paragraph_type');


How to print You have new private message, You have no new messages

The module automatically does that when a user logs in who has the message waiting.  It DOES NOT print you have no new messages - because that is redundant.  It did it that way when we use it on our site - Drupal 6 - have not enabled and used it however yet on Drupal 7


Help with LDAP module for user authentication in Drupal 8.3.7

Found the problem. I had a temporary cert in /tmp and specified in /etc/openldap/ldap.conf but systemd starts httpd with a private /tmp so the cert was not being found.


To migrate your database (including the configuration of the admin interface) from the staging to production server, check out the Backup and Migrate module.

RE: your question about "Open source":

Unless your configuration is something really special, with a specific target audience and use case, it may not be worth your while making your configuration, etc. available for others, but YMMV.

If you want to do this, you should create a Drupal Distribution and release it on Drupal.org/project/distributions along with the 600 or so distributions already available there. Like all other Drupal projects, you use git to interact with the repository, and you also need to be a git-vetted user if you want to create a non-sandbox distribution.

You build a distribution by first exporting its features (including custom cck, templates and Views using the Features module. Then turn this into a distribution using the Profiler library to create an install profile.  Finally, you package the distribution with the Drush Make packager (part of Drush).


Drush not reading config file from top-level /drush folder within Drupal install?

Sorry, there is a typo in Drush preventing this:

https://github.com/drush-ops/drush/pull/1542

This fix should be in the next version of Drush.  Sorry for the inconvenience.


What is the easiest way to update thousands of users' "created date"?

This answer assumes that changing the created dates is a one-time action, and that other modules in your Drupal site do not need to react to the users being updated.

IMHO, if you're looking at modules to do this, you're making things way too complicated for yourself. A simple SQL query should to the job:

UPDATE users SET created = 1234567890 WHERE uid <> 0;

You can choose / calculate the timestamp yourself (where it says 1234567890 in my example). I'm excluding the record with user id 0 because this repesents the anonymous user who does not have a created date.

How to run this query:

From a MySQL admin tool, like phpMyAdmin or HeidiSQL, whatever you have to access your database;
From the command line using the mysql command (don't know if this works on Windows):

$ mysql -u user_name -p -e 'UPDATE users SET created = 1234567890 WHERE uid <> 0' database_name

From the command line using Drush:

$ drush sql-query "UPDATE users SET created = 1234567890 WHERE uid <> 0"


How to display only content assigned to a user?

Create views by filtering the content type which you want to list in there.

Then add a argument in the view, which will be the field you are using to reference the user in your content type.

Supply UID of currently logged in user as default arguments & your content will be filtered for logged in user.

User will see all the fields values added by you on the page, fields are totally dependent upon your selection which you can add in views.


How to display associated content through shared taxonomy?

If I am understanding your situation correctly you want to display a list of clip pages grouped by topic summary.

In Drupal 6 you can use the http://drupal.org/project/views_groupby module, in Drupal 7 it's built in to views.

HTH


Simply - edit your pager options in view to fit your needs.


When does Drupal load variables from the database?

If the values need to be continuously updated, then it is better not to use variable_get()/variable_set() for storing it. This is because every time variable_set() is called, it clears the cache containing the values of the variables, which means that the next time a page is required, the Drupal variables will be loaded from the database, and not from the cache, with consequent lose of performance.

In such case, it is better to count the number of unread reports when reading from the database table containing the report data. This means the database table should contain a unread field that is set to TRUE when the report has not been read.

The values of the Drupal variables are loaded from the database, or the cache, when Drupal is bootstraping; the called function is variable_init(), which first checks the cache, and loads the values from the database, if the cache is empty.

  if ($cached = cache_get('variables', 'cache')) {
    $variables = $cached->data;
  }
  else {
    $result = db_query('SELECT * FROM {variable}');
    while ($variable = db_fetch_object($result)) {
      $variables[$variable->name] = unserialize($variable->value);
    }
    cache_set('variables', $variables);
  }


How do I specify a Forena PDO data source in settings.php?

A sample of what you are looking for can be found in Forena subfolder repos/sample/settings.php, it looks like so (and is for 7.x-4.x):

<?php
/*
 * Sample Repository configuration file
 */

/*
 * Security provider:  Specify the class name that is used to provide security
 */
$conf['access callback'] = 'user_access';

/*
 * Data provider:
 * Specify the class name that will be used to interpret data block files.
 * Note that data blocks in a repository
 *
 */
$conf['data provider'] = 'FrxPDO';

/*
 * URI:
 * The format of the uri depends on the type of data engine that's being used.
 * In database engines it might be the connection string to the db.  In the file
 * engine it would be the path to the directory containting the files
 */
$local_path = realpath(dirname(drupal_get_path('module','forena').'/forena.info'));
$conf['uri'] = 'sqlite:'. $local_path . '/repos/sample/sample.db';
$conf['debug'] = FALSE;
/**
 * Uncomment the following line to specify a particular path in which to save reports.
 * The default value would be controlled by Forena configuration page. If you'd like users
 * to be able to define their own reports in this repository then you need to make sure that this
 * is writable by the web user (e.g. apache).
 */
// $conf['report_path'] = 'sites/files/reports'

Disclosure: I'm a Forena co-maintainer.


searching custom node type contents from a module

Core search module will index all nodes, no matter where they have been defined (manually through admin/custom module.).


Installing an alpha dev version with composer

As I said, just don't specify a version and composer will automatically pick a version constraint that installs the most stable version:

$ composer require drupal/block_class
Using version ^1.0@alpha for drupal/block_class
./composer.json has been updated
Gathering patches for root package.
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
Gathering patches for root package.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/block_class (1.0.0-alpha1): Loading from cache
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles


How to dynamically change the title of a menu item

Views doesn't implement hook_menu() to add it's items, it uses the menu link API directly to add links. This makes it a bit trickier to do what you want as hook_menu_link_alter() isn't necessarily called when the caches are flushed, but only when the link is edited via the admin UI.

The links in menus don't even necessarily go through theme_menu_link() so you can't override the title at the theme level with that hook. Instead the only way I could find to do it was to implement hook_preprocess_link(), check the path, and change the title.

It's not a very pleasing solution, as theme_link() seems far too generic a place to be hooking into to change just one link title, but it might do the trick:

function MYMODULE_preprocess_link(&$vars) {
  if ($vars['path'] == 'newcomments') {
    $num_comments = MYMODULE_num_comments();
    $vars['text'] = format_plural($num_comments, '1 New Comment', '@count New Comments');
  }
}

The only problem is that if there are other links on the page that point to the same URL their title will also be changed. Hopefully this can be a 'feature' rather than a 'bug' ;)


Need help with Drupal javascript behaviors

In drupal 7, If you need to add JavaScript or CSS to your page where a form may be rendered, there is already a rendered array variable available from the Form API for just that. drupal_add_js() will not always add the JS to the form as the hook does not always run when the form will be displayed, in certain scenarios like if the page is cached. You should use the #attached array on any form element, if you want to add JavaScript or CSS, because this array will rendered in all certain scenarios.

$form['#attached']['js']["jQuery('#font-preview-" . $i . " span').removeClass().addClass(jQuery('select[name=\"font-select-" . $i ."\"]').val())"] = array( 'type' => 'inline');

For More details you can visit: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached


Custom fileds are not visible on user profile page

There are many things that may be causing this. If you are not using a custom template try going to the display options of the user's profile page
(admin/config/people/accounts/display) and set the fields to visible there.


How does one check if user has created a node of a content type in rules?

After seeing these big answers for Rules, I think you can try to do the same via code. Its much smaller and extremely faster than Rules!

/**
 * Implements hook_node_prepare()
 * @param type $node
 */
function mymodule_node_prepare($node) {
  if ($node->type == "my_type") {
    if (!isset($node->nid)) {
      $existing_nid = db_query("SELECT nid FROM {node} WHERE (type = :type1) AND uid = :uid", array("type1" => "my_type, "uid" => $node->uid))->fetchField();
      if ($existing_nid != FALSE) {
        drupal_goto("node/$existing_nid/edit");
      }
    }
  }
}

This code checks if the user already have created a node, if yes, instead of allowing him to create a new one, we redirect him to the edit form of the existing node.

If you want this feature without Rules or code, you can try the Profile module. It has this magical feature to configure any content-type as 'profile'. And when a content-type is configure as 'profile', users are not allowed to have more than one node of that particular type.

Thanks!


Alter views style using regenerate feature?

You do not need to enable / disable features on prod server after uploading the new files

First, on your prod site clear all the caches

Then go on the view's page admin/structure/views click on the dropdown list beside your view, you should have an operation 'revert' : that's it

If you dont have 'revert' operation, (and disable is present) it means the views is up to date with your feature's file

Of course, the start point is to re-export your feature's files from your local site and upload them to your server (do not export/import your view, the code must be in the feature's files)


An easier solution is to modify the 'label callback' property of the node entity.

function mymodule_entity_info_alter(&$entity_info) {
    $entity_info['node']['label callback'] = '_mymodule_label_callback_set';
}

function _mymodule_label_callback_set($entity, $entity_type){
    if($entity_type == 'node' && $entity->type == 'my_node_type'){
        //Compute new label here
       $label = 'test';
       return $label;
    }
}


Manually populating fields using SQL queries

Drupal acts a bit differently,

1) Can you try cleaning your cache.

2) Write a function in a custom module

function _get_nodes() {
  $options = array();
  $sql = "SELECT nid, type FROM {node}";
  //adjust the query to filter on content types, if needed
  $result = db_query($sql);
  foreach ($result as $row) {
    $node=node_load($row->nid);
    //dpm(node); maybe you have different naming convengion
    $node->field_global_news['und'][0]['value']=1;
    node_save($node);
    unset($node);
  }
  return $options;
 }


get the content type 'machine name' by the 'human readable name '

You can easily build a query to achieve this. However, as Molot mentioned, you have to handle human readable names that aren't unique.

  $machine_name = db_select('node_type', 'n')
  ->fields('n', array('type'))
      ->condition('name', 'Basic page')
      ->execute()->fetchField();


Where are css injector files stored on the server?

CSS Injector stores it's files in the files directory under:

'public://css_injector/css_injector_' . $crid . '.css';

as defined in _css_injector_rule_uri

This often maps to the following folder:

sites/default/files/css_injector

See also: css_injector_init for how the files are added by that module.


Line item custom field value not be saved after update line item

I have to "save" the whole form at bottom of the page, not only update that line.


How to troubleshoot Push Notifications module

This turned out to be my own error, I was using the wrong certificate, one that was not set up for push notifications, otherwise, everything works just like the instructions.


How to add a percent field in content type

Could you not just create either a integer or float number field and just label the field as "percentage" or whatever? And also use the "suffix" option on the field options to add "%"

You can also set the min and max values of 0 to 100 to keep it within percentage range of options

Or how would you be expecting a percentage field to act different from a float/integer field?


Make private pdf files Non-Downloadable via absolute url links

It should be as easy as adding an implementation of hook_file_download() to a custom module:

function MYMODULE_file_download($file) {
  // Add whatever other conditions you need to this, e.g. test the
  // file extension for .pdf
  if (user_is_anonymous()) {
    // Deny
    return -1;
  }

  // Allow
  return file_get_content_headers($file);
}


Rating for anonymous users plus redirection to the login page

Try the Voting Rules module.

  Administrators can configure actions to occur when a user submits a
  vote, when a user deletes a vote, and when the results of a vote are
  calculated. Currently, Voting Rules supports votes on nodes, users,
  and comments.

I didn't test it, but using it is possible to achieve what you want with the the Rules module.


Use Php views and in it  use gettype, I think you can acheive it by Php views ( also you can achieve it with hook_views_pre_render) and return data tye with gettype.

gettype — Get the type of a variable Description
string gettype (mixed $var )
Returns the type of the PHP variable var.


How do I get the submitted moderation state of a custom block?

all most there try the following

// Get the current  entity.
$entity = $form_state->getFormObject()->getEntity();
$moderation_state = $entity->get('moderation_state')->getString();
// Do the things.

or
   in a submit or validation thing
   try to

// use dump() as it is way better
dump($form_state->getValues()) // <-- and find in the array


If you have the jQuery UI library with dialog activated on your site, you should be able to do

$('<div>' + message + '</div>').dialog();


i cannot provide detailed steps to achieve this but there are various alternatives Comparison of Single Sign On (SSO) Modules to the bakery module you mentioned that are capable of sharing users. although you might want to just create those roles via a feature, depending on what you mean by

  sync my drupal website roles.

Services
i18n_sso
Domainaccess
CAS
account_sync
simplesamlphp_auth
shib_auth
Omniauth https://drupal.org/node/2177681
Oauth Connector
Bakery 3.x current development effort suggest it might soon support exporting roles in 3.x if you are a developer you can look there. i believe issue 556666 was committed to 2.x already aswell


One way to do it -- if you don't want to create/mess with the theme template files for your content type, would be to display the corresponding tag image via a view.

Here are the steps to doing that:

I'm assuming you already have your vocabulary set up properly and you have the image field added to it (can be done at admin/structure/taxonomy/[YOUR VOCAB ID]/fields) and some terms have been populated with their corresponding images.
Create a new view with a block display, and set it to apply only to the relevant content types

Add a term relationship to your view, so you can access the vocab/term fields, and not just the node fields!!

Once you've done that, go into the fields you want to pull for each node.  I'd remove the 'Title' field that's added by default and only add the field that represents the image associated with your term.  It should be somewhere under the 'Taxonomy term:....' section of the field list.
Make sure that you set it to use the relationship you created above

Finally, since we'll want this block to take its cue of which image to display based on which node it's on, let's add a contextual filter.  Under the 'Advanced' section --> 'Contextual filters', add the 'Content: Nid' one and make sure you set it up to take its NID from the page it appears on if a filter isn't present in the URL

All done!  Go to one of the relevant pages and test.  Of course, you'll have to enable the block via contexts or the block admin page (admin/structure/block) first, since it's not placed anywhere by default.  Display the block on the second sidebar, in the actual content section -- anywhere you want.

Let me know if this helps!!

================ EDIT =====================
Solution 2 (upon request)

To do this through your template file, go ahead and copy your regular node.tlp.php file and rename it node--[YOUR CONTENT TYPE MACHINE NAME].tpl.php

Then, right under or above the content, insert the following code:

$term=taxonomy_term_load($node->field_thats_term_reference['und'][0]['tid']);
$image_field=field_view_field('taxonomy_term', $term,'field_main_image');
print render($image_field);

Just substitute 'field_thats_term_reference' with the name of your term reference field, and substitute 'field_main_image' with your image field name.

That'll do the print out.  You can place this anywhere you want.  If you want to customize how the print out actually looks, just do a dpm($image_field) once you've set that variable (must have the devel module installed), and you can see all the parts of that field and how to get to them if you want to print them out separately as opposed to the default way render() prints it all out.  I think that part is beyond the scope of this question, but it should get you started!


Paragraph type can't delete individual items

I have this same problem and also have a link field set to unlimited. I don't see a remove button. Evidently there is a patch in progress for this specific issue. https://www.drupal.org/project/drupal/issues/1038316


don't allow multiple users with same email

Drupal by default does not allow multiple users with the same email if you try to create them through Drupal forms. If users are created by code this check is not performed.

My best guess it, that this caused by one of the rules Drupal commerce ships with. Specifically the "Create a new account for an anonymous order" rule. This rule fires when a user who is not logged-in completes checkout. It should check if the email is already registered, but might have been altered.
Alternatively you might have a similar rule created yourself or by a module that does not check if the e-mail is already existing.

Most of Drupal commerce's behavior is controllable by rules, so I'd start looking there for rules that create users.


You are looking for Conditional Field Module...

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new States
  API, plus the ability to modify fields appearance and behavior on
  certain conditions when viewing content.


Module getting "$entity" argument error with hook_entity_presave()

The exception you get (Controller "Drupal\sno\Controller\SnoController::sno_entity_presave()" requires that you provide a value for the "$entity" argument) is caused from the fact the controller's method associated to the sno.content route you define doesn't get any $entity argument, which is instead listed as its parameters.
That is a route, anyway, not a hook. If you want to implement hook_entity_presave(), you don't need to define a route for that. If the module isn't defining other routes, the sno.routing,yml file isn't even necessary.
As Jaypan already said, hooks aren't methods implemented in a class. They are plain PHP functions with a specific name.
In your case, it should be the following function. I corrected the function code because:

In a path like /node/add/issuances, issuances is the content type, or node bundle, not the entity type. As the code should act on a node whose bundle is issuances, the code needs to check the value returned from $entity->bundle().
Since hook_entity_presave() is invoked for every entity Drupal saves, it's necessary to check which entity is being saved, by checking the value returned from $entity->getEntityTypeId(), not just its bundle. This handles the case where two different entities have a bundle with the same name.

I took the module machine name from the namespace used in the question code and from the name of the routing file. If those are correct, also the module machine name should be correct.
// Put the following line on the top of the sno.module file.
use \Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function sno_entity_presave(EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'issuances') {
     $entity->set('field_s', '<value to assign to the field>');
  }
}

Alternatively, if the module only has code for a single entity type, hook_ENTITY_TYPE_presave() can be instead used. In this case, it's not necessary to check the entity type, as the hook is only invoked for a single entity type. (In this case, the entity type is Node.)
// Put the following line on the top of the sno.module file.
use \Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function sno_node_presave(EntityInterface $entity) {
  if ($entity->bundle() == 'issuances') {
     $entity->set('field_s', '<value to assign to the field>');
  }
}

As for the field, it's usually field_s for a field added via UI. If it's defined from code, the field is simply s. You need to verify the correct way to reference that field, as that isn't clear from the code shown in the code.
As side note, if you edit the code of a module that is installed, you need to install or uninstall a module, to make Drupal notice you added a hook into that installed module, as Drupal caches the list of hooks implemented by modules, and clears it when a module is installed or uninstalled.


How to add the js files to specfic modules only

It is, of course, not possible. The problem is:

JS files, by the nature of WWW, are added to HTML output
All modules participate in creation of one HTML output
You want to add JS "only to module", but because there is no isolation between parts of HTML output, it's plainly not doable.

To address what you didn't really ask, but probably need to know:

Never just add jQuery on your own. That's pretty dangerous thing to do and pretty much always will mess things up. There is jQuery Update module to address this need. It's not perfect, but way better than anything you will be able to create yourself now - because it was tested by hundreds of thousands.


Webform element validation custom module

i was able to get the value of surname from the Formstate, the form state had surname in surname field itself.

public static function validate(array &$element, FormStateInterface $formState, array &$form) {
    $webformKey = $element['#webform_key'];
    $value = $formState->getValue($webformKey);
    $surname= $formState->getValue('surname');
}

this did the trick.


How do I remove extra divs added by panels?

There are a couple ways you can tackle this.

One option is to simply create your own panel layouts.  I often do this because I like control over the markup and I want to reduce the divitus in my theme.  It also lets me create layouts that more directly match what I need.  It's pretty easy to create your own panel layouts in your theme.  Read more here.

Another option is to override the panel template files in your theme.  Similar to any module that provides a template file, you can copy that template file to your theme and change the markup.  You'll find the panel template files in [path_to_modules]/panels/plugins/layouts/[each_layout].


Module recommendation needed for recurring monthly membership plan?

There are a few options available.

I've seen this: https://www.drupal.org/project/commerce_recurring which integrates with Drupal commerce. It doesn't have a stable version though.

For something more stable, and which is independent of the Drupal commerce module, try Recurly
https://www.drupal.org/project/recurly

Recurly is a 3rd party subscription billing system.

Using the Recurly roles module: https://www.drupal.org/project/recurly_roles

You can have people subscribe to your website, and assign a paid membership user role after signup and subscription. If a user stops the subscription, then you can take away the role.

Then configure your videos to only be accessible to the paid member role.


Ok i think there must be an easer way using views so if  have taxonomy term "small box" which has a field "weight" linked to it with defaolt value 0.6  the folowing field in my nod is "amount" how do i get the result in views so i would see 0.6 multiplied by the "amount"

Thanks


@Berdir's answer helped me to figure out the solution. We should indeed clear the user input, but we can not simply just say $form_state->setUserInput([]), because there are some system values, that should stay(e.g. form_id, form_token, _triggering_element_name, etc.).
I have created a custom method for it:
  /**
   * Clears form input.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  protected function clearFormInput(array $form, FormStateInterface $form_state) {
    // Replace the form entity with an empty instance.
    $this->entity = $this->entityTypeManager->getStorage('my_entity_type')->create([]);
    // Clear user input.
    $input = $form_state->getUserInput();
    // We should not clear the system items from the user input.
    $clean_keys = $form_state->getCleanValueKeys();
    $clean_keys[] = 'ajax_page_state';
    foreach ($input as $key => $item) {
      if (!in_array($key, $clean_keys) && substr($key, 0, 1) !== '_') {
        unset($input[$key]);
      }
    }
    $form_state->setUserInput($input);
    // Rebuild the form state values.
    $form_state->setRebuild();
    $form_state->setStorage([]);
  }

I am calling $this->clearFormInput($form, $form_state); in the MymoduleForm::save() method(the very last step of the submission).
Update 08.03.2021
If you have a created date field in the entity form, it will be cached in $form_state after submission. You will have to reset it's value for the entities. You can do it by overriding the \Drupal\Core\Entity\EntityForm::processForm:
 /**
   * {@inheritdoc}
   *
   * Resets default values for a new entity.
   */
  public function processForm($element, FormStateInterface $form_state, $form) {
    $element = parent::processForm($element, $form_state, $form);

    if ($this->entity->isNew()) {
      $this->entity->set('created', $this->time->getRequestTime());
    }

    return $element;
  }


The Migrate module, not to be confused with Backup & Migrate, can provide this functionality. The project page says it better than I can.

  The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, and comments is included - it can easily be extended for migrating other kinds of content.

Deliberately, it's fairly complicated module. Here's a talk on it from DrupalCon denver


How can I add my Bootstrap classes to a custom menu?

What you want is theme_menu_link(). See the example here.


You can do that using the  Date module

This package contains both a flexible date/time field type Date field and a Date API that other modules can use.


The mistake is in the url parameters, it should be :

d8.com/user/logout?token=123

The _format is not needed for logout.
I found the parameter name for the token on this page https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Access%21CsrfAccessCheck.php/function/CsrfAccessCheck%3A%3Aaccess/8.3.x


Is there an easy for my authenticated users to search other authenticated users?

There is a default user search. You can go to "your_site/search/user" to try that out. You can set the permissions at "admin/people/permissions" to allow only authenticated users to use this search.


Clean URLs not working in Drupal 8.1.8 and IIS 8

Probably it's a directory permission issue. Drupal is not able to write into web/sites/default/files. Give this file directory right permissions for your server user. (www-data in case of apache)


Date format - @ symbol has unexpected behaviour

I was having the same issue and was able to get this working by escaping the @ symbol.

Example: 'M j, Y \@ G:i'


Theme is not working when files are uploaded from localhost to the web server

Have you tried putting another theme as default, them uploading the database again ?
If you then try to set your theme as default on the live site, it might work...


Isn't your admin theme uses a different template.php? I am assuming you try to theme /admin/content/node/article. If so, your active admin theme is where your override should go.


Create taxonomy terms from content type field

You can trigger this behavior by implementing the hook_entity_presave on a custom module. Inside of this hook, you will call a function which creates each time the taxonomy term using the title of the node created. Here is my example:

File: test.module

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function test_entity_presave(EntityInterface $entity) {
   if ($entity->bundle() == 'product') {
    if ($entity->isNew()) {
      $title = $entity->get('title')->getValue();
      \Drupal\test\Test::createTerm($title[0]['value']);
    }
  }
}

Assuming you have defined the createTerm function into Class Test:

File Test.php(Include this file in src folder)

namespace Drupal\test;

/**
 * Test class.
 */
class Test {
  public static function createTerm($title) {
    $term = [
      'name'     => $title,
      'vid'      => 'widget_type',
      'langcode' => 'en',
    ];
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($term);
    $term->save();
  }
}


How change widget of a "between exposed filter" to combo box?

You're close. After you expose the filter, change it from Single filter to Grouped filters using the radios right below the expose checkbox. Then you can define what each option is and make it a select box.


You have to check the permission to write to a user's wall, either during signup or doing it manually later - looks like you are missing that permission. You need to get appropriate permission from the facebook.


how to send $user variable from drupal to another php non-drupal page under same root?

I have a similar setup running; what I did was sending the session ID as a URL parameter, including the "bootstrap.inc" file, bootstrapping the database, and then looking up the info I needed.

Example where I've stored some info in the session:

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

if (@$_GET["sid"]) {
  $_SESSION["sid"] = @$_GET["sid"];
}

if (@$_SESSION["sid"]) {
  //Get the get username/role from the database
  $result = db_query("SELECT session FROM {sessions}
    WHERE uid > 0 and sid = '%s'", array(
      $_SESSION["sid"],
    )
  );

  while ($row = db_fetch_object($result)) {
    $_SESSION += unserializesession($row->session);
  }
}

function unserializesession($data) {
  if (strlen( $data) == 0) {
    return array();
  }

  // Match all the session keys and offsets.
  preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

  $returnArray = array();
  $lastOffset = null;
  $currentKey = '';

  foreach ($matchesarray[2] as $value) {
    $offset = $value[1];

    if (!is_null($lastOffset)) {
      $valueText = substr($data, $lastOffset, $offset - $lastOffset);
      $returnArray[$currentKey] = unserialize($valueText);
    }

    $currentKey = $value[0];
    $lastOffset = $offset + strlen($currentKey) + 1;
  }

  $valueText = substr($data, $lastOffset);
  $returnArray[$currentKey] = unserialize($valueText);

  return $returnArray;
}


I Finally found the error...

drupal_get_form was calling the submission again, I was creating a new form like the one I was substituing, but I was also updating the old.

Instead of creating a new form, I just used the $form variable instead of drupal_get_form.

Please find the new logic below!

function ajax_club_paginator_next($form, &$form_state)
{
    $page = intval($form_state['values']['current_page']);

    $html = '';
    $html .= '
';
    $html .= draw_clubes_page($page);
    $html .= '
';

    $paginator = '
';

    //Not Needed!
    //$form = drupal_get_form('club_paginator_form', $page);

    $paginator .= drupal_render($form);
    $paginator .= '
';

    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace("#club-paginator-content-replace", $html),
            ajax_command_replace("#paginator", $paginator)
        )
    );
}


Views hook gets ignored after 1 execution

Solution is to put the code in a file called MYMODULE.views_execution.inc.
I was using MYMODULE.views.inc


The Cache Expiration module is designed to clear items from caches, including Varnish.

  This module acts as a grid to detect and act upon events that will expire URLs from caches like reverse proxy caches. The Cache Expiration module is a spinoff of the expiration code of the Boost expiration code so other modules can use it. This module stands on its own and does not use Boost in any way.


The only way WYSIWYG works with Views is with either an embedded comment or using the Editable Views module:

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.

  Editable fields can be added on the base entity as well as on entities
  brought into the View by a relationship. Other, non-editable fields
  may be added to the View, in which case they function normally.


How can I distinguish the first image in an image field in a Twig template?

This code in a node.html.twig template will display only the first value of an image field that has multiple values:

{{ content.field_yourfieldname.0 }}

This will only display the second value:

{{ content.field_yourfieldname.1 }}

Source

Edit: apparently that wasn't really the question, my apologies.


Send mail with attachment using the MIME Mail module

The solution I've found is to use hook_mail_alter to attach the file to the email after it's generated and before it's sent. The key to that is making an array of details about your attachment and adding that to $message['params']['attachments'].

hook_mail will send mail, but if you're using another program to send (Swift Mailer or PET), then I believe you'll need hook_mail_alter to alter the mail instead of sending it yourself.

I also suggest using the Form API (also this) to keep track of your file. That's not required, however, just provide the necessary info.

function myhook_mail_alter(&$message) {

  print "message id: {$message['id']}\n";

  // if this email is one of the ones I want to alter:
  if (!empty($message['id']) && (preg_match('/^message-id-set-by-formmail[\d]{1,2}/', $message['id']))) {

    // $message['params']['body'] is a single string, not an array
    $result = preg_match('/\[my dumb string with node id# (\d+)]/', $message['params']['body'], $matches);

    print "Message body: \n {$message['params']['body']} \n\n Matches:\n";
    print_r($matches);

    if (!empty($matches[1])) {
      $file_id = $matches[1];
      $my_pdf = file_load($file_id);
      $original_attachments = $message['params']['attachments'];
      // $original_attachments is an array of associative arrays, each bearing details about an attachment.
      // Add an associative array about this desired attachment.
      $my_attachment = array(
        'filecontent' => file_get_contents($my_pdf->uri),
        'filemime' => $my_pdf->filemime,
        'filename' => $my_pdf->filename,
        'filepath' => NULL,
      );
      $message['params']['attachments'][] = $my_attachment;
    }

  }
}


How to execute custom code on user signup

You can do it in a simple custom module, be sure to first understand Drupal hooks system as this is the base for (almost) everything Drupal.

In your module, you can implement hook_user_presave() to be called before a user account is saved. It will be called for both creation and update, so you will need to guard your code with a condition to detect new user. After the REST call, there is several option to store the returned data. The easiest one is the use the data attribute of the user account. It is a simple PHP array that will be serialized in a database columns. It is not very good performande wise and not very flexible (you can query the stored data) but it is easy.

function MODULE_user_presave(&$edit, $account, $category) {
  // Accoding to user_save's documentation, this is a new user if
  // $account->is_new is set to TRUE or if $account->uid is not set
  if ($category == 'account' && (!empty($account->is_new) || !isset($account->uid)))) {
    $edit['data']['MODULE'] = MODULE_get_data_from_rest($account);
  }
}


Disable publish and unpublish options in VBO on the main content view for one role

Views Bulk Operations (VBO) contains a sub module called ACTIONS PERMISSIONS:

  A module called actions_permissions is included in the package. This
  module generates a permission for each action, and VBO honors those
  permissions before showing or executing the corresponding actions.
  This is useful if you want to provide your VBO to several groups of
  users with different privileges: the same view will accommodate those
  different groups, showing to each the actions that they are permitted
  to see.


I think the event should be keyup not click.


View inside display suite block field - contextual filter

You should use Display Suite Dynamic Field instead of Block Field.

It allows you to select a view and pass the appropriate contextual filter arguments.

From Dynamic Field documentation:

  A dynamic field can be used in combination with the Views Content Pane
  submodule of Ctools to pass contextual arguments to a view. Steps:

  Install Ctools, Views, and Display Suite.
  Enable the Views Content Panes module and Views UI.
  Create a new view. Add a contextual filter--for example, node NID. Add a content pane display. Configure the "arguments" argument of the
  display to enable the exposed filter you added. For example, select
  "From context" as the source of the argument and "Content ID" as the
  context.
  Create a dynamic field.
  Under manage display for a given content type, configure the dynamic field to use the views content pane you configured.


Best way of translating fixed text in Drupal 7

I would recommend looking at the String Overrides Advanced module it allows your Users to search for strings to translate into other languages using a friendly table, which it looks like you're trying to make yourself.

You're providing context here but the context you provide is not really the purpose of context. Context should describe the context of the string or word to help in the translation (not simply the place on the website the string shows up -- which is largely meaningless). An example of a context is:
https://api.drupal.org/comment/44448#comment-44448

which shows "Order" is a verb and not to be confused with a Noun for "drupal Commerce Order".

Note: I speak and write English and Spanish, when you write PHP code your php code should be in 1 language and not a mix of languages to be clear to developer(s) what you're code says. You shouldn't need to be bilingual to work on a piece of code. It makes your code needlessly complicated.


Reset the theme to bring back the content region with drush

drush vset theme_default 'bartik'

Then login at example.com/user/login


Theming: when I use a smaller device, my main content goes behind my sidebar

I took out the media selection of 480px for the content, and everything seemed to be working. I narrowed it down to a width: 100%. (inside of the media entry of course) After taking this out, everything was good to go.


I am having the same problem. It seems like there is no way to add 'flag' relationship in view used by facets..
The way I have done this is:

I installed the module 'Views PHP'
(https://drupal.org/project/views_php)
Added a 'global PHP'
field in my faceted view.
called the function to create flag
link and printed the link in the global php field: print flag_create_link('bookmarks', $data->entity)

Dont know why, my php view cudn't render $row->nid, thus I used $data->entity for node id.

Remember to enable php filter once views php is installed.

Hope It helps.


Specific permissions for rules components

Rules provides a UI to configure access to components based on a permission.

Edit the component
Click to expand "Settings"
Check "Configure access for using this component with a permission"


Part of your question is "... only want to allow editing the blocks provided by the Nodeblock module". Whereas the purpose of that module is like so (from its project page):

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

Together with "... I want to give users with a certain role the permission to manage some (but not all) blocks ..." (as in your question), it seems that a translation (summary) of your question is something like "How can I allow the content managers of my site to manage some (but not all) blocks (eg: edit the block text and title) without having to access the block administration page".

Using the Bean module you can perfectly allow your content managers to ""manage some (but not all) blocks (eg: edit the block text and title) without having to access the block administration page"". Here is a quote about the Bean module (from its project page):

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

Combined with the options available for granting the appropriate Bean permissions, it should give you a lot of flexibility about how exactly you want to use this (great) module in your specific case: for each Block type created with the BEAN module, you can use the typical Permissions page (at admin/people/permissions) to grant Add/Edit/View/Delete access to selected roles (Note: these are 4 separated permissions also). So if you'd create one such "block type" for the role "content managers", then all users with that role (and only those) could then Add/Edit/View/Delete such blocks.

Possible bonus: would you still need the Nodeblock module?

Some more background info about BEANs:

To define a Block type you use the admin UI (via admin/structure/block-types), which is similar to defining content types (via admin/structure/types).
The difference is that you don't create nodes (of a selected "content type", and by using node/add), but blocks instead (of a selected "block type", and by using block/add).

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

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

Remark: interesting detail on the Nodeblock project page:

  ... There are several other modules and approaches that allow nodes to be presented as a block. See a comparison at http://groups.drupal.org/node/93499 ...

And this last link states the following:

  The Bean module does not allow nodes to be presented as blocks, per se, but creates block entities instead. Since entities are the fundamental unit of Drupal 7 content, this is analogous and can accomplish many of the same ends.

This sounds like "Now that the BEAN module is available (it wasn't at the time this question was asked), you don't need blocks to be presented as nodes anymore to do more advanced things with blocks" ... no?

PS: The Bean module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. AND it has been integrated (already) in core in D8. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8.


Where can I see screenshots of various themes?

Some can be browsed here http://themegarden.org/drupal6/


"Jirafe credentials are not set" warning from Commerce

Jirafe is an analytics, alerting, and automation platform that is deeply integrated into ecommerce, marketing, and other platforms.

The Jirafe module integrates Jirafe with Drupal Commerce, and allows the following features:

  View your visits, orders, revenue, conversion %, AOV (average order value), and RPV (revenue per visit). This information can give you a great summary of your business at a glance. See how your visitors become customers at 5 critical points in your application. Easily see when visitors leave your site, so that you know what areas of your site to improve.

As you are using Commerce Kickstart, the module is already enabled. To configure You just need to:

Click on the Reports tab of your administration menu, or access admin/commerce/jirafe
Enter your credentials (Application ID and Token) that you get from jirafe and click Save


How do I grant to roles dynamically created permissions?

After granting the permissions, you should call the save() method to make the code work.

if ($anonymous_role = Role::load($anonymous_rid)) {
  $anonymous_role->grantPermission($permission);
  $anonymous_role->save();
}


'block/plugin' show a selected node. When editing the available nodes are filtered by type (or views)

Ok, isn't exactly what I was looking for, but does the job.
I created a content "News Holder", then added a field using entity reference and multiple selects. This field I set to have the number of "News Content" that I want and them a just need to place this content (used panels in this case).
This field can be configured to show a list (select list) of entities that the entity reference can reference.

So, using this way the user with admin privileges viewing the page can click the cog icon and edit, to edit this node. In the edit page he have direct access to the selects of the news content. It's direct and easy to use.

If someone still manage to do something similar or better, I would love to read =)


These variables are not available to template files, but you can easily add it to every template file by implementing hooks.

You need to prepare variable for twig files. To use the global variables in twig files you need to set it.

Prepares variables for the page template:

You will get details  template_preprocess_page.

function template_preprocess_page(&$variables) {
  $variables['base_path'] = base_path();
}


I just developed a small module named as Auto Unblock Users to unblock users.

This will only work if the user is blocked by Login Security module.


How do I create a multi-select checkbox field in a content entity?

This configuration worked for me:

 $fields['device'] = BaseFieldDefinition::create("list_string")
      ->setSetting('allowed_values', ['desktop'=>'Desktop', 'mobile'=>'Mobile', 'na'=>'N/A'])
      ->setLabel('Device')
      ->setDescription('Select associated devices')
      ->setRequired(TRUE)
      ->setCardinality(-1)
      ->setDisplayOptions('form', array(
        'type' => 'options_buttons',
        'weight' => 6
      ))
      ->setDisplayConfigurable('form', TRUE);


You can use path_is_admin():

if (!path_is_admin(current_path())) {
  // Do something...
}

Or check the theme:

if ($GLOBALS['theme'] == 'some_theme') {
  // Do something...
}


Content not showing up by default with exposed filters

In exposed filter section try to deselect all values in Select terms from vocabulary Event type field


Zen sub theme: page--node--name.tpl.php not working!

Drupal doesn't provide content type based template suggestions for page.tpl.php but for node.tpl.php. That means you can use a template like node--custom-content-name.tpl.php.

However, if you want to have a page.tpl.php for your content type, you need to tell Drupal about your template suggestion. Put this code in your template.php file:

function YOURTHEME_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
    $content_type = $variables['node']->type;
    $variables['theme_hook_suggestions'][] = 'page__' . $content_type;
  }
}

You should name your template file like: page--custom-content-name.tpl.php.


Delete the comment fields from the Article content type and uninstall the Comment module.


How to unset $page['#attached']['html_head_link'] from head?

OK. I found fresh module for this trouble. Module's author use hook_entity_view_alter() for implements head render. Check out their git respository to download the module and get the full code with comments.


Best Option: Use a non DB cache backend like Memcache
Next Best: Use a MySQL derivative that supports blob columns in a memory table and convert all cache tables to be of the type memory. Be sure to rebuild the indexes as BTREE's instead of HASH after converting to MEMORY. More details on this can be seen in this presentation: http://www.percona.com/resources/technical-presentations/drupal-and-mysql-performance-percona-live-mysql-webinar
Still good: Follow the directions here: Drupal 7: Database select query FROM cache_bootstrap brings server down

Note that all 3 of the above options are independent from each other; so you can do all 3. Also noted that the answer in #3, his database server was configured reasonably well; you might need to tune InnoDB in order to get better performance out of your's.

EDIT:
Also checkout my guide on tuning D7 https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG_KmVdZ7-o6Pok/edit#slide=id.p


The title is set as translatable by default (in the entity definition). Somehow you've disabled translation for this field. You can check the translatable fields for content entities here:

/admin/config/regional/content-language

This includes all fields, also the base fields, which you can't configure in Manage Fields of the content type.


Are old nodes automatically archived over time?

Drupal does not archive or otherwise delete or modify content automatically over time. There are a few possibilities as to what happened to node1 including:

An administrator or someone with permission to delete nodes of that content type deleted it
there is a rule or other module configuration that deletes nodes after a certain amount of time
Node 1 was deleted a long time ago and someone changed the front page after the fact (not likely as I think drupal verifies the path when you save that setting)

Drupal does keep a record of when nodes are deleted in the watchdog table. The watchdog table has a UI which can be found at /admin/reports/dblog. You can filter this list by type, but note that Drupal only stores a finite number of rows in this table with First In First Out as a rule. So it's possible that the record of node 1 being deleted has also been deleted.


Why should you use theme(), rather than calling the theme functions directly?

You have to use the theme() function for the override system to work. For example, your theme may override the theme function for a module, or a template (.tpl.php) file might be used instead.


How do I model content (types) from a database-centric point of view?

I'm assuming this question is about Drupal 7 ... Only using Site Building features (no custom module development yet) should get you pretty far (if not far enough ...).
The Relativity Data Model for Drupal
Have a look at the (illuminating) article "Relativity Model for Drupal", for which this is an introduction to it (quoted from this linked page):

The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:

Data architecture and data modeling merging as a single step through a documentation procedure.
Customized user interfaces that cater to individual workflows throughout permission roles.
Multi-level relational data structures that relate to other multi-level relational structures.
Mimicking the concept of database joins within Drupal's UI's.
Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

The small handful of modules (cfr. the last bullet) is like so (apart from Drupal core):

https://www.drupal.org/project/ctools
https://www.drupal.org/project/date
https://www.drupal.org/project/entity
https://www.drupal.org/project/entityreference
https://www.drupal.org/project/entityconnect
https://www.drupal.org/project/field_group
https://www.drupal.org/project/token
https://www.drupal.org/project/pathauto
https://www.drupal.org/project/views

This same topic is also presented in the video "Revolutionary DRUPAL Data Modeling Concept!! (This will change your Drupal life!)".
Typical add-on modules
Even though that small handful of modules above can get you already extremely far, I often add a subset of other contributed modules to it also, as further detailed below.
Tables, Columns and Foreign keys

Tables: Use the Entity Construction Kit (ECK) module to create 'entities' (= fieldable things ...). In your case that would be entities like Cities, District and Appartment.
Columns: For each of those entities use "fields" for each of the columns you mentioned. Should you run into fields such as dates, you would have to add modules such as date also.
Foreign keys: For the "foreign keys" use the Entity reference module (possibly some related modules of it also, extending its functionality, as mentioned on the ECK project page) and/or the References module (cfr. 'node_reference' and 'user_reference' as contained in CCK for D6).

Business logic
Using the Rules and Flag module, it is possible to implement all sorts of business logic (= rules), simply using the typical Drupal admin UI for those modules.
Queries, custom reports and charts

To perform queries (listings, etc), use the views module, possibly further extended with modules such as Views Slideshow: Galleria (there are dozens of modules to further enhance views).
The Forena module can be used as a supplement / alternative (e.g. if you'd need to also create charts or so, or if you have a need to access data in some external database such as MS SQL, Oracle, etc).
Create charts using the views integration of the Charts module to visualize a lot of data in a way that can be quickly digested.

Page Layout
Modules like Display Suite and/or Panels can help to enhance the look and feel of it all also.
Many more modules

Group (a pretty new alternative to Organic groups, to create arbitrary collections of your content and users and grant access control permissions on them).
Workflow (to create arbitrary workflows, and assign them to entities).
IP Geolocation Views & Maps, a mapping engine to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet)
Or, or  ... on and on goes the list.

Disclosure: I'm a (co-)maintainer of Forena and Charts.


Menu system - accepts extra args on path

I don't think you can do that in a general way, this is a behavior that's by design and many modules rely on this, so you would break their optional arguments. In fact, relying on this is currently the only way to support optional arguments without defining a menu router item for every possible combination.

If you want to do it for a specific page callback under your control, you could check if there are any arguments passed to your function with func_get_args() and if so, return a 404.

Note that this "feature" might be removed in 8.x, I've seen it mentioned in an issue.


The safest thing to do is to use the #attributes Form Control Attribute. You can specify a CSS class to target this element to then supply some css rules to indent these elements in your sites theme.

Similarly, you can add a class to add a line break somewhere within the widget markup to create your linebreak. Be sure to notice that the class example in the linked documentation takes a PHP array of class(es) (not a string label for the class) ... that messed me up last week for like 20 minutes.


What is the purpose of the Version Control API module?

Documentation, as Clive pointed out, provides good technical explanation. For those who need more "human-readable ones": Every time you download module from Drupal.org or any Drupal page, use issue queue or in any other way interacts with module or theme version, you are using Version Control API or other module with the same purpose.


You are missing the base hook definition. See how system_theme() does it for block templates. So, add 'base hook' => 'node' and it should work.


how to import from csv file to EntityForm

There doesn't seem to be any contributed module available for importing Entityform submissions from CSV.

You can simply try creating a small module which read CSV data and import Entityform submissions. To do this you can simply write a batch operation using Batch API and create Entityform Submissions using code snippet available here.

Another way could be to try Bundle Copy module that works with major entity in Drupal Core and also provide simple API for new/custom Entities. I've not tried Bundle Copy with Entities other than Node. You can try if this works with Entityform if not you can use its API and extend it.


Assign a row class like "row-1" for row 1, "row-2" for row 2

There are plenty of ways to go about this question, my suggestion is overriding twig templates.
You would need to override the Twig template for that view. If you enable debug, clear cache, inspect element, you will see the template for that view. Then for that twig file, just use the loop index
loop.index  The current iteration of the loop. (1 indexed)

to track which row you are in.


Display NOT a title field in Entity Reference field but my own field

If by "resolve" you mean what is searchable in the entity reference autocomplete field, then yes you can change the entity selection mode in the fields settings from simple to view and create a custom view to populate options. There is a good step by step tutorial on how to do that here: http://www.jackrabbithanna.com/articles/creating-entity-reference-view


Search API Saved Search tokens output [search-api-saved-search-result:url] has cron.php in urls

Here is the solution .  thanks to these answers Formatting output of token

/**
* Implements hook_tokens_alter().
*/
function rcn_tokens_alter(&$replacements,  $context){
  // fix urls being outputted with cron.php in the link.
  if(isset($replacements['[search-api-saved-search-result:url]'])){
  $url = $replacements['[search-api-saved-search-result:url]'];
  $newurl = str_replace("cron.php/", "", $url);
  $replacements['[search-api-saved-search-result:url]']  =   check_plain($newurl);
  }

}


Creating and storing data in the database

You don't have to worry about the database. But do some reading on how the forum works. If you're not getting any error messages you probably didn't set it up correctly.

Visit this page to see a list of all your forums: www.example.com/admin/content/forum/list

And some reading:

The Drupal forum tutorial
Forum: create threaded discussions - there are sub-menus depending on your version of Drupal


How to check if a database query has results?

If I'm correct the result of the execute() call should be a DatabaseStatementInterface which has a rowCount function.


Moving a div down if a zone is present using jQuery

At a guess I'd say your problem is context...$(this) won't be defined in your current code.

First thing to do is make sure the code runs on document ready so the elements you're targeting actually exist:

(function ($) {
  $(function() {
    // ...
  });
})(jQuery);

Next you need to handle $(this). In your current context you would need to check the <body> tag for that class, e.g.

if (!$('body').hasClass('responsive-layout-normal')) {
  // ...
}

And finally, since you're using a responsive theme you probably want that code to be responsive, and run when Omega changes its media query. Note that now, since you're binding to the <body> tag, and have proper context, $(this) will refer to the element you're expecting:

(function($) {
  $(function() {
    $('body').bind('responsivelayout', function(e, d) {
      if (!$(this).hasClass('responsive-layout-normal')) {
        // Make changes
      }
      else {
        // Undo changes
      }
    });
  });
})(jQuery);


The problem was the site didn't have writing permissions to the database. This meant that on installation of the module the necessary tables where not created and thus the above problem occurred.


How to show data of user that flagged a content(5 flag types or more)?

As per the "alternatives welcome also" in your question, I would format/present the data in your table in a different format/layout. which will make the data shown in it way more easy to digest/understand.

Have a look at this alternative, which shows the same data (to which I added a few more similar sample rows to illustrate what I mean):

---------------------------------------------------------------------
| User   | Email       | Flag A | Flag B | Flag C | Flag D | Flag E |
---------------------------------------------------------------------
| John   | John@a.com  | 4333   |        |        |        |        |
---------------------------------------------------------------------
| Jack   | Jack@b.com  | 9000   |        |        | 1390   | 7677   |
---------------------------------------------------------------------
| Hamed  | Hamed@c.com | 0123   | 0456   | 0789   |        |        |
---------------------------------------------------------------------
| Niall  | Niall@d.com |        | 3377   |        | 5566   |        |
---------------------------------------------------------------------

If you agree, note however that creating such table is not obvious if you're trying to do so with the Views module. However, using the Forena module (disclosure: I'm a co-maintainer), creating such table is straight forward: it's what is called a Crosstab table. This is a table with a special layout. It is formatted as a grid, with:

the rows representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), names of Models, etc.
the columns representing one or more other facts, such as periods (months of a year, years, etc), available types/flavors of something (like types of errors), etc.
the intersections of rows and columns containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) include a hyperlink to a drill-down report.

For more info on this, have a look at the "Northwind database" demo videos, i.e:

How to create a report/graph about Shipping summary (fast forward to about 4:15 if you're not interested in the SQL query prototyping part of it).
How to create Crosstab Tables and (related) charts (fast forward to about 2:15 if you're not interested in the SQL query prototyping part of it).

To create such table for each "content page" (as in your question), you can use an appropriate Report parameter, which is like the equivalent of a Contextual filter. In your case, the node's id (= nid) would probably be a good candidate for such parameter. Have a look at this example report, and note the query string (= state=OH) in its URL. Just change that string to, eg,state=IL (or select some other value for state in the Parameters form) to get the basic idea about such parameter. Refer to the tutorial about Forena report parameters for more details about this topic.

This technique can also be applied to any of your entities you want to create reports about (nodes, users, whatever). For example, after you enabled Forena in your own site, you'll have access to one of its sample reports (= Active users), located at /reports/drupaladmin.active_users. If you then follow the link "logs" in that report for any of the users in the report (say with user name = SomeUserName), you'll get the (log) details about that user, via an URL similar to /reports/drupaladmin.user_logs?name=SomeUserName. So in this case the user name is used as such report parameter also.


Migrate content from drupal8 to drupal8 programmatically with Node::load and Node::create

You might consider using Migrate module for this task. For pulling entities from external database use Drupal 8 migration module.


Theme select field with ul li in register form

I think you have to try using a widget that looks and acts like a select list, but is made HTML list & Javascript.


Exporting a group of pages as a single or multiple PDF programatically

I think your best choice here is Views Bulk Operations, you can create a view that lists your content and add the filters and fields you want and then generate the pdf using one of the modules for that matter, such as Views PDF or the Print module. You could generate actions that will be executed by the Bulk operations, one option to do this is to use Rules and Rule sets that are automatically exposed as VBO actions.

You've got a screencast on how to do this in https://www.youtube.com/watch?v=PszjYSq7xQQ and step by step here: http://blog.hsl.virginia.edu/drupalpress/views-pdf-vbo-rule-sets-thousands-of-custom-forms/


Converting a content type into a Profile2 profile

To your first question, create a view of the required information and using the Views Data Export module you can export it to a csv file.

Then you can import the information to users and profiles using the User Import module.

To your second question, Rules will do it for them. Create a new rule executed on the event 'After Saving New Account' with the action of 'Create an Entity' and define the node you want created, using the new user as author.


How to automatically load block--[blockname].tpl.php to region--[regionname].tpl.php

There is no theming function to do this, and there cannot be, because assigning block to regions is more logic than theming matter. So you should do it at module level.

When you are implementing hook_block_info(), you can specify default region, like this:

$blocks['example_empty'] = array(
  'info' => t('Example: empty block'),
  'status' => TRUE,
  'region' => 'sidebar_first',
  'visibility' => BLOCK_VISIBILITY_LISTED,
  'pages' => 'node/*',
);

You can also use hook_block_info_alter() to provide default regions for blocks not defined in your module.

See Examples for developers, block example for more details and samples.


Change page title from Views preprocess function

I don't think hook_preprocess_views_view() or hook_preprocess_page_title() is good ways in your case. You can use hook_views_pre_render

/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(ViewExecutable $view) {

  if ($view->id() == 'VIEW_ID') {
    $arg = $view->args; // Argument from view.
    $default_title = $view->getTitle(); // Get view title.
    $view->setTitle('New title'); // Set new title
  }
}

All variables you need in here.


Drupal Form Suffix + Suffix As a href + pop up the drupal users listing with checkboxes by click on that link

What you need is pretty much a huge select box :)

i can think to a couple of different approaches, but to mention one, i would proceed like this

Create your form and set the default values obviously.
At the end of your form add a  that will wrap around the list of possible choices
Target that  with the show/hide script triggered by the click on the link.
Create the list, using either a table or several divs, as long as you give each row an #id, something like
user-$uid".
since you are here you can even set a class for the rows that will highlights the row on hover.
Split each row into, assuming tables, cells and populate the table with the user data you need.
give each cell the same #id of its row, extend with something else to obtain things like

"user-$uid-mail"
"user-$uid-name"
I would avoid the checkboxes and go with an onClick event on each row, that calls a function passing the row #id as parameter.
The function will, hide the list, use the row #id to read the values of the fields, like

document.getElementById("user-$uid-name").value

and write the values inside the form elements.

profit.
i may have typed some function wrong, but that's the idea


Are the revision settings on a content type respected when the content is changed programatically?

No, not by default, if you're using node_load() & node_save(), without any other code, it will not retrieve the content type's revision setting. For example:

$my_node = node_load(123);
$my_node->title = 'new title';
node_save($my_node);

node_save() uses the $my_node->revision property to determine if it's creating a new revision. In the above example, $my_node will not have the revision flag set from a node_load() retrieval.

If you manually set the $my_node->revision to TRUE it will do this:

$my_node = node_load(123);
$my_node->revision = TRUE;
$my_node->title = 'new title';
node_save($my_node);


How to save content type before saving an exported view through code?

Change your install function to

$name = 'your content type Machine name';

// Define the node type.
$jobs = array(
'type' => $name,
'name' => $t('your content type name'),
'base' => 'node_content',
'title_label' => $t(' Title'),
'description' => $t('Description.'),
'custom' => TRUE,
);

// Set other node defaults not declared above.
$content_type = node_type_set_defaults($jobs);

Remove node info hook from .module file and start your function name in .module file with your module name.


taxonomy menu select list with redirect when a menu item is selected

Try Autocomplete Deluxe, it has a taxonomy widget available for use, and I used it just the other day and I believe that it does what you need it to do.


How to make a page look like it would have w/o tpl

To see the array $var / $variable -

echo "<pre>";
print_r($var); //or $variable whichever is applicable.
echo "</pre>";

This will output the entire $var/$variable array in structured manner and you can find out all the data available in your tpl.

Hope that is of some help...


How to set multiple error messages with form_set_error?

I would change the code to issue a single call to form_set_error() per element:

$errors = array();
if (strpos($form_state["values"]["body"], "<h1") === true)
    $error_messages["body"][] = "Blalalabalbal bablalbabla.";

if (strpos($form_state["values"]["body"], "<h3") === false)
    $error_messages["body"][] = "Do this do that balbablalba.";

foreach ($error_messages as $element => $messages) {
    form_set_error($element, theme('item_list', array('items' => messages)));
}


Why don't you try Autocomplete Widgets for Text and Number Fields

This module adds 3 autocomplete widgets for CCK fields of type Text and Number.

Autocomplete for allowed values list: This widget can be used for Text and Number fields and it takes candidate values from the defined list of Allowed values of the fields. You can even generate your allowed values list using PHP, so the limit to provide a widget with autocomplete features is your imagination!
Autocomplete for existing field data: This widget can be used for Text only and it takes candidate values from existing values in the database for that field.
(7.x only) Autocomplete for predefined suggestions: This widget can be used for Text only and allows an admin to provide a list of suggestions but still allows users to enter anything they want in a text field. Use this widget to help avoid (but not prevent) variations of the same value. Ex: burger, hamburger, Burger ...
(7.x only) Autocomplete for existing field data and some node titles: This widget works just like the "existing field data" widget above except it will also suggest node titles for nodes of a specific content type(s).


You might want to have a look a the Secure Pages module, which is:

  A small process which will redirect the required pages to a SSL version of the page.

You can easily set up the user/login path as an SSL-required page, and the redirect will be handled for you.

If you want to do it manually, a rule like this in .htaccess would probably work:

RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^user$ https://%{SERVER_NAME}/user [R=301,L]

That would need to go above Drupal's main rewrite rule for index.php.

It's worth bearing in mind you'll need to do this for the user/login path as well as that can be accessed directly.


How do I check radio buttons in Twig template?

That's a task for #states not for Twig. I think this also could be ajaxified a little bit more elegantly but using #states on some items does the job as well.

$form['payment'] = [
  '#type' => 'radios',
  '#title' => $this->t('Payment Mode'),
  '#options' => [
    'chk' => $this->t('by check'),
    'tfr' => $this->t('by bank transfer'),
    'crd' => $this->t('by card'),
  ],
  '#required' => TRUE,
];

$form['chk'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Check'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'chk'],
    ],
  ],
];

$form['tfr'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Bank Transfer'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'tfr'],
    ],
  ],
];

$form['crd'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Card'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'crd'],
    ],
  ],
];


How to skip "Checked available update data for" all modules when I just want to update core or a specific module?

Drush calls Drupal code to update the list of available releases, so regrettably there is no way to update the release info for just some subset of available projects.


You need to download internationalization module and enable field_translation module which comes in this package. How to translate the field labels:

Go to manage fields. For ex. Articles, the path will be admin/structure/types/manage/article/fields/
Click edit for field_tags.
You'll see a translate tab there. I have attached the screenshot.
Translate field name and description there. It works.


How do I implement cookieless subdomain?

All these cookies are set from/belong to the main domain www.example.com;

Check your $cookie_domain value in settings.php

/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on its full domain name. If you have multiple domains pointing at the
 * same Drupal site, you can either redirect them all to a single domain (see
 * comment in .htaccess), or uncomment the line below and specify their shared
 * base domain. Doing so assures that users remain logged in as they cross
 * between your various domains. Make sure to always start the $cookie_domain
 * with a leading dot, as per RFC 2109.
 */
# $cookie_domain = '.example.com';

the leading '.' means the cookies also apply to subdomains.

You could try something more specific, to restrict the drupal cookie domain, like:

$cookie_domain = '.www.example.com';


How to get friendly URLs to work in a headless implementation?

if you use drupal headless its mostly up to the front end framework to implement friendly urls

for react you will probably use routes but since this is beyond the scope of this forum the question might also be deemed as irrelevant


How do I remove the title field from a node's custom view mode

The output of the title is different from the other fields. The reasons for that is, that the title is used for the title block and as metadata in the html head:

html.html.twig:
<!DOCTYPE html>

    <title>{{ head_title|safe_join(' | ') }}</title>

If the node is used in another context, for example when it is part of a view, the title is placed in the node template as {{ label }}:

node.html.twig:
  {% if not page %}

      {{ label }}

  {% endif %}

This is controlled by the variable page, a boolean, which is true, if the view mode is full. This is standard in drupal, when the node is displayed as main content and the title should appear in the head.

If you want to change this default behavior, you have to edit the node twig or change the variable page in preprocess.

In preprocess this would look like this:

function theme_preprocess(&$variables, $hook) {

   if ($hook == 'node') {
      if ( $variables['elements']['#view_mode'] == 'teaser' ) {
         $variables['page'] = true;
      }
   }
}

This will remove the title from the view mode teaser.

Edit:

To answer the specific question in the latest comment, how to make the title field manageable in the display UI:

You have to change the field definition in a hook:

function mymodule_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->id() == 'node') {
    if (isset($fields['title'])) {
      $fields['title']->setDisplayConfigurable('view', TRUE);
    }
  }
}

Don't forget to remove {{ label }} from node twig, so that the title is not displayed twice.


You can use the Services Views module to expose the Profile 2 data you need.

  Views support for the Services module version 3.x and later.

  It has currently two features:
   - Create view based resource creating Services display in a view
   - Execute any view of the system via views resource call

  Demo video http://youtu.be/DZEhJKMeR5w


How to link Views Bulk Operations and Bibliography modules in a home-made search engine?

See this sandbox module that add export functionality for all results in a view as a footer / header: https://www.drupal.org/sandbox/szeidler/2394975


Article view with links to other articles

Add a  contextual filter: Content: Has taxonomy term ID (with depth), for displaying related articles


Maintain same node ID's when importing nodes

In short no (not easily/safely anyway).

If you're looking for specific content ID's, you may want to look into putting the UUID module on your source/destination site.  As far as I'm aware, this will allow you to keep a unique identifier on your nodes that match across sites, even though the node ID's will be different.


While migrating a site from a local instance to a staging instance there is always such problems of links of the images. we normally give myfolder/sites/default/files/images/myFile.jpg but while migrating to staging instance it should be /sites/default/files/images/myFile.jpg so that the server could trace the images.

If we use give myfolder/sites/default/files/images/myFile.jpg it would work fine within your local instance but while on staging it wont get loaded.

So always give /sites/default/files/images/myFile.jpg so that there is no problem....


You need to use a module like Pathologic which will force protocol relative URLs for all assets.

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

The public:// path is a stream wrapper, and has no effect on whether the browser sees http/https or not. Pathologic will fix all of this for you.


How to print custom text on search no result with search-results.tpl.php?

The core Drupal search module uses several template files that dictate both how search results are displayed, and what's displayed when there are no search results.

If you're already using a custom theme on your Drupal site, the best way to customize those would be to copy and paste the entire 'search-results.tpl.php' file from the search/ module folder into your own custom theme subfolder.

Open that file up for editing and you'll see the following at the bottom:

<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

This is what's displayed if search results are not found (thus the 'else')...  Modify the text to be anything you want here.  The second line, which calls the search_help() function is the one that displays the search suggestions.  Feel free to replace that too....

And as always, before you can see your changes, you'll probably need to clear cache!


Well it might seem a little noobish mistake but nevertheless, for everyone that is interested out there.

After a lot of research I found out how to make it.

The problem that arises when you try to render a form in a .tpl file is the functionality of the form.

I was trying to render $page['content']
and I couldn't do the above.

So I had to add to MYTHEME\template.php these lines:

function MYTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'commerce_checkout_form_checkout' => array(
      'render element' => 'form',
      'template' => 'commerce-checkout-form-checkout',
      'path' => drupal_get_path('theme', 'MYTHEME') . '/template/forms',
    ),
  );
}

and then I created: commerce-checkout-form-checkout.tpl.php in
MYTHEME/template/forms

and I just put this code inside:

<?php print render($form['cart_contents']); ?>

<?php print render($form['customer_profile_billing']); ?>

<?php print render($form['commerce_payment']); ?>

<?php print drupal_render_children($form); ?>

The key to render the form right was the last line:

<?php print drupal_render_children($form); ?>

which rendered all the missing funcionality (like ajax and submit buttons) from the form.

I hope this will help someone in the future to avoid all the time and hassle..


'heading' != 'paragraph heading' (in fact there's no such thing as an HTML paragraph heading). A heading tag is used to denote the heading of a section (a conceptual section, not necessarily a <section /> tag) - it doesn't have to be above, or any where near, a paragraph.

If you're interested in SEO, whatever you do don't convert them from an <h2> to a <div>. A <div> carries no semantic weighting whatsoever, while an <h2> does. If you're not happy with <h2>, obviously choose something else, but for the love of Matt Cutts not a <div> :)

Personally the only tags I'd recommend are <h2> (which is standard for adding a heading to a section in any website, not just a Drupal one) or <h3>, if you're already using <h2>'s to markup more semantically important sections elsewhere in the page.


If you are trying to search through a view's node title field, node body field, or some other string field specifically, you may be able to customize the filter how you would like:

Add filter Node: Title or Node: Body
Set the Operator to Contains any word
Click Expose
Click Update

This will display a filter to the user that can filter the view by the corresponding field values that contain any of the entered words, separated by spaces. This does not format the textfield into a textarea, but works functionally as you had asked.


How do I change the javascript loading order

To add a js library to the header, define your library in my_module.libraries.yml with the header: true property.

my_library:
  header: true
  etc ...

Any dependencies defined for your library will always be loaded before your library whether loading your js in the header or footer.

See Asset loading order section here.


You can write a views style plugin to get through this fast. Here is an example of that, which adds an outer wrapper of results plus a totalCount item:

<?php

namespace Drupal\mymodule\Plugin\views\style;

use Drupal\rest\Plugin\views\style\Serializer;

/**
 * The style plugin for serialized output formats.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "serializer_count",
 *   title = @Translation("Serializer with Count"),
 *   help = @Translation("Serializes views row data using the Serializer component and adds a count."),
 *   display_types = {"data"}
 * )
 */
class SerializerCount extends Serializer {

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];

    if (isset($this->view->pager)) {
      $count = $this->view->pager->getTotalItems();
    }
    else {
      $count = 0;
    }

    // If the Data Entity row plugin is used, this will be an array of entities
    // which will pass through Serializer to one of the registered Normalizers,
    // which will transform it to arrays/scalars. If the Data field row plugin
    // is used, $rows will not contain objects and will pass directly to the
    // Encoder.
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[$row_index] = $this->view->rowPlugin->render($row);
    }

    unset($this->view->row_index);

    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }

    return $this->serializer->serialize(['results' => ['items' => $rows, 'totalCount' => (int) $count]], $content_type, ['views_style_plugin' => $this]);
  }

}

Then clear cache, and change the plugin for the View under "Style".

So in your case, the final line would look like:

return $this->serializer->serialize(['items' => $rows], $content_type, ['views_style_plugin' => $this]);


There are two things I try to keep in mind when making this decision.

Is this a functional feature, or a purely visual one?  Functional components go in modules.  Purely visual ones go in the theme.

What happens if I alter or radically change the theme down the road and/or allow multiple themes for my site?  If you don't want to replicate the feature, then it should go in a module.

Drupal does make it easy to intertwine content, business logic, and presentation.  For the long term maintainability of a site, you really need to be careful when you implement things.

A good rule of thumb is that a theme should not need to know about IDs ($nid, $uid, $tid, etc) for anything, and should only need to know machine names to alter visual appearance.

In your case, adding a form to a node is a functional change, and I would really put that in a module.


Go to /admin/config/content/formats and check the CKeditor is enabled for FULL HTML. Also, could be a role issue, by default Full HTML is for admins only.

Important:
For safety/security reasons FULL HTML should be used by admins only. You're better off using basic_html as your format if this form is for authenticated or anonymous users. You may need to adjust the roles so anonymous can use it.


Replace textfield value on ajax callback

function test($form, &$form_state) {
  $form['your_name'] = array(
    '#title' => t('Your or your company name'),
    '#type' => 'textfield',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (isset($form_state['values']['your_name'])) {
    $form['your_name']['#value'] = 'if';
  }
  else {
    $form['your_name']['#value'] = 'else';
  }
  $form['load_settings'] = array(
    '#type' => 'button',
    '#value' => t('Load my settings'),
    '#submit' => 'simplenews_mod_load_subscriptions',
    '#ajax' => array(
      'wrapper' => 'subscribers-name',
      'callback' => 'simplenews_mod_load_subscriptions_ajax',
      'method' => 'replace',
    )
  );
  return $form;
}

function simplenews_mod_load_subscriptions_ajax($form, &$form_state) {
  return $form['your_name'];
}


Let the user add a PDF to a content type, but not as an attachment, content type is the pdf

This doesn't exactly answer your question (since maybe there is a module for that, but not that I'm aware), but here is what I do.

I have a content type for documents with two fields: summary/abstract and then a file upload field that accepts PDFs. If a PDF has a summary or abstract, I put the summary/abstract in that field and just link to the content's page figuring that the user can read that and then click on the document if they want. Otherwise, I still use this document content type to upload the file, leave the summary blank, and then link directly to the uploaded file itself. It would still have its own page created by the content type, but a site user isn't going to see that.


You may use Webform module and read this.

The full documentation is at http://drupal.org/documentation/modules/webform.

You can achieve the conditional field with Webform Conditional.

  This modules enhances the existing Conditional Rules of the Webform
  Module. It adds the ability to make components dependent on select
  components(i.e. listboxes, radio buttons, and checkboxes) that appear
  on the same page.

Here's a youtube video Screencast demo.

  Webform already has support for conditional fields on multi-page
  forms. For example Field C on Page 2 can be dependent on Field A on
  Page 1. This module adds the ability to have conditional fields on the
  same page. This module adds the ability to have Field B on page 1 be
  dependent on Field A also on Page 1.

Check the version of the Webform module; you may have it already.