How to connect to multiple Databases in Drupal 7? I'm building an encyclopedia website. There are about 20 subjects that must be stored in the Database (media,library,article,translations,...) and we want to create 20 databases and allocate one DB for every subject. is it possible to do such thing? The main site has 3 sub domains and every sub domain covers specific rows of the subjects. for example the library is a subject and math.mainsite.com must have access only to the math type of the library subject.

the sub-domains must not have not any data, they all should get their data from the 20 above mentioned DBs, so every site must connect to 20 DB.

We selected this strategy because the subjects are subdomain as well, I mean library.mainsite.com and article.mainsite.com and ... are valid urls.

thanks

Two steps:

Add database credentials to the $databases array in settings.php file. You can have as many additional databases as you want. Example code:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'YOUR_DEFAULT_DATABASE',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'your_second_db_alias' =>
  array (
    'default' =>
    array (
      'database' => 'YOUR_SECOND_DB',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Use the following code to change the database and run queries. Note that you must switch back to the original database afterwards.

// Change active database.
db_set_active('your_second_db_alias');
// Run queries.
$query = db_query("SELECT * FROM yourtable");
// IMPORTANT: return current active database to the default one. If you
// don't do this, everything after that point will be executed against the
// above database, and cause errors most probably. If you are connecting
// multiple Drupal installations, you can cause a pretty big mess if data is
// partially saved in the other database.
// Always double check that you have this line!
db_set_active();

Hope this helps!


How to change my maintenance page? As the title explains, I want to make a custom maintenance page, different from the default one.

For that I've read this tutorial: Theming the Drupal maintenance page.

I copied the file /module/system/maintenance-page.tpl.php to my theme folder, changed it a little bit, and I enabled the $conf['maintenance_theme'] = 'themeName'; line in settings.php; but I can't see the changes

What else do I need to do?

Hope this will help you,

Before site goes offline for maintenance mode, check the user who has permission to access the site during maintenance mode via admin/people/permissions
and check for this permission Use the site in maintenance mode. Default access will be given to the admin.

In Drupal 7, to create a custom maintenance page we have to override the default maintenance template file

We can do it by the following steps:

Copy maintenance-page.tpl.php from modules/system/
Paste it in active theme folder inside templates folder
ie., sites/all/themes/your_theme/templates/
Make the changes in new maintenance template file.
Clear the Drupal cache - configuration > performance > clear all caches

Note:

If you want how to Put Drupal 7 in Maintenance Mode, you can go through this link
To bring the site back online

The user who has permission to access the site during maintenance mode can
able to login using login page
Go to admin/config/development/maintenance and uncheck Put site into maintenance mode and save it.


Drupal and mobile - integration across multiple applications I have Drupal installed to Amazon EC. I was wondering is it possible to make another database so that mobile users can upload pictures with location there and users from the Drupal website can see these pictures? What would I need to do?

You need something like next, right?

User upload image from mobile application
User can see it in site

If it's right - it's not need new database, all can be maked with one. As one method - you can create special node type and one of next things:

Create custom module, that create new nodes (in my opinion - it's better)
Submit node creation form from application


Pass views filter from URL How do you pass a filter value by url in drupal 8?

On my website I have a view with a select to filter the results. This result is based on taxonomy term.

I have 4 options, All, badkamerrenovatie, elektriciteit and verwarming.

How can I set the filter by url so that I directly have a filtered list if people click on a link related to the taxonomy term. For example if people are on page elektriciteit and click trough to realisatie they see the filtered list and don't have to choose from the select.

This can be done using Contextual Filters under Advanced Settings of View Edit Page. You can add URL parameters as filters in it. This link will help you in detail

Thanks


Link pages from a child term to it's parent I have really two questions in one. I have pathauto make a page for all my terms. I have something like this:

USA
-NY
-NJ
-LA
UK
-London
-Hogwarts
-Manchester
France
-Paris
...

Anyway pathauto made pages for all the terms, so I have site/USA , site/USA/NY etc. I want to make it so that site/USA/NY has a link to it's parent which is site/USA. Is there any way to do this?

Another question, I'm also using the hierarchical select plugin to make a user select the deepest child possible (in this case just one level in). When a user tags content with NY, I also want that content to be tagged with USA, is that possible?

Node will have relation with the child term but there is no direct relation between the node and parent term.
So i think there are two ways to do it..
ONE : use node api and attached the parent term with the node.
TWO : while displaying the node fetch the parent term of the term and show them as well.


How to delete all unpublished comments? I have literally thousands of unpublished comments. I am wondering what is the easiest way to git rid of them altogether.

Thanks

The better way I think is to use Views and Views Bulk Operations and you can do a simple admin interface to delete all of them.

Otherwise, you still can delete directly throw a SQL query.


create a webform node with multi lingual language How to create a webform node with multi lingual language like french,spanish in drupal 6. so that when i hit the url it should display in particular language? webform localization is not supporting in drupal6. is there any other way around to do this. pls help?

You can use Internationalization module to achieve this functionality.

  This is a collection of modules to extend Drupal core multilingual
  capabilities and be able to build real life multilingual sites. Some
  features:

  Taxonomy translation (both, per language terms and translatable    terms) Multilingual variables
  Multilingual blocks (control visibility per language and translate    title and content)
  Language selection (when you switch the site language you'll see only    the content for that language)

Edit:

You need to set up translate of each node. If you create node/2 as defualt language French, then you edit the node and click on translate tab in top of page and set up translate node in spanish language.

If you view node/2 and select spanish language, then it will display the trasnlated node of node/2 in spanish language.

Setting language:

Go to the Languages page (Administration > Settings > Language in
Drupal 6, or Administration > Configuration > Regional and language >
Languages in Drupal 7) and add and enable desired languages.

Setting Multilingual for content type.

Go to the Content types administration page (Administration >
Content > Types in Drupal 6, or Administration > Structure > Content
types in Drupal 7).
Select a content type you want translated, and select "edit", then
"Workflow settings" for Drupal 6 or "Publishing options" for Drupal
At the "Multilingual support" section, select "Enabled, with
translation". Be sure to save each content type after enabling
multilingual support.


Overriding 'user.login.http' method I am trying to override the core login method in Drupal\user\Controller\UserAuthenticationController by extending the UserAuthenticationController class so that I can inject custom data into the response object. I could achieve override by creating an Event subscriber service and using the alterRoutes method.

 public function login(Request $request) {
     $response_data = parent::login($request);

      return $response_data;

  }

However the response data is an object of type Symfony\Component\HttpFoundation\Response and there is absolutely no way to access the data. I would like to do the following but not able to modify the response object.

 public function login(Request $request) {
     $response_data = parent::login($request);
     $response_date = $this->fetchCustomdata($response_data);
     return $response_data;

  }

  private function fetchCustomdata($response_data) {
   // Do some work and return modified $response_dat
   return $reponse_data
 }

Is there any better way to inject custom data into the response parameters?

Note: The additional data I am trying to inject is additional fields i have added to the user profile like First Name, Email and other reference fields. It is required to deliver these along with the other default responses along with the default response on login.

Note: I tried copying the original method and modifying the data and it works but it goes against the good practice as we are trying to reduce duplication.

I figured out how to actually do this. We need to go to the class from which the object was instantiated and figured out any public getter and setter methods. This should be obvious for someone well versed with OOPs. Here is I managed to modify the response.

public function login(Request $request) {
  $response_data = parent::login($request);

  // We need to get data in the original response and there is actually a
  // a public method provided by the parent class getContent which we are using
  // below.
  $mydata = $response_data->getContent();

  // Original data is serialized so we need to decode it.
  $decoded_data = $this->serializer->decode($mydata, 'json');
  $uid = $decoded_data['current_user']['uid'];
  $user = $this->userStorage->load($uid);

  // custom function to process the user
  $mynewdata = $this->customfunction($user);

  // Adding to the original decoded response array and
  // then encoding again.
  $decoded_data += $mynewdata;
  $combined data = $this->serializer->encode($decoded_data, 'json');

  // Setting the content to the origina response object. Important!!!
  $response_data->setContent($encoded_sponsor_data);
  return $response_data;
}


Display field's content as an image I'm using webform_multiple_file. To display my submissions, I created a view and added as field Webform submission data: Value

To customize my view I used print $fields['value_1']->content ;

This displays somthing like this:

  image1.png

  image2.jpeg

But I want to display just the first data and as an image like

Below the HTML return

image1.png

image2.jpeg

Any idea please? Thank you

Try something like this:

file_dir  = $file_create_url("public://");

print 'content . '';


How can I turn off caching redirect? I have a url that would normally redirect to a specific page, however, some code is run prior to this. I am returning a RedirectResponse instance, and it appears to be being cached. How can I force this not to be cached?

A response built from the RedirectReponse class is not cached. So you should not need to set any cache metadata (*). The problem here is probably the page cache for anonymous requests, which caches all responses, even redirects and no matter if they are cachable or not.
You can disable this cache by using the kill switch before returning the response:
\Drupal::service('page_cache_kill_switch')->trigger();

This will only disable the Internal Page Cache. To control caches outside of drupal, like proxies or browser caches, go to /admin/config/development/performance and set a "Page cache maximum age".
(*)
On the basis of @Smartsheet eng's comment use LocalRedirectResponse directly to prevent that RedirectResponse might be converted to this response without cache metadata (which would be cacheable by default):
$response = new LocalRedirectResponse('/foo');
$response->getCacheableMetadata()->setCacheMaxAge(0);

You still need the kill switch because the Internal Page Cache doesn't process the cache max-age.


How to remove a prefix with hook_form_alter? Looking at the source of a module, it is doing this:

$form['buttons']['back'] = array(
  '#prefix' => t('or'),
);

Now I want to remove that prefix; I tried the following code, but it doesn't make any difference.

function mymodule_form_formid_alter(&$form, &$form_state) {
  $form['buttons']['back']['#prefix'] = '';
}

I tested the following code, but it doesn't seems to work; the prefix is now 'testingor'.

function mymodule_form_formid_alter(&$form, &$form_state) {
  $form['buttons']['back']['#prefix'] = 'testing';
}

I tried the following code, but it doesn't make any difference.

function mymodule_form_formid_alter(&$form, &$form_state) {
  unset($form['buttons']['back']['#prefix']) ;
}

What am I doing wrong?

The form ID for the form I am trying to change is "commerce_checkout_form_checkout" which is used from the Drupal Commerce module.

In your hook_form_alter the following should do the job and has the benefit of leaving the element there if required.

$form['buttons']['back']['#access'] = false;


How do I allow modules to provide their own view? In Drupal 7, there is hook_views_default_views() which allows modules to provide their own views. What's the equivalent for Drupal 8?

Views are config, so:

Create a View
Export the config for it as a single item using the UI or drush (removing the uuid if applicable).
Include it in your module’s ./config/install folder
Install the module on a different site; the View will be created automatically


how to add "new" or "updated" on a view In my administration content editing page (drupal 7), I have a little red "new " or "updated" next to some items.  How can I make these red labels come out in my views listing?

You may use field "Content: Has new content" in views to display "updated" text


Acquia cloud installing a module: private key file I'm currently building a CMS using Drupal 8 hosted in Acquia Cloud.
At this time of the process, the goal was to do the setup of URL Patterns.

In order to do this, I need to install the module Pathauto and its requirements (Token and CTools) [as it's shown here].

After some going around, found out the installation of modules isn't actually as straightforward as clicking a button, inferred from seeing the following screen (doesn't appear that functionality).

After some research, found that there's a page in Acquia documentation with an explanation of how to install a Drupal module on Acquia Cloud.

The approache I started doing was to develop the application locally using Acquia Dev Desktop, add new modules using local tools like Drush or the Update Manager, and then push the code to Acquia Cloud with Acquia Dev Desktop.

After installing Acquia Dev Desktop, I need to do the login using the Acquia Cloud credentials.

While on it, there's a button meant to allow to clone this site locally, which is what I want to do now.

After filling up all the details (sanitizing the database),

I'm asked to provide a private key:

In order to get that key, Acquia allows to generate automatically a public key (using the button "Generate" in this last image)

Once the public key was generated, to complete the process I'm redirected to this link. Following it I was able to generate the SSH key which appears under

  /app/profile/ssh-keys
   on my Acquia Cloud account.

After this, I'm in need of a Private key file to continue the process and i'm blocked.
Given this information bellow, what can I do to have it?

Attentively

Tiago

The solution was to forget about Acquia and start using cPanel.

In here, was as straightforward as creating a subdomain, taking advantage of Softaculous scripts by installing in that location the 8.4.3 version of Drupal.

Once installation was complete (which was a matter of seconds) and I've logged in as admin, installing a module was never easier!

See for yourself:

Tiago


Installation fails due to clean URLs I have a Drupal 8.0.1 installation running under Apache 3.4 from /var/www. During installation, I cannot seem to pass the requirements for clean URLs. I've read through answers I've found on Drupal.org, but to no avail.

Does anyone have any suggestions?

rewrite engine is required to use clean url and you need to intall on terminal by execute the below command.

sudo a2enmod rewrite


Separate Comment Form DIV from Comments DIV Is there a way to edit the output of a specific file/line of code that will remove the comment form div from the comments div? Currently, I cannot separate the two to place them next to each other, rather than stacked on one another. It doesn't really work with the theme I'm editing, but cannot find a way to remove it.

Here as a really basic example is how the code looks now:

    (comments go here)

    (comment form goes here)

But what I need is this:

        (comments go here)

        (comment form goes here)

Thanks ahead of time!

Answered in comments of question, edit the html within the comments.tpl.php file of the theme's templates folder.


View of attached files to a node I use D8 Editor File upload to add files to a node. But i want an overall view from all the files in that node, but only in that node. I can create a view for all the files but i can't filter on the nid of the current page.

The project: attachment_links seems to kinda do what i want but its only for Drupal 7.  Does anyone know of a similar Drupal 8 project or a way do code it manually into a block?

The D8 Editor File upload is using the Drupal file system, so the files uploaded through module do have FID and can be listed in Views.

Here are steps to create a block to show only the files used on the currently visited node:

Create a View of type File with a Block display showing Filename (you probably have this already)
Add a Contextual filter in your Views Block Display called Entity ID from the File Usage Category.
Adjust the settings for that Contextual filter:
When the filter value is NOT available
Provide default value
Type to Content ID from URL
When the filter value IS available or a default is provided:
 Specify validation criteria
 Validator to Content
 Content type [choose appropriately]
 Leave the rest as default
Place the Block in a region you like, adjust the Block options File Usage: Entity ID to Node from URL and restrict to display only on relevant Content types.

Now when you visit nodes of the types you selected in Block and Contextual filter settings will list only the files uploaded to those nodes.


CSS Mime Type transferred as Zip in Chrome - 15 second delay Resource interpreted as Stylesheet but transferred with MIME type application/x-gzip: "http://www.energyjustice.net/modules/system/system.base.css?m7sb47".

I turned off the CSS aggregate and compress option, and emptied the Chrome browser cache.  So I'm not sure why I'm still getting this?

If there is nothing in the cache, this error causes Chrome to have a 15 second delay in transferring the system.base.css file.  Firefox works fine.

Drupal 7.14
Apache/1.3.41 (Unix) with mod_gzip/1.3.26.1a
Chrome 20.0.1132.57

It looks like mod_headers is installed.

This is a TOTAL shot in the dark here, but:

1) are you running "Avast!" ?

2) If you load your site and look at network traffic (e.g. "Net" panel in Firebug), are there any 304 responses from the server?


Config Export: How to store default value of taxonomy field? When I define a field with taxonomy term fields, I can set a default value depending on the available terms. Since the terms themselves are content, they are not stored via configuration management. When I export the configuration on one server (e.g. development) and import it into a different server (e.g. stage), these values may differ. Especially two terms with the same value on the servers don't necessarily share the same tid.

When I set a default value in dev, then this value's tid maybe not be the same as on the stage server and thus no default value or a wrong default value might be chosen, if I insert a new content of the type that has that field.

How do I manage this?

I figured out the solution.

The value stored in the config/sync is not the tid of the taxonomy term, but the uuid. Because of this, I can just change the value of uuid column in taxonomy_term_data row of the dev's term to that of the stage's server without affecting the tid column.


How to use default field_image if value is not provided? We are using Schema.org Metatag module to display meta tag attributes to the Article content type. We have a field that we using as an ImageObject using the field_image field. The field_image is setup so that if an image is not selected, then a default image will be displayed in the twig templates.

We had to add a [node:field_image:large:url] into the url field under ImageObject. When an image is selected, the correct url is added to the page. However, when the image is not selected (a default image should be used), the url field is displaying empty.

How to get the token to display the default value is the image is not added through the node edit process?

Current behavior:

"image" : {
  "@type" : "ImageObject",
   "representativeOfPage": "True",
}

Expected behavior (when image is not selected)

"image": {
  "@type": "ImageObject",
  "representativeOfPage": "True",
  "url": "https://path/to/default-image/large/cloud.jpg",
  "width": "400",
  "height": "260"
},

Seems the default image procedure as it is now doesn't store a file ID or something more useful in that image field. Means the image field doesn't get populated properly.

What I'd try is to create a custom module that adds a config page with a form and a '#type' => 'file_managed'field. The resulting file ID on upload now becomes variable via \Drupal::configFactory()->getEditable()->set() (and together with the right config/install and settings YML files).

Then I'd alter the node form via hook_form_BASE_FORM_ID_alter (see comments) and add a custom validate and/or submit function. Maybe just an element validate callback on the image field. And then check on submit if this field is empty, and if so then retrieve the file ID from the config page via \Drupal::config()->get(), load the file and save it into the image field (maybe the file ID is just enough).

Now the image field should be populated properly and everything else should work as expected.

Proof of Concept

OK I just tried what I wrote above and it's working quite fine. Except I didn't use the node form but hook_entity_presave instead to check if the image field is empty before setting the file ID retrieved from the settings value of the uploaded file on said config page.

Download or clone https://gitlab.com/leymannx/tdi
into /modules/custom.
Enable the module.
Go to /admin/config/media/tdi and upload a default image, save.
Now in your IDE or code editor open /modules/custom/tdi/tdi.module and

update the bundle if ($entity->bundle() == 'XX-YOUR-NODE-TYPE-HERE-XX') {
and the field name $entity->get('field_XX-YOUR-FIELD-NAME-HERE-XX')->setValue([['target_id' => $fid]]);

Save the module file.
Go to a node with an empty image field, edit and resave it, done.

On every node creation or update this module will check if the image field is empty and add a real managed image with a real file ID then. Now the metatag module should work just fine. If updating all nodes manually is too fiddly I'd recommend you let some code do that instead :)

I'm thinking about extending this approach to let admins choose content types and field names this default image should be set automatically. Maybe tomorrow ;)

Alternatively

If this doesn't work or if it's just too messy, the next thing I'd try is to hook into hook_page_attachments_alter same as schema_metatag_page_attachments_alter does to actually attach its values to the HTML head, and try to alter the values there. Which might become messy as well, depending on what methods you have available when you get there or if all you get is just a string to be manipulated quick and dirty.


Machine readable coordinates to Geofield I got a long txt file full of cordinates. Like this for every line;

 {"RT**n":"*****","RT**o":"*******","WGS**_lat":"******","WGS**_lon":"******" }

There are numbers, I just hide them since this is just a example.
Anyway. I got a lot of these and it would take me forever to manually insert them. Is there any way to import these into D7 Leaflet Geofield?

Thanks

This question is similar to the follosing, I recommend using the Feeds module: How do I import latitude/longitude into geofield?


Deployment strategy for servers on internal network I am following composer based workflow for Drupal 8, in which I commit only custom code and use composer install to install it on another environment.

However, on new workflow, the dev, test, staging instances are on Internal network, with no access to Internet (due to security reasons).

Can you suggest a deployment strategy to use in this scenario, so that I don't have to commit the whole files in git repository, as is.

PS: I am ok with something like Acquia pipelines, where things are 'compiled' into a branch, which is used for deployment. But using that is ruled out, as the code can't be sent to outside because of security concerns.

The correct way is to use Acquia BLT. It generates a deployment artifact, which can be deployed anywhere.

So that the composer will stay in local and the deployment artifact can be committed to a different branch for deployment, with all the dependencies.


How to use menu_get_object()? I was using menu_get_object() to load node information in Drupal 6.

if ($node = menu_get_object()) {
    // Get the nid
    $nid = $node->nid;
  }

Since menu_get_object() is deprecated in Drupal 8, I was using the following code.

if ($node_id = \Drupal::request()->attributes->get('node')) { #menu_get_object()
    //load all the information of the node
    $node = node_load($node_id);
  }
  echo '<pre>';print_r($node);exit();echo '</pre>'; //its okay
  echo $node->type->value; //not working

This is not getting the node values, but printing the node information's in array. How do I resolve this ?

UPDATE

I am getting all other values like $node->title->value and $node->nid->value, but not $node->type->value.

See
https://drupal.stackexchange.com/a/202185/45409

In Drupal 8, you can get url arguments based on what's in the routing.

To get the id alone:

$nid = \Drupal::routeMatch()->getRawParameter('node');

If you plan to load the node object, you can simply get it this way:

$node = \Drupal::routeMatch()->getParameter('node');

To find the parameter names, you can use:

$possible_parameters = \Drupal::routeMatch()->getParameters();

To find the node type, use:

$node->bundle();


"InvalidArgumentException: Field field_participant_email is unknown" although it exists We're working on a custom module where we are creating participant content types programatically. We then have some queries to check for where a participant exists.

However although the field field_participant_email exists and is defined, the below code results in the error InvalidArgumentException: Field field_participant_email is unknown.

$query = \Drupal::entityQuery('node');
$query->condition('type', 'participant');
$query->condition('field_participant_meeting', $meeting_id);
$query->condition('field_participant_email', $email);
$ids = $query->execute();

We've tried clearing cache, deleting and re-adding the field to no avail.

Does anyone have any suggestions or experiencing with this type of issue?

Much appreciated.

Update 1

For clarity, I've also checked the following:

checked the spelling of the field
deleted all the content types and reinstalled them through features
tried $query->condition('field_participant_email_value', $email);
tried $query->condition('field_participant_email.value', $email);

Update 2

Looking into the core/lib/Drupal/Core/Entity/Query/QueryInterface.php interface documentation, it seems that adding a condition against a custom field is not supported. This would explain why the error occurs. However I'm yet to find an alternative. I've also experienced the same error when trying to set the value of the field $node->set('field_participant_email', 'name@domain.com');.

The syntax for the field condition(s) is missing a column name (and potentially an operator)

$query->condition('field_participant_email.value', $email, '=');

Here is a useful tutorial on Entity Queries for Drupal 8 I always refer to:

The Drupal 8 version of EntityFieldQuery


Using theme regions from .tpl.php file I have defined many regions in my theme template. I would like to have a home page that uses these regions ... how can i use them?
I have made a home.tpl.php but i don't know how to assign code to regions ... is it possible to do it even outside the page.tpl.php?

If you define a region you would normally then do the following in your page.tpl.php file...

<?php if ($YOUR_REGION): ?>
    <?php print $YOUR_REGION; ?>
<?php endif; ?>

You should have some similar examples setup already especially if you are using a theme that ships with Drupal.

You can create specific page templates...

function YOURTHEME_preprocess_page(&$variables) {
  if (arg(0) == 'my_page') {
    $variables['template_file'] = 'page-my_page';
  }
}

Template suggestions

See: http://drupal.org/node/1089642

Context module

Also, the Context module is brilliant for this sort of thing if you intend on having different regions for different pages you can use Context layout.

http://drupal.org/project/context


Custom field type validation in field type definition class Scenario: I created custom field type and need to add my own custom constraint/validation prior to saving.

Problem: failed to add custom constraint plugin so I implemented the function in

public function preSave() {
$return = $this->custom_check($this->value, $this->getSetting('check_options'));
if(!$return[0]){
  drupal_set_message($return[1]->__toString(), 'error');
  $url = \Drupal::service('path.current')->getPath();
  $response = new RedirectResponse($url);
  $response->send();
  exit;
}
}

function custom_check($value, $check_options){
//checking goes here
}

I user drupal_set_message() and RedirectResponse as I couldn't get the $form or $formState of the node/%nid/edit to set the error at field and dor form rebuid.

I know that solution is not the best practice and I have to create my own constraints and validation but I spent time with no luck to work and I didn't found a working example that suits my case escpicially I need to validate based on field settings so I have to pass two parameters value and setting.

Please help getting the current form array and formstate in presave to rebuild instead of redirect. or show me how to write simple constraint that takes parameters and how to add it to my custom defined field type.

Thanks in advance.

Form validation checks the user input before it gets submitted. The submitted values don't necessarily go into the database, they can be used for other things. Presave can check values before they are stored in the database. The values don't need to come from a form, they can be generated by other code. So those two things are not connected.

If you want to validate a form, you have to use form validation. Presave doesn't know about forms. It is no problem to double check in presave, then you prevent wrong values to enter into the database from any code. But if you want to give the user a feedback in the form, use form validation. In presave you can only throw an exception after submit.


How to create a multi vendor Drupal commerce website? What is the best way to create a multi vendor Drupal commerce website in which every vendor has the option to create:

Their own store.
Their own menu/vocabulary.
Every vendor have access to its own menu/vocabulary.

A hint would be enough.

eCommerce in Drupal generally comes down to 2 modules:

Ubercart
Commerce.

Commerce is very powerful and flexible, and I'm sure you could use it to build your use case, but it might take a lot of work. It has a great distro called Commerce Kickstart to get you up and running quickly. And Pantheon will give you free hosting for you dev site and install the distro for you!

Ubercart is older, and still powerful, not quite as flexible. But this module may meed your use case exactly: Ubercart marketplace.

Other module :

Commerce-Marketplace


How can I insert fields from custom content to custom form? I have a problem with form. I had to create a custom content with fields. User can put variables into those fields and save to database, for example "Anna" into column field_student_name in table node__field_student_name. I see this connection where every field from this content type is saved under particular node.
Now I need to create a form with fields, which values will go to the same database tables, for example in this form I have a form field where I put "Tom", and this value is saved in table node__field_student_name in column field_student_name (the same as Anna in custom content).
At this moment I see two main potential ways to accomplish this task:

insert form from custom content to my new form  with entity.form_builder

I added this two lines info code:
$node = \Drupal\node\Entity\Node::create(['type' => 'my_students']);
$form = \Drupal::service('entity.form_builder')->getForm($node);
return $form

And this works fine, but I need only part of those fields :( And I don't wanna see section for admin like "add new revision" etc. Moreover, "Submit" button is on the top of the page

Create a form and in submit function do something like
$node->set('title', 'titile1')

but I prefer way #1. Besides that, I don't know how to do it with way #2. I don't know how can i put variables from $form['student]' into field_student_name column in node__field_student_name table. Moreover i am not sure if it is ok and if nodes id etc will be added in correct way.
To sum up, I think way #1 is better and easier but I don't have such a big knowledge to do this  and maybe here are more advanced, helpful people who can help me.
EDIT
I've create new mode student_user in student content type:
core.entity_view_mode.node.student_user.yml
langcode: en
status: true
dependencies:
  module:
    - node
id: node.student_user
label: student
targetEntityType: node
cache: true

core.entity_view_display.node.student.student_user.yml
langcode: en
status: true
dependencies:
  config:
    - core.entity_view_mode.node.student_user
    - field.field.node.student.field_name
    - node.type.student
  module:
    - options
    - user
id: node.student.student_user
targetEntityType: node
bundle: student
mode: student_user
content:
  field_name:
    weight: 103
    label: above
    settings:
      thousand_separator: ''
      prefix_suffix: true
    third_party_settings: {  }
    type: list_default
    region: content
hidden:
  links: true

and here i tried with routing
student.student_user:
path: '/test'
defaults:
_entity_view: 'node.student_user'
_title: 'Students'
requirements:
_permission: 'access content'
_entity_access: 'node.view'
I received an error
RuntimeException: Failed to find entity of type node in route named student.student_user

And then i tried with form
i added core.entity_form_display.node.student.student_form.yml and core.entity_form_mode.node.student_form.yml
and then i tried return it in controller
<?php

namespace Drupal\student\Controller;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\NodeInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\Core\Routing;

class TestController extends ControllerBase {

  function test() {

    $node = \Drupal\node\Entity\Node::create(['type' => 'student']);

    $form = \Drupal::service('entity.form_builder')->getForm($node, 'student_form');

    return $form;
  }
}
?>

error
Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException: The "node" entity type did not specify a "student_form" form class.

An entity can have multiple form modes, so you can exclude some fields in different form modes and leave fields that you want to display.
So, you can create form mode "custom_form_mode", go to manage fields, choose "custom_form_mode" and arrange fields.
In the custom code, you can use the code that you mention in #1, but with an extra argument in the getForm method, which is $operation, and that one is the form mode that you want to use to display form.
$node = \Drupal\node\Entity\Node::create(['type' => 'my_students']);
$form = \Drupal::service('entity.form_builder')->getForm($node, 'custom_form_mode');
return $form


how to add custom css as default for the whole site How can I add my css file as default for the whole Drupal site?

Where to put my CSS file so that it applies to whole Drupal 7 site that I am creating.

If you want it on every theme, then you'll want it in a module.

Using this method you won't have to put the CSS in with every theme - just add and enable the module.

Just create a module that uses the following code:

function MYMODULE_preprocess_page($vars) {
  $options = array(
    'group' => CSS_THEME,
    'every_page' => TRUE
  );
  drupal_add_css(drupal_get_path('module', 'MYMODULE') . '/MYGLOBALCSS.css', $options);
  $vars['styles'] = drupal_get_css();
}

drupal_add_css()

drupal_get_css()

You'll need to clear your theme registry to have the changes picked up.


How to use redirects on Nodes that are only used to populate block Views I have a custom content type that is really only used to populate a views banner, so I don't want that node to ever be browsed to or indexed.

I'm thinking this is a redirect kind of scenario, but I don't know exactly what that should mean. I'm using Clean URLS and Path Auto

Would something like Global Redirect be what I need or is there something else I should use?

Thinking ahead, there are other content type nodes that will have the same requirement.

You can use Rabbit Hole module for this.

  Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
  Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

  Options

  This works by providing multiple options to control what should happen when the entity is being viewed at its own page. You have the ability to

  Deliver an access denied page.

  Deliver a page not found page.

  Issue a page redirect to any path or external url.

  Or simply display the entity (regular behavior).

  This is configurable per bundle and per entity. There is also a permission that lets certain roles override Rabbit Hole completely.


How to programmatically add options to list_text field I want to programmatically add a drop down list field to the user profile via a custom module. How do I go about adding select options for the field?

// Create Field
'suffix' => array(
  'field_name' => 'suffix',
  'type' => 'list_text',
),

//Create instance
'suffix' => array(
  'field_name' => 'suffix',
  'entity_type' => 'user',
  'label' => 'Suffix',
  'bundle' => 'user',
  'options' => array(
   '0' => 'Mr.',
   '1' => 'Mrs.',
  ),
  'widget' => array(
  'type' => 'list_text',
  );
),

The field shows up but the options do not. Anyone have a good guide they know of or tell me what I'm missing?

Your available widgets for a list field are these: options_select, options_buttons and options_onoff, not list_text, that is the field type.

The widget values can be found on list_field_widget_info_alter(), where the list types are coupled with the widgets.

So I suppose you should update your field instance to use:

'widget' => array(
  'type' => 'options_select', // Drop down button or multi-select
  // OR
  // 'type' => 'options_buttons', // Radio buttons or checkboxes.
);

The way the widget is rendered depends on the cardinality defined on your field. If cardinality is set to 1, the first type will be used (drop down or radio buttons), if cardinality > 1, you'll get a multi-select field or checkboxes.

Assuming this field can only hold one value, you should also add

'cardinality' => 1,

To your field definition.

Leaving you with:

// Create Field
$field = array(
  'suffix' => array(
    'field_name' => 'suffix',
    'type' => 'list_text',
    'cardinality' => 1,
  ),
);
field_create_field($field);

//Create instance
$instance = array(
  'suffix' => array(
    'field_name' => 'suffix',
    'entity_type' => 'user',
    'label' => 'Suffix',
    'bundle' => 'user',
    'options' => array(
     '0' => 'Mr.',
     '1' => 'Mrs.',
    ),
    'widget' => array(
      'type' => 'options_select',
    ),
  ),
);
field_create_instance($instance);


Display text in an empty field group tab using custom code I have created a field group with an empty tab. I would like to use custom code in a module to display something in this empty tab - it will just be a render array.

Can someone show me how this can be done or a link that might help me discover how to do this?

Adding something like the below in hook_form_alter() works

<?php
    $group_name = 'group_some_name';
    $form['test'] = array(
      '#type' => 'container',
      'content' => array(
        '#markup' => 'test',
        '#prefix' => '<div>',
        '#suffix' => '</div>',
      ),
    );
    $form['#group_children']['test'] = $group_name;
    $form['#fieldgroups'][$group_name]->children[] = 'test';
?>

Seems like I had to add wrap the content in '#type' => 'container' for it to work


Appending string causing link to render as plain html The following code is returning html in plain text instead of link.for example its printing Edit slides intead of converting in to link.

$editslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/editslides');
      $editslides_link = (Link::fromTextAndUrl('Edit slides', $editslides)->toString());
      $exportslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/export');
      $exportslides_link =  (Link::fromTextAndUrl('Export slides', $exportslides)->toString());
      $deleteslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/delete');
      $deleteslides_link =  (Link::fromTextAndUrl('Delete', $deleteslides)->toString());
      $tmp[] =  $editslides_link .' ,' .$exportslides_link .' ,' .$deleteslides_link;

Though if i don't append string in $tmp[] code render the links. For example

  $tmp[] =  $editslides_link;

The complete code is as below

  public function dexp_layerslider_list() {
    $header = [
      'ID',
      'Name',
      'Action',
    ];
    $results = \Drupal::database->select('dexp_layerslider', 'd')->fields('d', [
      'id',
      'name',
    ])->execute();
    foreach ($results as $row) {
      $url = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/edit');
      $row->name = (Link::fromTextAndUrl($row->name, $url)->toString());
      $tmp = (array) $row;
      $editslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/editslides');
      $editslides_link = (Link::fromTextAndUrl('Edit slides', $editslides)->toString());
      $exportslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/export');
      $exportslides_link =  (Link::fromTextAndUrl('Export slides', $exportslides)->toString());
      $deleteslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/delete');
      $deleteslides_link =  (Link::fromTextAndUrl('Delete', $deleteslides)->toString());
      $tmp[] =  $editslides_link .' ,' .$exportslides_link .' ,' .$deleteslides_link;
      $rows[] = $tmp;
    }
    $table = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#attributes' => [],
      '#caption' => '',
      '#colgroups' => [],
      '#sticky' => FALSE,
      '#empty' => t('No slider created yet.'),
       );
     return  $table;
  }

The toString method of Link returns the HTML string for the link object.

HTML strings in the table render array are wrapped in a markup element which escapes many HTML tags for security concerns.

You can, however, pass your own render array in the row as follows:

$table['#rows'][0]['item']['data'] = [
  '#type' => 'inline_template',
  '#template' => '{{ link1 }}, {{ link2 }}, {{ link3 }}',
  '#context' => [
    'link1' => $link1->toRenderable(),
    'link2' => $link2->toRenderable(),
    'link3' => $link3->toRenderable(),
  ]
];


How to programatically access the value of a taxonomy term reference? I have a taxonomy term reference field attached to my user account.

I tried getting the value programatically in the same way as I get the value for text fields, but it doesn't work.

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;

$account = User::load($account->id());
// Returns the correct value.
$textfield = $account->get('field_textfield')->value;
// Does not return the correct value.
$termreference = $account->get('field_termreference')->value;

How am I supposed to get the value (name) of the referenced term programatically?

As the taxonomy term is a reference the value (or label) is not stored in the user entity, just the target_id. So you need to use:

$termreference = $account->get('field_termreference')->target_id;

This should be your code:

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;

$account = User::load($account->id());
// Returns the correct value.
$textfield = $account->get('field_textfield')->value;
// You need to use the target_id to access to the value.
$termreference = $account->get('field_termreference')->target_id;

Now you need to search the label:

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($termreference);
$name = $term->getName();

Your taxonomy label (name) will be in $name.


How to access raw data in twig template using views table format I use a table format view to display a list of articles article-list using draggable views to allow editors to order the list. I customize the content of rows depending on a boolean field is_header and a formatted text field title_override. I have sub-themed views-view-table--article-list.html.twig to accomplish this. It works well enough.

In the template, I test the truth of is_header and the non-emptiness of title_override as follows:

    {% if row.columns.field_is_header|render|striptags|trim %}

and

    {% if row.columns.field_title_override|render|striptags|trim %}

These tests yield the proper results, but they make the template very slow! Anything less than render|striptags|trim doesn't work.

QUESTION:

Is there a way to directly access the raw data values of these variables to avoid the render|striptags|trim overhead?

I've seen suggestions to use something like row._entity.field_is_header, but this way of using _entity seems to work only in templates for the HTML or Unformatted view styles. Seems like there should be an easy way to do this.

As a note, switching to using an HTML or Unformatted style doesn't seem possible because AFAIK draggable views can be set up only with the table format.

ANSWER:

Thanks to 4k4 for the answer to this question (see below). To apply his/her general answer to my specific question, here is a snippet of the twig script I ended up with:

{% for key, row in rows %}
  {% if view.field.field_is_header.value(view.result[key]) %}
    <conditional stuff>
  {% endif %}
  {% if view.field.field_title_override.value(view.result[key]) %}
    <stuff when the override is non-empty>
  {% else %}
    <stuff when the override is empty>
  {% endif %}
{% endfor %}

Note that rows is an array normally passed to the views-view-table.html.twig template, as documented in the original template's header comments. Note also that the availability of the view array is NOT documented in the original template's header comments (not that it would have saved me without 4k4's help).

You can try to apply getValue() of the field handler on the result row, for example:

{% if view.field.field_name.value(view.result[key]) %}

Edit:

In a views table template row is not of the type ResultRow, so you need to get it directly from the view object using key of the loop {% for key, row in rows %}.

See these questions for different views templates:
How can I get data from ResultRow object in views template and How to preprocess view field?


How To Hook To Commerce Add To Cart Button After Add? I'm trying to ask the same question in another way... hoping I can get an answer.

I have a function I need to trigger AFTER the product is added to the cart.

When I added a PHP function to a Pricing Rule it seems to execute -before- the product is added.

The Commerce website says that the a Pricing Rule may be triggered before or after the line item is added but I can't figure out how to do this.

You've got a rules event that fires when a product is added to the cart, which is called after the price calculation one, check commerce_cart_product_add function.

It uses rules_invoke_all, which means that you can either run actions on this event or invoke the hook directly, hook_commerce_cart_product_add normally.

// Invoke the product add event with the newly saved or updated line item.
rules_invoke_all('commerce_cart_product_add', $order, $product, $quantity, $line_item);


How to add Download link to File field I would like to know how I can make File field type display the upload as a download link, instead of having a link. So that user can just click and it will download).

The file field type, I added to a custom Content Type, which I created programmatically through a module.

Currently it looks like below, when I click the link, it takes to the uploaded file page. I would like to have it download instead.

Or maybe is there a way to change the view or add additional view to File types for download? or maybe change view for Content Type where it displays the Download link for the file?

If you don't need to update the link tag, then just use the download attribute, it should do the trick.

I've wrote a tiny Fiddle for you https://jsfiddle.net/45ug9p7t/1/

Keep in mind that not every browser has implemented this, check it out


How to apply coupon in commerce order programmatically? I'm working on creating web services for mobile applications to use drupal as backend. When ever the user applying a coupon code through mobile application, I'll get the coupon code through web services as JSON data.

So, How can I validate and apply the coupon to the order programmatically.
I found the below answer from StackExchange (programmatically add line item of commerce_discount type to order). But, what value I need to pass for $discount_name. And how can I get it?

commerce_discount_fixed_amount(EntityDrupalWrapper $wrapper, $discount_name);

When you are creating a discount, you will enter the name and the system will automatically generate machine-name. You need to use the machine name as an argument for commerce_discount_fixed_amount() function.

Here's a screenshot:

Here's how you would use it:

commerce_discount_fixed_amount(EntityDrupalWrapper $wrapper, 'discount_test_discount');


How do I create a view with some customization? I like to create a view to display properties information as shown below.

View

View page

7676 - SQFT

7    - BR

I created a view and added the fields based on my design. I made progress, but I am not able to create the second column of data (SQFT, BR).

How do I add the second column in this view?

I wouldn't use Fields setting for this case.

Try to override template for specific content type and set your view to display your content type in specific 'view mode' for example teaser.

In your view change 'Format' to 'unformated list' and change 'Show' setting to 'teaser' for example. This will display your content type in specific view mode, so now you can override your template for this custom content type using:

node--my_content_type_machine_name--display_mode.html.twig

be aware of correctly using double dashes, otherwise your template won't be registered by drupal. Then you can code custom HTML template for your content type in this specific view mode and you can customize your layout according to your needs.


Accessing unpublished group content I am using organic groups and I want the owner/reviewer of the group to be able to access an unpublished group content created by members of the group.

I know I can give "View any unpublished content" rights to a global user role, but this will be to strong (I have different reviewers for different groups and single reviewer should not have access to unpublished content of all the groups).

I want to give that right to the specific role in the group and "Organic groups global permissions" simply does not have that option.

I am familiar with hooks system but I am not sure how to approach the issue.
Any ideas?

Have a look at this example implementation which creates a new OG Permission View unpublished content and uses Node Grants to decide who can view unpublished nodes. You now can configure which OG Role in your groups are allowed to view unpublished nodes.

<?php
define('MY_MODULE_REALM_VIEW_UNPUBLISHED', 'my_module_view_unpublished');

/**
 * Implements hook_og_permission().
 */
function my_module_og_permission() {
  // Add OG permission to view unpublished nodes.
  return array(
    'view unpublished' => array(
      'title' => t('View unpublished content'),
      'description' => t("Allow user to see unpublished content within the group."),
      // Determine to which roles the permissions will be enabled by default.
      'default role' => array(OG_ADMINISTRATOR_ROLE),
    ),
  );
}

/**
 * Implements hook_node_grants().
 */
function my_module_node_grants($account, $op) {
  if ($op != 'view') {
    return;
  }

  $grants = array();

  // Handle access to unpublished nodes.
  // Get all OG Group IDs the user is allowed to view unpublished nodes in.
  $entities = og_get_entity_groups();
  foreach ($entities['node'] as $entity_id) {
    if (og_user_access('node', $entity_id, 'view unpublished')) {
      $grants[MY_MODULE_REALM_VIEW_UNPUBLISHED][] = $entity_id;
    }
  }

  return $grants;
}

/**
 * Implements hook_node_access_records().
 */
function my_module_node_access_records($node) {
  // Node is unpublished and belongs to a OG group.
  if (!(empty($node->status) && $groups = og_get_entity_groups('node', $node))) {
    return array();
  }

  foreach ($groups['node'] as $nid) {
    $grants[] = array(
      'realm' => MY_MODULE_REALM_VIEW_UNPUBLISHED,
      'gid' => $nid,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 10,
    );
  }
  return $grants;
}


How to remove spaces and beginning 0 from a contact number in Views PHP view? I have tried multiple variations and I cannot get this right. I have a contact number field that is user input; therefore, I need to clean it up so that I can use it in a tel: link on mobile devices.

Users could add numbers using different formats, such as:

021 457 7890
+27 21 567 7089
0214577898

What I want to do (using Views PHP) is to strip the spaces, +27, and 0 at the beginning. My PHP skills are limited, but the confusing part for me is the Value code input and the Output code input and getting this to output correctly.

Note: if there is a non-Views PHP workaround, that would be preferred.

You can do it using the PHP function str_replace

$number = $row->field_contact_number;
// Remove the spaces.
$number = str_replace(' ', '', $number);
// Grab the first number.
$first_number = substr($number, 0, 1);
if ($first_number == 0) {
  // Check if the first number is 0.
  // Get rid of the first number.
  $number = substr($number, 1, 999);
}
// Remove the + sign.
$number = str_replace('+', '', $number);
echo $number;

Although the question asked using Views PHP, it is not a good idea to enable the Views PHP and PHP Filter module. In Drupal 7, the alternative/preferred method would be to add the following code to the bottom of your template.php file (located in /sites/all/themes/yourtheme/ folder).

function themename_preprocess_views_view_fields($vars){
  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    $number = $vars['fields']['field_contact_number']->content;
    // Remove the spaces.
    $number = str_replace(' ', '', $number);
    // Grab the first number.
    $first_number = substr($number, 0, 1);
    if ($first_number == 0) {
      // Check if the first number is 0.
      // Get rid of the first number.
      $number = substr($number, 1, 999);
    }
    // Remove the + sign.
    $number = str_replace('+', '', $number);
    $vars['fields']['field_contact_number']->content = $number;
  }
}

Replace themename with your theme name
Replace view_name with your view name
Replace block_1 with your machine name

Remember to flush the cache to see the changes.


Create a secondary form to fill data into an entity I've an entity that models a contact (I'm using RedHen CRM) and obviously I can fill the data from the usual admin form. But if I want to publish another form for non admin users to insert their data and with less fields displayed, which module (or solution) can I use?
I'm using webform, but I'm having some trouble with addressfield...

I don't know about the webform solution/Redhen

but programmatically/basic drupal speaking I would just use HOOK_form_FORM_ID_alter to restrict access to certain form elements based on role/permission.
Find the id of the form and have a look at the array via devel or something similar, every field normally has an '#acces' variable already included. Setting those to 0 for the fields does exactly what one expects it would do.

This way you can re-use the standard form for all purposes instead of adding a second one. So future edits to the entity fields will automatically be added to all forms and you don't have to fiddle around with all sorts of secondary processing in the submit handler.


How bad is it to use Node_load in a loop in drupal 7? Something like:

for ($i = 0; $i < 100; $i++) {
    $node = node_load($i);
    print $node->fieldYouWant;
}

That is a lot easier to read, gives you access to all the fields etc. However, in a loop, I would imagine Drupal would fall over? Or is the built in caching sufficient to not have to worry about it?

You should never need to use node_load() in a loop, that's what node_load_multiple() is for:

$nids = array(1, 2, 3, 4, 5);
foreach (node_load_multiple($nids) as $node) {
  ...
}

It's hard to imagine a scenario where loading the nodes individually would be necessary or desirable.


How to use hook_field_preprocess to add a prefix/suffix to an entity reference field for different view modes? I'm trying to move some markup from twig templates to hook_preprocess_field().
I have an entity reference field (media image) that I want to add a prefix and suffix to.
I added a prefix and suffix like this:
function MYMODULE_preprocess_field__MYFIELD(&$variables) {
  $prefix = 'Hi... ';
  $view_mode = $variables['element']['#view_mode'];
  if ($view_mode == 'second_view_mode') {
    $prefix = 'Hello... ';
  }
  $suffix = '... there.';
  $variables['items'][0]['content']['#prefix'] = $prefix;
  $variables['items'][0]['content']['#suffix'] = $suffix;
}

With this code, my prefix and suffix get added, but they are cached, and the same for all view modes.
If I rebuild the cache and visit a node in second_view_mode, then I see Hello...  as the prefix for all instances of the field.  But if I rebuild the cache and visit a node not in second_view_mode, then I see Hi...  for all instances of the field, even those on a node in second_view_mode.
I use this same approach/code for formatted text fields and I don't experience this caching problem.  So I think I need to do something different for this entity reference field, but I don't know what to do.
How do I add a prefix/suffix to an entity reference field in a preprocess function for different view modes?

If you have configured the reference field to render the referenced entities then the build array usually contains #cache keys, which result in a separate cache entry for this render array including anything you've attached to it in preprocess. This has nothing to do with the view mode of the parent entity, the cached result will also be reused when the media is displayed in a different entity.
You could split up the field content in multiple render elements so that you have the prefix/suffix outside of the cached element content:
$variables['items'][0]['content'] = [
  'prefix' => ['#markup' => $prefix],
  'content' => $variables['items'][0]['content'],
  'suffix' => ['#markup' => $suffix],
];


Ubercart - different payment gateway settings per product i want to be able to set one product as UC_CREDIT_AUTH_ONLY, meaning no charge will be made now. in the admin i can only change this setting globally, meaning that all my products will be charged UC_CREDIT_AUTH_ONLY. How can i get this to work only for one?

currently i'm using paypal website pro as gateway, but if i have to, i'll switch to athorize.net.

using drupal 6 + ubercart 2

Thank you.

There is a sandbox project for multiple gateways. I attempted to contact the developer a few days ago, but haven't heard back.

http://drupal.org/node/1106004

you select the profile in the product edit. Its not complete but close.


How to create an RTL CSS file (style-rtl.css) for Drupal modules Say I have a "style.css" file for a module, and that file contains the following syntax:

.myCalss1 {
  right: 10px;
  margin: 0 5px 0 0;
}

I then create an extra file, "style-rtl.css" with the following syntax (flipping of the previous):

.myClass1 {
  right: initial;
  left: 10px;
  margin: 0 0 0 5px;
}

How can I make the system prefer the RTL file?

Solution

Create the flipped rtl css (for example, based on the structure I've described above) and then go to your theme's or module's folder, and there go to the libraries file (like libraries.yml) and create a reference in the end of the library ---> To your new file. Here is an example from the libraries file of one of my modules (admin toolbar):

Note:

The file might not work correctly if you will indent your syntax using the tab key or the space key. If there is a problem try the other of these two indenting options (some files can't work well when you pick a specific method for indenting them - It has to do with the structure of the file types themselves).


hook node access drupal 7, not working when the node is updated I have created a module using the following code.

<?php
global $user;

if (in_array('contributor', array_values($user->roles))) {
    function publishEntities_node_access($node, $op, $account) {
        if (in_array('article', node_permissions_get_configured_types())) {
            if($node->status==0) {
                if ($op == 'update') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_ALLOW;
                    }
                }
                if ($op == 'delete') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_ALLOW;
                    }
                }
            }
            elseif($node->status==1) {
                if ($op == 'update') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_DENY;
                    }
                }
                if ($op == 'delete') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_DENY;
                    }
                }
            }
        }

        if (in_array('events', node_permissions_get_configured_types())) {
            if($node->status==0) {
                if ($op == 'update') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_ALLOW;
                    }
                }
                if ($op == 'delete') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_ALLOW;
                    }
                }
            }
            elseif($node->status==1) {
                if ($op == 'update') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_DENY;
                    }
                }
                if ($op == 'delete') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_DENY;
                    }
                }
            }
        }
    }
}

The module does not work after the node is being updated.

Can anybody help me to make this module work as expected?

I cant seem anything that stands out as a problem other than maybe moving:

if (in_array('contributor', array_values($user->roles))) {

Into the hook_node_access and change $user for $account.

However when troubleshooting problems like this I would firstly ensure you do not have any other access control modules enabled, they can often override each other depending on the modules weight in the system table.

Turn off all modules but core and try isolate parts of your code to get it working bit by bit. For example start off initially with:

function publish_entities_node_access($node, $op, $account) {

        if ($op == 'view') {
            if ($account->uid == $node->uid) {
                  return NODE_ACCESS_ALLOW;
            }
            else {
                  return NODE_ACCESS_DENY;
            }
        }
 }

This code should work and easy to test, if you are not the author of the node then you will not be able to view it. You can then start adding on your additional if statements above until you run into a problem.

You can also install the devel module to nicely output the array's to ensure the values you are using conditionally in your code are available.


Custom Field type was empty in views Im build a module, and this module was add a new field type, and all its good, but when i try to use this field in view, its print empty.. no value.., but when I use delta field, its retrieve value ..

look here:

how i can integrate field value with view ..?

this code I used for create field ..

// Install New type of field module.install
function custom_anees_location_field_schema($field) {
  $schema = array();
  $schema['columns']['option'] = array(
      'type' => 'varchar',
      'length' => 25,
      'not null' => FALSE
  );
  return $schema;
}
 // mymodule.module
function custom_anees_location_field_info() {
  return array(
    'country_list_location' => array(
      'label' => t('Country Location'),
      'description' => t('Field For spesfic Location content'),
      'settings' => array('max_length' => 255),
      'instance_settings' => array(
        'text_processing' => 0,
      ),
      'default_widget' => 'options_select',
      'default_formatter' => 'states_field_options',
    ),
  );
}

function custom_anees_location_field_widget_info_alter(&$info) {
  $widgets = array(
    'options_select' => array('country_list_location'),
  );
  foreach ($widgets as $widget => $field_types) {
    $info[$widget]['field types'] = array_merge($info[$widget]['field types'], $field_types);
  }
}

function custom_anees_location_element_validate($element, &$form_state) {
  switch ($element['#type']) {
    case 'textfield':
      if ($element['#value'] == '') {
        form_error($element, t('Case Name may not be blank.'));
      }
      break;
    case 'checkboxes':
      if (empty($element['#value'])) {
        form_error($element, t('You must give at least one role access to this state.'));
      }
      break;
  }
}

You need to let Views know about your custom field in database with hook_views_data. Here is an article that explains all about it: http://blog.menhir.be/2008/10/22/expose-database-fields-to-views-in-a-custom-drupal-module/


How to make gmap marker tooltip display node title without tags? My project uses gmap of nodes locations. When marker is hovered  popup tooltip displays link to node with node title in it. Any possibility  to display node titles in marker tooltips without any tags?

Quote from the Comparison of mapping modules:

GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

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

Get Locations,
Geofield,
Geolocation Field
Location.

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

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


How to set nodes to be excluded from a block view based in the url of current node? I have a view block listing nodes. Let's say I have the following nodes (it's urls)

node/first-node
node/second-node
node/third-node
node/fourth-node

Then I have the view block listing this 4 nodes. This block is shown in the First sidebar in all pages.

What I need: when the block is shown at the page node/fourth-node, I need to arbitrarily exclude from the view block from the following nodes.

   node/second-node
   node/third-node

I need to do this in a way so that then after I can do the same thing with other nodes.

I thought of adding a field to the node called: "Exclude from view block at:" to be filled with the paths (one per line) where the node will not be listed in the view block (similar to blocks settings). Then I will need to modify the view.

Is this a correct approach? If so, what do I have to do in the view?

What you could do if you could use either Views Filters and use the view Filter options to set which URL's to exclude based on tokens.

You could also maybe use Views Rule to try and do something similar.

I think the Views Filters may be an easier option. But if you want to do your suggestion (add a field to the node) then what you can do is pretty much exactly what you said, you would add a filter to the view based upon the available tokens and field data.


Drupal site shows frontpage instead of added content I'm restoring a client's site after they lost all information. After some trouble, we could restore their database, which now shows all tables. The problem is that, after uploading all files and connecting to the database, the page displays Drupal's default frontpage and says 'no content has been created yet'. The database contains all tables, and I'm assuming the connection is right; otherwise I'd get an error message.

Why aren't I seeing all info stored there?

You might have all of the tables, but you might not have all of the rows, perhaps. Two tables to look at: node and node_revision. See of there are rows there.


How to add classes to BODY tag dynamically based on page path/depth? How to add classes to the body tag dynamically such as this example below?

-Home
-Cities
--Melbourne       <body class="melbourne">
---Theme Parks       <body class="melbourne theme_parks">
---Restaurants       <body class="melbourne restaurants">
--New York       <body class="new_york">
---Theme Parks       <body class="new_york theme_parks">
---Restaurants       <body class="new_york restaurants">
-Contact Us       <body class="contact_us">

Drupal newbie here and without programming background. Therefore, I'd much appreciate if you could be as detailed as possible when sharing a solution.

To expound on Nikhil Mohan's answer, you can implement template_preprocess_html() inside your theme's template.php file. Read the documentation on Overriding Themable Output to understand the basics of what is going on here.

Within this function, you have access to the variable $vars['classes_array'], which holds a list of classes that will be applied to the HTML <body> tag on the page.

Unfortunately, information about the current page's location in the menu is not immediately available. You could use menu_get_item() and then menu_get_ancestors() to get this information, but that is a lot of processing power for something that we can probably get to with a simpiler approach.

Assuming you are using the pathauto module to automatically create semantic paths for your content pages based on the menu path (i.e., your Melbourne Theme Parks page would have the path 'melbourne/theme_parks') you can use the page's path to create the classes you are looking for:

function THEMENAME_preprocess_html(&$vars) {
  $path = drupal_get_path_alias();
  $aliases = explode('/', $path);

  foreach($aliases as $alias) {
    $vars['classes_array'][] = drupal_clean_css_identifier($alias);
  }
}

That's it. Drupal will now look at the path alias of the current page and add a class to the <body> tag for each chunk of the path alias.


Altering the breadcrumb contents I'm trying to use this hook in order to alter a breadcrumb link :

hook_menu_breadcrumb_alter(&$active_trail, $item)

The hook don't seem to be called.

I've tried :

Using the hook on a theme
Using the hook on a custom module (breadcrumb_finder_fix)
Clearing all caches using Drush

I have the Devel module installed and activated, and the following doesn't produce any output.

function breadcrumb_finder_fix_menu_breadcrumb_alter(&$active_trail, $item) {
    drupal_set_message(krumo($active_trail));
}

Any ideas ? Directions ? Please advise.

OBS : I've read this answer : https://drupal.stackexchange.com/a/7659/12647

Probably a little late to respond, but I came across this thread this morning whilst looking for a way to override the breadcrumb in Drupal 7, it helped a little so I thought I would add my solution.

This creates extra crumbs based on content types and adds the current page to the crumb. I'm using this to add a crumb to a filtering view seen before the given node.

function MYMODULE_menu_breadcrumb_alter(&$active_trail, $item) {

    //STORE THE LAST ITEM
    $end = end($active_trail);

    foreach ($active_trail as $key => $crumb){

        //CHECK AGAINST NODE TYPE
        if($crumb['map'][1]->type == 'NODE_MACHINE_NAME'){

            //INSERT THE REPLACEMENT CRUMB
            $active_trail[$key] = array(
                'title' => t("Title"),
                'href' => 'PATH',
                'link_path' => 'PATH',
                'localized_options' => array(),
                'type' => 0
            );
            //RECREATE ITEM
            $active_trail[] = $crumb;
        }

    }

    //SHOW CURRENT PAGE IN BREADCRUMB BY DUPLICATING THE LAST ARRAY ITEM IN ACTIVE_TRAIL

    if (!drupal_is_front_page()) {
        if ($item['href'] == $end['href']) {
            $active_trail[] = $end;
        }
    }

}


Display Image logo along with site slogan and site name I  am using Impact theme for my site. It either displays text logo(site name, site slogan) or image logo. I want both image logo and text logo for my site.
Any help is welcome.

I would recommend to use the "Panels" module to do that. Create a "mini-panel" and while editing one of it's panes (boxes of content) choose on the edit menu "Page elements" and then add "Logo, "Site name", and "Site slogan" respectively. Make sure you arrange them as your liking.

The second part of your work is to do some CSS for this. The Panels css system takes some time to learn --- You should use DOM tags carefully to isolate the Id's and classes of the right div's and manipulate them in relation to their upper div's, but it's worth the shot.

If your site is responsive you should add some responsiveness with a Media query, i.e:

@media screen and (max-width:519px) {#panel-col-first {width:100%;} #panel-col-last {width: 100%;}}

In Panels, make sure that after you choose basic details and layout you navigate in "content" tab. Then, Add the aforementioned details - Here is a screen that'll show you how:


How to print the node body in a custom block? I am trying to print the node body in a custom block, but it's not showing up. I'm I doing this correctly?

$refer = $_SERVER[HTTP_REFERER];
$parsed = parse_url($refer);
$alias = array_pop($parsed);
$dst = \Drupal::service('path.alias_manager')->getPathByAlias($alias , $langcode);
$nid = array_pop(explode('/', $dst));
$dest_node = node_load($nid);

$body = $dest_node->get('body')->getValue();
print $body; //have tried other printing methods also but invain

Thanks

$dest_node->get('body')->getValue();

this will return an array. So,$body is an array.
If you want the Body field values, then get it by accessing the proper index of the $body array. i.e $body[0]['value']

just replace print $body; with print $body[0]['value'];


Extend the Scheduler module forms Hi i'm trying to extend scheduler module forms. The one i need is  included as fieldset in node as extra field refer to image

/**
 *  Implements hook_form_node_type_form_alter().
 */

 function nodequeue_scheduler_form_node_type_form_alter(&$form, $form_state) {

    //This  node type configuration form with schedule options

    $form['scheduler']['nodequeue_sheduler'] = array(
      '#type' => 'fieldset',
      '#title' => t('Nodequeue Scheduler Settings'),
      '#collapsible' => FALSE,
      '#group' => 'scheduler',
      '#weight' => 10,
    );

   }

/**
 * Implements hook_form_FORM_ID_alter().
 */
function nodequeue_scheduler_form_scheduler_node_form_alter(&$form, $form_state) {

   //feldset or vertical tab for scheduler to ammend
$options = array (1,2,3);
// Adding few custom fields
$form['scheduler_settings']['publish_nodequeue'] = array(
 '#type' => 'fieldset',
 '#title' => t('Nodequeue Scheduling settings'),

);
$form['scheduler_settings'] ['publish_nodequeue']['schedule_nodequeue'] = array(
 '#type' => 'checkbox',
 '#default_value' => 1,
 '#title' => t('Add to nodequeue when published')
);

$form['scheduler_settings']['publish_nodequeue']['nodequeue_position'] = array(
 '#type' => 'select',
 '#options' => $options,
 '#title' => t('Position')

);
$form['scheduler_settings']['publish_nodequeue']['publish_on'] = array(
 '#type' => 'textfield',
 '#title' => t('Publish on'),
 '#maxlength' => 30,

);
// function scheduler_mail_form_scheduler_node_form_alter(&$form, $form_state) {
//    $email_enabled = variable_get('scheduler_mail_enable_' . $form['type']['#value'], 0);
//    if (!$email_enabled) {
//      return;
//    }

//    $node = $form['#node'];
//    $settings = _scheduler_mail_load($node);

//    $form['scheduler_settings']['scheduler_mail'] = array(
//      '#type' => 'fieldset',
//      '#title' => t('Email settings'),
//    );
//    $form['scheduler_settings']['scheduler_mail']['scheduler_mail_send'] = array(
//      '#type' => 'checkbox',
//      '#title' => t('Send an email notification when this node is (un)published'),
//      '#default_value' => $settings->send,
//    );
//    $form['scheduler_settings']['scheduler_mail']['scheduler_mail_address'] = array(
//      '#type' => 'textfield',
//      '#title' => t('Use this email address'),
//      '#description' => t('If left blank, email will go to the original author of this node'),
//      '#default_value' => $settings->address,
//      '#maxlength' => 255,
//      '#states' => array(
//        'visible' => array(
//          "input[name='scheduler_mail_send']" => array("checked" => true)
//        ),
//      ),
//    );
//    $form['#validate'][] = '_scheduler_mail_validate';
//    $form['#submit'][] = '_scheduler_mail_submit';
  }

I have found module scheduler mail and it alters the node type form and add some configuration fields as checkbox but not getting the form which is in node edit form . How do i do it in drupal 7

If scheduler is using hook_form_alter() on a form, and your module is also using hook_form_alter() on the same form, the order of execution of these two hook_form_alter() functions matters. Evidently, your module's hook_form_alter() is getting called before scheduler can add the new form elements you're trying to modify.

Drupal executes these hooks in order of module weight. If you do not set the module weight, then I believe they all default to the same value and hooks with the same weight will get called in alphabetical order (but this is not guaranteed).

To ensure that your module gets called after scheduler, you need to set your module's weight to be greater than the scheduler's module weight. This is how you do that in your module's install file:

/**
 * Implements hook_install().
 */
function my_module_install() {
  // Because we need to alter a form that is also altered by the scheduler
  // module, we need to ensure this module gets loaded AFTER the scheduler.
  $weight = db_query('SELECT weight FROM {system} WHERE name = :name', array(':name' => 'scheduler'))->fetchField();
  db_update('system')
    ->fields(array(
      'weight' => $weight + 1
    ))
    ->condition('name', 'my_module')
    ->execute();
}


Change date on icon click event I'm trying to create a custom block that display the current date (Only Day of the month, 2 digits with leading zeros and A full textual representation of the day of the week) using the tocken module.

Now my problem is how to change the date when the next, prev icon is cicked?
For example: Today is saturday the 05th. When i click next, i get sunday the 6th. And when i click prev, i get friday the 04th.
Maybe this can be possible using javascript or php.

There are two ways to go about this.
Pure JS
You can send the date shown to the JavaScript either via drupal_add_js or as a data attribute and let the JavaScript manage the date changes. You would need to change the current date +/- 1 when clicking on a button and figure out the name of the day and the day number of the day and display that. This should be relative simple to do.
AJAX
You can let the use AJAX and send the selected date to a custom menu callback which returns the markup for the new date.
Of the two solutions I would prefer the pure JS version. The Ajax version is more complex to implement and will generate a bigger load on the webserver. It could be a nice solution if you want to do advanced theming and don't want to place that logic in the JS (like weekends / holidays etc are displayed in different styles)


Checkbox in user edit page I have customized the user-edit page in Drupal7 using user-profile-edit.tpl.php.  I have also added reCAPTCHA to it using the reCAPTCHA module.

I would also like it so that there is an "I agree to terms and conditions" checkbox, and only when the user clicks this check box should the information be saved (i.e, it should be a required field).

How can I do that?

I found the Terms of Use module and the Legal module but they appear only on the registration form, whereas I want it in user-edit page (form). I thought of adding a field to the account settings for users but I am not getting any desired field for that.

Any suggestions?

Following the answer below, I was able to do some progress. However I want it to be a required field and if I click on that in its field setting then automatically it is shown on the user registration page which I do not want .

You can select the Boolean field and widget type as Single on/off check box...This should solve your problem...No need to use any modules


During form validation, can you "stash" a form for an end user while they fill out a different form? Core of the question

I have a form that might throw a validation error based on the values in other entities on the site.  If a user fills out an entity form and hits submit, they will see validation errors that tell them another entity is in conflict.

I would like to provide the user with an option to update the other entity on the site to clear up the validation issue.  The problem with that, however, is that the user would have to navigate away from the form throwing the validation errors, and they'd then lose their input.

I would like to fix this up without using Ajax, because I think that Ajax will complicate the UI and I'd like to keep javascript out of the equation for now.

Is there a standard non-hackish way to use $form and $form_state in a way that will allow me to just grab the user input and stash it into the SESSION or something so once the user fills out a secondary form, they go back to the original form and their originally input values are still there?

The desired user experience

{Entity A} exists with field data on the site that will cause a
validation error on {New Entity B} add form.
User enters field input into {New Entity B} add form, and hits submit.
My custom {New Entity B} form validation callback checks {Entity A} and
discovers a problem that requires {Entity A} to be edited before
{New Entity B} can be saved.
User does ??? and {New Entity B} $form and {New Entity B} $form_state are "saved
for later" while user goes to {Entity A} edit form.
User updates and saves {Entity A} and is redirected back to {New Entity B} add form.
{New Entity B} add form has the same input values the user already entered, because they were retrieved from a "stashed" {New Entity B} $form and {New Entity B} $form_state.

Is this possible?  How?

Edit

Caveat about uncertainty of form fields

The exact fields on the entity form are unknown.  I want to apply this logic to numerous entity forms, which means I don't know which fields are there in my validation callbacks.  This is why I'm looking to stash $form and $form_state in their entirety.  I don't want to get involved with individual field values.

I just looked at your Entity Availability project page, and it looks interesting. You are facing the classic Temporal dependency problem of all scheduling systems (eg Departure time depends on Arrival time). This is the one data dependency which cannot be resolved statically.

The Webforms module uses $_SESSION to store information for multi-page forms for the anonymous user. In the case of the Webform module, the submission ID ($sid) is saved the $_SESSION, and the $form_state is saved in and retrieved from the database, however I see no problem with using $_SESSION to maintain a working copy of the $form_state object ($_SESSION['form_id'] = $form_state;). However, I would suggest you look at a cache_entity_availability table keyed on, perhaps, form_id and uid, just in case the session expires (servers down, network problem etc).

Thanks for the additional info, and good luck with the project.


fast saving single field value I've got around 70k nodes of specified type on my site. I need to run an update on them. Some operations and setting one field to desired value. node_save is really slow and it causes crashes (too long callstack mayby). Is there faster way to write info on this one particular field?

There was field_attach_update mentioned in one post, but it isn't much faster.

EDIT:
There is quite complex view built on this node type, but is not working on this field which I want to update.

I'd definitely go for field_attach_update.

The idea is simple. Just load the node and save it using field_attach_update.

Ex:

$node = node_load($nid);
$node->field_name[LANGUAGE_NONE][0]['value'] = 'New value';
field_attach_presave('node', $node);
field_attach_update('node', $node);
  // Clear the static loading cache.
entity_get_controller('node')->resetCache(array($node->nid));

This will not changed any timestamp or any other hook that node_save usually invokes. Loading the node will also invoke some hooks so probably it's not that efficient.

If you have the nid and if the node structure is dead simple, you can do it like this as well:

 $node = new stdClass();
 $node->nid = $nid; // Enter the nid taken. Make sure it exists.
 $node->type = 'article';
 $node->field_name[LANGUAGE_NONE][0]['value'] = 'New value';
 field_attach_presave('node', $node);
 field_attach_update('node', $node);
  // Clear the static loading cache.
 entity_get_controller('node')->resetCache(array($node->nid));

Anyways, if you are trying to update anything other than than fields, this will no work (comment status, published status, etc). Also If you are using node_save, cache for the particular node will be cleared automatically for different methods we need to clear it with 'entity_get_controller'.

Update:
It appears that you should also call field_attach_presave() to let other modules process the field input properly. File module, for example, uses it to set the file status to permanent using this hook. I have updated my 2 examples above.


Embed Views Map in Slider/Slideshow I need to have a slider on my main page that has a number of images (taken from views), and also a map that slides. Can anyone recommend any tutorials on how to embed a block as one of the images in a slider or any other solutions to this? So far everything that I have seen is just for embedding images.

You can use Views slideshow module :

  Views Slideshow can be used to create a slideshow of any content (not
  just images) that can appear in a View... Potential uses :

  News item slideshow (such as the title, image and teaser of the last 5 news articles submitted)
  The last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).
  Rotate hottest new products, contact links, share links, entire nodes, categories, image galleries, etc.

There are many tutorials links on the project page , i.e how to create a simple slideshow with some node fields.

Define the relationship between your images & maps ( taxonomy ? fields of the same node ? ...), set a view showing them, then display it as a slideshow.

If you can't find how to join your content in a view query, have a look at Multiple nodes in one slide using views slideshow or another module ...


Is there a way to disallow spaces in the user name registration form in drupal 7? I hate spaces in usernames, a user can easily add two or more spaces without realizing it. I need to have more control over the username format than Drupal allows by default.

I recently wrote a custom module to disallow spaces and other characters in usernames. Feel free to comment on the code. I also modified username_check to do the same validations in the ajax callback.

//implement hook_form_FORM_ID_alter
function custom_form_user_register_form_alter(&$form, $form_state, $form_id) {
  //define validation function
  $form['#validate'][] = 'my_user_register_validate';
  //overwrite the username help text
  $form['account']['name']['#description'] = 'Username has to be between 5-15 characters long and can only contain letters and numbers';
}

function my_user_register_validate($form, &$form_state) {

  $output['error'] = FALSE;
  $username = $form_state['input']['name'];
  $password = $form_state['input']['pass']['pass1'];

  if (strlen($username) < 5 || strlen($username) > 15) {
    $output['error'] = TRUE;
    $output['msg'] = t('The username has to be between 5 and 15 characters long. ');
  }
  if (strpos($username,' ') > 0 || strpos($username,'.') > 0 || strpos($username,'-') > 0 || strpos($username,'_') > 0 || strpos($username, "'") !== FALSE ){
    $output['error'] = TRUE;
    $output['msg'] = t('Username cannot contain spaces . - _ ' . chr(39)  );
  }

//display username errors
  if ($output['error']){
    //drupal_set_message( $output['msg'], 'error');
    form_set_error('name', $output['msg']);
  }
}


hook_theme_registry_alter() and theme() How can hook_theme_registry_alter() associate, for example, theme_mymodule_image_output() with the 'image' theme ID?

As reported in the documentation, hook_theme_registry_alter() is invoked from Drupal to allow third-party modules to alter the theme registry information returned from hook_theme().

The value returned from the implementations of hook_theme() is an array containing information about the different theme functions implemented by the modules (or themes).

function node_theme() {
  return array(
    'node' => array(
      'arguments' => array('node' => NULL, 'teaser' => FALSE, 'page' => FALSE),
      'template' => 'node',
    ),
    'node_list' => array(
      'arguments' => array('items' => NULL, 'title' => NULL),
    ),
    'node_search_admin' => array(
      'arguments' => array('form' => NULL),
    ),
    'node_filter_form' => array(
      'arguments' => array('form' => NULL),
      'file' => 'node.admin.inc',
    ),
    'node_filters' => array(
      'arguments' => array('form' => NULL),
      'file' => 'node.admin.inc',
    ),
    'node_admin_nodes' => array(
      'arguments' => array('form' => NULL),
      'file' => 'node.admin.inc',
    ),
    'node_add_list' => array(
      'arguments' => array('content' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_form' => array(
      'arguments' => array('form' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_preview' => array(
      'arguments' => array('node' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_log_message' => array(
      'arguments' => array('log' => NULL),
    ),
    'node_submitted' => array(
      'arguments' => array('node' => NULL),
    ),
  );
}

The returned array used what in my previous comment I called theme ID, and it is the same value that is passed to theme().
node_theme() doesn't use it, but the documentation for hook_theme() reports that the array can use the function index to report which function needs to be called as theme function.

A module implementing hook_theme_registry_alter() should use the following code to change the function that is invoked when theme('image') is called.

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

When a module alters the theme registry using that code, any call to theme('image', ...) will not invoke theme_image() anymore, but it will invoke the function defined from that module.
To notice that it is not necessary to name the function theme_mymodule_image_output(); the code would work the same if the function is renamed mymodule_image_output() and the code of mymodule_theme_registry_alter() is accordingly changed. I usually use the prefix theme_ to make clear the function is a theme function.


How to import a display mode configuration from a custom module I have a custom module with the file config/install/core.entity_view_display.node.event.featured.yml
which contains config for a display mode called 'featured' for the content type 'event'.

The problem is, Drupal won't import these settings because the view mode 'featured' already exists.

I'm aware it already exists. I don't want to create the view mode. I want to simply import the settings for that view mode. I.e. populate the settings for each of the fields in that display mode.

Is there a way to do this without deleting the view mode before installing my module?

Features may help you solve this problem - https://www.drupal.org/project/features . If you have Features enabled, and the module include a mymodule.features.yml file in it, it can gracefully handle updating existing configuration like this without throwing the nasty error. You can do a drush fr mymodule and it will import the new configuration without having to delete existing. As 4x4 was mentioning, this wouldn't be ideal for configuration site owners are changing, but if it's something you're updating and maintaining as the developer, it's an ideal route to go.


Alternative #markup in a block's build function Version: Drupal 8.7.x

I am adding some canvas element to my page, and it gets ignored by Drupal. I can't even see it in the source page of browser.

If I have something like this in my code:

public function build(){
   $content = "Something<canvas id='12' width='100' height='100'>
               </canvas>"
   return ['#markup'=>$content];
}

View page source will only shows

 Something

I was thinking that this might be an issue with the #markup. I was wondering if there are any alternative way to work with canvas.

You can use #allowed_tags on the markup.

So put it like that:

  $content = "Something<canvas id='12' width='100' height='100'>
               </canvas>"
   return [
     '#markup' => $content,
     '#allowed_tags' => [
       'canvas',
       'span'
     ]
   ];

not exactly sure if you need to add the span tag.

But also note that following is suggested as Drupal Best Practice from https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/group/theme_render/8.7.x:

  #markup: Specifies that the array provides HTML markup directly. Unless
  the markup is very simple, such as an explanation in a paragraph tag, it
  is normally preferable to use #theme or #type instead, so that the
  theme can customize the markup

And this is the explanation from Drupal regarding #markup and tags:

  Note that the value is passed through
  \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS
  vectors while allowing a permissive list of HTML tags that are not XSS
  vectors. (For example,  and  are not allowed.) See
  \Drupal\Component\Utility\Xss::$adminTags for the list of allowed
  tags. If your markup needs any of the tags not in this whitelist, then
  you can implement a theme hook and/or an asset library. Alternatively,
  you can use the key #allowed_tags to alter which tags are filtered.