"When" not getting validated in fluent Validation, why my second "When" condition is always true ..? - fluent

When(opt => opt.submitOrderRequest.requestHeader.operation.ToString() == "NewActivation" || opt.submitOrderRequest.requestHeader.operation.ToString() == "HardwareUpgrade", () =>
{
RuleForEach(x => x.submitOrderRequest.requestBody.device).Cascade(CascadeMode.StopOnFirstFailure).ChildRules(device =>
{ ...stuff RuleFor
When(opt => opt.submitOrderRequest.requestHeader.operation.ToString() ==
"HardwareUpgrade" &&
opt.submitOrderRequest.requestHeader.operation.ToString() != "NewActivation", () =>
{
}
}
}

Related

Creating a slider by two input type="range" in reactjs

I have a JSON file called by a fetch() request. I have two input of type="range" .I want to merge the two.
Something like this.
I'd like to make the double slider , however if I position two elements on top of one another, only the top one is accepting mouse clicks. I do not wish to use any external library in React for the slider or the space between the two handlers, which is colourised.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
library: null,
librarySecond: null,
perPage: 20,
currentPage: 1,
maxPage: null,
filterTotalF: "",
filterTotalS: "",
rangevalTotalF: "",
rangevalTotalS: ""
};
}
componentDidMount() {
fetch("/json,bc", {
method: "get"
})
.then(response => response.text())
.then(text => {
let Maindata = JSON.parse(text.replace(/\'/g, '"'));
this.setState(
state => ({
...state,
data: Maindata
}),
() => {
this.reorganiseLibrary();
}
);
})
.catch(error => console.error(error));
}
reorganiseLibrary = () => {
const { filterTotalF, filterTotalS, perPage, data } = this.state;
let library = data;
let librarySecond = data;
librarySecond = _.chunk(librarySecond, perPage);
this.setState({
librarySecond,
currentPage: 1,
maxPage: librarySecond.length === 0 ? 1 : librarySecond.length
});
let defaultFilterF = null;
defaultFilterF = filterTotalF
? filterTotalF
: this.renderMinFilter(librarySecond);
let defaultFilterS = null;
defaultFilterS = filterTotalS
? filterTotalS
: this.renderMaxFilter(librarySecond);
if (defaultFilterF !== "" && defaultFilterS !== "") {
library = library.filter(
item =>
item.totalCom >= defaultFilterF && item.totalCom <= defaultFilterS
);
}
if (filterExitTimeDepF !== "" && filterExitTimeDepS !== "") {
library = library.filter(
item =>
this.rendershowexittimeDep(
item.info.departureinformation.ticketinfooo.exitinfo.showexittime
) >= filterExitTimeDepF &&
this.rendershowexittimeDep(
item.info.departureinformation.ticketinfooo.exitinfo.showexittime
) <= filterExitTimeDepS
);
}
if (filterExitTimeDesF !== "" && filterExitTimeDesS !== "") {
library = library.filter(
item =>
this.rendershowexittimeDes(
item.info.returninformation.ticketinfooo.exitinfo.showexittime
) >= filterExitTimeDesF &&
this.rendershowexittimeDes(
item.info.returninformation.ticketinfooo.exitinfo.showexittime
) <= filterExitTimeDesS
);
}
library = _.chunk(library, perPage);
this.setState({
library,
currentPage: 1,
maxPage: library.length === 0 ? 1 : library.length
});
};
renderMinFilter = librarySecond => {
return librarySecond.reduce((acc, lib) => {
const libMin = Math.min(...lib.map(item => item.totalCom));
return acc === undefined ? libMin : libMin < acc ? libMin : acc;
}, undefined);
};
renderMaxFilter = librarySecond => {
return librarySecond.reduce((acc, lib) => {
const libMax = Math.max(...lib.map(item => item.totalCom));
return libMax > acc ? libMax : acc;
}, 0);
};
// Previous Page
previousPage = event => {
this.handleClick(event);
this.setState({
currentPage: this.state.currentPage - 1
});
};
// Next Page
nextPage = event => {
this.handleClick(event);
this.setState({
currentPage: this.state.currentPage + 1
});
};
// handle filter
handleFilterTotal = evt => {
let value = evt.target.value;
let key = evt.target.getAttribute("data-key");
if (key == "1") {
this.setState(
{
filterTotalF: evt.target.value,
rangevalTotalF: evt.target.value
},
() => {
this.reorganiseLibrary();
}
);
} else if (key == "2") {
this.setState(
{
filterTotalS: evt.target.value,
rangevalTotalS: evt.target.value
},
() => {
this.reorganiseLibrary();
}
);
}
};
// handle per page
handlePerPage = evt =>
this.setState(
{
perPage: evt.target.value
},
() => this.reorganiseLibrary()
);
// handle render of library
renderLibrary = () => {
const { library, currentPage } = this.state;
if (!library || (library && library.length === 0)) {
return (
<div className="nodata">
<div className="tltnodata">برای جستجوی شما نتیجه ای یافت نشد!</div>
<div className="textnodata">
شما می توانید با انجام مجدد عملیات جستجو,نتیجه مورد نظر خود را
بیابید
</div>
</div>
);
}
return library[currentPage - 1]
.sort((a, b) => a.total - b.total)
.map((item, i) => (
<div className="item">
<span>{item.id}</span>
</div>
));
};
renderMinTotal = () => {
const { librarySecond } = this.state;
if (!librarySecond || (librarySecond && librarySecond.length === 0)) {
return "";
}
return librarySecond.reduce((acc, lib) => {
const libMin = Math.min(...lib.map(item => item.totalCom));
return acc === undefined ? libMin : libMin < acc ? libMin : acc;
}, undefined);
};
renderMaxTotal = () => {
const { librarySecond } = this.state;
if (!librarySecond || (librarySecond && librarySecond.length === 0)) {
return "";
}
return librarySecond.reduce((acc, lib) => {
const libMax = Math.max(...lib.map(item => item.totalCom));
return libMax > acc ? libMax : acc;
}, 0);
};
render() {
const {
library,
currentPage,
perPage,
maxPage,
rangevalTotalF,
rangevalTotalS,
librarySecond
} = this.state;
let defaultRangeF = null;
defaultRangeF = rangevalTotalF ? (
<span>{rangevalTotalF}</span>
) : (
<span>{this.renderMinTotal()}</span>
);
let defaultRangeS = null;
defaultRangeS = rangevalTotalS ? (
<span>{rangevalTotalS}</span>
) : (
<span>{this.renderMaxTotal()}</span>
);
return (
<div>
<div className="filter-box">
<div className="wrapper">
<input
type="range"
min={this.renderMinTotal()}
max={this.renderMaxTotal()}
defaultValue={this.renderMaxTotal()}
step="1000"
onChange={this.handleFilterTotal}
data-key="2"
className="exitTimeSecond"
/>
<div className="rangevalSecond">{defaultRangeS}</div>
</div>
<div className="wrapper">
<input
type="range"
min={this.renderMinTotal()}
max={this.renderMaxTotal()}
defaultValue={this.renderMinTotal()}
step="1000"
onChange={this.handleFilterTotal}
data-key="1"
className="exitTimeFirst"
/>
<div className="rangevalFirst">{defaultRangeF}</div>
</div>
</div>
{this.renderLibrary()}
<ul id="page-numbers">
<li className="nexprevPage">
{currentPage !== 1 && (
<button onClick={this.previousPage}>
<span className="fa-backward" />
</button>
)}
</li>
<li className="controlsPage active">{this.state.currentPage}</li>
<li className="restControls">...</li>
<li className="controlsPage">{this.state.maxPage}</li>
<li className="nexprevPage">
{currentPage < maxPage && (
<button onClick={this.nextPage}>
<span className="fa-forward" />
</button>
)}
</li>
</ul>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("Result"));

Yii2 : Setting Access Control matchcallback

I just want to know if I can do this so I dont have to repeat the same code over and over
[
'allow' => true,
'actions' => ['index', 'update', 'view', 'logout'],
'roles' => ['#'],
'matchCallback' => function(){
return (Yii::$app->user->identity->team_id == '47' && Yii::$app->user->identity->team_id == '62'
&& Yii::$app->user->identity->team_id == '63' && Yii::$app->user->identity->team_id == '64'
&& Yii::$app->user->identity->team_id == '65' && Yii::$app->user->identity->team_id == '66' && Yii::$app->user->identity->role_id == '1');
}
],
Or something similar to that.
Thank you
First, I don't understand why you are using && instead of ||. Is it a typo?
Now for answering the question, I think it will be better for example to create a function for that purpose in the Model representing your identity like below: (I am sure you will need it later somewhere else)
public function belongsToGroup()
{
if( $this->team_id == '47'
|| $this->team_id == '62'
...
&& $this->role_id == '1' ){
return true;
} else {
return false;
}
}
And then just call your function in the authorisation control:
[
'allow' => true,
'actions' => ['index', 'update', 'view', 'logout'],
'roles' => ['#'],
'matchCallback' => function($rule, $action){
return Yii::$app->user->identity->belongsToGroup();
}
],

Filter a gridview column that is processed by a function in yii2

I have a column named wp_status. If person A, person B, person C, person D approves a work, the value of column wp_status will be changed to Approved, else the value will be as it is in the database - Assigned.
The code to change the value dynamically in the gridview is -
[
'label' => 'Status',
'attribute'=>'wp_status',
'value' => function ($model) {
return $model->Status();
}
],
And the function Status in model Workpermit is -
public function Status()
{
//$data = Workpermit::findOne($this->id);
$total = $this->wp_status;
if($this->wp_type == 'Safe Work Permit' && $this->wp_apoapproval == 'Approved' && $this->wp_spsapproval == 'Approved' && $this->wp_officerapproval == 'Approved'){
$total = 'Approved';
}
return $total;
}
This works fine so far. But I'm not sure how to filter it with Kartik Select2 widget. I tried like following -
[
'label' => 'Status',
'attribute'=>'wp_status',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Workpermit::Status()->asArray()->all(), 'total', 'total'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Permit Status'],
'value' => function ($model) {
return $model->Status();
}
],
And here I'm getting error - Using $this when not in object context
could be uisng a getter
public function getStatus()
{
//$data = Workpermit::findOne($this->id);
$total = $this->wp_status;
if($this->wp_type == 'Safe Work Permit' && $this->wp_apoapproval == 'Approved' && $this->wp_spsapproval == 'Approved' && $this->wp_officerapproval == 'Approved'){
$total = 'Approved';
}
return $total;
}
the call $model->status (status lowercase)
[
'label' => 'Status',
'attribute'=>'wp_status',
'value' => function ($model) {
return $model->status;
}
],

Yii2 When Validation

Out of two pairs of input fields I only need one or the other. I can't get the validation right.
listing_image_url and poster_image_url should only be required if $model->listingImage is null.
Also tried using strlen($model->listingImage) == 0.
[['listing_image_url', 'poster_image_url'], 'required',
'when' => function($model){
var_dump($model->listingImage); //result is empty string '0'
return $model->listingImage == NULL && $model->posterImage == NULL;
},'whenClient' => "function(attribute, value) {
return $('#vod-listingimage').val() == '' && $('#vod-posterimage').val() == '';
}", 'message' => 'look'
],
Just as above but the other way around.
[['listingImage', 'posterImage'], 'required',
'when' => function($model) {
return $model->listing_image_url == NULL && $model->poster_image_url == NULL;
},
'whenClient' => "function(attribute, value) {
return $('#vod-listing_image_url').val() == '' && $('#vod-poster_image_url').val() == '';
}", 'message' => 'hi'
],
You could create your own inline validator for the model validation on backend side, like this:
[['listingImage', 'posterImage'], function($attribute, $params) {
if ($this->listingImage === null && empty($this->$attribute)) {
$this->addError($attribute, 'Can not be blank if listingImage is null');
}
}]
In order to also provide the client side validation you can build a custom standalone validator.
I tried myself something similar and the behavior is odd indeed.
But you can create a validator that checks if only one of the two fields is selected.
public function validateListingAgainstPoster($attribute, $params)
{
if (!empty($this->listing_image_url) && !empty($this->poster_image_url)) {
$this->addError($attribute, 'Only one of "Listing" or "Poster" fields can be selected.');
}
if (empty($this->listing_image_url) && empty($this->poster_image_url)) {
$this->addError($attribute, 'Please select one of "Listing" or "Poster Group".');
}
}
And in your rules:
[['listing_image_url', 'poster_image_url'], 'validateListingAgainstPoster', 'skipOnEmpty' => false, 'skipOnError' => false],

refactoring of simple code in Yii2 (if-else)

i was doing some refactoring of code on project in Yii2 framework.
I'm just asking if this can be written nicer, with less repetition (i try to follow DRY whenever i can). Any literature recommendation about this kind of topic is more than welcome, sorry for bad English.
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
if (isset($exception->statusCode)) {
if ($exception->statusCode == 500) {
return $this->render('error-500', ['exception' => $exception]);
} elseif ($exception->statusCode == 404) {
return $this->render('error-404', ['exception' => $exception]);
} else {
return $this->render('error', ['exception' => $exception]);
}
} elseif (isset($exception->code)) {
if ($exception->code == 500) {
return $this->render('error-500', ['exception' => $exception]);
} elseif ($exception->code == 404) {
return $this->render('error-404', ['exception' => $exception]);
} else {
return $this->render('error', ['exception' => $exception]);
}
}
} else {
$exception = new \yii\web\HttpException(500);
return $this->render('error-500', ['exception' => $exception]);
}
You can do so if you like
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
if (isset($exception->statusCode){
return $this-render('error-' . $exception->statusCode , ['exception' => $exception] );
} else if (isset($exception->code)) {
return $this-render('error-' . $exception->code , ['exception' => $exception] )
} else {
$exception = new \yii\web\HttpException(500);
return $this->render('error-500', ['exception' => $exception]);
}
}
or so if like more compact
if ($exception !== null) {
if (isset($exception->statusCode, $exception->code){
return $this-render('error-' . ($exception->statusCode) ? $exception->statusCode : $exception->code , ['exception' => $exception] );
} else {
$exception = new \yii\web\HttpException(500);
return $this->render('error-500', ['exception' => $exception]);
}
}
Another possible way
if ($exception !== null) {
$exceptionCode = isset($exception->statusCode)?$exception->statusCode:
( isset($exception->code)?$exception->code:null );
if($exceptionCode){
$viewFile = ($exceptionCode == 500)?'error-500':
( ($exceptionCode == 404)?'error-404':'error');
return $this->render($viewFile, ['exception' => $exception]);
} else {
// you need to something here
}
}