Campos relacionados

Buenas noches, soy nuevo en el uso de SUITE CRM, y me gustaría que alguien me ayudara con lo siguiente. En la sección de Oportunidades necesito llenar un campo con los datos del Producto que sale cuando se despliega la ventana emergente, eso es al seleccionar que producto quiero agregar, en la ventana emergente me salen las opciones de Nombre, Precio, el campo nombre lo carga correctamente al seleccionar el producto, porque lo hice con una relación del módulo Productos al módulo Oportunidades, pero el campo precio no veo la forma de hacerlo, intente hacerlo con relaciones pero tengo que seleccionar dos veces, una para el producto y otra para el precio, por favor ayúdenme. Muchas gracias de antemano, si es necesario hacer esto a base de código y pueden indicarme como es les agradecería mucho.

Hello @Carballo_Buque

I appreciate your guidance in addressing the challenge in SuiteCRM. Here’s a comprehensive breakdown of the solution with step-by-step instructions for clarity:

Step 1: Set Up Relationship

  • Ensure a relationship between the Products and Opportunities modules is established for the “Product” field.

Step 2: Logic Hook Implementation

  • Create a ‘before_save’ logic hook in SuiteCRM to execute custom PHP code.

  • Navigate to the custom/modules/Opportunities/logic_hooks.php file.

  • Add the following code:

$hook_version = 1;
$hook_array = array();

$hook_array['before_save'] = array();
$hook_array['before_save'][] = array(
    1,
    'Update Price on Opportunities',
    'custom/modules/Opportunities/OpportunityLogicHook.php',
    'OpportunityLogicHook',
    'updatePrice'
);
  • Create the logic hook file at custom/modules/Opportunities/OpportunityLogicHook.php.

  • Add the logic hook code:

if (!defined('sugarEntry') || !sugarEntry) {
    die('Not A Valid Entry Point');
}

class OpportunityLogicHook
{
    public function updatePrice($bean, $event, $arguments)
    {
        // Check if the product is selected
        if (!empty($bean->product_id)) {
            // Retrieve the related product record
            $product = BeanFactory::getBean('Products', $bean->product_id);

            // Update the price field in Opportunities with the price from the product
            $bean->price_field = $product->price;
        }
    }
}

Step 3: Customize Code

  • Adjust placeholders in the code (e.g., ‘price_field’, ‘product_id’, ‘Products’, ‘price’) with your actual field names and module names.

Step 4: Testing

  • Go to the admin section and ‘Repair and Rebuild’.

I hope this detailed breakdown proves helpful to you. If you have any concerns regarding this, feel free to share.

Thanks.

Hola chirag_biz309 adjunto unas fotos para explicar mejor lo que necesito hacer, tu ayuda por favor.

Estoy tratando con un código JavaScript pero aun no me funciona.



Solución: Sobrescribir la función “display()” del archivo “modules/Opprtunities/views/view.edit.php” con este código

public function display()
    {       
        global $mod_strings;
        //javascript to make field mandatory
        $jsscript = <<<EOQ
           <script>            
                    document.getElementById('btn_aos_products_opportunities_1_name').onclick = function()
                    {
                        var popup_request_data = 
                        {
                            'call_back_function' : 'set_return',
                            'form_name' : 'EditView',
                            'field_to_name_array' : 
                            {
                                'id' : 'aos_products_opportunities_1aos_products_ida',
                                'name' : 'aos_products_opportunities_1_name',
                                'price' : 'precio_del_producto_c',
                            }
                        };
                    open_popup('AOS_Products', 600, 400, '', true, false, popup_request_data);
                    }

                    /*************
                        SOBREESCRIBO LA FUNCION ser_return que viene por defecto en el CRM
                    ***********/
                        
                    function set_return(popup_reply_data) {

                      //  console.log('Entro a esta funcion: set_return AAAAA');

                      from_popup_return = true;
                      var form_name = popup_reply_data.form_name;
                      var name_to_value_array = popup_reply_data.name_to_value_array;

                      for (var the_key in name_to_value_array) {
                        if (the_key == 'toJSON') {
                          /* just ignore */
                        }
                        else {
                          
                          var displayValue = name_to_value_array[the_key].replace(/&amp;/gi, '&').replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/&#039;/gi, '\'').replace(/&quot;/gi, '"');
                          
                            /********
                                CONTROL EL TIPO DE VALOR
                                SI ES UN NUMERO LO REDONDEO A DOS DECIMALES
                            *******/
                          if (!isNaN(displayValue)) {
                            displayValue = parseFloat(displayValue).toFixed(2);
                          }


                          if (window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
                            window.document.forms[form_name].elements[the_key].value = displayValue;
                            SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
                          }

                        }
                      }
                    }

        </script>
EOQ;
        parent::display();
        echo $jsscript;     //echo the script
    }

}

Interesting solution :+1:

But note, that won’t work on SuiteCRM v8 and later - are you ok with that?

Yes, thanks for the clarification.