Combine 2 foreach loops - foreach

Im stuck in a 2 foreach loop and i can't pass to combine the values.
My question is, how can i combine the 2 foreach loop in this case?
public function getImageColors($id, $code)
{
$values = $this->_storageModel->getOptions($id, $code);
$product = Mage::getModel('catalog/product')->load($id);
$id = $product->getId();
$productName = $product->getName();
$productURL = $product->getProductUrl();
$_gallery = Mage::getModel('catalog/product')->load($id)->getMediaGalleryImages();
if (count($values) > 1) {
foreach($values as $key => $val) {
foreach ($_gallery as $_image) {
$url_image = $_image->getUrl();
echo '<div data-main-image-src="'.$url_image.'" class="color'. $val . '" id="color' . $id . ' ></div>';
}
}
}
return '';
}
Another simple example:
$data1 = array('Blue','Red','Yellow','Black','White');
$data2 = array('blue.jpg','red.jpg','black.jpg','white.jpg');
foreach ($data1 as $val1) {
$val1 = $color;
}
foreach ($data2 as $val2) {
$val2 = $image;
}
the point is to get the values in a string but not concatenated.
need to be like : echo <div class="<?php echo $color; ?>"><img src="<?php echo $image; ?>"></div>
how can i combine to echo the foreach value for both arrays ?

Do you need to use foreach loop?? With for loop it can be easily done by this code
$temp=count($data1)>count($data2)?count($data2):count($data1);
for($i=0;$i<$temp;$i++)
{
echo $data1[$i].'->'.$data2[$i].'<br>';
}

Related

Stop process if condition is null and return message

I have a controller like this:
public ActionResult CargaCSV(HttpPostedFileBase archivo)
{
List<string[]> registros = new List<string[]>();
confService = new ConfiguracionService();
if (archivo.ContentLength > 0)
{
StreamReader sR = new StreamReader(archivo.InputStream);
string linea;
string resultado = "";
var f = 0;
while ((linea = sR.ReadLine()) != null)
{
if (f == 0)
{
f++;
continue;
}
else
{
String[] registros_ = linea.Split(',');
registros.Add(registros_);
}
}
sR.Close();
ViewBag.Message = resultado;
confService.GuardarMatrizCsv(registros,usuarioCaptura);
}
return Json(registros);
}
As you can see I return result into div:
ViewBag.Message = resultado;
View:
<div class="" style="height: 150px; overflow: auto; margin-bottom:10px;">
<pre id="resultado">#ViewBag.Message</pre>
</div>
That I want to do is to cancel all proccess if (archivo.ContentLength > 0) return null and return: ViewBag.Message = "you need attach file to load it"; and stop all process
How can I achieve this?
Update:
I call CargaCSV method with ajax call:
$("#btnCargarCsv").on("click", function () {
var data = new FormData();
data.append("archivo", $("#archivo")[0].files[0]);
$.ajax({
"type": "POST",
"url": "/Configuracion/CargaCSV",
"contentType": false,
"processData": false,
"data": data,
success: function (s) {
var result = $("#resultado");
result.text("");
result.append("<table>");
result.append("<tr>");
result.append("<th> Unidad </th>");
result.append("<th> CR Mínimo </th>");
result.append("<th> CR Máximo </th>");
result.append("<th> % Mínimo </th>");
result.append("<th> % Máximo </th>");
result.append("</tr>");
for (var i = 0; i < s.length; i++) {
var val = s[i];
result.append("<tr>");
result.append("<td> " + val[0] + " </td>");
result.append("<td> " + val[1] + " </td>");
result.append("<td> " + val[2] + " </td>");
result.append("<td> " + val[3] + " </td>");
result.append("<td> " + val[4] + " </td>");
result.append("</tr>");
}
result.append("</table>");
}
});
});
So here I append data into table and show data into pre html tag "resultado"
Your returning a JsonResult, not a ViewResult, so setting a ViewBag property is pointless (ViewBag is for passing data to a View) and your
<pre id="resultado">#ViewBag.Message</pre>
element will only ever display the initial value of ViewBag.Message when the page is first rendered.
You need to return the message in your JsonResult and test it in the ajax success method.
Change the controller code to return different values based on your condition
public ActionResult CargaCSV(HttpPostedFileBase archivo)
{
if (archivo.ContentLength = 0)
{
string message = "you need attach file to load it";
return Json( new { message = message });
}
.... // your code to process the file
return Json(new { registros = registros });
}
and change the code in the success callback to test the result
success: function (data) {
if (data.message) {
$('#resultado').text(data.message);
} else if (data.registros) {
var result = $("#resultado");
....
for (var i = 0; i < data.registros.length; i++) {
var val = data.registros[i];
....
}
result.append("</table>");
}
}
As a side note, you could simplify your script by generating the <table> and its headings (which should be in a <thead> element) in the view (and style it using display: none;and just add the <tr> elements inside its <tbody> element (and then show/hide the table in the success callback), for example
<table id="resultstable" style="display:none">
<thead>
....
</thead>
<tbody id="results"></tbody>
<table>
Script
var table = $('#resultstable');
var results = $('#results');
var message = $('#resultado');
$('btnCargarCsv').on('click', function () {
....
$.ajax({
....
success: function (data) {
if (data.message) {
message.text(data.message);
table.hide();
} else if (data.registros) {
results.empty(); //remove any existing rows
table.show();
for (var i = 0; i < data.registros.length; i++) {
var val = data.registros[i];
var row = $('<tr></tr>');
for(int j = 0; j < val.length; j++) {
row.append($('<td></td>').text(val[j]));
}
results.append(row);
}
}
}
});
});
In addition, you should be testing if the value of the file input is null before making the ajax call (and cancel the ajax call and display the message if it is) to prevent an unnecessary call to the server.

ZEND This result is a forward only result set, calling rewind() after moving forward is not supported

I have this error after this code to :
This result is a forward only result set, calling rewind() after moving forward is not supported.
Page.phtml :
foreach ($company as $key => $value)
{
foreach ($userfeature as $key => $data)
{
echo "<tr>";
if($value->site_id == $data->site_id)
{
echo "<td>".$value->party_code." ".$value->party_name. "</td>";
}
}
}
Controller.php
public function indexsiteuserAction()
{
$this->layout('layout/admin');
$compteAdmin[] = $this->admincompte();
$user_id = (int) $this->params()->fromRoute('id', 0);
if (!$user_id)
{
return $this->redirect()->toRoute('administrateur', array('action' => 'adduser'));
}
try
{
$user = $this->getUserTable()->getUser($user_id);
$userfeature = $this->getAdminUserFeatureTable()->afficheruserFeature($user_id);
}
catch (\Exception $ex)
{
return $this->redirect()->toRoute('administrateur', array('action' => 'indexuser'));
}
return new ViewModel(
array(
'user_id' => $user_id,
'user'=> $user,
'userfeature' => $userfeature,
'compteAdmin' => $compteAdmin,
'company' => $this->getCompanyTable()->fetchAll(),
));
}
Userfeaturetable.php
public function getUserFeature($user_id)
{
$user_id = (int) $user_id;
$rowset = $this->tableGateway->select(array('user_id' => $user_id));
$row = $rowset->current();
if (!$row)
{
throw new \Exception("Could not find row $user_id");
}
return $row;
}
companyTable.php
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet ;
}
Why do not I have the right to embed my two ' foreach ()' ?
Your need to buffer the result.
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
$resultSet->buffer();
return $resultSet ;
}

Default for text element in zf2 forms

How can I setup default for Text element in ZF2 Forms?
I tried the following:
In the view file. This does not get to data, and is not saved:
if($form->get('agencyName')->getValue() === '')
$form->get('agencyName')->setValue('Virtual Field Practicum');
This affects neither view, nor DB:
$this->add(array(
'name' => 'agencyName',
'options' => array(
'label' => 'Agency Name',
),
'attributes' => array(
'disabled' => 'disabled',
'value' => 'Virtual Field Practicum',
)
));
I also tried to modify entity in two ways, but it did not affect anything:
public function __construct()
{
//set default agency name
$this->agencyName = 'Virtual Field Practicum';
}
OR:
public function setAgencyName($agencyName)
{
if ($agencyName === '')
$this->agencyName = 'Virtual Field Practicum';
else
$this->agencyName = $agencyName;
return $this;
}
Edit 1
Adding my generic actions to the post:
1) This one is responsible to load the forms, and process non-ajax calls:
public function editTabAction()
{
$buildName = $this->params()->fromRoute('buildName', 'unknown');
if ($buildName == 'unknown') {
$buildName = $this->params()->fromPost('buildName', 'unknown');
if ($buildName == 'unknown') {
trigger_error('Could not retrieve build name for ' . $buildName . ' entity for this form!');
}
}
//extract parameter from dispatch command
$studEvalId = (int)$this->params()->fromRoute('studEvalId', 0);
if ($studEvalId == 0) {
//extract parameter from the form submission
$studEvalId = (int)$this->params()->fromPost('studEvalId', 0);
if ($studEvalId == 0) {
return $this->notFoundAction();
}
}
$data = $this->getEntity($buildName, $studEvalId);
// Get your ObjectManager from the ServiceManager
$objectManager = $this->getEntityManager();
// get from from FormElementManager plugin
//forms are defined in Module.php
$formName = $buildName . "Form";
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get($formName);
$form->setHydrator(new DoctrineHydrator($objectManager ));
$form->setObject($this->getEntityInstanceFromBuildName($buildName));
$form->bind($data);
//set class and Id for buttons like SaveChanges to reference it
$form->setAttribute('class', "studentFormsClass_$studEvalId");
$form->setAttribute('id', "studentFormsId_$studEvalId" . "_$buildName");
//set buildName to the form
$form->get('buildName')->setAttribute('value', $buildName);
$request = $this->getRequest();
if ($request->isPost()) {
$formValidatorName = "OnlineFieldEvaluation\Form\\" . $buildName . "FormValidator";
$formValidator = new $formValidatorName();
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->savetodb($form->getData(), $buildName);
// Redirect to list of forms
return false;
} else {
foreach ($form->getMessages() as $messageId => $message) {
echo '<pre>';
echo "Validation failure '$messageId':";
print_r($message);
echo '</pre>';
}
}
}
$view = new ViewModel(array(
'studEvalId' => $studEvalId,
'buildName' => $buildName,
'form' => $form,
));
$view->setTemplate('online-field-evaluation/tabs/edit' . $buildName . '.phtml');
return $view;
}
2) This one is responsible for ajax calls:
public function validatepostajaxAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$buildName = $this->params()->fromRoute('buildName', 'unknown');
if ($buildName == 'unknown') {
$buildName = $this->params()->fromPost('buildName', 'unknown');
if ($buildName == 'unknown') {
trigger_error('Could not retrieve build name for ' . $buildName . ' entity for this form!');
}
}
//extract parameter from dispatch command
$studEvalId = (int)$this->params()->fromRoute('studEvalId', 0);
if ($studEvalId == 0) {
//extract parameter from the form submission
$studEvalId = (int)$this->params()->fromPost('studEvalId', 0);
if ($studEvalId == 0) {
return $this->notFoundAction();
}
}
$data = $this->getEntity($buildName, $studEvalId);
$objectManager = $this->getEntityManager();
$formName = $buildName . "Form";
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get($formName);
$form->setHydrator(new DoctrineHydrator($objectManager ));
$entityName = 'OnlineFieldEvaluation\Entity\\' . $buildName;
$form->setObject(new $entityName());
$form->bind($data);
//set class and Id for buttons like SaveChanges to reference it
$form->setAttribute('class', "studentFormsClass_$studEvalId");
$form->setAttribute('id', "studentFormsId_$studEvalId" . "_$buildName");
//set buildName to the form
$form->get('buildName')->setAttribute('value', $buildName);
$messages = array();
if ($request->isPost()) {
$formValidatorName = "OnlineFieldEvaluation\Form\\" . $buildName . "FormValidator";
$formValidator = new $formValidatorName();
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
if (!$form->isValid()) {
$errors = $form->getMessages();
foreach ($errors as $key => $row) {
if (!empty($row) && $key != 'submit') {
foreach ($row as $keyer => $rower) {
//save error(s) per-element that
//needed by Javascript
$messages[$key][] = $rower;
}
}
}
}
if (!empty($messages)) {
$response->setContent(
\Zend\Json\Json::encode(
array('status' => 'error',
'messages' => (array) $messages,
'buildName' => $buildName,
'studEvalId' => $studEvalId
)));
} else {
//save to db <span class="wp-smiley wp-emoji wp-emoji-wink" title=";)">;)</span>
$this->savetodb($form->getData(), $buildName);
$response->setContent(
\Zend\Json\Json::encode(
array(
'status' => 'success',
'messages' => 'Successfuly saved.',
'buildName' => $buildName,
'studEvalId' => $studEvalId
)
));
}
}
return $response;
}
To setup a default value for an element, simply do the following:
Open controller's action, that renders desired view
Instantiate a form, get the element by its name and do call setValue() on that
That looks like as following:
public function addAction()
{
$form = new YourAgencyForm();
$form->get('agencyName')->setValue('Virtual Field Practicum');
....
It's really that simple

Zend framework $form->isValid($formData) Return invalid and I dont know why

I have a 2-steps-form (Fancy Name), but, when I submit this form, the validation return false all time, I debugged it and I receive all the parameters I want, but for some reason the isValid is false and get some error in the RadioButton element, this is the code:
This is the forms/Users.php
public function signup()
{
$contryModel = new Application_Model_Country();
$countries = $contryModel->getCountries();
foreach ($countries as $array)
{
if(isset($array['id_country'])){
$countryArr[$array['id_country']] = $array['country'];
}
}
array_unshift($countryArr, '-- Select Your Country --');
$name = new Zend_Form_Element_Text('Name');
$name->setLabel('Name')
->setRequired(true)
->addValidator('NotEmpty');
$lastname = new Zend_Form_Element_Text('LastName');
$lastname->setLabel('Last Name')
->setRequired(true)
->addValidator('NotEmpty');
$email = new Zend_Form_Element_Text('Email');
$email->setLabel('Email')
->setRequired(true)
->addValidator('NotEmpty');
$website = new Zend_Form_Element_Text('Website');
$website->setLabel('Website')
->setRequired(true)
->addValidator('NotEmpty');
$country = new Zend_Form_Element_Select('Country');
$country->setLabel('Country')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions($countryArr);
$city = new Zend_Form_Element_Select('City');
$city->setLabel('City')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions(array('-- Select Your City --'))
->setRegisterInArrayValidator(false)
->setAttrib('disabled',true);
$password = new Zend_Form_Element_Password('Password');
$password->setLabel('Password')
->setRequired(true)
->addValidator('NotEmpty');
$rpassword = new Zend_Form_Element_Password('RepeatPassword');
$rpassword->setLabel('Repeat Password')
->setRequired(true)
->addValidator('NotEmpty');
$why = new Zend_Form_Element_Textarea('Why');
$why->setRequired(true)
->addValidator('NotEmpty')
->setAttrib('cols', '50')
->setAttrib('rows', '4');
$job = new Zend_Form_Element_Text('Job');
$job->setLabel("Job")
->setRequired(true)
->addValidator('NotEmpty');
$boxes = new Application_Model_Colors();
$res = $boxes->getColors();
foreach($res as $colors){
$colorArr[$colors['id']]['color'] = $colors['color'];
$colorArr[$colors['id']]['overColor'] = $colors['overColor'];
}
$color = new Zend_Form_Element_Radio('color');
$color->setLabel('Color')
->addMultiOptions($colorArr)
->addValidator('NotEmpty');
$save = new Zend_Form_Element_Submit('Submit');
$save->setLabel('Save');
$this->addElements(array($name, $lastname, $email, $website, $password, $rpassword, $job, $country, $city, $color, $why, $save));
}
*This is a part of the view * where I format the Radios
<?php
foreach($this->form->color->options as $key=>$colors){
echo "<label><input type='radio' value='$key' name='color'><div class='registrationBoxes' style='background-color:#".$colors['color']."' data-color='".$colors['color']."' data-overColor='".$colors['overColor']."' value='".$colors['color']."'></div></label>";
}
?>
And here is the Controller
public function indexAction()
{
$form = new Application_Form_Users();
$form->signup();
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
if($form->isValid($formData))
{
$formData = $this->getRequest()->getPost();
$name = $formData['Name'];
$lastName = $formData['LastName'];
$email = $formData['Email'];
$website = $formData['Website'];
$password = $formData['Password'];
$rpassword = $formData['RepeatPassword'];
$job = $formData['Job'];
$country = $formData['Country'];
$city = $formData['City'];
$color = $formData['color'];
$why = $formData['Why'];
$date_create = date('Y-m-d H:i:s');
$position = new Application_Model_Country();
$latLong = $position->getLatLong($city);
if($password == $rpassword){
$data = array( 'name'=>$name,
'last_name'=>$lastName,
'email'=>$email,
'website'=>$website,
'password'=>md5($password),
'date_create'=>$date_create,
'job'=>$job,
'country'=>$country,
'city'=>$city,
'color'=>$color,
'why'=>$why,
'latitude'=>$latLong['latitude'],
'longitude'=>$latLong['longitude']
);
$add = new Application_Model_Users();
$res = $add->insertUser($data);
if($res){
$this->view->message = "Registration Successfuly.";
$this->_redirect("/contact");
}else{
$this->view->errorMessage = "We have a problem with your registration, please try again later.";
}
}else{
$this->view->errorMessage = "Password and confirm password don't match.";
$form->populate($formData);
}
} else {
$this->view->errorMessage = "There is an error on your registration, all fields are requried";
$form->populate($formData);
}
}
}
a die(var_dump()) return this:
array(12) {
["Name"]=>
string(9) "Some name"
["LastName"]=>
string(13) "Some lastName"
["Email"]=>
string(21) "Someemail#hotmail.com"
["Password"]=>
string(5) "Some "
["RepeatPassword"]=>
string(5) "Some "
["Website"]=>
string(12) "Some website"
["Job"]=>
string(8) "Some job"
["Country"]=>
string(1) "7"
["City"]=>
string(3) "434"
["color"]=>
string(1) "3"
["Why"]=>
string(10) "Emotional!"
["Submit"]=>
string(4) "Save"
}
As you can see, all the parameters are coming and with value, but for no reason the isValid is returning false, some idea guys?
Thanks.-
EDIT
This is a part of the Zend/form.php code required by Tonunu
public function __construct ($options = null)
{
if (is_array($options)) {
$this->setOptions($options);
} elseif ($options instanceof Zend_Config) {
$this->setConfig($options);
}
// Extensions...
$this->init();
$this->loadDefaultDecorators();
}
public function __clone ()
{
$elements = array();
foreach ($this->getElements() as $name => $element) {
$elements[] = clone $element;
}
$this->setElements($elements);
$subForms = array();
foreach ($this->getSubForms() as $name => $subForm) {
$subForms[$name] = clone $subForm;
}
$this->setSubForms($subForms);
$displayGroups = array();
foreach ($this->_displayGroups as $group) {
$clone = clone $group;
$elements = array();
foreach ($clone->getElements() as $name => $e) {
$elements[] = $this->getElement($name);
}
$clone->setElements($elements);
$displayGroups[] = $clone;
}
$this->setDisplayGroups($displayGroups);
}
public function setOptions (array $options)
{
if (isset($options['prefixPath'])) {
$this->addPrefixPaths($options['prefixPath']);
unset($options['prefixPath']);
}
if (isset($options['elementPrefixPath'])) {
$this->addElementPrefixPaths($options['elementPrefixPath']);
unset($options['elementPrefixPath']);
}
if (isset($options['displayGroupPrefixPath'])) {
$this->addDisplayGroupPrefixPaths(
$options['displayGroupPrefixPath']);
unset($options['displayGroupPrefixPath']);
}
if (isset($options['elementDecorators'])) {
$this->_elementDecorators = $options['elementDecorators'];
unset($options['elementDecorators']);
}
if (isset($options['elements'])) {
$this->setElements($options['elements']);
unset($options['elements']);
}
if (isset($options['defaultDisplayGroupClass'])) {
$this->setDefaultDisplayGroupClass(
$options['defaultDisplayGroupClass']);
unset($options['defaultDisplayGroupClass']);
}
if (isset($options['displayGroupDecorators'])) {
$displayGroupDecorators = $options['displayGroupDecorators'];
unset($options['displayGroupDecorators']);
}
if (isset($options['elementsBelongTo'])) {
$elementsBelongTo = $options['elementsBelongTo'];
unset($options['elementsBelongTo']);
}
if (isset($options['attribs'])) {
$this->addAttribs($options['attribs']);
unset($options['attribs']);
}
$forbidden = array('Options', 'Config', 'PluginLoader', 'SubForms',
'View', 'Translator', 'Attrib', 'Default');
foreach ($options as $key => $value) {
$normalized = ucfirst($key);
if (in_array($normalized, $forbidden)) {
continue;
}
$method = 'set' . $normalized;
if (method_exists($this, $method)) {
$this->$method($value);
} else {
$this->setAttrib($key, $value);
}
}
if (isset($displayGroupDecorators)) {
$this->setDisplayGroupDecorators($displayGroupDecorators);
}
if (isset($elementsBelongTo)) {
$this->setElementsBelongTo($elementsBelongTo);
}
return $this;
}
In order to check if your form is valid, you have to put your data into it, using this method !
$form->setData($formData)
and then you can ask for validation
$form->isValid()
So what you need is :
$formData = $this->getRequest()->getPost();
$form->setData($formData);
if($form->isValid()){
//Blablablabla
}

How to define that table has been left-joined

I need to set conditions to fields of left joined table.
So I need to know:
Is this table has been left joined?
If so, what alias of leftjoined table to use to add new condition.
Here current code example:
class PStudentFormFilter extends BasePStudentFormFilter
{
public function configure()
{
$this->setWidget('name', new sfWidgetFormInput());
$this->setWidget('phone', new sfWidgetFormInput());
$this->setValidator('name', new sfValidatorPass(array('required' => false)));
$this->setValidator('phone', new sfValidatorPass(array('required' => false)));
}
private function leftJoinPersonalInfoQuery(Doctrine_Query $query)
{
if (isset($this->__leftJoinPersonalInfoQuery)) return;
$this->__leftJoinPersonalInfoQuery = true;
$query->leftJoin($query->getRootAlias().'.PersonalInfo pi');
}
public function addNameColumnQuery(Doctrine_Query $query, $field, $value)
{
$value = trim($value['text']);
if (!$value)
{
return;
}
$value = str_replace(' ', '%', $value);
$this->leftJoinPersonalInfoQuery($query);
$query->andWhere("CONCAT(pi.surname, ' ', pi.first_name, ' ', pi.patronymic) LIKE ?", "%$value%");
}
public function addPhoneColumnQuery(Doctrine_Query $query, $field, $value)
{
$value = trim($value['text']);
if (!$value)
{
return;
}
$value = str_replace(' ', '%', $value);
$this->leftJoinPersonalInfoQuery($query);
$query->andWhere("pi.mobile_phone LIKE ?", "%$value%");
}
}
You could try to analyse the return value of $query->getDqlPart('from') to get this to work.

Resources