I am using yii cgridview and i want to add alt in the checkboxes. I am successfull to add this but i want to add $data->rem_type i mean variable in this . here is the code i have tried
array(
'name' => 'check',
'id' => 'selectedIds',
'value' => '$data->rem_id',
'class' => 'CCheckBoxColumn',
'selectableRows' => '100',
'checkBoxHtmlOptions'=>array(
'alt'=>'$data->rem_type'),
),
but it producing the html like this
<input alt="{$data->rem_type}" value="12" id="selectedIds_0" type="checkbox" name="selectedIds[]">
If i removed the quotes (i.e 'alt'=>$data->rem_type)) it show me the error Undefined variable: data
can anybody help me ??
Ok, so I haven't tested this but I think you can do it like this:
extend the CCheckBoxColumn to CheckBoxColumn and overwrite the getDataCellContent function:
class CheckBoxColumn extends CCheckBoxColumn {
public function getDataCellContent($row) {
$data = $this->grid->dataProvider->data[$row];
if ($this->value !== null)
$value = $this->evaluateExpression($this->value, array('data' => $data, 'row' => $row));
elseif ($this->name !== null)
$value = CHtml::value($data, $this->name);
else
$value = $this->grid->dataProvider->keys[$row];
$checked = false;
if ($this->checked !== null)
$checked = $this->evaluateExpression($this->checked, array('data' => $data, 'row' => $row));
$options = $this->checkBoxHtmlOptions;
if ($this->disabled !== null)
$options['disabled'] = $this->evaluateExpression($this->disabled, array('data' => $data, 'row' => $row));
if (array_key_exists("alt", $options)) { //checks if you have set an alt
$options['alt'] = $this->evaluateExpression($options['alt'], array('data' => $data, 'row' => $row)); //if you have it will evaluate the expression
}
$name = $options['name'];
unset($options['name']);
$options['value'] = $value;
$options['id'] = $this->id . '_' . $row;
return CHtml::checkBox($name, $checked, $options);
}
}
I have copied most of the code from the original function
And added this part:
if (array_key_exists("alt", $options)) { //checks if you have set an alt
$options['alt'] = $this->evaluateExpression($options['alt'], array('data' =>data, 'row' => $row)); //if you have it will evaluate the expression
}
There is probably a way to do this better, i.e. not copy the code but I'll let you to this.
Save this in your components folder, include it in your config.php.
And use this class in your widget:
array(
'name' => 'check',
'id' => 'selectedIds',
'value' => '$data->rem_id',
'class' => 'CheckBoxColumn',// <-- instead of CCheckBoxColumn
'selectableRows' => '100',
'checkBoxHtmlOptions'=>array(
'alt'=>'$data->rem_type'),
),
Let me know if it works!
Related
I want to get a variable from a class in a function , the variable has arrays and i want to print all of theme in foreach loop
Here is my code :
class MP {
public function mp_setup_fields() {
$fields_socialmedia = array(
array(
'label' => 'شبکه های اجتماعی',
'id' => '',
'type' => 'hidden',
'section' => 'mp_custom_section',
),
);
}
}
I want get $fields_socialmedia in my home page
class MP {
public function mp_setup_fields() {
$fields_socialmedia = array(
array(
'label' => 'شبکه های اجتماعی',
'id' => '',
'type' => 'hidden',
'section' => 'mp_custom_section',
),
);
return $fields_socialmedia;
}
}
At first create object of your class then call method of object like below
$mp = new MP();
$array = $mp->mp_setup_fields();
foreach ($array as $value){
foreach ($value as $key => $v){
echo $key ."=". $v;
}
}
I am currently inserting data from json api url into my database, except some arrays are not completed filled out resulting in 'undefined index' errors.
Is there a good way to deal with this? Ofcourse checking each item index with an if isset statement and only setting it if it is available would work but that would be quite tedious for each entry.
foreach($items['response']['groups'] as $item) {
foreach($item['items'] as $item) {
Bar::firstOrCreate([
'lat' => $item['venue']['location']['lat'],
'long' => $item['venue']['location']['lng'],
'postalCode' => $item['venue']['location']['postalCode'],
'city' => $item['venue']['location']['city'],
'state' => $item['venue']['location']['state'],
'country' => $item['venue']['location']['country'],
'address' => $item['venue']['location']['address'],
'rating' => $item['venue']['rating'],
'website' => $item['venue']['url'],
]);
}
}
use simplest way like:
foreach($items['response']['groups'] as $item1) {
foreach($item1['items'] as $item) {
Bar::firstOrCreate([
'lat' => isset($item['venue']['location']['lat'])?$item['venue']['location']['lat'] : '',
'long' => isset($item['venue']['location']['lng'])?$item['venue']['location']['lng'] : '',
'postalCode' => isset($item['venue']['location']['postalCode'])?$item['venue']['location']['postalCode'] : '',
'city' => isset($item['venue']['location']['city'])?$item['venue']['location']['city'] : '',
'state' => isset($item['venue']['location']['state'])?$item['venue']['location']['state'] : '',
'country' => isset($item['venue']['location']['country'])?item['venue']['location']['country'] : '',
'address' => isset($item['venue']['location']['address'])?$item['venue']['location']['address'] : '',
'rating' => isset($item['venue']['rating'])?$item['venue']['rating'] : '',
'website' => isset($item['venue']['url'])?$item['venue']['url'] : '',
]);
}
}
Your problem here is that you rewrite value of $item on each iteration.
foreach($items['response']['groups'] as $item) {
foreach($item['items'] as $item) {
// after first iteration here `$item` doesn't have `items` key
}
Use different variables in every foreach.
Check each array for completeness and only Bar::firstOrCreate() if it's really complete:
foreach($items['response']['groups'] as $item) {
foreach($item['items'] as $item) {
if(
isset($item['venue']) &&
isset($item['venue']['location']) &&
isset($item['venue']['location']['lat']) &&
isset($item['venue']['location']['lng']) &&
isset($item['venue']['location']['postalCode']) &&
isset($item['venue']['location']['city']) &&
isset($item['venue']['location']['state']) &&
isset($item['venue']['location']['country']) &&
isset($item['venue']['location']['address']) &&
isset($item['venue']['location']['lng']) &&
isset($item['venue']['rating']) &&
isset($item['venue']['url'])
)
Bar::firstOrCreate([
'lat' => $item['venue']['location']['lat'],
'long' => $item['venue']['location']['lng'],
'postalCode' => $item['venue']['location']['postalCode'],
'city' => $item['venue']['location']['city'],
'state' => $item['venue']['location']['state'],
'country' => $item['venue']['location']['country'],
'address' => $item['venue']['location']['address'],
'rating' => $item['venue']['rating'],
'website' => $item['venue']['url'],
]);
}
}
you can use these simple steps
remove all the keys from nested arrays that contain no value, then
remove all the empty nested arrays.
$yourArray= array_map('array_filter', $yourArray);
$yourArray= array_filter( $yourArray);
You will have to check the existence of an index somewhere ! If you don't want to do it in the controller, you could have an entity like which checks every field :
<?php
class MyEntity
{
private $lat;
private $long;
private $postalcode;
...
public static function createInstanceFromArray(array $item)
{
if (isset($item['lat']) {
$this->setLat($item['lat']);
}
... and so on
// you could also do it automatic :
foreach($item as $key => $value) {
$methodName = 'set' . ucfirst($key);
if (method_exists($this, $methodName)) {
$this->{$methodName}($value);
}
}
}
public function setLat($lat)
{
$this->lat = $lat;
return $this;
}
public function getLat()
{
return $this->lat;
}
}
Then you could do the following to your original code :
foreach($items['response']['groups'] as $item) {
foreach($item['items'] as $subItem) {
$myEntity = MyNamespace\MyEntity::cretaInstanceFromArray($subItem['venue']);
}
}
Then you could set the fields of your entity with your methods :
'lat' => $myEntity->getLat();
....
this way, even if the array field does not exists, the entity returns a default value.
If you don't want to use objects, you could use array_merge with default values to ensure you will not have undefindex indexes :
$item = array_merge([
'lat' => '',
'long' => '',
'postalCode' => '',
...
], $item['venue']);
And put that treatment in a function for an exemple.
first of, just wanted to let you know that I am a newbie at CI. but I am having trouble with this piece of code where is breaking and I can't seem to be able to find the answer anywhere.
for some reason the code is breaking at the first if statement.. if possible could you help me out understand what is really happening there?
Thank you all for your help!
function main
{
$this->load->model(getData) psudo code for this area...
}
---model---
function getData....
{
Sql = this->db->query(sql code that returns all the information required.)
$result = $sql->result_array();
$types = array ( 'EVENT|TIME' => array( 'id' => 1, 'name' => 'Regular' ),
'PROPOSITION|REGULAR' => array( 'id' => 2, 'name' =>'Propositions'),
'EVENT|TIME' => array( 'id' => 3, 'name' => 'Now' ),
'PROPOSITION|FUTURES' => array( 'id' => 4, 'name' => 'Future' ));
$var = array();
foreach ($result as $event) {
$cat = $event['type'] . '|' . $event['sub_type'];
$typeId = $types[$cat]['id'];
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
{
if(!is_array($var[$event['event_id']]))
{
$var[$event['event_id']] = array( 'event_name' =>
$event['event_name'],'event_abbreviation' =>
$event['event_abbreviation']);
}
$var[$event['event_id']]['var'][$event['type_id']] = array(
'type_name' => $event['abbreviation'],'type_abbreviation' => $event['name']
);
}
$event[$event['event_id']]['var'][$event['type_id']]['types'][$typeId] =
$types[$cat]['name'];
}
return $myResults;
}
In this line
if(!is_array($var[$event['event_id']]['var']$event['type_id']]))
You are missing a [ somewhere. I'm guessing before $event['type_id'].
So replace with:
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
This simple script should theoretically check the form for errors and then print any errors it finds.
The formValidate function takes in a form array, each field in the form has a value which is validated. The field also has an errors key whose value is an empty array. I am trying to append any errors I find to the errors array of the particular field. I then return the form array when I am done.
I later print out all the errors for the fields. Unfortunately the errors never show up.
I have been breaking my head over this for many hours now and I cant for the life of me figure out why the form errors in my script are not appeding.
Any help would be greatly appreciated!
# get value from array
function array_get(array $array, $key, $default = null)
{
return (array_key_exists($key, $array)) ? $array[$key] : $default;
}
# get string value from array
function array_get_string(array $array, $key, $default = '', $trim = true)
{
$val = array_get($array, $key);
if (is_string($val)) {
return ($trim) ? trim($val) : $val;
}
return $default;
}
function validateForm($form)
{
// validateField each field
foreach ($form as $field)
{
foreach ($field['validation'] as $validate)
{
switch($validate)
{
case 'email':
if(!filter_var($field['value'], FILTER_VALIDATE_EMAIL)) {
$field['errors'][] = $field['value'] . ' is an invalid email address.';
}
break;
case 'number':
if(!preg_match('/^[0-9 ]+$/', $field['value'])) {
$field['errors'][] = $field['value'] . ' is an invalid number.';
}
break;
case 'alpha':
if(!preg_match('/^[a-zA-Z ]+$/', $field['value'])) {
$field['errors'][] = $field['value'] . ' contains invalid characters. This field only accepts letters and spaces.';
}
break;
}
}
}
return $form;
}
// $post = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );
$post = $_POST;
$ajax = array_get_string($post, "request_method") == 'ajax';
# select data that needs validation
$form = array(
'fullname' => array(
'value' => array_get_string($post, "full-name"),
'validation' => array('alpha', 'required'),
'errors' => array(),
),
'emailaddress' => array(
'value' => array_get_string($post, "email-address"),
'validation' => array('email'),
'errors' => array(),
),
'activites' => array(
'value' => array_get_string($post, "activites"),
'validation' => array('default'),
'errors' => array(),
),
'country' => array(
'value' => array_get_string($post, "country"),
'validation' => array('default'),
'errors' => array(),
),
'contactpreference' => array(
'value' => array_get_string($post, "contact-preference"),
'validation' => array('default'),
'errors' => array(),
),
'message' => array(
'value' => array_get_string($post, "message"),
'validation' => array('alpha'),
'errors' => array(),
),
);
// validate the form
$form = validateForm($form);
foreach ($form as $field)
{
foreach ($field['errors'] as $error)
{
echo $error . '<br />';
}
}
foreach creates a copy of the array and works on it. If you need to make changes to the original array, pass it by reference like so:
foreach($form as &$field) {
...
}
I have an array in this form:
$data = array(
array(
'id' => '1',
'bar' => 'foo',
'page' => 'front',
),
array(
'id' => 'bar',
'bar' => 'foo',
'page' => 'front',
),
array(
'id' => 'different,
'bar' => 'bar',
'page' => 'back',
),
array(
'id' => 'another',
'title' => __("Custom CSS",'solidstyle_admin'),
'foo' => 'bar',
'page' => 'back',
),
);
And I want to list all ids grouped by pages and saved as variables, so if the above array is an input then output will look just like this one:
$front = array('1','bar');
$back = array('different','another');
//$data['page'] = array($id1, $id2, (...));
I was trying to do that using foreach and this is how it starts:
function my_output() {
foreach($data as $something) {
$id = $something['id'];
$page = $something['page'];
}
return $output;
}
I was trying multiple foreach loops, and the best result I got was:
front = 1
front = bar
back = different
back = another
But I have absolutely no idea how to achieve what I want to do, I don't want anyone to do my job, just any hints? Keep in mind I'm a bit new to PHP and I don't know too much about arrays.
Thank you!
Sounds like you want:
$ids = array();
foreach ($data as $page) {
$pageName = $page['page'];
// create an empty array for your IDs
if (!isset($ids[$pageName])) {
$ids[$pageName] = array();
}
// add to the array of IDs
$ids[$pageName][] = $page['id'];
}
var_dump($ids); // array('front' => array('1', 'bar'), ...
Stick with the loop idea and do a conditional check.
function my_output() {
$front = array();
$back = array();
foreach($data as $something) {
$id = $something['id'];
$page = $something['page'];
if ($page === 'front') {
$front[] = $id;
} else if ($page === 'back') {
$back[] = $id;
}
}
// Not sure what you want to return here, but you could return an array of pages
$output = array('front' => $front, 'back' => $back);
return $output;
}
This will return something similar to:
$output = array(
'front' => array(
0 => '1',
1 => 'bar',
),
'back' => array(
0 => 'something',
1 => 'another',
)
)
Edit: Keep in mind that my answer only accounts for the two pages you listed in your answer. If you have more pages you can also use what cbuckley's answer showed.