Laravel:
ErrorException in Model.php line 2336: in_array() expects parameter 2
to be array, string given
class Student extends Model
{
protected $guarded = 'student_id';
//protected $fillable = ['full_name', 'current_grade','branch'];
}
should I use fillable ? because when I use guarded alone its throwing this error
You need to pass in an array even when you only have one item in guarded.
protected $guarded = ['student_id'];
Related
How can I exclude the child domain property when I use the grailsWebDataBinder?
For example, I have domains:
class Car {
String carPropertyToExclude
Set<Detail> details
static hasMany = [details: Detail]
}
class Detail {
String detailPropertyToExclude
static belongsTo= [car: Car]
}
I want to exclude the detailPropertyToExclude from Detail when I call the bind method of grailsWebDataBinder and give the car instance as a parameter
Code:
List blackList = ["carPropertyToExclude"]
grailsWebDataBinder.bind(car, new SimpleMapDataBindingSource(params), null, blackList)
Note:
Don't suggest the bindable: false or variants when excluded from anywhere. Only need to know is there a way to do it by providing blackList as bind() method parameter.
These variants also not working:
List blackList = ["carPropertyToExclude", "details.detailPropertyToExclude"]
List blackList = ["carPropertyToExclude", [Detail.class : "detailPropertyToExclude"]]
The main question is how to prepare the blackList to exclude also child's property?
blacklist parameter supports only direct object properties
you can use DataBindingListener
import grails.databinding.events.DataBindingListenerAdapter
class BlackListener extends DataBindingListenerAdapter{
List<String> list
//returns false if you want to exclude property from binding
public Boolean beforeBinding(Object obj, String propertyName, Object value, Object errors) {
return !list.contains("${obj?.class.name}.${propertyName}".toString())
}
}
...
List blackList = ["Car.carPropertyToExclude", "Details.detailPropertyToExclude"]
grailsWebDataBinder.bind(car, new SimpleMapDataBindingSource(params),
new BlackListener(list:blackList) )
UPD:
Unfortunately the method above does not work with Collection binding.
The problem that SimpleDataBinder.setPropertyValue(...) method loses listener when processing a list.
Not sure if following workaround is good (potentially context initialization required)
but it's possible to register converter for each black list:
import grails.databinding.SimpleDataBinder
import grails.databinding.SimpleMapDataBindingSource
import grails.databinding.converters.ValueConverter
SimpleDataBinder setBlackList(SimpleDataBinder binder, Map<Class,List<String>> blackLists) {
blackLists.each { Class clazz, List<String> blackList ->
def vc = new ValueConverter(){
boolean canConvert(Object value){
return value instanceof Map
}
Object convert(Object value){
def obj = clazz.newInstance()
binder.bind( obj, new SimpleMapDataBindingSource(value), [], blackList )
return obj
}
Class<?> getTargetType(){ clazz }
}
binder.registerConverter(vc)
}
return binder
}
...
Map blackLists = [
(Car.class) : ["carPropertyToExclude"],
(Detail.class) : ["detailPropertyToExclude"]
]
setBlackList(grailsWebDataBinder,blackLists)
...
grailsWebDataBinder.bind(car, new SimpleMapDataBindingSource(params), null,
blackLists[car.getClass()] )
PS: as alternative possible to set grailsWebDataBinder.conversionService...
In a controller you can exclude props from binding by:
def someAction(){
Car car = new Car()
bindData car, params, [exclude: ['carPropertyToExclude', 'details']]
car.details = params.list('details').collect{
bindData new Detail(), [exclude: ['detailPropertyToExclude']]
}
}
You might also want to use the command-objects to represent your form-data.
I have found one solution based on daggett answer. Maybe in greater versions, the bug is fixed or will be fixed. The bug is that when we give the listener as a parameter of bind method for child domains the listener isn't triggered but when we set it as class level listener works. Grails version 3.2.11.
I have created the BlackListener like this:
public class BlackListListener extends DataBindingListenerAdapter {
private final Map<Class<?>, Collection<String>> blackList;
public BlackListListener(Map<Class<?>, Collection<String>> blackList) {
this.blackList = blackList;
}
public Boolean beforeBinding(Object obj, String propertyName, Object value, Object errors) {
Boolean result = Boolean.TRUE;
Collection<String> list = blackList.get(obj.getClass());
if (CollectionUtils.isNotEmpty(list)) {
result = !list.contains(propertyName);
}
return result;
}
}
Then I make my own grailsWebDatabinder bean as prototype:
<bean id="webDataBinder" class="grails.web.databinding.GrailsWebDataBinder" c:_0-ref="grailsApplication"
scope="prototype"/>
<bean id="carBinder" class="CarDataBinder" c:_0-ref="webDataBinder"/>
and then when I want to use data binder I inject the webDataBinder and init listener:
public CarDataBinder(GrailsWebDataBinder grailsWebDataBinder) {
this.grailsWebDataBinder = grailsWebDataBinder;
DataBindingListener blackListListener = new BlackListListener(
ImmutableMap.of(
Car.class, ImmutableSet.of("carPropertyToExclude"),
Detail.class, ImmutableSet.of("detailPropertyToExclude")
)
);
grailsWebDataBinder.setDataBindingListeners(blackListListener);
}
and then:
void bindData(Car car, Map<?, ?> params) {
grailsWebDataBinder.bind(car, new SimpleMapDataBindingSource(params));
}
If there are better ways you can post.
I have the following models:
class User {
public function recruiter()
{
return $this->hasOne('App\Recruiter');
}
}
class Recruiter extends Model {
public function jobs()
{
return $this->hasMany('App\Job');
}
}
class Job extends Model {
protected $fillable = [
'job_type_id',
'recruiter_id',
'start_at',
'end_at',
'job_title',
'job_ref',
'job_desc'
];
// other stuff
}
When I call the following create method the fillable properties on the Job model work as expected.
$job = Auth::user()->recruiter->jobs()->create($request->all());
When I call the update method the fillable properties are ignored and end up with mass assignment vulnerability.
Auth::user()->recruiter->jobs()->update($request->all());
Why is this happening?
It's because you need to pass the id of the job as well (Laravel dosen't know what to update). So added to the fillable array.
class Job extends Model {
protected $fillable = [
'id',
'job_type_id',
'recruiter_id',
'start_at',
'end_at',
'job_title',
'job_ref',
'job_desc'
];
// other stuff
}
It seems like there is a weird bug. With this, still in Laravel 5.7.
You need to do this, for it to respect $fillable:
$jobs = Auth::user()->recruiter->jobs();
$jobs->update($request->all());
Don't ask me why, but if you try:
(Auth::user()->recruiter->jobs())->update($request->all());
It just ignores $fillable.
In my grails project, I've used the method Object.findAllByIdInList(), passing a list as parameter.
The code used is the following:
def allSelectedIds = ReceiptItem.findAllByIdInList(par)
In which the ReceiptItem is a domain class defined as follows:
class Receipt {
double totalAmount;
Date releaseDate;
int vatPercentage;
int discount;
Boolean isPayed;
Boolean isInvoice;
static belongsTo = [patient:Patient]
static hasMany = [receiptItems:ReceiptItem]
static constraints = {
receiptItems(blank: false)
patient(blank: false)
totalAmount(blank: false)
vatPercentage(blank: false, nullable: false)
}
}
and par is the list of ids defined as follows:
def par = params.list("receiptItemsSelected")
receiptItemsSelected is defined in the gsp page into the remoteFunction() as follows:
params: '\'receiptItemsSelected=\' + jQuery(this).val()'
The problem is that the line above throws the following exception:
java.lang.String cannot be cast to java.lang.Long. Stacktrace follows:
Message: java.lang.String cannot be cast to java.lang.Long
I don't understand why it is throwing this exception.
Thanks for your help
Probably list par has ids as String. Generally id for domain objects is stored as Long. Try this instead
ReceiptItem.findAllByIdInList(par*.toLong())
*Also make sure that id represented as string isNumber().
assert !'C'.isNumber()
assert '4'.isNumber()
Why no constant strings in T4MVC generated code? My guess would be compilation-time copying of constant values...
But adding constants to the generated code would allow T4MVC generated stuff to be used in attributes.
I think about something like this:
insert #line 400:
public const String ControllerNameCONST = #"<#=controller.ClassName #>";
insert #line 445:
[<#= GeneratedCode #>, DebuggerNonUserCode]
public static class ActionNamesCONST {
<#foreach (var method in controller.ActionMethodsWithUniqueNames) { #>
<# if (UseLowercaseRoutes) { #>
public const string <#=method.ActionName #> = (<#=method.ActionNameValueExpression #>).ToLowerInvariant();
<# } else { #>
public const string <#=method.ActionName #> = <#=method.ActionNameValueExpression #>;
<# }
} #>
}
So someone could use it like this:
[SomeAttribute(HomeController.ControllerNameCONST)]
//instead of
[SomeAttribute("Home")]
//or
[SomeAttribute(HomeController.ActionNamesCONST.SomeAction)]
//instead of
[SomeAttribute("SomeAction")]
Edit: used it as an autocomplete attribute on a model, so the "target" controller and action can be specified on the model. Although could rework the autocomplete attribute to take an ActionResult as parameter instead of controller+action names...
Update (12/7/2011): this issue is now fixed (in 2.6.65). See http://mvccontrib.codeplex.com/workitem/7177.
T4MVC does generate many constants. e.g.
For the controller name: MVC.Home.Name
For the action names: MVC.Home.ActionNames.About
For the view names: MVC.Home.Views.About
Here is the domain class I have defined:
package mypackage
public enum UFModeType {
I(0),
O(1),
R(3)
Integer mode
public UserFileModeType(Integer mode) {
this.mode = mode;
}
static list() {
[I, O, R]
}
}
This is a property of another domain Parent where it is as follows:
package mypackage
class Parent {
String name
... ... ...
UFModeType uFMode
static mapping = {
table 'parent_table_with_ufMode_col_as_number'
version false
tablePerHierarchy false
id generator:'sequence', params:[sequence:'myseq']
columns {
id column:'parentid'
uFMode column: 'UFMODE'
}
}
static constraints = {
userFileMode(nullable: true)
}
}
The gsp call for this looks like this:
g:select name="uFMode" from="${mypackage.UFModeType?.list()}" value="${parentInstance?.uFMode?.name()}" /
I have tried a lot of variants of the above in the gsp call but I am getting error that the db insert fails saying the entry of ufmode is invalid number, thus this is not being passed as a number. I printed the params in the controllers save and it shows this:
Params in save=[uFMode:I ...
I am sure I may be missing some minor thing in syntax, but I have tried a lot of things without much success, so any inputs will be greatly appreciated.
Thanks!
Try changing
value="${parentInstance?.uFMode?.name()}
to
value="${parentInstance?.uFMode?.mode()}
From the definition of UFModeType you give you do not have a name attribute.