What I need to achieve is to add multiple td rows in one tr. F.e:
<tr>
<td="0"> row1 </td>
<td="1"> row2 </td>
<td="2"> row3 </td>
</tr>
How can I achieve it? I'm trying like so:
$td = Html::tag('td data-col-seq', [
'0' => 'test'
'1' => 'test2'
]);
return Html::tag('tr', $td);
But I get Array to string conversion error, besides that, I don't get the values. All I get is <td data-col-seq 0="test"> NO VALUE HERE </td>
I hope you understood the problem. Thank you for any help!
One way to solve your problem is as follows
$cols = '';
$row = '';
$data = [0, 1, 2]; //just a sample here
// create all td tags at first based on your sample
foreach ($data as $value) {
$cols .= Html::tag('td', 'rows' . $value, [
'value' => $value,
]);
}
$row .= Html::tag('tr', $cols); //then create a tr tag to include all td tags
var_dump($row);
The first param of Html::tag function is the tag name, second one is the content inside the tag that you just created, last one is the attrs attached to the tag.
The reason why you came accross that error is that the second param needs to be string type, while you passed an array, which should be the last param. May this you help.
assuming you need a td tag with row1 conttnet and data-col-seq as attribute you should use
$options = ['data-col-seq' => 'your-values'];
echo Html::tag('a', 'row1', $options);
for several value .. build te proper code using a loop
see http://www.yiiframework.com/doc-2.0/yii-helpers-html.html for reference and http://www.yiiframework.com/doc-2.0/guide-helper-html.html for guide
Related
I am looking for a way to retrieve all models in a database. Then loop through all of the models and read out the values for name, firstname and phonenumber.
So far I've gotten this and failed to go past it:
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
I am then looking to implement those three values in a simple HTML table:
<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>
The table should be part of a PDF output, so ideally I would save it to a variable:
$html_table = '<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>';
I would need to get this for every model that fulfills the criteria of status = 'active' in the database.
So far I've only been able to get tables via gridView and not in a HTML template either.
You don't really need a data provider to achieve this, you could simply try :
$models = Employee::find()->where(['status'=>'active'])->orderBy('name ASC')->all();
foreach ($models as $model) {
echo "<tr><td>{$model->firstname}</td><td>{$model->name}</td><td>{$model->phone}</td></tr>";
}
Read more : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data
You can get all models like this:
$employees = Employee::find()
->select('firstname, name, phone')
->asArray()
->where(['status'=>'active'])
->all();
This way you will get an array of arrays containing the 3 selected fields, so now you only need to use a foreach to loop through them and create the table:
$html = '<table>';
foreach($employees as $employee) {
$html .= '<tr><td>'.$employee['firstname'].'</td><td>'.$employee['name'].'</td><td>'.$employee['phone'].'</td></tr>';
}
$html .= '</table>'
How do you check within the view template if the result object contains any entries?
(There was a similar question already, but this one is slightly different)
Take the CakePHP 3 blog tutorial for example. They show how to list all articles on one page:
// src/Controller/ArticlesController.php
public function index() {
$this->set('articles', $this->Articles->find('all'));
}
And the view template:
<!-- File: src/Template/Articles/index.ctp -->
<table>
<tr>
<th>Id</th>
<th>Title</th>
</tr>
<?php foreach ($articles as $article): ?>
<tr>
<td><?= $article->id ?></td>
<td>
<?= $this->Html->link($article->title, ['action' => 'view', $article->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</table>
Disadvantage: if there are no entries in the database the HTML table is still rendered.
How can I prevent this and show a simple message like "Sorry no results" insteat?
In CakePHP 2 I used
if ( !empty($articles['0']['id']) ) {
// result table and foreach here
} else {
echo '<p>Sorry no results...</p>';
}
But since $articles is now an object this doesn't work anymore... Is there a new "short way" to check the result object? Or do you usally use another foreach first, like
$there_are_results = false;
foreach ($articles as $article) {
if ( !empty($article->id) ) {
$there_are_results = true;
break;
}
}
if ( $there_are_results == true ) {
// result table and second foreach here
} else {
echo '<p>Sorry no results...</p>';
}
Thanks for your hints.
You can use the iterator_count() function to know if there are results in the set:
if (iterator_count($articles)) {
....
}
You can also use the collection methods to get the first element:
if (collection($articles)->first()) {
}
Edit:
Since CakePHP 3.0.5 the best way to check for emptiness on a query or a result set is this:
if (!$articles->isEmpty()) {
...
}
I believe you can call $articles->count() from your template. (Check for 0)
Something I have been struggling for a while..
if(!$articles->isEmpty()) {
gives error on empty value
Call to a member function isEmpty() on null
<?php if(iterator_count($articles)) { ?>
Argument 1 passed to iterator_count() must implement interface Traversable, null given
<?php if (collection($articles)->first()) {?>
Only an array or \Traversable is allowed for Collection
I got
to work, the problem if you render a different view in the controller $this->render('index');
for a function you should do that after the values has been set
I've got this hash of hashes and I'm trying to populate a select box with values from each hash. Anyway I'm having trouble getting to my inner hash variables. I am able to generate the right number of options in my select, but I'm currently only able to set the value parameter of each select option.
Heres my hash:
my $export_types = { a => {label => "Foo", ext => ".js"},
b => {label => "Bar", ext => ".gz"}};
Heres what I've tried so far for my foreach:
my $select = "<select id='fancy'>";
foreach my $key (sort keys %{$export_types})
{
$select .= "<option value='$key' ";
if($saved_value eq $key || (!$saved_value && $key eq "a"))
{
$select .="selected='selected'";
}
$select .= ">".$export_types{$key}{label}."</option>";
}
$select .= "</select>";
apparently I'm accessing the label property wrong. For that particular line I also tried:
$select .= ">".$export_types{$key}->{label}."</option>";
but that was to no avail as well. I'm sure I'm missing something simple.
Thanks for the help :)
The expression
$export_types{$key}{label}
assumes that there is a hash %export_types. This is not the case. If you had a use strict in scope, you would have been alerted to this fact.
Because $export_types is a hash reference, we have to dereference it before using the subscript operator to access some value. Either
$export_types->{$key}{label}
or
$$export_types{$key}{label}
(I prefer the former).
I am trying to set a maxlength for the form_textarea() in Codeigniter.
I tried the following:
<?php
$options = array(
'maxlength' => '100'
);
?>
<tr>
<td><?= form_label('Profiel:');?></td>
<td><?= form_textarea('Profiel', $options, $info['Profiel']);?></td>
</tr>
When I edit my form to edit the text in the textarea it says Array. So the text is gone and is replaced with Array.
But that is not working.
Maybe I have to use Jquery?
Codeigniter allows you to pass attributes into your form elements by way of an associative array.
Documentation for the form helper is here: http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
Although I can see exactly what you're trying to do, there's one caveat with textareas. From the documentation:
form_textarea()
This function is identical in all respects to the form_input()
function above except that it generates a "textarea" type. Note:
Instead of the "maxlength" and "size" attributes in the above example,
you will instead specify "rows" and "cols".
So, you need to pass rows and columns instead of maxlength for textareas. Your code would look something like this:
$options = array(
'rows' => 10,
'cols' => 10
);
form_textarea(array(
'cols' => 1,
'rows' => 1
));
I'm trying to fetch a series of ids from a database table that includes cross-referencing - each element, a "topic", includes a column for "parent topic" that is within the same table. Given a single parent topic, I want to build an array of all the subtopics that have it as their parent, and then all of the subtopics of those topics, etc.
This doesn't seem like it's that hard, but as a self-taught programmer I feel I'm using all the wrong tools. The merge-array() and var_dump() sections, in particular, feel wrong and I'm not sure about the overall approach. What should I replace these elements with?
function get_subtopics($parent_topic)
{
//returns an array of subtopics minus the first
$all_subs = array();
$query = $this->db->get_where('topics', array('parent_topic' => $parent_topic));
$subs = $query->result_array();
$resubs = array();
$query->free_result();
//push subs to all_subs
//while the subs array has members, find their child
while (count($subs)>0) {
foreach ($subs as $s) {
$query = $this->db->get_where('topics', array('parent_topic' => $s['id']));
$resubs = array_merge($resubs, $query->result_array());
$query->free_result();
}
$all_subs = array_merge($all_subs, $resubs);
var_dump($resubs);
}
//Returns an array of ids
return $all_subs;
}
EDIT:
The objective of this is to form a "pool" of topics from which problems will be drawn for a random generator - I'm trying to get all of the subtopics into one array, with no tree structure to differentiate them. Users that specify a parent topic, like "math" should get an even mix of math subtopics like "algebra", "algebra:quadratics" or "calculus" from which problems will be drawn. Hope that clarifies a little.
There are 2 ways to do this either just get all the records from the database and build a tree structure using a php recursive function like below.
//Build menu array containing links and subs
$items = Array(
//highest level
'cms' => Array(
'title' => 'CMS',
//Array containing submenu items for cms
'subs' => Array(
'intro-to-cms' => Array('title' => 'Intro to CMS'),
'specific-cms' => Array('title' => 'Specific CMS'),
'installing-a-cms' => Array('title' => 'Installing a CMS')
),
)
);
//Display the menu
echo navlinks($items, $page);
/**
* Recursive function creates a navigation out of an array with n level children
* #param type $items
* #return string containing treestructure
*/
function navlinks($items, $page=false)
{
$html = '<ul>';
foreach ($items AS $uri => $info) {
//Check if the pagename is the same as the link name and set it to current when it is
$html .= '<li'.($info['title'] == $page ? ' class="current"' : '').'>';
echo ' ' . $info['title'] . '';
//If the link has a sub array, recurse this function to build another list in this listitem
if (isset($info['subs']) && is_array($info['subs'])) {
$html .= navlinks($info['subs']);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
In order to just filter on 1 parent with its underlying children you will need a rather tricky query in advance like explained in a previous comment on stackoverflow. (link below)
MySQL parent -> child query