Object of class could not be converted to string of class CI_DB_mysqli_result - arrays

Controller :
function index()
{
$this->load->helper(array('form', 'url','common'));
$this->load->library(array('session','pagination'));
$this->load->model('productsdisplay','',TRUE);
$data=array(
'header' => $this->load->view('frontend/assets/header', '', TRUE),
'footer' => $this->load->view('frontend/assets/footer', '', TRUE),
);
$item= $this->input->get('products', TRUE);
$newarray[]=array();
$item_id =$this->db->query('select id from item where slug=(".$item.")');
$result=$item_id->result();
var_dump($result);
$data['category']=$this->productsdisplay->getAllCategories($item_id);
$data['kvas']=$this->productsdisplay->getAllKva();
$data['items']=$this->productsdisplay->getAllItems();
$data['applications']=$this->productsdisplay->getAllApplication();
$data['products'] = $this->productsdisplay->getAllProduct();
$data['ads'] = $this->productsdisplay->getAllAds();
$insert_id=$this->productsdisplay->addEnquiry($this->input->post());
$this->load->view('frontend/product/index',$data);
}
Model :
function getAllCategories($item_id)
{
if($item_id!=''){
$this->db->select('category_name');
$this->db->order_by("category_name", "ASC");
$query = $this->db->where('product_type',$item_id);
$query = $this->db->get('category');
return $query->result();
}
}
I am not able to understand how to solve this error. Please help me regarding the issue.
I am a beginner in CI.

The query which gets $item_id is wrong. It should be changed as follows
$item_id =$this->db->query('select id from item where slug='.$item);

Related

How to insert into a table based on an Eloquent relationship an array of foreign keys

I have two models TeamMember and ProjectRequest.
A TeamMember can have one ProjectRequest, that is why I created the following Eloquent relationship on TeamMember:
class TeamMember extends Model {
//
protected $table = 'team_members';
protected $fillable = ['project_request_id'];
// Relations
public function projectTeam() {
return $this->hasOne('\App\Models\ProjectRequest', 'project_request_id');
}
}
In my Controller I want to query both tables, however it returns the failure message.
What is important to know is that $request->projectTeam is an array of emails, looking like this:
array:2 [
0 => "mv#something.com"
1 => "as#something.com"
]
Meaning that I need to bulk insert into team_members table the project_request_ id for each team member where the emails are in the array.
How can I do that in the right way? The following is my attempt:
public function createProjectTeam(Request $request){
try {
$title = $request->projectTitle;
$TeamMember = $request->projectTeam;
$projectRequest = ProjectRequest::create(['project_title' => $title]);
$projectRequestId = $projectRequest->id;
$projectTeam = $this->teamMembers->projectTeam()->create(['project_request_id'=> $projectRequestId])->where('email', $TeamMember);
//$projectTeam = TeamMember::createMany(['project_request_id' => $projectRequestId])->where($TeamMember);
//dd($projectTeam);
return $projectRequest.$projectTeam;
} catch(\Exception $e){
return ['success' => false, 'message' => 'project team creation failed'];
}
}
There are a few things you can do.
Eloquent offers a whereIn() method which allows you to query where a field equals one or more in a specified array.
Secondly, you can use the update() method to update all qualifying team members with the project_request_id:
public function createProjectTeam(Request $request)
{
try {
$projectRequest = ProjectRequest::create(['project_title' => $request->projectTitle]);
TeamMember::whereIn('email', $request->projectTeam)
->update([
'project_request_id' => $projectRequest->id
]);
return [
'success' => true,
'team_members' => $request->projectTeam
];
} catch(\Exception $e) {
return [
'success' => false,
'message' => 'project team creation failed'
];
}
}
I hope this helps.

Sonata admin - Sorting by translated property

I have a code:
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
[..]
This is a property from translation (KNP translatable). I tried use:
translations.name - label is sortable, but values are missing
name or translate.name - label is not sortable, but values are ok
I don't have any idea how I should to do this. Maybe someone here can help me?
Did you try $listMapper->add('name',null, array('sortable'=>true)) ?
Ok, I made it.
1) Create abstract admin class:
use Sonata\AdminBundle\Admin\AbstractAdmin as BaseAbstractAdmin;
abstract class AbstractAdmin extends BaseAbstractAdmin { .. }
2) Use this class in your admin classes:
class UserAdmin extends AbstractAdmin { .. }
3) Add this to your column definition:
->add(
'fieldName',
null,
[
'sortable' => true,
'sort_field_mapping' => ['fieldName' => 'id'],
'sort_parent_association_mappings' => [],
]
)
4) Add this method to your abstract admin class:
protected function prepareQueryForTranslatableColumns($query)
{
$currentAlias = $query->getRootAliases()[0];
$locale = $this->request->getLocale();
$parameters = $this->getFilterParameters();
$sortBy = $parameters['_sort_by'];
$fieldDescription = $this->getListFieldDescription($sortBy);
$mapping = $fieldDescription->getAssociationMapping();
$entityClass = $mapping['targetEntity'] ?: $this->getClass();
if ($mapping) {
$mappings = $fieldDescription->getParentAssociationMappings();
$mappings[] = $mapping;
foreach ($mappings as $parentMapping) {
$fieldName = $parentMapping['fieldName'];
$query->leftJoin($currentAlias . '.' . $fieldName, $fieldName);
$currentAlias = $fieldName;
}
}
$query
->leftJoin(
$currentAlias . '.translations',
'tr',
'with',
'tr.locale = :lang OR
(NOT EXISTS(SELECT t.id FROM ' . $entityClass . 'Translation t WHERE t.translatable = tr.translatable AND t.locale = :lang)
AND tr.locale = :lang_default)'
)
->addOrderBy('tr.name', $parameters['_sort_order'])
->setParameter(':lang', $locale)
->setParameter(':lang_default', 'en');
return $query;
}
I use JOIN to get translations for currently selected locale and, if translation doesn't exist yet for current locale, I add translation for default locale (it is a reason for use NOT EXIST).
5) Add this method to your admin class:
public function createQuery($context = 'list')
{
$query = parent::createQuery($context);
if ('list' === $context) {
$parameters = $this->getFilterParameters();
$sortBy = $parameters['_sort_by'];
if (in_array($sortBy, ['fieldName', 'fieldName.fieldName2', 'fieldName3', ..])) {
$query = parent::prepareQueryForTranslatableColumns($query);
}
}
return $query;
}
Late answer but I was having the same problem.
The easiest solution for me was to set the right property mapping like this:
$listMapper->add(
'translations',
null,
[
'sortable' => true,
'associated_property' => 'name',
'sort_field_mapping' => [
'fieldName' => 'name',
],
'sort_parent_association_mappings' => [
['fieldName' => 'translations'],
],
]
);

array named for no reason

I calling a repository method and passing an array in it for the parameters. But the array is named after the first parameter and I don't understand why.
Here's the call :
/**
* #param $month
* #param $year
* #return Conges[]
*/
public function getAllCongesPayes($year, $month)
{
return $this->congesRepository->getNbCongesByMonth(array('year' => $year, 'month' => $month, 'cngPaye' => true));
}
And in the error I can see that :
array('year' => array('year' => '2016', 'month' => '05', 'cngPaye' => true)))
And of course it's saying "Missing argument 2" because only one array is in it.
Here is the repository method:
public function getNbCongesByMonth($year, $month, $conge){
$qb = $this->createQueryBuilder('e');
$listOfEntities = $qb
->select('count(e) as nb')
// ->leftjoin('e.cngUsrLogin', 'u')
->where(
$qb->expr()->like('e.cngDateDebut',
$qb->expr()->literal($year.'-'.$month.'-%')
)
)
->andWhere('e.congesPayes = :conge')
// ->andWhere('u.usrGestionCra = 1')
// ->groupBy('e')
->setParameter('conge', $conge)
->getQuery()
->getResult();
return $listOfEntities;
}
and the call in the controller :
$this->congesService = $this->get("intranet.conges_service");
$nbCongesPayes = $this->congesService->getAllCongesPayes('2016', '05');
If someone could explain why this happens that would be awesome.
Thanks in advance.
OK, I'm really dumb and figured it 2 minutes after... Sorry for the post...
Here is the answer :
public function getNbCongesByMonth($array){
$qb = $this->createQueryBuilder('e');
$listOfEntities = $qb
->select('count(e) as nb')
// ->leftjoin('e.cngUsrLogin', 'u')
->where(
$qb->expr()->like('e.cngDateDebut',
$qb->expr()->literal($array['year'].'-'.$array['month'].'-%')
)
)
->andWhere('e.cngPaye = :conge')
// ->andWhere('u.usrGestionCra = 1')
// ->groupBy('e')
->setParameter('conge', $array['cngPaye'])
->getQuery()
->getResult();
return $listOfEntities;
}
Needed to pass an array in the parameters. I don't know why I did that.
Anyway it's solved

Cakephp dropdown list (selectlist) + how to display a value from the model and a related model

I would like to display in a dropdownlist (selectlist) that concatenated the value of a field form the model and and a field from a related model. I have a table 'working_day' which is linked to a table 'user' and 'pause'. In the view 'Pause'(add and edit), I have a dropdownlist that displays the working_day_id but I wish to displays the fields 'date' of 'WorkingDay' and the fields 'username' of 'User'.
For example : 13/04/2016 (jerome S).
I already tried $virtualfield, it work when i use field from 'WorkingDay' but it does not work when i use the field from 'User'.
db schema
the $virtualfield that i tried :
public $virtualFields = array('workingday_display_field' => 'concat(WorkingDay.date_working_day, " (", User.username, ")")');
public $displayField = 'workingday_display_field';
I also tried the solution proposed below but it does not work, the same problem occurs :
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields['workingday_display_field'] = sprintf('concat(%s.date_working_day, " (", %s.username, ")")', $this->alias, $this->User->alias);
$this->displayField = "workingday_display_field";
}
Does anyone know how to solve the problem?
Thanks in advance.
There are some issues with doing it this way when using a different Model alias, another recommended way is to handle these in the Models construct method:
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields['name'] = sprintf('CONCAT(%s.first_name, " ",%s.last_name)', $this->alias, $this->alias);
$this->virtualFields['namewithemail'] = sprintf('CONCAT(%s.first_name, " ", %s.last_name, " (", %s.email, ")")', $this->alias, $this->alias, $this->alias);
$this->displayField = "namewithemail";
}
This is described in this section of the book: http://book.cakephp.org/2.0/en/models/virtual-fields.html#virtual-fields-and-model-aliases
I have a similar situation where I need to create a list that combines two fields from different tables. What I ended up doing was overriding find() to return the appropriate list.
public function find($type = 'first', $params = array()) {
$workingdays = array();
if ($type == 'list'){
$params = array_merge(
array('contain' => array('User')),
$params
);
$workingdaysUnformatted = parent::find('all', $params);
foreach($workingdaysUnformatted as $workingday){
$workingdays['WorkingDay']['workingday_display_field'] = $workingday['WorkingDay']['date'].' ('.$workingday['User']['username'].')'
}
}
else
$workingdays = parent::find($type, $params);
return $workingdays;
}
There may be a classier way to format the list that you want to return, but this illustrates the general idea.

cakephp how can i tell before function from an update

I am working on a CakePHP 2.x. The scenario is I am sending an encrypted and decrypted data to the database. So in order to do this I have written beforeSave function in each modal.
so right now the problem is whenever data is updated, the data is not going encrypted into db .. please anyone know how to i fix this issue
I am doing this in my controller. The update and save function:
foreach($data as $datas){
$count = $this->Contact->checkkey($datas['idUser'],$datas['key']);
if($count>0){
$this->Contact->updateContactAgainstkey($datas['name'],
$this->request->data['Contact']['mobileNo'],
$this->request->data['Contact']['other'],
$this->request->data['Contact']['email'],
$datas['key'],$datas['idUser']);
}else{
$this->Contact->create();
$this->Contact->save($this->request->data);
}
}
updateFunction in Model
public function updateContactAgainstkey($name,$mobileNo,
$other,$email,$key,$userid){
if($this->updateAll(
array('name' => "'$name'",
'mobileNo' => "'$mobileNo'",
'workNo' => "'$workNo'",
'homeNo' => "'$homeNo'",
'other' => "'$other'",
'email' => "'$email'",),
array('User_id'=>$userid,'key'=>$key))){
return true;
}else{
return false;
}
}
beforeSave function
public function beforeSave($options=array()) {
if ( isset ( $this -> data [ $this -> alias ] [ 'mobileNo' ] ) ) {
$this -> data [ $this -> alias ] [ 'mobileNo' ] = AllSecure::encrypt($this->data[$this->alias]['email']);
}
return true;
}
please help me if anyone know how to deal with this issue.
Try following code in model
public function updateAll($fields, $conditions = true) {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$created = FALSE;
$options = array();
if($db->update($this, $fields, null, $conditions)) {
$created = TRUE;
$this->Behaviors->trigger($this, 'afterSave', array($created, $options));
$this->afterSave($created);
$this->_clearCache();
$this->id = false;
return true;
}
return FALSE;
}
look here
http://nuts-and-bolts-of-cakephp.com/2010/01/27/make-updateall-fire-behavior-callbacks/
here better to use save function for updating data like:
$data=array();
$data['Contact']['mobileNo']=$this->request->data['Contact']['mobileNo'];
$data['Contact']['other']=$this->request->data['Contact']['other'];
$data['Contact']['other']=$this->request->data['Contact']['other'];
........... .............. ................
$this->Contact->id = "primerykey";
$this->Contact->save($data);
where $data contains all field that you want to update with value

Resources