filter records in popup list view if assigned user is login SUITECRM - sugarcrm

I want to filter records so that the assigned user can only see the records that are assigned to him from the popup list view.
The reason why I'm not doing this in the roles management is because if I assigned a user to a client record then other users that have the same role wouldn't able to see it so I've set the role->list tab to "all" and added custom code in list view that only the login user can see their own records.
Here's what I've done.
<?php
require_once('include/MVC/View/views/view.popup.php');
class AccountsViewPopup extends ViewPopup
{
public function display()
{
parent::display(); // TODO: Change the autogenerated stub
require_once 'modules/ACLRoles/ACLRole.php';
$ACLRole = new ACLRole();
$roles = $ACLRole->getUserRoles($GLOBALS['current_user']->id);
if (in_array('User1', $roles)) {
global $db, $current_user;
$this->where .= " AND accounts.assigned_user_id = '$current_user->id' AND deleted=0 ";
}
}
}
But i get this error:
Undefined property: AccountsViewPopup::$where

For list view only: custom/modules/MODULE_NAME/views/view.list.php
and following is the helping code:
require_once('include/MVC/View/views/view.list.php');
class MODULE_NAMEViewList extends ViewList {
function listViewProcess() {
global $current_user;
$this->params['custom_where'] = ' AND module_name.name = "test" ';
parent::listViewProcess();
}
}
For list and popup view(both):
You need to change the logic inside create_new_list_query function which actually prepares a query. Some modules have override it a bean level(e.g. see modules/Leads/Lead.php).
If you want to override it in upgrade safe manner then create a file in custom directory e.g: custom/modules/Leads/Lead.php, then extend it from the core bean class like following:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('modules/Leads/Lead.php');
class CustomLead extends Lead {
function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false, $ifListForExport = false)
{
// Code from create_new_list_query in and then modify it accordingly.
}
}
Register new bean class in this location: custom/Extension/application/Ext/Include/custom_leads_class.php and registration code will look like following:
<?php
$objectList['Leads'] = 'Lead';
$beanList['Leads'] = 'CustomLead';
$beanFiles['CustomLead'] = 'custom/modules/Leads/Lead.php';
?>

I know this has been answered, but decided to post my solution anyway. I had almost the same problem some time ago (7.10.7).
PopupView has method getCustomWhereClause() which you can implement in your custom view.
It has to return containing string with the conditions.
Example:
custom/modules/Meetings/views/view.popup.php
/*class declaration and other stuff*/
protected function getCustomWhereClause()
{
global $current_user;
return " ( {$this->bean->table_name}.assigned_user_id='{$current_user->id}') ";
}
Remember to leave at least one space at the start and the end because SuiteCRM actually forgets to add it and it may result in broken query (but it's fairly easy to find in logs).

Related

Create CSS classes based on user role

Working with Moodle 3.9 and a fork of the current Academi theme.
I am trying to create a css class hook on the <body> element which is based on the user's role(s). I understand that a user's role(s) are context-driven, (maybe a student in one course, and something else in another), so I would output all the roles as classes for a given context.
Based on some extensive digging on the moodle forum I have the following:
// User role based CSS classes
global $USER, $PAGE;
$context = context_system::instance();
$roles = get_user_roles($context, $USER->id, true);
if(is_array($roles)) {
foreach($roles as $role) {
$PAGE->add_body_class('role-'.$role->shortname);
}
} else {
$PAGE->add_body_class('role-none');
}
Preferably I'd like this to run on every page. From within the theme, I've tried just placing this in just about every location/function I thought could be executed early enough to modify the body element. Either I get no output at all or a warning indicating that it is too late to run add_body_class().
I've had a skim of the Page and Output APIs and I still don't have a sense of how or when to execute this code. Should this be a custom plugin instead?
Override the header() function on the core renderer of your current theme template, for instance, on theme\YOUR_THEME\classes\output\core_renderer.php:
namespace theme_YOUR_THEME\output;
defined('MOODLE_INTERNAL') || die;
use context_system;
class core_renderer extends \theme_boost\output\core_renderer {
public function header() {
global $USER;
$roles = get_user_roles(context_system::instance(),$USER->id);
if (is_array($roles) && !empty($roles)){
foreach($roles as $role){
$this->page->add_body_class('role-'.$role->shortname);
}
}else{
$this->page->add_body_class('role-none');
}
return parent::header();
}
}
This way, every page would call this function and have the desired css classes added to the body tag.

How to integrate web services with custom module in SugarCRM?

I'm using SugarCRM to develop a software for customers management. I created a custom module from basic template with custom fields. Is it possible to get rid of SugarCRM db and perform CRUD operations through external web serivices? Actually I was able to show web services data in the datailview by setting the bean property of a custom controller.
class CustomerController extends SugarController{
public function action_detailview(){
$customer = new Customer();
$customer = getCustomerFromWebService();
$this->bean = $customer;
$this->view = "detail";
}
}
I would like to do the same thing with listview, but I don't know how set the records of the list (if it exists) used by the default listview.
You can change list view by customizing view.list.php in custom/modules/modulename/views/view.list.php using following code:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('include/MVC/View/views/view.list.php');
// name of class match module
class modulenameViewList extends ViewList{
// where clause that will be inserted in sql query
var $where = 'like 'htc'';
function modulenameViewList()
{
parent::ViewList();
}
/*
* Override listViewProcess with addition to where clause to exclude project templates
*/
function listViewProcess()
{
$this->lv->setup($this->seed, 'include/ListView/ListViewGeneric.tpl', $this->where, $this->params);
echo $this->lv->display();
}
}
?>

ZEND: Displaying form error messages on failed validation

I have a form say:
class Application_Form_UserDetails extends Zend_Form
{
public function init()
{
$pswd = new Zend_Form_Element_Password('password');
$pswd->setLabel('New password:');
$pswd->setAttrib('size', 25);
$pswd->setRequired(false);
$pswd->addValidator('StringLength', false, array(4,15));
$pswd->addErrorMessage('Wron password');
}
}
In my user details controller class I have:
class UserDetailsController extends Zend_Controller_Action {
public function editAction()
{
$userId = $this->userInfo->id;
$DbTableUsers = new Application_Model_DbTable_User;
$obj = $DbTableUsers->getUserDetails($userId);
$this->view->formUser = new $this->_UserDetails_form_class;
$this->view->formCompany = new $this->_CompanyDetails_form_class;
if ($obj) {
$this->view->formUser->populate($obj);
}
$url = $this->view->url(array('action' => 'update-user-details'));
$this->view->formUser->setAction($url);
}
public function updateUserDetailsAction()
{
$formUser = new $this->_UserDetails_form_class;
if ($formUser->isValid($this->getRequest()->getPost())) {
}
else {
//validation failed
$formUser->markAsError();
$this->view->formUser = $formUser;
$this->_helper->redirector('edit', 'user-details');
}
}
}
The first time Edit action is called the form built and displayed.
User fills the form and sends it (updateUserDetailsAction is called).
In updateUserDetailsAction, on validation failure I mark the form as having errors and want to display the form with error messages that I previously set in updateUserDetailsAction class.
Then I redirect:
$this->_helper->redirector('edit', 'user-details');
in order to display the same form but with errors for the user to re-enter correct values.
The problem is I don't know how to let know the edit action that the form must display validation errors?
On $this->_helper->redirector('edit', 'user-details'); the form is redisplayed
as a new form with cleared erros but I need them displayed.
Do I do this the correct way?
regards
Tom
Problem comes from the fact that you are redirecting and in each method you are creating a new instance of the form, that means the form class is loosing its state - data you injected from the request and any other values passed to this object.
Combine editAction and updateUserDetailsAction into one method:
...
$formUser = new Form();
// populate the form from the model
if ($this->getRequest()->isPost()) {
if ($formUser->isValid($this->getRequest()->getPost())) {
// update the model
}
}
...
and have the form being submitted to the edit action. This will simplify your code and remove code duplication.
If you just wan to fix your code you can instantiate the form object in the init() method of your controller as set it as a property of your controller. This will way you will reuse same instance after redirection. I still think that solution above is much more compact and easier to understand for someone else.

Yii2: how to use custom validation function for activeform?

In my form's model, I have a custom validation function for a field defined in this way
class SignupForm extends Model
{
public function rules()
{
return [
['birth_date', 'checkDateFormat'],
// other rules
];
}
public function checkDateFormat($attribute, $params)
{
// no real check at the moment to be sure that the error is triggered
$this->addError($attribute, Yii::t('user', 'You entered an invalid date format.'));
}
}
The error message doesn't appear under the field in the form view when I push the submit button, while other rules like the required email and password appear.
I'm working on the Signup native form, so to be sure that it is not a filed problem, I've set the rule
['username', 'checkDateFormat']
and removed all the other rules related to the username field, but the message doesn't appear either for it.
I've tried passing nothing as parameters to checkDateFormat, I've tried to explicitly pass the field's name to addError()
$this->addError('username', '....');
but nothing appears.
Which is the correct way to set a custom validation function?
Did you read documentation?
According to the above validation steps, an attribute will be
validated if and only if it is an active attribute declared in
scenarios() and is associated with one or multiple active rules
declared in rules().
So your code should looks like:
class SignupForm extends Model
{
public function rules()
{
return [
['birth_date', 'checkDateFormat'],
// other rules
];
}
public function scenarios()
{
$scenarios = [
'some_scenario' => ['birth_date'],
];
return array_merge(parent::scenarios(), $scenarios);
}
public function checkDateFormat($attribute, $params)
{
// no real check at the moment to be sure that the error is triggered
$this->addError($attribute, Yii::t('user', 'You entered an invalid date format.'));
}
}
And in controller set scenario, example:
$signupForm = new SignupForm(['scenario' => 'some_scenario']);
Try forcing the validation on empty field
['birth_date', 'checkDateFormat', 'skipOnEmpty' => false, 'skipOnError' => false],
Also, make sure you don't assign id to your birth_date field in your view.
If you do have id for your birth_date, you need to specify the selectors
<?= $form->field($model, 'birth_date', ['selectors' => ['input' => '#myBirthDate']])->textInput(['id' => 'myBirthDate']) ?>
To make custom validations in yii 2 , you can write custom function in model and assign that function in rule.
for eg. I have to apply password criteria in password field then I will write like this in model.
public function rules()
{
return [
['new_password','passwordCriteria'],
];
}
public function passwordCriteria()
{
if(!empty($this->new_password)){
if(strlen($this->new_password)<8){
$this->addError('new_password','Password must contains eight letters one digit and one character.');
}
else{
if(!preg_match('/[0-9]/',$this->new_password)){
$this->addError('new_password','Password must contain one digit.');
}
if(!preg_match('/[a-zA-Z]/', $this->new_password)){
$this->addError('new_password','Password must contain one character.');
}
}
}
}
You need to trigger $model->validate() somewhere if you are extending from class Model.
I stumbled on this when using the CRUD generator. The generated actionCreate() function doesn't include a model validation call so custom validators never get called. Also, the _form doesn't include and error summary.
So add the error summary to the _form.
<?= $form->errorSummary($model); ?>
...and add the validation call - $model->validate() - to the controller action
public function actionCreate()
{
$model = new YourModel();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {...
Although it's an old post i thought I should answer.
You should create a Custom Validator Class and to create a validator that supports client-side validation, you should implement the yii\validators\Validator::clientValidateAttribute() method which returns a piece of JavaScript code that performs the validation on the client-side. Within the JavaScript code.
You may use the following predefined variables:
attribute: the name of the attribute being validated.
value: the value being validated.
messages: an array used to hold the validation error messages for
the attribute.
deferred: an array which deferred objects can be pushed into
(explained in the next subsection).
SO that means you can use messages array to push your messages to the client end on runtime within the javascript code block in this method.
I will create a class that includes dummy checks that could be replaced the way you want them to. and change the namespace according to your yii2 advanced or basic.
Custom Client-side Validator
namespace common\components;
use yii\validators\Validator;
class DateFormatValidator extends Validator{
public function init() {
parent::init ();
$this->message = 'You entered an invalid date format.';
}
public function validateAttribute( $model , $attribute ) {
if ( /*SOME CONDITION TO CHECK*/) {
$model->addError ( $attribute , $this->message );
}
}
public function clientValidateAttribute( $model , $attribute , $view ) {
$message = json_encode ( $this->message , JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
return <<<JS
if ($("#DATE-1").val()=="" || $("#DATE-2").val() =="") {
messages.push($message);
}
JS;
}
}
and then inside your model SigupForm add the rule
['birth_date', 'common\components\DateFormatValidator'],
Deferred Validation
You can even add ajax calls inside the clientValidateAttribute function and on the base of the result of that ajax call you can push message to the client end but you can use the deferred object provided by yii that is an array of Deferred objects and you push your calls inside that array or explicitly create the Deferred Object and call its resolve() method.
Default Yii's deferred Object
public function clientValidateAttribute($model, $attribute, $view)
{
return <<<JS
deferred.push($.get("/check", {value: value}).done(function(data) {
if ('' !== data) {
messages.push(data);
}
}));
JS;
}
More about Deferred Validation
You need to render the model from controller. Without initializing the model in view. And in the controller you need to call the validate function
Are you sure the first parameter of addError shouldn't be like this
$this->addError(**'attribute'**, Yii::t('user', 'You entered an invalid date format.'));
I had common problem.
In your validation function:
public function checkDateFormat($attribute, $params)
{
// no real check at the moment to be sure that the error is triggered
$this->addError($attribute, Yii::t('user', 'You entered an invalid date format.'));
}
$params doesn`t get any value at all. It actually always equals to Null. You have to check for your attribute value in function:
public function checkDateFormat($attribute, $params)
{
if($this->birth_date == False)
{
$this->addError($attribute, Yii::t('user', 'You entered an invalid date format.'));
}
}
that`s how it worked for me.
If you don't use scenarios for your model, you must mark your atribute as 'safe':
['birth_date','safe'],
['birth_date', 'checkDateFormat'],
And, on the other hand, you can use this for date validation:
['birth_date','safe'],
[['birth_date'],'date', 'format'=>'php:Y-m-d'],
You can change format as you want.
**We should set attributes to the function to work with input value **
public function rules()
{
return [
['social_id','passwordCriteria'],
];
}
public function passwordCriteria($attribute, $params)
{
if(!empty($this->$attribute)){
$input_value = $this->$attribute;
//all good
}else{
//Error empty value
$this->addError('social_id','Error - value is empty');
}
}
Are you by any chance using client side validation? If you do then you have to write a javascript function that would validate the input. You can see how they do it here:
http://www.yiiframework.com/doc-2.0/guide-input-validation.html#conditional-validation
Another solution would be to disable client validation, use ajax validation, that should bring back the error too.
Also make sure that you have not overwritten the template of the input, meaning make sure you still have the {error} in there if you did overwrite it.
Your syntax on rules should be something like this man,
[['birth_date'], 'checkDateFormat']
not this
['birth_date', 'checkDateFormat']
So in your case, it should look like below
...
class SignupForm extends Model
{
public function rules()
{
// Notice the different with your previous code here
return [
[['birth_date'], 'checkDateFormat'],
// other rules
];
}
public function checkDateFormat($attribute, $params)
{
// no real check at the moment to be sure that the error is triggered
$this->addError($attribute, Yii::t('user', 'You entered an invalid date format.'));
}
}

Accessing beans in View Class

Hi I'm still very new to SugarCRM and trying to get my head round sugars MVC.
I'm making a module which doesn't have its own SugarBean instead it needs to interact with the Contacts Beans and Quotes Bean.
My example code is below.
My Question is how can i get access to the $contact_bean and $quote_bean from the controller.php in the view.searchengineer.php file so i can call information from them after the records have been loaded.
controller.php
Class PCP_TasksController extends SugarController
{
function action_search_engineers()
{
// Get Contacts ID
$contact_id = $_GET['Contact_id'];
//Load Contacts Bean and pull Record
$contact_bean = New Contact();
$contact_bean->retrieve($contact_id );
//Get Quote ID
$quote_id = $_GET['Quote_id'];
//Load Quotes Module and pull record
$quote_bean = New AOS_Quotes();
$quote_bean->retrieve($quote_id );
$this->view = 'SearchEngineer';
}
}
views/view.searchengineer.php
class PCP_tasksViewSearchengineer extends SugarView
{
function display() {
Echo "The Contact Name is ";
Echo "The Quote Ref is ";
}
}
I'd just put that same code directly in the view instead.