Prevent deletion of some products - crm

Hello i want to disable delete or prevent them from deleting certain products in some module when user clicks delete button. Is there any experts who knows this ?
Thanks in advance any help would be appreciated.
found a sample code trying to put it together but i think there something more missing. sorry im pretty new with this:
<?php
if (isset($_REQUEST['action'])
&& $_REQUEST['action'] == 'DetailView'){
$sql = 'update AOS_Products set deleted = 0 where id ="'.$bean->id.'"p';
$result = $GLOBALS['db']->query($sql);
$GLOBALS['db']->fetchByAssoc($result);
} else{
SugarApplication::appendErrorMessage("Warning: this product shouldn't be deleted.");
}
here's the delete button i want to disable.
also the inspect element of the delete button:

You need to set up what products id you want to protect before execute the query
<?php
if (isset($_REQUEST['action'])
&& $_REQUEST['action'] == 'DetailView'){
$arrayId = array(1, 2, 3, 4); //ids to protect
$delete = True; //boolean used for check if delete or not
foreach ($arrayId as $id) {
if($bean->id == $id) //check if id to delete is one of the protected id's
{ //looking the code i guess "$bean->id" have the product id
$delete = False;
}
}
if($delete)
{
//if true, run the query for delete
$sql = 'update AOS_Products set deleted = 0 where id ="'.$bean->id.'"p';
$result = $GLOBALS['db']->query($sql);
$GLOBALS['db']->fetchByAssoc($result);
}
else
{
SugarApplication::appendErrorMessage("Warning: this product shouldn't be deleted.");
}
} else{
//Any message related to the reason of no access the first if
}

In view.detail.php add below line
unset($this->dv->defs['templateMeta']['form']['buttons'][2]);

Related

WordPress prevent delete taxonomy

I would like to prevent that some categories are accidentally deleted. For this I use a meta entry for the category to be protected.
I use the following code for this:
// edit: wrong hook! ** add_action( 'delete_term_taxonomy', 'taxonomy_delete_protection', 10, 1 );
add_action( 'pre_delete_term', 'taxonomy_delete_protection', 10, 1 );
function taxonomy_delete_protection ( $term_id )
{
if (get_term_meta ($term_id, 'delete-protect', true) === true)
{
wp_die('Cannot delete this category');
}
}
Unfortunately, instead of my error message, only "Something went wrong" is displayed. Why?
Edit: The `delete_term_taxonomy` is the wrong hook for my code, because it deleted the meta before i can check the meta entry. `pre_delete_term` does fire before anything happens with the category.
The "Why" is because of the following JavaScript that ships with WordPress:
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
/**
* Removes the term from the parent box and the tag cloud.
*
* `data.match(/tag_ID=(\d+)/)[1]` matches the term ID from the data variable.
* This term ID is then used to select the relevant HTML elements:
* The parent box and the tag cloud.
*/
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + wp.i18n.__( 'Sorry, you are not allowed to do that.' ) + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + wp.i18n.__( 'Something went wrong.' ) + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
The expected response to this POST request is:
'1' if the term was deleted
'-1' if your user doesn't have permission to delete the term.
For all other cases, "Something went wrong" is displayed.
You are terminating the script early with wp_die, yielding an unexpected response, which comes under "other cases".
There isn't a way to provide a custom error message in the notice box here without writing some JavaScript of your own.
This is my current solution, not perfect but it works.
The "Something went wrong" message show up if you delete the taxonomy with the row action. So i unset the "delete" action so it couldn't be triggered this way.
add_filter ('category_row_actions', 'unset_taxonomy_row_actions', 10, 2);
function unset_taxonomy_row_actions ($actions, $term)
{
$delete_protected = get_term_meta ($term->term_id, 'delete-protect', true);
if ($delete_protected)
{
unset ($actions['delete']);
}
return $actions;
}
Then i hide the "Delete" Link in the taxonomy edit form with css. It's still could be triggered if you inspect the site and it's link, but there is no hook to remove this action otherwise.
add_action( 'category_edit_form', 'remove_delete_edit_term_form', 10, 2 );
function remove_delete_edit_term_form ($term, $taxonomy)
{
$delete_protected = get_term_meta ($term->term_id, 'delete-protect', true);
if ($delete_protected)
{
// insert css
echo '<style type="text/css">#delete-link {display: none !important;}</style>';
}
}
Finally the check before deleting the taxonomy. This should catch all other ways, like the bulk action "delete". I didn't found another way yet to stop the script from deleting the taxonomy.
add_action ('pre_delete_term', 'taxonomy_delete_protection', 10, 1 );
function taxonomy_delete_protection ( $term_id )
{
$delete_protected = get_term_meta ($term_id, 'delete-protect', true);
if ($delete_protected)
{
$term = get_term ($term_id);
$error = new WP_Error ();
$error->add (1, '<h2>Delete Protection Active!</h2>You cannot delete "' . $term->name . '"!');
wp_die ($error);
}
}
This solution provides a way to disable all categories from being deleted by a non Admin. This is for anyone like myself who's been searching.
function disable_delete_cat() {
global $wp_taxonomies;
if(!current_user_can('administrator')){
$wp_taxonomies[ 'category' ]->cap->delete_terms = 'do_not_allow';
}
}
add_action('init','disable_delete_cat');
The easiest solution (that will automatically take care of all different places where you can possibly delete the category/term) and in my opinion the most flexible one is using the user_has_cap hook:
function maybeDoNotAllowDeletion($allcaps, $caps, array $args, $user)
{
if ($args[0] !== 'delete_term') return $allcaps;
// you can skip protection for any user here
// let's say that for the default admin with id === 1
if ($args[1] === 1) return $allcaps;
$termId = $args[2];
$term = get_term($termId);
// you can skip protection for all taxonomies except
// some special one - let's say it is called 'sections'
if ($term->taxonomy !== 'sections') return $allcaps;
// you can protect only selected set of terms from
// the 'sections' taxonomy here
$protectedTermIds = [23, 122, 3234];
if (in_array($termId, $protectedTermIds )) {
$allcaps['delete_categories'] = false;
// if you have some custom caps set
$allcaps['delete_sections'] = false;
}
return $allcaps;
}
add_filter('user_has_cap', 'maybeDoNotAllowDeletion', 10, 4);

WordPress - Gravity Forms: How to add a "confirm phone number" field

If you are familiar with WordPress Gravity Forms then you know that can add a "Phone" field from the advanced fields options. That's great but I am working on a site that offers a service to mobile users so I need make sure that the person filling out the form does so twice (in two fields) to ensure that there isn't a typo in their mobile number entered. I've been looking everywhere and can't figure out how to do this.
This code from http://gravitywiz.com/custom-field-confirmation/ worked perfectly for me. There are more detailed instructions on their site.
Paste this into your functions.php file and change register_confirmation_fields(8, array(1, 2)); to suit your form.
/**
* Double Confirmation Fields
* http://gravitywiz.com/2012/05/01/custom-field-confirmation/
*/
register_confirmation_fields(8, array(1, 2));
add_filter('gform_validation', 'gfcf_validation');
function gfcf_validation($validation_result) {
global $gfcf_fields;
$form = $validation_result['form'];
$confirm_error = false;
if(!isset($gfcf_fields[$form['id']]))
return $validation_result;
foreach($gfcf_fields[$form['id']] as $confirm_fields) {
$values = array();
// loop through form fields and gather all field values for current set of confirm fields
foreach($form['fields'] as $field) {
if(!in_array($field['id'], $confirm_fields))
continue;
$values[] = rgpost("input_{$field['id']}");
}
// filter out unique values, if greater than 1, a value was different
if(count(array_unique($values)) <= 1)
continue;
$confirm_error = true;
foreach($form['fields'] as &$field) {
if(!in_array($field['id'], $confirm_fields))
continue;
// fix to remove phone format instruction
if(RGFormsModel::get_input_type($field) == 'phone')
$field['phoneFormat'] = '';
$field['failed_validation'] = true;
$field['validation_message'] = 'Your values do not match.';
}
}
$validation_result['form'] = $form;
$validation_result['is_valid'] = !$validation_result['is_valid'] ? false : !$confirm_error;
return $validation_result;
}
function register_confirmation_fields($form_id, $fields) {
global $gfcf_fields;
if(!$gfcf_fields)
$gfcf_fields = array();
if(!isset($gfcf_fields[$form_id]))
$gfcf_fields[$form_id] = array();
$gfcf_fields[$form_id][] = $fields;
}
// register field IDs 1 and 2 on form ID 8
register_confirmation_fields(8, array(1, 2));

hook_alter uc_addresses submit function in Drupal/Ubercart

I am trying to hook into uc_addresses submit function, but it has become very confusing very fast. Just to note this is Ubercart running on Drupal 6. So I've isolated the code in uc_addresses.module that I'm interested in hooking in to:
function uc_addresses_get_address_form_submit($form, &$form_state) {
global $user;
$address_user = $form['stored_values']['#value']['user'];
$address = $form['stored_values']['#value']['address'];
$view = $form['stored_values']['#value']['view'];
if ($form_state['clicked_button']['#value'] == t('Delete address')) {
cache_clear_all();
$form_state['redirect'] =
array('user/'. $address_user->uid .'/addresses/' . $address->aid . '/delete');
}
else {
if (!$address) {
$address = new stdClass();
$address->uid = $address_user->uid;
}
$valid = TRUE;
foreach (element_children($form_state['values']['panes']) as $pane_id) {
$func = _address_pane_data($pane_id, 'callback');
$isvalid = $func('process', $address, $form_state['values']['panes'][$pane_id]);
if ($isvalid === FALSE) {
$_SESSION['expanded_panes'][] = $key;
$valid = FALSE;
}
}
if ($view == 'edit') { // Update database
_uc_addresses_db_update_address($address);
}
elseif ($view == 'new' || $view == 'add') { // Insert into datebase
_uc_addresses_db_add_address($address);
}
$form_state['redirect'] = array('user/'. $address_user->uid .'/addresses');
}
}
The goal is to copy a portion of the submitted form values in the database. Which in itself may be an issue because I need to make sure my hook occurs after the values have been written to the table. So my question is what should my hook function look like if I want it to occur after this form has been submitted?
Okay so foolish me didn't realize that there is a huge section in the uc_addresses documention about hooks. Link to the documentation. In this specific case where you want to hook into form submissions I would recommend using hook_uc_addresses_address_insert() and hook_uc_addresses_address_update().

wordpress contact form 7 unique id

i am currently using contact form 7 for wordpress. i would like a unique id for every form filled in and sent.
i have had a look around the internet but cant find anything, although i did find the following:
http://contactform7.com/special-mail-tags/
would there be any easy way to make my own function to do something similar to the above tags? i would need it to be a function to go into my themes function file, so that plugin updates wont affect it.
Cheers Dan
[_serial_number] field is an auto-incremented form submission ID. You just have to have Flamingo plugin installed as well. See http://contactform7.com/special-mail-tags/
(It's the same link as in the question, I guess the field wasn't there when the question was asked).
To generate ID for the Contactform7 you need to hook the 'wpcf7_posted_data'.
However, to generate incremental ID you need to save the forms in database so you can retrieve which ID should be next on next Form submit. For this you will need CFDB plugin (https://cfdbplugin.com/).
If you dont want to put the code inside theme functions.php file, you can use this plugin instead: https://wordpress.org/plugins/add-actions-and-filters/
Example code:
function pk_generate_ID($formName, $fieldName) {
//Retrieve highest ID from all records for given form stored by CFDB, increment by 1 and return.
require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php');
$start = '001';
$exp = new CFDBFormIterator();
$atts = array();
$atts['show'] = $fieldName;
$atts['filter'] = "$fieldName>=$start&&$fieldName<999999999999"; //is_numeric() is not permitted by default for CFDB filter
$atts['limit'] = '1';
$atts['orderby'] = "$fieldName DESC";
$atts['unbuffered'] = 'true';
$exp->export($formName, $atts);
$found = $start;
while ($row = $exp->nextRow()) {
$row2 = $row[$fieldName];
$row2 += 1;
$found = max($found,$row2);
}
return $found;
}
function pk_modify_data( $posted_data){
$formName = 'Form1'; // change this to your form's name
$fieldName = 'ID-1'; // change this to your field ID name
//Get title of the form from private property.
$cf_sub = (array) WPCF7_Submission::get_instance();
$cf = (array) $cf_sub["\0WPCF7_Submission\0contact_form"];
$title = (string) $cf["\0WPCF7_ContactForm\0title"];
if ( $posted_data && $title == $formName) ) { //formName match
$posted_data[$fieldName] = pk_generate_ID($formName, $fieldName);
}
return $posted_data;
}
add_filter('wpcf7_posted_data', 'pk_modify_data');

How can user 1 or super admin be excluded in search results in Drupal 7?

I'm looking for a way to exclude the admin user or user 1 from user search results in drupal 7.
I want this to not show up for security reasons.
If you build a custom search using Views, you can set the filter(s) to only show users with certain roles. Do not expose the filter to users. If User 1 has the "administrator" role and everyone else has another (non-administrator) role, when you apply the filter, only non-administrator accounts will show up when a search is run.
You can implement hook_preprocess_search_result() by inserting the following into template.php. Note you'll have to clear the Drupal cache to enable this function in Configuration -> Performance -> Clear Cache
function <themename>_preprocess_search_result(&$variables) {
global $language;
$display_result = true;
if( $variables['module'] == 'user' ) {
if( $variables['user']->uid == 1 || $variables['id'] == 1 ) {
$display_result = false;
$variables = array();
}
}
if( $display_result ) {
$result = $variables['result'];
$variables['url'] = check_url($result['link']);
$variables['title'] = check_plain($result['title']);
if (isset($result['language']) && $result['language'] != $language->language && $result['language'] != LANGUAGE_NONE) {
$variables['title_attributes_array']['xml:lang'] = $result['language'];
$variables['content_attributes_array']['xml:lang'] = $result['language'];
}
$info = array();
if (!empty($result['module'])) {
$info['module'] = check_plain($result['module']);
}
if (!empty($result['user'])) {
$info['user'] = $result['user'];
}
if (!empty($result['date'])) {
$info['date'] = format_date($result['date'], 'short');
}
if (isset($result['extra']) && is_array($result['extra'])) {
$info = array_merge($info, $result['extra']);
}
// Check for existence. User search does not include snippets.
$variables['snippet'] = isset($result['snippet']) ? $result['snippet'] : '';
// Provide separated and grouped meta information..
$variables['info_split'] = $info;
$variables['info'] = implode(' - ', $info);
$variables['theme_hook_suggestions'][] = 'search_result__' . $variables['module'];
}
}
Another way to do it would be search-result.tpl.php and check the $info_split array to check if the search result was user one and not display any output.
Don't forget that you'll need to also prevent users from visiting site.com/user/1 as they'll be able to get just as much information from this page.

Resources