Got errors When try load xml zend framework 2 - zend-framework2

I have create a controller:
public function testAction() {
$hml = '<div>
<table>
<tr>
<td class="foo">
<div>
Lorem ipsum <span class="bar">
One
Two
Three
Four
</span>
</div>
</td>
</tr>
</table>
</div>';
​​​​​​​​ use Zend\Dom\Query;
$dom = new Query($html);
$results = $dom->execute('.foo .bar a');
return new ViewModel(array(
'results' => $results,
)
);
}
My View
<!-- Begin page content -->
<div id="container">
<div class="pane ui-layout-center">
<?php
print_r($results);
?>
</div>
But I when I run that controller I got the message:
Cannot query; no document registered
anybody know what is the problem?

It does not work, because you have a typo in variable names. You store HTML in the $hml variable, however pass a non existing $html variable to the constructor of the Query class.

Related

Html Agility Pack asp.net mvc Xpath

I have this html:
Picture with html code
I need to show in my View : Бавария Майнц -2.25
I try write this:
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(
"https://www.parimatch.com/sport/futbol/germanija-bundesliga");
foreach (HtmlNode table in htmlDoc.DocumentNode.SelectNodes("//div[#id='oddsNote']/table/tbody"))
{
foreach (HtmlNode row in table.SelectNodes("tr"))
{
HtmlNodeCollection cells = row.SelectNodes("td");
if (cells == null)
{
continue;
}
foreach (HtmlNode cell in cells)
{
ViewBag.Results += cell.InnerText;
}
}
}
but my table always null. Where I have a mistake?
and what are the other options to output in View except Viewbag?
My HTML:
<div id ="z_container">
<div id = "Z_contentw">
<div id = "OddList">
<form name ="f1" id = "f1">
<div class = "container_grey">
<div class = "wrapper">
<table id = "4529899" class ="dt_twp">
<tbody class ="row1 processed">
<tr class ="bk">
<td> "02/03" <br> "21:00"</td>
<td class ="l"> <a class ="om" id ="a738">Bavaria Mainc</a></td>
<td> <b 3.5></td>
</tr>
</tbody>
<tbody class ="row2 processed">
<tr class ="bk">
<td> "03/03" <br> "19:00"</td>
<td class ="l"> <a class ="om" id ="a739">Roma Milan</a></td>
<td> <b 2.5></td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</div>
I need to show: 02/03 21:00 Bavaria Mainc 03/03 19:00 Roma Milan
Your xpath has an id that is not in the html you provided other than that
If you want the text in one line as you showed then it can be
var text = string.Join(" ", doc.DocumentNode.SelectNodes("//tr[#class='bk']//text()[normalize-space()]").Select(t=>t.InnerText));
If you want to model the data then use the indices of the td, the first one has the time the second has the teams so create a simple model
class FootballMatch
{
public string Time;
public string Teams;
}
and get the data using the following
var matches = doc.DocumentNode.SelectNodes("//tr[#class='bk']").
Select(tr => new FootballMatch() {
Time = string.Join(" ", tr.SelectNodes("./td[1]//text()").Select(t => t.InnerText)),
Teams = tr.SelectSingleNode("./td[2]//text()[normalize-space()]").InnerText,
});

Grails Pagination

Hello im back with another tedious question!
Trying to get my table to paginate. There are 12 users in the table. Here is my controller function
def listDuplicates(params) {
def result = User.getAllWithDuplicateIDs()
def totalDupCount = result.size()
/*sout for troubleshooting */
System.out.println("Duplicate:" + result.ID + " " + result.username)
params.max = Math.min(params.max ? params.int('max') : 10, 100)
return [resultList: result, totalDupCount: totalDupCount, params:params ]
}
Here is my view
<div>
<fieldset class="warningFieldSet">
<h1 style="color: red" align="center">
<g:message code="Duplicate IDs" />
</h1>
<p style="color: red; margin-left: 20px;">Duplicate IDs Found!</p>
<table>
<thead>
<tr>
<g:sortableColumn property="Username" title="Username" />
<g:sortableColumn property="ID" title="ID" />
<g:sortableColumn property="Status" title="Status" />
</tr>
</thead>
<tbody>
<g:each in="${resultList}" status="i" var="resultDuplicate">
<tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
<td>
${resultDuplicate.username}
</td>
<td style="color: red; font-weight: bold">
${resultDuplicate.id}
</td>
<td>
${resultDuplicate.accountStatus }
</tr>
</g:each>
</tbody>
<tfoot>
<g:if test="${totalDupCount >10 }">
<div class="paginateButtons">
<g:paginate action= "listDuplicates" total="${totalDupCount}" />
</div>
</g:if>
</tfoot>
</table>
</fieldset>
</div>
Domain function for finding the duplicate IDs
static List<User> getAllWithDuplicateIDs() {
findAll("FROM User WHERE id IN (SELECT id FROM User group by id having count(*) > 1) AND id != '' ", [])
}
The buttons show up. And in the URL the offset and max is displayed. The table just puts all 12 displayed instead of 10 on one page and 2 on the other. 2 Page numbers show up so It knows that it is only suppose to display only 10 per page. It just isn't doing it in the table itself. Im assuming its some kind of issue with passing params and such.
Any Suggestions/Opinions/Help are/is greatly appreciated!
Grails pagination is based on two parameters: max and offset. max determines the page size, and offset determines where the current page starts. The controller receives these parameters and generally passes them to a database query. The list method added to domain objects by grails handles these parameters, and the finder methods take a queryParams. The usual pattern is to pass the params object directly to list or as the queryParams parameter to the finders. This returns a result set starting at the given offset, with one page length.
In your example, you're calling getAllWithDuplicateIDs without making use of these parameters. Update your query to take them, like this:
static List<User> getAllWithDuplicateIDs(params) {
findAll("FROM User WHERE id IN (SELECT id FROM User group by id having count(*) > 1) AND id != '' ", [], params)
}
Alternatively, page it in memory with something like
results = results.drop(params.offset).take(params.max)
Paging directly in the query is preferable, since it will perform better handle cases where the entire list doesn't fit in memory.
Provide max and offset function params this:
def result = User.getAllWithDuplicateIDs([max:params.max, offset:params.offset])
And use them in in query to database.
Or check the answer how to get results from list with max and offset in answer here
Look at this example .
Domain class ..
class Job {
static belongsTo = [company:Company]
String jobtitle
String jobdescription
String jobskills
String joblocation
String experience
String jobtype
String salary
}
Controller Code..
def uijobs () {
[res:Job.list(params),jobcount:Job.count()]
}
and view is here.
<div class="container" id="main">
<div class="row">
<g:each in="${res}">
<div class="col-sm-4">
<div class="panel panel-warning">
<div class="panel-heading">
<h4 class="panel-title"><g:link action="infopagejob" controller="Job" id="${it.id}">${it.jobtitle}</g:link></h4>
</div>
<div class="panel-body">
<table class="table">
<tr class="info" >
<td > Job Location</td>
<td >${it.joblocation}</td>
</tr>
<tr class="info">
<td>Description</td>
<td>${it.jobdescription}</td>
</tr>
</table>
</div>
</div>
</div>
</g:each>
</div>
<g:paginate next="Forward" prev="Back" maxsteps="10" controller="Job" action="uijobs" total="${jobcount}" params="${params}"/>
</div></div>

HOw to link table to #Html.ActionLink

I have program in mvc which fetch data from controller and then display in view.It makes dynamic table with data in it. Inside it there is a link "SEE DETAILS", but instead of a single link i want to make whole table as a link like :
#Html.ActionLink("SEE DETAILS", "AppDetail", new { #id = item.id, appnameformp = item.AppNameForMP }, new { #style = "color:#C55000;font-size: 11px;text-decoration:none;" })
but i don't know how to do it...Any help is really appreciated and thanks in advance.
<div class="grid_9.5 alpha">
#foreach (var item in Model)
{
<div class="grid_4 alpha box_shadow" id="featured-subbillboard" style="margin-bottom:10px;" >
<table>
<tr >
<td><img height="140" width="130" src=#item.imgfile />
</td>
<td> </td>
<td class="table">
<h1 class="heading1" style="margin-top:10px; line-height: .4em;">#item.AppNameForMP </h1>
<h2 class="heading2">#item.DevName </h2>
<br />
<p class="para">
#if (item.AppDesc.Length > 50)
{#item.AppDesc.Remove(#item.AppDesc.Length -50)}
else
{ #item.AppDesc}
</p>
#Html.ActionLink("SEE DETAILS", "AppDetail", new { #id = item.id, appnameformp = item.AppNameForMP }, new { #style = "color:#C55000;font-size: 11px;text-decoration:none;" })
</td>
</tr>
</table>
</div>
}
</div>
Just use a regular anchor tag, and use #Url.Action() to get the href:
<a href="#Url.Action("AppDetail")">
<!-- table here -->
</a>
Also, note that while block-level links are now supported in HTML5, browser support and even implementation is not consistent. Some will handle linking the whole table well, while others will do all kinds of weird stuff. Just something to be aware of.

create div dynamically on click of a hyperlink in asp.net mvc

1.I want to dynamically generate div containing textbox with unique id on click of button
<input id="<%:rid %>" type="button" value="reply"/>
2.I also want to use jquery ajax mathod to carry the textbox data to ashx file .
Can anyone help me
code
var lineItemCount = 0;
$(document).ready(function () {
$(".commentbox input[type='button']").click(function () {
var id = $(this).attr("id");
alert(id);
var cid = id.substring(5);
var containerid = "container" + cid;
alert(containerid);
//Increase the lineitemcount
lineItemCount++;
//Add a new lineitem to the container, pass the lineItemCount to makesure
getLineItem()
// can generate a unique lineItem with unique Textbox ids
$(containerid).append(getLineItem(lineItemCount));
});
});
//Create a new DIV with Textboxes
function getLineItem(number) {
var div = document.createElement('div');
//Give the div a unique id
div.setAttribute('id', 'lineitem_' + number);
//pass unique values to the getTextbox() function
var t1 = getTextbox('txt_' + number + '_1');
div.appendChild(t1);
return div;
}
//Create a textbox, make sure the id passed to this function is unique...
function getTextbox(id) {
var textbox = document.createElement('input');
textbox.setAttribute('id', id);
textbox.setAttribute('name', id);
return textbox;
}
iteration through model in aspx page
<%var i=1;%>
<%foreach (var commentitem in item.commentsModelList)
{
<table border="0" class="commentbox">
<tr>
<%var rid = "reply" + i;%>
<div id="<%:containerid %>">
<td> <input id="<%:rid %>" type="button" value="reply"/>
</div>
</td>
</tr>
</table>
<% i++;}%>
I changed your markup little bit to get the corresponding id of items on my click events
HTML
<table border="0" class="commentbox">
<tr>
<td>Some Item text
</td>
</tr>
<tr>
<td>
<div id="container-1" ></div>
<input type="button" class='btnReply' id="reply-1" value="Reply" />
</td>
</tr>
</table>
And the Script
$(function(){
$(".commentbox .btnReply").click(function(){
$(this).hide();
var id=$(this).attr("id").split("-")[1]
var strDiv="<input type='text' class='txtCmnt' id='txtReply-"+id+"' /> <input type='button' class='btnSave' value='Save' id='btnSave-"+id+"' /> ";
$("#container-"+id).html(strDiv);
});
$(".commentbox").on("click",".btnSave",function(){
var itemId=$(this).attr("id").split("-")[1]
var txt=$(this).parent().find(".txtCmnt").val();
$.post("/echo/json/", {reply: txt, id: itemId},function(data){
alert(data);
//do whatever with the response
})
});
});
Here is the jsfiddle example : http://jsfiddle.net/UGMkq/30/
You need to change the post target url to your relevant page which handles the ajax response.
EDIT : As per the comment about handing Multiple Divs
As long as you have the container div ids unique, it will work, I just changed the markup to include more than one item.
<table border="0" class="commentbox">
<tr>
<td>Some Item text<br/>
<div id="container-1" ></div>
<input type="button" class='btnReply' id="reply-1" value="Reply" />
</td>
</tr>
<tr>
<td>Some Another Content here <br/>
<div id="container-2" ></div>
<input type="button" class='btnReply' id="reply-2" value="Reply" />
</td>
</tr>
</table>
Here is the sample :http://jsfiddle.net/UGMkq/44/
For the above output to be rendered, you probably want to write your razor syntax like this
<table border="0" class="commentbox">
#foreach (var commentitem in item.commentsModelList)
{
<tr>
<td>Some Another Content here<br/>
<div id="container-#(commentitem.Id)" ></div>
<input type="button" class='btnReply' id="reply-#(commentitem.Id)" value="Reply" />
</td>
</tr>
}
</table>
Instead of creating a new table for each item, I created a new row in existing table.

Embedding a form in a partial with a foreach statement

Objective:
list a set of records with a checkbox next to each along with a "delete" input. If the user checks one checkbox or multiple checkboxes, the submit action will get the id of each checkbox and delete corresponding record(s).
I know this functionality is provided on the backend, but I'm trying provide the functionality to the frontend users that are logged in.
Update: I can now render the widget correctly, but am still having difficulty capturing the ID of the checkbox(s) that are selected. Help here would be appreciated.
Index page:
<h1>Jobs</h1>
<?php include_partial('list', array('saved_jobss' => $saved_jobss, 'form' => $form)) ?>
//I'm not sure if I can even pass two objects??
Index action:
public function executeIndex(sfWebRequest $request)
{
$userId = sfContext::getInstance()->getUser()->getId();
$this->saved_jobss = Doctrine_Core::getTable('saved_jobs')->getSavedJobs($userId);
$this->form = new Saved_JobsForm();
}
Partial page named: _list
<table class="sortable">
<thead>
<tr>
<th>Delete</th>
<th>Company:</th>
<th>Job name:</th>
<th>Job No.</th>
<th>Saved:</th>
</tr>
</thead>
<tbody>
<?php foreach ($saved_jobss as $saved_jobs): ?>
<tr>
<td>
<?php echo $form['id']->renderRow() ?>
<td>
<a href="
<?php
$jobId = $saved_jobs->getJobId();
echo 'job/'.$saved_jobs->getJob($jobId);
?>
">
<?php
$jobId = $saved_jobs->getJobId();
echo $saved_jobs->getJobCompany($jobId);
?>
</a>
</td>
<td>
<?php
$jobId = $saved_jobs->getJobId();
echo $saved_jobs->getJobName($jobId);
?>
</td>
<td>
<?php
echo $saved_jobs->getJobId();
?>
</td>
<td><?php echo date("M-j-y", strtotime($saved_jobs->getCreatedAt())) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<input type="submit" value="Delete" />
</form>
Action:
public function executeSubmit(sfWebRequest $request)
{
$this->forward404Unless($request->isMethod('post'));
$params = $request->getPostParameters();
$this->redirect('saved_jobs/deleteConfirmation?'.http_build_query($params));
}
Form class:
class Saved_JobsForm extends BaseSaved_JobsForm
{
public function configure()
{
$this->widgetSchema['id'] = new sfWidgetFormInputCheckbox();
$this->widgetSchema->setLabel('id', false);
}
}
I tinkered with the idea of using javascript, but was unsure if that was the way to go or not. Any help, or a point in the right direction would be most appreciated. Thanks in advance.
Solved: I just passed a link to each record with the action and record Id.

Resources