validate model depending radio button selected - yii

I have install yii-user extension and add some column in tbl_profile table for registration. Registration type are two type: Personal and company
following are the column added:
For company: company_name, comoany_type
For personal: phone
For both personal and company: mobile, fullname, country, states, postal_code, address1, address2
I have use jquery to hide and disable the input field of form according to radio button selection of registration type.
Same goes for country selection for both registration type. Two Options: e.g USA and other country
I am confused that how can I validate the property according to the registration type selected. e.g. If I select the personal then disable the validation for the company property field.
There are two models with their property:
Profile: fullname, company_name, company_type, mobile, phone, firstaddress, secondaddress, country, states, postal_code
RegistrationForm: username, password, email
I have also define rules for those property on corresponding model.
I have tried validating model like this but doesn't works:
if(isset($_POST['RegistrationForm'])) {
if($_POST['Profile']['account_type'] == 'personal')
{
//for personal account
$profile->account_type = $_POST['Profile']['account_type'];
$model->username = $_POST['RegistrationForm']['username'];
$model->password = $_POST['RegistrationForm']['password'];
$model->verifyPassword = $_POST['RegistrationForm']['verifyPassword'];
$model->email = $_POST['RegistrationForm']['email'];
$model->verifyCode = $_POST['RegistrationForm']['verifyCode'];
$model->accept = $_POST['RegistrationForm']['accept'];
$profile->fullname = $_POST['Profile']['fullname'];
$profile->phone = $_POST['Profile']['phone'];
$profile->ext = $_POST['Profile']['ext'];
$profile->mobile = $_POST['Profile']['mobile'];
if($_POST['choose_country'] == 'other')
{
$profile->country = $_POST['choose_country'];
$profile->states = $_POST['profile_states'];
$profile->postalcode = $_POST['Profile']['postalcode'];
$profile->firstaddress = $_POST['Profile']['firstaddress'];
$profile->secondaddress = $_POST['Profile']['secondaddress'];
}
if($_POST['choose_country'] == 'Nepal')
{
$profile->country = $_POST['choose_country'];
$profile->firstaddress = $_POST['Profile']['firstaddress'];
$profile->secondaddress = $_POST['Profile']['secondaddress'];
}
}
if($_POST['Profile']['account_type'] == 'company')
{
//for organization account
$profile->account_type = $_POST['Profile']['account_type'];
$model->username = $_POST['RegistrationForm']['username'];
$model->password = $_POST['RegistrationForm']['password'];
$model->verifyPassword = $_POST['RegistrationForm']['verifyPassword'];
$model->email = $_POST['RegistrationForm']['email'];
$model->verifyCode = $_POST['RegistrationForm']['verifyCode'];
$model->accept = $_POST['RegistrationForm']['accept'];
$profile->fullname = $_POST['Profile']['fullname'];
$profile->ext = $_POST['profile']['ext'];
$profile->mobile = $_POST['Profile']['mobile'];
$profile->company_name = $_POST['Profile']['company_name'];
$profile->company_type = $_POST['Profile']['company_type'];
$profile->designation = $_POST['Profile']['designation'];
if($_POST['choose_country'] == 'Nepal')
{
$profile->country = $_POST['choose_country'];
$profile->states = $_POST['Profile']['states'];
$profile->postalcode = $_POST['Profile']['postalcode'];
$profile->firstaddress = $_POST['profile']['firstaddress'];
$profile->secondaddress = $_POST['profile']['secondaddress'];
}
if($_POST['choose_country'] == 'others')
{
$profile->country = $_POST['profile']['country'];
$profile->firstaddress = $_POST['profile']['firstaddress'];
$profile->secondaddress = $_POST['profile']['secondaddress'];
}
}
//$model->attributes=$_POST['RegistrationForm'];
//$profile->attributes=((isset($_POST['Profile'])?$_POST['Profile']:array()));
if($model->validate()&&$profile->validate())
{
}
}
Problem:
If I select the personal radio button and submit form it still validate the company_name , company type and same for country selection then shows the validation errors. Here what I want is to disable the validation of model depending on selection of radio button either personal or company type.

I never worked with yii-user extension but as a solution I can propose to restrict company and personal validations by setting different scenarios for your $profile model depending on $_POST['Profile']['account_type'] just before assigning values to model from $_POST, e.g.:
if ($_POST['Profile']['account_type'] === "personal")
$profile->scenario = "personal";
else
$profile->scenario = "company";
After that in rules() method of your Profile model you specify corresponding scenario for each account type dependent field:
public function rules() {
return array(
// ...general rules
array("company_name", "validateCompanyName", 'on' => array("company")),
array("company_type", "validateCompanyType", 'on' => array("company")),
array("phone", "validatePersonalPhone", 'on' => array("personal"))
)
}
I believe that this way it will be enough to assign values to models like this:
$model->attributes = $_POST['RegistrationForm'];
$profile->attributes = $_POST['Profile'];

Related

Magento 2: Get Product, Sku and Manufacturer name from database

I use this query to get Product Name and Sku.
I would to add "brand name" that is stored in Manufacturer attributes . Is it possible to expand this query to get manufacturer name by product?
SELECT nametable.value,
nametable.store_id,
m2_catalog_product_entity.sku
FROM `m2_catalog_product_entity_varchar` AS nametable
LEFT JOIN m2_catalog_product_entity
ON nametable.entity_id = m2_catalog_product_entity.entity_id
WHERE nametable.attribute_id = (SELECT attribute_id
FROM `m2_eav_attribute`
WHERE `entity_type_id` = 4 and store_id = 0
AND `attribute_code` LIKE 'name');
I would highly recommend leveraging Magento 2 product object for retrieving the information instead of building queries yourself.
Inside a php class you can retrieve it like this using factory method:
<?php
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ProductFactory $product
) {
$this->product = $product;
parent::__construct($context);
}
public function getProduct($id)
{
$product = $this->product->create()->load($entity_id);
$sku = $product->getSku(); // get SKU
$name = $product->getName(); // get name
$manufacturer = $product->getManufacturer(); // get manufacturer
}
}
Or via Object Manager
$entity_id = "your product id";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($entity_id);
$sku = $product->getSku(); // get SKU
$name = $product->getName(); // get name
$manufacturer = $product->getManufacturer(); // get manufacturer
To retrieve any attribute you want, you can use
$attribute = $product->getData("attribute_code"); // get any attribute

Angular 6, catching ' error/not valid parameter ' in activated route

I am facing a problem with route parameter error catching. Here is the situation explained below.
The route params are as follows for displaying data in components of navbar:
http://localhost:4200/{ company_type }/{ company_name }/{ org-id }/{ component_name }
The website is opening even when I change the company_name to any string and company_id to null || 14cd156. I will get articles when I change company name in route. But, when I change id I get an error
core.js:1624 ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found","url" ...
The API doesn't check for company name. It only checks the company id company coming from route params. What I want to do is: to navigate to not-found page in case the company_name and company_id are invalid. Let's say,
company_type = consulting
company_name = ABC
id = 1
page=Article
In page Article when I change http://localhost:4200/consulting/ABC/5/articles to http://localhost:4200/consulting/3edsads/5/artciles the website shows data of Articles page. But, the data is route parameter is wrong.
articles.component.ts
getOrgArticles(page: number = 1) {
let queryParams = this.getQueryParams(page);
this.queryArticles =
this.service.getOrgArticles(queryParams).
subscribe((data: any) => {
this.page = page;
this.pageSize = queryParams['per-page'] || this.pageSize;
this.articles = this.articles.concat(data['articles']);
this.pageCount = data._meta.pageCount;
this.isLastPage() ? this.hideNextButton() : this.showNextButton();
this.totalCount = data._meta.totalCount;
},
error => {
});
}
service.ts
getOrgArticles(queryParams) {
const qpString = this.queryString(queryParams);
return this.http.get(`${this.api}/articles?${qpString}`);
}
I really wish to find some solution from you. Thank you

How to display external information on Odoo 11?

I'm working on Weather application using Odoo11, I have a Python script that fetches weather information from this API: https://openweathermap.org/api
The script works fine but I have no idea how to integrate it with Odoo.
Can you give guidelines about how to achieve this, for example how to show this information in a form view, tree or Kanban?
Any example will be very helpful for me.
If you only want to show some text that´s always updated you can use a computed field
from odoo import api
weather = fields.Text( # this can be an image or any other field type
string='Weather',
compute='_compute_weather'
)
#api.depends() # leave this empty, so this is executed always when the view with this field is loaded
def _compute_weather(self):
for record in self:
# retrieve the weather information here
record.weather = weather_information # assign the weather information to the variable
Show it in a form view as any other field
<field name="weather" />
Note: If you want to store the information on the database you can just create a button or a atomate task, for instance, to store or update the values in the fields (without compute method).
Note2: Check the source code of the user_weather_map module from Cybrosis, it may be helpful
You can use the module User Weather Notification.
This module uses external API.
def get_weather(self, user_id):
rec = self.env['user.weather.map.config'].search([('user_id', '=', user_id)], limit=1)
if rec:
weather_path = 'http://api.openweathermap.org/data/2.5/weather?'
if rec.u_longitude and rec.u_latitude:
params = urllib.urlencode(
{'lat': rec.u_latitude, 'lon': rec.u_longitude, 'APPID': rec.appid})
elif rec.city:
params = urllib.urlencode(
{'q': rec.city, 'APPID': rec.appid})
else:
return {
'issue': 'localization'
}
url = weather_path + params
try:
f = urllib.urlopen(url)
except Exception:
f = False
if f:
ret = f.read().decode('utf-8')
result = json.loads(ret)
if result:
if "cod" in result.keys():
if result['cod'] == 200:
city = False
city2 = False
if "name" in result.keys():
city = result['name']
if not city:
if rec.method == 'address':
city = rec.city
if rec.method == 'address':
city2 = rec.city
temp = pytemperature.k2c(result['main']['temp'])
min_temp = pytemperature.k2c(result['main']['temp_min'])
max_temp = pytemperature.k2c(result['main']['temp_max'])
weather_rec = self.search([('user_id', '=', rec.user_id.id)])
now_utc = datetime.now(timezone('UTC'))
user_list = self.env['res.users'].search([('id', '=', user_id)])
if user_list.partner_id.tz:
tz = pytz.timezone(user_list.partner_id.tz)
now_pacific = now_utc.astimezone(timezone(str(tz)))
current_time = now_pacific.strftime('%d %B %Y, %I:%M%p')
vals = {
'date_weather_update': current_time,
'name': city,
'city': city2,
'user_id': user_id,
'weather': result['weather'][0]['main'],
'description': result['weather'][0]['description'],
'temp': temp,
'pressure': result['main']['pressure'],
'humidity': result['main']['humidity'],
'min_temp': min_temp,
'max_temp': max_temp,
}
if weather_rec:
weather_rec.write(vals)
return {
'issue': ''
}
else:
weather_rec.create(vals)
return {
'issue': ''
}
else:
return {
'issue': 'timezone'
}
else:
return {
'issue': 'localization'
}
else:
return {
'issue': 'bad_request'
}
else:
return {
'issue': 'internet'
}
else:
return {
'issue': 'config'
}
This is the code that I use in that module. you can just convert it into odoo11.
Thank you.

get user role by user id in moodle

I want to get user role from user id. I am using loop in my code where i want to show all user except admin. i used below code but its not working.
$context = get_context_instance (CONTEXT_SYSTEM);
$roles = get_user_roles($context, $USER->id, false);
$role = key($roles);
$roleid = $roles[$role]->roleid;
Its provide me blank array as like screenshot. Also below my all code.
https://prnt.sc/gq8p12
$allUsers = $DB->get_records('user');
$SQL = "SELECT * FROM `".$CFG->prefix."config` WHERE `name` LIKE 'siteadmins'";
$getSiteAdmins = $DB->get_record_sql($SQL);
$explodeAdminIds = explode(',', $getSiteAdmins->value);
$context = get_context_instance (CONTEXT_SYSTEM);
if(!empty($allUsers))
{
foreach ($allUsers as $allUser)
{
if(!in_array($allUser->id, $explodeAdminIds))
{
$roles = get_user_roles($context, $allUser->id, false);
$role = key($roles);
$roleid = $roles[$role]->roleid;
echo 'USER ID -- '.$allUser->id.' >>> ';
print_r($roles); echo '<br>';
$name = ''.$allUser->id.'_'.$allUser->firstname.' '.$allUser->lastname.'';
$confirmed = ($allUser->confirmed == 1) ? 'Active' : 'In-active';
$table->data[] = array(
$i,
$name,
'Team Name',
$allUser->email,
$allUser->phone1,
'Role',
$confirmed,
//empty($coachusrarr)?'--':implode(',',$coachusrarr),
//empty($tmpleaderarr)?'--':implode(',',$tmpleaderarr),
//$coach,
);
$i++;
}
}
}
The basic problem is that get_user_roles($context, $userid) will only get you a list of roles assigned at that particular context level. Very few users have roles assigned at the system context, it is much more usual for roles to be assigned at a course level. This allows users to have different roles in different courses (a teacher on one course, might be enrolled as a student on another course).
If you want to get all the roles for a user, then you're going to need to do something like this:
$roleassignments = $DB->get_records('role_assignments', ['userid' => $user->id]);
You can then loop through all the $roleassignments and extract the 'roleid' from them (alternatively, you could use the $DB->get_fieldset command, to extract the roleids directly).
Note also that you should be using context_system::instance() instead of the old get_context_instance(CONTEXT_SYSTEM) (unless you are using a very old and insecure version of Moodle).
For getting the site admins, use get_admins() (or, if you really want to access the config value, use $CFG->siteadmins).
If you want to get a user role for a course by user id then this script will help you.
$context = context_course::instance($COURSE->id);
$roles = get_user_roles($context, $USER->id, true);
$role = key($roles);
$rolename = $roles[$role]->shortname;

Grails query to filter on association and only return matching entities

I have the following 1 - M (one way) relationship:
Customer (1) -> (M) Address
I am trying to filter the addresses for a specific customer that contain certain text e.g.
def results = Customer.withCriteria {
eq "id", 995L
addresses {
ilike 'description', '%text%'
}
}
The problem is that this returns the Customer and when I in turn access the "addresses" it gives me the full list of addresses rather than the filtered list of addresses.
It's not possible for me to use Address.withCriteria as I can't access the association table from the criteria query.
I'm hoping to avoid reverting to a raw SQL query as this would mean not being able to use a lot functionality that's in place to build up criteria queries in a flexible and reusable manner.
Would love to hear any thoughts ...
I believe the reason for the different behavior in 2.1 is documented here
Specifically this point:
The previous default of LEFT JOIN for criteria queries across associations is now INNER JOIN.
IIRC, Hibernate doesn't eagerly load associations when you use an inner join.
Looks like you can use createAlias to specify an outer join example here:
My experience with this particular issue is from experience with NHibernate, so I can't really shed more light on getting it working correctly than that. I'll happily delete this answer if it turns out to be incorrect.
Try this:
def results = Customer.createCriteria().listDistinct() {
eq('id', 995L)
addresses {
ilike('description', '%Z%')
}
}
This gives you the Customer object that has the correct id and any matching addresses, and only those addresses than match.
You could also use this query (slightly modified) to get all customers that have a matching address:
def results = Customer.createCriteria().listDistinct() {
addresses {
ilike('description', '%Z%')
}
}
results.each {c->
println "Customer " + c.name
c.addresses.each {address->
println "Address " + address.description
}
}
EDIT
Here are the domain classes and the way I added the addresses:
class Customer {
String name
static hasMany = [addresses: PostalAddress]
static constraints = {
}
}
class PostalAddress {
String description
static belongsTo = [customer: Customer]
static constraints = {
}
}
//added via Bootstrap for testing
def init = { servletContext ->
def custA = new Customer(name: 'A').save(failOnError: true)
def custB = new Customer(name: 'B').save(failOnError: true)
def custC = new Customer(name: 'C').save(failOnError: true)
def add1 = new PostalAddress(description: 'Z1', customer: custA).save(failOnError: true)
def add2 = new PostalAddress(description: 'Z2', customer: custA).save(failOnError: true)
def add3 = new PostalAddress(description: 'Z3', customer: custA).save(failOnError: true)
def add4 = new PostalAddress(description: 'W4', customer: custA).save(failOnError: true)
def add5 = new PostalAddress(description: 'W5', customer: custA).save(failOnError: true)
def add6 = new PostalAddress(description: 'W6', customer: custA).save(failOnError: true)
}
When I run this I get the following output:
Customer A
Address Z3
Address Z1
Address Z2