Laravel 5.5. - Property [xxxx] does not exist on this collection instance - laravel-5.5

I created two methods that make sql requests that i want to share to all views in my backoffice :
public function getEntities()
{
$vcs = Valuechain::select('valuechains.id', 'lang_valuechain.vcname', 'lang_valuechain.vcshortname')
->withCount('segments')
->join('sectors', 'valuechains.sector_id', '=', 'sectors.id')
->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
->where('langs.isMainlanguage', '=', '1')
->whereNull('valuechains.deleted_at')
->whereNull('sectors.deleted_at')
->get();
return $vcs;
}
public function getEntitiesWithKeyneeds()
{
$valuechains = Valuechain::orderBy('valuechains.id')
->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
->where('langs.isMainlanguage', '=', '1')
->with('segments')
->with('keyneeds')
->withCount('segments')
->withCount('keyneeds')
->get();
foreach ($valuechains as $valuechain) {
$ids[] = $valuechain->id;
}
foreach ($ids as $id) {
$vcskns[] = Segment::select(
'lang_valuechain.vcname', 'lang_valuechain.vcshortname',
'lang_segment.segname', 'lang_segment.segshortname', 'segments.id',
'lang_segment.created_at', 'lang_segment.updated_at', 'lang_segment.deleted_at'
)
->distinct()
->withCount('keyneeds')
->join('lang_segment', 'segments.id', '=', 'lang_segment.segment_id')
->join('valuechains', 'segments.valuechain_id', '=', 'valuechains.id')
->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
->join('sectors', 'valuechains.sector_id', '=', 'sectors.id')
->join('lang_sector', 'sectors.id', '=', 'lang_sector.sector_id')
->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
->where([
['langs.isMainlanguage', '=', '1'],
['valuechains.id', '=', $id]
])
->whereNull('valuechains.deleted_at')
->whereNull('sectors.deleted_at')
->whereNull('segments.deleted_at')
->get();
}
return $vcskns;
}
I call this method in another method which returns a view :
public function index(EntityInterface $vcs)
{
$entitiesLists = $vcs->getEntities();
$entitiesWithKnLists = $vcs->getEntitiesWithKeyneeds();
return view('admin.home', compact('entitiesLists', 'entitiesWithKnLists'));
}
I have a var_dump which returns for entitiesWithKnLists :
[
{
"vcname":"VC1",
"vcshortname":"VC1",
"segname":"S1",
"segshortname":"S1",
"id":1,
"created_at":"2018-06-07 09:18:31",
"updated_at":"2018-06-07 09:18:31",
"deleted_at":null,
"keyneeds_count":0
},
{
"vcname":"VC1",
"vcshortname":"VC1",
"segname":"S2",
"segshortname":"S2",
...
},
{
"vcname":"VC2",
"vcshortname":"VC2",
"segname":"S3",
"segshortname":"S3",
...
},
]
In my view vcname is repeated and i want to display it only once so I wrote in my view the following code :
#foreach($entitiesWithKnLists as $entitiesWithKnList)
{{ $entitiesWithKnList->first()->vcname }}<br>
#endforeach
It returns the correct values I expect.
When i want to display "segname" as we can see in the var_dump, I just write something similar :
#foreach($entitiesWithKnLists as $entitiesWithKnList)
{{ $entitiesWithKnList->segname }}
#endforeach
I obtain an error message :
Property [segname] does not exist on this collection instance.
Thanks

I finally solved the issue this way :
#foreach($entitiesWithKnLists as $entitiesWithKnList)
{{ $entitiesWithKnList->first()->vcname }}
#for ($i=0; $i< count($entitiesWithKnList); $i++ )
{{ $entitiesWithKnList[$i]->segname }}
#endfor
#endforeach

Related

If-Else condition not getting detected in Google Apps Script

I am looping over the list "res_1" and when the Id is "400" then need to multiply "Total_Weight" with variable "cost_400"; else if the id is "400W", then need to multiply "Total_Weight"
with variable "cost_400W". In the end, "result" array should contain "Vendor" and correspoding number ("Total_Weight" * "cost_400").
In the code below, I loop over "res_1", but for some reason, the if condition is not getting detected and it does not go inside the corresponding if or else if condition.
Any suggestions would be appreciated.
Expected result:
result = [['ABC',42341820 ],['DEF',91734000]]
Input:
res_1:
[ { Id: '400 ', Vendor: 'ABC', Total_Weight: 32322 },
{ Id: '400W ', Vendor: 'DEF', Total_Weight: 61156 } ]
var cost_400 = 1310
var cost_400W = 1500
res_1.forEach((r2,i2)=>{
if (r2['Id'] == "400" ) {
Logger.log(r2['Total_Weight']*cost_400)
}
else if (r2['Id'] == "400W" ) {
Logger.log(r2['Total_Weight']*cost_400W)
}
});
Issue:
Extra space on the res_1. if (r2['Id'] == "400" ) and if (r2['Id'] == "400W" ) will always get false because '400 ' is not equal to '400' and '400W ' is not equal to '400W'.
Solution:
If you cannot manipulate the output of res, you can use String.match() and reverse the if else statement. The reason for reversal is that String.match(400) can catch both 400 and 400W and if we start with String.match('400W') we can prevent the method from catching 400.
Your code should look like this:
function myFunction() {
var res_1=
[ { Id: '400 ', Vendor: 'ABC', Total_Weight: 32322 },
{ Id: '400W ', Vendor: 'DEF', Total_Weight: 61156 } ]
var cost_400 = 1310
var cost_400W = 1500
res_1.forEach((r2,i2)=>{
if (r2['Id'].match("400W")) {
Logger.log(r2['Total_Weight']*cost_400W)
}
else if (r2['Id'].match("400")) {
Logger.log(r2['Total_Weight']*cost_400)
}
});
}
Output:
Reference:
String.match()

Google Polymer: google-map-search doesn't work

<paper-dialog id="post" entry-animation="scale-up-animation" exit-animation="fade-out-animation">
<div class="find-area">
<paper-textarea on-input="find" id="find_textarea" class="find-place-text" label="Find your place" maxlength="250"></paper-textarea>
</div>
<div class="map-area">
<google-map id="[[map]]"
api-key="000000000myapi000000"
latitude="[[lat]]"
longitude="[[lon]]"
fit-to-markers>
</google-map>
<google-map-search id="google_search"
globalSearch="true"
map="[[map]]"
results="[[results]]">
</google-map-search>
</div>
<paper-button on-tap="[[upload]]">Accept</paper-button>
<label>coords:[[ results::lat ]], [[ results::lon ]]</label>
<label>query:[[ query ]]</label>
<label>map:[[ map ]]</label>
<label>results:[[results]]</label>
</paper-dialog>
<script>
function _showPosition(position) {
try {
x.latitude = position.coords.latitude;
x.longitude = position.coords.longitude;
}catch (err){
alert(err+'; position:'+position)
}
}
function showError(error) {
alert('error:'+ error)
}*/
function _submit(event) {
Polymer.dom(event).localTarget.parentElement.submit();
}
Polymer({
is: 'profile-new-post',
properties: {
enable : {
type: Boolean,
value: true
},
lat : {
value : 37.77493
},
lon : {
value : -122.41942
},
query : {
type : String,
value : ""
},
results : {
type : Array
},
map : {
type : Object
}
},
func : function (e) {
this.map = this.$.map;
post.open();
},
find : function (e) {
this.$.google_search.query = this.$.find_textarea.value;
this.query = this.$.google_search.query;
this.$.google_search.search();
this.lat = this.$.google_search.results.latitude;
this.lon = this.$.google_search.results.longitude;
//alert(this.$.google_search.results.latitude + '; ' + this.$.google_search.results.longitude)
},
I'm trying to use [[]] brackets because of django use {{}}. Map, results and coords are empty at output lables. It shows map with San Francisco but when i try to print text in input it doesn't want to search. The aren't any errors in console. I've saw tutorial video from google about this, but there was old version of Polymer and many things like {{ $.element.atribute }} inside element head doesn't work (it doesn't know what '$' is). Maybe someone can explain for me what's the biggest difference between [[ ]] and {{ }}, because i can't understand it from official tutorial?
Solve: to solve it, i must put source from inside dialog to new template with property is="dom-bind.
<p><paper-button raisedButton on-tap="upload">Upload</paper-button></p>
<paper-button id="dialogbutton" on-tap="func">Post</paper-button>
<paper-dialog id="post" entry-animation="scale-up-animation" exit-animation="fade-out-animation">
<template is="dom-bind">
<div class="find-area">
<paper-input value="{{ input_query }}" on-input="find" id="find_textarea" class="find-place-text" label="Find your place" maxlength="250"></paper-input>
</div>
<div class="map-area">
<google-map-search
id="google_search"
map="{{ map }}"
query="{{ input_query }}"
results="{{results}}"
on-google-map-search-results="searchingComplite">
</google-map-search>
<google-map
map="{{map}}"
latitude="{{results[0}.latitude}}"
longitude="{{results[0}.longitude}}">
</google-map>
</div>
<paper-button on-tap="upload">Accept</paper-button>
<label>coords:{{ lat }}, {{ lon }}</label>
<label>query:{{ query }}</label>
<label>map:{{ map }}</label>
<label>results:{{ results }}</label>
</template>
There are a couple of issues here:
Yes, the [[]] brackets are the problem here because they enforce one-way binding. That means that the results from the google-map-search can't propagate upwards and the labels are empty. You need to change the results=[[results]] to results={{results}} to enable two-way binding
For declerative event handlers, you don't need any brackets. So this line <paper-button on-tap="[[upload]]">Accept</paper-button> should be ?<paper-button on-tap="upload">Accept</paper-button>
To access sub-properties of an data bound object you need to use dot notation (.). This line <label>coords:[[ results::lat ]], [[ results::lon ]]</label> should be changed to <label>coords:[[ results.lat ]], [[ results.lon ]]</label>
I would also change lat and lon to computed properties which either return default values (alternatively just use attributes on your google-map element for that) or the values from your search result.

How change product name in admin orders prestashop

I have problem with old prestashop.
Wants to do to the name of the product is in the form of a list
attribute
br
attribute
br
...
<td><a href="index.php?tab=AdminCatalog&id_product='.$product['product_id'].'&updateproduct&token='.$tokenCatalog.'">
<span class="productName">'.$product['product_name'].'</span><br />
'.($product['product_reference'] ? $this->l('Ref:').' '.$product['product_reference'] : '')
.(($product['product_reference'] AND $product['product_supplier_reference']) ? ' / '.$product['product_supplier_reference'] : '')
.'</a></td>
Put this code at the top of your file :
$product_name = $product['product_name']
$pos = strpos($product_name, ' - ');
if($pos !== false) {
$product_name = substr_replace($product_name, '<br />', $pos, 3);
}
$product_name = str_replace(', ', '<br />', $product_name);
We replace the first ' - ' and each ', ' by a <br /> so each attributes are on a single line.
Then you can use $product_name instead of $product['product_name'] in your code :
<td><a href="index.php?tab=AdminCatalog&id_product='.$product['product_id'].'&updateproduct&token='.$tokenCatalog.'">
<span class="productName">'.$product_name.'</span><br />
'.($product['product_reference'] ? $this->l('Ref:').' '.$product['product_reference'] : '')
.(($product['product_reference'] AND $product['product_supplier_reference']) ? ' / '.$product['product_supplier_reference'] : '')
.'</a></td>

Django form wont submit because of autocomplete widget field

I want to fill a text input in my form using an autocomplete widget that I have created using jquery ui. Everything works exactly how I want to, except when the form is submitted.
The problem is that when I submit the form, the text input is automatically reseted (I don't know why) and after that, the page reloads saying that the field is required (just validation working how it's supposed to). Of course, if it didn't reset the field everything would go fine.
I dont know if my select event of the autocomplete is working fine, here is the code:
select : function (e, ui) {
// I create a new attribute to store de database primary key of this option. This is
// usefull later on.
$('#%(input_id)s').attr('itemid', ui.item.real_value);
// I set the input text value's.
$('#%(input_id)s').val(ui.item.label);
}
Here is the full code of the autocomplete:
class AutocompleteTextInputWidget (forms.TextInput):
def media(self):
js = ("/js/autocomplete.js", "pepe.js")
def __init__(self, source, options={}, attrs={}):
self.options = None
self.attrs = {'autocomplete': 'off'}
self.source = source
self.minLength = 1
self.delay = 0
if len(options) > 0:
self.options = JSONEncoder().encode(options)
self.attrs.update(attrs)
def render(self, name, value=None, attrs=None):
final_attrs = self.build_attrs(attrs)
options = ''
if value:
final_attrs['value'] = escape(value)
if isinstance(self.source, list) or isinstance(self.source, tuple):
# Crea un Json con las opciones.
source = '['
for i in range(0, len(self.source)):
if i > 0:
source += ', '
source += '"' + self.source[i] + '"'
source += ']'
options = u'''
delay : %(delay)d,
minLength : %(minlength)s,
source : %(source)s
''' % {
'delay' : self.delay,
'minlength' : self.minLength,
'source' : source
}
elif isinstance(self.source, str):
options = u'''
delay : %(delay)d,
minLength : %(minlength)s,
source : function (request, response) {
if ($(this).data('xhr')) {
$(this).data('xhr').abort();
}
$(this).data('xhr', $.ajax({
url : "%(source_url)s",
dataType : "json",
data : {term : request.term},
beforeSend : function(xhr, settings) {
$('#%(input_id)s').removeAttr('itemid');
},
success : function(data) {
if (data != 'CACHE_MISS') {
response($.map(data, function(item) {
return {
label : item[1],
value: item[1],
real_value : item[0]
};
}));
}
},
}))
},
select : function (e, ui) {
$('#%(input_id)s').attr('itemid', ui.item.real_value);
$('#%(input_id)s').val(ui.item.label);
}
''' % {
'delay' : self.delay,
'minlength' : self.delay,
'source_url' : self.source,
'input_id' : final_attrs['id'],
}
if not self.attrs.has_key('id'):
final_attrs['id'] = 'id_%s' % name
return mark_safe(u'''
<input type="text" %(attrs)s/>
<script type="text/javascript">
$("#%(input_id)s").autocomplete({
%(options)s
});
</script>
''' % {
'attrs' : flatatt(final_attrs),
'options' : options,
'input_id' : final_attrs['id']
})
Tip: If I write some text without selecting it from the autocomplete, it still fails.
Another tip: If I set the field as optional it arrives to the view empty.
What should I do to make this work when I submit the form??? I have spent hours trying to
make this work. How can I make the form to recognise that I have allready filled that field?
Here is the code of the form:
test = forms.CharField(label = "autotest", widget = AutocompleteTextInputWidget('/myjsonservice'))
This is the rendered html:
<input type="text" autocomplete="off" id="id_test"/>
<script type="text/javascript">
$("#id_test").autocomplete({
delay : 0,
minLength : 0,
source : function (request, response) {
if ($(this).data('xhr')) {
$(this).data('xhr').abort();
}
$(this).data('xhr', $.ajax({
url : "/myjsonservice",
dataType : "json",
data : {term : request.term},
beforeSend : function(xhr, settings) {
$('#id_test').removeAttr('itemid');
},
success : function(data) {
if (data != 'CACHE_MISS') {
response($.map(data, function(item) {
return {
label : item[1],
value: item[1],
real_value : item[0]
};
}));
}
},
}))
},
select : function (e, ui) {
$('#id_test').attr('itemid', ui.item.real_value);
$('#id_test').val(ui.item.label);
}
});
</script>
Finally found the answer, the problem was that the "name" attribute wasn't rendered. Hence, the field could't get to the view as part of the request.
The final code of the autocomplete widget ended up like this:
class AutocompleteTextInputWidget (forms.TextInput):
def media(self):
js = ("/js/autocomplete.js", "pepe.js")
def __init__(self, source, options={}, attrs={}):
self.options = None
self.attrs = {'autocomplete': 'off'}
self.source = source
self.minLength = 1
self.delay = 0
if len(options) > 0:
self.options = JSONEncoder().encode(options)
self.attrs.update(attrs)
def render(self, name, value=None, attrs=None):
final_attrs = self.build_attrs(attrs)
options = ''
if value:
final_attrs['value'] = escape(value)
if isinstance(self.source, list) or isinstance(self.source, tuple):
# Crea un Json con las opciones.
source = '['
for i in range(0, len(self.source)):
if i > 0:
source += ', '
source += '"' + self.source[i] + '"'
source += ']'
options = u'''
delay : %(delay)d,
minLength : %(minlength)s,
source : %(source)s
''' % {
'delay' : self.delay,
'minlength' : self.minLength,
'source' : source
}
elif isinstance(self.source, str):
options = u'''
delay : %(delay)d,
minLength : %(minlength)s,
source : function (request, response) {
if ($(this).data('xhr')) {
$(this).data('xhr').abort();
}
$(this).data('xhr', $.ajax({
url : "%(source_url)s",
dataType : "json",
data : {term : request.term},
beforeSend : function(xhr, settings) {
$('#%(input_id)s').removeAttr('itemid');
},
success : function(data) {
if (data != 'CACHE_MISS') {
response($.map(data, function(item) {
return {
label : item[1],
value: item[1],
real_value : item[0]
};
}));
}
},
}))
},
select : function (e, ui) {
$('#%(input_id)s').attr('itemid', ui.item.real_value);
$('#%(input_id)s').val(ui.item.label);
}
''' % {
'delay' : self.delay,
'minlength' : self.delay,
'source_url' : self.source,
'input_id' : final_attrs['id'],
}
if not self.attrs.has_key('id'):
final_attrs['id'] = 'id_%s' % name
return mark_safe(u'''
<input type="text" name="%(name)s" %(attrs)s/>
<script type="text/javascript">
$("#%(input_id)s").autocomplete({
%(options)s
});
</script>
''' % {
'attrs' : flatatt(final_attrs),
'options' : options,
'input_id' : final_attrs['id'],
'name' : name
})
If someone knows how to improve this messy code it would be nice.
If someone knows about a nice widget documentation for django 1.4 (Other than the oficial, which sucks by the way) it would be nice too.
Bye, good coding everyone!!!

adding dropdown to joomla registration

I am want to add a dropdown to joomla 2.5 registration.I believe I can use sql form field type but I want that sql to return all schools of a particular city ( which is in registration form) .So question is how a sql query will accept a parameter?
You have to create one field type in the models==>fields.
for ex: create a php file as schools.php, and then include the following code.
==> schools.php(filename)
defined('JPATH_BASE') or die;
class JFormFieldSchools extends JFormField
{
protected $type = 'Schools';
protected function getInput()
{
// Initialize variables.
$html = array();
$attr = '';
// Initialize some field attributes.
$attr .= $this->element['class'] ? ' class="'.(string) $this->element['class'].'"' : '';
$attr .= ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : '';
$attr .= $this->element['size'] ? ' size="'.(int) $this->element['size'].'"' : '';
// Initialize JavaScript field attributes.
$attr .= $this->element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : '';
// Get some field values from the form.
$contactId = (int) $this->form->getValue('id');
$categoryId = (int) $this->form->getValue('catid');
// Build the query for the ordering list.
$query = 'SELECT ordering AS value, name AS text' .
' FROM #__contact_details' .
' WHERE catid = ' . (int) $categoryId .
' ORDER BY ordering';
// Create a read-only list (no name) with a hidden input to store the value.
if ((string) $this->element['readonly'] == 'true') {
$html[] = JHtml::_('list.ordering', '', $query, trim($attr), $this->value, $contactId ? 0 : 1);
$html[] = '<input type="hidden" name="'.$this->name.'" value="'.$this->value.'"/>';
}
// Create a regular list.
else {
$html[] = JHtml::_('list.ordering', $this->name, $query, trim($attr), $this->value, $contactId ? 0 : 1);
}
return implode($html);
}
}
Then you have to change the mysql query as your needs.
If have to change on the default joomla registration page then have following path(.../com_users/models/forms/registration.xml ).
<field name="xxxxx" type="Schools"
description="COM_USERS_REGISTER_NAME_DESC"
filter="string"
label="COM_USERS_REGISTER_NAME_LABEL"
message="COM_USERS_REGISTER_NAME_MESSAGE"
required="true"
size="30" />