So basically I have an array mutator which works perfectly, but the field its pulling is only a char 1 and only 1 entry so it works fine
However I want to do the exact same thing with a field that contains multiple entries by a comma separator. below is what i have that works and and example of what I want.
The field interests contains a number from 1 to 3,
protected $userTypes = array(
'1' => 'Owner',
'2' => 'Admin',
'3' => 'Standard User'
);
public function getUserTypeAttribute($value)
{
return $this->userTypes[$value];
}
now I have another field lets call it, InterestList but it has multiple entries separated by commas like so 3,4,5,6,7
How would I get the code like above to work for something like that?
Try this --
<?php
// lets define the interest list
protected $interestList = array(
'1' => 'Play',
'2' => 'Sing',
'3' => 'Hobby'
);
// function for getting the interesttype strings
public function getIntestetTypeString($intStr=''){
// $intStr = '1,3' ; may be something like
$interestList = '';
if(!empty($intStr)){
$attrToIterate = explode(", ",$intStr) ;
foreach($attrToIterate as $value){
if($interestList){
$interestList .= ','. $this->interestList[$value] ;
}else{
$interestList .= $this->interestList[$value] ;
}
}
}
return $interestList ;
}
Hey so I ended up with an answer, Below is the code
public function getInterestsAttribute($value)
{
$InterestList = array(
'1' => 'Books',
'2' => 'Cars',
'3' => 'Cats'
);
$strExplode = explode(",",$value);
foreach ($strExplode as $i=>$ANUMBER){
echo $InterestList[$ANUMBER];
}
}
Then in the blade you just go about your way as normal. eg.
{{ $UserProfile->Interests }}
Related
I have questions model in laravel that has a database structure like this:
question_id | is_active
------------+-----------
1 | Y
2 | Y
3 | N
... | ...
I have an input in form of an array that i want to validate with questions model, this array will contain key that act as the question_id and the value as the question answer, that looks like this:
$QnAs = [
'1' => '3',
'2' => '5',
'4' => '1',
'6' => '4',
'7' => '2',
'8' => '0',
]
The validation system will required all the Active (is_active == 'Y') questions that present in the array as question_id as the key of array to represent it and the value of each array is 1, 2, 3, or 4.
I can achieve that by looping through every question that active like this:
$collections = Questions::where('is_active','Y')->get();
foreach($collections as $collection){
if(!array_key_exists($collection->question_id,$QnAs)){
return false; // doesn't find the question id in array key input
} elseif(!in_array($QnAs[$collection->$question_id],['1','2','3','4'])){
return false; // input value for this array does not match with required value
}
}
the problem with this code is , when i process 15k++ data it will take a long time too process because it has to loop through every model collection , is there any other approach that can simplify the code and the process ?
Your code wont work . Beacause return will immediately end the execution of current function. So the checking will be done only with the first value in collections and it will return the result based on the first element in the array $collections.
you can change the code as following :
$collections = Questions::where('is_active','Y')->get();
$result = true;
foreach($collections as $collection)
{
if(!array_key_exists($collection->question_id,$QnAs))
{
$result = false; // doesn't find the question id in array key input
}
}
return $result;
The above code will work
You can research more for greater performance
The problem is you are getting all of the active questions,
so the point is to limit the datas,
Firstly, add composite index on question_id and is_active
$table->index(['question_id', 'is_active']);
And try this code:
$QnAs = [
'1' => '3',
'2' => '5',
'4' => '1',
'6' => '4',
'7' => '2',
'8' => '0',
];
// filter elements allowed:
$valid_QnAs = array();
foreach($QnAs as $k => $v) {
if (in_array($v, [1,2,3,4])) {
$valid_QnAs[$k] = $v;
}
}
$not_in_active = Questions::where('is_active','Y')
->whereNotIn('question_id', array_keys($valid_QnAs))
->exists();
if ($not_in_active) return false;
I have 1 row having 5 form fields. User can add/remove rows. Its repeatable row.
Now i want to store these fields into database with PDO php.
For normal values i am using this code but i am confused for repeater field.
$data = array(
'bill_no' => trim($_REQUEST['bill_no']),
'from_name' => trim($_REQUEST['from_name']),
'to_name' => trim($_REQUEST['to_name']),
'date' => trim($_REQUEST['date_bill']),
'mr_or_ms' => trim($_REQUEST['mr_or_ms']),
);
if($crud->InsertData("bill",$data)) {
header("Location: add-bill.php");
}
Insert Function:
public function InsertData($table,$fields) {
$field = array_keys($fields);
$single_field = implode(",", $field);
$val = implode("','", $fields);
try {
$query = $this->db->prepare("INSERT INTO ".$table."(".$single_field.") VALUES('".$val."')");
$query->execute();
return true;
} catch(PDOException $e) {
echo "unable to insert data";
}
}
Please help me to insert fields. Thanks
Change the names of your form fields, add [] to the end to get PHP arrays. For example change bill_no to bill_no[]. Something like this:
foreach($_REQUEST['bill_no'] as $row_number => $row_content){
$data = array(
'bill_no' => trim($_REQUEST['bill_no'][$row_number]),
'from_name' => trim($_REQUEST['from_name'][$row_number]),
'to_name' => trim($_REQUEST['to_name'][$row_number]),
'date' => trim($_REQUEST['date_bill'][$row_number]),
'mr_or_ms' => trim($_REQUEST['mr_or_ms'][$row_number]),
);
$crud->InsertData("bill",$data);
}
This assumes the browser is not mixing up the order of the fields, so maybe it's better to add unique names to the form fields when adding rows.
Also, there's no input data validation at all, please ensure you are escaping all data properly.
I did it with this method.
$total=count($_POST['description']);
for($i=0; $i<$total; $i++){
$data1 = array(
'bill_no' => trim($_POST['bill_no']),
'description' => trim($_POST['description'][$i]),
'nos' => trim($_POST['nos'][$i]),
'nos_day' => trim($_POST['nos_day'][$i]),
'pay' => trim($_POST['pay'][$i]),
'weekly_off' => trim($_POST['weekly'][$i]),
'hra' => trim($_POST['hra'][$i]),
'rs' => trim($_POST['rs'][$i]),
'ps' => trim($_POST['ps'][$i]),
);
$crud->InsertData("bill_details",$data1);
}
i'm newbie in Cake and wodering how to insert multiple rows in a single saveall function,
i got this table,
CREATE TABLE IF NOT EXISTS `dates` (
`date` varchar(10) COLLATE utf8_unicode_ci NOT NULL
)
what i'm trying to do is let user select start date and end date using JQuery calander, once submit all the dates between this range will be saved into database, i already got the array of dates eg:
`array(
(int) 0 => '5/8/2013',
(int) 1 => '6/8/2013',
(int) 2 => '7/8/2013',
(int) 3 => '8/8/2013',
)
`
then my controller looks like this:
public function index(){
if ($this->request->is('post')) {
$this->Date->create();
$data = array();
$data['dates']=array();
$startDate = $this->request->data['Date']['from'];
$endDate = $this->request->data['Date']['to'];
$datesBlocked = $this->loopDates($this->request->data['Date']['from'],$this->request->data['Date']['to']);
$data['dates'][] = $this->request->data['Blockdate']['from'];
$data['dates'][] = $this->request->data['Blockdate']['to'];
/*foreach($datesBlocked as $data) {
$data['dates'][] = $data;
}*/
if($this->Date->saveAll($data)) {
$this->Session->setFlash(__('done'));
if ($this->Session->read('UserAuth.User.user_group_id') == 1) {
// $this->redirect("/manages");
}
}
}
public function loopDates($from,$to){
$blockdates = array();
$start = strtotime($from);
$end = strtotime($to);
debug($start);
$counter = 0;
for($t=$start;$t<=$end;$t+=86400) {
$d = getdate($t);
$blockdates[$counter++] = $d['mday'].'/'.$d['mon'].'/'.$d['year'];
}
debug($blockdates);
return $blockdates;
}
issue was i can't get foreach work, if i uncomment the foreach, i got error said Illegal string offset 'dates' , so i commented that and try to only add the start date and end date to the array to see if that works, then i got another error said.
`array(
'dates' => array(
(int) 0 => '08/05/2013',
(int) 1 => '09/05/2013'
)
)
`
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1005]Code
cuz i'm trying to insert 2 values into one field...i know it should be sth like
`array(
'dates' => array( (int) 0 => '08/05/2013',
)
'dates' => array((int) 1 => '09/05/2013'
))
`but can't figure out how to do it. Any help would be much appreciate!!!!
The structure you'll want your array to save multiple dates using saveAll() is this:
array(
'Date' => array(
0 => array(
'date' => '08/05/2013',
),
1 => array(
'date' => '09/05/2013',
)
),
)
I know that this is a little late, but to write multiple rows in a loop, you have to proceed the save with a create().
eg:
foreach($items as $lineItem){
$this->Invoice->create();
$this->Invoice->save(array(
'user_id'=>$property['User']['id'],
'invoice_id'=>$invId['Invoices']['id'],
'item_id'=>$lineItem['item_number'],
'quantity'=>$lineItem['quantity'],
'price'=>$lineItem['mc_gross']
);
}
Just thought it was worth mentioning, hopefully it will help someone.
Please help me to retrieve data from a table by multiple condition in Cakephp
I have one table name: article; I have tried to retrieve data with the code below
I want to get specific id as given in the parameter; article_price > 0 and article_status > 1
public function getArticle($artID = ''){
return $this->find('all', array(
'condition' => array(
'article_id =' => $artID,
'article_price' => '> 0',
'article_status = ' => '1'),
'order' => 'article_id DESC'
));
}
// the out put was selected all data without condition that I want.
What was the problem with my code?
What I found out is I print: echo $this->element ('sql_dump'); and I got the following sql statement:
SELECT `article`.`article_id`, `article`.`name`, `article`.`article_price`, `article`.`article_status` FROM `db_1stcakephp`.`article` AS `article` WHERE 1 = 1 ORDER BY `article_id` DESC
Please help me.
Thank!
If your model name is Article:
public function getArticle($art_id) {
return $this->find('first', array(
'conditions' => array(
'Article.article_id' => $art_id,
'Article.article_price >' => 0,
'Article.article_status >' => 1,
),
));
}
Using 'Model.field' syntax is optional, until your models have relationship and have the same names - for example Article.status and Author.status.
Moving comparison sign into array's key part allows you to do:
'Article.price >' => $minPrice,
'Article.price <=' => $maxPrice,
And I didn't really notice typo in 'conditions'.
I'm trying to fetch all rows to an array variable
array that i want is like this
$data1 = array('fields'=>array(
array(
'id' => 1,
'nama_file' => "sunset.jpg",
'judul' => "Sunset",
'isi' => "Matahari terbenam indah sekali",
),
array(
'id' => 2,
'nama_file' => "water_lilies.jpg",
'judul' => "Bunga Lilly",
'isi' => "Bunga lilly air sangat indah",
),)
And I've done this:
$q = $this->db->query('select id, nama_file, judul, isi from tfoto where dihapus ="T" ');
$data1=array('fields');
foreach($q->result() as $row) {
$data1['fields']=array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
}
test output:
<?php
foreach($fields as $field){
echo $field['nama_file'];
.
.
.
};?>
and I got Message: Illegal string offset 'nama_file';'judul'; etc.
I am a newbie to MySQL/PHP, so forgive me if this is a very basic question. I tried looking all over but I could not find an answer to it.
This line:
$data1['fields']=array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
Should be:
$data1['fields'][] = array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
Because you have to append new arrays to $data1 and not replacing it.