Drupal 6 getting the node title from a submitted form - drupal

I am using form_alter to edit the submit function when editing content. In my custom function I wish to edit a custom message to the screen with the title name. I thought a way I could do this is something as follows
function mymodule_myfunction(&$form) {
drupal_set_message(t('Some text ' . $form['#node']->title));
}
The title is not being joined to the 'Some text'
I am calling my function by using the following line in my form_alter:
$form['#submit'][] = 'mymodule_myfunction';

All submit functions get two parameters passed to them: $form, which is the final form array after all of the adjustments for hook_form_alter and the like, and $form_state which among other values contains the submitted values, which have been cleaned and checked for ranges. (For instance, if you have three items in a select box, the data in $form_state['values'] already has made sure that the value for that input is one of the three legal values.)
Generally, you shouldn't use $form['#post'] - it's not part of the published way to get at values, and an update to the core to handle some problem with FAPI could conceivably break your code.
Try this:
function mymodule_myfunction($form, &$form_state) {
drupal_set_message(t('Some Message #title'),
array('#title' => $form_state['values']['title'])));
}
Note the corrected use of the t() function - the intent of that function is to allow other users to translate text, and so by using 'Some Message #title' the translator knows more about what is going on. Additionally you get the advantage that text fed through the t function in this way also is fed through check_plain(), which prevents someone from doing something malicious with the input.

DKinzer recommended using dsm($form)to see the variables. The Node title is not populated. It can be found in the Post array. The following line allowed me to do what I wanted.
drupal_set_message(t('Some Text '.$form['#post']['title']));

Try changing the signature of your
function mymodule_myfunction(&$form) {
drupal_set_message(t('Some text ' . $form['#node']->title));
}
To:
function mymodule_myfunction($form, &$form_state) {
drupal_set_message(t('Some text ' . $form['#node']->title));
}
Also try installing the devel module so you can do things like
dsm($form);
dsm($form_state);
And see exactly what you are dealing with.
Also, if all you want to do is give a message when a new node of type 'X' is created a better way is to use hook_nodeapi;
It could look something like this;
function modulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($op == 'insert' && $node->type == 'my node type') {
drupal_set_message($node-title . ' is cool.');
}
}

Related

SilverStripe CMS, Dropdown Field search by title or another match?

Hi I would like to get a search either by title or by product code in this use case, but the map('ID', 'Title') method does not expect an array to the second parameter, how could I get it?
/* original snippet */
DropdownField::create(
'ProductID',
'Prodotto',
Product::get()->sort('Title', 'ASC')->map('ID', 'Title')
)->setEmptyString('-- Seleziona --');
/* dummy sample snippet */
DropdownField::create(
'ProductID',
'Prodotto',
Product::get()->sort('Title', 'ASC')->map('ID', ['Code','Title'])
)->setEmptyString('-- Seleziona --');
I took a look at the API, unfortunately I couldn't find a method that satisfies this for the DropdownField.
Thank you
Your question asks for a search but your code is generating a string for the DropDownField.
If you want more advanced labels for the Dropdown you'd need a helper method on the Product DataObject like
public function getCodeAndTitleFormatted()
{
return $this->Code . ': ' . $this->Title;
}
Then you use this method in your ->map() statement to create your DropDownField like:
DropdownField::create(
'ProductID',
'Prodotto',
Product::get()->sort('Title', 'ASC')->map('ID', 'getCodeAndTitleFormatted')
)->setEmptyString('-- Seleziona --');

Drupal 7 - Change field widget type based on form status (add/edit)

I have an entity reference field using Autocomplete widget type. I´d like to change the widget type to 'select list' for adding new node, and keep autocomplete when editing.
Have been two days I´m working on this. I didn´t found any solution.
One way I've done this is using hook_form_alter. Create a custom module (if you don't have one already (let's call it mymodule for now) and add the function:
function mymodule_form_alter(&$form, &$form_state, $form_id)
In there you can check the id to see which form is being processed, it should be something along the lines of mytype_node_form but you can also inspect it fairly easily by executing something like drupal_set_message(print_r($form_id, true)); in the function.
You can check to see if you're adding or updating by checking $form_state['node']->nid. After that you can modify the form by doing something like the following:
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
// check to see if this is our form and it is a new node form (doesn't have an id yet)
if ($form_id == 'mytype_node_form' && !isset($form_state['node']->nid)) {
$form['field_coordinators']['und']['#type'] = 'select';
}
}
That's just a start mind you, you'll likely have to change or even remove other properties but you can look into these settings by setting the field to use a select list and inspecting the structure of $form, again.

Module field with feeds, module generating data

I have an issue with triming a field before it is saved. I wanted to use substr(), or regex() with preg_match(). I have built a Drupal 7 module, but it can't work at all. I have tried using the trim plugin in feeds tamper module, but it doesn't seem to work. The data I am using is from a feed from Google Alerts. I have posted this issue here.
This is what I have done so far, and I know my regular expression is wrong; I was trying to get it do anything, just to see if I could get it to work, but I am pretty lost on how to add this type of function to a Drupal module.
function sub_node_save() {
$url = $node->field_web_screenhot['und'][0]['url'];
$url = preg_match('~^(http|ftp)(s)?\:\/\/((([a-z0-9\-]*)(\.))+[a-z0-9]*)($|/.*$)~i',$url );
$node->field_web_screenhot['und'][0]['url'] =$url;
return ;
}
I used the Devel module to get the field.
If there's an easy way to use substr(), I would consider that or something else.
Basically, I just want to take the Google redirect off the URL, so it is just the basic URL to the web site.
Depending on your question and later comments, I'd suggesting using node_presave hook (http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_presave/7) for this.
It's called before both insert (new) and update ops so you will need extra validations to prevent it from executing on node updates if you want.
<?php
function MYMODULE_node_presave($node) {
// check if nodetype is "mytype"
if ($node->type == 'mytype'){
// PHP's parse_url to get params set to an array.
$parts = parse_url($node->field_web_screenhot['und'][0]['url']);
// Now we explode the params by "&" to get the URL.
$queryParts = explode('&', $parts['query']);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
//valid_url validates the URL (duh!), urldecode() makes the URL an actual one with fixing "//" in http, q is from the URL you provided.
if (valid_url(urldecode($parms['q']))){
$node->field_web_screenhot['und'][0]['url'] = urldecode($parms['q']);
}
}
}

retrieve cck field for form_alter

I would like to retrieve a cck field "field_info" in my form alter to insert into another table when user is submitting. This doesn't seem to work.
//mymodule_form_alter() implemented
function mymodule_form_mysubmit{
$test = $form['field_info']['#value'];
//insert stuff code
}
Is there any mistake in the code?
You say module_form_alter() is implemented, but just to confirm, you need to have the following in it:
$form['#submit'][] = 'mymodule_form_mysubmit';
Assuming you do, to get the value of field_info, your submit function should look like:
function mymodule_form_mysubmit($form, &$form_state) {
$test = $form_state['values']['field_info'][0]['value'];
}
$form_state contains the current state of the form being submitted. CCK always assumes that there could be multiple values for a field, so it always puts things in an array (hence ['field_info'][0]).
I found the solution
$test = $form['field_info'][0]['#value'];

Removing [nid:n] in nodereference autocomplete

Using the autocomplete field for a cck nodereference always displays the node id as a cryptic bracketed extension:
Page Title [nid:23]
I understand that this ensures that selections are unique in case nodes have the same title, but obviously this is a nasty thing to expose to the user.
Has anyone had any success in removing these brackets, or adding a different unique identifier?
Ultimately, you need to change the output of nodereference_autocomplete() in nodereference.module.
To do this properly, you want a custom module to cleanly override the function.
This function is defined as a menu callback, thus,
/**
* Implementation of hook_menu_alter().
*/
function custom_module_menu_alter(&$items) {
$items['nodereference/autocomplete']['page callback'] = 'custom_module_new_nodereference_autocomplete';
}
Then, copy the nodereference_autocomplete function into your custom module, changing it's name to match your callback. Then change this one line:
$matches[$row['title'] ." [nid:$id]"] = '<div class="reference-autocomplete">'. $row['rendered'] . '</div>';
Dropping the nid reference.
$matches[$row['title']] = '<div class="reference-autocomplete">'. $row['rendered'] . '</div>';
I believe the identifier is purely cosmetic at this point, which means you could also change the text however you like. If it is not purely cosmetic, well, I haven't tested to see what will happen in the wrong conditions.
I always meant to identify how to do this. Thank you for motivating me with your question.
What Grayside has posted will work... as long as you don't have two nodes with the same title. In other words, if you want to do as Grayside has proposed, you need to be aware that the nid is not entirely unimportant. The nodereference_autocomplete_validate() function does two things. It checks to see if there is a node that matches, and if so, it passes the nid on, setting it to the $form_state array. If it can't find a node, it will set an error. If the nid is present, it will be used to get the node, which also is faster, the code is here:
preg_match('/^(?:\s*|(.*) )?\[\s*nid\s*:\s*(\d+)\s*\]$/', $value, $matches);
if (!empty($matches)) {
// Explicit [nid:n].
list(, $title, $nid) = $matches;
if (!empty($title) && ($n = node_load($nid)) && $title != $n->title) {
form_error($element[$field_key], t('%name: title mismatch. Please check your selection.', array('%name' => t($field['widget']['label']))));
}
}
This just checks to see if there is a nid and checks if that node matches with the title, if so the nid is passed on.
The 2nd option is a bit slower, but it is here errors can happen. If you follow the execution, you will see, that if will try to find a node based on title alone, and will take the first node that matches. The result of this, is that if you have two nodes with the same title, one of them will always be used. This might not be a problem for you, but the thing is, that you will never find out if this happens. Everything will work just fine and the user will think that he selected the node he wanted to. This might be the case, but he might as well have chosen the wrong node.
So in short, you can get rid of the nid in the autocomplete callback, but it has 2 drawbacks:
performance (little)
uncertainty in selecting the correct node.
So you have to think about it, before going this route. Especially, since you most likely wont be able to find the problem of the selection of the wrong nodes, should it happen. Another thing to be aware of, is that the nid showing up, also brings some valuable info to the users, a quick way to lookup the node, should they be in doubt if it is the one they want, if several nodes have similar titles.
I got Grayside's answer to work, but I had to use MENU alter, instead of the FORM alter he posted. No biggy!
function custommodule_menu_alter(&$items) {
$items['nodereference/autocomplete']['page callback'] = 'fp_tweaks_nodereference_autocomplete';
}
I've found an alternative solution is to change your widget type to select list and then use the chosen module to convert your list to an autocomplete field.
This handles nodes with the same title, and actually I think the UI is better than the one provided by the autocomplete widget.
To anyone coming across this (rather old) topic by way of a google search - for Drupal 7 please consider using entityreference module and "Entity Reference" field type if possible.
You can acheive a lot more in configuration with an "Entity Reference" field. It doesn't have this problem with the nid in square brackets.
Here is the full Drupal 7 version (References 7.x-2.1) of Grayside's answer. This goes in your custom module:
/**
* Implementation of hook_menu_alter().
*/
function custom_menu_alter(&$items) {
$items['node_reference/autocomplete/%/%/%']['page callback'] = 'custom_new_node_reference_autocomplete';
}
/**
* Implementation of Menu callback for the autocomplete results.
*/
function custom_new_node_reference_autocomplete($entity_type, $bundle, $field_name, $string = '') {
$field = field_info_field($field_name);
$instance = field_info_instance($entity_type, $field_name, $bundle);
$options = array(
'string' => $string,
'match' => $instance['widget']['settings']['autocomplete_match'],
'limit' => 10,
);
$references = node_reference_potential_references($field, $options);
$matches = array();
foreach ($references as $id => $row) {
// Markup is fine in autocompletion results (might happen when rendered
// through Views) but we want to remove hyperlinks.
$suggestion = preg_replace('/<a href="([^<]*)">([^<]*)<\/a>/', '$2', $row['rendered']);
// Add a class wrapper for a few required CSS overrides.
$matches[$row['title']] = '<div class="reference-autocomplete">' . $suggestion . '</div>'; // this is the line that was modified to remove the "[nid:XX]" disambiguator
}
drupal_json_output($matches);
}

Resources